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