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), 'DXUser';
379 unless ($dbm->get($call, $data)) {
380 $ref = decode($data);
385 if (UNIVERSAL::isa($ref, 'DXUser')) {
386 dbg("DXUser::get: got strange answer from decode of $call". ref $ref. " ignoring");
389 # we have a reference and it *is* a DXUser
391 dbg("DXUser::get: no reference returned from decode of $call $!");
394 $lru->put($call, $ref);
399 # get an existing either from the channel (if there is one) or from the database
401 # It is important to note that if you have done a get (for the channel say) and you
402 # want access or modify that you must use this call (and you must NOT use get's all
403 # over the place willy nilly!)
410 my $dxchan = DXChannel::get($call);
412 my $ref = $dxchan->user;
413 return $ref if $ref && UNIVERSAL::isa($ref, 'DXUser');
415 dbg("DXUser::get_current: got invalid user ref for $call from dxchan $dxchan->{call} ". ref $ref. " ignoring");
421 # get all callsigns in the database
427 my $sth = $dbh->prepare(qq{select call from user}) or confess($dbh->errstr);
428 my $rv = $sth->execute();
432 while (my @r = $sth->fetchrow_array) {
435 return @row; # 'cos it's already sorted
438 return (sort keys %u);
449 confess "Trying to put nothing!" unless $self && ref $self;
450 my $call = $self->{call};
452 delete $self->{annok} if $self->{annok};
453 delete $self->{dxok} if $self->{dxok};
455 $lru->put($call, $self);
460 my $ref = $self->encode;
461 $dbm->put($call, $ref);
468 goto &asc_encode unless $v3;
470 return nfreeze($self);
476 goto &asc_decode unless $v3;
481 # create a string from a user reference (in_ascii)
490 my $ref = bless {}, ref $self;
491 foreach my $k (qw(qth lat long qra sort call homenode node lastoper lastin)) {
492 $ref->{$k} = $self->{$k} if exists $self->{$k};
494 $ref->{name} = $self->{name} if exists $self->{name} && $self->{name} !~ /selfspot/i;
503 # create a hash from a string (in ascii)
509 $s =~ s/\%([0-9A-F][0-9A-F])/chr(hex($1))/eg;
519 # del - delete a user
528 my $call = $self->{call};
535 # close - close down a user
541 $self->{lastin} = time;
552 $dbh->commit if $dbh_working;
560 # return a list of valid elements
570 # export the database to an ascii file
576 my $basic_info_only = shift;
579 rename "$fn.oooo", "$fn.ooooo" if -e "$fn.oooo";
580 rename "$fn.ooo", "$fn.oooo" if -e "$fn.ooo";
581 rename "$fn.oo", "$fn.ooo" if -e "$fn.oo";
582 rename "$fn.o", "$fn.oo" if -e "$fn.o";
583 rename "$fn", "$fn.o" if -e "$fn";
588 my $fh = new IO::File ">$fn" or return "cannot open $fn ($!)";
590 my $t = scalar localtime;
591 print $fh q{#!/usr/bin/perl
593 # The exported userfile for a DXSpider System
595 # Input file: $filename
601 # search local then perl directories
605 # root of directory tree for this system
607 $root = $ENV{'DXSPIDER_ROOT'} if $ENV{'DXSPIDER_ROOT'};
609 unshift @INC, "$root/perl"; # this IS the right way round!
610 unshift @INC, "$root/local";
612 # try to detect a lockfile (this isn't atomic but
614 $lockfn = "$root/local/cluster.lck"; # lock file name
616 open(CLLOCK, "$lockfn") or die "Can't open Lockfile ($lockfn) $!";
619 die "Lockfile ($lockfn) and process $pid exists - cluster must be stopped first\n" if kill 0, $pid;
630 $main::userfn = shift @ARGV;
631 print "user filename now $userfn\n";
634 DXUser->del_file($main::userfn);
635 DXUser->init($main::userfn, 1);
642 my $ref = asc_decode($f[1]);
647 print "# Error: $f[0]\t$f[1]\n";
651 DXUser->sync; DXUser->finish;
652 print "There are $count user records and $err errors\n";
654 print $fh "__DATA__\n";
657 my $sth = $dbh->prepare(q{select call,data from user}) or confess($dbh->errstr);
658 my $rv = $sth->execute;
660 while (my @row = $sth->fetchrow_array) {
661 my $call = shift @row;
662 my $data = shift @row;
663 if (!is_callsign($call) || $call =~ /^0/) {
664 LogDbg('DXCommand', "Export Error1: $call\t$data");
669 my $ref = bless decode_json($data), __PACKAGE__;
670 my $t = $ref->{lastin} || 0;
671 if ($ref->{sort} eq 'U' && !$ref->{priv} && $main::systime > $t + $tooold) {
672 unless ($ref->{lat} && $ref->{long} || $ref->{qth} || $ref->{qra}) {
673 LogDbg('DXCommand', "$ref->{call} deleted, too old");
680 # only store users that are reasonably active or have useful information
681 print $fh "$call\t" . $ref->asc_encode($basic_info_only) . "\n";
685 dbg(carp($dbh->errstr));
691 for ($action = DB_File::R_FIRST(); !$dbm->seq($key, $val, $action); $action = DB_File::R_NEXT()) {
692 if (!is_callsign($key) || $key =~ /^0/) {
695 $eval =~ s/([\%\x00-\x1f\x7f-\xff])/sprintf("%%%02X", ord($1))/eg;
696 $ekey =~ s/([\%\x00-\x1f\x7f-\xff])/sprintf("%%%02X", ord($1))/eg;
697 LogDbg('DXCommand', "Export Error1: $ekey\t$eval");
698 eval {$dbm->del($key)};
699 dbg(carp("Export Error1: $ekey\t$eval\n$@")) if $@;
703 my $ref = decode($val);
705 my $t = $ref->{lastin} || 0;
706 if ($ref->{sort} eq 'U' && !$ref->{priv} && $main::systime > $t + $tooold) {
707 unless ($ref->{lat} && $ref->{long} || $ref->{qth} || $ref->{qra}) {
708 eval {$dbm->del($key)};
709 dbg(carp("Export Error2: $key\t$val\n$@")) if $@;
710 LogDbg('DXCommand', "$ref->{call} deleted, too old");
715 # only store users that are reasonably active or have useful information
716 print $fh "$key\t" . $ref->asc_encode($basic_info_only) . "\n";
719 LogDbg('DXCommand', "Export Error3: $key\t$val");
720 eval {$dbm->del($key)};
721 dbg(carp("Export Error3: $key\t$val\n$@")) if $@;
728 return "$count Users $del Deleted $err Errors ('sh/log Export' for details)";
735 # add one or more groups
739 my $ref = $self->{group} || [ 'local' ];
740 $self->{group} = $ref if !$self->{group};
741 push @$ref, @_ if @_;
744 # remove one or more groups
748 my $ref = $self->{group} || [ 'local' ];
751 $self->{group} = $ref if !$self->{group};
753 @$ref = map { my $a = $_; return (grep { $_ eq $a } @in) ? () : $a } @$ref;
756 # does this thing contain all the groups listed?
760 my $ref = $self->{group};
763 return 0 if !$ref || @_ == 0;
764 return 1 if @$ref == 0 && @_ == 0;
765 for ($n = 0; $n < @_; ) {
768 $n++ if grep $_ eq $a, @_;
774 # simplified group test just for one group
779 my $ref = $self->{group};
782 return grep $_ eq $s, $ref;
785 # set up a default group (only happens for them's that connect direct)
789 $self->{group} = [ 'local' ];
792 # set up empty buddies (only happens for them's that connect direct)
796 $self->{buddies} = [ ];
800 # return a prompt for a field
805 my ($self, $ele) = @_;
809 # some variable accessors
813 @_ ? $self->{'sort'} = shift : $self->{'sort'} ;
818 # want is default = 1
825 $self->{$s} = $val if defined $val;
826 return exists $self->{$s} ? $self->{$s} : 1;
829 # wantnot is default = 0
836 $self->{$s} = $val if defined $val;
837 return exists $self->{$s} ? $self->{$s} : 0;
842 return _want('beep', @_);
847 return _want('ann', @_);
852 return _want('wwv', @_);
857 return _want('wcy', @_);
862 return _want('echo', @_);
867 return _want('wx', @_);
872 return _want('dx', @_);
877 return _want('talk', @_);
882 return _want('grid', @_);
887 return _want('email', @_);
892 return _want('ann_talk', @_);
897 return _want('pc16', @_);
902 return _want('sendpc16', @_);
907 return _want('routepc16', @_);
912 return _want('usstate', @_);
917 return _want('dxcq', @_);
922 return _want('dxitu', @_);
927 return _want('gtk', @_);
932 return _want('pc9x', @_);
939 $self->{wantlogininfo} = $val if defined $val;
940 return $self->{wantlogininfo};
946 return $self->{sort} =~ /[ACRSX]/;
952 return grep $_ eq 'local_node', @{$self->{group}};
958 return $self->{sort} eq 'U';
964 return $self->{sort} eq 'B';
970 return $self->{sort} eq 'S';
976 return $self->{sort} eq 'C';
982 return $self->{sort} eq 'X';
988 return $self->{sort} eq 'R';
994 return $self->{sort} eq 'A';
1000 delete $self->{passwd};
1003 sub unset_passphrase
1006 delete $self->{passphrase};
1012 my $call = uc shift;
1013 $self->{believe} ||= [];
1014 push @{$self->{believe}}, $call unless grep $_ eq $call, @{$self->{believe}};
1020 my $call = uc shift;
1021 if (exists $self->{believe}) {
1022 $self->{believe} = [grep {$_ ne $call} @{$self->{believe}}];
1023 delete $self->{believe} unless @{$self->{believe}};
1030 return exists $self->{believe} ? @{$self->{believe}} : ();
1037 $self->{lastping} ||= {};
1038 $self->{lastping} = {} unless ref $self->{lastping};
1039 my $b = $self->{lastping};
1040 $b->{$call} = shift if @_;