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