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
18 use vars qw($root $is_win $systime $lockfn @inqueue $starttime $lockfn @outstanding_connects
19 $zombies @listeners $lang $myalias @debug $userfn $clusteraddr
20 $clusterport $mycall $decease $routeroot $me $reqreg $bumpexisting
21 $allowdxby $dbh $dsn $dbuser $dbpass $do_xml $systime_days $systime_daystart
22 $can_encode $maxconnect_user $maxconnect_node $idle_interval $log_flush_interval
26 $lang = 'en'; # default language
27 $clusteraddr = '127.0.0.1'; # cluster tcp host address - used for things like console.pl
28 $clusterport = 27754; # cluster tcp port
29 $yes = 'Yes'; # visual representation of yes
30 $no = 'No'; # ditto for no
31 $user_interval = 11*60; # the interval between unsolicited prompts if no traffic
33 # make sure that modules are searched in the order local then perl
37 # take into account any local::lib that might be present
41 import local::lib unless ($@);
43 # root of directory tree for this system
45 $root = $ENV{'DXSPIDER_ROOT'} if $ENV{'DXSPIDER_ROOT'};
47 unshift @INC, "$root/perl"; # this IS the right way round!
48 unshift @INC, "$root/local";
50 # do some validation of the input
51 die "The directory $root doesn't exist, please RTFM" unless -d $root;
52 die "$root/local doesn't exist, please RTFM" unless -d "$root/local";
53 die "$root/local/DXVars.pm doesn't exist, please RTFM" unless -e "$root/local/DXVars.pm";
55 # create some directories
56 mkdir "$root/local_cmd", 02774 unless -d "$root/local_cmd";
58 # locally stored data lives here
59 my $local_data = "$root/local_data";
60 mkdir $local_data, 02774 unless -d $local_data;
62 # try to create and lock a lockfile (this isn't atomic but
64 $lockfn = "$root/local_data/cluster.lck"; # lock file name
66 open(CLLOCK, "$lockfn") or die "Can't open Lockfile ($lockfn) $!";
71 warn "Lockfile ($lockfn) and process $pid exist, another cluster running?\n";
78 open(CLLOCK, ">$lockfn") or die "Can't open Lockfile ($lockfn) $!";
82 $is_win = ($^O =~ /^MS/ || $^O =~ /^OS-2/) ? 1 : 0; # is it Windows?
92 # order here is important - DXDebug snarfs Carp et al so that Mojo errors go into the debug log
155 use POSIX ":sys_wait_h";
162 @inqueue = (); # the main input queue, an array of hashes
163 $systime = 0; # the time now (in seconds)
164 $starttime = 0; # the starting time of the cluster
165 @outstanding_connects = (); # list of outstanding connects
166 @listeners = (); # list of listeners
167 $reqreg = 0; # 1 = registration required, 2 = deregister people
168 $bumpexisting = 1; # 1 = allow new connection to disconnect old, 0 - don't allow it
169 our $allowmultiple = 0; # This is used in conjunction with $bumpexisting, in a rather weird way.
170 our $min_reconnection_rate = 5*60; # minimum value of seconds between connections per user to allow co-existing users
171 our $max_ssid = 15; # highest ssid to be searched for a spare one on multiple connections
173 # If $allowmultiple > 0 and the $reconnection_rate is some value of seconds
174 # based on the average connection time calculated from the $user->conntimel entries / frequency is
175 # less than $reconnection_rate then we assume that there is more than one device (probably HRD) trying
176 # to connect "at once". In which case we probe for a spare SSID for a user callsign to allow up to
177 # $allowmultiple connections per callsign.
179 $allowdxby = 0; # 1 = allow "dx by <othercall>", 0 - don't allow it
180 $maxconnect_user = 3; # the maximum no of concurrent connections a user can have at a time
181 $maxconnect_node = 0; # Ditto but for nodes. In either case if a new incoming connection
182 # takes the no of references in the routing table above these numbers
183 # then the connection is refused. This only affects INCOMING connections.
184 $idle_interval = 0.500; # the wait between invocations of the main idle loop processing.
185 $log_flush_interval = 2; # interval to wait between log flushes
187 our $ending; # signal that we are ending;
188 our $broadcast_debug; # allow broadcasting of debug info down "enhanced" user connections
189 our $clssecs; # the amount of cpu time the DXSpider process have consumed
190 our $cldsecs; # the amount of cpu time any child processes have consumed
193 # send a message to call on conn and disconnect
196 my ($conn, $call, $mess) = @_;
198 $conn->disable_read(1);
199 dbg("-> D $call $mess\n") if isdbg('chan');
200 $conn->send_now("D$call|$mess");
205 # handle incoming messages
208 my ($conn, $msg) = @_;
209 my ($sort, $call, $line) = DXChannel::decode_input(0, $msg);
210 return unless defined $sort;
214 if (is_webcall($call) && $conn->isa('IntMsg')) {
215 my $newcall = find_next_webcall();
217 already_conn($conn, $call, "Maximum no of web connected connects ($Web::maxssid) exceeded");
221 $user = DXUser::get_current($call);
223 $user = DXUser->new($call);
227 $user->qth('on the web');
228 $user->homenode($main::mycall);
229 $user->lat($main::mylatitude);
230 $user->long($main::mylongitude);
231 $user->qra($main::mylocator);
233 $user->startt($main::systime);
235 $dxchan = Web->new($call, $conn, $user);
236 $dxchan->enhanced(1);
238 $msg =~ s/^A#WEB|/A$call|/;
239 $conn->send_now("C$call");
241 # "Normal" connections
242 unless (is_callsign($call)) {
243 already_conn($conn, $call, DXM::msg($lang, "illcall", $call));
248 my $basecall = $call;
249 $basecall =~ s/-\d+$//; # remember this for later multiple user processing
250 my $baseuser = DXUser::get_current($basecall);
251 my $lock = $user->lockout if $user;
252 if ($baseuser && $baseuser->lockout || $lock) {
253 if (!$user || !defined $lock || $lock) {
254 my $host = $conn->peerhost;
255 LogDbg('DXCommand', "$call on $host is locked out, disconnected");
261 # set up the basic channel info for "Normal" Users
262 # is there one already connected to me - locally?
264 $user = DXUser::get_current($call);
265 $dxchan = DXChannel::get($call);
268 if ($user && $user->is_node) {
269 already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
272 if ($allowmultiple && $user->is_user) {
273 # determine whether we are a candidate, have we flip-flopped frequently enough?
274 my @lastconns = @{$user->connlist} if $user->connlist;
276 if (@lastconns >= $DXUser::maxconnlist) {
277 $allow = $lastconns[-1]->[0] - $lastconns[0]->[0] < $min_reconnection_rate;
279 # search for a spare ssid
280 L1: for (my $count = $call =~ /-\d+$/?0:1; $allow && $count < $allowmultiple; ) { # remember we have one call already
282 for (; $lastid < $max_ssid && $count < $allowmultiple; ++$lastid) {
283 my $chan = DXChannel::get("$basecall-$lastid");
288 # we have a free call-ssid, save it
289 $newcall = "$basecall-$lastid";
295 # handle "normal" (non-multiple) connections in the existing way
296 if ($call eq $newcall) {
298 my $ip = $dxchan->hostname;
299 $dxchan->send_now('D', DXM::msg($lang, 'conbump', $call, $ip));
300 LogDbg('DXCommand', "$call bumped off by $ip, disconnected");
303 already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
308 # make sure that the conn has the (possibly) new callsign
309 $conn->conns($newcall);
310 $msg =~ s/$call/$newcall/;
314 # (fairly) politely disconnect people that are connected to too many other places at once
315 my $r = Route::get($call);
316 if ($conn->{sort} && $conn->{sort} =~ /^I/ && $r && $user) {
318 my $m = $r->isa('Route::Node') ? $maxconnect_node : $maxconnect_user;
319 my $c = $user->maxconnect;
321 $v = defined $c ? $c : $m;
322 if ($v && @n >= $v+$allowmultiple) {
323 my $nodes = join ',', @n;
324 LogDbg('DXCommand', "$call has too many connections ($v) at $nodes - disconnected");
325 already_conn($conn, $call, DXM::msg($lang, 'contomany', $call, $v, $nodes));
331 $user->{lang} = $main::lang if !$user->{lang}; # to autoupdate old systems
333 $user = DXUser->new($call);
337 # NOTE we are SHARING the same $user if $allowmultiple is > 1
339 $user->startt($systime); # mark the start time of this connection
340 if ($user->is_node) {
341 $dxchan = DXProt->new($call, $conn, $user);
342 } elsif ($user->is_user) {
343 $dxchan = DXCommandmode->new($newcall, $conn, $user);
345 die "Invalid sort of user on $call = $sort";
351 $conn->set_error(sub {my $err = shift; LogDbg('DXCommand', "Comms error '$err' received for call $dxchan->{call}"); $dxchan->disconnect(1);});
352 $conn->set_on_eof(sub {$dxchan->disconnect});
353 $conn->set_rproc(sub {my ($conn,$msg) = @_; $dxchan->rec($msg);});
355 $dxchan->enhanced(1);
364 return \&new_channel;
369 # cease running this program, close down all the connections nicely
374 cluck("ceasing") if $ceasing;
376 return if $ceasing++;
379 $SIG{'TERM'} = 'IGNORE';
380 $SIG{'INT'} = 'IGNORE';
384 DXUser::writeoutjson;
386 if (defined &Local::finish) {
388 Local::finish(); # end local processing
390 dbg("Local::finish error $@") if $@;
398 # disconnect UDP customers
401 # end everything else
405 # close all databases
408 # close all listeners
409 foreach my $l (@listeners) {
413 LogDbg('cluster', "DXSpider V$version, build $build (git: $gitversion) ended");
414 dbg("bye bye everyone - bye bye");
418 $dbh->finish if $dbh;
423 # the reaper of children
427 while (($cpid = waitpid(-1, WNOHANG)) > 0) {
428 dbg("cpid: $cpid") if isdbg('reap');
429 # Msg->pid_gone($cpid);
430 $zombies-- if $zombies > 0;
432 dbg("cpid: $cpid") if isdbg('reap');
435 # this is where the input queue is dealt with and things are dispatched off to other parts of
440 my $t = $systime - $starttime;
441 my $days = int $t / 86400;
443 my $hours = int $t / 3600;
445 my $mins = int $t / 60;
446 return sprintf "%d %02d:%02d", $days, $hours, $mins;
451 AGWMsg::init(\&new_channel);
458 #############################################################
460 # The start of the main line of code
462 #############################################################
464 $starttime = $systime = time;
465 $systime_days = int ($systime / 86400);
466 $systime_daystart = $systime_days * 86400;
467 $lang = 'en' unless $lang;
469 unless ($DB::VERSION) {
470 $SIG{INT} = $SIG{TERM} = \&cease;
473 # open the debug file, set various FHs to be unbuffered
474 dbginit($broadcast_debug ? \&DXCommandmode::broadcast_debug : undef);
478 STDOUT->autoflush(1);
481 # try to load the database
482 if (DXSql::init($dsn)) {
483 $dbh = DXSql->new($dsn);
484 $dbh = $dbh->connect($dsn, $dbuser, $dbpass) if $dbh;
487 # try to load Encode and Git
490 my $w = $SIG{__DIE__};
491 $SIG{__DIE__} = 'IGNORE';
492 eval { require Encode; };
497 eval { require Git; };
501 # determine the real version number
502 my $repo = Git->repository(Directory => "$root/.git");
504 my $desc = $repo->command_oneline(['describe', '--long'], STDERR => 0);
506 my ($v, $s, $b, $g) = $desc =~ /^([\d.]+)(?:\.(\d+))?-(\d+)-g([0-9a-f]+)/;
509 dbg("Git: V=$v S=$s B=$b g=$g");
512 $gitversion = "$g\[r]";
519 # try to load XML::Simple
523 my ($year) = (gmtime)[5];
525 LogDbg('cluster', "DXSpider V$version, build $build (git: $gitversion) started");
526 dbg("Copyright (c) 1998-$year Dirk Koopman G1TLH");
529 dbg("loading prefixes ...");
531 my $r = Prefix::init();
535 dbg("loading band data ...");
538 # initialise User file system
539 dbg("loading user file system ...");
540 DXUser::init(4); # version 4 == json format
542 # look for the sysop and the alias user and complain if they aren't there
544 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;
545 my $ref = DXUser::get($mycall);
546 die "$mycall missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
547 my $oldsort = $ref->sort;
548 if ($oldsort ne 'S') {
550 dbg "Resetting node type from $oldsort -> DXSpider ('S')";
552 $ref = DXUser::get($myalias);
553 die "$myalias missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
554 $oldsort = $ref->sort;
555 if ($oldsort ne 'U') {
557 dbg "Resetting sysop user type from $oldsort -> User ('U')";
561 # start listening for incoming messages/connects
562 dbg("starting listeners ...");
563 my $conn = IntMsg->new_server($clusteraddr, $clusterport, \&login);
564 $conn->conns("Server $clusteraddr/$clusterport using IntMsg");
565 push @listeners, $conn;
566 dbg("Internal port: $clusteraddr $clusterport using IntMsg");
567 foreach my $l (@main::listen) {
569 my $pkg = $l->[2] || 'ExtMsg';
570 my $login = $l->[3] || 'login';
572 $conn = $pkg->new_server($l->[0], $l->[1], \&{"${pkg}::${login}"});
573 $conn->conns("Server $l->[0]/$l->[1] using ${pkg}::${login}");
574 push @listeners, $conn;
575 dbg("External Port: $l->[0] $l->[1] using ${pkg}::${login}");
578 dbg("AGW Listener") if $AGWMsg::enable;
581 dbg("BPQ Listener") if $BPQMsg::enable;
582 BPQMsg::init(\&new_channel);
584 dbg("UDP Listener") if $UDPMsg::enable;
585 UDPMsg::init(\&new_channel);
588 dbg("load badwords: " . (BadWords::load or "Ok"));
591 unless ($DB::VERSION) {
592 $SIG{INT} = $SIG{TERM} = sub { $ending = 10; };
596 $SIG{HUP} = 'IGNORE';
597 $SIG{CHLD} = sub { $zombies++ };
599 $SIG{PIPE} = sub { dbg("Broken PIPE signal received"); };
600 $SIG{IO} = sub { dbg("SIGIO received"); };
601 $SIG{WINCH} = $SIG{STOP} = $SIG{CONT} = 'IGNORE';
602 $SIG{KILL} = 'DEFAULT'; # as if it matters....
604 # catch the rest with a hopeful message
607 # dbg("Catching SIG $_") if isdbg('chan');
608 $SIG{$_} = sub { my $sig = shift; DXDebug::confess("Caught signal $sig"); };
614 dbg("Starting Dupe system");
617 # read in system messages
618 dbg("Read in Messages");
621 # read in command aliases
622 dbg("Read in Aliases");
625 # initialise the Geomagnetic data engine
631 # initial the Spot stuff
632 dbg("Starting DX Spot system");
635 # initialise the protocol engine
636 dbg("Start Protocol Engines ...");
639 # put in a DXCluster node for us here so we can add users and take them away
640 $routeroot = Route::Node->new($mycall, $version*100+5300, Route::here($main::me->here)|Route::conf($main::me->conf));
641 $routeroot->do_pc9x(1);
642 $routeroot->via_pc92(1);
644 # make sure that there is a routing OUTPUT node default file
645 #unless (Filter::read_in('route', 'node_default', 0)) {
646 # my $dxcc = $main::me->dxcc;
647 # $Route::filterdef->cmd($main::me, 'route', 'accept', "node_default call $mycall" );
650 # read in any existing message headers and clean out old crap
651 dbg("reading existing message headers ...");
655 # read in any cron jobs
656 dbg("reading cron jobs ...");
659 # read in database desriptors
660 dbg("reading database descriptors ...");
663 # starting local stuff
664 dbg("doing local initialisation ...");
666 if (defined &Local::init) {
670 dbg("Local::init error $@") if $@;
674 # this, such as it is, is the main loop!
675 dbg("orft we jolly well go ...");
676 my $script = new Script "startup";
677 $script->run($main::me) if $script;
679 #open(DB::OUT, "|tee /tmp/aa");
682 our $io_disconnected;
687 # DXCommandmode::process(); # process ongoing command mode stuff
688 # DXProt::process(); # process ongoing ak1a pcxx stuff
690 if (defined &Local::process) {
692 Local::process(); # do any localised processing
694 dbg("Local::process error $@") if $@;
700 dbg("DXSpider Ending $ending");
702 unless ($io_disconnected++) {
705 foreach $dxchan (DXChannel::get_all_users) {
710 foreach $dxchan (DXChannel::get_all_nodes) {
711 next if $dxchan == $main::me;
712 $dxchan->disconnect(2);
714 $main::me->disconnect;
717 Mojo::IOLoop->stop if --$ending <= 0;
727 my $days = int ($systime / 86400);
728 if ($systime_days != $days) {
729 $systime_days = $days;
730 $systime_daystart = $days * 86400;
732 IsoTime::update($systime);
733 DXCommandmode::process(); # process ongoing command mode stuff
734 DXProt::process(); # process ongoing ak1a pcxx stuff
735 DXCron::process(); # do cron jobs
737 DXConnect::process();
742 DXCron::process(); # do cron jobs
743 IsoTime::update($systime);
744 DXConnect::process();
780 dbg("Before Web::start_node");
782 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
784 dbg("After Web::start_node");
789 my $main_loop = Mojo::IOLoop->recurring($idle_interval => \&idle_loop);
790 my $log_flush_loop = Mojo::IOLoop->recurring($log_flush_interval => \&DXLog::flushall);
791 my $cpusecs_loop = Mojo::IOLoop->recurring(5 => sub {my @t = times; $clssecs = $t[0]+$t[1]; $cldsecs = $t[2]+$t[3]});
792 my $persec = Mojo::IOLoop->recurring(1 => \&per_sec);
793 my $per10sec = Mojo::IOLoop->recurring(10 => \&per_10_sec);
794 my $permin = Mojo::IOLoop->recurring(60 => \&per_minute);
795 my $per10min = Mojo::IOLoop->recurring(600 => \&per_10_minute);
796 my $perhour = Mojo::IOLoop->recurring(3600 => \&per_hour);
797 my $perday = Mojo::IOLoop->recurring(86400 => \&per_day);