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