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