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";
158 use vars qw($version $build $gitversion $gitbranch);
163 @inqueue = (); # the main input queue, an array of hashes
164 $systime = 0; # the time now (in seconds)
165 $starttime = 0; # the starting time of the cluster
166 @outstanding_connects = (); # list of outstanding connects
167 @listeners = (); # list of listeners
168 $reqreg = 0; # 1 = registration required, 2 = deregister people
169 $bumpexisting = 1; # 1 = allow new connection to disconnect old, 0 - don't allow it
170 our $allowmultiple = 0; # This is used in conjunction with $bumpexisting, in a rather weird way.
171 our $min_reconnection_rate = 5*60; # minimum value of seconds between connections per user to allow co-existing users
172 our $max_ssid = 15; # highest ssid to be searched for a spare one on multiple connections
174 # If $allowmultiple > 0 and the $reconnection_rate is some value of seconds
175 # based on the average connection time calculated from the $user->conntimel entries / frequency is
176 # less than $reconnection_rate then we assume that there is more than one device (probably HRD) trying
177 # to connect "at once". In which case we probe for a spare SSID for a user callsign to allow up to
178 # $allowmultiple connections per callsign.
180 $allowdxby = 0; # 1 = allow "dx by <othercall>", 0 - don't allow it
181 $maxconnect_user = 3; # the maximum no of concurrent connections a user can have at a time
182 $maxconnect_node = 0; # Ditto but for nodes. In either case if a new incoming connection
183 # takes the no of references in the routing table above these numbers
184 # then the connection is refused. This only affects INCOMING connections.
185 $idle_interval = 0.500; # the wait between invocations of the main idle loop processing.
186 $log_flush_interval = 2; # interval to wait between log flushes
188 our $ending; # signal that we are ending;
189 our $broadcast_debug; # allow broadcasting of debug info down "enhanced" user connections
190 our $clssecs; # the amount of cpu time the DXSpider process have consumed
191 our $cldsecs; # the amount of cpu time any child processes have consumed
194 # send a message to call on conn and disconnect
197 my ($conn, $call, $mess) = @_;
199 $conn->disable_read(1);
200 dbg("-> D $call $mess\n") if isdbg('chan');
201 $conn->send_now("D$call|$mess");
206 # handle incoming messages
209 my ($conn, $msg) = @_;
210 my ($sort, $call, $line) = DXChannel::decode_input(0, $msg);
211 return unless defined $sort;
215 if (is_webcall($call) && $conn->isa('IntMsg')) {
216 my $newcall = find_next_webcall();
218 already_conn($conn, $call, "Maximum no of web connected connects ($Web::maxssid) exceeded");
222 $user = DXUser::get_current($call);
224 $user = DXUser->new($call);
228 $user->qth('on the web');
229 $user->homenode($main::mycall);
230 $user->lat($main::mylatitude);
231 $user->long($main::mylongitude);
232 $user->qra($main::mylocator);
234 $user->startt($main::systime);
236 $dxchan = Web->new($call, $conn, $user);
237 $dxchan->enhanced(1);
239 $msg =~ s/^A#WEB|/A$call|/;
240 $conn->send_now("C$call");
242 # "Normal" connections
243 unless (is_callsign($call)) {
244 already_conn($conn, $call, DXM::msg($lang, "illcall", $call));
249 $user = DXUser::get_current($call);
250 my $basecall = $call;
251 $basecall =~ s/-\d+$//; # remember this for later multiple user processing
254 # make sure we act on any locked status that the actual incoming call has.
255 $lock = $user->lockout;
256 } elsif ($allowmultiple && $call ne $basecall) {
257 # if we are allowing multiple connections and there is a basecall minus incoming ssid, use the basecall's lock status
258 $user = DXUser::get_current($basecall);
259 $lock = $user->lockout if $user;
262 # now deal with the lock
264 my $host = $conn->peerhost;
265 LogDbg('', "$call on $host is locked out, disconnected");
270 # set up the basic channel info for "Normal" Users
271 # is there one already connected to me - locally?
273 $dxchan = DXChannel::get($call);
276 if ($user && $user->is_node) {
277 already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
280 if ($allowmultiple && $user->is_user) {
281 # determine whether we are a candidate, have we flip-flopped frequently enough?
282 my @lastconns = @{$user->connlist} if $user->connlist;
284 if (@lastconns >= $DXUser::maxconnlist) {
285 $allow = $lastconns[-1]->[0] - $lastconns[0]->[0] < $min_reconnection_rate;
287 # search for a spare ssid
288 L1: for (my $count = $call =~ /-\d+$/?0:1; $allow && $count < $allowmultiple; ) { # remember we have one call already
290 for (; $lastid < $max_ssid && $count < $allowmultiple; ++$lastid) {
291 my $chan = DXChannel::get("$basecall-$lastid");
296 # we have a free call-ssid, save it
297 $newcall = "$basecall-$lastid";
303 # handle "normal" (non-multiple) connections in the existing way
304 if ($call eq $newcall) {
306 my $ip = $dxchan->hostname;
307 $dxchan->send_now('D', DXM::msg($lang, 'conbump', $call, $ip));
308 LogDbg('', "$call bumped off by $ip, disconnected");
311 already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
316 # make sure that the conn has the (possibly) new callsign
317 $conn->conns($newcall);
318 $msg =~ s/$call/$newcall/;
322 # (fairly) politely disconnect people that are connected to too many other places at once
323 my $r = Route::get($call);
324 if ($conn->{sort} && $conn->{sort} =~ /^I/ && $r && $user) {
326 my $m = $r->isa('Route::Node') ? $maxconnect_node : $maxconnect_user;
327 my $c = $user->maxconnect;
329 $v = defined $c ? $c : $m;
330 if ($v && @n >= $v+$allowmultiple) {
331 my $nodes = join ',', @n;
332 LogDbg('', "$call has too many connections ($v) at $nodes - disconnected");
333 already_conn($conn, $call, DXM::msg($lang, 'contomany', $call, $v, $nodes));
339 $user->{lang} = $main::lang if !$user->{lang}; # to autoupdate old systems
341 $user = DXUser->new($call);
345 # NOTE we are SHARING the same $user if $allowmultiple is > 1
347 $user->startt($systime); # mark the start time of this connection
348 if ($user->is_node) {
349 $dxchan = DXProt->new($call, $conn, $user);
350 } elsif ($user->is_user) {
351 $dxchan = DXCommandmode->new($newcall, $conn, $user);
353 die "Invalid sort of user on $call = $sort";
359 $conn->set_error(sub {my $err = shift; LogDbg('', "Comms error '$err' received for call $dxchan->{call}"); $dxchan->disconnect(1);});
360 $conn->set_on_eof(sub {$dxchan->disconnect});
361 $conn->set_rproc(sub {my ($conn,$msg) = @_; $dxchan->rec($msg);});
363 $dxchan->enhanced(1);
372 return \&new_channel;
377 # cease running this program, close down all the connections nicely
382 cluck("ceasing") if $ceasing;
384 return if $ceasing++;
387 $SIG{'TERM'} = 'IGNORE';
388 $SIG{'INT'} = 'IGNORE';
392 if (defined &Local::finish) {
394 Local::finish(); # end local processing
396 dbg("Local::finish error $@") if $@;
404 # disconnect UDP customers
407 # end everything else
411 # close all databases
414 # close all listeners
415 foreach my $l (@listeners) {
419 LogDbg('cluster', "DXSpider V$version, build $build (git: $gitbranch/$gitversion) ended");
420 dbg("bye bye everyone - bye bye");
424 $dbh->finish if $dbh;
429 # the reaper of children
433 while (($cpid = waitpid(-1, WNOHANG)) > 0) {
434 dbg("cpid: $cpid") if isdbg('reap');
435 # Msg->pid_gone($cpid);
436 $zombies-- if $zombies > 0;
438 dbg("cpid: $cpid") if isdbg('reap');
441 # this is where the input queue is dealt with and things are dispatched off to other parts of
446 my $t = $systime - $starttime;
447 my $days = int $t / 86400;
449 my $hours = int $t / 3600;
451 my $mins = int $t / 60;
452 return sprintf "%d %02d:%02d", $days, $hours, $mins;
457 AGWMsg::init(\&new_channel);
464 #############################################################
466 # The start of the main line of code
468 #############################################################
470 $starttime = $systime = time;
471 $systime_days = int ($systime / 86400);
472 $systime_daystart = $systime_days * 86400;
473 $lang = 'en' unless $lang;
475 unless ($DB::VERSION) {
476 $SIG{INT} = $SIG{TERM} = \&cease;
479 # open the debug file, set various FHs to be unbuffered
480 dbginit($broadcast_debug ? \&DXCommandmode::broadcast_debug : undef);
484 STDOUT->autoflush(1);
487 # try to load the database
488 if (DXSql::init($dsn)) {
489 $dbh = DXSql->new($dsn);
490 $dbh = $dbh->connect($dsn, $dbuser, $dbpass) if $dbh;
493 # try to load Encode and Git
496 my $w = $SIG{__DIE__};
497 $SIG{__DIE__} = 'IGNORE';
498 eval { require Encode; };
504 $gitversion = 'none';
505 eval { require Git; };
509 # determine the real version number
510 my $repo = Git->repository(Directory => "$root/.git");
512 my $desc = $repo->command_oneline(['describe', '--long'], STDERR => 0);
514 my ($v, $s, $b, $g) = $desc =~ /^([\d.]+)(?:\.(\d+))?-(\d+)-g([0-9a-f]+)/;
517 dbg("Git: V=$v S=$s B=$b g=$g");
520 $gitversion = "$g\[r]";
522 my @branch = $repo->command([qw{branch}], STDERR=>0);
524 my ($star, $b) = split /\s+/;
535 # try to load XML::Simple
539 my ($year) = (gmtime)[5];
541 LogDbg('cluster', "DXSpider V$version, build $build (git: $gitbranch/$gitversion) started");
542 dbg("Copyright (c) 1998-$year Dirk Koopman G1TLH");
545 dbg("loading prefixes ...");
547 my $r = Prefix::init();
551 dbg("loading band data ...");
554 # initialise User file system
555 dbg("loading user file system ...");
556 DXUser::init(4); # version 4 == json format
558 # look for the sysop and the alias user and complain if they aren't there
560 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;
561 my $ref = DXUser::get($mycall);
562 die "$mycall missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
563 my $oldsort = $ref->sort;
564 if ($oldsort ne 'S') {
566 dbg "Resetting node type from $oldsort -> DXSpider ('S')";
568 $ref = DXUser::get($myalias);
569 die "$myalias missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
570 $oldsort = $ref->sort;
571 if ($oldsort ne 'U') {
573 dbg "Resetting sysop user type from $oldsort -> User ('U')";
577 # start listening for incoming messages/connects
578 dbg("starting listeners ...");
579 my $conn = IntMsg->new_server($clusteraddr, $clusterport, \&login);
580 $conn->conns("Server $clusteraddr/$clusterport using IntMsg");
581 push @listeners, $conn;
582 dbg("Internal port: $clusteraddr $clusterport using IntMsg");
583 foreach my $l (@main::listen) {
585 my $pkg = $l->[2] || 'ExtMsg';
586 my $login = $l->[3] || 'login';
588 $conn = $pkg->new_server($l->[0], $l->[1], \&{"${pkg}::${login}"});
589 $conn->conns("Server $l->[0]/$l->[1] using ${pkg}::${login}");
590 push @listeners, $conn;
591 dbg("External Port: $l->[0] $l->[1] using ${pkg}::${login}");
594 dbg("AGW Listener") if $AGWMsg::enable;
597 dbg("BPQ Listener") if $BPQMsg::enable;
598 BPQMsg::init(\&new_channel);
600 dbg("UDP Listener") if $UDPMsg::enable;
601 UDPMsg::init(\&new_channel);
604 dbg("load badwords: " . (BadWords::load or "Ok"));
607 unless ($DB::VERSION) {
608 $SIG{INT} = $SIG{TERM} = sub { $ending = 10; };
612 $SIG{HUP} = 'IGNORE';
613 $SIG{CHLD} = sub { $zombies++ };
615 $SIG{PIPE} = sub { dbg("Broken PIPE signal received"); };
616 $SIG{IO} = sub { dbg("SIGIO received"); };
617 $SIG{WINCH} = $SIG{STOP} = $SIG{CONT} = 'IGNORE';
618 $SIG{KILL} = 'DEFAULT'; # as if it matters....
620 # catch the rest with a hopeful message
623 # dbg("Catching SIG $_") if isdbg('chan');
624 $SIG{$_} = sub { my $sig = shift; DXDebug::confess("Caught signal $sig"); };
630 dbg("Starting Dupe system");
633 # read in system messages
634 dbg("Read in Messages");
637 # read in command aliases
638 dbg("Read in Aliases");
641 # initialise the Geomagnetic data engine
647 # initial the Spot stuff
648 dbg("Starting DX Spot system");
651 # initialise the protocol engine
652 dbg("Start Protocol Engines ...");
655 # put in a DXCluster node for us here so we can add users and take them away
656 $routeroot = Route::Node->new($mycall, $version*100+5300, Route::here($main::me->here)|Route::conf($main::me->conf));
657 $routeroot->do_pc9x(1);
658 $routeroot->via_pc92(1);
660 # make sure that there is a routing OUTPUT node default file
661 #unless (Filter::read_in('route', 'node_default', 0)) {
662 # my $dxcc = $main::me->dxcc;
663 # $Route::filterdef->cmd($main::me, 'route', 'accept', "node_default call $mycall" );
666 # read in any existing message headers and clean out old crap
667 dbg("reading existing message headers ...");
671 # read in any cron jobs
672 dbg("reading cron jobs ...");
675 # read in database desriptors
676 dbg("reading database descriptors ...");
679 # starting local stuff
680 dbg("doing local initialisation ...");
682 if (defined &Local::init) {
686 dbg("Local::init error $@") if $@;
690 # this, such as it is, is the main loop!
691 dbg("orft we jolly well go ...");
692 my $script = new Script "startup";
693 $script->run($main::me) if $script;
695 #open(DB::OUT, "|tee /tmp/aa");
698 our $io_disconnected;
703 # DXCommandmode::process(); # process ongoing command mode stuff
704 # DXProt::process(); # process ongoing ak1a pcxx stuff
706 if (defined &Local::process) {
708 Local::process(); # do any localised processing
710 dbg("Local::process error $@") if $@;
716 dbg("DXSpider Ending $ending");
718 unless ($io_disconnected++) {
721 foreach $dxchan (DXChannel::get_all_users) {
726 foreach $dxchan (DXChannel::get_all_nodes) {
727 next if $dxchan == $main::me;
728 $dxchan->disconnect(2);
730 $main::me->disconnect;
733 Mojo::IOLoop->stop if --$ending <= 0;
743 my $days = int ($systime / 86400);
744 if ($systime_days != $days) {
745 $systime_days = $days;
746 $systime_daystart = $days * 86400;
748 IsoTime::update($systime);
749 DXCommandmode::process(); # process ongoing command mode stuff
750 DXProt::process(); # process ongoing ak1a pcxx stuff
751 DXCron::process(); # do cron jobs
753 DXConnect::process();
758 DXCron::process(); # do cron jobs
759 IsoTime::update($systime);
760 DXConnect::process();
796 dbg("Before Web::start_node");
798 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
800 dbg("After Web::start_node");
805 my $main_loop = Mojo::IOLoop->recurring($idle_interval => \&idle_loop);
806 my $log_flush_loop = Mojo::IOLoop->recurring($log_flush_interval => \&DXLog::flushall);
807 my $cpusecs_loop = Mojo::IOLoop->recurring(5 => sub {my @t = times; $clssecs = $t[0]+$t[1]; $cldsecs = $t[2]+$t[3]});
808 my $persec = Mojo::IOLoop->recurring(1 => \&per_sec);
809 my $per10sec = Mojo::IOLoop->recurring(10 => \&per_10_sec);
810 my $permin = Mojo::IOLoop->recurring(60 => \&per_minute);
811 my $per10min = Mojo::IOLoop->recurring(600 => \&per_10_minute);
812 my $perhour = Mojo::IOLoop->recurring(3600 => \&per_hour);
813 my $perday = Mojo::IOLoop->recurring(86400 => \&per_day);