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 user_interval => '0,Prompt IdleTime',
89 version => '1,Version',
90 wantann => '0,Req Announce,yesno',
91 wantann_talk => '0,Talklike Anns,yesno',
92 wantbeacon => '0,Want RBN Beacon,yesno',
93 wantbeep => '0,Req Beep,yesno',
94 wantcw => '0,Want RBN CW,yesno',
95 wantdx => '0,Req DX Spots,yesno',
96 wantdxcq => '0,Show CQ Zone,yesno',
97 wantdxitu => '0,Show ITU Zone,yesno',
98 wantecho => '0,Req Echo,yesno',
99 wantemail => '0,Req Msgs as Email,yesno',
100 wantft => '0,Want RBN FT4/8,yesno',
101 wantgtk => '0,Want GTK interface,yesno',
102 wantlogininfo => '0,Login Info Req,yesno',
103 wantpc16 => '9,Want Users from node,yesno',
104 wantpc9x => '0,Want PC9X interface,yesno',
105 wantpsk => '0,Want RBN PSK,yesno',
106 wantrbn => '0,Want RBN spots,yesno',
107 wantroutepc19 => '9,Route PC19,yesno',
108 wantrtty => '0,Want RBN RTTY,yesno',
109 wantsendpc16 => '9,Send PC16,yesno',
110 wanttalk => '0,Req Talk,yesno',
111 wantusstate => '0,Show US State,yesno',
112 wantwcy => '0,Req WCY,yesno',
113 wantwwv => '0,Req WWV,yesno',
114 wantwx => '0,Req WX,yesno',
115 width => '0,Preferred Width',
116 xpert => '0,Expert Status,yesno',
117 wantgrid => '0,Show DX Grid,yesno',
124 my $name = $AUTOLOAD;
126 return if $name =~ /::DESTROY$/;
129 confess "Non-existant field '$AUTOLOAD'" if !$valid{$name};
130 # this clever line of code creates a subroutine which takes over from autoload
131 # from OO Perl - Conway
132 *$AUTOLOAD = sub {@_ > 1 ? $_[0]->{$name} = $_[1] : $_[0]->{$name}};
141 # initialise the system
147 $json = DXJSON->new->canonical(1);
149 $filename = localdata("$fn.v3j");
150 unless (-e $filename || $mode == 2 ) {
151 if (-e localdata("$fn.v3") || -e localdata("$fn.v2")) {
152 LogDbg('DXUser', "New User File version $filename does not exist, running conversion from users.v3 or v2, please wait");
153 system('/spider/perl/convert-users-v3-to-v3j.pl');
159 if (-e $filename || $mode) {
160 $lru = LRU->newbase("DXUser", $lrusize);
162 $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?]";
164 $dbm = tie (%u, 'DB_File', $filename, O_RDONLY, 0666, $DB_BTREE) or confess "can't open user file: $fn ($!) [rebuild it from user_json?]";
169 die "Cannot open $filename ($!)\n" unless $dbm || $mode == 2;
173 # delete files with extreme prejudice
176 # with extreme prejudice
177 unlink "$main::data/users.v3j";
178 unlink "$main::local_data/users.v3j";
182 # periodic processing
186 if ($main::systime > $lasttime + 15) {
188 $lasttime = $main::systime;
198 dbg('DXUser finished') unless $readonly;
205 # new - create a new user
212 my $self = bless {call => $call, 'sort'=>'U'}, $pkg;
220 # $call =~ s/-\d+$//o;
222 # confess "can't create existing call $call in User\n!" if $u{$call};
224 my $self = $pkg->alloc($call);
230 # get - get an existing user - this seems to return a different reference everytime it is
239 # is it in the LRU cache?
240 my $ref = $lru->get($call);
241 if ($ref && ref $ref eq 'DXUser') {
246 unless ($dbm->get($call, $data)) {
247 eval { $ref = decode($data); };
249 if (!UNIVERSAL::isa($ref, 'DXUser')) {
250 dbg("DXUser::get: got strange answer from decode of $call". ref $ref. " ignoring");
253 # we have a reference and it *is* a DXUser
256 LogDbg('err', "DXUser::get decode error on $call '$@'");
258 dbg("DXUser::get: no reference returned from decode of $call $!");
262 $lru->put($call, $ref);
269 # get an existing either from the channel (if there is one) or from the database
271 # It is important to note that if you have done a get (for the channel say) and you
272 # want access or modify that you must use this call (and you must NOT use get's all
273 # over the place willy nilly!)
280 my $dxchan = DXChannel::get($call);
282 my $ref = $dxchan->user;
283 return $ref if $ref && UNIVERSAL::isa($ref, 'DXUser');
285 dbg("DXUser::get_current: got invalid user ref for $call from dxchan $dxchan->{call} ". ref $ref. " ignoring");
291 # get all callsigns in the database
296 return (sort keys %u);
306 confess "Trying to put nothing!" unless $self && ref $self;
307 my $call = $self->{call};
310 delete $self->{annok};
311 delete $self->{dxok};
312 $self->{lastseen} = $main::systime;
313 $lru->put($call, $self);
314 my $ref = $self->encode;
315 $dbm->put($call, $ref);
316 DXChannel::refresh_user($call, $ref);
324 return $json->decode(shift, __PACKAGE__);
330 return $json->encode(shift);
335 # del - delete a user
341 my $call = $self->{call};
347 # close - close down a user
355 # add a record to the connect list
356 $self->{lastin} = $main::systime;
357 my $ref = [$self->{startt} || $startt, $main::systime];
358 push @$ref, $ip if $ip;
359 push @{$self->{connlist}}, $ref;
360 shift @{$self->{connlist}} if @{$self->{connlist}} > $maxconnlist;
374 # return a list of valid elements
387 # add one or more groups
391 my $ref = $self->{group} || [ 'local' ];
392 $self->{group} = $ref if !$self->{group};
393 push @$ref, @_ if @_;
396 # remove one or more groups
400 my $ref = $self->{group} || [ 'local' ];
403 $self->{group} = $ref if !$self->{group};
405 @$ref = map { my $a = $_; return (grep { $_ eq $a } @in) ? () : $a } @$ref;
408 # does this thing contain all the groups listed?
412 my $ref = $self->{group};
415 return 0 if !$ref || @_ == 0;
416 return 1 if @$ref == 0 && @_ == 0;
417 for ($n = 0; $n < @_; ) {
420 $n++ if grep $_ eq $a, @_;
426 # simplified group test just for one group
431 my $ref = $self->{group};
434 return grep $_ eq $s, $ref;
437 # set up a default group (only happens for them's that connect direct)
441 $self->{group} = [ 'local' ];
444 # set up empty buddies (only happens for them's that connect direct)
448 $self->{buddies} = [ ];
452 # return a prompt for a field
457 my ($self, $ele) = @_;
461 # some variable accessors
465 @_ ? $self->{'sort'} = shift : $self->{'sort'} ;
470 # want is default = 1
477 $self->{$s} = $val if defined $val;
478 return exists $self->{$s} ? $self->{$s} : 1;
481 # wantnot is default = 0
488 $self->{$s} = $val if defined $val;
489 return exists $self->{$s} ? $self->{$s} : 0;
494 return _want('beep', @_);
499 return _want('ann', @_);
504 return _want('wwv', @_);
509 return _want('wcy', @_);
514 return _want('echo', @_);
519 return _want('wx', @_);
524 return _want('dx', @_);
529 return _want('talk', @_);
534 return _wantnot('grid', @_);
539 return _want('email', @_);
544 return _want('ann_talk', @_);
549 return _want('pc16', @_);
554 return _want('sendpc16', @_);
559 return _want('routepc16', @_);
564 return _want('usstate', @_);
569 return _wantnot('dxcq', @_);
574 return _wantnot('dxitu', @_);
579 return _want('gtk', @_);
584 return _want('pc9x', @_);
591 $self->{wantlogininfo} = $val if defined $val;
592 return $self->{wantlogininfo};
598 return $self->{sort} =~ /^[ACRSX]$/;
604 return grep $_ eq 'local_node', @{$self->{group}};
610 return $self->{sort} =~ /^[UW]$/;
616 return $self->{sort} eq 'W';
622 return $self->{sort} eq 'B';
628 return $self->{sort} eq 'S';
634 return $self->{sort} eq 'C';
640 return $self->{sort} eq 'X';
646 return $self->{sort} eq 'R';
652 return $self->{sort} eq 'A';
658 return $self->{sort} eq 'N'
664 delete $self->{passwd};
670 delete $self->{passphrase};
677 $self->{believe} ||= [];
678 push @{$self->{believe}}, $call unless grep $_ eq $call, @{$self->{believe}};
685 if (exists $self->{believe}) {
686 $self->{believe} = [grep {$_ ne $call} @{$self->{believe}}];
687 delete $self->{believe} unless @{$self->{believe}};
694 return exists $self->{believe} ? @{$self->{believe}} : ();
701 $self->{lastping} ||= {};
702 $self->{lastping} = {} unless ref $self->{lastping};
703 my $b = $self->{lastping};
704 $b->{$call} = shift if @_;
710 # export the database to an ascii file
715 my $name = shift || 'user_json';
717 my $fn = $name ne 'user_json' ? $name : "$main::local_data/$name"; # force use of local
720 copy $fn, "$fn.keep" unless -e "$fn.keep";
721 copy "$fn.ooooo", "$fn.backstop" unless -e "$fn,backstop";
723 move "$fn.oooo", "$fn.ooooo" if -e "$fn.oooo";
724 move "$fn.ooo", "$fn.oooo" if -e "$fn.ooo";
725 move "$fn.oo", "$fn.ooo" if -e "$fn.oo";
726 move "$fn.o", "$fn.oo" if -e "$fn.o";
727 move "$fn", "$fn.o" if -e "$fn";
730 my $ta = [gettimeofday];
743 my $fh = new IO::File ">$fn" or return "cannot open $fn ($!)";
748 my $t = scalar localtime;
749 print $fh export_preamble();
752 for ($action = R_FIRST; !$dbm->seq($key, $val, $action); $action = R_NEXT) {
753 if (!is_callsign($key) || $key =~ /^0/) {
756 $eval =~ s/([\%\x00-\x1f\x7f-\xff])/sprintf("%%%02X", ord($1))/eg;
757 $ekey =~ s/([\%\x00-\x1f\x7f-\xff])/sprintf("%%%02X", ord($1))/eg;
758 LogDbg('DXCommand', "Export Error1: invalid call '$key' => '$val'");
765 eval {$ref = decode($val); };
767 my $t = $ref->{lastseen} if exists $ref->{lastseen};
768 $t ||= $ref->{lastin} if exists $ref->{lastin};
769 $t ||= $ref->{lastoper} if exists $ref->{lastoper};
773 if (!$ref->{priv} && $main::systime > $t + $tooold) {
774 unless (($ref->{lat} && $ref->{long}) || $ref->{qth} || $ref->{name} || $ref->{qra}) {
775 LogDbg('DXCommand', sprintf("$ref->{call} deleted, empty and too Old at %s", difft($t, ' ')));
782 if ($main::systime > $t + $veryold) {
783 LogDbg('DXCommand', sprintf("$ref->{call} deleted, POSITIVELY ANCIENT at %s", difft($t, ' ')));
789 if (exists $ref->{lockout} && $ref->{lockout} == 1 && exists $ref->{priv} && $ref->{priv} == 1) {
790 LogDbg('DXCommand', "$ref->{call} depriv'd and unlocked");
791 $ref->{lockout} = $ref->{priv} = 0;
795 if ($ref->is_node && $main::systime > $t + $veryold) {
796 LogDbg('DXCommand', sprintf("NODE $ref->{call} deleted (%s) old", difft($t, ' ')));
803 my $normcall = normalise_call($key);
804 if ($normcall ne $key) {
805 # if the normalised call does not exist, create it from the duff call.
806 my $nref = DXUser::get_current($normcall);
808 $ref->{call} = $normcall;
810 LogDbg('DXCommand', "DXProt: spurious call $key normalises to $normcall renaming $key -> $normcall");
813 LogDbg('DXCommand', "DXProt: spurious call $key (should be $normcall), removing");
821 LogDbg('DXCommand', "Export Error3: '$key'\t" . carp($val) ."\n$@");
827 # only store users that are reasonably active or have useful information
828 print $fh "$key\t" . encode($ref) . "\n";
834 while (my ($k, $v) = each %del) {
835 eval {$dbm->del($k)};
836 LogDbg('DXCommand', "Error deleting key: $k value: $v error: $@") if $@;
839 my $diff = _diffms($ta);
840 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)};
841 LogDbg('command', $s);
847 return q{#!/usr/bin/perl
849 # The exported userfile for a DXSpider System
851 # Input file: $filename
857 # search local then perl directories
861 # root of directory tree for this system
863 $root = $ENV{'DXSPIDER_ROOT'} if $ENV{'DXSPIDER_ROOT'};
865 unshift @INC, "$root/perl"; # this IS the right way round!
866 unshift @INC, "$root/local";
868 # try to detect a lockfile (this isn't atomic but
870 $lockfn = "$root/local_data/cluster.lck"; # lock file name
872 open(CLLOCK, "$lockfn") or die "Can't open Lockfile ($lockfn) $!";
875 die "Lockfile ($lockfn) and process $pid exists - cluster must be stopped first\n" if kill 0, $pid;
885 use Time::HiRes qw(gettimeofday tv_interval);
888 our $json = JSON->new->canonical(1);
890 my $ta = [gettimeofday];
891 our $filename = "$main::local_data/users.v3j";
892 my $exists = -e $filename ? "OVERWRITING" : "CREATING";
893 print "perl user_json $exists $filename\n";
904 my $ref = decode($f[1]);
909 print "# Error: $f[0]\t$f[1]\n";
913 DXUser::sync(); DXUser::finish();
914 my $diff = _diffms($ta);
915 print "There are $count user records and $err errors in $diff mS\n";
926 my $name = shift || 'recover_json';
928 my $fn = $name ne 'recover_json' ? $name : "$main::local_data/$name"; # force use of local
931 move "$fn.oooo", "$fn.ooooo" if -e "$fn.oooo";
932 move "$fn.ooo", "$fn.oooo" if -e "$fn.ooo";
933 move "$fn.oo", "$fn.ooo" if -e "$fn.oo";
934 move "$fn.o", "$fn.oo" if -e "$fn.o";
935 move "$fn", "$fn.o" if -e "$fn";
937 my $ta = [gettimeofday];
942 my $strings = "strings $filename";
943 my $ifh = new IO::File "$strings |" or return "cannot open input $filename ($!)";
944 my $fh = new IO::File ">$fn" or return "cannot open output $fn ($!)";
949 my $t = scalar localtime;
950 print $fh export_preamble();
956 while (defined ($l = $ifh->getline)) {
957 next unless $l =~ /^{"call":"[-\d\w\/]+"/;
964 eval{ $v = decode($data); };
969 next if $data eq $last;
970 print $fh "$v->{call}\t$l\n";
981 my $diff = _diffms($ta);
982 my $s = qq{Recovered users to $fn - $count Users, $errs errors $total possible records read in $diff mS ('sh/log recover' for details)};
983 LogDbg('command', $s);
990 print "DXUser Ended\n" unless $readonly;