2 # DX cluster user routines
4 # Copyright (c) 1998 - Dirk Koopman G1TLH
21 use vars qw(%u $dbm $dbh $filename %valid $lastoperinterval $lasttime $lru $lrusize $tooold $v3 $v4);
27 $lastoperinterval = 60*24*60*60;
30 $tooold = 86400 * 365; # this marks an old user who hasn't given enough info to be useful
35 # hash of valid elements and a simple prompt
38 alias => '0,Real Callsign',
41 lat => '0,Latitude,slat',
42 long => '0,Longitude,slong',
44 email => '0,E-mail Address,parray',
45 priv => '9,Privilege Level',
46 lastin => '0,Last Time in,cldatetime',
47 passwd => '9,Password,yesno',
48 passphrase => '9,Pass Phrase,yesno',
49 addr => '0,Full Address',
50 'sort' => '0,Type of User', # A - ak1a, U - User, S - spider cluster, B - BBS
51 xpert => '0,Expert Status,yesno',
53 node => '0,Last Node',
54 homenode => '0,Home Node',
55 lockout => '9,Locked out?,yesno', # won't let them in at all
56 dxok => '9,Accept DX Spots?,yesno', # accept his dx spots?
57 annok => '9,Accept Announces?,yesno', # accept his announces?
59 hmsgno => '0,Highest Msgno',
60 group => '0,Group,parray', # used to create a group of users/nodes for some purpose or other
61 buddies => '0,Buddies,parray',
62 isolate => '9,Isolate network,yesno',
63 wantbeep => '0,Req Beep,yesno',
64 wantann => '0,Req Announce,yesno',
65 wantwwv => '0,Req WWV,yesno',
66 wantwcy => '0,Req WCY,yesno',
67 wantecho => '0,Req Echo,yesno',
68 wanttalk => '0,Req Talk,yesno',
69 wantwx => '0,Req WX,yesno',
70 wantdx => '0,Req DX Spots,yesno',
71 wantemail => '0,Req Msgs as Email,yesno',
72 pagelth => '0,Current Pagelth',
73 pingint => '9,Node Ping interval',
74 nopings => '9,Ping Obs Count',
75 wantlogininfo => '0,Login Info Req,yesno',
76 wantgrid => '0,Show DX Grid,yesno',
77 wantann_talk => '0,Talklike Anns,yesno',
78 wantpc16 => '9,Want Users from node,yesno',
79 wantsendpc16 => '9,Send PC16,yesno',
80 wantroutepc19 => '9,Route PC19,yesno',
81 wantusstate => '0,Show US State,yesno',
82 wantdxcq => '0,Show CQ Zone,yesno',
83 wantdxitu => '0,Show ITU Zone,yesno',
84 wantgtk => '0,Want GTK interface,yesno',
85 wantpc9x => '0,Want PC9X interface,yesno',
86 lastoper => '9,Last for/oper,cldatetime',
87 nothere => '0,Not Here Text',
88 registered => '9,Registered?,yesno',
89 prompt => '0,Required Prompt',
90 version => '1,Version',
92 believe => '1,Believable nodes,parray',
93 lastping => '1,Last Ping at,ptimelist',
94 maxconnect => '1,Max Connections',
101 my $name = $AUTOLOAD;
103 return if $name =~ /::DESTROY$/;
106 confess "Non-existant field '$AUTOLOAD'" if !$valid{$name};
107 # this clever line of code creates a subroutine which takes over from autoload
108 # from OO Perl - Conway
109 *$AUTOLOAD = sub {@_ > 1 ? $_[0]->{$name} = $_[1] : $_[0]->{$name}};
116 # initialise the system
120 my ($pkg, $fn, $mode) = @_;
122 confess "need a filename in User" if !$fn;
136 $v3 = 1; $convert = 0;
137 dbg("One of more of the modules DBI, DBD::SQLite and JSON appear to be missing!!");
138 dbg("trying to continue in compatibility mode (this may fail)");
139 dbg("please install DBI, DBD::SQLite and JSON from CPAN as soon as possible");
149 dbg("One of the modules DB_File and Storable appears to be missing!!");
150 dbg("trying to continue in compatibility mode (this may fail)");
151 dbg("please install Storable from CPAN as soon as possible");
154 import Storable qw(nfreeze thaw);
158 $convert++ if -e "$fn.v2" && !-e $ufn;
163 import JSON qw(-convert_blessed_universally);
167 $convert++ if -e "$fn.v3" && !-e $ufn;
171 # open "database" files
174 $dbm = tie (%u, 'DB_File', "$fn.v3", O_CREAT|O_RDWR, 0666, $DB::File::DB_BTREE) or confess "can't open user file: $fn ($!) [rebuild it from user_asc?]";
176 $dbm = tie (%u, 'DB_File', "$fn.v3", O_RDONLY, 0666, $DB_File::DB_BTREE) or confess "can't open user file: $fn ($!) [rebuild it from user_asc?]";
178 die "Cannot open $fn.v3 ($!)\n" unless $dbm;
182 $dbh = DBI->connect("dbi:SQLite:dbname=$ufn","","") or die "Cannot open $ufn ($!)\n";
186 # do a conversion if required
187 if ($dbm && $v3 && $convert) {
188 my ($key, $val, $action, $count, $err) = ('','',0,0,0);
191 dbg("Converting the User File to V3 ");
192 dbg("This will take a while, I suggest you go and have cup of strong tea");
193 my $odbm = tie (%oldu, 'DB_File', "$fn.v2", O_RDONLY, 0666, $DB_File::DB_BTREE) or confess "can't open user file: $fn.v2 ($!) [rebuild it from user_asc?]";
194 for ($action = DB_File::R_FIRST; !$odbm->seq($key, $val, $action); $action = DB_File::R_NEXT) {
195 my $ref = asc_decode($val);
205 dbg("Conversion completed $count records $err errors");
208 if ($dbh && $v4 && $convert) {
209 my ($key, $val, $action, $count, $err) = ('','',0,0,0);
212 my $table = q{create table user(
213 call text not null unique,
214 lastseen int not null,
217 $dbh->do($table) or die "cannot create user table in $ufn " . $dbh->errstr;
220 $dbh->do(q(create index x1 on user(lastseen))) or die $dbh->errstr;
223 dbg("Converting the User File to V4 ");
224 dbg("This will take a while, I suggest you go and have cup of strong tea");
228 import Storable qw(nfreeze thaw);
229 my $odbm = tie (%oldu, 'DB_File', "$fn.v3", O_RDONLY, 0666, $DB_File::DB_BTREE) or confess "can't open user file: $fn.v3 ($!) [rebuild it from user_asc?]";
231 for ($action = DB_File::R_FIRST; !$odbm->seq($key, $val, $action); $action = DB_File::R_NEXT) {
232 my $ref = thaw($val);
234 my $r = _insert($ref);
239 dbg("error converting call $ref->{call} - " . $dbh->errstr);
248 dbg("Conversion completed $count records $err errors");
252 $lru = LRU->newbase("DXUser", $lrusize);
261 confess "need a filename in User" if !$fn;
263 $suffix = '.v4' if $v4;
264 $suffix ||= '.v3' if $v3;
271 # periodic processing
275 if ($main::systime > $lasttime + 5) {
277 $lasttime = $main::systime;
291 $dbh->disconnect if $dbh;
295 # new - create a new user
302 my $self = bless {call => $call, 'sort'=>'U'}, $pkg;
303 _insert($self) or confess($dbh->errstr) if $v4;
310 my $json = JSON->new->allow_blessed->convert_blessed->encode($self);
311 $dbh->begin_work unless $dbh_working++;
312 my $r = $dbh->do(q{replace into user values(?,?,?)}, undef, $self->{call}, $main::systime, $json);
319 my $sth = $dbh->prepare(qq{select data from user where call = ?}) or confess($dbh->errstr);
320 my $rv = $sth->execute($call);
322 my @row = $sth->fetchrow_array;
332 # $call =~ s/-\d+$//o;
334 # confess "can't create existing call $call in User\n!" if $u{$call};
336 my $self = $pkg->alloc($call);
337 $self->put unless $v4;
342 # get - get an existing user - this seems to return a different reference everytime it is
351 # is it in the LRU cache?
352 my $ref = $lru->get($call);
353 return $ref if $ref && ref $ref eq 'DXUser';
357 if ($data = _select($call)) {
358 $ref = bless decode_json($data), __PACKAGE__;
359 $lru->put($call, $ref);
363 unless ($dbm->get($call, $data)) {
364 $ref = decode($data);
366 if (ref $ref ne 'DXUser') {
367 dbg("DXUser::get: got strange answer from decode ". ref $ref. " ignoring");
371 dbg("DXUser::get: no reference returned from decode $!");
374 $lru->put($call, $ref);
383 # get an existing either from the channel (if there is one) or from the database
385 # It is important to note that if you have done a get (for the channel say) and you
386 # want access or modify that you must use this call (and you must NOT use get's all
387 # over the place willy nilly!)
394 my $dxchan = DXChannel::get($call);
396 my $ref = $dxchan->user;
397 return $ref if ref $ref eq 'DXUser';
399 dbg("DXUser::get_current: got invalid user ref from dxchan $dxchan->{call} ". ref $ref. " ignoring");
405 # get all callsigns in the database
411 my $sth = $dbh->prepare(qq{select call from user}) or confess($dbh->errstr);
412 my $rv = $sth->execute();
416 while (my @r = $sth->fetchrow_array) {
419 return @row; # 'cos it's already sorted
422 return (sort keys %u);
433 confess "Trying to put nothing!" unless $self && ref $self;
434 my $call = $self->{call};
436 delete $self->{annok} if $self->{annok};
437 delete $self->{dxok} if $self->{dxok};
439 $lru->put($call, $self);
444 my $ref = $self->encode;
445 $dbm->put($call, $ref);
452 goto &asc_encode unless $v3;
454 return nfreeze($self);
460 goto &asc_decode unless $v3;
465 # create a string from a user reference (in_ascii)
474 my $ref = bless {}, ref $self;
475 foreach my $k (qw(qth lat long qra sort call homenode node lastoper lastin)) {
476 $ref->{$k} = $self->{$k} if exists $self->{$k};
478 $ref->{name} = $self->{name} if exists $self->{name} && $self->{name} !~ /selfspot/i;
487 # create a hash from a string (in ascii)
493 $s =~ s/\%([0-9A-F][0-9A-F])/chr(hex($1))/eg;
503 # del - delete a user
512 my $call = $self->{call};
519 # close - close down a user
525 $self->{lastin} = time;
536 $dbh->commit if $dbh_working;
544 # return a list of valid elements
554 # export the database to an ascii file
560 my $basic_info_only = shift;
563 rename "$fn.oooo", "$fn.ooooo" if -e "$fn.oooo";
564 rename "$fn.ooo", "$fn.oooo" if -e "$fn.ooo";
565 rename "$fn.oo", "$fn.ooo" if -e "$fn.oo";
566 rename "$fn.o", "$fn.oo" if -e "$fn.o";
567 rename "$fn", "$fn.o" if -e "$fn";
572 my $fh = new IO::File ">$fn" or return "cannot open $fn ($!)";
577 my $t = scalar localtime;
578 print $fh q{#!/usr/bin/perl
580 # The exported userfile for a DXSpider System
582 # Input file: $filename
588 # search local then perl directories
592 # root of directory tree for this system
594 $root = $ENV{'DXSPIDER_ROOT'} if $ENV{'DXSPIDER_ROOT'};
596 unshift @INC, "$root/perl"; # this IS the right way round!
597 unshift @INC, "$root/local";
599 # try to detect a lockfile (this isn't atomic but
601 $lockfn = "$root/local/cluster.lck"; # lock file name
603 open(CLLOCK, "$lockfn") or die "Can't open Lockfile ($lockfn) $!";
606 die "Lockfile ($lockfn) and process $pid exists - cluster must be stopped first\n" if kill 0, $pid;
617 $main::userfn = shift @ARGV;
618 print "user filename now $userfn\n";
621 DXUser->del_file($main::userfn);
622 DXUser->init($main::userfn, 1);
629 my $ref = asc_decode($f[1]);
634 print "# Error: $f[0]\t$f[1]\n";
638 DXUser->sync; DXUser->finish;
639 print "There are $count user records and $err errors\n";
641 print $fh "__DATA__\n";
643 for ($action = DB_File::R_FIRST; !$dbm->seq($key, $val, $action); $action = DB_File::R_NEXT) {
644 if (!is_callsign($key) || $key =~ /^0/) {
647 $eval =~ s/([\%\x00-\x1f\x7f-\xff])/sprintf("%%%02X", ord($1))/eg;
648 $ekey =~ s/([\%\x00-\x1f\x7f-\xff])/sprintf("%%%02X", ord($1))/eg;
649 LogDbg('DXCommand', "Export Error1: $ekey\t$eval");
650 eval {$dbm->del($key)};
651 dbg(carp("Export Error1: $ekey\t$eval\n$@")) if $@;
655 my $ref = decode($val);
657 my $t = $ref->{lastin} || 0;
658 if ($ref->{sort} eq 'U' && !$ref->{priv} && $main::systime > $t + $tooold) {
659 unless ($ref->{lat} && $ref->{long} || $ref->{qth} || $ref->{qra}) {
660 eval {$dbm->del($key)};
661 dbg(carp("Export Error2: $key\t$val\n$@")) if $@;
662 LogDbg('DXCommand', "$ref->{call} deleted, too old");
667 # only store users that are reasonably active or have useful information
668 print $fh "$key\t" . $ref->asc_encode($basic_info_only) . "\n";
671 LogDbg('DXCommand', "Export Error3: $key\t$val");
672 eval {$dbm->del($key)};
673 dbg(carp("Export Error3: $key\t$val\n$@")) if $@;
679 return "$count Users $del Deleted $err Errors ('sh/log Export' for details)";
686 # add one or more groups
690 my $ref = $self->{group} || [ 'local' ];
691 $self->{group} = $ref if !$self->{group};
692 push @$ref, @_ if @_;
695 # remove one or more groups
699 my $ref = $self->{group} || [ 'local' ];
702 $self->{group} = $ref if !$self->{group};
704 @$ref = map { my $a = $_; return (grep { $_ eq $a } @in) ? () : $a } @$ref;
707 # does this thing contain all the groups listed?
711 my $ref = $self->{group};
714 return 0 if !$ref || @_ == 0;
715 return 1 if @$ref == 0 && @_ == 0;
716 for ($n = 0; $n < @_; ) {
719 $n++ if grep $_ eq $a, @_;
725 # simplified group test just for one group
730 my $ref = $self->{group};
733 return grep $_ eq $s, $ref;
736 # set up a default group (only happens for them's that connect direct)
740 $self->{group} = [ 'local' ];
743 # set up empty buddies (only happens for them's that connect direct)
747 $self->{buddies} = [ ];
751 # return a prompt for a field
756 my ($self, $ele) = @_;
760 # some variable accessors
764 @_ ? $self->{'sort'} = shift : $self->{'sort'} ;
769 # want is default = 1
776 $self->{$s} = $val if defined $val;
777 return exists $self->{$s} ? $self->{$s} : 1;
780 # wantnot is default = 0
787 $self->{$s} = $val if defined $val;
788 return exists $self->{$s} ? $self->{$s} : 0;
793 return _want('beep', @_);
798 return _want('ann', @_);
803 return _want('wwv', @_);
808 return _want('wcy', @_);
813 return _want('echo', @_);
818 return _want('wx', @_);
823 return _want('dx', @_);
828 return _want('talk', @_);
833 return _want('grid', @_);
838 return _want('email', @_);
843 return _want('ann_talk', @_);
848 return _want('pc16', @_);
853 return _want('sendpc16', @_);
858 return _want('routepc16', @_);
863 return _want('usstate', @_);
868 return _want('dxcq', @_);
873 return _want('dxitu', @_);
878 return _want('gtk', @_);
883 return _want('pc9x', @_);
890 $self->{wantlogininfo} = $val if defined $val;
891 return $self->{wantlogininfo};
897 return $self->{sort} =~ /[ACRSX]/;
903 return grep $_ eq 'local_node', @{$self->{group}};
909 return $self->{sort} eq 'U';
915 return $self->{sort} eq 'B';
921 return $self->{sort} eq 'S';
927 return $self->{sort} eq 'C';
933 return $self->{sort} eq 'X';
939 return $self->{sort} eq 'R';
945 return $self->{sort} eq 'A';
951 delete $self->{passwd};
957 delete $self->{passphrase};
964 $self->{believe} ||= [];
965 push @{$self->{believe}}, $call unless grep $_ eq $call, @{$self->{believe}};
972 if (exists $self->{believe}) {
973 $self->{believe} = [grep {$_ ne $call} @{$self->{believe}}];
974 delete $self->{believe} unless @{$self->{believe}};
981 return exists $self->{believe} ? @{$self->{believe}} : ();
988 $self->{lastping} ||= {};
989 $self->{lastping} = {} unless ref $self->{lastping};
990 my $b = $self->{lastping};
991 $b->{$call} = shift if @_;