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