remove any leading ::ffff: on ipv4 addresses
[spider.git] / perl / Prefix.pm
1 #
2 # prefix handling
3 #
4 # Copyright (c) - Dirk Koopman G1TLH
5 #
6 #
7 #
8
9 package Prefix;
10
11 use IO::File;
12 use DXVars;
13 use DB_File;
14 use Data::Dumper;
15 use DXDebug;
16 use DXUtil;
17 use USDB;
18 use LRU;
19
20 use strict;
21
22 use vars qw($db %prefix_loc %pre $lru $lrusize $misses $hits $matchtotal);
23
24 $db = undef;                                    # the DB_File handle
25 %prefix_loc = ();                               # the meat of the info
26 %pre = ();                                              # the prefix list
27 $hits = $misses = $matchtotal = 1;              # cache stats
28 $lrusize = 1000;                                # size of prefix LRU cache
29
30 sub init
31 {
32         my $r = load();
33         return $r if $r;
34
35         # fix up the node's default country codes
36         unless (@main::my_cc) {
37                 push @main::my_cc, (61..67) if $main::mycall =~ /^GB/;
38                 push @main::my_cc, qw(EA EA6 EA8 EA9) if $main::mycall =~ /^E[ABCD]/;
39                 push @main::my_cc, qw(I IT IS) if $main::mycall =~ /^I/;
40                 push @main::my_cc, qw(SV SV5 SV9) if $main::mycall =~ /^SV/;
41
42                 # catchall
43                 push @main::my_cc, $main::mycall unless @main::my_cc;
44         }
45
46         my @c;
47         for (@main::my_cc) {
48                 if (/^\d+$/) {
49                         push @c, $_;
50                 } else {
51                         my @dxcc = extract($_);
52                         push @c, $dxcc[1]->dxcc if @dxcc > 1;
53                 }
54         }
55         return "\@main::my_cc does not contain a valid prefix or callsign (" . join(',', @main::my_cc) . ")" unless @c;
56         @main::my_cc = @c;
57         return undef;
58 }
59
60 sub load
61 {
62         # untie every thing
63         if ($db) {
64                 undef $db;
65                 untie %pre;
66                 %pre = ();
67                 %prefix_loc = ();
68                 $lru->close if $lru;
69                 undef $lru;
70         }
71
72         # tie the main prefix database
73         eval {$db = tie(%pre, "DB_File", undef, O_RDWR|O_CREAT, 0664, $DB_BTREE);};
74         my $out = "$@($!)" if !$db || $@ ;
75         my $fn = localdata("prefix_data.pl");
76         eval {do $fn if !$out; };
77         $out .= $@ if $@;
78         $lru = LRU->newbase('Prefix', $lrusize);
79
80         return $out;
81 }
82
83 sub loaded
84 {
85         return $db;
86 }
87
88 sub store
89 {
90         my ($k, $l);
91         my $fh = new IO::File;
92         my $fn = localdata("prefix_data.pl");
93   
94         confess "Prefix system not started" if !$db;
95   
96         # save versions!
97         rename "$fn.oooo", "$fn.ooooo" if -e "$fn.oooo";
98         rename "$fn.ooo", "$fn.oooo" if -e "$fn.ooo";
99         rename "$fn.oo", "$fn.ooo" if -e "$fn.oo";
100         rename "$fn.o", "$fn.oo" if -e "$fn.o";
101         rename "$fn", "$fn.o" if -e "$fn";
102   
103         $fh->open(">$fn") or die "Can't open $fn ($!)";
104
105         # prefix location data
106         $fh->print("%prefix_loc = (\n");
107         foreach $l (sort {$a <=> $b} keys %prefix_loc) {
108                 my $r = $prefix_loc{$l};
109                 $fh->printf("   $l => bless( { name => '%s', dxcc => %d, itu => %d, utcoff => %d, lat => %f, long => %f }, 'Prefix'),\n",
110                                         $r->{name}, $r->{dxcc}, $r->{itu}, $r->{cq}, $r->{utcoff}, $r->{lat}, $r->{long});
111         }
112         $fh->print(");\n\n");
113
114         # prefix data
115         $fh->print("%pre = (\n");
116         foreach $k (sort keys %pre) {
117                 $fh->print("   '$k' => [");
118                 my @list = @{$pre{$k}};
119                 my $l;
120                 my $str;
121                 foreach $l (@list) {
122                         $str .= " $l,";
123                 }
124                 chop $str;  
125                 $fh->print("$str ],\n");
126         }
127         $fh->print(");\n");
128         undef $fh;
129         untie %pre; 
130 }
131
132 # what you get is a list that looks like:-
133
134 # prefix => @list of blessed references to prefix_locs 
135 #
136 # This routine will only do what you ask for, if you wish to be intelligent
137 # then that is YOUR problem!
138 #
139
140 sub get
141 {
142         my $key = shift;
143         my $ref;
144         my $gotkey = $key;
145         return () if $db->seq($gotkey, $ref, R_CURSOR);
146         return () if $key ne substr $gotkey, 0, length $key;
147
148         return ($gotkey,  map { $prefix_loc{$_} } split ',', $ref);
149 }
150
151 #
152 # get the next key that matches, this assumes that you have done a 'get' first
153 #
154
155 sub next
156 {
157         my $key = shift;
158         my $ref;
159         my $gotkey;
160   
161         return () if $db->seq($gotkey, $ref, R_NEXT);
162         return () if $key ne substr $gotkey, 0, length $key;
163   
164         return ($gotkey,  map { $prefix_loc{$_} } split ',', $ref);
165 }
166
167 #
168 # put the key LRU incluing the city state info
169 #
170
171 sub lru_put
172 {
173         my ($call, $ref) = @_;
174         $call =~ s/^=//;
175         my @s = USDB::get($call);
176         
177         if (@s) {
178                 # this is deep magic, because this is a reference to static data, it
179         # must be copied.
180                 my $h = { %{$ref->[1]} };
181                 bless $h, ref $ref->[1];
182                 $h->{city} = $s[0];
183                 $h->{state} = $s[1];
184                 $ref->[1] = $h;
185         } else {
186                 $ref->[1]->{city} = $ref->[1]->{state} = "" unless exists $ref->[1]->{state};
187         }
188         
189         dbg("Prefix::lru_put $call -> ($ref->[1]->{city}, $ref->[1]->{state})") if isdbg('prefix');
190         $lru->put($call, $ref);
191 }
192
193
194 # search for the nearest match of a prefix string (starting
195 # from the RH end of the string passed)
196 #
197
198 sub matchprefix
199 {
200         my $pref = shift;
201         my @partials;
202
203         for (my $i = length $pref; $i; $i--) {
204                 $matchtotal++;
205                 my $s = substr($pref, 0, $i);
206                 push @partials, $s;
207                 my $p = $lru->get($s);
208                 if ($p) {
209                         $hits++;
210                         if (isdbg('prefix')) {
211                                 my $percent = sprintf "%.1f", $hits * 100 / $misses;
212                                 dbg("Partial Prefix Cache Hit: $s Hits: $hits/$misses of $matchtotal = $percent\%");
213                         }
214                         lru_put($_, $p) for @partials;
215                         return @$p;
216                 } else {
217                         $misses++;
218                         my @out = get($s);
219                         if (isdbg('prefix')) {
220                                 my $part = $out[0] || "*";
221                                 $part .= '*' unless $part eq '*' || $part eq $s;
222                                 dbg("Partial prefix: $pref $s $part" );
223                         } 
224                         if (@out && $out[0] eq $s) {
225                                 return @out;
226                         } 
227                 }
228         }
229         return ();
230 }
231
232 #
233 # extract a 'prefix' from a callsign, in other words the largest entity that will
234 # obtain a result from the prefix table.
235 #
236 # This is done by repeated probing, callsigns of the type VO1/G1TLH or
237 # G1TLH/VO1 (should) return VO1
238 #
239
240 sub extract
241 {
242         my $calls = uc shift;
243         my @out;
244         my $p;
245         my @parts;
246         my ($call, $sp, $i);
247
248 LM:     foreach $call (split /,/, $calls) {
249
250                 $matchtotal++;
251                 $call =~ s/-\d+$//;             # ignore SSIDs
252                 my @nout;
253                 my $ecall = "=$call";
254
255                 # first check if this is a call (by prefixing it with an = sign)
256                 my $p = $lru->get($ecall);
257                 if ($p) {
258                         $hits++;
259                         if (isdbg('prefix')) {
260                                 my $percent = sprintf "%.1f", $hits * 100 / $misses;
261                                 dbg("Prefix Exact Cache Hit: $call Hits: $hits/$misses of $matchtotal = $percent\%");
262                         }
263                         push @out, @$p;
264                         next;
265                 }
266
267                 # then check if the whole thing succeeds either because it is cached
268                 # or because it simply is a stored prefix as callsign (or even a prefix)
269                 $p = $lru->get($call);
270                 if ($p) {
271                         $hits++;
272                         if (isdbg('prefix')) {
273                                 my $percent = sprintf "%.1f", $hits * 100 / $misses;
274                                 dbg("Prefix Cache Hit: $call Hits: $hits/$misses of $matchtotal = $percent\%");
275                         }
276                         push @out, @$p;
277                         next;
278                 }
279
280                 # is it in the USDB, force a matchprefix to match?
281                 my @s = USDB::get($call);
282                 if (@s) {
283                         @nout = get($call);
284                         @nout = matchprefix($call) unless @nout;
285                         $nout[0] = $ecall if @nout;
286                 } else {
287
288                         # try a straight get for an exact callsign
289                         @nout = get($ecall);
290                 }
291
292                 # now store the exact prefix if it has been found
293                 if (@nout && $nout[0] eq $ecall) {
294                         $misses++;
295                         $nout[0] = $call;
296                         lru_put("=$call", \@nout);
297                         dbg("got exact prefix: $nout[0]") if isdbg('prefix');
298                         push @out, @nout;
299                         next;
300                 }
301
302                 # now try a non-exact call/prefix
303                 if ((@nout = get($call)) && $nout[0] eq $call) {
304                         $misses++;
305                         lru_put($call, \@nout);
306                         dbg("got exact prefix: $nout[0]") if isdbg('prefix');
307                         push @out, @nout;
308                         next;
309                 }
310
311                 # now split the call into parts if required
312                 @parts = ($call =~ '/') ? split('/', $call) : ($call);
313                 dbg("Parts: $call = " . join(' ', @parts))      if isdbg('prefix');
314
315                 # remove any /0-9 /P /A /M /MM /AM suffixes etc
316                 if (@parts > 1) {
317                         @parts = grep { !/^\d+$/ && !/^[PABM]$/ && !/^(?:|AM|MM|BCN|JOTA|SIX|WEB|NET|Q\w+)$/; } @parts;
318
319                         # can we resolve them by direct lookup
320                         my $s = join('/', @parts); 
321                         @nout = get($s);
322                         if (@nout && $nout[0] eq $s) {
323                                 dbg("got exact multipart prefix: $call $s") if isdbg('prefix');
324                                 $misses++;
325                                 lru_put($call, \@nout);
326                                 push @out, @nout;
327                                 next;
328                         }
329                 }
330                 dbg("Parts now: $call = " . join(' ', @parts))  if isdbg('prefix');
331   
332                 # at this point we should have two or three parts
333                 # if it is three parts then join the first and last parts together
334                 # to get an answer
335
336                 # first deal with prefix/x00xx/single letter things
337                 if (@parts == 3 && length $parts[0] <= length $parts[1]) {
338                         @nout = matchprefix($parts[0]);
339                         if (@nout) {
340                                 my $s = join('/', $nout[0], $parts[2]);
341                                 my @try = get($s);
342                                 if (@try && $try[0] eq $s) {
343                                         dbg("got 3 part prefix: $call $s") if isdbg('prefix');
344                                         $misses++;
345                                         lru_put($call, \@try);
346                                         push @out, @try;
347                                         next;
348                                 }
349                                 
350                                 # if the second part is a callsign and the last part is one letter
351                                 if (is_callsign($parts[1]) && length $parts[2] == 1) {
352                                         pop @parts;
353                                 }
354                         }
355                 }
356
357                 # if it is a two parter 
358                 if (@parts == 2) {
359
360                         # try it as it is as compound, taking the first part as the prefix
361                         @nout = matchprefix($parts[0]);
362                         if (@nout) {
363                                 my $s = join('/', $nout[0], $parts[1]);
364                                 my @try = get($s);
365                                 if (@try && $try[0] eq $s) {
366                                         dbg("got 2 part prefix: $call $s") if isdbg('prefix');
367                                         $misses++;
368                                         lru_put($call, \@try);
369                                         push @out, @try;
370                                         next;
371                                 }
372                         }
373                 }
374
375                 # remove the problematic /J suffix
376                 pop @parts if @parts > 1 && $parts[$#parts] eq 'J';
377
378                 # single parter
379                 if (@parts == 1) {
380                         @nout = matchprefix($parts[0]);
381                         if (@nout) {
382                                 dbg("got prefix: $call = $nout[0]") if isdbg('prefix');
383                                 $misses++;
384                                 lru_put($call, \@nout);
385                                 push @out, @nout;
386                                 next;
387                         }
388                 }
389
390                 # try ALL the parts
391         my @checked;
392                 my $n;
393 L1:             for ($n = 0; $n < @parts; $n++) {
394                         my $sp = '';
395                         my ($k, $i);
396                         for ($i = $k = 0; $i < @parts; $i++) {
397                                 next if $checked[$i];
398                                 my $p = $parts[$i];
399                                 if (!$sp || length $p < length $sp) {
400                                         dbg("try part: $p") if isdbg('prefix');
401                                         $k = $i;
402                                         $sp = $p;
403                                 }
404                         }
405                         $checked[$k] = 1;
406                         $sp =~ s/-\d+$//;     # remove any SSID
407                         
408                         # now start to resolve it from the right hand end
409                         @nout = matchprefix($sp);
410                         
411                         # try and search for it in the descriptions as
412                         # a whole callsign if it has multiple parts and the output
413                         # is more two long, this should catch things like
414                         # FR5DX/T without having to explicitly stick it into
415                         # the prefix table.
416                         
417                         if (@nout) {
418                                 if (@parts > 1) {
419                                         $parts[$k] = $nout[0];
420                                         my $try = join('/', @parts);
421                                         my @try = get($try);
422                                         if (isdbg('prefix')) {
423                                                 my $part = $try[0] || "*";
424                                                 $part .= '*' unless $part eq '*' || $part eq $try;
425                                                 dbg("Compound prefix: $try $part" );
426                                         }
427                                         if (@try && $try eq $try[0]) {
428                                                 $misses++;
429                                                 lru_put($call, \@try);
430                                                 push @out, @try;
431                                         } else {
432                                                 $misses++;
433                                                 lru_put($call, \@nout);
434                                                 push @out, @nout;
435                                         }
436                                 } else {
437                                         $misses++;
438                                         lru_put($call, \@nout);
439                                         push @out, @nout;
440                                 }
441                                 next LM;
442                         }
443                 }
444
445                 # we are a pirate!
446                 @nout = matchprefix('QQ');
447                 $misses++;
448                 lru_put($call, \@nout);
449                 push @out, @nout;
450         }
451         
452         if (isdbg('prefixdata')) {
453                 my $dd = new Data::Dumper([ \@out ], [qw(@out)]);
454                 dbg($dd->Dumpxs);
455         }
456         return @out;
457 }
458
459 #
460 # turn a list of prefixes / dxcc numbers into a list of dxcc/itu/zone numbers
461 #
462 # nc = dxcc
463 # ni = itu
464 # nz = zone
465 # ns = state
466 #
467
468 sub to_ciz
469 {
470         my $cmd = shift;
471         my @out;
472         
473         foreach my $v (@_) {
474                 if ($cmd ne 'ns' && $v =~ /^\d+$/) {    
475                         push @out, $v unless grep $_ eq $v, @out;
476                 } else {
477                         if ($cmd eq 'ns' && $v =~ /^[A-Z][A-Z]$/i) {
478                                 push @out, uc $v unless grep $_ eq uc $v, @out;
479                         } else {
480                                 my @pre = Prefix::extract($v);
481                                 if (@pre) {
482                                         shift @pre;
483                                         foreach my $p (@pre) {
484                                                 my $n = $p->dxcc if $cmd eq 'nc' ;
485                                                 $n = $p->itu if $cmd eq 'ni' ;
486                                                 $n = $p->cq if $cmd eq 'nz' ;
487                                                 $n = $p->state if $cmd eq 'ns';
488                                                 push @out, $n unless grep $_ eq $n, @out;
489                                         }
490                                 }
491                         }                       
492                 }
493         }
494         return @out;
495 }
496
497 # get the full country data (dxcc, itu, cq, state, city) as a list
498 # from a callsign. 
499 sub cty_data
500 {
501         my $call = shift;
502         
503         my @dxcc = extract($call);
504         if (@dxcc) {
505                 my $state = $dxcc[1]->state || '';
506                 my $city = $dxcc[1]->city || '';
507                 my $name = $dxcc[1]->name || '';
508                 
509                 return ($dxcc[1]->dxcc, $dxcc[1]->itu, $dxcc[1]->cq, $state, $city, $name);
510         }
511         return (666,0,0,'','','Pirate-Country-QQ');             
512 }
513
514 my %valid = (
515                          lat => '0,Latitude,slat',
516                          long => '0,Longitude,slong',
517                          dxcc => '0,DXCC',
518                          name => '0,Name',
519                          itu => '0,ITU',
520                          cq => '0,CQ',
521                          state => '0,State',
522                          city => '0,City',
523                          utcoff => '0,UTC offset',
524                          cont => '0,Continent',
525                         );
526
527 sub AUTOLOAD
528 {
529         no strict;
530         my $name = $AUTOLOAD;
531   
532         return if $name =~ /::DESTROY$/;
533         $name =~ s/^.*:://o;
534   
535         confess "Non-existant field '$AUTOLOAD'" if !$valid{$name};
536         # this clever line of code creates a subroutine which takes over from autoload
537         # from OO Perl - Conway
538         *$AUTOLOAD = sub {@_ > 1 ? $_[0]->{$name} = $_[1] : $_[0]->{$name}} ;
539        goto &$AUTOLOAD;
540 }
541
542 #
543 # return a prompt for a field
544 #
545
546 sub field_prompt
547
548         my ($self, $ele) = @_;
549         return $valid{$ele};
550 }
551 1;
552
553 __END__