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
24 $broadcast_debug $yes $no $user_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
36 # set default paths, these should be overwritten by DXVars.pm
37 use vars qw($data $system $cmd $localcmd $userfn $clusteraddr $clusterport $yes $no $user_interval $lang $local_data);
39 $lang = 'en'; # default language
40 $yes = 'Yes'; # visual representation of yes
41 $no = 'No'; # ditto for no
42 $user_interval = 11*60; # the interval between unsolicited prompts if no traffic
45 # make sure that modules are searched in the order local then perl
48 $SIG{'__WARN__'} = sub { warn $_[0] if $DOWARN };
50 # take into account any local::lib that might be present
56 import local::lib qw(/spider/perl5lib);
59 # root of directory tree for this system
61 $root = $ENV{'DXSPIDER_ROOT'} if $ENV{'DXSPIDER_ROOT'};
63 unshift @INC, "$root/perl5lib" unless grep {$_ eq "$root/perl5lib"} @INC;
64 unshift @INC, "$root/perl"; # this IS the right way round!
65 unshift @INC, "$root/local";
67 # do some validation of the input
68 die "The directory $root doesn't exist, please RTFM" unless -d $root;
69 die "$root/local doesn't exist, please RTFM" unless -d "$root/local";
70 die "$root/local/DXVars.pm doesn't exist, please RTFM" unless -e "$root/local/DXVars.pm";
72 # create some directories
73 mkdir "$root/local_cmd", 02774 unless -d "$root/local_cmd";
75 # locally stored data lives here
76 $local_data = "$root/local_data";
77 mkdir $local_data, 02774 unless -d $local_data;
79 $system = "$root/sys";
81 $localcmd = "$root/local_cmd";
82 $userfn = "$data/users";
84 # try to create and lock a lockfile (this isn't atomic but
86 $lockfn = "$root/local_data/cluster.lck"; # lock file name
88 open(CLLOCK, "$lockfn") or die "Can't open Lockfile ($lockfn) $!";
93 warn "Lockfile ($lockfn) and process $pid exist, another cluster running?\n";
100 open(CLLOCK, ">$lockfn") or die "Can't open Lockfile ($lockfn) $!";
104 $is_win = ($^O =~ /^MS/ || $^O =~ /^OS-2/) ? 1 : 0; # is it Windows?
113 # order here is important - DXDebug snarfs Carp et al so that Mojo errors go into the debug log
114 use Mojolicious 7.26;
176 use POSIX ":sys_wait_h";
183 $lang //= 'en'; # default language
184 $clusteraddr //= '127.0.0.1'; # cluster tcp host address - used for things like console.pl
185 $clusterport //= 27754; # cluster tcp port
186 $yes //= 'Yes'; # visual representation of yes
187 $no //= 'No'; # ditto for no
188 $user_interval //= 11*60; # the interval between unsolicited prompts if no traffic
190 @inqueue = (); # the main input queue, an array of hashes
191 $systime = 0; # the time now (in seconds)
192 $starttime = 0; # the starting time of the cluster
193 @outstanding_connects = (); # list of outstanding connects
194 @listeners = (); # list of listeners
195 $reqreg = 0; # 1 = registration required, 2 = deregister people
196 $bumpexisting = 1; # 1 = allow new connection to disconnect old, 0 - don't allow it
197 our $allowmultiple = 0; # This is used in conjunction with $bumpexisting, in a rather weird way.
198 our $min_reconnection_rate = 5*60; # minimum value of seconds between connections per user to allow co-existing users
199 our $max_ssid = 15; # highest ssid to be searched for a spare one on multiple connections
201 # If $allowmultiple > 0 and the $reconnection_rate is some value of seconds
202 # based on the average connection time calculated from the $user->conntimel entries / frequency is
203 # less than $reconnection_rate then we assume that there is more than one device (probably HRD) trying
204 # to connect "at once". In which case we probe for a spare SSID for a user callsign to allow up to
205 # $allowmultiple connections per callsign.
207 $allowdxby = 0; # 1 = allow "dx by <othercall>", 0 - don't allow it
208 $maxconnect_user = 3; # the maximum no of concurrent connections a user can have at a time
209 $maxconnect_node = 0; # Ditto but for nodes. In either case if a new incoming connection
210 # takes the no of references in the routing table above these numbers
211 # then the connection is refused. This only affects INCOMING connections.
212 $idle_interval = 0.500; # the wait between invocations of the main idle loop processing.
213 $log_flush_interval = 2; # interval to wait between log flushes
215 our $ending; # signal that we are ending;
216 our $broadcast_debug; # allow broadcasting of debug info down "enhanced" user connections
217 our $clssecs; # the amount of cpu time the DXSpider process have consumed
218 our $cldsecs; # the amount of cpu time any child processes have consumed
219 our $allowslashcall; # Allow / in connecting callsigns (ie PA0/G1TLH, or even PA0/G1TLH/2)
221 our @localhost_names = qw(127.0.0.1 ::1); # all ip addresses that will need to be aliased below (ipv4 or ipv6)
223 our $localhost_alias_ipv4; # these are the IPV4 & 6 aliases for localhost connected clients
224 our $localhost_alias_ipv6; # for things (PC92, PC61 etc) that expose IP addresses. These *may*
225 # be set by Msg.pm stuff if they are left undefined but, if you need
226 # certanty then set/var them in the startup file.
228 our $save_route_cache; # save and restore route cache on restart. Probably only useful for G1TLH testing
230 use vars qw($version $subversion $build $gitversion $gitbranch);
232 # send a message to call on conn and disconnect
235 my ($conn, $call, $mess) = @_;
237 $conn->disable_read(1);
238 dbg("-> D $call $mess\n") if isdbg('chan');
239 $conn->send_now("D$call|$mess");
244 # handle incoming messages
247 my ($conn, $msg) = @_;
248 my ($sort, $call, $line) = DXChannel::decode_input(0, $msg);
249 return unless defined $sort;
253 if (is_webcall($call) && $conn->isa('IntMsg')) {
254 my $newcall = find_next_webcall();
256 already_conn($conn, $call, "Maximum no of web connected connects ($Web::maxssid) exceeded");
259 $call = normalise_call($newcall);
261 $user = DXUser::get_current($call);
263 $user = DXUser->new($call);
267 $user->qth('on the web');
268 $user->homenode($main::mycall);
269 $user->lat($main::mylatitude);
270 $user->long($main::mylongitude);
271 $user->qra($main::mylocator);
273 $user->startt($main::systime);
275 $dxchan = Web->new($call, $conn, $user);
276 $dxchan->enhanced(1);
278 $msg =~ s/^A#WEB|/A$call|/;
279 $conn->send_now("C$call");
281 # "Normal" connections
283 # normalise calls like G1TST-0/G1TST-00/G1TST-01 to G1TST and G1TST-1 respectively
284 my $ncall = normalise_call($call);
285 if ($call ne $ncall) {
286 LogDbg('err', "new_channel login invalid $call converted to $ncall");
287 $msg =~ s/$call/$ncall/;
290 # is it a valid callsign (in format)?
291 unless (is_callsign($call)) {
292 already_conn($conn, $call, DXM::msg($lang, "illcall", $call));
299 $user = DXUser::get_current($call);
300 my $basecall = $call;
301 $basecall =~ s/-\d+$//; # remember this for later multiple user processing, it's used for other stuff than checking lockout status
303 # make sure we act on any locked status that the actual incoming call has.
304 $lock = $user->lockout;
305 } elsif ($basecall ne $call) {
306 # if there isn't a SSID on the $call, then try the base
307 my $luser = DXUser::get_current($basecall);
308 $lock = $luser->lockout if $luser;
311 # now deal with the lock
312 my $host = $conn->peerhost;
314 LogDbg('', "$call on $host is locked out, disconnected");
319 # Is he from a badip?
320 if (DXCIDR::find($host)) {
321 LogDbg('', "$call on $host is from a badip $host, disconnected");
326 # set up the basic channel info for "Normal" Users
327 # is there one already connected to me - locally?
329 $dxchan = DXChannel::get($call);
332 if ($user && $user->is_node) {
333 already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
336 if ($allowmultiple && $user->is_user) {
337 # determine whether we are a candidate, have we flip-flopped frequently enough?
338 my @lastconns = @{$user->connlist} if $user->connlist;
340 if (@lastconns >= $DXUser::maxconnlist) {
341 $allow = $lastconns[-1]->[0] - $lastconns[0]->[0] < $min_reconnection_rate;
343 # search for a spare ssid
344 L1: for (my $count = $call =~ /-\d+$/?0:1; $allow && $count < $allowmultiple; ) { # remember we have one call already
346 for (; $lastid < $max_ssid && $count < $allowmultiple; ++$lastid) {
347 my $chan = DXChannel::get("$basecall-$lastid");
352 # we have a free call-ssid, save it
353 $newcall = "$basecall-$lastid";
359 # handle "normal" (non-multiple) connections in the existing way
360 if ($call eq $newcall) {
362 my $ip = $dxchan->hostname;
363 $dxchan->send_now('D', DXM::msg($lang, 'conbump', $call, $ip));
364 LogDbg('', "$call bumped off by $ip, disconnected");
367 already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
372 # make sure that the conn has the (possibly) new callsign
373 $conn->conns($newcall);
374 $msg =~ s/$call/$newcall/;
378 # (fairly) politely disconnect people that are connected to too many other places at once
379 my $r = Route::get($call);
380 if ($conn->{sort} && $conn->{sort} =~ /^I/ && $r && $user) {
382 my $m = $r->isa('Route::Node') ? $maxconnect_node : $maxconnect_user;
383 my $c = $user->maxconnect;
385 $v = defined $c ? $c : $m;
386 if ($v && @n >= $v+$allowmultiple) {
387 my $nodes = join ',', @n;
388 LogDbg('', "$call has too many connections ($v) at $nodes - disconnected");
389 already_conn($conn, $call, DXM::msg($lang, 'contomany', $call, $v, $nodes));
395 $user->{lang} = $main::lang if !$user->{lang}; # to autoupdate old systems
397 $user = DXUser->new($call);
401 # NOTE we are SHARING the same $user if $allowmultiple is > 1
403 $user->startt($systime); # mark the start time of this connection
404 if ($user->is_node) {
405 $dxchan = DXProt->new($call, $conn, $user);
406 } elsif ($user->is_rbn) {
407 $dxchan = RBN->new($newcall, $conn, $user);
408 } elsif ($user->is_user) {
409 $dxchan = DXCommandmode->new($newcall, $conn, $user);
411 die "Invalid sort of user on $call = $sort";
417 $conn->set_error(sub {my $err = shift; LogDbg('', "Comms error '$err' received for call $dxchan->{call}"); $dxchan->disconnect(1);});
418 $conn->set_on_eof(sub {$dxchan->disconnect});
419 $conn->set_rproc(sub {my ($conn,$msg) = @_; $dxchan->rec($msg);});
421 $dxchan->enhanced(1);
430 return \&new_channel;
435 # cease running this program, close down all the connections nicely
440 cluck("ceasing") if $ceasing;
442 return if $ceasing++;
444 dbg("DXSpider Ceasing");
447 $SIG{'TERM'} = 'IGNORE';
448 $SIG{'INT'} = 'IGNORE';
452 if (defined &Local::finish) {
454 Local::finish(); # end local processing
456 dbg("Local::finish error $@") if $@;
464 # disconnect UDP customers
467 # end everything else
472 # close all databases
476 Route::write_cache() if $save_route_cache;
478 # close all listeners
479 foreach my $l (@listeners) {
485 LogDbg('cluster', "DXSpider v$version build $build (git: $gitbranch/$gitversion) using perl $^V on $^O ended");
486 dbg("bye bye everyone - bye bye");
490 $dbh->finish if $dbh;
495 # the reaper of children
499 while (($cpid = waitpid(-1, WNOHANG)) > 0) {
500 dbg("cpid: $cpid") if isdbg('reap');
501 # Msg->pid_gone($cpid);
502 $zombies-- if $zombies > 0;
504 dbg("cpid: $cpid") if isdbg('reap');
507 # this is where the input queue is dealt with and things are dispatched off to other parts of
512 my $t = $systime - $starttime;
513 my $days = int $t / 86400;
515 my $hours = int $t / 3600;
517 my $mins = int $t / 60;
518 return sprintf "%d %02d:%02d", $days, $hours, $mins;
523 AGWMsg::init(\&new_channel);
528 #############################################################
530 # The start of the main line of code
532 #############################################################
536 $starttime = $systime = time;
537 $systime_days = int ($systime / 86400);
538 $systime_daystart = $systime_days * 86400;
539 $lang = 'en' unless $lang;
541 unless ($DB::VERSION) {
542 $SIG{INT} = $SIG{TERM} = \&cease;
545 # open the debug file, set various FHs to be unbuffered
546 dbginit(undef, $broadcast_debug ? \&DXCommandmode::broadcast_debug : undef);
550 STDOUT->autoflush(1);
553 dbg "Perl path: " . join(':', @INC);
555 # try to load Encode and Git
558 my $w = $SIG{__DIE__};
559 $SIG{__DIE__} = 'IGNORE';
560 eval { require Encode; };
567 $gitversion = 'none';
569 # determine the real Git build number and branch
571 eval {$desc = `git --git-dir=$root/.git describe --long`};
573 my ($v, $s, $b, $g) = $desc =~ /^([\d\.]+)(?:\.(\d+))?-(\d+)-g([0-9a-f]+)/;
575 my $subversion = $s || 0; # not used elsewhere
577 $gitversion = "$g\[r]";
582 eval {@branch = `git --git-dir=$root/.git branch`};
585 my ($star, $b) = split /\s+/;
598 $SIG{HUP} = 'IGNORE';
599 $SIG{CHLD} = sub { $zombies++ };
601 $SIG{PIPE} = sub { dbg("Broken PIPE signal received"); };
602 $SIG{IO} = sub { dbg("SIGIO received"); };
603 $SIG{WINCH} = $SIG{STOP} = $SIG{CONT} = 'IGNORE';
604 $SIG{KILL} = 'DEFAULT'; # as if it matters....
606 # catch the rest with a hopeful message
609 # dbg("Catching SIG $_") if isdbg('chan');
610 $SIG{$_} = sub { my $sig = shift; DXDebug::confess("Caught signal $sig"); };
617 my ($year) = (gmtime)[5];
619 LogDbg('cluster', "DXSpider v$version build $build (git: $gitbranch/$gitversion) using perl $^V on $^O started");
620 LogDbg('cluster', "Copyright (c) 1998-$year Dirk Koopman G1TLH");
621 LogDbg('cluster', "Capabilities: ve7cc rbn");
624 unless ($DB::VERSION) {
625 $SIG{INT} = $SIG{TERM} = sub { $ending = 10; };
629 # setup location of motd & issue
631 $motd = localdata($motd);
632 localdata_mv("issue");
635 # try to load XML::Simple
640 dbg("loading prefixes ...");
642 my $r = Prefix::init();
646 dbg("loading band data ...");
649 # initialise User file system
650 dbg("loading user file system ...");
651 DXUser::init(4); # version 4 == json format
653 Filter::init(); # doesn't do much, but has to be done
656 # look for the sysop and the alias user and complain if they aren't there
658 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;
659 my $ref = DXUser::get($mycall);
660 die "\$mycall missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
661 my $oldsort = $ref->sort;
662 if ($oldsort ne 'S') {
664 dbg("Resetting node type from $oldsort -> DXSpider ('S')");
666 $ref = DXUser::get($myalias);
667 die "\$myalias missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
668 $oldsort = $ref->sort;
669 if ($oldsort ne 'U') {
671 dbg("Resetting sysop user type from $oldsort -> User ('U')");
675 # make sure that mycall, myalias and homenode are upper case;
677 if ($mycall =~ /[a-z]/) {
678 LogDbg('err', "\$mycall '$mycall' contains lower case letters, correcting");
679 $mycall = uc $mycall;
682 if ($myalias =~ /[a-z]/) {
683 LogDbg('err', "\$myalias '$myalias' contains lower case letters, correcting");
684 $myalias = uc $myalias;
688 LogDbg('err', "DXVars.pm has $flag errors. See above. Please edit DXVars.pm to correct");
692 # read any route cache there might be
693 Route::read_cache() if $save_route_cache;
695 # start listening for incoming messages/connects
696 dbg("starting listeners ...");
697 my $conn = IntMsg->new_server($clusteraddr, $clusterport, \&login);
698 $conn->conns("Server $clusteraddr/$clusterport using IntMsg");
699 push @listeners, $conn;
700 dbg("Internal port: $clusteraddr $clusterport using IntMsg");
701 foreach my $l (@main::listen) {
703 my $pkg = $l->[2] || 'ExtMsg';
704 my $login = $l->[3] || 'login';
706 $conn = $pkg->new_server($l->[0], $l->[1], \&{"${pkg}::${login}"});
707 $conn->conns("Server $l->[0]/$l->[1] using ${pkg}::${login}");
708 push @listeners, $conn;
709 dbg("External Port: $l->[0] $l->[1] using ${pkg}::${login}");
713 dbg("AGW Listener") if $AGWMsg::enable;
716 dbg("BPQ Listener") if $BPQMsg::enable;
717 BPQMsg::init(\&new_channel);
719 dbg("UDP Listener") if $UDPMsg::enable;
720 UDPMsg::init(\&new_channel);
723 dbg("Starting Dupe system");
726 # read in system messages
727 dbg("Read in Messages");
730 # read in command aliases
731 dbg("Read in Aliases");
734 # initialise the protocol engine
735 dbg("Start Protocol Engines ...");
738 # read startup script
739 my $script = new Script "startup";
740 $script->run($main::me) if $script;
743 # initialise the Geomagnetic data engine
744 dbg("Start WWV system");
746 dbg("Start WCY system");
748 dbg("Start Announce and Talk system");
749 AnnTalk::init(); # initialise announce cache
752 # put in a DXCluster node for us here so we can add users and take them away
753 $routeroot = Route::Node->new($mycall, $version*100+5300, Route::here($main::me->here)|Route::conf($main::me->conf));
754 $routeroot->do_pc9x(1);
755 $routeroot->via_pc92(1);
757 # make sure that there is a routing OUTPUT node default file
758 #unless (Filter::read_in('route', 'node_default', 0)) {
759 # my $dxcc = $main::me->dxcc;
760 # $Route::filterdef->cmd($main::me, 'route', 'accept', "node_default call $mycall" );
763 # initial the Spot stuff
764 dbg("Starting DX Spot system");
767 # try to load the spot database if present
768 if (DXSql::init($dsn)) {
769 $dbh = DXSql->new($dsn);
770 $dbh = $dbh->connect($dsn, $dbuser, $dbpass) if $dbh;
774 # read in any existing message headers and clean out old crap
775 dbg("Reading existing Message/Bulletine headers ...");
779 # read in any cron jobs
780 dbg("Reading cron jobs ...");
783 # read in database desriptors
784 dbg("Reading database descriptors ...");
787 dbg("Rtarting RBN ...");
790 # starting local stuff
791 dbg("Starting DXQsl system");
801 dbg("Ooing local initialisations ...");
802 if (defined &Local::init) {
806 dbg("Local::init error $@") if $@;
810 # this, such as it is, is the main loop!
811 dbg("Orft we jolly well go ...");
813 #open(DB::OUT, "|tee /tmp/aa");
816 our $io_disconnected;
821 # DXCommandmode::process(); # process ongoing command mode stuff
822 # DXProt::process(); # process ongoing ak1a pcxx stuff
824 if (defined &Local::process) {
826 Local::process(); # do any localised processing
828 dbg("Local::process error $@") if $@;
834 dbg("DXSpider Ending $ending");
836 unless ($io_disconnected++) {
839 foreach $dxchan (DXChannel::get_all_users) {
844 foreach $dxchan (DXChannel::get_all_nodes) {
845 next if $dxchan == $main::me;
846 $dxchan->disconnect(2);
848 $main::me->disconnect;
851 Mojo::IOLoop->stop_gracefully if --$ending <= 0;
861 my $days = int ($systime / 86400);
862 if ($systime_days != $days) {
863 $systime_days = $days;
864 $systime_daystart = $days * 86400;
866 IsoTime::update($systime);
867 DXCommandmode::process(); # process ongoing command mode stuff
868 DXProt::process(); # process ongoing ak1a pcxx stuff
870 DXConnect::process();
875 IsoTime::update($systime);
876 DXConnect::process();
879 DXCron::process(); # do cron jobs
898 RBN::per_10_minute();
899 Route::write_cache() if $save_route_cache;
914 dbg("Before Web::start_node");
916 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
918 dbg("After Web::start_node");
924 my $main_loop = Mojo::IOLoop->recurring($idle_interval => \&idle_loop);
925 my $log_flush_loop = Mojo::IOLoop->recurring($log_flush_interval => \&DXLog::flushall);
926 my $cpusecs_loop = Mojo::IOLoop->recurring(5 => sub {my @t = times; $clssecs = $t[0]+$t[1]; $cldsecs = $t[2]+$t[3]});
927 my $persec = Mojo::IOLoop->recurring(1 => \&per_sec);
928 my $per10sec = Mojo::IOLoop->recurring(10 => \&per_10_sec);
929 my $permin = Mojo::IOLoop->recurring(60 => \&per_minute);
930 my $per10min = Mojo::IOLoop->recurring(600 => \&per_10_minute);
931 my $perhour = Mojo::IOLoop->recurring(3600 => \&per_hour);
932 my $perday = Mojo::IOLoop->recurring(86400 => \&per_day);
943 print "DXSpider Ending\n";