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
34 # make sure that modules are searched in the order local then perl
37 $SIG{'__WARN__'} = sub { warn $_[0] if $DOWARN };
39 # take into account any local::lib that might be present
45 import local::lib qw(/spider/perl5lib);
48 # root of directory tree for this system
50 $root = $ENV{'DXSPIDER_ROOT'} if $ENV{'DXSPIDER_ROOT'};
52 unshift @INC, "$root/perl5lib" unless grep {$_ eq "$root/perl5lib"} @INC;
53 unshift @INC, "$root/perl"; # this IS the right way round!
54 unshift @INC, "$root/local";
56 # do some validation of the input
57 die "The directory $root doesn't exist, please RTFM" unless -d $root;
58 die "$root/local doesn't exist, please RTFM" unless -d "$root/local";
59 die "$root/local/DXVars.pm doesn't exist, please RTFM" unless -e "$root/local/DXVars.pm";
61 # create some directories
62 mkdir "$root/local_cmd", 02774 unless -d "$root/local_cmd";
64 # locally stored data lives here
65 my $local_data = "$root/local_data";
66 mkdir $local_data, 02774 unless -d $local_data;
68 # try to create and lock a lockfile (this isn't atomic but
70 $lockfn = "$root/local_data/cluster.lck"; # lock file name
72 open(CLLOCK, "$lockfn") or die "Can't open Lockfile ($lockfn) $!";
77 warn "Lockfile ($lockfn) and process $pid exist, another cluster running?\n";
84 open(CLLOCK, ">$lockfn") or die "Can't open Lockfile ($lockfn) $!";
88 $is_win = ($^O =~ /^MS/ || $^O =~ /^OS-2/) ? 1 : 0; # is it Windows?
97 # order here is important - DXDebug snarfs Carp et al so that Mojo errors go into the debug log
160 use POSIX ":sys_wait_h";
163 use vars qw($version $build $gitversion $gitbranch);
170 @inqueue = (); # the main input queue, an array of hashes
171 $systime = 0; # the time now (in seconds)
172 $starttime = 0; # the starting time of the cluster
173 @outstanding_connects = (); # list of outstanding connects
174 @listeners = (); # list of listeners
175 $reqreg = 0; # 1 = registration required, 2 = deregister people
176 $bumpexisting = 1; # 1 = allow new connection to disconnect old, 0 - don't allow it
177 our $allowmultiple = 0; # This is used in conjunction with $bumpexisting, in a rather weird way.
178 our $min_reconnection_rate = 5*60; # minimum value of seconds between connections per user to allow co-existing users
179 our $max_ssid = 15; # highest ssid to be searched for a spare one on multiple connections
181 # If $allowmultiple > 0 and the $reconnection_rate is some value of seconds
182 # based on the average connection time calculated from the $user->conntimel entries / frequency is
183 # less than $reconnection_rate then we assume that there is more than one device (probably HRD) trying
184 # to connect "at once". In which case we probe for a spare SSID for a user callsign to allow up to
185 # $allowmultiple connections per callsign.
187 $allowdxby = 0; # 1 = allow "dx by <othercall>", 0 - don't allow it
188 $maxconnect_user = 3; # the maximum no of concurrent connections a user can have at a time
189 $maxconnect_node = 0; # Ditto but for nodes. In either case if a new incoming connection
190 # takes the no of references in the routing table above these numbers
191 # then the connection is refused. This only affects INCOMING connections.
192 $idle_interval = 0.500; # the wait between invocations of the main idle loop processing.
193 $log_flush_interval = 2; # interval to wait between log flushes
195 our $ending; # signal that we are ending;
196 our $broadcast_debug; # allow broadcasting of debug info down "enhanced" user connections
197 our $clssecs; # the amount of cpu time the DXSpider process have consumed
198 our $cldsecs; # the amount of cpu time any child processes have consumed
199 our $allowslashcall; # Allow / in connecting callsigns (ie PA0/G1TLH, or even PA0/G1TLH/2)
202 # send a message to call on conn and disconnect
205 my ($conn, $call, $mess) = @_;
207 $conn->disable_read(1);
208 dbg("-> D $call $mess\n") if isdbg('chan');
209 $conn->send_now("D$call|$mess");
214 # handle incoming messages
217 my ($conn, $msg) = @_;
218 my ($sort, $call, $line) = DXChannel::decode_input(0, $msg);
219 return unless defined $sort;
223 if (is_webcall($call) && $conn->isa('IntMsg')) {
224 my $newcall = find_next_webcall();
226 already_conn($conn, $call, "Maximum no of web connected connects ($Web::maxssid) exceeded");
230 $user = DXUser::get_current($call);
232 $user = DXUser->new($call);
236 $user->qth('on the web');
237 $user->homenode($main::mycall);
238 $user->lat($main::mylatitude);
239 $user->long($main::mylongitude);
240 $user->qra($main::mylocator);
242 $user->startt($main::systime);
244 $dxchan = Web->new($call, $conn, $user);
245 $dxchan->enhanced(1);
247 $msg =~ s/^A#WEB|/A$call|/;
248 $conn->send_now("C$call");
250 # "Normal" connections
251 unless (is_callsign($call)) {
252 already_conn($conn, $call, DXM::msg($lang, "illcall", $call));
258 $user = DXUser::get_current($call);
260 my $basecall = $call;
261 $basecall =~ s/-\d+$//; # remember this for later multiple user processing, it's used for other stuff than checking lockout status
263 # make sure we act on any locked status that the actual incoming call has.
264 $lock = $user->lockout;
265 } elsif ($basecall ne $call) {
266 # if there isn't a SSID on the $call, then try the base
267 my $luser = DXUser::get_current($basecall);
268 $lock = $luser->lockout if $luser;
271 # now deal with the lock
273 my $host = $conn->peerhost;
274 LogDbg('', "$call on $host is locked out, disconnected");
279 # set up the basic channel info for "Normal" Users
280 # is there one already connected to me - locally?
282 $dxchan = DXChannel::get($call);
285 if ($user && $user->is_node) {
286 already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
289 if ($allowmultiple && $user->is_user) {
290 # determine whether we are a candidate, have we flip-flopped frequently enough?
291 my @lastconns = @{$user->connlist} if $user->connlist;
293 if (@lastconns >= $DXUser::maxconnlist) {
294 $allow = $lastconns[-1]->[0] - $lastconns[0]->[0] < $min_reconnection_rate;
296 # search for a spare ssid
297 L1: for (my $count = $call =~ /-\d+$/?0:1; $allow && $count < $allowmultiple; ) { # remember we have one call already
299 for (; $lastid < $max_ssid && $count < $allowmultiple; ++$lastid) {
300 my $chan = DXChannel::get("$basecall-$lastid");
305 # we have a free call-ssid, save it
306 $newcall = "$basecall-$lastid";
312 # handle "normal" (non-multiple) connections in the existing way
313 if ($call eq $newcall) {
315 my $ip = $dxchan->hostname;
316 $dxchan->send_now('D', DXM::msg($lang, 'conbump', $call, $ip));
317 LogDbg('', "$call bumped off by $ip, disconnected");
320 already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
325 # make sure that the conn has the (possibly) new callsign
326 $conn->conns($newcall);
327 $msg =~ s/$call/$newcall/;
331 # (fairly) politely disconnect people that are connected to too many other places at once
332 my $r = Route::get($call);
333 if ($conn->{sort} && $conn->{sort} =~ /^I/ && $r && $user) {
335 my $m = $r->isa('Route::Node') ? $maxconnect_node : $maxconnect_user;
336 my $c = $user->maxconnect;
338 $v = defined $c ? $c : $m;
339 if ($v && @n >= $v+$allowmultiple) {
340 my $nodes = join ',', @n;
341 LogDbg('', "$call has too many connections ($v) at $nodes - disconnected");
342 already_conn($conn, $call, DXM::msg($lang, 'contomany', $call, $v, $nodes));
348 $user->{lang} = $main::lang if !$user->{lang}; # to autoupdate old systems
350 $user = DXUser->new($call);
354 # NOTE we are SHARING the same $user if $allowmultiple is > 1
356 $user->startt($systime); # mark the start time of this connection
357 if ($user->is_node) {
358 $dxchan = DXProt->new($call, $conn, $user);
359 } elsif ($user->is_rbn) {
360 $dxchan = RBN->new($newcall, $conn, $user);
361 } elsif ($user->is_user) {
362 $dxchan = DXCommandmode->new($newcall, $conn, $user);
364 die "Invalid sort of user on $call = $sort";
370 $conn->set_error(sub {my $err = shift; LogDbg('', "Comms error '$err' received for call $dxchan->{call}"); $dxchan->disconnect(1);});
371 $conn->set_on_eof(sub {$dxchan->disconnect});
372 $conn->set_rproc(sub {my ($conn,$msg) = @_; $dxchan->rec($msg);});
374 $dxchan->enhanced(1);
383 return \&new_channel;
388 # cease running this program, close down all the connections nicely
393 cluck("ceasing") if $ceasing;
395 return if $ceasing++;
398 $SIG{'TERM'} = 'IGNORE';
399 $SIG{'INT'} = 'IGNORE';
403 if (defined &Local::finish) {
405 Local::finish(); # end local processing
407 dbg("Local::finish error $@") if $@;
415 # disconnect UDP customers
418 # end everything else
423 # close all databases
426 # close all listeners
427 foreach my $l (@listeners) {
431 LogDbg('cluster', "DXSpider v$version build $build (git: $gitbranch/$gitversion) using perl $^V on $^O ended");
432 dbg("bye bye everyone - bye bye");
436 $dbh->finish if $dbh;
441 # the reaper of children
445 while (($cpid = waitpid(-1, WNOHANG)) > 0) {
446 dbg("cpid: $cpid") if isdbg('reap');
447 # Msg->pid_gone($cpid);
448 $zombies-- if $zombies > 0;
450 dbg("cpid: $cpid") if isdbg('reap');
453 # this is where the input queue is dealt with and things are dispatched off to other parts of
458 my $t = $systime - $starttime;
459 my $days = int $t / 86400;
461 my $hours = int $t / 3600;
463 my $mins = int $t / 60;
464 return sprintf "%d %02d:%02d", $days, $hours, $mins;
469 AGWMsg::init(\&new_channel);
476 #############################################################
478 # The start of the main line of code
480 #############################################################
484 $starttime = $systime = time;
485 $systime_days = int ($systime / 86400);
486 $systime_daystart = $systime_days * 86400;
487 $lang = 'en' unless $lang;
489 unless ($DB::VERSION) {
490 $SIG{INT} = $SIG{TERM} = \&cease;
493 # open the debug file, set various FHs to be unbuffered
494 dbginit(undef, $broadcast_debug ? \&DXCommandmode::broadcast_debug : undef);
498 STDOUT->autoflush(1);
501 dbg "Perl path: " . join(':', @INC);
503 # try to load the database
504 if (DXSql::init($dsn)) {
505 $dbh = DXSql->new($dsn);
506 $dbh = $dbh->connect($dsn, $dbuser, $dbpass) if $dbh;
509 # try to load Encode and Git
512 my $w = $SIG{__DIE__};
513 $SIG{__DIE__} = 'IGNORE';
514 eval { require Encode; };
521 $gitversion = 'none';
523 # determine the real Git build number and branch
525 eval {$desc = `git --git-dir=$root/.git describe --long`};
527 my ($v, $s, $b, $g) = $desc =~ /^([\d\.]+)(?:\.(\d+))?-(\d+)-g([0-9a-f]+)/;
529 my $subversion = $s || 0; # not used elsewhere
531 $gitversion = "$g\[r]";
536 eval {@branch = `git --git-dir=$root/.git branch`};
539 my ($star, $b) = split /\s+/;
551 # setup location of motd & issue
553 $motd = localdata($motd);
554 localdata_mv("issue");
557 # try to load XML::Simple
561 my ($year) = (gmtime)[5];
563 LogDbg('cluster', "DXSpider v$version build $build (git: $gitbranch/$gitversion) using perl $^V on $^O started");
564 dbg("Copyright (c) 1998-$year Dirk Koopman G1TLH");
567 dbg("loading prefixes ...");
569 my $r = Prefix::init();
573 dbg("loading band data ...");
576 # initialise User file system
577 dbg("loading user file system ...");
578 DXUser::init(4); # version 4 == json format
580 Filter::init(); # doesn't do much, but has to be done
583 # look for the sysop and the alias user and complain if they aren't there
585 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;
586 my $ref = DXUser::get($mycall);
587 die "$mycall missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
588 my $oldsort = $ref->sort;
589 if ($oldsort ne 'S') {
591 dbg("Resetting node type from $oldsort -> DXSpider ('S')");
593 $ref = DXUser::get($myalias);
594 die "$myalias missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
595 $oldsort = $ref->sort;
596 if ($oldsort ne 'U') {
598 dbg("Resetting sysop user type from $oldsort -> User ('U')");
602 # start listening for incoming messages/connects
603 dbg("starting listeners ...");
604 my $conn = IntMsg->new_server($clusteraddr, $clusterport, \&login);
605 $conn->conns("Server $clusteraddr/$clusterport using IntMsg");
606 push @listeners, $conn;
607 dbg("Internal port: $clusteraddr $clusterport using IntMsg");
608 foreach my $l (@main::listen) {
610 my $pkg = $l->[2] || 'ExtMsg';
611 my $login = $l->[3] || 'login';
613 $conn = $pkg->new_server($l->[0], $l->[1], \&{"${pkg}::${login}"});
614 $conn->conns("Server $l->[0]/$l->[1] using ${pkg}::${login}");
615 push @listeners, $conn;
616 dbg("External Port: $l->[0] $l->[1] using ${pkg}::${login}");
619 dbg("AGW Listener") if $AGWMsg::enable;
622 dbg("BPQ Listener") if $BPQMsg::enable;
623 BPQMsg::init(\&new_channel);
625 dbg("UDP Listener") if $UDPMsg::enable;
626 UDPMsg::init(\&new_channel);
629 dbg("load badwords: " . (BadWords::load or "Ok"));
632 unless ($DB::VERSION) {
633 $SIG{INT} = $SIG{TERM} = sub { $ending = 10; };
637 $SIG{HUP} = 'IGNORE';
638 $SIG{CHLD} = sub { $zombies++ };
640 $SIG{PIPE} = sub { dbg("Broken PIPE signal received"); };
641 $SIG{IO} = sub { dbg("SIGIO received"); };
642 $SIG{WINCH} = $SIG{STOP} = $SIG{CONT} = 'IGNORE';
643 $SIG{KILL} = 'DEFAULT'; # as if it matters....
645 # catch the rest with a hopeful message
648 # dbg("Catching SIG $_") if isdbg('chan');
649 $SIG{$_} = sub { my $sig = shift; DXDebug::confess("Caught signal $sig"); };
655 dbg("Starting Dupe system");
658 # read in system messages
659 dbg("Read in Messages");
662 # read in command aliases
663 dbg("Read in Aliases");
666 # initialise the Geomagnetic data engine
672 # initialise the protocol engine
673 dbg("Start Protocol Engines ...");
676 # read startup script
677 my $script = new Script "startup";
678 $script->run($main::me) if $script;
680 # put in a DXCluster node for us here so we can add users and take them away
681 $routeroot = Route::Node->new($mycall, $version*100+5300, Route::here($main::me->here)|Route::conf($main::me->conf));
682 $routeroot->do_pc9x(1);
683 $routeroot->via_pc92(1);
685 # make sure that there is a routing OUTPUT node default file
686 #unless (Filter::read_in('route', 'node_default', 0)) {
687 # my $dxcc = $main::me->dxcc;
688 # $Route::filterdef->cmd($main::me, 'route', 'accept', "node_default call $mycall" );
691 # initial the Spot stuff
692 dbg("Starting DX Spot system");
695 # read in any existing message headers and clean out old crap
696 dbg("reading existing message headers ...");
700 # read in any cron jobs
701 dbg("reading cron jobs ...");
704 # read in database desriptors
705 dbg("reading database descriptors ...");
708 dbg("starting RBN ...");
711 # starting local stuff
712 dbg("doing local initialisation ...");
714 if (defined &Local::init) {
718 dbg("Local::init error $@") if $@;
722 # this, such as it is, is the main loop!
723 dbg("orft we jolly well go ...");
725 #open(DB::OUT, "|tee /tmp/aa");
728 our $io_disconnected;
733 # DXCommandmode::process(); # process ongoing command mode stuff
734 # DXProt::process(); # process ongoing ak1a pcxx stuff
736 if (defined &Local::process) {
738 Local::process(); # do any localised processing
740 dbg("Local::process error $@") if $@;
746 dbg("DXSpider Ending $ending");
748 unless ($io_disconnected++) {
751 foreach $dxchan (DXChannel::get_all_users) {
756 foreach $dxchan (DXChannel::get_all_nodes) {
757 next if $dxchan == $main::me;
758 $dxchan->disconnect(2);
760 $main::me->disconnect;
763 Mojo::IOLoop->stop_gracefully if --$ending <= 0;
773 my $days = int ($systime / 86400);
774 if ($systime_days != $days) {
775 $systime_days = $days;
776 $systime_daystart = $days * 86400;
778 IsoTime::update($systime);
779 DXCommandmode::process(); # process ongoing command mode stuff
780 DXProt::process(); # process ongoing ak1a pcxx stuff
782 DXConnect::process();
787 IsoTime::update($systime);
788 DXConnect::process();
791 DXCron::process(); # do cron jobs
810 RBN::per_10_minute();
825 dbg("Before Web::start_node");
827 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
829 dbg("After Web::start_node");
834 my $main_loop = Mojo::IOLoop->recurring($idle_interval => \&idle_loop);
835 my $log_flush_loop = Mojo::IOLoop->recurring($log_flush_interval => \&DXLog::flushall);
836 my $cpusecs_loop = Mojo::IOLoop->recurring(5 => sub {my @t = times; $clssecs = $t[0]+$t[1]; $cldsecs = $t[2]+$t[3]});
837 my $persec = Mojo::IOLoop->recurring(1 => \&per_sec);
838 my $per10sec = Mojo::IOLoop->recurring(10 => \&per_10_sec);
839 my $permin = Mojo::IOLoop->recurring(60 => \&per_minute);
840 my $per10min = Mojo::IOLoop->recurring(600 => \&per_10_minute);
841 my $perhour = Mojo::IOLoop->recurring(3600 => \&per_hour);
842 my $perday = Mojo::IOLoop->recurring(86400 => \&per_day);