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