8890fae9185b4d990bf9f0d6737304d22b6088a6
[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                  );
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 = DXJSON->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         return $json->decode(shift, __PACKAGE__);
313 }
314
315 # freeze the user
316 sub encode
317 {
318         return $json->encode(shift);
319 }
320
321
322 #
323 # del - delete a user
324 #
325
326 sub del
327 {
328         my $self = shift;
329         my $call = $self->{call};
330         $lru->remove($call);
331         $dbm->del($call);
332 }
333
334 #
335 # close - close down a user
336 #
337
338 sub close
339 {
340         my $self = shift;
341         my $startt = shift;
342         my $ip = shift;
343         $self->{lastseen} = $self->{lastin} = $main::systime;
344         # add a record to the connect list
345         my $ref = [$startt || $self->{startt}, $main::systime];
346         push @$ref, $ip if $ip;
347         push @{$self->{connlist}}, $ref;
348         shift @{$self->{connlist}} if @{$self->{connlist}} > $maxconnlist;
349         $self->put();
350 }
351
352 #
353 # sync the database
354 #
355
356 sub sync
357 {
358         $dbm->sync;
359 }
360
361 #
362 # return a list of valid elements 
363
364
365 sub fields
366 {
367         return keys(%valid);
368 }
369
370
371 #
372 # export the database to an ascii file
373 #
374
375 sub export
376 {
377         my $name = shift || 'user_json';
378         my $basic_info_only = shift;
379
380         my $fn = $name ne 'user_json' ? $name : "$main::local_data/$name";                       # force use of local
381         
382         # save old ones
383         move "$fn.oooo", "$fn.ooooo" if -e "$fn.oooo";
384         move "$fn.ooo", "$fn.oooo" if -e "$fn.ooo";
385         move "$fn.oo", "$fn.ooo" if -e "$fn.oo";
386         move "$fn.o", "$fn.oo" if -e "$fn.o";
387         move "$fn", "$fn.o" if -e "$fn";
388
389         my $ta = [gettimeofday];
390         my $count = 0;
391         my $err = 0;
392         my $del = 0;
393         my $fh = new IO::File ">$fn" or return "cannot open $fn ($!)";
394         if ($fh) {
395                 my $key = 0;
396                 my $val = undef;
397                 my $action;
398                 my $t = scalar localtime;
399                 print $fh q{#!/usr/bin/perl
400 #
401 # The exported userfile for a DXSpider System
402 #
403 # Input file: $filename
404 #       Time: $t
405 #
406                         
407 package main;
408                         
409 # search local then perl directories
410 BEGIN {
411         umask 002;
412                                 
413         # root of directory tree for this system
414         $root = "/spider"; 
415         $root = $ENV{'DXSPIDER_ROOT'} if $ENV{'DXSPIDER_ROOT'};
416         
417         unshift @INC, "$root/perl";     # this IS the right way round!
418         unshift @INC, "$root/local";
419         
420         # try to detect a lockfile (this isn't atomic but 
421         # should do for now
422         $lockfn = "$root/local_data/cluster.lck";       # lock file name
423         if (-e $lockfn) {
424                 open(CLLOCK, "$lockfn") or die "Can't open Lockfile ($lockfn) $!";
425                 my $pid = <CLLOCK>;
426                 chomp $pid;
427                 die "Lockfile ($lockfn) and process $pid exists - cluster must be stopped first\n" if kill 0, $pid;
428                 close CLLOCK;
429         }
430 }
431
432 use SysVar;
433 use DXUtil;
434 use DXUser;
435 use JSON;
436 use Time::HiRes qw(gettimeofday tv_interval);
437 package DXUser;
438
439 our $json = JSON->new->canonical(1);
440
441 my $ta = [gettimeofday];
442 our $filename = "$main::local_data/users.v3j";
443 my $exists = -e $filename ? "OVERWRITING" : "CREATING"; 
444 print "perl user_json $exists $filename\n";
445
446 del_file();
447 init(2);
448 %u = ();
449 my $count = 0;
450 my $err = 0;
451 while (<DATA>) {
452         chomp;
453         my @f = split /\t/;
454         my $ref = decode($f[1]);
455         if ($ref) {
456                 $ref->put();
457                 $count++;
458         } else {
459                 print "# Error: $f[0]\t$f[1]\n";
460                 $err++
461         }
462 }
463 DXUser::sync(); DXUser::finish();
464 my $diff = _diffms($ta);
465 print "There are $count user records and $err errors in $diff mS\n";
466 };
467                 print $fh "__DATA__\n";
468
469         for ($action = R_FIRST; !$dbm->seq($key, $val, $action); $action = R_NEXT) {
470                         if (!is_callsign($key) || $key =~ /^0/) {
471                                 my $eval = $val;
472                                 my $ekey = $key;
473                                 $eval =~ s/([\%\x00-\x1f\x7f-\xff])/sprintf("%%%02X", ord($1))/eg; 
474                                 $ekey =~ s/([\%\x00-\x1f\x7f-\xff])/sprintf("%%%02X", ord($1))/eg;
475                                 LogDbg('DXCommand', "Export Error1: invalid call '$key' => '$val'");
476                                 eval {$dbm->del($key)};
477                             dbg(carp("Export Error1: delete $key => '$val' $@")) if $@;
478                                 ++$err;
479                                 next;
480                         }
481                         my $ref;
482                         eval {$ref = decode($val); };
483                         if ($ref) {
484                                 my $t = $ref->{lastin} || 0;
485                                 if ($ref->is_user && !$ref->{priv} && $main::systime > $t + $tooold) {
486                                         unless ($ref->{lat} && $ref->{long} || $ref->{qth} || $ref->{qra}) {
487                                                 eval {$dbm->del($key)};
488                                                 dbg(carp("Export Error2: delete '$key' => '$val' $@")) if $@;
489                                                 LogDbg('DXCommand', "$ref->{call} deleted, too old");
490                                                 $del++;
491                                                 next;
492                                         }
493                                 }
494                                 # only store users that are reasonably active or have useful information
495                                 print $fh "$key\t" . encode($ref) . "\n";
496                                 ++$count;
497                         } else {
498                                 LogDbg('DXCommand', "Export Error3: '$key'\t" . carp($val) ."\n$@");
499                                 eval {$dbm->del($key)};
500                                 dbg(carp("Export Error3: delete '$key' => '$val' $@")) if $@;
501                                 ++$err;
502                         }
503                 } 
504         $fh->close;
505     }
506         my $diff = _diffms($ta);
507         my $s = qq{Exported users to $fn - $count Users $del Deleted $err Errors in $diff mS ('sh/log Export' for details)};
508         LogDbg('command', $s);
509         return $s;
510 }
511
512 #
513 # group handling
514 #
515
516 # add one or more groups
517 sub add_group
518 {
519         my $self = shift;
520         my $ref = $self->{group} || [ 'local' ];
521         $self->{group} = $ref if !$self->{group};
522         push @$ref, @_ if @_;
523 }
524
525 # remove one or more groups
526 sub del_group
527 {
528         my $self = shift;
529         my $ref = $self->{group} || [ 'local' ];
530         my @in = @_;
531         
532         $self->{group} = $ref if !$self->{group};
533         
534         @$ref = map { my $a = $_; return (grep { $_ eq $a } @in) ? () : $a } @$ref;
535 }
536
537 # does this thing contain all the groups listed?
538 sub union
539 {
540         my $self = shift;
541         my $ref = $self->{group};
542         my $n;
543         
544         return 0 if !$ref || @_ == 0;
545         return 1 if @$ref == 0 && @_ == 0;
546         for ($n = 0; $n < @_; ) {
547                 for (@$ref) {
548                         my $a = $_;
549                         $n++ if grep $_ eq $a, @_; 
550                 }
551         }
552         return $n >= @_;
553 }
554
555 # simplified group test just for one group
556 sub in_group
557 {
558         my $self = shift;
559         my $s = shift;
560         my $ref = $self->{group};
561         
562         return 0 if !$ref;
563         return grep $_ eq $s, $ref;
564 }
565
566 # set up a default group (only happens for them's that connect direct)
567 sub new_group
568 {
569         my $self = shift;
570         $self->{group} = [ 'local' ];
571 }
572
573 # set up empty buddies (only happens for them's that connect direct)
574 sub new_buddies
575 {
576         my $self = shift;
577         $self->{buddies} = [  ];
578 }
579
580 #
581 # return a prompt for a field
582 #
583
584 sub field_prompt
585
586         my ($self, $ele) = @_;
587         return $valid{$ele};
588 }
589
590 # some variable accessors
591 sub sort
592 {
593         my $self = shift;
594         @_ ? $self->{'sort'} = shift : $self->{'sort'} ;
595 }
596
597 # some accessors
598
599 # want is default = 1
600 sub _want
601 {
602         my $n = shift;
603         my $self = shift;
604         my $val = shift;
605         my $s = "want$n";
606         $self->{$s} = $val if defined $val;
607         return exists $self->{$s} ? $self->{$s} : 1;
608 }
609
610 # wantnot is default = 0
611 sub _wantnot
612 {
613         my $n = shift;
614         my $self = shift;
615         my $val = shift;
616         my $s = "want$n";
617         $self->{$s} = $val if defined $val;
618         return exists $self->{$s} ? $self->{$s} : 0;
619 }
620
621 sub wantbeep
622 {
623         return _want('beep', @_);
624 }
625
626 sub wantann
627 {
628         return _want('ann', @_);
629 }
630
631 sub wantwwv
632 {
633         return _want('wwv', @_);
634 }
635
636 sub wantwcy
637 {
638         return _want('wcy', @_);
639 }
640
641 sub wantecho
642 {
643         return _want('echo', @_);
644 }
645
646 sub wantwx
647 {
648         return _want('wx', @_);
649 }
650
651 sub wantdx
652 {
653         return _want('dx', @_);
654 }
655
656 sub wanttalk
657 {
658         return _want('talk', @_);
659 }
660
661 sub wantgrid
662 {
663         return _wantnot('grid', @_);
664 }
665
666 sub wantemail
667 {
668         return _want('email', @_);
669 }
670
671 sub wantann_talk
672 {
673         return _want('ann_talk', @_);
674 }
675
676 sub wantpc16
677 {
678         return _want('pc16', @_);
679 }
680
681 sub wantsendpc16
682 {
683         return _want('sendpc16', @_);
684 }
685
686 sub wantroutepc16
687 {
688         return _want('routepc16', @_);
689 }
690
691 sub wantusstate
692 {
693         return _want('usstate', @_);
694 }
695
696 sub wantdxcq
697 {
698         return _wantnot('dxcq', @_);
699 }
700
701 sub wantdxitu
702 {
703         return _wantnot('dxitu', @_);
704 }
705
706 sub wantgtk
707 {
708         return _want('gtk', @_);
709 }
710
711 sub wantpc9x
712 {
713         return _want('pc9x', @_);
714 }
715
716 sub wantlogininfo
717 {
718         my $self = shift;
719         my $val = shift;
720         $self->{wantlogininfo} = $val if defined $val;
721         return $self->{wantlogininfo};
722 }
723
724 sub is_node
725 {
726         my $self = shift;
727         return $self->{sort} =~ /^[ACRSX]$/;
728 }
729
730 sub is_local_node
731 {
732         my $self = shift;
733         return grep $_ eq 'local_node', @{$self->{group}};
734 }
735
736 sub is_user
737 {
738         my $self = shift;
739         return $self->{sort} =~ /^[UW]$/;
740 }
741
742 sub is_web
743 {
744         my $self = shift;
745         return $self->{sort} eq 'W';
746 }
747
748 sub is_bbs
749 {
750         my $self = shift;
751         return $self->{sort} eq 'B';
752 }
753
754 sub is_spider
755 {
756         my $self = shift;
757         return $self->{sort} eq 'S';
758 }
759
760 sub is_clx
761 {
762         my $self = shift;
763         return $self->{sort} eq 'C';
764 }
765
766 sub is_dxnet
767 {
768         my $self = shift;
769         return $self->{sort} eq 'X';
770 }
771
772 sub is_arcluster
773 {
774         my $self = shift;
775         return $self->{sort} eq 'R';
776 }
777
778 sub is_ak1a
779 {
780         my $self = shift;
781         return $self->{sort} eq 'A';
782 }
783
784 sub is_rbn
785 {
786         my $self = shift;
787         return $self->{sort} eq 'N'
788 }
789
790 sub unset_passwd
791 {
792         my $self = shift;
793         delete $self->{passwd};
794 }
795
796 sub unset_passphrase
797 {
798         my $self = shift;
799         delete $self->{passphrase};
800 }
801
802 sub set_believe
803 {
804         my $self = shift;
805         my $call = uc shift;
806         $self->{believe} ||= [];
807         push @{$self->{believe}}, $call unless grep $_ eq $call, @{$self->{believe}};
808 }
809
810 sub unset_believe
811 {
812         my $self = shift;
813         my $call = uc shift;
814         if (exists $self->{believe}) {
815                 $self->{believe} = [grep {$_ ne $call} @{$self->{believe}}];
816                 delete $self->{believe} unless @{$self->{believe}};
817         }
818 }
819
820 sub believe
821 {
822         my $self = shift;
823         return exists $self->{believe} ? @{$self->{believe}} : ();
824 }
825
826 sub lastping
827 {
828         my $self = shift;
829         my $call = shift;
830         $self->{lastping} ||= {};
831         $self->{lastping} = {} unless ref $self->{lastping};
832         my $b = $self->{lastping};
833         $b->{$call} = shift if @_;
834         return $b->{$call};     
835 }
836 1;
837 __END__
838
839
840
841
842