fix various issues
[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 $name = shift;
416         my $basic_info_only = shift;
417
418         my $fn = "$main::local_data/$name";
419         
420         # save old ones
421         move "$fn.oooo", "$fn.ooooo" if -e "$fn.oooo";
422         move "$fn.ooo", "$fn.oooo" if -e "$fn.ooo";
423         move "$fn.oo", "$fn.ooo" if -e "$fn.oo";
424         move "$fn.o", "$fn.oo" if -e "$fn.o";
425         move "$fn", "$fn.o" if -e "$fn";
426
427         my $count = 0;
428         my $err = 0;
429         my $del = 0;
430         my $fh = new IO::File ">$fn" or return "cannot open $fn ($!)";
431         if ($fh) {
432                 my $key = 0;
433                 my $val = undef;
434                 my $action;
435                 my $t = scalar localtime;
436                 print $fh q{#!/usr/bin/perl
437 #
438 # The exported userfile for a DXSpider System
439 #
440 # Input file: $filename
441 #       Time: $t
442 #
443                         
444 package main;
445                         
446 # search local then perl directories
447 BEGIN {
448         umask 002;
449                                 
450         # root of directory tree for this system
451         $root = "/spider"; 
452         $root = $ENV{'DXSPIDER_ROOT'} if $ENV{'DXSPIDER_ROOT'};
453         
454         unshift @INC, "$root/perl";     # this IS the right way round!
455         unshift @INC, "$root/local";
456         
457         # try to detect a lockfile (this isn't atomic but 
458         # should do for now
459         $lockfn = "$root/local_data/cluster.lck";       # lock file name
460         if (-e $lockfn) {
461                 open(CLLOCK, "$lockfn") or die "Can't open Lockfile ($lockfn) $!";
462                 my $pid = <CLLOCK>;
463                 chomp $pid;
464                 die "Lockfile ($lockfn) and process $pid exists - cluster must be stopped first\n" if kill 0, $pid;
465                 close CLLOCK;
466         }
467 }
468
469 package DXUser;
470
471 use SysVar;
472 use DXUser;
473
474 if (@ARGV) {
475         $main::userfn = shift @ARGV;
476         print "user filename now $userfn\n";
477 }
478
479 DXUser::del_file();
480 DXUser::init();
481 %u = ();
482 my $count = 0;
483 my $err = 0;
484 while (<DATA>) {
485         chomp;
486         my @f = split /\t/;
487         my $ref = asc_decode($f[1]);
488         if ($ref) {
489                 $ref->put();
490                 $count++;
491         } else {
492                 print "# Error: $f[0]\t$f[1]\n";
493                 $err++
494         }
495 }
496 DXUser::sync; DXUser::finish;
497 print "There are $count user records and $err errors\n";
498 };
499                 print $fh "__DATA__\n";
500
501         for ($action = R_FIRST; !$dbm->seq($key, $val, $action); $action = R_NEXT) {
502                         if (!is_callsign($key) || $key =~ /^0/) {
503                                 my $eval = $val;
504                                 my $ekey = $key;
505                                 $eval =~ s/([\%\x00-\x1f\x7f-\xff])/sprintf("%%%02X", ord($1))/eg; 
506                                 $ekey =~ s/([\%\x00-\x1f\x7f-\xff])/sprintf("%%%02X", ord($1))/eg; 
507                                 LogDbg('DXCommand', "Export Error1: $ekey\t$eval");
508                                 eval {$dbm->del($key)};
509                                 dbg(carp("Export Error1: $ekey\t$eval\n$@")) if $@;
510                                 ++$err;
511                                 next;
512                         }
513                         my $ref = decode($val);
514                         if ($ref) {
515                                 my $t = $ref->{lastin} || 0;
516                                 if ($ref->{sort} eq 'U' && !$ref->{priv} && $main::systime > $t + $tooold) {
517                                         unless ($ref->{lat} && $ref->{long} || $ref->{qth} || $ref->{qra}) {
518                                                 eval {$dbm->del($key)};
519                                                 dbg(carp("Export Error2: $key\t$val\n$@")) if $@;
520                                                 LogDbg('DXCommand', "$ref->{call} deleted, too old");
521                                                 $del++;
522                                                 next;
523                                         }
524                                 }
525                                 # only store users that are reasonably active or have useful information
526                                 print $fh "$key\t" . $ref->asc_encode($basic_info_only) . "\n";
527                                 ++$count;
528                         } else {
529                                 LogDbg('DXCommand', "Export Error3: $key\t$val");
530                                 eval {$dbm->del($key)};
531                                 dbg(carp("Export Error3: $key\t$val\n$@")) if $@;
532                                 ++$err;
533                         }
534                 } 
535         $fh->close;
536     } 
537         return "$count Users $del Deleted $err Errors ('sh/log Export' for details)";
538 }
539
540 #
541 # group handling
542 #
543
544 # add one or more groups
545 sub add_group
546 {
547         my $self = shift;
548         my $ref = $self->{group} || [ 'local' ];
549         $self->{group} = $ref if !$self->{group};
550         push @$ref, @_ if @_;
551 }
552
553 # remove one or more groups
554 sub del_group
555 {
556         my $self = shift;
557         my $ref = $self->{group} || [ 'local' ];
558         my @in = @_;
559         
560         $self->{group} = $ref if !$self->{group};
561         
562         @$ref = map { my $a = $_; return (grep { $_ eq $a } @in) ? () : $a } @$ref;
563 }
564
565 # does this thing contain all the groups listed?
566 sub union
567 {
568         my $self = shift;
569         my $ref = $self->{group};
570         my $n;
571         
572         return 0 if !$ref || @_ == 0;
573         return 1 if @$ref == 0 && @_ == 0;
574         for ($n = 0; $n < @_; ) {
575                 for (@$ref) {
576                         my $a = $_;
577                         $n++ if grep $_ eq $a, @_; 
578                 }
579         }
580         return $n >= @_;
581 }
582
583 # simplified group test just for one group
584 sub in_group
585 {
586         my $self = shift;
587         my $s = shift;
588         my $ref = $self->{group};
589         
590         return 0 if !$ref;
591         return grep $_ eq $s, $ref;
592 }
593
594 # set up a default group (only happens for them's that connect direct)
595 sub new_group
596 {
597         my $self = shift;
598         $self->{group} = [ 'local' ];
599 }
600
601 # set up empty buddies (only happens for them's that connect direct)
602 sub new_buddies
603 {
604         my $self = shift;
605         $self->{buddies} = [  ];
606 }
607
608 #
609 # return a prompt for a field
610 #
611
612 sub field_prompt
613
614         my ($self, $ele) = @_;
615         return $valid{$ele};
616 }
617
618 # some variable accessors
619 sub sort
620 {
621         my $self = shift;
622         @_ ? $self->{'sort'} = shift : $self->{'sort'} ;
623 }
624
625 # some accessors
626
627 # want is default = 1
628 sub _want
629 {
630         my $n = shift;
631         my $self = shift;
632         my $val = shift;
633         my $s = "want$n";
634         $self->{$s} = $val if defined $val;
635         return exists $self->{$s} ? $self->{$s} : 1;
636 }
637
638 # wantnot is default = 0
639 sub _wantnot
640 {
641         my $n = shift;
642         my $self = shift;
643         my $val = shift;
644         my $s = "want$n";
645         $self->{$s} = $val if defined $val;
646         return exists $self->{$s} ? $self->{$s} : 0;
647 }
648
649 sub wantbeep
650 {
651         return _want('beep', @_);
652 }
653
654 sub wantann
655 {
656         return _want('ann', @_);
657 }
658
659 sub wantwwv
660 {
661         return _want('wwv', @_);
662 }
663
664 sub wantwcy
665 {
666         return _want('wcy', @_);
667 }
668
669 sub wantecho
670 {
671         return _want('echo', @_);
672 }
673
674 sub wantwx
675 {
676         return _want('wx', @_);
677 }
678
679 sub wantdx
680 {
681         return _want('dx', @_);
682 }
683
684 sub wanttalk
685 {
686         return _want('talk', @_);
687 }
688
689 sub wantgrid
690 {
691         return _want('grid', @_);
692 }
693
694 sub wantemail
695 {
696         return _want('email', @_);
697 }
698
699 sub wantann_talk
700 {
701         return _want('ann_talk', @_);
702 }
703
704 sub wantpc16
705 {
706         return _want('pc16', @_);
707 }
708
709 sub wantsendpc16
710 {
711         return _want('sendpc16', @_);
712 }
713
714 sub wantroutepc16
715 {
716         return _want('routepc16', @_);
717 }
718
719 sub wantusstate
720 {
721         return _want('usstate', @_);
722 }
723
724 sub wantdxcq
725 {
726         return _want('dxcq', @_);
727 }
728
729 sub wantdxitu
730 {
731         return _want('dxitu', @_);
732 }
733
734 sub wantgtk
735 {
736         return _want('gtk', @_);
737 }
738
739 sub wantpc9x
740 {
741         return _want('pc9x', @_);
742 }
743
744 sub wantlogininfo
745 {
746         my $self = shift;
747         my $val = shift;
748         $self->{wantlogininfo} = $val if defined $val;
749         return $self->{wantlogininfo};
750 }
751
752 sub is_node
753 {
754         my $self = shift;
755         return $self->{sort} =~ /[ACRSX]/;
756 }
757
758 sub is_local_node
759 {
760         my $self = shift;
761         return grep $_ eq 'local_node', @{$self->{group}};
762 }
763
764 sub is_user
765 {
766         my $self = shift;
767         return $self->{sort} eq 'U';
768 }
769
770 sub is_bbs
771 {
772         my $self = shift;
773         return $self->{sort} eq 'B';
774 }
775
776 sub is_spider
777 {
778         my $self = shift;
779         return $self->{sort} eq 'S';
780 }
781
782 sub is_clx
783 {
784         my $self = shift;
785         return $self->{sort} eq 'C';
786 }
787
788 sub is_dxnet
789 {
790         my $self = shift;
791         return $self->{sort} eq 'X';
792 }
793
794 sub is_arcluster
795 {
796         my $self = shift;
797         return $self->{sort} eq 'R';
798 }
799
800 sub is_ak1a
801 {
802         my $self = shift;
803         return $self->{sort} eq 'A';
804 }
805
806 sub unset_passwd
807 {
808         my $self = shift;
809         delete $self->{passwd};
810 }
811
812 sub unset_passphrase
813 {
814         my $self = shift;
815         delete $self->{passphrase};
816 }
817
818 sub set_believe
819 {
820         my $self = shift;
821         my $call = uc shift;
822         $self->{believe} ||= [];
823         push @{$self->{believe}}, $call unless grep $_ eq $call, @{$self->{believe}};
824 }
825
826 sub unset_believe
827 {
828         my $self = shift;
829         my $call = uc shift;
830         if (exists $self->{believe}) {
831                 $self->{believe} = [grep {$_ ne $call} @{$self->{believe}}];
832                 delete $self->{believe} unless @{$self->{believe}};
833         }
834 }
835
836 sub believe
837 {
838         my $self = shift;
839         return exists $self->{believe} ? @{$self->{believe}} : ();
840 }
841
842 sub lastping
843 {
844         my $self = shift;
845         my $call = shift;
846         $self->{lastping} ||= {};
847         $self->{lastping} = {} unless ref $self->{lastping};
848         my $b = $self->{lastping};
849         $b->{$call} = shift if @_;
850         return $b->{$call};     
851 }
852 1;
853 __END__
854
855
856
857
858