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