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
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
35 # make sure that modules are searched in the order local then perl
38 $SIG{'__WARN__'} = sub { warn $_[0] if $DOWARN };
40 # take into account any local::lib that might be present
44 import local::lib unless ($@);
46 # root of directory tree for this system
48 $root = $ENV{'DXSPIDER_ROOT'} if $ENV{'DXSPIDER_ROOT'};
50 unshift @INC, "$root/perl"; # this IS the right way round!
51 unshift @INC, "$root/local";
53 # do some validation of the input
54 die "The directory $root doesn't exist, please RTFM" unless -d $root;
55 die "$root/local doesn't exist, please RTFM" unless -d "$root/local";
56 die "$root/local/DXVars.pm doesn't exist, please RTFM" unless -e "$root/local/DXVars.pm";
58 # create some directories
59 mkdir "$root/local_cmd", 02774 unless -d "$root/local_cmd";
61 # locally stored data lives here
62 my $local_data = "$root/local_data";
63 mkdir $local_data, 02774 unless -d $local_data;
65 # try to create and lock a lockfile (this isn't atomic but
67 $lockfn = "$root/local_data/cluster.lck"; # lock file name
69 open(CLLOCK, "$lockfn") or die "Can't open Lockfile ($lockfn) $!";
74 warn "Lockfile ($lockfn) and process $pid exist, another cluster running?\n";
81 open(CLLOCK, ">$lockfn") or die "Can't open Lockfile ($lockfn) $!";
85 $is_win = ($^O =~ /^MS/ || $^O =~ /^OS-2/) ? 1 : 0; # is it Windows?
93 # order here is important - DXDebug snarfs Carp et al so that Mojo errors go into the debug log
156 use POSIX ":sys_wait_h";
159 use vars qw($version $build $gitversion $gitbranch);
166 @inqueue = (); # the main input queue, an array of hashes
167 $systime = 0; # the time now (in seconds)
168 $starttime = 0; # the starting time of the cluster
169 @outstanding_connects = (); # list of outstanding connects
170 @listeners = (); # list of listeners
171 $reqreg = 0; # 1 = registration required, 2 = deregister people
172 $bumpexisting = 1; # 1 = allow new connection to disconnect old, 0 - don't allow it
173 our $allowmultiple = 0; # This is used in conjunction with $bumpexisting, in a rather weird way.
174 our $min_reconnection_rate = 5*60; # minimum value of seconds between connections per user to allow co-existing users
175 our $max_ssid = 15; # highest ssid to be searched for a spare one on multiple connections
177 # If $allowmultiple > 0 and the $reconnection_rate is some value of seconds
178 # based on the average connection time calculated from the $user->conntimel entries / frequency is
179 # less than $reconnection_rate then we assume that there is more than one device (probably HRD) trying
180 # to connect "at once". In which case we probe for a spare SSID for a user callsign to allow up to
181 # $allowmultiple connections per callsign.
183 $allowdxby = 0; # 1 = allow "dx by <othercall>", 0 - don't allow it
184 $maxconnect_user = 3; # the maximum no of concurrent connections a user can have at a time
185 $maxconnect_node = 0; # Ditto but for nodes. In either case if a new incoming connection
186 # takes the no of references in the routing table above these numbers
187 # then the connection is refused. This only affects INCOMING connections.
188 $idle_interval = 0.500; # the wait between invocations of the main idle loop processing.
189 $log_flush_interval = 2; # interval to wait between log flushes
191 our $ending; # signal that we are ending;
192 our $broadcast_debug; # allow broadcasting of debug info down "enhanced" user connections
193 our $clssecs; # the amount of cpu time the DXSpider process have consumed
194 our $cldsecs; # the amount of cpu time any child processes have consumed
195 our $allowslashcall; # Allow / in connecting callsigns (ie PA0/G1TLH, or even PA0/G1TLH/2)
198 # send a message to call on conn and disconnect
201 my ($conn, $call, $mess) = @_;
203 $conn->disable_read(1);
204 dbg("-> D $call $mess\n") if isdbg('chan');
205 $conn->send_now("D$call|$mess");
210 # handle incoming messages
213 my ($conn, $msg) = @_;
214 my ($sort, $call, $line) = DXChannel::decode_input(0, $msg);
215 return unless defined $sort;
219 if (is_webcall($call) && $conn->isa('IntMsg')) {
220 my $newcall = find_next_webcall();
222 already_conn($conn, $call, "Maximum no of web connected connects ($Web::maxssid) exceeded");
226 $user = DXUser::get_current($call);
228 $user = DXUser->new($call);
232 $user->qth('on the web');
233 $user->homenode($main::mycall);
234 $user->lat($main::mylatitude);
235 $user->long($main::mylongitude);
236 $user->qra($main::mylocator);
238 $user->startt($main::systime);
240 $dxchan = Web->new($call, $conn, $user);
241 $dxchan->enhanced(1);
243 $msg =~ s/^A#WEB|/A$call|/;
244 $conn->send_now("C$call");
246 # "Normal" connections
247 unless (is_callsign($call)) {
248 already_conn($conn, $call, DXM::msg($lang, "illcall", $call));
253 $user = DXUser::get_current($call);
254 my $basecall = $call;
255 $basecall =~ s/-\d+$//; # remember this for later multiple user processing
258 # make sure we act on any locked status that the actual incoming call has.
259 $lock = $user->lockout;
260 } elsif ($allowmultiple && $call ne $basecall) {
261 # if we are allowing multiple connections and there is a basecall minus incoming ssid, use the basecall's lock status
262 $user = DXUser::get_current($basecall);
263 $lock = $user->lockout if $user;
266 # now deal with the lock
268 my $host = $conn->peerhost;
269 LogDbg('', "$call on $host is locked out, disconnected");
274 # set up the basic channel info for "Normal" Users
275 # is there one already connected to me - locally?
277 $dxchan = DXChannel::get($call);
280 if ($user && $user->is_node) {
281 already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
284 if ($allowmultiple && $user->is_user) {
285 # determine whether we are a candidate, have we flip-flopped frequently enough?
286 my @lastconns = @{$user->connlist} if $user->connlist;
288 if (@lastconns >= $DXUser::maxconnlist) {
289 $allow = $lastconns[-1]->[0] - $lastconns[0]->[0] < $min_reconnection_rate;
291 # search for a spare ssid
292 L1: for (my $count = $call =~ /-\d+$/?0:1; $allow && $count < $allowmultiple; ) { # remember we have one call already
294 for (; $lastid < $max_ssid && $count < $allowmultiple; ++$lastid) {
295 my $chan = DXChannel::get("$basecall-$lastid");
300 # we have a free call-ssid, save it
301 $newcall = "$basecall-$lastid";
307 # handle "normal" (non-multiple) connections in the existing way
308 if ($call eq $newcall) {
310 my $ip = $dxchan->hostname;
311 $dxchan->send_now('D', DXM::msg($lang, 'conbump', $call, $ip));
312 LogDbg('', "$call bumped off by $ip, disconnected");
315 already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
320 # make sure that the conn has the (possibly) new callsign
321 $conn->conns($newcall);
322 $msg =~ s/$call/$newcall/;
326 # (fairly) politely disconnect people that are connected to too many other places at once
327 my $r = Route::get($call);
328 if ($conn->{sort} && $conn->{sort} =~ /^I/ && $r && $user) {
330 my $m = $r->isa('Route::Node') ? $maxconnect_node : $maxconnect_user;
331 my $c = $user->maxconnect;
333 $v = defined $c ? $c : $m;
334 if ($v && @n >= $v+$allowmultiple) {
335 my $nodes = join ',', @n;
336 LogDbg('', "$call has too many connections ($v) at $nodes - disconnected");
337 already_conn($conn, $call, DXM::msg($lang, 'contomany', $call, $v, $nodes));
343 $user->{lang} = $main::lang if !$user->{lang}; # to autoupdate old systems
345 $user = DXUser->new($call);
349 # NOTE we are SHARING the same $user if $allowmultiple is > 1
351 $user->startt($systime); # mark the start time of this connection
352 if ($user->is_node) {
353 $dxchan = DXProt->new($call, $conn, $user);
354 } elsif ($user->is_rbn) {
355 $dxchan = RBN->new($newcall, $conn, $user);
356 } elsif ($user->is_user) {
357 $dxchan = DXCommandmode->new($newcall, $conn, $user);
359 die "Invalid sort of user on $call = $sort";
365 $conn->set_error(sub {my $err = shift; LogDbg('', "Comms error '$err' received for call $dxchan->{call}"); $dxchan->disconnect(1);});
366 $conn->set_on_eof(sub {$dxchan->disconnect});
367 $conn->set_rproc(sub {my ($conn,$msg) = @_; $dxchan->rec($msg);});
369 $dxchan->enhanced(1);
378 return \&new_channel;
383 # cease running this program, close down all the connections nicely
388 cluck("ceasing") if $ceasing;
390 return if $ceasing++;
393 $SIG{'TERM'} = 'IGNORE';
394 $SIG{'INT'} = 'IGNORE';
398 if (defined &Local::finish) {
400 Local::finish(); # end local processing
402 dbg("Local::finish error $@") if $@;
410 # disconnect UDP customers
413 # end everything else
417 # close all databases
420 # close all listeners
421 foreach my $l (@listeners) {
425 LogDbg('cluster', "DXSpider V$version, build $build (git: $gitbranch/$gitversion) ended");
426 dbg("bye bye everyone - bye bye");
430 $dbh->finish if $dbh;
435 # the reaper of children
439 while (($cpid = waitpid(-1, WNOHANG)) > 0) {
440 dbg("cpid: $cpid") if isdbg('reap');
441 # Msg->pid_gone($cpid);
442 $zombies-- if $zombies > 0;
444 dbg("cpid: $cpid") if isdbg('reap');
447 # this is where the input queue is dealt with and things are dispatched off to other parts of
452 my $t = $systime - $starttime;
453 my $days = int $t / 86400;
455 my $hours = int $t / 3600;
457 my $mins = int $t / 60;
458 return sprintf "%d %02d:%02d", $days, $hours, $mins;
463 AGWMsg::init(\&new_channel);
470 #############################################################
472 # The start of the main line of code
474 #############################################################
476 $starttime = $systime = time;
477 $systime_days = int ($systime / 86400);
478 $systime_daystart = $systime_days * 86400;
479 $lang = 'en' unless $lang;
481 unless ($DB::VERSION) {
482 $SIG{INT} = $SIG{TERM} = \&cease;
485 # open the debug file, set various FHs to be unbuffered
486 dbginit($broadcast_debug ? \&DXCommandmode::broadcast_debug : undef);
490 STDOUT->autoflush(1);
493 # try to load the database
494 if (DXSql::init($dsn)) {
495 $dbh = DXSql->new($dsn);
496 $dbh = $dbh->connect($dsn, $dbuser, $dbpass) if $dbh;
499 # try to load Encode and Git
502 my $w = $SIG{__DIE__};
503 $SIG{__DIE__} = 'IGNORE';
504 eval { require Encode; };
510 $gitversion = 'none';
511 eval { require Git; };
515 # determine the real version number
516 my $repo = Git->repository(Directory => "$root/.git");
518 my $desc = $repo->command_oneline(['describe', '--long'], STDERR => 0);
520 my ($v, $s, $b, $g) = $desc =~ /^([\d.]+)(?:\.(\d+))?-(\d+)-g([0-9a-f]+)/;
522 dbg("Git: $desc") if isdbg('git');
523 dbg("Git: V=$v S=$s B=$b g=$g") if isdbg('git');
526 $gitversion = "$g\[r]";
528 my @branch = $repo->command([qw{branch}], STDERR=>0);
530 my ($star, $b) = split /\s+/;
541 # try to load XML::Simple
545 my ($year) = (gmtime)[5];
547 LogDbg('cluster', "DXSpider V$version, build $build (git: $gitbranch/$gitversion) started");
548 dbg("Copyright (c) 1998-$year Dirk Koopman G1TLH");
551 dbg("loading prefixes ...");
553 my $r = Prefix::init();
557 dbg("loading band data ...");
560 # initialise User file system
561 dbg("loading user file system ...");
562 DXUser::init(4); # version 4 == json format
564 # look for the sysop and the alias user and complain if they aren't there
566 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;
567 my $ref = DXUser::get($mycall);
568 die "$mycall missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
569 my $oldsort = $ref->sort;
570 if ($oldsort ne 'S') {
572 dbg("Resetting node type from $oldsort -> DXSpider ('S')");
574 $ref = DXUser::get($myalias);
575 die "$myalias missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
576 $oldsort = $ref->sort;
577 if ($oldsort ne 'U') {
579 dbg("Resetting sysop user type from $oldsort -> User ('U')");
583 # start listening for incoming messages/connects
584 dbg("starting listeners ...");
585 my $conn = IntMsg->new_server($clusteraddr, $clusterport, \&login);
586 $conn->conns("Server $clusteraddr/$clusterport using IntMsg");
587 push @listeners, $conn;
588 dbg("Internal port: $clusteraddr $clusterport using IntMsg");
589 foreach my $l (@main::listen) {
591 my $pkg = $l->[2] || 'ExtMsg';
592 my $login = $l->[3] || 'login';
594 $conn = $pkg->new_server($l->[0], $l->[1], \&{"${pkg}::${login}"});
595 $conn->conns("Server $l->[0]/$l->[1] using ${pkg}::${login}");
596 push @listeners, $conn;
597 dbg("External Port: $l->[0] $l->[1] using ${pkg}::${login}");
600 dbg("AGW Listener") if $AGWMsg::enable;
603 dbg("BPQ Listener") if $BPQMsg::enable;
604 BPQMsg::init(\&new_channel);
606 dbg("UDP Listener") if $UDPMsg::enable;
607 UDPMsg::init(\&new_channel);
610 dbg("load badwords: " . (BadWords::load or "Ok"));
613 unless ($DB::VERSION) {
614 $SIG{INT} = $SIG{TERM} = sub { $ending = 10; };
618 $SIG{HUP} = 'IGNORE';
619 $SIG{CHLD} = sub { $zombies++ };
621 $SIG{PIPE} = sub { dbg("Broken PIPE signal received"); };
622 $SIG{IO} = sub { dbg("SIGIO received"); };
623 $SIG{WINCH} = $SIG{STOP} = $SIG{CONT} = 'IGNORE';
624 $SIG{KILL} = 'DEFAULT'; # as if it matters....
626 # catch the rest with a hopeful message
629 # dbg("Catching SIG $_") if isdbg('chan');
630 $SIG{$_} = sub { my $sig = shift; DXDebug::confess("Caught signal $sig"); };
636 dbg("Starting Dupe system");
639 # read in system messages
640 dbg("Read in Messages");
643 # read in command aliases
644 dbg("Read in Aliases");
647 # initialise the Geomagnetic data engine
653 # initial the Spot stuff
654 dbg("Starting DX Spot system");
657 # initialise the protocol engine
658 dbg("Start Protocol Engines ...");
661 # put in a DXCluster node for us here so we can add users and take them away
662 $routeroot = Route::Node->new($mycall, $version*100+5300, Route::here($main::me->here)|Route::conf($main::me->conf));
663 $routeroot->do_pc9x(1);
664 $routeroot->via_pc92(1);
666 # make sure that there is a routing OUTPUT node default file
667 #unless (Filter::read_in('route', 'node_default', 0)) {
668 # my $dxcc = $main::me->dxcc;
669 # $Route::filterdef->cmd($main::me, 'route', 'accept', "node_default call $mycall" );
672 # read in any existing message headers and clean out old crap
673 dbg("reading existing message headers ...");
677 # read in any cron jobs
678 dbg("reading cron jobs ...");
681 # read in database desriptors
682 dbg("reading database descriptors ...");
685 # starting local stuff
686 dbg("doing local initialisation ...");
688 if (defined &Local::init) {
692 dbg("Local::init error $@") if $@;
696 # this, such as it is, is the main loop!
697 dbg("orft we jolly well go ...");
698 my $script = new Script "startup";
699 $script->run($main::me) if $script;
701 #open(DB::OUT, "|tee /tmp/aa");
704 our $io_disconnected;
709 # DXCommandmode::process(); # process ongoing command mode stuff
710 # DXProt::process(); # process ongoing ak1a pcxx stuff
712 if (defined &Local::process) {
714 Local::process(); # do any localised processing
716 dbg("Local::process error $@") if $@;
722 dbg("DXSpider Ending $ending");
724 unless ($io_disconnected++) {
727 foreach $dxchan (DXChannel::get_all_users) {
732 foreach $dxchan (DXChannel::get_all_nodes) {
733 next if $dxchan == $main::me;
734 $dxchan->disconnect(2);
736 $main::me->disconnect;
739 Mojo::IOLoop->stop if --$ending <= 0;
749 my $days = int ($systime / 86400);
750 if ($systime_days != $days) {
751 $systime_days = $days;
752 $systime_daystart = $days * 86400;
754 IsoTime::update($systime);
755 DXCommandmode::process(); # process ongoing command mode stuff
756 DXProt::process(); # process ongoing ak1a pcxx stuff
757 DXCron::process(); # do cron jobs
759 DXConnect::process();
764 DXCron::process(); # do cron jobs
765 IsoTime::update($systime);
766 DXConnect::process();
802 dbg("Before Web::start_node");
804 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
806 dbg("After Web::start_node");
811 my $main_loop = Mojo::IOLoop->recurring($idle_interval => \&idle_loop);
812 my $log_flush_loop = Mojo::IOLoop->recurring($log_flush_interval => \&DXLog::flushall);
813 my $cpusecs_loop = Mojo::IOLoop->recurring(5 => sub {my @t = times; $clssecs = $t[0]+$t[1]; $cldsecs = $t[2]+$t[3]});
814 my $persec = Mojo::IOLoop->recurring(1 => \&per_sec);
815 my $per10sec = Mojo::IOLoop->recurring(10 => \&per_10_sec);
816 my $permin = Mojo::IOLoop->recurring(60 => \&per_minute);
817 my $per10min = Mojo::IOLoop->recurring(600 => \&per_10_minute);
818 my $perhour = Mojo::IOLoop->recurring(3600 => \&per_hour);
819 my $perday = Mojo::IOLoop->recurring(86400 => \&per_day);