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