File: Utils.pm

package info (click to toggle)
lagan 2.0-3
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 1,360 kB
  • sloc: ansic: 8,542; perl: 7,732; cpp: 3,260; makefile: 85
file content (551 lines) | stat: -rw-r--r-- 12,736 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
package Utils;
require 5.000;

use strict;
use Exporter;
use Cwd;
use IO::File;
use POSIX qw(setsid);
use Sys::Syslog qw(:DEFAULT setlogsock);

sub Trim( @ );
sub Lock_File( $ ; $ $ $ );
sub Unlock_File( $ );
sub Write_Log( $ $ ; $ $ );
sub Parse_Filename( $ );
sub Get_Abs_Path( $ );
sub Expand_Path( $ );
sub Get_Random_Key( ; $ );
sub Hex2Ascii( $ );
sub Ascii2Hex( $ );
sub Get_Config_Record( $ $ );
sub Round( $ );
sub Set_Log( $ $ );
sub Log( $ $ );
sub Min( $ $ );
sub Max( $ $ );
sub Reg_Diff( $ $ ; $ $ $ $ $ );
sub Reg_Rem_Overlap( $ ; $ $ $ );
sub Reg_Sort( $ ; $ $ $ );
sub Reg_Intersect( $ $ ; $ $ $ $ $ );
sub Reg_Merge( $ ; $ $ $ );

use vars qw(@ISA @EXPORT $VERSION $JOB $Error $Syslog $Facility $Msg_Prefix);

@ISA = qw(Exporter);
@EXPORT = qw(Trim Lock_File Unlock_File Write_Log Parse_Filename 
  Get_Abs_Path Expand_Path Hex2Ascii Ascii2Hex Get_Config_Record 
  Get_Random_Key Round Set_Log Log Min Max Reg_Diff Reg_Rem_Overlap
  Reg_Sort Reg_Intersect Reg_Merge redirect_err2log openlogs safe_glob
  daemon wr_log wr_err start_watcher confirm $JOB);

my $Id = '$Id: Utils.pm,v 1.21 2005/01/07 23:08:59 poliakov Exp $';
($VERSION) = ($Id =~ /,v\s+(\d+\S+)/o);
$JOB = '^(\S+)\@(\S+?)_(\d{4})(?:_(.+)|)$';

$Error = 0;
$Syslog = 0;
$Facility = "user";
$Msg_Prefix = undef;

my $E_FORK = "cannot fork";
my @LOG_FILE = ();
my %Locks = ();

sub Trim( @ ) {
  for (my $i = 0; $i <= $#_; ++$i) {
    $_[$i] =~ s/^\s+//;
    $_[$i] =~ s/\s+$//
  }
}

sub Lock_File( $ ; $ $ $ ) {
  my ($file, $retry, $timeout, $max_mtime) = @_;
  my ($lock_fh, $start_time, $mtime);

  if (!$file || ($file =~ /\/$/o)) {
    $Error = "Invalid filename";
    return 0;
  }
  $file = Get_Abs_Path("$file.lock");
  if (exists($Locks{$file})) { $Error = "Already locked"; return 1; }
  if (!-w (Parse_Filename($file))[0]) {
    $Error = "Permission denied";
    return 0;
  }
  if (!defined($retry)) { $retry = 1; }
  if (!defined($timeout)) { $timeout = 1200; }
  if (!defined($max_mtime)) {
    $max_mtime = ($timeout > 0) ? int($timeout / 2) : 0;
  }
  $start_time = time();
  LOCK: {
    if (!($lock_fh = IO::File->new($file, O_RDWR|O_CREAT|O_EXCL))) {
      if (!$retry || (($timeout > 0) && ((time() - $start_time) > $timeout))) {
        $Error = "Locked by someone else";
	return 0;
      }
      if ($max_mtime > 0) {
        $mtime = (stat($file))[9];
        if ($mtime && ((time() - $mtime) > $max_mtime)) { unlink($file); }
      }
      redo LOCK;
    }
  }
  $lock_fh->close();
  $Locks{$file} = 1;
  return 1;
}

sub Unlock_File( $ ) {
  my ($file) = @_;

  if (!$file) { $Error = "Invalid filename"; return 0; }
  $file = Get_Abs_Path("$file.lock");
  if (!exists($Locks{$file})) { $Error = "Not locked"; return 0; }
  if (!unlink($file)) { $Error = "Cannot unlock"; return 0; }
  delete($Locks{$file});
  return 1;
}

{
  my $Uname;
  foreach my $dir ('/bin', '/sbin', '/usr/bin', '/usr/sbin') {
    -x "$dir/uname" and $Uname = "$dir/uname", last;
  }
  my $Host = $Uname ? `$Uname -n` : 'localhost';
  chomp($Host);
  ($Host) = ($Host =~ /^([^\.]+)(\..*)?$/);

sub Write_Log( $ $ ; $ $ ) {
  no strict "refs";
  my ($log_file, $msg, $name, $pid) = @_;
  my $error = 0;
  my $date;
  local *LOG;

  if (!defined($log_file) || !defined($msg)) { return 0; }
  if (*{$log_file}{IO}) {
    *LOG = *{$log_file}{IO};
  } elsif ($log_file eq '/dev/null') {
    return 1;
  } else {
    if (!Lock_File($log_file)) { return 0; }
    if (!open(LOG, ">> $log_file")) { $error = 1; }
  }
  if (!$error) {
    chomp($msg);
    $date = localtime(time());
    if (!$name) { $name = $0; }
    if (!$pid) { $pid = $$; }
    if (!print LOG "$date $Host $name\[$pid\]:  $msg\n") { $error = 1; }
    if (!*{$log_file}{IO}) { close(LOG); }
  }
  if ($error && $!) { $Error = "$!"; }
  if (!*{$log_file}{IO}) { Unlock_File($log_file); }
  return !$error;
}}

sub Parse_Filename( $ ) {
  my ($name) = @_;
  my ($last_slash_pos, $dir, $file);
  
  if (!defined($name)) { return (); }
  $last_slash_pos = rindex($name, "/");
  if ($last_slash_pos >= 0) {
    $dir = substr($name, 0, $last_slash_pos + 1);
    $file = substr($name, $last_slash_pos + 1);
  } else {
    $dir = "";
    $file = $name;
  }
  return ($dir, $file);
}

sub Expand_Path( $ ) {
  my ($path) = @_;
  my $home_dir;
  
  $path && ($path =~ /^~/o) or return $path;
  $path =~ /^~([^\/]*)(.*)$/o;
  $home_dir = $1 ? (getpwnam($1))[7] :
    ($ENV{"HOME"} || $ENV{"LOGDIR"} || (getpwuid($>))[7]);
  defined($home_dir) and $path = "$home_dir$2";
  return $path;
}

sub Get_Abs_Path( $ ) {
  my ($path) = @_;

  defined($path) or return $path;
  $path = Expand_Path($path);
  $path =~ /^\//o or $path = getcwd() . "/$path";
  $path =~ s(/{2,})(/)g;
  
# get rid of "/./"

  while ($path =~ /^(.*?)\/\.(?:|\/(.*))$/o) {  
    $path = "$1/" . ($2 ? $2 : "");
  }
  
# get rid of "/../"

  while ($path =~ /^(((?:.*?\/)*?)[^\/]+){0,1}?\/\.\.(?:|\/(.*))$/o) {
    $path = ($1 ? $2 : "/") . ($3 ? $3 : "");
  }
  return $path;
}

{
  my @Chars = ("A" .. "Z", "a" .. "z", 0 .. 9);
  srand();

sub Get_Random_Key( ; $ ) {
  my ($len) = @_;
  
  if (!defined($len) || ($len !~ /^\d+$/o) || ($len < 2) || ($len > 1024)) {
    $len = 8;
  }
  return join("", @Chars[map {rand @Chars } (1 .. 8)]);
}}

sub Hex2Ascii( $ ) {
  my ($str) = @_;
  
  if ($str) { $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg; }
  return $str;
}

{
  my $a2h = {
    "\t" => "%29",
    "+" => "%2B",
    "," => "%2C",
    "." => "%2E",
    ";" => "%3B",
    "/" => "%2F",
    "?" => "%3F",
    ":" => "%3A",
    "@" => "%40",
    "=" => "%3D",
    "&" => "%26",
    " " => "%20",
    "<" => "%3C",
    ">" => "%3E",
    "\"" => "%22",
    "%" => "%25",
    "#" => "%23",
    "[" => "%5B",
    "]" => "%5D",
    "{" => "%7B",
    "}" => "%7D",
    "|" => "%7C",
    "\\" => "%5C",
    "^" => "%5E",
    "~" => "%7E",
    "`" => "%60"};	

sub Ascii2Hex( $ ) {
  my ($str) = @_;
  my $new_str = "";

  if (!$str) { return $str; }
  foreach my $char (split(//, $str)) {
    if (exists($a2h->{$char})) { $char = $a2h->{$char}; }
    $new_str .= $char;
  }
  return $new_str;
}}

sub Get_Config_Record( $ $ ) {
  my ($conf_file, $rec) = @_;
  my ($db, $field, $value);
  my @result = ();

  if (!($db = Registry->New($conf_file, "r", 1))) {
    $Error = "$Registry::Error", return ();
  }
  if (!$db->Record_Exists($rec)) {
    $Error = qq("$rec" record not found);
    return ();
  }
  foreach my $field (qw(dir users log)) {
    if (!($value = Expand_Path($db->Get_Val($rec, $field)))) {
      if ($field eq "log") {
        $value = "";
      } else {
        $Error = qq("$field" field of "$rec" record is missing), return ();
      }
    } elsif ($value !~ /^\//o) {
      $Error = qq("$field" field of "$rec" record should be absolute path);
      return ();
    }
    push(@result, $value);
  }
  foreach my $field (qw(max_down grace_period)) {
    if (!($value = $db->Get_Val($rec, $field)) ||
        ($value !~ /^\d+$/o)) {
      $value = 0;
    }
    push(@result, $value);
  }
  return @result;
}

sub Round( $ ) {
  my ($num) = @_;
  
  return int($num + 0.5);
}

sub Log( $ $ ) {
  my ($log_num, $msg) = @_;

  (defined($log_num) && ($log_num >= 0) && $LOG_FILE[$log_num]) and
    Write_Log($LOG_FILE[$log_num], $msg);
}

sub Set_Log( $ $ ) {
  my ($log_num, $file) = @_;
  
  (defined($log_num) && ($log_num >= 0) && $file) and
    $LOG_FILE[$log_num] = $file;
}

sub Min( $ $ ) {
  my ($i, $j) = @_;
  
  return ($i < $j) ? $i : $j;
}

sub Max( $ $ ) {
  my ($i, $j) = @_;
  
  return ($i > $j) ? $i : $j;
}

sub Reg_Diff( $ $ ; $ $ $ $ $ ) {
  my ($regs1, $regs2, $strict, $s1, $e1, $s2, $e2) = @_;
  my (@new_regs, $start, $end, $new_reg);
  
  $regs1 && $regs2 or return $regs1;
  $s1 ||= 0;
  defined($e1) or $e1 = 1;
  $s2 ||= 0;
  defined($e2) or $e2 = 1;
  for (my $i = 0; $i < @$regs1; ++$i) {
    $start = $$regs1[$i][$s1];
    $end = $$regs1[$i][$e1];
    for (my $j = 0; $j < @$regs2; ++$j) {
      $$regs2[$j][$s2] > $end and last;
      $$regs2[$j][$e2] < $start and next;
      if (($$regs2[$j][$s2] <= $start) && ($$regs2[$j][$e2] >= $end)) {
        undef($start), last;
      }
      if (($$regs2[$j][$s2] > $start) && ($$regs2[$j][$e2] >= $end)) {
        $end = $$regs2[$j][$s2] - 1, last;
      }
      if (($$regs2[$j][$s2] <= $start) && ($$regs2[$j][$e2] < $end)) {
        $start = $$regs2[$j][$e2] + 1, next;
      }
      ($start < ($$regs2[$j][$s2] - 1)) || !$strict and
        $new_reg = [@{$$regs1[$i]}],
        $$new_reg[$s1] = $start,
        $$new_reg[$e1] = $$regs2[$j][$s2] - 1,
        push(@new_regs, $new_reg);
      $start = $$regs2[$j][$e2] + 1;
    }
    !defined($start) || ($start > $end) and next;
    ($start < $end) || !$strict and
      $new_reg = [@{$$regs1[$i]}],
      $$new_reg[$s1] = $start,
      $$new_reg[$e1] = $end,
      push(@new_regs, $new_reg);
  }
  return \@new_regs;
}

sub Reg_Rem_Overlap( $ ; $ $ $ ) {
  my ($regs, $strict, $s, $e) = @_;
  my (@new_regs);
  
  $regs or return $regs;
  $s ||= 0;
  defined($e) or $e = 1;
  for (my $i = 0; $i < @$regs; ++$i) { push(@new_regs, [@{$$regs[$i]}]); }
  for (my $i = 0; $i < @new_regs; ++$i) {
    if (($i < $#new_regs) && ($new_regs[$i + 1][$s] <= $new_regs[$i][$e])) {
      $new_regs[$i + 1][$e] <= $new_regs[$i][$e] and
        splice(@new_regs, $i + 1, 1),
        --$i, next;
      $new_regs[$i + 1][$s] = $new_regs[$i][$e] + 1;
    }
    ($new_regs[$i][$s] < $new_regs[$i][$e]) || !$strict and next;
    splice(@new_regs, $i, 1);
    --$i;
  }
  return \@new_regs;
}

sub Reg_Sort( $ ; $ $ $ ) {
  my ($regs, $rev, $s, $e) = @_;
  my (@new_regs);
  
  $regs or return $regs;
  $s ||= 0;
  defined($e) or $e = 1;
  if ($rev) {
    @new_regs = sort { ($$b[$s] <=> $$a[$s]) || ($$b[$e] <=> $$a[$e]) } @$regs;
  } else {
    @new_regs = sort { ($$a[$s] <=> $$b[$s]) || ($$a[$e] <=> $$b[$e]) } @$regs;
  }
  return \@new_regs;
}

sub Reg_Intersect( $ $ ; $ $ $ $ $ ) {
  my ($regs1, $regs2, $strict, $s1, $e1, $s2, $e2) = @_;
  
  $regs1 && $regs2 or return undef;
  $s1 ||= 0;
  defined($e1) or $e1 = 1;
  $s2 ||= 0;
  defined($e2) or $e2 = 1;
  return Reg_Diff($regs1, Reg_Diff($regs1, $regs2, $strict, $s1, $e1,
    $s2, $e2), $strict, $s1, $e1, $s1, $e1);
}

sub Reg_Merge( $ ; $ $ $ ) {
  my ($regs, $strict, $s, $e) = @_;
  my (@new_regs);
  
  $regs or return $regs;
  $s ||= 0;
  defined($e) or $e = 1;
  for (my $i = 0; $i < @$regs; ++$i) { push(@new_regs, [@{$$regs[$i]}]); }
  for (my $i = 0; $i < @new_regs; ++$i) {
    ($i < $#new_regs) &&
        ($new_regs[$i + 1][$s] == ($new_regs[$i][$e] + 1)) and
      $new_regs[$i][$e] = $new_regs[$i + 1][$e],
      splice(@new_regs, $i + 1, 1),
      --$i, next;
  }
  for (my $i = 0; $i < @new_regs; ++$i) {
    ($new_regs[$i][$s] < $new_regs[$i][$e]) || !$strict and next;
    splice(@new_regs, $i, 1);
    --$i;
  }
  return \@new_regs;
}

sub safe_glob {
  my ($regexp, $dir) = @_;
  my (@files);
  local (*DIR);
  
  $dir ||= ".";
  $regexp ||= ".*";
  opendir(DIR, $dir) or return;
  @files = grep { /$regexp/ } readdir(DIR);
  closedir(DIR);
  return wantarray() ? @files : scalar(@files);
}

sub redirect_err2log {
  my ($facility) = @_;
  
  $Facility = $facility;
  stderr2log();
}

sub stderr2log {
  my ($oldfh);
  
  open(STDERR, "> /dev/null");
  open(STDERR, "| logger -p $Facility.err -t '$0\[$$\]'");
  $oldfh = select(STDERR); $| = 1; select($oldfh);  
}

sub openlogs {
  my ($facility) = @_;
  
  $facility and $Facility = $facility;
  stderr2log();
  setlogsock("unix");
  openlog($0, "pid", $Facility);
  $Syslog = 1;
}

sub daemon {
  my ($facility) = @_;
  my ($pid);

  if ($pid = fork()) {
    exit(0);
  } elsif (!defined($pid)) {
    wr_err("$E_FORK: $!");
    die;
  } else {
    setsid();
    close(STDIN);
    close(STDOUT);
    open(STDOUT, "> /dev/null");
    openlogs($facility);
  }
}

sub start_watcher {
  my ($watcher, $facility, @params) = @_;
  my ($pid, $parent);

  $parent = $$;
  if ($pid = fork()) {
    return;
  } elsif (!defined($pid)) {
    wr_err("$E_FORK: $!");
    die;
  } else {
    setsid();
    close(STDIN);
    close(STDOUT);
    open(STDOUT, "> /dev/null");
    $0 .= "_watcher";
    openlogs($facility);
    &$watcher($parent, @params);
  }
}

sub wr_log {
  my $msg = shift;
  
  chomp($msg);
  $msg = ( $Msg_Prefix ? &$Msg_Prefix : "") . $msg;
  if ($Syslog) {
    syslog("info", "%s", $msg);
  } else {
    print "$msg\n";
  }
}

sub wr_err {
  my $msg = shift;
  
  chomp($msg);
  print STDERR (( $Msg_Prefix ? &$Msg_Prefix : ""), "$msg\n");
  return 1;
}

sub confirm {
  my ($msg) = @_;
  my ($ans);
  
  print $msg;
  $ans = <STDIN>;
  chomp($ans);
  return ($ans =~ /^(y|yes)$/io) ? 1 : 0;
}

END {
  foreach my $lock (keys(%Locks)) { unlink($lock); }
}

1;