add logging of PC92A ip addresses
[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 (ref $ref ne 'DXUser') {
253                                 dbg("DXUser::get: got strange answer from decode ". ref $ref. " ignoring");
254                                 return undef;
255                         }
256                 } else {
257                         dbg("DXUser::get: no reference returned from decode $!");
258                         return undef;
259                 }
260                 $lru->put($call, $ref);
261                 return $ref;
262         }
263         return undef;
264 }
265
266 #
267 # get an existing either from the channel (if there is one) or from the database
268 #
269 # It is important to note that if you have done a get (for the channel say) and you
270 # want access or modify that you must use this call (and you must NOT use get's all
271 # over the place willy nilly!)
272 #
273
274 sub get_current
275 {
276         my $call = uc shift;
277   
278         my $dxchan = DXChannel::get($call);
279         if ($dxchan) {
280                 my $ref = $dxchan->user;
281                 return $ref if ref $ref eq 'DXUser';
282
283                 dbg("DXUser::get_current: got invalid user ref from dxchan $dxchan->{call} ". ref $ref. " ignoring");
284         }
285         return get($call);
286 }
287
288 #
289 # get all callsigns in the database 
290 #
291
292 sub get_all_calls
293 {
294         return (sort keys %u);
295 }
296
297 #
298 # put - put a user
299 #
300
301 sub put
302 {
303         my $self = shift;
304         confess "Trying to put nothing!" unless $self && ref $self;
305         my $call = $self->{call};
306
307         $dbm->del($call);
308         delete $self->{annok} if $self->{annok};
309         delete $self->{dxok} if $self->{dxok};
310
311         $lru->put($call, $self);
312         my $ref = $self->encode;
313         $dbm->put($call, $ref);
314 }
315
316 # freeze the user
317 sub encode
318 {
319         goto &asc_encode unless $v3;
320         my $self = shift;
321         return nfreeze($self);
322 }
323
324 # thaw the user
325 sub decode
326 {
327         goto &asc_decode unless $v3;
328         return thaw(shift);
329 }
330
331
332 # create a string from a user reference (in_ascii)
333 #
334 sub asc_encode
335 {
336         my $self = shift;
337         my $strip = shift;
338         my $p;
339
340         if ($strip) {
341                 my $ref = bless {}, ref $self;
342                 foreach my $k (qw(qth lat long qra sort call homenode node lastoper lastin)) {
343                         $ref->{$k} = $self->{$k} if exists $self->{$k};
344                 }
345                 $ref->{name} = $self->{name} if exists $self->{name} && $self->{name} !~ /selfspot/i;
346                 $p = dd($ref);
347         } else {
348                 $p = dd($self);
349         }
350         return $p;
351 }
352
353 #
354 # create a hash from a string (in ascii)
355 #
356 sub asc_decode
357 {
358         my $s = shift;
359         my $ref;
360         $s =~ s/\%([0-9A-F][0-9A-F])/chr(hex($1))/eg;
361         eval '$ref = ' . $s;
362         if ($@) {
363                 LogDbg('err', $@);
364                 $ref = undef;
365         }
366         return $ref;
367 }
368
369 #
370 # del - delete a user
371 #
372
373 sub del
374 {
375         my $self = shift;
376         my $call = $self->{call};
377         $lru->remove($call);
378         $dbm->del($call);
379 }
380
381 #
382 # close - close down a user
383 #
384
385 sub close
386 {
387         my $self = shift;
388         $self->{lastin} = time;
389         $self->put();
390 }
391
392 #
393 # sync the database
394 #
395
396 sub sync
397 {
398         $dbm->sync;
399 }
400
401 #
402 # return a list of valid elements 
403
404
405 sub fields
406 {
407         return keys(%valid);
408 }
409
410
411 #
412 # export the database to an ascii file
413 #
414
415 sub export
416 {
417         my $fn = shift;
418         my $basic_info_only = shift;
419         
420         # save old ones
421         rename "$fn.oooo", "$fn.ooooo" if -e "$fn.oooo";
422         rename "$fn.ooo", "$fn.oooo" if -e "$fn.ooo";
423         rename "$fn.oo", "$fn.ooo" if -e "$fn.oo";
424         rename "$fn.o", "$fn.oo" if -e "$fn.o";
425         rename "$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/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 DXVars;
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($main::userfn);
480 DXUser->init($main::userfn, 1);
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