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