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;
170 $main::systime ||= time; # becuase user_asc doesn't set it
172 # open "database" files
175 $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?]";
177 $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?]";
179 die "Cannot open $fn.v3 ($!)\n" unless $dbm;
183 $dbh = DBI->connect("dbi:SQLite:dbname=$ufn","","") or die "Cannot open $ufn ($!)\n";
186 my $table = q{create table user(
187 call text not null unique,
188 lastseen int not null,
191 $dbh->do($table) or die "cannot create user table in $ufn " . $dbh->errstr;
194 $dbh->do(q(create index x1 on user(lastseen))) or die $dbh->errstr;
196 $dbh->do(q{PRAGMA cache_size = 8000});
197 $dbh->do(q{PRAGMA synchronous = OFF});
201 # do a conversion if required
202 if ($dbm && $v3 && $convert) {
203 my ($key, $val, $action, $count, $err) = ('','',0,0,0);
208 import Storable qw(nfreeze thaw);
211 dbg("Converting the User File to V3 ");
212 dbg("This will take a while, I suggest you go and have a cup of strong tea");
213 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?]";
214 for ($action = DB_File::R_FIRST(); !$odbm->seq($key, $val, $action); $action = DB_File::R_NEXT()) {
215 my $ref = asc_decode($val);
225 dbg("Conversion completed $count records $err errors");
228 if ($dbh && $v4 && $convert) {
229 my ($key, $val, $action, $count, $err) = ('','',0,0,0);
233 dbg("Converting the User File to V4 ");
234 dbg("This will take a while, I suggest you go and have a cup of strong tea");
238 import Storable qw(nfreeze thaw);
239 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?]";
242 for ($action = DB_File::R_FIRST(); !$odbm->seq($key, $val, $action); $action = DB_File::R_NEXT()) {
243 my $ref = thaw($val);
245 my $r = _insert($ref);
250 dbg("error converting call $ref->{call} - " . $dbh->errstr);
259 dbg("Conversion completed $count records $err errors");
263 $lru = LRU->newbase("DXUser", $lrusize);
272 confess "need a filename in User" if !$fn;
274 $suffix = '.v4' if $v4;
275 $suffix ||= '.v3' if $v3;
282 # periodic processing
286 if ($main::systime > $lasttime + 5) {
288 $lasttime = $main::systime;
302 $dbh->disconnect if $dbh;
306 # new - create a new user
313 my $self = bless {call => $call, 'sort'=>'U'}, $pkg;
314 _insert($self) or confess($dbh->errstr) if $v4;
321 my $json = JSON->new->allow_blessed->convert_blessed->encode($self);
322 $dbh->begin_work unless $dbh_working++;
323 my $r = $dbh->do(q{replace into user values(?,?,?)}, undef, $self->{call}, $main::systime, $json);
330 my $sth = $dbh->prepare(qq{select data from user where call = ?}) or confess($dbh->errstr);
331 my $rv = $sth->execute($call);
333 my @row = $sth->fetchrow_array;
342 my $r = $dbh->do(q{delete from user where call = ?}, undef, $call);
350 # $call =~ s/-\d+$//o;
352 # confess "can't create existing call $call in User\n!" if $u{$call};
354 my $self = $pkg->alloc($call);
355 $self->put unless $v4;
360 # get - get an existing user - this seems to return a different reference everytime it is
369 # is it in the LRU cache?
370 my $ref = $lru->get($call);
371 return $ref if $ref && ref $ref eq 'DXUser';
375 if ($data = _select($call)) {
376 $ref = bless decode_json($data), __PACKAGE__;
377 $lru->put($call, $ref);
381 unless ($dbm->get($call, $data)) {
382 $ref = decode($data);
384 if (ref $ref ne 'DXUser') {
385 dbg("DXUser::get: got strange answer from decode ". ref $ref. " ignoring");
389 dbg("DXUser::get: no reference returned from decode $!");
392 $lru->put($call, $ref);
401 # get an existing either from the channel (if there is one) or from the database
403 # It is important to note that if you have done a get (for the channel say) and you
404 # want access or modify that you must use this call (and you must NOT use get's all
405 # over the place willy nilly!)
412 my $dxchan = DXChannel::get($call);
414 my $ref = $dxchan->user;
415 return $ref if ref $ref eq 'DXUser';
417 dbg("DXUser::get_current: got invalid user ref from dxchan $dxchan->{call} ". ref $ref. " ignoring");
423 # get all callsigns in the database
429 my $sth = $dbh->prepare(qq{select call from user}) or confess($dbh->errstr);
430 my $rv = $sth->execute();
434 while (my @r = $sth->fetchrow_array) {
437 return @row; # 'cos it's already sorted
440 return (sort keys %u);
451 confess "Trying to put nothing!" unless $self && ref $self;
452 my $call = $self->{call};
454 delete $self->{annok} if $self->{annok};
455 delete $self->{dxok} if $self->{dxok};
457 $lru->put($call, $self);
462 my $ref = $self->encode;
463 $dbm->put($call, $ref);
470 goto &asc_encode unless $v3;
472 return nfreeze($self);
478 goto &asc_decode unless $v3;
483 # create a string from a user reference (in_ascii)
492 my $ref = bless {}, ref $self;
493 foreach my $k (qw(qth lat long qra sort call homenode node lastoper lastin)) {
494 $ref->{$k} = $self->{$k} if exists $self->{$k};
496 $ref->{name} = $self->{name} if exists $self->{name} && $self->{name} !~ /selfspot/i;
505 # create a hash from a string (in ascii)
511 $s =~ s/\%([0-9A-F][0-9A-F])/chr(hex($1))/eg;
521 # del - delete a user
530 my $call = $self->{call};
537 # close - close down a user
543 $self->{lastin} = time;
554 $dbh->commit if $dbh_working;
562 # return a list of valid elements
572 # export the database to an ascii file
578 my $basic_info_only = shift;
581 rename "$fn.oooo", "$fn.ooooo" if -e "$fn.oooo";
582 rename "$fn.ooo", "$fn.oooo" if -e "$fn.ooo";
583 rename "$fn.oo", "$fn.ooo" if -e "$fn.oo";
584 rename "$fn.o", "$fn.oo" if -e "$fn.o";
585 rename "$fn", "$fn.o" if -e "$fn";
590 my $fh = new IO::File ">$fn" or return "cannot open $fn ($!)";
592 my $t = scalar localtime;
593 print $fh q{#!/usr/bin/perl
595 # The exported userfile for a DXSpider System
597 # Input file: $filename
603 # search local then perl directories
607 # root of directory tree for this system
609 $root = $ENV{'DXSPIDER_ROOT'} if $ENV{'DXSPIDER_ROOT'};
611 unshift @INC, "$root/perl"; # this IS the right way round!
612 unshift @INC, "$root/local";
614 # try to detect a lockfile (this isn't atomic but
616 $lockfn = "$root/local/cluster.lck"; # lock file name
618 open(CLLOCK, "$lockfn") or die "Can't open Lockfile ($lockfn) $!";
621 die "Lockfile ($lockfn) and process $pid exists - cluster must be stopped first\n" if kill 0, $pid;
632 $main::userfn = shift @ARGV;
633 print "user filename now $userfn\n";
636 DXUser->del_file($main::userfn);
637 DXUser->init($main::userfn, 1);
644 my $ref = asc_decode($f[1]);
649 print "# Error: $f[0]\t$f[1]\n";
653 DXUser->sync; DXUser->finish;
654 print "There are $count user records and $err errors\n";
656 print $fh "__DATA__\n";
659 my $sth = $dbh->prepare(q{select call,data from user}) or confess($dbh->errstr);
660 my $rv = $sth->execute;
662 while (my @row = $sth->fetchrow_array) {
663 my $call = shift @row;
664 my $data = shift @row;
665 if (!is_callsign($call) || $call =~ /^0/) {
666 LogDbg('DXCommand', "Export Error1: $call\t$data");
671 my $ref = bless decode_json($data), __PACKAGE__;
672 my $t = $ref->{lastin} || 0;
673 if ($ref->{sort} eq 'U' && !$ref->{priv} && $main::systime > $t + $tooold) {
674 unless ($ref->{lat} && $ref->{long} || $ref->{qth} || $ref->{qra}) {
675 LogDbg('DXCommand', "$ref->{call} deleted, too old");
682 # only store users that are reasonably active or have useful information
683 print $fh "$call\t" . $ref->asc_encode($basic_info_only) . "\n";
687 dbg(carp($dbh->errstr));
693 for ($action = DB_File::R_FIRST(); !$dbm->seq($key, $val, $action); $action = DB_File::R_NEXT()) {
694 if (!is_callsign($key) || $key =~ /^0/) {
697 $eval =~ s/([\%\x00-\x1f\x7f-\xff])/sprintf("%%%02X", ord($1))/eg;
698 $ekey =~ s/([\%\x00-\x1f\x7f-\xff])/sprintf("%%%02X", ord($1))/eg;
699 LogDbg('DXCommand', "Export Error1: $ekey\t$eval");
700 eval {$dbm->del($key)};
701 dbg(carp("Export Error1: $ekey\t$eval\n$@")) if $@;
705 my $ref = decode($val);
707 my $t = $ref->{lastin} || 0;
708 if ($ref->{sort} eq 'U' && !$ref->{priv} && $main::systime > $t + $tooold) {
709 unless ($ref->{lat} && $ref->{long} || $ref->{qth} || $ref->{qra}) {
710 eval {$dbm->del($key)};
711 dbg(carp("Export Error2: $key\t$val\n$@")) if $@;
712 LogDbg('DXCommand', "$ref->{call} deleted, too old");
717 # only store users that are reasonably active or have useful information
718 print $fh "$key\t" . $ref->asc_encode($basic_info_only) . "\n";
721 LogDbg('DXCommand', "Export Error3: $key\t$val");
722 eval {$dbm->del($key)};
723 dbg(carp("Export Error3: $key\t$val\n$@")) if $@;
730 return "$count Users $del Deleted $err Errors ('sh/log Export' for details)";
737 # add one or more groups
741 my $ref = $self->{group} || [ 'local' ];
742 $self->{group} = $ref if !$self->{group};
743 push @$ref, @_ if @_;
746 # remove one or more groups
750 my $ref = $self->{group} || [ 'local' ];
753 $self->{group} = $ref if !$self->{group};
755 @$ref = map { my $a = $_; return (grep { $_ eq $a } @in) ? () : $a } @$ref;
758 # does this thing contain all the groups listed?
762 my $ref = $self->{group};
765 return 0 if !$ref || @_ == 0;
766 return 1 if @$ref == 0 && @_ == 0;
767 for ($n = 0; $n < @_; ) {
770 $n++ if grep $_ eq $a, @_;
776 # simplified group test just for one group
781 my $ref = $self->{group};
784 return grep $_ eq $s, $ref;
787 # set up a default group (only happens for them's that connect direct)
791 $self->{group} = [ 'local' ];
794 # set up empty buddies (only happens for them's that connect direct)
798 $self->{buddies} = [ ];
802 # return a prompt for a field
807 my ($self, $ele) = @_;
811 # some variable accessors
815 @_ ? $self->{'sort'} = shift : $self->{'sort'} ;
820 # want is default = 1
827 $self->{$s} = $val if defined $val;
828 return exists $self->{$s} ? $self->{$s} : 1;
831 # wantnot is default = 0
838 $self->{$s} = $val if defined $val;
839 return exists $self->{$s} ? $self->{$s} : 0;
844 return _want('beep', @_);
849 return _want('ann', @_);
854 return _want('wwv', @_);
859 return _want('wcy', @_);
864 return _want('echo', @_);
869 return _want('wx', @_);
874 return _want('dx', @_);
879 return _want('talk', @_);
884 return _want('grid', @_);
889 return _want('email', @_);
894 return _want('ann_talk', @_);
899 return _want('pc16', @_);
904 return _want('sendpc16', @_);
909 return _want('routepc16', @_);
914 return _want('usstate', @_);
919 return _want('dxcq', @_);
924 return _want('dxitu', @_);
929 return _want('gtk', @_);
934 return _want('pc9x', @_);
941 $self->{wantlogininfo} = $val if defined $val;
942 return $self->{wantlogininfo};
948 return $self->{sort} =~ /[ACRSX]/;
954 return grep $_ eq 'local_node', @{$self->{group}};
960 return $self->{sort} eq 'U';
966 return $self->{sort} eq 'B';
972 return $self->{sort} eq 'S';
978 return $self->{sort} eq 'C';
984 return $self->{sort} eq 'X';
990 return $self->{sort} eq 'R';
996 return $self->{sort} eq 'A';
1002 delete $self->{passwd};
1005 sub unset_passphrase
1008 delete $self->{passphrase};
1014 my $call = uc shift;
1015 $self->{believe} ||= [];
1016 push @{$self->{believe}}, $call unless grep $_ eq $call, @{$self->{believe}};
1022 my $call = uc shift;
1023 if (exists $self->{believe}) {
1024 $self->{believe} = [grep {$_ ne $call} @{$self->{believe}}];
1025 delete $self->{believe} unless @{$self->{believe}};
1032 return exists $self->{believe} ? @{$self->{believe}} : ();
1039 $self->{lastping} ||= {};
1040 $self->{lastping} = {} unless ref $self->{lastping};
1041 my $b = $self->{lastping};
1042 $b->{$call} = shift if @_;