3 # This is the DX cluster 'daemon'. It sits in the middle of its little
4 # web of client routines sucking and blowing data where it may.
6 # Hence the name of 'spider' (although it may become 'dxspider')
8 # Copyright (c) 1998 Dirk Koopman G1TLH
19 use vars qw($root $is_win $systime $lockfn @inqueue $starttime $lockfn @outstanding_connects
20 $zombies @listeners $lang $myalias @debug $userfn $clusteraddr
21 $clusterport $mycall $decease $routeroot $me $reqreg $bumpexisting
22 $allowdxby $dbh $dsn $dbuser $dbpass $do_xml $systime_days $systime_daystart
23 $can_encode $maxconnect_user $maxconnect_node $idle_interval $log_flush_interval
24 $broadcast_debug $yes $no $user_interval
27 #$lang = 'en'; # default language
28 #$clusteraddr = '127.0.0.1'; # cluster tcp host address - used for things like console.pl
29 #$clusterport = 27754; # cluster tcp port
30 #$yes = 'Yes'; # visual representation of yes
31 #$no = 'No'; # ditto for no
32 #$user_interval = 11*60; # the interval between unsolicited prompts if no traffic
36 # set default paths, these should be overwritten by DXVars.pm
37 use vars qw($data $system $cmd $localcmd $userfn $clusteraddr $clusterport $yes $no $user_interval $lang $local_data);
39 $lang = 'en'; # default language
40 $yes = 'Yes'; # visual representation of yes
41 $no = 'No'; # ditto for no
42 $user_interval = 11*60; # the interval between unsolicited prompts if no traffic
45 # make sure that modules are searched in the order local then perl
48 $SIG{'__WARN__'} = sub { warn $_[0] if $DOWARN };
50 # take into account any local::lib that might be present
56 import local::lib qw(/spider/perl5lib);
59 # root of directory tree for this system
61 $root = $ENV{'DXSPIDER_ROOT'} if $ENV{'DXSPIDER_ROOT'};
63 unshift @INC, "$root/perl5lib" unless grep {$_ eq "$root/perl5lib"} @INC;
64 unshift @INC, "$root/perl"; # this IS the right way round!
65 unshift @INC, "$root/local";
67 # do some validation of the input
68 die "The directory $root doesn't exist, please RTFM" unless -d $root;
69 die "$root/local doesn't exist, please RTFM" unless -d "$root/local";
70 die "$root/local/DXVars.pm doesn't exist, please RTFM" unless -e "$root/local/DXVars.pm";
72 # create some directories
73 mkdir "$root/local_cmd", 02774 unless -d "$root/local_cmd";
75 # locally stored data lives here
76 $local_data = "$root/local_data";
77 mkdir $local_data, 02774 unless -d $local_data;
79 $system = "$root/sys";
81 $localcmd = "$root/local_cmd";
82 $userfn = "$data/users";
84 # try to create and lock a lockfile (this isn't atomic but
86 $lockfn = "$root/local_data/cluster.lck"; # lock file name
88 open(CLLOCK, "$lockfn") or die "Can't open Lockfile ($lockfn) $!";
93 warn "Lockfile ($lockfn) and process $pid exist, another cluster running?\n";
100 open(CLLOCK, ">$lockfn") or die "Can't open Lockfile ($lockfn) $!";
104 $is_win = ($^O =~ /^MS/ || $^O =~ /^OS-2/) ? 1 : 0; # is it Windows?
113 # order here is important - DXDebug snarfs Carp et al so that Mojo errors go into the debug log
114 use Mojolicious 7.26;
176 use POSIX ":sys_wait_h";
179 use vars qw($version $build $gitversion $gitbranch);
185 $lang //= 'en'; # default language
186 $clusteraddr //= '127.0.0.1'; # cluster tcp host address - used for things like console.pl
187 $clusterport //= 27754; # cluster tcp port
188 $yes //= 'Yes'; # visual representation of yes
189 $no //= 'No'; # ditto for no
190 $user_interval //= 11*60; # the interval between unsolicited prompts if no traffic
193 $clusteraddr //= '127.0.0.1'; # cluster tcp host address - used for things like console.pl
194 $clusterport //= 27754; # cluster tcp port
195 @inqueue = (); # the main input queue, an array of hashes
196 $systime = 0; # the time now (in seconds)
197 $starttime = 0; # the starting time of the cluster
198 @outstanding_connects = (); # list of outstanding connects
199 @listeners = (); # list of listeners
200 $reqreg = 0; # 1 = registration required, 2 = deregister people
201 $bumpexisting = 1; # 1 = allow new connection to disconnect old, 0 - don't allow it
202 our $allowmultiple = 0; # This is used in conjunction with $bumpexisting, in a rather weird way.
203 our $min_reconnection_rate = 5*60; # minimum value of seconds between connections per user to allow co-existing users
204 our $max_ssid = 15; # highest ssid to be searched for a spare one on multiple connections
206 # If $allowmultiple > 0 and the $reconnection_rate is some value of seconds
207 # based on the average connection time calculated from the $user->conntimel entries / frequency is
208 # less than $reconnection_rate then we assume that there is more than one device (probably HRD) trying
209 # to connect "at once". In which case we probe for a spare SSID for a user callsign to allow up to
210 # $allowmultiple connections per callsign.
212 $allowdxby = 0; # 1 = allow "dx by <othercall>", 0 - don't allow it
213 $maxconnect_user = 3; # the maximum no of concurrent connections a user can have at a time
214 $maxconnect_node = 0; # Ditto but for nodes. In either case if a new incoming connection
215 # takes the no of references in the routing table above these numbers
216 # then the connection is refused. This only affects INCOMING connections.
217 $idle_interval = 0.500; # the wait between invocations of the main idle loop processing.
218 $log_flush_interval = 2; # interval to wait between log flushes
220 our $ending; # signal that we are ending;
221 our $broadcast_debug; # allow broadcasting of debug info down "enhanced" user connections
222 our $clssecs; # the amount of cpu time the DXSpider process have consumed
223 our $cldsecs; # the amount of cpu time any child processes have consumed
224 our $allowslashcall; # Allow / in connecting callsigns (ie PA0/G1TLH, or even PA0/G1TLH/2)
227 use vars qw($version $subversion $build $gitversion $gitbranch);
229 # send a message to call on conn and disconnect
232 my ($conn, $call, $mess) = @_;
234 $conn->disable_read(1);
235 dbg("-> D $call $mess\n") if isdbg('chan');
236 $conn->send_now("D$call|$mess");
241 # handle incoming messages
244 my ($conn, $msg) = @_;
245 my ($sort, $call, $line) = DXChannel::decode_input(0, $msg);
246 return unless defined $sort;
250 if (is_webcall($call) && $conn->isa('IntMsg')) {
251 my $newcall = find_next_webcall();
253 already_conn($conn, $call, "Maximum no of web connected connects ($Web::maxssid) exceeded");
256 $call = normalise_call($newcall);
258 $user = DXUser::get_current($call);
260 $user = DXUser->new($call);
264 $user->qth('on the web');
265 $user->homenode($main::mycall);
266 $user->lat($main::mylatitude);
267 $user->long($main::mylongitude);
268 $user->qra($main::mylocator);
270 $user->startt($main::systime);
272 $dxchan = Web->new($call, $conn, $user);
273 $dxchan->enhanced(1);
275 $msg =~ s/^A#WEB|/A$call|/;
276 $conn->send_now("C$call");
278 # "Normal" connections
280 # normalise calls like G1TST-0/G1TST-00/G1TST-01 to G1TST and G1TST-1 respectively
281 my $ncall = normalise_call($call);
282 if ($call ne $ncall) {
283 LogDbg('err', "new_channel login invalid $call converted to $ncall");
284 $msg =~ s/$call/$ncall/;
287 # is it a valid callsign (in format)?
288 unless (is_callsign($call)) {
289 already_conn($conn, $call, DXM::msg($lang, "illcall", $call));
296 $user = DXUser::get_current($call);
297 my $basecall = $call;
298 $basecall =~ s/-\d+$//; # remember this for later multiple user processing, it's used for other stuff than checking lockout status
300 # make sure we act on any locked status that the actual incoming call has.
301 $lock = $user->lockout;
302 } elsif ($basecall ne $call) {
303 # if there isn't a SSID on the $call, then try the base
304 my $luser = DXUser::get_current($basecall);
305 $lock = $luser->lockout if $luser;
308 # now deal with the lock
310 my $host = $conn->peerhost;
311 LogDbg('', "$call on $host is locked out, disconnected");
316 # set up the basic channel info for "Normal" Users
317 # is there one already connected to me - locally?
319 $dxchan = DXChannel::get($call);
322 if ($user && $user->is_node) {
323 already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
326 if ($allowmultiple && $user->is_user) {
327 # determine whether we are a candidate, have we flip-flopped frequently enough?
328 my @lastconns = @{$user->connlist} if $user->connlist;
330 if (@lastconns >= $DXUser::maxconnlist) {
331 $allow = $lastconns[-1]->[0] - $lastconns[0]->[0] < $min_reconnection_rate;
333 # search for a spare ssid
334 L1: for (my $count = $call =~ /-\d+$/?0:1; $allow && $count < $allowmultiple; ) { # remember we have one call already
336 for (; $lastid < $max_ssid && $count < $allowmultiple; ++$lastid) {
337 my $chan = DXChannel::get("$basecall-$lastid");
342 # we have a free call-ssid, save it
343 $newcall = "$basecall-$lastid";
349 # handle "normal" (non-multiple) connections in the existing way
350 if ($call eq $newcall) {
352 my $ip = $dxchan->hostname;
353 $dxchan->send_now('D', DXM::msg($lang, 'conbump', $call, $ip));
354 LogDbg('', "$call bumped off by $ip, disconnected");
357 already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
362 # make sure that the conn has the (possibly) new callsign
363 $conn->conns($newcall);
364 $msg =~ s/$call/$newcall/;
368 # (fairly) politely disconnect people that are connected to too many other places at once
369 my $r = Route::get($call);
370 if ($conn->{sort} && $conn->{sort} =~ /^I/ && $r && $user) {
372 my $m = $r->isa('Route::Node') ? $maxconnect_node : $maxconnect_user;
373 my $c = $user->maxconnect;
375 $v = defined $c ? $c : $m;
376 if ($v && @n >= $v+$allowmultiple) {
377 my $nodes = join ',', @n;
378 LogDbg('', "$call has too many connections ($v) at $nodes - disconnected");
379 already_conn($conn, $call, DXM::msg($lang, 'contomany', $call, $v, $nodes));
385 $user->{lang} = $main::lang if !$user->{lang}; # to autoupdate old systems
387 $user = DXUser->new($call);
391 # NOTE we are SHARING the same $user if $allowmultiple is > 1
393 $user->startt($systime); # mark the start time of this connection
394 if ($user->is_node) {
395 $dxchan = DXProt->new($call, $conn, $user);
396 } elsif ($user->is_rbn) {
397 $dxchan = RBN->new($newcall, $conn, $user);
398 } elsif ($user->is_user) {
399 $dxchan = DXCommandmode->new($newcall, $conn, $user);
401 die "Invalid sort of user on $call = $sort";
407 $conn->set_error(sub {my $err = shift; LogDbg('', "Comms error '$err' received for call $dxchan->{call}"); $dxchan->disconnect(1);});
408 $conn->set_on_eof(sub {$dxchan->disconnect});
409 $conn->set_rproc(sub {my ($conn,$msg) = @_; $dxchan->rec($msg);});
411 $dxchan->enhanced(1);
420 return \&new_channel;
425 # cease running this program, close down all the connections nicely
430 cluck("ceasing") if $ceasing;
432 return if $ceasing++;
435 $SIG{'TERM'} = 'IGNORE';
436 $SIG{'INT'} = 'IGNORE';
440 if (defined &Local::finish) {
442 Local::finish(); # end local processing
444 dbg("Local::finish error $@") if $@;
452 # disconnect UDP customers
455 # end everything else
460 # close all databases
463 # close all listeners
464 foreach my $l (@listeners) {
468 LogDbg('cluster', "DXSpider v$version build $build (git: $gitbranch/$gitversion) using perl $^V on $^O ended");
469 dbg("bye bye everyone - bye bye");
473 $dbh->finish if $dbh;
478 # the reaper of children
482 while (($cpid = waitpid(-1, WNOHANG)) > 0) {
483 dbg("cpid: $cpid") if isdbg('reap');
484 # Msg->pid_gone($cpid);
485 $zombies-- if $zombies > 0;
487 dbg("cpid: $cpid") if isdbg('reap');
490 # this is where the input queue is dealt with and things are dispatched off to other parts of
495 my $t = $systime - $starttime;
496 my $days = int $t / 86400;
498 my $hours = int $t / 3600;
500 my $mins = int $t / 60;
501 return sprintf "%d %02d:%02d", $days, $hours, $mins;
506 AGWMsg::init(\&new_channel);
512 #############################################################
514 # The start of the main line of code
516 #############################################################
520 $starttime = $systime = time;
521 $systime_days = int ($systime / 86400);
522 $systime_daystart = $systime_days * 86400;
523 $lang = 'en' unless $lang;
525 unless ($DB::VERSION) {
526 $SIG{INT} = $SIG{TERM} = \&cease;
529 # open the debug file, set various FHs to be unbuffered
530 dbginit(undef, $broadcast_debug ? \&DXCommandmode::broadcast_debug : undef);
534 STDOUT->autoflush(1);
537 dbg "Perl path: " . join(':', @INC);
539 # try to load the database
540 if (DXSql::init($dsn)) {
541 $dbh = DXSql->new($dsn);
542 $dbh = $dbh->connect($dsn, $dbuser, $dbpass) if $dbh;
545 # try to load Encode and Git
548 my $w = $SIG{__DIE__};
549 $SIG{__DIE__} = 'IGNORE';
550 eval { require Encode; };
557 $gitversion = 'none';
559 # determine the real Git build number and branch
561 eval {$desc = `git --git-dir=$root/.git describe --long`};
563 my ($v, $s, $b, $g) = $desc =~ /^([\d\.]+)(?:\.(\d+))?-(\d+)-g([0-9a-f]+)/;
565 my $subversion = $s || 0; # not used elsewhere
567 $gitversion = "$g\[r]";
572 eval {@branch = `git --git-dir=$root/.git branch`};
575 my ($star, $b) = split /\s+/;
588 # setup location of motd & issue
590 $motd = localdata($motd);
591 localdata_mv("issue");
594 # try to load XML::Simple
598 my ($year) = (gmtime)[5];
600 LogDbg('cluster', "DXSpider v$version build $build (git: $gitbranch/$gitversion) using perl $^V on $^O started");
601 dbg("Copyright (c) 1998-$year Dirk Koopman G1TLH");
604 dbg("loading prefixes ...");
606 my $r = Prefix::init();
610 dbg("loading band data ...");
613 # initialise User file system
614 dbg("loading user file system ...");
615 DXUser::init(4); # version 4 == json format
617 Filter::init(); # doesn't do much, but has to be done
619 AnnTalk::init(); # initialise announce cache
623 # look for the sysop and the alias user and complain if they aren't there
625 die "\$myalias \& \$mycall are the same ($mycall)!, they must be different (hint: make \$mycall = '${mycall}-2';). Oh and don't forget to rerun create_sysop.pl!" if $mycall eq $myalias;
626 my $ref = DXUser::get($mycall);
627 die "$mycall missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
628 my $oldsort = $ref->sort;
629 if ($oldsort ne 'S') {
631 dbg("Resetting node type from $oldsort -> DXSpider ('S')");
633 $ref = DXUser::get($myalias);
634 die "$myalias missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
635 $oldsort = $ref->sort;
636 if ($oldsort ne 'U') {
638 dbg("Resetting sysop user type from $oldsort -> User ('U')");
643 # start listening for incoming messages/connects
644 dbg("starting listeners ...");
645 my $conn = IntMsg->new_server($clusteraddr, $clusterport, \&login);
646 $conn->conns("Server $clusteraddr/$clusterport using IntMsg");
647 push @listeners, $conn;
648 dbg("Internal port: $clusteraddr $clusterport using IntMsg");
649 foreach my $l (@main::listen) {
651 my $pkg = $l->[2] || 'ExtMsg';
652 my $login = $l->[3] || 'login';
654 $conn = $pkg->new_server($l->[0], $l->[1], \&{"${pkg}::${login}"});
655 $conn->conns("Server $l->[0]/$l->[1] using ${pkg}::${login}");
656 push @listeners, $conn;
657 dbg("External Port: $l->[0] $l->[1] using ${pkg}::${login}");
661 dbg("AGW Listener") if $AGWMsg::enable;
664 dbg("BPQ Listener") if $BPQMsg::enable;
665 BPQMsg::init(\&new_channel);
667 dbg("UDP Listener") if $UDPMsg::enable;
668 UDPMsg::init(\&new_channel);
671 dbg("load badwords: " . (BadWords::load or "Ok"));
674 unless ($DB::VERSION) {
675 $SIG{INT} = $SIG{TERM} = sub { $ending = 10; };
682 $SIG{HUP} = 'IGNORE';
683 $SIG{CHLD} = sub { $zombies++ };
685 $SIG{PIPE} = sub { dbg("Broken PIPE signal received"); };
686 $SIG{IO} = sub { dbg("SIGIO received"); };
687 $SIG{WINCH} = $SIG{STOP} = $SIG{CONT} = 'IGNORE';
688 $SIG{KILL} = 'DEFAULT'; # as if it matters....
690 # catch the rest with a hopeful message
693 # dbg("Catching SIG $_") if isdbg('chan');
694 $SIG{$_} = sub { my $sig = shift; DXDebug::confess("Caught signal $sig"); };
700 dbg("Starting Dupe system");
703 # read in system messages
704 dbg("Read in Messages");
707 # read in command aliases
708 dbg("Read in Aliases");
711 # initialise the Geomagnetic data engine
717 # initialise the protocol engine
718 dbg("Start Protocol Engines ...");
721 # read startup script
722 my $script = new Script "startup";
723 $script->run($main::me) if $script;
725 # put in a DXCluster node for us here so we can add users and take them away
726 $routeroot = Route::Node->new($mycall, $version*100+5300, Route::here($main::me->here)|Route::conf($main::me->conf));
727 $routeroot->do_pc9x(1);
728 $routeroot->via_pc92(1);
730 # make sure that there is a routing OUTPUT node default file
731 #unless (Filter::read_in('route', 'node_default', 0)) {
732 # my $dxcc = $main::me->dxcc;
733 # $Route::filterdef->cmd($main::me, 'route', 'accept', "node_default call $mycall" );
736 # initial the Spot stuff
737 dbg("Starting DX Spot system");
740 # read in any existing message headers and clean out old crap
741 dbg("reading existing message headers ...");
745 # read in any cron jobs
746 dbg("reading cron jobs ...");
749 # read in database desriptors
750 dbg("reading database descriptors ...");
753 dbg("starting RBN ...");
756 # starting local stuff
757 dbg("doing local initialisation ...");
759 if (defined &Local::init) {
763 dbg("Local::init error $@") if $@;
767 # this, such as it is, is the main loop!
768 dbg("orft we jolly well go ...");
770 #open(DB::OUT, "|tee /tmp/aa");
773 our $io_disconnected;
778 # DXCommandmode::process(); # process ongoing command mode stuff
779 # DXProt::process(); # process ongoing ak1a pcxx stuff
781 if (defined &Local::process) {
783 Local::process(); # do any localised processing
785 dbg("Local::process error $@") if $@;
791 dbg("DXSpider Ending $ending");
793 unless ($io_disconnected++) {
796 foreach $dxchan (DXChannel::get_all_users) {
801 foreach $dxchan (DXChannel::get_all_nodes) {
802 next if $dxchan == $main::me;
803 $dxchan->disconnect(2);
805 $main::me->disconnect;
808 Mojo::IOLoop->stop_gracefully if --$ending <= 0;
818 my $days = int ($systime / 86400);
819 if ($systime_days != $days) {
820 $systime_days = $days;
821 $systime_daystart = $days * 86400;
823 IsoTime::update($systime);
824 DXCommandmode::process(); # process ongoing command mode stuff
825 DXProt::process(); # process ongoing ak1a pcxx stuff
827 DXConnect::process();
832 IsoTime::update($systime);
833 DXConnect::process();
836 DXCron::process(); # do cron jobs
855 RBN::per_10_minute();
870 dbg("Before Web::start_node");
872 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
874 dbg("After Web::start_node");
880 my $main_loop = Mojo::IOLoop->recurring($idle_interval => \&idle_loop);
881 my $log_flush_loop = Mojo::IOLoop->recurring($log_flush_interval => \&DXLog::flushall);
882 my $cpusecs_loop = Mojo::IOLoop->recurring(5 => sub {my @t = times; $clssecs = $t[0]+$t[1]; $cldsecs = $t[2]+$t[3]});
883 my $persec = Mojo::IOLoop->recurring(1 => \&per_sec);
884 my $per10sec = Mojo::IOLoop->recurring(10 => \&per_10_sec);
885 my $permin = Mojo::IOLoop->recurring(60 => \&per_minute);
886 my $per10min = Mojo::IOLoop->recurring(600 => \&per_10_minute);
887 my $perhour = Mojo::IOLoop->recurring(3600 => \&per_hour);
888 my $perday = Mojo::IOLoop->recurring(86400 => \&per_day);