put dx.pl into an explicit handle sub
[spider.git] / perl / DXUser.pm
1 #
2 # DX cluster user routines
3 #
4 # Copyright (c) 1998 - Dirk Koopman G1TLH
5 #
6 #
7 #
8
9 package DXUser;
10
11 use DXLog;
12 use DB_File;
13 use Data::Dumper;
14 use Fcntl;
15 use IO::File;
16 use DXDebug;
17 use DXUtil;
18 use LRU;
19 use File::Copy;
20
21 use strict;
22
23 use vars qw(%u $dbm $filename %valid $lastoperinterval $lasttime $lru $lrusize $tooold $v3);
24
25 %u = ();
26 $dbm = undef;
27 $filename = undef;
28 $lastoperinterval = 60*24*60*60;
29 $lasttime = 0;
30 $lrusize = 2000;
31 $tooold = 86400 * 365;          # this marks an old user who hasn't given enough info to be useful
32 $v3 = 0;
33
34 # hash of valid elements and a simple prompt
35 %valid = (
36                   call => '0,Callsign',
37                   alias => '0,Real Callsign',
38                   name => '0,Name',
39                   qth => '0,Home QTH',
40                   lat => '0,Latitude,slat',
41                   long => '0,Longitude,slong',
42                   qra => '0,Locator',
43                   email => '0,E-mail Address,parray',
44                   priv => '9,Privilege Level',
45                   lastin => '0,Last Time in,cldatetime',
46                   passwd => '9,Password,yesno',
47                   passphrase => '9,Pass Phrase,yesno',
48                   addr => '0,Full Address',
49                   'sort' => '0,Type of User', # A - ak1a, U - User, S - spider cluster, B - BBS
50                   xpert => '0,Expert Status,yesno',
51                   bbs => '0,Home BBS',
52                   node => '0,Last Node',
53                   homenode => '0,Home Node',
54                   lockout => '9,Locked out?,yesno',     # won't let them in at all
55                   dxok => '9,Accept DX Spots?,yesno', # accept his dx spots?
56                   annok => '9,Accept Announces?,yesno', # accept his announces?
57                   lang => '0,Language',
58                   hmsgno => '0,Highest Msgno',
59                   group => '0,Group,parray',    # used to create a group of users/nodes for some purpose or other
60                   buddies => '0,Buddies,parray',
61                   isolate => '9,Isolate network,yesno',
62                   wantbeep => '0,Req Beep,yesno',
63                   wantann => '0,Req Announce,yesno',
64                   wantwwv => '0,Req WWV,yesno',
65                   wantwcy => '0,Req WCY,yesno',
66                   wantecho => '0,Req Echo,yesno',
67                   wanttalk => '0,Req Talk,yesno',
68                   wantwx => '0,Req WX,yesno',
69                   wantdx => '0,Req DX Spots,yesno',
70                   wantemail => '0,Req Msgs as Email,yesno',
71                   pagelth => '0,Current Pagelth',
72                   pingint => '9,Node Ping interval',
73                   nopings => '9,Ping Obs Count',
74                   wantlogininfo => '0,Login Info Req,yesno',
75           wantgrid => '0,Show DX Grid,yesno',
76                   wantann_talk => '0,Talklike Anns,yesno',
77                   wantpc16 => '9,Want Users from node,yesno',
78                   wantsendpc16 => '9,Send PC16,yesno',
79                   wantroutepc19 => '9,Route PC19,yesno',
80                   wantusstate => '0,Show US State,yesno',
81                   wantdxcq => '0,Show CQ Zone,yesno',
82                   wantdxitu => '0,Show ITU Zone,yesno',
83                   wantgtk => '0,Want GTK interface,yesno',
84                   wantpc9x => '0,Want PC9X interface,yesno',
85                   lastoper => '9,Last for/oper,cldatetime',
86                   nothere => '0,Not Here Text',
87                   registered => '9,Registered?,yesno',
88                   prompt => '0,Required Prompt',
89                   version => '1,Version',
90                   build => '1,Build',
91                   believe => '1,Believable nodes,parray',
92                   lastping => '1,Last Ping at,ptimelist',
93                   maxconnect => '1,Max Connections',
94                  );
95
96 #no strict;
97 sub AUTOLOAD
98 {
99         no strict;
100         my $name = $AUTOLOAD;
101   
102         return if $name =~ /::DESTROY$/;
103         $name =~ s/^.*:://o;
104   
105         confess "Non-existant field '$AUTOLOAD'" if !$valid{$name};
106         # this clever line of code creates a subroutine which takes over from autoload
107         # from OO Perl - Conway
108         *$AUTOLOAD = sub {@_ > 1 ? $_[0]->{$name} = $_[1] : $_[0]->{$name}};
109        goto &$AUTOLOAD;
110 }
111
112 #use strict;
113
114 #
115 # initialise the system
116 #
117 sub init
118 {
119         my $mode = shift;
120   
121         my $ufn;
122         my $convert;
123         
124         eval {
125                 require Storable;
126         };
127
128         my $fn = "users";
129         
130         if ($@) {
131                 $ufn = localdata("users.v2");
132                 $v3 = $convert = 0;
133                 dbg("the module Storable appears to be missing!!");
134                 dbg("trying to continue in compatibility mode (this may fail)");
135                 dbg("please install Storable from CPAN as soon as possible");
136         } else {
137                 import Storable qw(nfreeze thaw);
138
139                 $ufn = localdata("users.v3");
140                 $v3 = 1;
141                 $convert++ if -e localdata("users.v2") && !-e $ufn;
142         }
143         
144         if ($mode) {
145                 $dbm = tie (%u, 'DB_File', $ufn, O_CREAT|O_RDWR, 0666, $DB_BTREE) or confess "can't open user file: $fn ($!) [rebuild it from user_asc?]";
146         } else {
147                 $dbm = tie (%u, 'DB_File', $ufn, O_RDONLY, 0666, $DB_BTREE) or confess "can't open user file: $fn ($!) [rebuild it from user_asc?]";
148         }
149
150         die "Cannot open $ufn ($!)\n" unless $dbm;
151
152         $lru = LRU->newbase("DXUser", $lrusize);
153         
154         # do a conversion if required
155         if ($dbm && $convert) {
156                 my ($key, $val, $action, $count, $err) = ('','',0,0,0);
157                 
158                 my %oldu;
159                 dbg("Converting the User File to V3 ");
160                 dbg("This will take a while, I suggest you go and have cup of strong tea");
161                 my $odbm = tie (%oldu, 'DB_File', localdata("users.v2"), O_RDONLY, 0666, $DB_BTREE) or confess "can't open user file: $fn.v2 ($!) [rebuild it from user_asc?]";
162         for ($action = R_FIRST; !$odbm->seq($key, $val, $action); $action = R_NEXT) {
163                         my $ref = asc_decode($val);
164                         if ($ref) {
165                                 $ref->put;
166                                 $count++;
167                         } else {
168                                 $err++
169                         }
170                 } 
171                 undef $odbm;
172                 untie %oldu;
173                 dbg("Conversion completed $count records $err errors");
174         }
175         $filename = $ufn;
176 }
177
178 sub del_file
179 {
180         my $fn = localdata("users");
181         $fn .= $v3 ? ".v3" : ".v2";
182         unlink $fn;
183 }
184
185 #
186 # periodic processing
187 #
188 sub process
189 {
190         if ($main::systime > $lasttime + 15) {
191                 $dbm->sync if $dbm;
192                 $lasttime = $main::systime;
193         }
194 }
195
196 #
197 # close the system
198 #
199
200 sub finish
201 {
202         undef $dbm;
203         untie %u;
204 }
205
206 #
207 # new - create a new user
208 #
209
210 sub alloc
211 {
212         my $pkg = shift;
213         my $call = uc shift;
214         my $self = bless {call => $call, 'sort'=>'U'}, $pkg;
215         return $self;
216 }
217
218 sub new
219 {
220         my $pkg = shift;
221         my $call = shift;
222         #  $call =~ s/-\d+$//o;
223   
224 #       confess "can't create existing call $call in User\n!" if $u{$call};
225
226         my $self = $pkg->alloc($call);
227         $self->put;
228         return $self;
229 }
230
231 #
232 # get - get an existing user - this seems to return a different reference everytime it is
233 #       called - see below
234 #
235
236 sub get
237 {
238         my $call = uc shift;
239         my $data;
240         
241         # is it in the LRU cache?
242         my $ref = $lru->get($call);
243         return $ref if $ref && ref $ref eq 'DXUser';
244         
245         # search for it
246         unless ($dbm->get($call, $data)) {
247                 $ref = decode($data);
248                 if ($ref) {
249                         if (!UNIVERSAL::isa($ref, 'DXUser')) {
250                                 dbg("DXUser::get: got strange answer from decode of $call". ref $ref. " ignoring");
251                                 return undef;
252                         }
253                         # we have a reference and it *is* a DXUser
254                 } else {
255                         dbg("DXUser::get: no reference returned from decode of $call $!");
256                         return undef;
257                 }
258                 $lru->put($call, $ref);
259                 return $ref;
260         }
261         return undef;
262 }
263
264 #
265 # get an existing either from the channel (if there is one) or from the database
266 #
267 # It is important to note that if you have done a get (for the channel say) and you
268 # want access or modify that you must use this call (and you must NOT use get's all
269 # over the place willy nilly!)
270 #
271
272 sub get_current
273 {
274         my $call = uc shift;
275   
276         my $dxchan = DXChannel::get($call);
277         if ($dxchan) {
278                 my $ref = $dxchan->user;
279                 return $ref if $ref && UNIVERSAL::isa($ref, 'DXUser');
280
281                 dbg("DXUser::get_current: got invalid user ref for $call from dxchan $dxchan->{call} ". ref $ref. " ignoring");
282         }
283         return get($call);
284 }
285
286 #
287 # get all callsigns in the database 
288 #
289
290 sub get_all_calls
291 {
292         return (sort keys %u);
293 }
294
295 #
296 # put - put a user
297 #
298
299 sub put
300 {
301         my $self = shift;
302         confess "Trying to put nothing!" unless $self && ref $self;
303         my $call = $self->{call};
304
305         $dbm->del($call);
306         delete $self->{annok} if $self->{annok};
307         delete $self->{dxok} if $self->{dxok};
308
309         $lru->put($call, $self);
310         my $ref = $self->encode;
311         $dbm->put($call, $ref);
312 }
313
314 # freeze the user
315 sub encode
316 {
317         goto &asc_encode unless $v3;
318         my $self = shift;
319         return nfreeze($self);
320 }
321
322 # thaw the user
323 sub decode
324 {
325         goto &asc_decode unless $v3;
326         return thaw(shift);
327 }
328
329
330 # create a string from a user reference (in_ascii)
331 #
332 sub asc_encode
333 {
334         my $self = shift;
335         my $strip = shift;
336         my $p;
337
338         if ($strip) {
339                 my $ref = bless {}, ref $self;
340                 foreach my $k (qw(qth lat long qra sort call homenode node lastoper lastin)) {
341                         $ref->{$k} = $self->{$k} if exists $self->{$k};
342                 }
343                 $ref->{name} = $self->{name} if exists $self->{name} && $self->{name} !~ /selfspot/i;
344                 $p = dd($ref);
345         } else {
346                 $p = dd($self);
347         }
348         return $p;
349 }
350
351 #
352 # create a hash from a string (in ascii)
353 #
354 sub asc_decode
355 {
356         my $s = shift;
357         my $ref;
358         $s =~ s/\%([0-9A-F][0-9A-F])/chr(hex($1))/eg;
359         eval '$ref = ' . $s;
360         if ($@) {
361                 LogDbg('err', $@);
362                 $ref = undef;
363         }
364         return $ref;
365 }
366
367 #
368 # del - delete a user
369 #
370
371 sub del
372 {
373         my $self = shift;
374         my $call = $self->{call};
375         $lru->remove($call);
376         $dbm->del($call);
377 }
378
379 #
380 # close - close down a user
381 #
382
383 sub close
384 {
385         my $self = shift;
386         $self->{lastin} = time;
387         $self->put();
388 }
389
390 #
391 # sync the database
392 #
393
394 sub sync
395 {
396         $dbm->sync;
397 }
398
399 #
400 # return a list of valid elements 
401
402
403 sub fields
404 {
405         return keys(%valid);
406 }
407
408
409 #
410 # export the database to an ascii file
411 #
412
413 sub export
414 {
415         my $name = shift || 'user_asc';
416         my $basic_info_only = shift;
417
418         my $fn = $name ne 'user_asc' ? $name : "$main::local_data/$name";                       # force use of local
419         
420         # save old ones
421         move "$fn.oooo", "$fn.ooooo" if -e "$fn.oooo";
422         move "$fn.ooo", "$fn.oooo" if -e "$fn.ooo";
423         move "$fn.oo", "$fn.ooo" if -e "$fn.oo";
424         move "$fn.o", "$fn.oo" if -e "$fn.o";
425         move "$fn", "$fn.o" if -e "$fn";
426
427         my $count = 0;
428         my $err = 0;
429         my $del = 0;
430         my $fh = new IO::File ">$fn" or return "cannot open $fn ($!)";
431         if ($fh) {
432                 my $key = 0;
433                 my $val = undef;
434                 my $action;
435                 my $t = scalar localtime;
436                 print $fh q{#!/usr/bin/perl
437 #
438 # The exported userfile for a DXSpider System
439 #
440 # Input file: $filename
441 #       Time: $t
442 #
443                         
444 package main;
445                         
446 # search local then perl directories
447 BEGIN {
448         umask 002;
449                                 
450         # root of directory tree for this system
451         $root = "/spider"; 
452         $root = $ENV{'DXSPIDER_ROOT'} if $ENV{'DXSPIDER_ROOT'};
453         
454         unshift @INC, "$root/perl";     # this IS the right way round!
455         unshift @INC, "$root/local";
456         
457         # try to detect a lockfile (this isn't atomic but 
458         # should do for now
459         $lockfn = "$root/local_data/cluster.lck";       # lock file name
460         if (-e $lockfn) {
461                 open(CLLOCK, "$lockfn") or die "Can't open Lockfile ($lockfn) $!";
462                 my $pid = <CLLOCK>;
463                 chomp $pid;
464                 die "Lockfile ($lockfn) and process $pid exists - cluster must be stopped first\n" if kill 0, $pid;
465                 close CLLOCK;
466         }
467 }
468
469 use SysVar;
470 use DXUser;
471
472 if (@ARGV) {
473         $main::userfn = shift @ARGV;
474         print "user filename now $userfn\n";
475 }
476
477 package DXUser;
478
479 del_file();
480 init(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->is_user && !$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         my $s = qq{Exported users to $fn - $count Users $del Deleted $err Errors ('sh/log Export' for details)};
538         LogDbg('command', $s);
539         return $s;
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} =~ /^[UW]$/;
770 }
771
772 sub is_web
773 {
774         my $self = shift;
775         return $self->{sort} eq 'W';
776 }
777
778 sub is_bbs
779 {
780         my $self = shift;
781         return $self->{sort} eq 'B';
782 }
783
784 sub is_spider
785 {
786         my $self = shift;
787         return $self->{sort} eq 'S';
788 }
789
790 sub is_clx
791 {
792         my $self = shift;
793         return $self->{sort} eq 'C';
794 }
795
796 sub is_dxnet
797 {
798         my $self = shift;
799         return $self->{sort} eq 'X';
800 }
801
802 sub is_arcluster
803 {
804         my $self = shift;
805         return $self->{sort} eq 'R';
806 }
807
808 sub is_ak1a
809 {
810         my $self = shift;
811         return $self->{sort} eq 'A';
812 }
813
814 sub unset_passwd
815 {
816         my $self = shift;
817         delete $self->{passwd};
818 }
819
820 sub unset_passphrase
821 {
822         my $self = shift;
823         delete $self->{passphrase};
824 }
825
826 sub set_believe
827 {
828         my $self = shift;
829         my $call = uc shift;
830         $self->{believe} ||= [];
831         push @{$self->{believe}}, $call unless grep $_ eq $call, @{$self->{believe}};
832 }
833
834 sub unset_believe
835 {
836         my $self = shift;
837         my $call = uc shift;
838         if (exists $self->{believe}) {
839                 $self->{believe} = [grep {$_ ne $call} @{$self->{believe}}];
840                 delete $self->{believe} unless @{$self->{believe}};
841         }
842 }
843
844 sub believe
845 {
846         my $self = shift;
847         return exists $self->{believe} ? @{$self->{believe}} : ();
848 }
849
850 sub lastping
851 {
852         my $self = shift;
853         my $call = shift;
854         $self->{lastping} ||= {};
855         $self->{lastping} = {} unless ref $self->{lastping};
856         my $b = $self->{lastping};
857         $b->{$call} = shift if @_;
858         return $b->{$call};     
859 }
860 1;
861 __END__
862
863
864
865
866