2 # various utilities which are exported globally
4 # Copyright (c) 1998 - Dirk Koopman G1TLH
16 use Time::HiRes qw(gettimeofday tv_interval);
18 use Socket qw(AF_INET6 AF_INET inet_pton);
22 use vars qw(@month %patmap $pi $d2r $r2d @ISA @EXPORT);
26 @EXPORT = qw(atime ztime cldate cldatetime slat slong yesno promptf
27 parray parraypairs phex phash shellregex readfilestr writefilestr
29 print_all_fields cltounix unpad is_callsign is_latlong
30 is_qra is_freq is_digits is_pctext is_pcflag insertitem deleteitem
31 is_prefix dd is_ipaddr $pi $d2r $r2d localdata localdata_mv
32 diffms _diffms _diffus difft parraydifft is_ztime basecall
33 normalise_call is_numeric
37 @month = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
52 $ptonok = !defined inet_pton(AF_INET, '016.17.184.1')
53 && !defined inet_pton(AF_INET6, '2067::1:')
54 # Some old versions of Socket are hopelessly broken
55 && length(inet_pton(AF_INET, '1.1.1.1')) == 4;
58 # a full time for logging and other purposes
62 my ($sec,$min,$hour,$mday,$mon,$year) = gmtime((defined $t) ? $t : time);
64 my $buf = sprintf "%02d%s%04d\@%02d:%02d:%02d", $mday, $month[$mon], $year, $hour, $min, $sec;
68 # get a zulu time in cluster format (2300Z)
72 $t = defined $t ? $t : time;
74 my ($sec,$min,$hour) = $dst ? localtime($t): gmtime($t);
75 my $buf = sprintf "%02d%02d%s", $hour, $min, ($dst) ? '' : 'Z';
79 # get a cluster format date (23-Jun-1998)
83 $t = defined $t ? $t : time;
85 my ($sec,$min,$hour,$mday,$mon,$year) = $dst ? localtime($t) : gmtime($t);
87 my $buf = sprintf "%2d-%s-%04d", $mday, $month[$mon], $year;
91 # return a cluster style date time
96 my $date = cldate($t, $dst);
97 my $time = ztime($t, $dst);
101 # return a unix date from a cluster date and time
106 my ($thisyear) = (gmtime)[5] + 1900;
108 return 0 unless $date =~ /^\s*(\d+)-(\w\w\w)-([12][90]\d\d)$/;
109 return 0 if $3 > 2036;
110 return 0 unless abs($thisyear-$3) <= 1;
112 return 0 unless $time =~ /^([012]\d)([012345]\d)Z$/;
113 $time = "$1:$2 +0000";
114 my $r = str2time("$date $time");
116 return $r == -1 ? undef : $r;
119 # turn a latitude in degrees into a string
123 my ($deg, $min, $let);
124 $let = $n >= 0 ? 'N' : 'S';
127 $min = int ((($n - $deg) * 60) + 0.5);
128 return "$deg $min $let";
131 # turn a longitude in degrees into a string
135 my ($deg, $min, $let);
136 $let = $n >= 0 ? 'E' : 'W';
139 $min = int ((($n - $deg) * 60) + 0.5);
140 return "$deg $min $let";
143 # turn a true into 'yes' and false into 'no'
147 return $n ? $main::yes : $main::no;
150 # provide a data dumpered version of the object passed
154 my $dd = new Data::Dumper([$value]);
157 $dd->Quotekeys($] < 5.005 ? 1 : 0);
158 $value = $dd->Dumpxs;
159 $value =~ s/([\r\n\t])/sprintf("%%%02X", ord($1))/eg;
160 $value =~ s/^\s*\[//;
161 $value =~ s/\]\s*$//;
166 # format a prompt with its current value and return it with its privilege
169 my ($line, $value, $promptl) = @_;
170 my ($priv, $prompt, $action) = split ',', $line;
172 # if there is an action treat it as a subroutine and replace $value
174 my $q = qq{\$value = $action(\$value)};
176 } elsif (ref $value) {
180 $prompt = sprintf "%${promptl}s: %s", $prompt, $value;
181 return ($priv, $prompt);
184 # turn a hex field into printed hex
188 return sprintf '%X', $val;
191 # take an arg as a hash of call=>time pairs and print it
196 for (sort keys %$ref) {
197 $out .= "$_=" . atime($ref->{$_}) . ", ";
204 # take an arg as an array list and print it
208 return ref $ref ? join(', ', sort @{$ref}) : $ref;
211 # take the arg as an array reference and print as a list of pairs
218 for ($i = 0; $i < @$ref; $i += 2) {
220 my $r2 = @$ref[$i+1];
223 chop $out; # remove last space
224 chop $out; # remove last comma
228 # take the arg as a hash reference and print it out as such
234 foreach my $k (sort keys %$ref) {
235 $out .= "${k}=>$ref->{$k}, ";
237 $out =~ s/, $// if $out;
244 my @a = split /,/, $ref->field_prompt(shift);
245 my @b = split /,/, $ref->field_prompt(shift);
246 return lc $a[1] cmp lc $b[1];
249 # print all the fields for a record according to privilege
251 # The prompt record is of the format '<priv>,<prompt>[,<action>'
252 # and is expanded by promptf above
256 my $self = shift; # is a dxchan
257 my $ref = shift; # is a thingy with field_prompt and fields methods defined
259 my @fields = $ref->fields;
261 my $width = $self->width - 1;
265 # find the maximum length of the prompt
266 foreach $field (@fields) {
267 if (defined $ref->{$field}) {
268 my (undef, $prompt, undef) = split ',', $ref->field_prompt($field);
269 $promptl = length $prompt if length $prompt > $promptl;
274 foreach $field (sort {_sort_fields($ref, $a, $b)} @fields) {
275 if (defined $ref->{$field}) {
276 my ($priv, $ans) = promptf($ref->field_prompt($field), $ref->{$field}, $promptl);
278 if (length $ans > $width) {
279 $Text::Wrap::columns = $width-2;
280 my ($p, $a) = split /: /, $ans, 2;
281 @tmp = split/\n/, Text::Wrap::wrap("$p: ", (' ' x $promptl) . ': ', $a);
285 push @out, @tmp if ($self->priv >= $priv);
291 # generate a regex from a shell type expression
292 # see 'perl cookbook' 6.9
296 $in =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
298 return '^' . $in . "\$";
301 # read in a file into a string and return it.
302 # the filename can be split into a dir and file and the
303 # file can be in upper or lower case.
304 # there can also be a suffix
307 my ($dir, $file, $suffix) = @_;
312 $fn = "$dir/$f.$suffix";
315 $fn = "$dir/$file.$suffix";
328 my $fh = new IO::File $fn;
338 # write out a file in the format required for reading
339 # in via readfilestr, it expects the same arguments
340 # and a reference to an object
350 confess('no object to write in writefilestr') unless $obj;
351 confess('object not a reference in writefilestr') unless ref $obj;
355 $fn = "$dir/$f.$suffix";
358 $fn = "$dir/$file.$suffix";
371 my $fh = new IO::File ">$fn";
373 my $dd = new Data::Dumper([ $obj ]);
377 # $fh->print(@_) if @_ > 0; # any header comments, lines etc
378 $fh->print($dd->Dumpxs);
385 copy(@_) or return $!;
388 # remove leading and trailing spaces from an input string
397 # check that a field only has callsign characters in it
401 (?:\d?[A-Z]{1,2}\d{0,2}/)? # out of area prefix /
402 (?:\d?[A-Z]{1,2}\d{1,5}) # main prefix one (required) - lengthened for special calls
403 [A-Z]{1,8} # callsign letters (required)
404 (?:-(?:\d{1,2}))? # - nn possibly (eg G8BPQ-8)
405 (?:/[0-9A-Z]{1,7})? # / another prefix, callsign or special label (including /MM, /P as well as /EURO or /LGT) possibly
406 (?:/(?:AM?|MM?|P))? # finally /A /AM /M /MM /P
409 # longest callign allowed is 1X11/1Y11XXXXX-11/XXXXXXX/MM
414 return $_[0] =~ m!^(?:[A-Z]{1,2}\d+ | \d[A-Z]{1,2}}\d+)!x # basic prefix
418 # check that a PC protocol field is valid text
421 return undef unless length $_[0];
422 return undef if $_[0] =~ /[\x00-\x08\x0a-\x1f\x80-\x9f]/;
426 # check that a PC prot flag is fairly valid (doesn't check the difference between 1/0 and */-)
429 return $_[0] =~ /^[01\*\-]+$/;
432 # check that a thing is a frequency
435 return $_[0] =~ /^\d+(?:\.\d+)?$/;
438 # check that a thing is just digits
441 return $_[0] =~ /^[\d]+$/;
444 # does it look like a qra locator?
447 return unless length $_[0] == 4 || length $_[0] == 6;
448 return $_[0] =~ /^[A-Ra-r][A-Ra-r]\d\d(?:[A-Xa-x][A-Xa-x])?$/;
451 # does it look like a valid lat/long
454 return $_[0] =~ /^\s*\d{1,2}\s+\d{1,2}\s*[NnSs]\s+1?\d{1,2}\s+\d{1,2}\s*[EeWw]\s*$/;
457 # is it an ip address?
462 if (inet_pton(AF_INET6, $_[0])) {
463 return ($_[0] =~ /([:0-9a-f]+)/);
466 if (inet_pton(AF_INET, $_[0])) {
467 return ($_[0] =~ /([\.\d]+)/);
472 return ($_[0] =~ /^(:?:?(?:[0-9a-f]{1,4}\:)?(?:\:[0-9a-f]{1,4}(?:\:\:)?){1,8})$/i);
474 return ($_[0] =~ /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/);
480 # is it a zulu time hhmmZ
483 return $_[0] =~ /^(?:(?:2[0-3])|(?:[01][0-9]))[0-5][0-9]Z$/;
486 # insert an item into a list if it isn't already there returns 1 if there 0 if not
492 return 1 if grep {$_ eq $item } @$list;
497 # delete an item from a list if it is there returns no deleted
504 @$list = grep {$_ ne $item } @$list;
508 # find the correct local_data directory
509 # basically, if there is a local_data directory with this filename and it is younger than the
510 # equivalent one in the (system) data directory then return that name rather than the system one
514 my $lfn = "$main::local_data/$ifn";
515 my $dfn = "$main::data/$ifn";
517 if (-e "$main::local_data") {
518 if ((-e $dfn) && (-e $lfn)) {
519 $lfn = $dfn if -M $dfn < -M $lfn;
521 $lfn = $dfn if -e $dfn;
530 # move a file or a directory from data -> local_data if isn't there already
534 if (-e "$main::data/$ifn" ) {
535 unless (-e "$main::local_data/$ifn") {
536 move("$main::data/$ifn", "$main::local_data/$ifn") or die "localdata_mv: cannot move $ifn from '$main::data' -> '$main::local_data' $!\n";
541 # measure the time taken for something to happen; use Time::HiRes qw(gettimeofday tv_interval);
545 my $tb = shift || [gettimeofday];
546 my $a = int($ta->[0] * 1000) + int($ta->[1] / 1000);
547 my $b = int($tb->[0] * 1000) + int($tb->[1] / 1000);
551 # and in microseconds
555 my $tb = shift || [gettimeofday];
556 my $a = int($ta->[0] * 1000000) + int($ta->[1]);
557 my $b = int($tb->[0] * 1000000) + int($tb->[1]);
568 my $msecs = _diffms($ta, $tb);
571 my $s = "subprocess stats cmd: '$line' $call ${msecs}mS";
572 $s .= " $no lines" if $no;
576 # expects either an array reference or two times (in the correct order [start, end])
580 my $adds = shift // 0;
583 if (ref $b eq 'ARRAY') {
584 $t = $b->[1] - $b->[0];
586 if ($adds && $adds =~ /^\d+$/ && $adds >= $b) {
590 $t = $main::systime - $b;
593 return '-(ve)' if $t < 0;
596 $y = int $t / (86400*365);
597 $out .= sprintf ("%s${y}y", $adds?' ':'') if $y;
598 $t -= $y * 86400 * 365;
600 $out .= sprintf ("%s${d}d", $adds?' ':'') if $d;
603 $out .= sprintf ("%s${h}h", $adds?' ':'') if $h;
606 $out .= sprintf ("%s${m}m", $adds?' ':'') if $m;
607 if (($d == 0 && $adds) || (int $adds && $adds == 2)) {
609 $out .= sprintf ("%s${s}s", $adds?' ':'') if $s;
610 $out ||= sprintf ("%s0s", $adds?' ':'');
612 $out = '0s' unless length $out;
616 # print an array ref of difft refs
622 my $s = $_->[2] ? "($_->[2])" : '';
623 $out .= sprintf "%s=%s$s, ", atime($_->[0]), difft($_->[0], $_->[1]);
631 my ($r) = $_[0] =~ m{^((?:[\w\d]+/)?[\w\d]+(?:/[\w\d]+)*)(?:-\d+)?(?:-\#)?$};
637 my ($c, $ssid) = $_[0] =~ m|^((?:[\w\d]+/)?[\d\w]+(?:/[\w\d]+)*)(?:-(\d+))?(?:-\#)?$|;
640 $ncall .= "-$ssid" if $ssid;
646 return $_[0] =~ /^[\.\d]+$/;