2 # DX cluster user routines
4 # Copyright (c) 1998 - Dirk Koopman G1TLH
20 use Data::Structure::Util qw(unbless);
21 use Time::HiRes qw(gettimeofday tv_interval);
28 use vars qw(%u $dbm $filename %valid $lastoperinterval $lasttime $lru $lrusize $tooold $veryold $v3);
33 $lastoperinterval = 60*24*60*60;
36 $tooold = 86400 * 365 * 2; # this marks an old user who hasn't given enough info to be useful
37 $veryold = $tooold * 6; # Ancient default 12 years
39 our $maxconnlist = 3; # remember this many connection time (duration) [start, end] pairs
43 # hash of valid elements and a simple prompt
45 'sort' => '0,Type of User', # A - ak1a, U - User, S - spider cluster, B - BBS
46 addr => '0,Full Address',
47 alias => '0,Real Callsign',
48 annok => '9,Accept Announces?,yesno', # accept his announces?
50 believe => '1,Believable nodes,parray',
51 buddies => '0,Buddies,parray',
54 clientoutput => '0,User OUT Format',
55 clientinput => '0,User IN Format',
56 connlist => '1,Connections,parraydifft',
57 dxok => '9,Accept DX Spots?,yesno', # accept his dx spots?
58 email => '0,E-mail Address,parray',
59 group => '0,Group,parray', # used to create a group of users/nodes for some purpose or other
60 hmsgno => '0,Highest Msgno',
61 homenode => '0,Home Node',
62 isolate => '9,Isolate network,yesno',
63 K => '9,Seen on PC92 K,yesno',
65 lastin => '0,Last Time in,cldatetime',
66 lastoper => '9,Last for/oper,cldatetime',
67 lastping => '1,Last Ping at,ptimelist',
68 lastseen => '0,Last Seen,cldatetime',
69 lat => '0,Latitude,slat',
70 lockout => '9,Locked out?,yesno', # won't let them in at all
71 long => '0,Longitude,slong',
72 maxconnect => '1,Max Connections',
74 node => '0,Last Node',
75 nopings => '9,Ping Obs Count',
76 nothere => '0,Not Here Text',
77 pagelth => '0,Current Pagelth',
78 passphrase => '9,Pass Phrase,yesno',
79 passwd => '9,Password,yesno',
80 pingint => '9,Node Ping interval',
81 priv => '9,Privilege Level',
82 prompt => '0,Required Prompt',
85 rbnseeme => '0,RBN See Me,yesno',
86 registered => '9,Registered?,yesno',
87 startt => '0,Start Time,cldatetime',
88 version => '1,Version',
89 wantann => '0,Req Announce,yesno',
90 wantann_talk => '0,Talklike Anns,yesno',
91 wantbeacon => '0,Want RBN Beacon,yesno',
92 wantbeep => '0,Req Beep,yesno',
93 wantcw => '0,Want RBN CW,yesno',
94 wantdx => '0,Req DX Spots,yesno',
95 wantdxcq => '0,Show CQ Zone,yesno',
96 wantdxitu => '0,Show ITU Zone,yesno',
97 wantecho => '0,Req Echo,yesno',
98 wantemail => '0,Req Msgs as Email,yesno',
99 wantft => '0,Want RBN FT4/8,yesno',
100 wantgtk => '0,Want GTK interface,yesno',
101 wantlogininfo => '0,Login Info Req,yesno',
102 wantpc16 => '9,Want Users from node,yesno',
103 wantpc9x => '0,Want PC9X interface,yesno',
104 wantpsk => '0,Want RBN PSK,yesno',
105 wantrbn => '0,Want RBN spots,yesno',
106 wantroutepc19 => '9,Route PC19,yesno',
107 wantrtty => '0,Want RBN RTTY,yesno',
108 wantsendpc16 => '9,Send PC16,yesno',
109 wanttalk => '0,Req Talk,yesno',
110 wantusstate => '0,Show US State,yesno',
111 wantwcy => '0,Req WCY,yesno',
112 wantwwv => '0,Req WWV,yesno',
113 wantwx => '0,Req WX,yesno',
114 width => '0,Preferred Width',
115 xpert => '0,Expert Status,yesno',
116 wantgrid => '0,Show DX Grid,yesno',
123 my $name = $AUTOLOAD;
125 return if $name =~ /::DESTROY$/;
128 confess "Non-existant field '$AUTOLOAD'" if !$valid{$name};
129 # this clever line of code creates a subroutine which takes over from autoload
130 # from OO Perl - Conway
131 *$AUTOLOAD = sub {@_ > 1 ? $_[0]->{$name} = $_[1] : $_[0]->{$name}};
140 # initialise the system
146 $json = DXJSON->new->canonical(1);
148 $filename = localdata("$fn.v3j");
149 unless (-e $filename || $mode == 2 ) {
150 if (-e localdata("$fn.v3") || -e localdata("$fn.v2")) {
151 LogDbg('DXUser', "New User File version $filename does not exist, running conversion from users.v3 or v2, please wait");
152 system('/spider/perl/convert-users-v3-to-v3j.pl');
158 if (-e $filename || $mode) {
159 $lru = LRU->newbase("DXUser", $lrusize);
161 $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?]";
163 $dbm = tie (%u, 'DB_File', $filename, O_RDONLY, 0666, $DB_BTREE) or confess "can't open user file: $fn ($!) [rebuild it from user_json?]";
168 die "Cannot open $filename ($!)\n" unless $dbm || $mode == 2;
172 # delete files with extreme prejudice
175 # with extreme prejudice
176 unlink "$main::data/users.v3j";
177 unlink "$main::local_data/users.v3j";
181 # periodic processing
185 if ($main::systime > $lasttime + 15) {
187 $lasttime = $main::systime;
197 dbg('DXUser finished') unless $readonly;
204 # new - create a new user
211 my $self = bless {call => $call, 'sort'=>'U'}, $pkg;
219 # $call =~ s/-\d+$//o;
221 # confess "can't create existing call $call in User\n!" if $u{$call};
223 my $self = $pkg->alloc($call);
229 # get - get an existing user - this seems to return a different reference everytime it is
238 # is it in the LRU cache?
239 my $ref = $lru->get($call);
240 if ($ref && ref $ref eq 'DXUser') {
245 unless ($dbm->get($call, $data)) {
246 eval { $ref = decode($data); };
248 if (!UNIVERSAL::isa($ref, 'DXUser')) {
249 dbg("DXUser::get: got strange answer from decode of $call". ref $ref. " ignoring");
252 # we have a reference and it *is* a DXUser
255 LogDbg('err', "DXUser::get decode error on $call '$@'");
257 dbg("DXUser::get: no reference returned from decode of $call $!");
261 $lru->put($call, $ref);
268 # get an existing either from the channel (if there is one) or from the database
270 # It is important to note that if you have done a get (for the channel say) and you
271 # want access or modify that you must use this call (and you must NOT use get's all
272 # over the place willy nilly!)
279 my $dxchan = DXChannel::get($call);
281 my $ref = $dxchan->user;
282 return $ref if $ref && UNIVERSAL::isa($ref, 'DXUser');
284 dbg("DXUser::get_current: got invalid user ref for $call from dxchan $dxchan->{call} ". ref $ref. " ignoring");
290 # get all callsigns in the database
295 return (sort keys %u);
305 confess "Trying to put nothing!" unless $self && ref $self;
306 my $call = $self->{call};
309 delete $self->{annok};
310 delete $self->{dxok};
311 $self->{lastseen} = $main::systime;
312 $lru->put($call, $self);
313 my $ref = $self->encode;
314 $dbm->put($call, $ref);
315 DXChannel::refresh_user($call, $ref);
323 return $json->decode(shift, __PACKAGE__);
329 return $json->encode(shift);
334 # del - delete a user
340 my $call = $self->{call};
346 # close - close down a user
354 # add a record to the connect list
355 $self->{lastin} = $main::systime;
356 my $ref = [$startt || $self->{startt}, $main::systime];
357 push @$ref, $ip if $ip;
358 push @{$self->{connlist}}, $ref;
359 shift @{$self->{connlist}} if @{$self->{connlist}} > $maxconnlist;
373 # return a list of valid elements
386 # add one or more groups
390 my $ref = $self->{group} || [ 'local' ];
391 $self->{group} = $ref if !$self->{group};
392 push @$ref, @_ if @_;
395 # remove one or more groups
399 my $ref = $self->{group} || [ 'local' ];
402 $self->{group} = $ref if !$self->{group};
404 @$ref = map { my $a = $_; return (grep { $_ eq $a } @in) ? () : $a } @$ref;
407 # does this thing contain all the groups listed?
411 my $ref = $self->{group};
414 return 0 if !$ref || @_ == 0;
415 return 1 if @$ref == 0 && @_ == 0;
416 for ($n = 0; $n < @_; ) {
419 $n++ if grep $_ eq $a, @_;
425 # simplified group test just for one group
430 my $ref = $self->{group};
433 return grep $_ eq $s, $ref;
436 # set up a default group (only happens for them's that connect direct)
440 $self->{group} = [ 'local' ];
443 # set up empty buddies (only happens for them's that connect direct)
447 $self->{buddies} = [ ];
451 # return a prompt for a field
456 my ($self, $ele) = @_;
460 # some variable accessors
464 @_ ? $self->{'sort'} = shift : $self->{'sort'} ;
469 # want is default = 1
476 $self->{$s} = $val if defined $val;
477 return exists $self->{$s} ? $self->{$s} : 1;
480 # wantnot is default = 0
487 $self->{$s} = $val if defined $val;
488 return exists $self->{$s} ? $self->{$s} : 0;
493 return _want('beep', @_);
498 return _want('ann', @_);
503 return _want('wwv', @_);
508 return _want('wcy', @_);
513 return _want('echo', @_);
518 return _want('wx', @_);
523 return _want('dx', @_);
528 return _want('talk', @_);
533 return _wantnot('grid', @_);
538 return _want('email', @_);
543 return _want('ann_talk', @_);
548 return _want('pc16', @_);
553 return _want('sendpc16', @_);
558 return _want('routepc16', @_);
563 return _want('usstate', @_);
568 return _wantnot('dxcq', @_);
573 return _wantnot('dxitu', @_);
578 return _want('gtk', @_);
583 return _want('pc9x', @_);
590 $self->{wantlogininfo} = $val if defined $val;
591 return $self->{wantlogininfo};
597 return $self->{sort} =~ /^[ACRSX]$/;
603 return grep $_ eq 'local_node', @{$self->{group}};
609 return $self->{sort} =~ /^[UW]$/;
615 return $self->{sort} eq 'W';
621 return $self->{sort} eq 'B';
627 return $self->{sort} eq 'S';
633 return $self->{sort} eq 'C';
639 return $self->{sort} eq 'X';
645 return $self->{sort} eq 'R';
651 return $self->{sort} eq 'A';
657 return $self->{sort} eq 'N'
663 delete $self->{passwd};
669 delete $self->{passphrase};
676 $self->{believe} ||= [];
677 push @{$self->{believe}}, $call unless grep $_ eq $call, @{$self->{believe}};
684 if (exists $self->{believe}) {
685 $self->{believe} = [grep {$_ ne $call} @{$self->{believe}}];
686 delete $self->{believe} unless @{$self->{believe}};
693 return exists $self->{believe} ? @{$self->{believe}} : ();
700 $self->{lastping} ||= {};
701 $self->{lastping} = {} unless ref $self->{lastping};
702 my $b = $self->{lastping};
703 $b->{$call} = shift if @_;
709 # export the database to an ascii file
714 my $name = shift || 'user_json';
716 my $fn = $name ne 'user_json' ? $name : "$main::local_data/$name"; # force use of local
719 copy $fn, "$fn.keep" unless -e "$fn.keep";
720 copy "$fn.ooooo", "$fn.backstop" unless -e "$fn,backstop";
722 move "$fn.oooo", "$fn.ooooo" if -e "$fn.oooo";
723 move "$fn.ooo", "$fn.oooo" if -e "$fn.ooo";
724 move "$fn.oo", "$fn.ooo" if -e "$fn.oo";
725 move "$fn.o", "$fn.oo" if -e "$fn.o";
726 move "$fn", "$fn.o" if -e "$fn";
729 my $ta = [gettimeofday];
742 my $fh = new IO::File ">$fn" or return "cannot open $fn ($!)";
747 my $t = scalar localtime;
748 print $fh export_preamble();
751 for ($action = R_FIRST; !$dbm->seq($key, $val, $action); $action = R_NEXT) {
752 if (!is_callsign($key) || $key =~ /^0/) {
755 $eval =~ s/([\%\x00-\x1f\x7f-\xff])/sprintf("%%%02X", ord($1))/eg;
756 $ekey =~ s/([\%\x00-\x1f\x7f-\xff])/sprintf("%%%02X", ord($1))/eg;
757 LogDbg('DXCommand', "Export Error1: invalid call '$key' => '$val'");
764 eval {$ref = decode($val); };
766 my $t = $ref->{lastseen} if exists $ref->{lastseen};
767 $t ||= $ref->{lastin} if exists $ref->{lastin};
768 $t ||= $ref->{lastoper} if exists $ref->{lastoper};
772 if (!$ref->{priv} && $main::systime > $t + $tooold) {
773 unless (($ref->{lat} && $ref->{long}) || $ref->{qth} || $ref->{name} || $ref->{qra}) {
774 LogDbg('DXCommand', sprintf("$ref->{call} deleted, empty and too Old at %s", difft($t, ' ')));
781 if ($main::systime > $t + $veryold) {
782 LogDbg('DXCommand', sprintf("$ref->{call} deleted, POSITIVELY ANCIENT at %s", difft($t, ' ')));
788 if (exists $ref->{lockout} && $ref->{lockout} == 1 && exists $ref->{priv} && $ref->{priv} == 1) {
789 LogDbg('DXCommand', "$ref->{call} depriv'd and unlocked");
790 $ref->{lockout} = $ref->{priv} = 0;
794 if ($ref->is_node && $main::systime > $t + $veryold) {
795 LogDbg('DXCommand', sprintf("NODE $ref->{call} deleted (%s) old", difft($t, ' ')));
802 my $normcall = normalise_call($key);
803 if ($normcall ne $key) {
804 # if the normalised call does not exist, create it from the duff call.
805 my $nref = DXUser::get_current($normcall);
807 $ref->{call} = $normcall;
809 LogDbg('DXCommand', "DXProt: spurious call $key normalises to $normcall renaming $key -> $normcall");
812 LogDbg('DXCommand', "DXProt: spurious call $key (should be $normcall), removing");
820 LogDbg('DXCommand', "Export Error3: '$key'\t" . carp($val) ."\n$@");
826 # only store users that are reasonably active or have useful information
827 print $fh "$key\t" . encode($ref) . "\n";
833 while (my ($k, $v) = each %del) {
834 eval {$dbm->del($k)};
835 LogDbg('DXCommand', "Error deleting key: $k value: $v error: $@") if $@;
838 my $diff = _diffms($ta);
839 my $s = qq{Exported users to $fn - $count Users, $del Deleted ($old empty \& too old, $ancient ancient, $nodes nodes, $spurious spurious), $renamed renamed, $unlocked Unlocked, $err Errors in $diff mS ('sh/log Export' for details)};
840 LogDbg('command', $s);
846 return q{#!/usr/bin/perl
848 # The exported userfile for a DXSpider System
850 # Input file: $filename
856 # search local then perl directories
860 # root of directory tree for this system
862 $root = $ENV{'DXSPIDER_ROOT'} if $ENV{'DXSPIDER_ROOT'};
864 unshift @INC, "$root/perl"; # this IS the right way round!
865 unshift @INC, "$root/local";
867 # try to detect a lockfile (this isn't atomic but
869 $lockfn = "$root/local_data/cluster.lck"; # lock file name
871 open(CLLOCK, "$lockfn") or die "Can't open Lockfile ($lockfn) $!";
874 die "Lockfile ($lockfn) and process $pid exists - cluster must be stopped first\n" if kill 0, $pid;
884 use Time::HiRes qw(gettimeofday tv_interval);
887 our $json = JSON->new->canonical(1);
889 my $ta = [gettimeofday];
890 our $filename = "$main::local_data/users.v3j";
891 my $exists = -e $filename ? "OVERWRITING" : "CREATING";
892 print "perl user_json $exists $filename\n";
903 my $ref = decode($f[1]);
908 print "# Error: $f[0]\t$f[1]\n";
912 DXUser::sync(); DXUser::finish();
913 my $diff = _diffms($ta);
914 print "There are $count user records and $err errors in $diff mS\n";
925 my $name = shift || 'recover_json';
927 my $fn = $name ne 'recover_json' ? $name : "$main::local_data/$name"; # force use of local
930 move "$fn.oooo", "$fn.ooooo" if -e "$fn.oooo";
931 move "$fn.ooo", "$fn.oooo" if -e "$fn.ooo";
932 move "$fn.oo", "$fn.ooo" if -e "$fn.oo";
933 move "$fn.o", "$fn.oo" if -e "$fn.o";
934 move "$fn", "$fn.o" if -e "$fn";
936 my $ta = [gettimeofday];
941 my $strings = "strings $filename";
942 my $ifh = new IO::File "$strings |" or return "cannot open input $filename ($!)";
943 my $fh = new IO::File ">$fn" or return "cannot open output $fn ($!)";
948 my $t = scalar localtime;
949 print $fh export_preamble();
955 while (defined ($l = $ifh->getline)) {
956 next unless $l =~ /^{"call":"[-\d\w\/]+"/;
963 eval{ $v = decode($data); };
968 next if $data eq $last;
969 print $fh "$v->{call}\t$l\n";
980 my $diff = _diffms($ta);
981 my $s = qq{Recovered users to $fn - $count Users, $errs errors $total possible records read in $diff mS ('sh/log recover' for details)};
982 LogDbg('command', $s);
989 print "DXUser Ended\n" unless $readonly;