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