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 connlist => '1,Connections,parraydifft',
55 dxok => '9,Accept DX Spots?,yesno', # accept his dx spots?
56 email => '0,E-mail Address,parray',
57 group => '0,Group,parray', # used to create a group of users/nodes for some purpose or other
58 hmsgno => '0,Highest Msgno',
59 homenode => '0,Home Node',
60 isolate => '9,Isolate network,yesno',
61 K => '9,Seen on PC92 K,yesno',
63 lastin => '0,Last Time in,cldatetime',
64 lastoper => '9,Last for/oper,cldatetime',
65 lastping => '1,Last Ping at,ptimelist',
66 lastseen => '0,Last Seen,cldatetime',
67 lat => '0,Latitude,slat',
68 lockout => '9,Locked out?,yesno', # won't let them in at all
69 long => '0,Longitude,slong',
70 maxconnect => '1,Max Connections',
72 node => '0,Last Node',
73 nopings => '9,Ping Obs Count',
74 nothere => '0,Not Here Text',
75 pagelth => '0,Current Pagelth',
76 passphrase => '9,Pass Phrase,yesno',
77 passwd => '9,Password,yesno',
78 pingint => '9,Node Ping interval',
79 priv => '9,Privilege Level',
80 prompt => '0,Required Prompt',
83 rbnseeme => '0,RBN See Me',
84 registered => '9,Registered?,yesno',
85 startt => '0,Start Time,cldatetime',
86 version => '1,Version',
87 wantann => '0,Req Announce,yesno',
88 wantann_talk => '0,Talklike Anns,yesno',
89 wantbeacon => '0,Want RBN Beacon,yesno',
90 wantbeep => '0,Req Beep,yesno',
91 wantcw => '0,Want RBN CW,yesno',
92 wantdx => '0,Req DX Spots,yesno',
93 wantdxcq => '0,Show CQ Zone,yesno',
94 wantdxitu => '0,Show ITU Zone,yesno',
95 wantecho => '0,Req Echo,yesno',
96 wantemail => '0,Req Msgs as Email,yesno',
97 wantft => '0,Want RBN FT4/8,yesno',
98 wantgtk => '0,Want GTK interface,yesno',
99 wantlogininfo => '0,Login Info Req,yesno',
100 wantpc16 => '9,Want Users from node,yesno',
101 wantpc9x => '0,Want PC9X interface,yesno',
102 wantpsk => '0,Want RBN PSK,yesno',
103 wantrbn => '0,Want RBN spots,yesno',
104 wantroutepc19 => '9,Route PC19,yesno',
105 wantrtty => '0,Want RBN RTTY,yesno',
106 wantsendpc16 => '9,Send PC16,yesno',
107 wanttalk => '0,Req Talk,yesno',
108 wantusstate => '0,Show US State,yesno',
109 wantwcy => '0,Req WCY,yesno',
110 wantwwv => '0,Req WWV,yesno',
111 wantwx => '0,Req WX,yesno',
112 width => '0,Preferred Width',
113 xpert => '0,Expert Status,yesno',
114 wantgrid => '0,Show DX Grid,yesno',
121 my $name = $AUTOLOAD;
123 return if $name =~ /::DESTROY$/;
126 confess "Non-existant field '$AUTOLOAD'" if !$valid{$name};
127 # this clever line of code creates a subroutine which takes over from autoload
128 # from OO Perl - Conway
129 *$AUTOLOAD = sub {@_ > 1 ? $_[0]->{$name} = $_[1] : $_[0]->{$name}};
136 # initialise the system
142 $json = DXJSON->new->canonical(1);
144 $filename = localdata("$fn.v3j");
145 unless (-e $filename || $mode == 2 ) {
146 if (-e localdata("$fn.v3") || -e localdata("$fn.v2")) {
147 LogDbg('DXUser', "New User File version $filename does not exist, running conversion from users.v3 or v2, please wait");
148 system('/spider/perl/convert-users-v3-to-v3j.pl');
154 if (-e $filename || $mode) {
155 $lru = LRU->newbase("DXUser", $lrusize);
157 $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?]";
159 $dbm = tie (%u, 'DB_File', $filename, O_RDONLY, 0666, $DB_BTREE) or confess "can't open user file: $fn ($!) [rebuild it from user_json?]";
162 die "Cannot open $filename ($!)\n" unless $dbm || $mode == 2;
166 # delete files with extreme prejudice
169 # with extreme prejudice
170 unlink "$main::data/users.v3j";
171 unlink "$main::local_data/users.v3j";
175 # periodic processing
179 if ($main::systime > $lasttime + 15) {
181 $lasttime = $main::systime;
197 # new - create a new user
204 my $self = bless {call => $call, 'sort'=>'U'}, $pkg;
212 # $call =~ s/-\d+$//o;
214 # confess "can't create existing call $call in User\n!" if $u{$call};
216 my $self = $pkg->alloc($call);
222 # get - get an existing user - this seems to return a different reference everytime it is
231 # is it in the LRU cache?
232 my $ref = $lru->get($call);
233 if ($ref && ref $ref eq 'DXUser') {
238 unless ($dbm->get($call, $data)) {
239 eval { $ref = decode($data); };
241 if (!UNIVERSAL::isa($ref, 'DXUser')) {
242 dbg("DXUser::get: got strange answer from decode of $call". ref $ref. " ignoring");
245 # we have a reference and it *is* a DXUser
248 LogDbg('err', "DXUser::get decode error on $call '$@'");
250 dbg("DXUser::get: no reference returned from decode of $call $!");
254 $lru->put($call, $ref);
261 # get an existing either from the channel (if there is one) or from the database
263 # It is important to note that if you have done a get (for the channel say) and you
264 # want access or modify that you must use this call (and you must NOT use get's all
265 # over the place willy nilly!)
272 my $dxchan = DXChannel::get($call);
274 my $ref = $dxchan->user;
275 return $ref if $ref && UNIVERSAL::isa($ref, 'DXUser');
277 dbg("DXUser::get_current: got invalid user ref for $call from dxchan $dxchan->{call} ". ref $ref. " ignoring");
283 # get all callsigns in the database
288 return (sort keys %u);
298 confess "Trying to put nothing!" unless $self && ref $self;
299 my $call = $self->{call};
302 delete $self->{annok};
303 delete $self->{dxok};
304 $self->{lastseen} = $main::systime;
305 $lru->put($call, $self);
306 my $ref = $self->encode;
307 $dbm->put($call, $ref);
308 DXChannel::refresh_user($call, $ref);
316 return $json->decode(shift, __PACKAGE__);
322 return $json->encode(shift);
327 # del - delete a user
333 my $call = $self->{call};
339 # close - close down a user
347 # add a record to the connect list
348 $self->{lastin} = $main::systime;
349 my $ref = [$startt || $self->{startt}, $main::systime];
350 push @$ref, $ip if $ip;
351 push @{$self->{connlist}}, $ref;
352 shift @{$self->{connlist}} if @{$self->{connlist}} > $maxconnlist;
366 # return a list of valid elements
379 # add one or more groups
383 my $ref = $self->{group} || [ 'local' ];
384 $self->{group} = $ref if !$self->{group};
385 push @$ref, @_ if @_;
388 # remove one or more groups
392 my $ref = $self->{group} || [ 'local' ];
395 $self->{group} = $ref if !$self->{group};
397 @$ref = map { my $a = $_; return (grep { $_ eq $a } @in) ? () : $a } @$ref;
400 # does this thing contain all the groups listed?
404 my $ref = $self->{group};
407 return 0 if !$ref || @_ == 0;
408 return 1 if @$ref == 0 && @_ == 0;
409 for ($n = 0; $n < @_; ) {
412 $n++ if grep $_ eq $a, @_;
418 # simplified group test just for one group
423 my $ref = $self->{group};
426 return grep $_ eq $s, $ref;
429 # set up a default group (only happens for them's that connect direct)
433 $self->{group} = [ 'local' ];
436 # set up empty buddies (only happens for them's that connect direct)
440 $self->{buddies} = [ ];
444 # return a prompt for a field
449 my ($self, $ele) = @_;
453 # some variable accessors
457 @_ ? $self->{'sort'} = shift : $self->{'sort'} ;
462 # want is default = 1
469 $self->{$s} = $val if defined $val;
470 return exists $self->{$s} ? $self->{$s} : 1;
473 # wantnot is default = 0
480 $self->{$s} = $val if defined $val;
481 return exists $self->{$s} ? $self->{$s} : 0;
486 return _want('beep', @_);
491 return _want('ann', @_);
496 return _want('wwv', @_);
501 return _want('wcy', @_);
506 return _want('echo', @_);
511 return _want('wx', @_);
516 return _want('dx', @_);
521 return _want('talk', @_);
526 return _wantnot('grid', @_);
531 return _want('email', @_);
536 return _want('ann_talk', @_);
541 return _want('pc16', @_);
546 return _want('sendpc16', @_);
551 return _want('routepc16', @_);
556 return _want('usstate', @_);
561 return _wantnot('dxcq', @_);
566 return _wantnot('dxitu', @_);
571 return _want('gtk', @_);
576 return _want('pc9x', @_);
583 $self->{wantlogininfo} = $val if defined $val;
584 return $self->{wantlogininfo};
590 return $self->{sort} =~ /^[ACRSX]$/;
596 return grep $_ eq 'local_node', @{$self->{group}};
602 return $self->{sort} =~ /^[UW]$/;
608 return $self->{sort} eq 'W';
614 return $self->{sort} eq 'B';
620 return $self->{sort} eq 'S';
626 return $self->{sort} eq 'C';
632 return $self->{sort} eq 'X';
638 return $self->{sort} eq 'R';
644 return $self->{sort} eq 'A';
650 return $self->{sort} eq 'N'
656 delete $self->{passwd};
662 delete $self->{passphrase};
669 $self->{believe} ||= [];
670 push @{$self->{believe}}, $call unless grep $_ eq $call, @{$self->{believe}};
677 if (exists $self->{believe}) {
678 $self->{believe} = [grep {$_ ne $call} @{$self->{believe}}];
679 delete $self->{believe} unless @{$self->{believe}};
686 return exists $self->{believe} ? @{$self->{believe}} : ();
693 $self->{lastping} ||= {};
694 $self->{lastping} = {} unless ref $self->{lastping};
695 my $b = $self->{lastping};
696 $b->{$call} = shift if @_;
702 # export the database to an ascii file
707 my $name = shift || 'user_json';
709 my $fn = $name ne 'user_json' ? $name : "$main::local_data/$name"; # force use of local
712 copy $fn, "$fn.keep" unless -e "$fn.keep";
713 copy "$fn.ooooo", "$fn.backstop" unless -e "$fn,backstop";
715 move "$fn.oooo", "$fn.ooooo" if -e "$fn.oooo";
716 move "$fn.ooo", "$fn.oooo" if -e "$fn.ooo";
717 move "$fn.oo", "$fn.ooo" if -e "$fn.oo";
718 move "$fn.o", "$fn.oo" if -e "$fn.o";
719 move "$fn", "$fn.o" if -e "$fn";
722 my $ta = [gettimeofday];
735 my $fh = new IO::File ">$fn" or return "cannot open $fn ($!)";
740 my $t = scalar localtime;
741 print $fh export_preamble();
744 for ($action = R_FIRST; !$dbm->seq($key, $val, $action); $action = R_NEXT) {
745 if (!is_callsign($key) || $key =~ /^0/) {
748 $eval =~ s/([\%\x00-\x1f\x7f-\xff])/sprintf("%%%02X", ord($1))/eg;
749 $ekey =~ s/([\%\x00-\x1f\x7f-\xff])/sprintf("%%%02X", ord($1))/eg;
750 LogDbg('DXCommand', "Export Error1: invalid call '$key' => '$val'");
757 eval {$ref = decode($val); };
759 my $t = $ref->{lastseen} if exists $ref->{lastseen};
760 $t ||= $ref->{lastin} if exists $ref->{lastin};
761 $t ||= $ref->{lastoper} if exists $ref->{lastoper};
765 if (!$ref->{priv} && $main::systime > $t + $tooold) {
766 unless (($ref->{lat} && $ref->{long}) || $ref->{qth} || $ref->{name} || $ref->{qra}) {
767 LogDbg('DXCommand', sprintf("$ref->{call} deleted, empty and too Old at %s", difft($t, ' ')));
774 if ($main::systime > $t + $veryold) {
775 LogDbg('DXCommand', sprintf("$ref->{call} deleted, POSITIVELY ANCIENT at %s", difft($t, ' ')));
781 if (exists $ref->{lockout} && $ref->{lockout} == 1 && exists $ref->{priv} && $ref->{priv} == 1) {
782 LogDbg('DXCommand', "$ref->{call} depriv'd and unlocked");
783 $ref->{lockout} = $ref->{priv} = 0;
787 if ($ref->is_node && $main::systime > $t + $veryold) {
788 LogDbg('DXCommand', sprintf("NODE $ref->{call} deleted (%s) old", difft($t, ' ')));
795 my $normcall = normalise_call($key);
796 if ($normcall ne $key) {
797 # if the normalised call does not exist, create it from the duff call.
798 my $nref = DXUser::get_current($normcall);
800 $ref->{call} = $normcall;
802 LogDbg('DXCommand', "DXProt: spurious call $key normalises to $normcall renaming $key -> $normcall");
805 LogDbg('DXCommand', "DXProt: spurious call $key (should be $normcall), removing");
813 LogDbg('DXCommand', "Export Error3: '$key'\t" . carp($val) ."\n$@");
819 # only store users that are reasonably active or have useful information
820 print $fh "$key\t" . encode($ref) . "\n";
826 while (my ($k, $v) = each %del) {
827 eval {$dbm->del($k)};
828 LogDbg('DXCommand', "Error deleting key: $k value: $v error: $@") if $@;
831 my $diff = _diffms($ta);
832 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)};
833 LogDbg('command', $s);
839 return q{#!/usr/bin/perl
841 # The exported userfile for a DXSpider System
843 # Input file: $filename
849 # search local then perl directories
853 # root of directory tree for this system
855 $root = $ENV{'DXSPIDER_ROOT'} if $ENV{'DXSPIDER_ROOT'};
857 unshift @INC, "$root/perl"; # this IS the right way round!
858 unshift @INC, "$root/local";
860 # try to detect a lockfile (this isn't atomic but
862 $lockfn = "$root/local_data/cluster.lck"; # lock file name
864 open(CLLOCK, "$lockfn") or die "Can't open Lockfile ($lockfn) $!";
867 die "Lockfile ($lockfn) and process $pid exists - cluster must be stopped first\n" if kill 0, $pid;
877 use Time::HiRes qw(gettimeofday tv_interval);
880 our $json = JSON->new->canonical(1);
882 my $ta = [gettimeofday];
883 our $filename = "$main::local_data/users.v3j";
884 my $exists = -e $filename ? "OVERWRITING" : "CREATING";
885 print "perl user_json $exists $filename\n";
896 my $ref = decode($f[1]);
901 print "# Error: $f[0]\t$f[1]\n";
905 DXUser::sync(); DXUser::finish();
906 my $diff = _diffms($ta);
907 print "There are $count user records and $err errors in $diff mS\n";
918 my $name = shift || 'recover_json';
920 my $fn = $name ne 'recover_json' ? $name : "$main::local_data/$name"; # force use of local
923 move "$fn.oooo", "$fn.ooooo" if -e "$fn.oooo";
924 move "$fn.ooo", "$fn.oooo" if -e "$fn.ooo";
925 move "$fn.oo", "$fn.ooo" if -e "$fn.oo";
926 move "$fn.o", "$fn.oo" if -e "$fn.o";
927 move "$fn", "$fn.o" if -e "$fn";
929 my $ta = [gettimeofday];
934 my $strings = "strings $filename";
935 my $ifh = new IO::File "$strings |" or return "cannot open input $filename ($!)";
936 my $fh = new IO::File ">$fn" or return "cannot open output $fn ($!)";
941 my $t = scalar localtime;
942 print $fh export_preamble();
948 while (defined ($l = $ifh->getline)) {
949 next unless $l =~ /^{"call":"[-\d\w\/]+"/;
956 eval{ $v = decode($data); };
961 next if $data eq $last;
962 print $fh "$v->{call}\t$l\n";
973 my $diff = _diffms($ta);
974 my $s = qq{Recovered users to $fn - $count Users, $errs errors $total possible records read in $diff mS ('sh/log recover' for details)};
975 LogDbg('command', $s);