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