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