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?
96 # order here is important - DXDebug snarfs Carp et al so that Mojo errors go into the debug log
159 use POSIX ":sys_wait_h";
162 use vars qw($version $build $gitversion $gitbranch);
169 @inqueue = (); # the main input queue, an array of hashes
170 $systime = 0; # the time now (in seconds)
171 $starttime = 0; # the starting time of the cluster
172 @outstanding_connects = (); # list of outstanding connects
173 @listeners = (); # list of listeners
174 $reqreg = 0; # 1 = registration required, 2 = deregister people
175 $bumpexisting = 1; # 1 = allow new connection to disconnect old, 0 - don't allow it
176 our $allowmultiple = 0; # This is used in conjunction with $bumpexisting, in a rather weird way.
177 our $min_reconnection_rate = 5*60; # minimum value of seconds between connections per user to allow co-existing users
178 our $max_ssid = 15; # highest ssid to be searched for a spare one on multiple connections
180 # If $allowmultiple > 0 and the $reconnection_rate is some value of seconds
181 # based on the average connection time calculated from the $user->conntimel entries / frequency is
182 # less than $reconnection_rate then we assume that there is more than one device (probably HRD) trying
183 # to connect "at once". In which case we probe for a spare SSID for a user callsign to allow up to
184 # $allowmultiple connections per callsign.
186 $allowdxby = 0; # 1 = allow "dx by <othercall>", 0 - don't allow it
187 $maxconnect_user = 3; # the maximum no of concurrent connections a user can have at a time
188 $maxconnect_node = 0; # Ditto but for nodes. In either case if a new incoming connection
189 # takes the no of references in the routing table above these numbers
190 # then the connection is refused. This only affects INCOMING connections.
191 $idle_interval = 0.500; # the wait between invocations of the main idle loop processing.
192 $log_flush_interval = 2; # interval to wait between log flushes
194 our $ending; # signal that we are ending;
195 our $broadcast_debug; # allow broadcasting of debug info down "enhanced" user connections
196 our $clssecs; # the amount of cpu time the DXSpider process have consumed
197 our $cldsecs; # the amount of cpu time any child processes have consumed
198 our $allowslashcall; # Allow / in connecting callsigns (ie PA0/G1TLH, or even PA0/G1TLH/2)
201 # send a message to call on conn and disconnect
204 my ($conn, $call, $mess) = @_;
206 $conn->disable_read(1);
207 dbg("-> D $call $mess\n") if isdbg('chan');
208 $conn->send_now("D$call|$mess");
213 # handle incoming messages
216 my ($conn, $msg) = @_;
217 my ($sort, $call, $line) = DXChannel::decode_input(0, $msg);
218 return unless defined $sort;
222 if (is_webcall($call) && $conn->isa('IntMsg')) {
223 my $newcall = find_next_webcall();
225 already_conn($conn, $call, "Maximum no of web connected connects ($Web::maxssid) exceeded");
229 $user = DXUser::get_current($call);
231 $user = DXUser->new($call);
235 $user->qth('on the web');
236 $user->homenode($main::mycall);
237 $user->lat($main::mylatitude);
238 $user->long($main::mylongitude);
239 $user->qra($main::mylocator);
241 $user->startt($main::systime);
243 $dxchan = Web->new($call, $conn, $user);
244 $dxchan->enhanced(1);
246 $msg =~ s/^A#WEB|/A$call|/;
247 $conn->send_now("C$call");
249 # "Normal" connections
250 unless (is_callsign($call)) {
251 already_conn($conn, $call, DXM::msg($lang, "illcall", $call));
256 $user = DXUser::get_current($call);
258 my $basecall = $call;
259 $basecall =~ s/-\d+$//; # remember this for later multiple user processing
262 # make sure we act on any locked status that the actual incoming call has.
263 $lock = $user->lockout;
264 } elsif ($allowmultiple && $call ne $basecall) {
265 # if we are allowing multiple connections and there is a basecall minus incoming ssid, use the basecall's lock status
266 $user = DXUser::get_current($basecall);
267 $lock = $user->lockout if $user;
270 # now deal with the lock
272 my $host = $conn->peerhost;
273 LogDbg('', "$call on $host is locked out, disconnected");
278 # set up the basic channel info for "Normal" Users
279 # is there one already connected to me - locally?
281 $dxchan = DXChannel::get($call);
284 if ($user && $user->is_node) {
285 already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
288 if ($allowmultiple && $user->is_user) {
289 # determine whether we are a candidate, have we flip-flopped frequently enough?
290 my @lastconns = @{$user->connlist} if $user->connlist;
292 if (@lastconns >= $DXUser::maxconnlist) {
293 $allow = $lastconns[-1]->[0] - $lastconns[0]->[0] < $min_reconnection_rate;
295 # search for a spare ssid
296 L1: for (my $count = $call =~ /-\d+$/?0:1; $allow && $count < $allowmultiple; ) { # remember we have one call already
298 for (; $lastid < $max_ssid && $count < $allowmultiple; ++$lastid) {
299 my $chan = DXChannel::get("$basecall-$lastid");
304 # we have a free call-ssid, save it
305 $newcall = "$basecall-$lastid";
311 # handle "normal" (non-multiple) connections in the existing way
312 if ($call eq $newcall) {
314 my $ip = $dxchan->hostname;
315 $dxchan->send_now('D', DXM::msg($lang, 'conbump', $call, $ip));
316 LogDbg('', "$call bumped off by $ip, disconnected");
319 already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
324 # make sure that the conn has the (possibly) new callsign
325 $conn->conns($newcall);
326 $msg =~ s/$call/$newcall/;
330 # (fairly) politely disconnect people that are connected to too many other places at once
331 my $r = Route::get($call);
332 if ($conn->{sort} && $conn->{sort} =~ /^I/ && $r && $user) {
334 my $m = $r->isa('Route::Node') ? $maxconnect_node : $maxconnect_user;
335 my $c = $user->maxconnect;
337 $v = defined $c ? $c : $m;
338 if ($v && @n >= $v+$allowmultiple) {
339 my $nodes = join ',', @n;
340 LogDbg('', "$call has too many connections ($v) at $nodes - disconnected");
341 already_conn($conn, $call, DXM::msg($lang, 'contomany', $call, $v, $nodes));
347 $user->{lang} = $main::lang if !$user->{lang}; # to autoupdate old systems
349 $user = DXUser->new($call);
353 # NOTE we are SHARING the same $user if $allowmultiple is > 1
355 $user->startt($systime); # mark the start time of this connection
356 if ($user->is_node) {
357 $dxchan = DXProt->new($call, $conn, $user);
358 } elsif ($user->is_rbn) {
359 $dxchan = RBN->new($newcall, $conn, $user);
360 } elsif ($user->is_user) {
361 $dxchan = DXCommandmode->new($newcall, $conn, $user);
363 die "Invalid sort of user on $call = $sort";
369 $conn->set_error(sub {my $err = shift; LogDbg('', "Comms error '$err' received for call $dxchan->{call}"); $dxchan->disconnect(1);});
370 $conn->set_on_eof(sub {$dxchan->disconnect});
371 $conn->set_rproc(sub {my ($conn,$msg) = @_; $dxchan->rec($msg);});
373 $dxchan->enhanced(1);
382 return \&new_channel;
387 # cease running this program, close down all the connections nicely
392 cluck("ceasing") if $ceasing;
394 return if $ceasing++;
397 $SIG{'TERM'} = 'IGNORE';
398 $SIG{'INT'} = 'IGNORE';
402 if (defined &Local::finish) {
404 Local::finish(); # end local processing
406 dbg("Local::finish error $@") if $@;
414 # disconnect UDP customers
417 # end everything else
422 # close all databases
425 # close all listeners
426 foreach my $l (@listeners) {
430 LogDbg('cluster', "DXSpider V$version, build $build (git: $gitbranch/$gitversion) ended");
431 dbg("bye bye everyone - bye bye");
435 $dbh->finish if $dbh;
440 # the reaper of children
444 while (($cpid = waitpid(-1, WNOHANG)) > 0) {
445 dbg("cpid: $cpid") if isdbg('reap');
446 # Msg->pid_gone($cpid);
447 $zombies-- if $zombies > 0;
449 dbg("cpid: $cpid") if isdbg('reap');
452 # this is where the input queue is dealt with and things are dispatched off to other parts of
457 my $t = $systime - $starttime;
458 my $days = int $t / 86400;
460 my $hours = int $t / 3600;
462 my $mins = int $t / 60;
463 return sprintf "%d %02d:%02d", $days, $hours, $mins;
468 AGWMsg::init(\&new_channel);
475 #############################################################
477 # The start of the main line of code
479 #############################################################
481 $starttime = $systime = time;
482 $systime_days = int ($systime / 86400);
483 $systime_daystart = $systime_days * 86400;
484 $lang = 'en' unless $lang;
486 unless ($DB::VERSION) {
487 $SIG{INT} = $SIG{TERM} = \&cease;
490 # open the debug file, set various FHs to be unbuffered
491 dbginit($broadcast_debug ? \&DXCommandmode::broadcast_debug : undef);
495 STDOUT->autoflush(1);
498 dbg "Perl path: " . join(':', @INC);
500 # try to load the database
501 if (DXSql::init($dsn)) {
502 $dbh = DXSql->new($dsn);
503 $dbh = $dbh->connect($dsn, $dbuser, $dbpass) if $dbh;
506 # try to load Encode and Git
509 my $w = $SIG{__DIE__};
510 $SIG{__DIE__} = 'IGNORE';
511 eval { require Encode; };
517 $gitversion = 'none';
518 eval { require Git; };
522 # determine the real version number
523 my $repo = Git->repository(Directory => "$root/.git");
525 my $desc = $repo->command_oneline(['describe', '--long'], STDERR => 0);
527 my ($v, $s, $b, $g) = $desc =~ /^([\d.]+)(?:\.(\d+))?-(\d+)-g([0-9a-f]+)/;
529 dbg("Git: $desc") if isdbg('git');
530 dbg("Git: V=$v S=$s B=$b g=$g") if isdbg('git');
533 $gitversion = "$g\[r]";
535 my @branch = $repo->command([qw{branch}], STDERR=>0);
537 my ($star, $b) = split /\s+/;
548 # try to load XML::Simple
552 my ($year) = (gmtime)[5];
554 LogDbg('cluster', "DXSpider V$version, build $build (git: $gitbranch/$gitversion) started");
555 dbg("Copyright (c) 1998-$year Dirk Koopman G1TLH");
558 dbg("loading prefixes ...");
560 my $r = Prefix::init();
564 dbg("loading band data ...");
567 # initialise User file system
568 dbg("loading user file system ...");
569 DXUser::init(4); # version 4 == json format
571 Filter::init(); # doesn't do much, but has to be done
574 # look for the sysop and the alias user and complain if they aren't there
576 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;
577 my $ref = DXUser::get($mycall);
578 die "$mycall missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
579 my $oldsort = $ref->sort;
580 if ($oldsort ne 'S') {
582 dbg("Resetting node type from $oldsort -> DXSpider ('S')");
584 $ref = DXUser::get($myalias);
585 die "$myalias missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
586 $oldsort = $ref->sort;
587 if ($oldsort ne 'U') {
589 dbg("Resetting sysop user type from $oldsort -> User ('U')");
593 # start listening for incoming messages/connects
594 dbg("starting listeners ...");
595 my $conn = IntMsg->new_server($clusteraddr, $clusterport, \&login);
596 $conn->conns("Server $clusteraddr/$clusterport using IntMsg");
597 push @listeners, $conn;
598 dbg("Internal port: $clusteraddr $clusterport using IntMsg");
599 foreach my $l (@main::listen) {
601 my $pkg = $l->[2] || 'ExtMsg';
602 my $login = $l->[3] || 'login';
604 $conn = $pkg->new_server($l->[0], $l->[1], \&{"${pkg}::${login}"});
605 $conn->conns("Server $l->[0]/$l->[1] using ${pkg}::${login}");
606 push @listeners, $conn;
607 dbg("External Port: $l->[0] $l->[1] using ${pkg}::${login}");
610 dbg("AGW Listener") if $AGWMsg::enable;
613 dbg("BPQ Listener") if $BPQMsg::enable;
614 BPQMsg::init(\&new_channel);
616 dbg("UDP Listener") if $UDPMsg::enable;
617 UDPMsg::init(\&new_channel);
620 dbg("load badwords: " . (BadWords::load or "Ok"));
623 unless ($DB::VERSION) {
624 $SIG{INT} = $SIG{TERM} = sub { $ending = 10; };
628 $SIG{HUP} = 'IGNORE';
629 $SIG{CHLD} = sub { $zombies++ };
631 $SIG{PIPE} = sub { dbg("Broken PIPE signal received"); };
632 $SIG{IO} = sub { dbg("SIGIO received"); };
633 $SIG{WINCH} = $SIG{STOP} = $SIG{CONT} = 'IGNORE';
634 $SIG{KILL} = 'DEFAULT'; # as if it matters....
636 # catch the rest with a hopeful message
639 # dbg("Catching SIG $_") if isdbg('chan');
640 $SIG{$_} = sub { my $sig = shift; DXDebug::confess("Caught signal $sig"); };
646 dbg("Starting Dupe system");
649 # read in system messages
650 dbg("Read in Messages");
653 # read in command aliases
654 dbg("Read in Aliases");
657 # initialise the Geomagnetic data engine
663 # initial the Spot stuff
664 dbg("Starting DX Spot system");
667 # initialise the protocol engine
668 dbg("Start Protocol Engines ...");
671 # put in a DXCluster node for us here so we can add users and take them away
672 $routeroot = Route::Node->new($mycall, $version*100+5300, Route::here($main::me->here)|Route::conf($main::me->conf));
673 $routeroot->do_pc9x(1);
674 $routeroot->via_pc92(1);
676 # make sure that there is a routing OUTPUT node default file
677 #unless (Filter::read_in('route', 'node_default', 0)) {
678 # my $dxcc = $main::me->dxcc;
679 # $Route::filterdef->cmd($main::me, 'route', 'accept', "node_default call $mycall" );
682 # read in any existing message headers and clean out old crap
683 dbg("reading existing message headers ...");
687 # read in any cron jobs
688 dbg("reading cron jobs ...");
691 # read in database desriptors
692 dbg("reading database descriptors ...");
695 dbg("starting RBN ...");
698 # starting local stuff
699 dbg("doing local initialisation ...");
701 if (defined &Local::init) {
705 dbg("Local::init error $@") if $@;
709 # this, such as it is, is the main loop!
710 dbg("orft we jolly well go ...");
711 my $script = new Script "startup";
712 $script->run($main::me) if $script;
714 #open(DB::OUT, "|tee /tmp/aa");
717 our $io_disconnected;
722 # DXCommandmode::process(); # process ongoing command mode stuff
723 # DXProt::process(); # process ongoing ak1a pcxx stuff
725 if (defined &Local::process) {
727 Local::process(); # do any localised processing
729 dbg("Local::process error $@") if $@;
735 dbg("DXSpider Ending $ending");
737 unless ($io_disconnected++) {
740 foreach $dxchan (DXChannel::get_all_users) {
745 foreach $dxchan (DXChannel::get_all_nodes) {
746 next if $dxchan == $main::me;
747 $dxchan->disconnect(2);
749 $main::me->disconnect;
752 Mojo::IOLoop->stop if --$ending <= 0;
762 my $days = int ($systime / 86400);
763 if ($systime_days != $days) {
764 $systime_days = $days;
765 $systime_daystart = $days * 86400;
767 IsoTime::update($systime);
768 DXCommandmode::process(); # process ongoing command mode stuff
769 DXProt::process(); # process ongoing ak1a pcxx stuff
771 DXConnect::process();
776 IsoTime::update($systime);
777 DXConnect::process();
780 DXCron::process(); # do cron jobs
799 RBN::per_10_minute();
814 dbg("Before Web::start_node");
816 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
818 dbg("After Web::start_node");
823 my $main_loop = Mojo::IOLoop->recurring($idle_interval => \&idle_loop);
824 my $log_flush_loop = Mojo::IOLoop->recurring($log_flush_interval => \&DXLog::flushall);
825 my $cpusecs_loop = Mojo::IOLoop->recurring(5 => sub {my @t = times; $clssecs = $t[0]+$t[1]; $cldsecs = $t[2]+$t[3]});
826 my $persec = Mojo::IOLoop->recurring(1 => \&per_sec);
827 my $per10sec = Mojo::IOLoop->recurring(10 => \&per_10_sec);
828 my $permin = Mojo::IOLoop->recurring(60 => \&per_minute);
829 my $per10min = Mojo::IOLoop->recurring(600 => \&per_10_minute);
830 my $perhour = Mojo::IOLoop->recurring(3600 => \&per_hour);
831 my $perday = Mojo::IOLoop->recurring(86400 => \&per_day);