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