add DXCIDR, fix version no tracking
[spider.git] / perl / DXUser.pm
1 #
2 # DX cluster user routines
3 #
4 # Copyright (c) 1998 - Dirk Koopman G1TLH
5 #
6 #
7 #
8
9 package DXUser;
10
11 use DXLog;
12 use DB_File;
13 use Data::Dumper;
14 use Fcntl;
15 use IO::File;
16 use DXDebug;
17 use DXUtil;
18 use LRU;
19
20 use strict;
21
22 use vars qw(%u $dbm $filename %valid $lastoperinterval $lasttime $lru $lrusize $tooold $v3);
23
24 %u = ();
25 $dbm = undef;
26 $filename = undef;
27 $lastoperinterval = 60*24*60*60;
28 $lasttime = 0;
29 $lrusize = 2000;
30 $tooold = 86400 * 365;          # this marks an old user who hasn't given enough info to be useful
31 $v3 = 0;
32
33 # hash of valid elements and a simple prompt
34 %valid = (
35                   'sort' => '0,Type of User', # A - ak1a, U - User, S - spider cluster, B - BBS
36                   addr => '0,Full Address',
37                   alias => '0,Real Callsign',
38                   annok => '9,Accept Announces?,yesno', # accept his announces?
39                   bbs => '0,Home BBS',
40                   believe => '1,Believable nodes,parray',
41                   buddies => '0,Buddies,parray',
42                   build => '1,Build',
43                   call => '0,Callsign',
44                   dxok => '9,Accept DX Spots?,yesno', # accept his dx spots?
45                   email => '0,E-mail Address,parray',
46                   group => '0,Group,parray',    # used to create a group of users/nodes for some purpose or other
47                   hmsgno => '0,Highest Msgno',
48                   homenode => '0,Home Node',
49                   isolate => '9,Isolate network,yesno',
50                   K => '9,Seen on PC92 K,yesno',
51                   lang => '0,Language',
52                   lastin => '0,Last Time in,cldatetime',
53                   lastoper => '9,Last for/oper,cldatetime',
54                   lastping => '1,Last Ping at,ptimelist',
55                   lat => '0,Latitude,slat',
56                   lockout => '9,Locked out?,yesno',     # won't let them in at all
57                   long => '0,Longitude,slong',
58                   maxconnect => '1,Max Connections',
59                   name => '0,Name',
60                   node => '0,Last Node',
61                   nopings => '9,Ping Obs Count',
62                   nothere => '0,Not Here Text',
63                   pagelth => '0,Current Pagelth',
64                   passphrase => '9,Pass Phrase,yesno',
65                   passwd => '9,Password,yesno',
66                   pingint => '9,Node Ping interval',
67                   priv => '9,Privilege Level',
68                   prompt => '0,Required Prompt',
69                   qra => '0,Locator',
70                   qth => '0,Home QTH',
71                   registered => '9,Registered?,yesno',
72                   version => '1,Version',
73                   wantann => '0,Req Announce,yesno',
74                   wantann_talk => '0,Talklike Anns,yesno',
75                   wantbeep => '0,Req Beep,yesno',
76                   wantdx => '0,Req DX Spots,yesno',
77                   wantdxcq => '0,Show CQ Zone,yesno',
78                   wantdxitu => '0,Show ITU Zone,yesno',
79                   wantecho => '0,Req Echo,yesno',
80                   wantemail => '0,Req Msgs as Email,yesno',
81                   wantgtk => '0,Want GTK interface,yesno',
82                   wantlogininfo => '0,Login Info Req,yesno',
83                   wantpc16 => '9,Want Users from node,yesno',
84                   wantpc9x => '0,Want PC9X interface,yesno',
85                   wantroutepc19 => '9,Route PC19,yesno',
86                   wantsendpc16 => '9,Send PC16,yesno',
87                   wanttalk => '0,Req Talk,yesno',
88                   wantusstate => '0,Show US State,yesno',
89                   wantwcy => '0,Req WCY,yesno',
90                   wantwwv => '0,Req WWV,yesno',
91                   wantwx => '0,Req WX,yesno',
92                   width => '0,Preferred Width',
93                   xpert => '0,Expert Status,yesno',
94           wantgrid => '0,Show DX Grid,yesno',
95                  );
96
97 #no strict;
98 sub AUTOLOAD
99 {
100         no strict;
101         my $name = $AUTOLOAD;
102   
103         return if $name =~ /::DESTROY$/;
104         $name =~ s/^.*:://o;
105   
106         confess "Non-existant field '$AUTOLOAD'" if !$valid{$name};
107         # this clever line of code creates a subroutine which takes over from autoload
108         # from OO Perl - Conway
109         *$AUTOLOAD = sub {@_ > 1 ? $_[0]->{$name} = $_[1] : $_[0]->{$name}};
110        goto &$AUTOLOAD;
111 }
112
113 #use strict;
114
115 #
116 # initialise the system
117 #
118 sub init
119 {
120         my ($pkg, $fn, $mode) = @_;
121   
122         confess "need a filename in User" if !$fn;
123
124         my $ufn;
125         my $convert;
126         
127         eval {
128                 require Storable;
129         };
130
131 #       eval "use Storable qw(nfreeze thaw)";
132         
133         if ($@) {
134                 $ufn = "$fn.v2";
135                 $v3 = $convert = 0;
136                 dbg("the module Storable appears to be missing!!");
137                 dbg("trying to continue in compatibility mode (this may fail)");
138                 dbg("please install Storable from CPAN as soon as possible");
139         } else {
140                 import Storable qw(nfreeze thaw);
141
142                 $ufn = "$fn.v3";
143                 $v3 = 1;
144                 $convert++ if -e "$fn.v2" && !-e $ufn;
145         }
146         
147         if ($mode) {
148                 $dbm = tie (%u, 'DB_File', $ufn, O_CREAT|O_RDWR, 0666, $DB_BTREE) or confess "can't open user file: $fn ($!) [rebuild it from user_asc?]";
149         } else {
150                 $dbm = tie (%u, 'DB_File', $ufn, O_RDONLY, 0666, $DB_BTREE) or confess "can't open user file: $fn ($!) [rebuild it from user_asc?]";
151         }
152
153         die "Cannot open $ufn ($!)\n" unless $dbm;
154
155         $lru = LRU->newbase("DXUser", $lrusize);
156         
157         # do a conversion if required
158         if ($dbm && $convert) {
159                 my ($key, $val, $action, $count, $err) = ('','',0,0,0);
160                 
161                 my %oldu;
162                 dbg("Converting the User File to V3 ");
163                 dbg("This will take a while, I suggest you go and have cup of strong tea");
164                 my $odbm = tie (%oldu, 'DB_File', "$fn.v2", O_RDONLY, 0666, $DB_BTREE) or confess "can't open user file: $fn.v2 ($!) [rebuild it from user_asc?]";
165         for ($action = R_FIRST; !$odbm->seq($key, $val, $action); $action = R_NEXT) {
166                         my $ref = asc_decode($val);
167                         if ($ref) {
168                                 $ref->put;
169                                 $count++;
170                         } else {
171                                 $err++
172                         }
173                 } 
174                 undef $odbm;
175                 untie %oldu;
176                 dbg("Conversion completed $count records $err errors");
177         }
178         $filename = $ufn;
179 }
180
181 sub del_file
182 {
183         my ($pkg, $fn) = @_;
184   
185         confess "need a filename in User" if !$fn;
186         $fn .= $v3 ? ".v3" : ".v2";
187         unlink $fn;
188 }
189
190 #
191 # periodic processing
192 #
193 sub process
194 {
195         if ($main::systime > $lasttime + 15) {
196                 $dbm->sync;
197                 $lasttime = $main::systime;
198         }
199 }
200
201 #
202 # close the system
203 #
204
205 sub finish
206 {
207         undef $dbm;
208         untie %u;
209 }
210
211 #
212 # new - create a new user
213 #
214
215 sub alloc
216 {
217         my $pkg = shift;
218         my $call = uc shift;
219         my $self = bless {call => $call, 'sort'=>'U'}, $pkg;
220         return $self;
221 }
222
223 sub new
224 {
225         my $pkg = shift;
226         my $call = shift;
227         #  $call =~ s/-\d+$//o;
228   
229 #       confess "can't create existing call $call in User\n!" if $u{$call};
230
231         my $self = $pkg->alloc($call);
232         $self->put;
233         return $self;
234 }
235
236 #
237 # get - get an existing user - this seems to return a different reference everytime it is
238 #       called - see below
239 #
240
241 sub get
242 {
243         my $call = uc shift;
244         my $data;
245         
246         # is it in the LRU cache?
247         my $ref = $lru->get($call);
248         return $ref if $ref && ref $ref eq 'DXUser';
249         
250         # search for it
251         unless ($dbm->get($call, $data)) {
252                 $ref = eval{decode($data)};
253                 if ($ref) {
254                         if (!UNIVERSAL::isa($ref, 'DXUser')) {
255                                 dbg("DXUser::get: got strange answer from decode of $call". ref $ref. " ignoring");
256                                 return undef;
257                         }
258                         # we have a reference and it *is* a DXUser
259                 } else {
260                         dbg("DXUser::get: no reference returned from decode of $call $! $@");
261                         return undef;
262                 }
263                 $lru->put($call, $ref);
264                 return $ref;
265         }
266         return undef;
267 }
268
269 #
270 # get an existing either from the channel (if there is one) or from the database
271 #
272 # It is important to note that if you have done a get (for the channel say) and you
273 # want access or modify that you must use this call (and you must NOT use get's all
274 # over the place willy nilly!)
275 #
276
277 sub get_current
278 {
279         my $call = uc shift;
280   
281         my $dxchan = DXChannel::get($call);
282         if ($dxchan) {
283                 my $ref = $dxchan->user;
284                 return $ref if $ref && UNIVERSAL::isa($ref, 'DXUser');
285
286                 dbg("DXUser::get_current: got invalid user ref for $call from dxchan $dxchan->{call} ". ref $ref. " ignoring");
287         }
288         return get($call);
289 }
290
291 #
292 # get all callsigns in the database 
293 #
294
295 sub get_all_calls
296 {
297         return (sort keys %u);
298 }
299
300 #
301 # put - put a user
302 #
303
304 sub put
305 {
306         my $self = shift;
307         confess "Trying to put nothing!" unless $self && ref $self;
308         my $call = $self->{call};
309
310         $dbm->del($call);
311         delete $self->{annok} if $self->{annok};
312         delete $self->{dxok} if $self->{dxok};
313
314         $lru->put($call, $self);
315         my $ref = $self->encode;
316         $dbm->put($call, $ref);
317 }
318
319 # freeze the user
320 sub encode
321 {
322         goto &asc_encode unless $v3;
323         my $self = shift;
324         return nfreeze($self);
325 }
326
327 # thaw the user
328 sub decode
329 {
330         goto &asc_decode unless $v3;
331         return thaw(shift);
332 }
333
334
335 # create a string from a user reference (in_ascii)
336 #
337 sub asc_encode
338 {
339         my $self = shift;
340         my $strip = shift;
341         my $p;
342
343         if ($strip) {
344                 my $ref = bless {}, ref $self;
345                 foreach my $k (qw(qth lat long qra sort call homenode node lastoper lastin)) {
346                         $ref->{$k} = $self->{$k} if exists $self->{$k};
347                 }
348                 $ref->{name} = $self->{name} if exists $self->{name} && $self->{name} !~ /selfspot/i;
349                 $p = dd($ref);
350         } else {
351                 $p = dd($self);
352         }
353         return $p;
354 }
355
356 #
357 # create a hash from a string (in ascii)
358 #
359 sub asc_decode
360 {
361         my $s = shift;
362         my $ref;
363         $s =~ s/\%([0-9A-F][0-9A-F])/chr(hex($1))/eg;
364         eval '$ref = ' . $s;
365         if ($@) {
366                 LogDbg('err', $@);
367                 $ref = undef;
368         }
369         return $ref;
370 }
371
372 #
373 # del - delete a user
374 #
375
376 sub del
377 {
378         my $self = shift;
379         my $call = $self->{call};
380         $lru->remove($call);
381         $dbm->del($call);
382 }
383
384 #
385 # close - close down a user
386 #
387
388 sub close
389 {
390         my $self = shift;
391         $self->{lastin} = time;
392         $self->put();
393 }
394
395 #
396 # sync the database
397 #
398
399 sub sync
400 {
401         $dbm->sync;
402 }
403
404 #
405 # return a list of valid elements 
406
407
408 sub fields
409 {
410         return keys(%valid);
411 }
412
413
414 #
415 # export the database to an ascii file
416 #
417
418 sub export
419 {
420         my $fn = shift;
421         my $basic_info_only = shift;
422         
423         # save old ones
424         rename "$fn.oooo", "$fn.ooooo" if -e "$fn.oooo";
425         rename "$fn.ooo", "$fn.oooo" if -e "$fn.ooo";
426         rename "$fn.oo", "$fn.ooo" if -e "$fn.oo";
427         rename "$fn.o", "$fn.oo" if -e "$fn.o";
428         rename "$fn", "$fn.o" if -e "$fn";
429
430         my $count = 0;
431         my $err = 0;
432         my $del = 0;
433         my $fh = new IO::File ">$fn" or return "cannot open $fn ($!)";
434         if ($fh) {
435                 my $key = 0;
436                 my $val = undef;
437                 my $action;
438                 my $t = scalar localtime;
439                 print $fh q{#!/usr/bin/perl
440 #
441 # The exported userfile for a DXSpider System
442 #
443 # Input file: $filename
444 #       Time: $t
445 #
446                         
447 package main;
448                         
449 # search local then perl directories
450 BEGIN {
451         umask 002;
452                                 
453         # root of directory tree for this system
454         $root = "/spider"; 
455         $root = $ENV{'DXSPIDER_ROOT'} if $ENV{'DXSPIDER_ROOT'};
456         
457         unshift @INC, "$root/perl";     # this IS the right way round!
458         unshift @INC, "$root/local";
459         
460         # try to detect a lockfile (this isn't atomic but 
461         # should do for now
462         $lockfn = "$root/local/cluster.lck";       # lock file name
463         if (-e $lockfn) {
464                 open(CLLOCK, "$lockfn") or die "Can't open Lockfile ($lockfn) $!";
465                 my $pid = <CLLOCK>;
466                 chomp $pid;
467                 die "Lockfile ($lockfn) and process $pid exists - cluster must be stopped first\n" if kill 0, $pid;
468                 close CLLOCK;
469         }
470 }
471
472 package DXUser;
473
474 use DXVars;
475 use DXUser;
476
477 if (@ARGV) {
478         $main::userfn = shift @ARGV;
479         print "user filename now $userfn\n";
480 }
481
482 DXUser->del_file($main::userfn);
483 DXUser->init($main::userfn, 1);
484 %u = ();
485 my $count = 0;
486 my $err = 0;
487 while (<DATA>) {
488         chomp;
489         my @f = split /\t/;
490         my $ref = asc_decode($f[1]);
491         if ($ref) {
492                 $ref->put();
493                 $count++;
494         } else {
495                 print "# Error: $f[0]\t$f[1]\n";
496                 $err++
497         }
498 }
499 DXUser->sync; DXUser->finish;
500 print "There are $count user records and $err errors\n";
501 };
502                 print $fh "__DATA__\n";
503
504         for ($action = R_FIRST; !$dbm->seq($key, $val, $action); $action = R_NEXT) {
505                         if (!is_callsign($key) || $key =~ /^0/) {
506                                 my $eval = $val;
507                                 my $ekey = $key;
508                                 $eval =~ s/([\%\x00-\x1f\x7f-\xff])/sprintf("%%%02X", ord($1))/eg; 
509                                 $ekey =~ s/([\%\x00-\x1f\x7f-\xff])/sprintf("%%%02X", ord($1))/eg; 
510                                 LogDbg('DXCommand', "Export Error1: $ekey\t$eval");
511                                 eval {$dbm->del($key)};
512                                 dbg(carp("Export Error1: $ekey\t$eval\n$@")) if $@;
513                                 ++$err;
514                                 next;
515                         }
516                         my $ref = decode($val);
517                         if ($ref) {
518                                 my $t = $ref->{lastin} || 0;
519                                 if ($ref->{sort} eq 'U' && !$ref->{priv} && $main::systime > $t + $tooold) {
520                                         unless ($ref->{lat} && $ref->{long} || $ref->{qth} || $ref->{qra}) {
521                                                 eval {$dbm->del($key)};
522                                                 dbg(carp("Export Error2: $key\t$val\n$@")) if $@;
523                                                 LogDbg('DXCommand', "$ref->{call} deleted, too old");
524                                                 $del++;
525                                                 next;
526                                         }
527                                 }
528                                 # only store users that are reasonably active or have useful information
529                                 print $fh "$key\t" . $ref->asc_encode($basic_info_only) . "\n";
530                                 ++$count;
531                         } else {
532                                 LogDbg('DXCommand', "Export Error3: $key\t$val");
533                                 eval {$dbm->del($key)};
534                                 dbg(carp("Export Error3: $key\t$val\n$@")) if $@;
535                                 ++$err;
536                         }
537                 } 
538         $fh->close;
539     } 
540         return "$count Users $del Deleted $err Errors ('sh/log Export' for details)";
541 }
542
543 #
544 # group handling
545 #
546
547 # add one or more groups
548 sub add_group
549 {
550         my $self = shift;
551         my $ref = $self->{group} || [ 'local' ];
552         $self->{group} = $ref if !$self->{group};
553         push @$ref, @_ if @_;
554 }
555
556 # remove one or more groups
557 sub del_group
558 {
559         my $self = shift;
560         my $ref = $self->{group} || [ 'local' ];
561         my @in = @_;
562         
563         $self->{group} = $ref if !$self->{group};
564         
565         @$ref = map { my $a = $_; return (grep { $_ eq $a } @in) ? () : $a } @$ref;
566 }
567
568 # does this thing contain all the groups listed?
569 sub union
570 {
571         my $self = shift;
572         my $ref = $self->{group};
573         my $n;
574         
575         return 0 if !$ref || @_ == 0;
576         return 1 if @$ref == 0 && @_ == 0;
577         for ($n = 0; $n < @_; ) {
578                 for (@$ref) {
579                         my $a = $_;
580                         $n++ if grep $_ eq $a, @_; 
581                 }
582         }
583         return $n >= @_;
584 }
585
586 # simplified group test just for one group
587 sub in_group
588 {
589         my $self = shift;
590         my $s = shift;
591         my $ref = $self->{group};
592         
593         return 0 if !$ref;
594         return grep $_ eq $s, $ref;
595 }
596
597 # set up a default group (only happens for them's that connect direct)
598 sub new_group
599 {
600         my $self = shift;
601         $self->{group} = [ 'local' ];
602 }
603
604 # set up empty buddies (only happens for them's that connect direct)
605 sub new_buddies
606 {
607         my $self = shift;
608         $self->{buddies} = [  ];
609 }
610
611 #
612 # return a prompt for a field
613 #
614
615 sub field_prompt
616
617         my ($self, $ele) = @_;
618         return $valid{$ele};
619 }
620
621 # some variable accessors
622 sub sort
623 {
624         my $self = shift;
625         @_ ? $self->{'sort'} = shift : $self->{'sort'} ;
626 }
627
628 # some accessors
629
630 # want is default = 1
631 sub _want
632 {
633         my $n = shift;
634         my $self = shift;
635         my $val = shift;
636         my $s = "want$n";
637         $self->{$s} = $val if defined $val;
638         return exists $self->{$s} ? $self->{$s} : 1;
639 }
640
641 # wantnot is default = 0
642 sub _wantnot
643 {
644         my $n = shift;
645         my $self = shift;
646         my $val = shift;
647         my $s = "want$n";
648         $self->{$s} = $val if defined $val;
649         return exists $self->{$s} ? $self->{$s} : 0;
650 }
651
652 sub wantbeep
653 {
654         return _want('beep', @_);
655 }
656
657 sub wantann
658 {
659         return _want('ann', @_);
660 }
661
662 sub wantwwv
663 {
664         return _want('wwv', @_);
665 }
666
667 sub wantwcy
668 {
669         return _want('wcy', @_);
670 }
671
672 sub wantecho
673 {
674         return _want('echo', @_);
675 }
676
677 sub wantwx
678 {
679         return _want('wx', @_);
680 }
681
682 sub wantdx
683 {
684         return _want('dx', @_);
685 }
686
687 sub wanttalk
688 {
689         return _want('talk', @_);
690 }
691
692 sub wantgrid
693 {
694         return _want('grid', @_);
695 }
696
697 sub wantemail
698 {
699         return _want('email', @_);
700 }
701
702 sub wantann_talk
703 {
704         return _want('ann_talk', @_);
705 }
706
707 sub wantpc16
708 {
709         return _want('pc16', @_);
710 }
711
712 sub wantsendpc16
713 {
714         return _want('sendpc16', @_);
715 }
716
717 sub wantroutepc16
718 {
719         return _want('routepc16', @_);
720 }
721
722 sub wantusstate
723 {
724         return _want('usstate', @_);
725 }
726
727 sub wantdxcq
728 {
729         return _want('dxcq', @_);
730 }
731
732 sub wantdxitu
733 {
734         return _want('dxitu', @_);
735 }
736
737 sub wantgtk
738 {
739         return _want('gtk', @_);
740 }
741
742 sub wantpc9x
743 {
744         return _want('pc9x', @_);
745 }
746
747 sub wantlogininfo
748 {
749         my $self = shift;
750         my $val = shift;
751         $self->{wantlogininfo} = $val if defined $val;
752         return $self->{wantlogininfo};
753 }
754
755 sub is_node
756 {
757         my $self = shift;
758         return $self->{sort} =~ /[ACRSX]/;
759 }
760
761 sub is_local_node
762 {
763         my $self = shift;
764         return grep $_ eq 'local_node', @{$self->{group}};
765 }
766
767 sub is_user
768 {
769         my $self = shift;
770         return $self->{sort} eq 'U';
771 }
772
773 sub is_bbs
774 {
775         my $self = shift;
776         return $self->{sort} eq 'B';
777 }
778
779 sub is_spider
780 {
781         my $self = shift;
782         return $self->{sort} eq 'S';
783 }
784
785 sub is_clx
786 {
787         my $self = shift;
788         return $self->{sort} eq 'C';
789 }
790
791 sub is_dxnet
792 {
793         my $self = shift;
794         return $self->{sort} eq 'X';
795 }
796
797 sub is_arcluster
798 {
799         my $self = shift;
800         return $self->{sort} eq 'R';
801 }
802
803 sub is_ak1a
804 {
805         my $self = shift;
806         return $self->{sort} eq 'A';
807 }
808
809 sub unset_passwd
810 {
811         my $self = shift;
812         delete $self->{passwd};
813 }
814
815 sub unset_passphrase
816 {
817         my $self = shift;
818         delete $self->{passphrase};
819 }
820
821 sub set_believe
822 {
823         my $self = shift;
824         my $call = uc shift;
825         $self->{believe} ||= [];
826         push @{$self->{believe}}, $call unless grep $_ eq $call, @{$self->{believe}};
827 }
828
829 sub unset_believe
830 {
831         my $self = shift;
832         my $call = uc shift;
833         if (exists $self->{believe}) {
834                 $self->{believe} = [grep {$_ ne $call} @{$self->{believe}}];
835                 delete $self->{believe} unless @{$self->{believe}};
836         }
837 }
838
839 sub believe
840 {
841         my $self = shift;
842         return exists $self->{believe} ? @{$self->{believe}} : ();
843 }
844
845 sub lastping
846 {
847         my $self = shift;
848         my $call = shift;
849         $self->{lastping} ||= {};
850         $self->{lastping} = {} unless ref $self->{lastping};
851         my $b = $self->{lastping};
852         $b->{$call} = shift if @_;
853         return $b->{$call};     
854 }
855 1;
856 __END__
857
858
859
860
861