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";
162 @inqueue = (); # the main input queue, an array of hashes
163 $systime = 0; # the time now (in seconds)
164 $starttime = 0; # the starting time of the cluster
165 @outstanding_connects = (); # list of outstanding connects
166 @listeners = (); # list of listeners
167 $reqreg = 0; # 1 = registration required, 2 = deregister people
168 $bumpexisting = 1; # 1 = allow new connection to disconnect old, 0 - don't allow it
169 $allowdxby = 0; # 1 = allow "dx by <othercall>", 0 - don't allow it
170 $maxconnect_user = 3; # the maximum no of concurrent connections a user can have at a time
171 $maxconnect_node = 0; # Ditto but for nodes. In either case if a new incoming connection
172 # takes the no of references in the routing table above these numbers
173 # then the connection is refused. This only affects INCOMING connections.
174 $idle_interval = 0.500; # the wait between invocations of the main idle loop processing.
175 $log_flush_interval = 2; # interval to wait between log flushes
177 our $ending; # signal that we are ending;
178 our $broadcast_debug; # allow broadcasting of debug info down "enhanced" user connections
179 our $clssecs; # the amount of cpu time the DXSpider process have consumed
180 our $cldsecs; # the amount of cpu time any child processes have consumed
183 # send a message to call on conn and disconnect
186 my ($conn, $call, $mess) = @_;
188 $conn->disable_read(1);
189 dbg("-> D $call $mess\n") if isdbg('chan');
190 $conn->send_now("D$call|$mess");
195 # handle incoming messages
198 my ($conn, $msg) = @_;
199 my ($sort, $call, $line) = DXChannel::decode_input(0, $msg);
200 return unless defined $sort;
204 if (is_webcall($call) && $conn->isa('IntMsg')) {
205 my $newcall = find_next_webcall();
207 already_conn($conn, $call, "Maximum no of web connected connects ($Web::maxssid) exceeded");
211 $user = DXUser::get_current($call);
213 $user = DXUser->new($call);
217 $user->qth('on the web');
218 $user->homenode($main::mycall);
219 $user->lat($main::mylatitude);
220 $user->long($main::mylongitude);
221 $user->qra($main::mylocator);
224 $dxchan = Web->new($call, $conn, $user);
225 $dxchan->enhanced(1);
227 $msg =~ s/^A#WEB|/A$call|/;
228 $conn->send_now("C$call");
230 # "Normal" connections
231 unless (is_callsign($call)) {
232 already_conn($conn, $call, DXM::msg($lang, "illcall", $call));
236 # set up the basic channel info for "Normal" Users
237 # is there one already connected to me - locally?
239 $user = DXUser::get_current($call);
240 $dxchan = DXChannel::get($call);
242 if ($user && $user->is_node) {
243 already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
247 my $ip = $dxchan->hostname;
248 $dxchan->send_now('D', DXM::msg($lang, 'conbump', $call, $ip));
249 LogDbg('DXCommand', "$call bumped off by $ip, disconnected");
252 already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
257 # (fairly) politely disconnect people that are connected to too many other places at once
258 my $r = Route::get($call);
259 if ($conn->{sort} && $conn->{sort} =~ /^I/ && $r && $user) {
261 my $m = $r->isa('Route::Node') ? $maxconnect_node : $maxconnect_user;
262 my $c = $user->maxconnect;
264 $v = defined $c ? $c : $m;
265 if ($v && @n >= $v) {
266 my $nodes = join ',', @n;
267 LogDbg('DXCommand', "$call has too many connections ($v) at $nodes - disconnected");
268 already_conn($conn, $call, DXM::msg($lang, 'contomany', $call, $v, $nodes));
274 my $basecall = $call;
275 $basecall =~ s/-\d+$//;
276 my $baseuser = DXUser::get_current($basecall);
277 my $lock = $user->lockout if $user;
278 if ($baseuser && $baseuser->lockout || $lock) {
279 if (!$user || !defined $lock || $lock) {
280 my $host = $conn->peerhost;
281 LogDbg('DXCommand', "$call on $host is locked out, disconnected");
288 $user->{lang} = $main::lang if !$user->{lang}; # to autoupdate old systems
290 $user = DXUser->new($call);
294 if ($user->is_node) {
295 $dxchan = DXProt->new($call, $conn, $user);
296 } elsif ($user->is_user) {
297 $dxchan = DXCommandmode->new($call, $conn, $user);
299 die "Invalid sort of user on $call = $sort";
302 # check that the conn has a callsign
303 $conn->conns($call) if $conn->isa('IntMsg');
308 $conn->set_error(sub {my $err = shift; LogDbg('DXCommand', "Comms error '$err' received for call $dxchan->{call}"); $dxchan->disconnect(1);});
309 $conn->set_on_eof(sub {$dxchan->disconnect});
310 $conn->set_rproc(sub {my ($conn,$msg) = @_; $dxchan->rec($msg);});
312 $dxchan->enhanced(1);
321 return \&new_channel;
326 # cease running this program, close down all the connections nicely
331 cluck("ceasing") if $ceasing;
333 return if $ceasing++;
336 $SIG{'TERM'} = 'IGNORE';
337 $SIG{'INT'} = 'IGNORE';
342 if (defined &Local::finish) {
344 Local::finish(); # end local processing
346 dbg("Local::finish error $@") if $@;
354 # disconnect UDP customers
357 # end everything else
361 # close all databases
364 # close all listeners
365 foreach my $l (@listeners) {
369 LogDbg('cluster', "DXSpider V$version, build $build (git: $gitversion) ended");
370 dbg("bye bye everyone - bye bye");
374 $dbh->finish if $dbh;
379 # the reaper of children
383 while (($cpid = waitpid(-1, WNOHANG)) > 0) {
384 dbg("cpid: $cpid") if isdbg('reap');
385 # Msg->pid_gone($cpid);
386 $zombies-- if $zombies > 0;
388 dbg("cpid: $cpid") if isdbg('reap');
391 # this is where the input queue is dealt with and things are dispatched off to other parts of
396 my $t = $systime - $starttime;
397 my $days = int $t / 86400;
399 my $hours = int $t / 3600;
401 my $mins = int $t / 60;
402 return sprintf "%d %02d:%02d", $days, $hours, $mins;
407 AGWMsg::init(\&new_channel);
414 #############################################################
416 # The start of the main line of code
418 #############################################################
420 $starttime = $systime = time;
421 $systime_days = int ($systime / 86400);
422 $systime_daystart = $systime_days * 86400;
423 $lang = 'en' unless $lang;
425 unless ($DB::VERSION) {
426 $SIG{INT} = $SIG{TERM} = \&cease;
429 # open the debug file, set various FHs to be unbuffered
430 dbginit($broadcast_debug ? \&DXCommandmode::broadcast_debug : undef);
434 STDOUT->autoflush(1);
437 # try to load the database
438 if (DXSql::init($dsn)) {
439 $dbh = DXSql->new($dsn);
440 $dbh = $dbh->connect($dsn, $dbuser, $dbpass) if $dbh;
443 # try to load Encode and Git
446 my $w = $SIG{__DIE__};
447 $SIG{__DIE__} = 'IGNORE';
448 eval { require Encode; };
453 eval { require Git; };
457 # determine the real version number
458 my $repo = Git->repository(Directory => "$root/.git");
460 my $desc = $repo->command_oneline(['describe', '--long'], STDERR => 0);
462 my ($v, $s, $b, $g) = $desc =~ /^([\d.]+)(?:\.(\d+))?-(\d+)-g([0-9a-f]+)/;
465 $gitversion = "$g\[r]";
472 # try to load XML::Simple
476 my ($year) = (gmtime)[5];
478 LogDbg('cluster', "DXSpider V$version, build $build (git: $gitversion) started");
479 dbg("Copyright (c) 1998-$year Dirk Koopman G1TLH");
482 dbg("loading prefixes ...");
484 my $r = Prefix::init();
488 dbg("loading band data ...");
491 # initialise User file system
492 dbg("loading user file system ...");
495 # look for the sysop and the alias user and complain if they aren't there
497 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;
498 my $ref = DXUser::get($mycall);
499 die "$mycall missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
500 my $oldsort = $ref->sort;
501 if ($oldsort ne 'S') {
503 dbg "Resetting node type from $oldsort -> DXSpider ('S')";
505 $ref = DXUser::get($myalias);
506 die "$myalias missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
507 $oldsort = $ref->sort;
508 if ($oldsort ne 'U') {
510 dbg "Resetting sysop user type from $oldsort -> User ('U')";
514 # start listening for incoming messages/connects
515 dbg("starting listeners ...");
516 my $conn = IntMsg->new_server($clusteraddr, $clusterport, \&login);
517 $conn->conns("Server $clusteraddr/$clusterport using IntMsg");
518 push @listeners, $conn;
519 dbg("Internal port: $clusteraddr $clusterport using IntMsg");
520 foreach my $l (@main::listen) {
522 my $pkg = $l->[2] || 'ExtMsg';
523 my $login = $l->[3] || 'login';
525 $conn = $pkg->new_server($l->[0], $l->[1], \&{"${pkg}::${login}"});
526 $conn->conns("Server $l->[0]/$l->[1] using ${pkg}::${login}");
527 push @listeners, $conn;
528 dbg("External Port: $l->[0] $l->[1] using ${pkg}::${login}");
531 dbg("AGW Listener") if $AGWMsg::enable;
534 dbg("BPQ Listener") if $BPQMsg::enable;
535 BPQMsg::init(\&new_channel);
537 dbg("UDP Listener") if $UDPMsg::enable;
538 UDPMsg::init(\&new_channel);
541 dbg("load badwords: " . (BadWords::load or "Ok"));
544 unless ($DB::VERSION) {
545 $SIG{INT} = $SIG{TERM} = sub { $ending = 10; };
549 $SIG{HUP} = 'IGNORE';
550 $SIG{CHLD} = sub { $zombies++ };
552 $SIG{PIPE} = sub { dbg("Broken PIPE signal received"); };
553 $SIG{IO} = sub { dbg("SIGIO received"); };
554 $SIG{WINCH} = $SIG{STOP} = $SIG{CONT} = 'IGNORE';
555 $SIG{KILL} = 'DEFAULT'; # as if it matters....
557 # catch the rest with a hopeful message
560 # dbg("Catching SIG $_") if isdbg('chan');
561 $SIG{$_} = sub { my $sig = shift; DXDebug::confess("Caught signal $sig"); };
567 dbg("Starting Dupe system");
570 # read in system messages
571 dbg("Read in Messages");
574 # read in command aliases
575 dbg("Read in Aliases");
578 # initialise the Geomagnetic data engine
584 # initial the Spot stuff
585 dbg("Starting DX Spot system");
588 # initialise the protocol engine
589 dbg("Start Protocol Engines ...");
592 # put in a DXCluster node for us here so we can add users and take them away
593 $routeroot = Route::Node->new($mycall, $version*100+5300, Route::here($main::me->here)|Route::conf($main::me->conf));
594 $routeroot->do_pc9x(1);
595 $routeroot->via_pc92(1);
597 # make sure that there is a routing OUTPUT node default file
598 #unless (Filter::read_in('route', 'node_default', 0)) {
599 # my $dxcc = $main::me->dxcc;
600 # $Route::filterdef->cmd($main::me, 'route', 'accept', "node_default call $mycall" );
603 # read in any existing message headers and clean out old crap
604 dbg("reading existing message headers ...");
608 # read in any cron jobs
609 dbg("reading cron jobs ...");
612 # read in database desriptors
613 dbg("reading database descriptors ...");
616 # starting local stuff
617 dbg("doing local initialisation ...");
619 if (defined &Local::init) {
623 dbg("Local::init error $@") if $@;
627 # this, such as it is, is the main loop!
628 dbg("orft we jolly well go ...");
629 my $script = new Script "startup";
630 $script->run($main::me) if $script;
632 #open(DB::OUT, "|tee /tmp/aa");
635 our $io_disconnected;
640 # DXCommandmode::process(); # process ongoing command mode stuff
641 # DXProt::process(); # process ongoing ak1a pcxx stuff
643 if (defined &Local::process) {
645 Local::process(); # do any localised processing
647 dbg("Local::process error $@") if $@;
653 dbg("DXSpider Ending $ending");
655 unless ($io_disconnected++) {
658 foreach $dxchan (DXChannel::get_all_users) {
663 foreach $dxchan (DXChannel::get_all_nodes) {
664 next if $dxchan == $main::me;
665 $dxchan->disconnect(2);
667 $main::me->disconnect;
670 Mojo::IOLoop->stop if --$ending <= 0;
680 my $days = int ($systime / 86400);
681 if ($systime_days != $days) {
682 $systime_days = $days;
683 $systime_daystart = $days * 86400;
685 IsoTime::update($systime);
686 DXCommandmode::process(); # process ongoing command mode stuff
687 DXProt::process(); # process ongoing ak1a pcxx stuff
688 DXCron::process(); # do cron jobs
690 DXConnect::process();
695 DXCron::process(); # do cron jobs
696 IsoTime::update($systime);
697 DXConnect::process();
733 dbg("Before Web::start_node");
735 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
737 dbg("After Web::start_node");
742 my $main_loop = Mojo::IOLoop->recurring($idle_interval => \&idle_loop);
743 my $log_flush_loop = Mojo::IOLoop->recurring($log_flush_interval => \&DXLog::flushall);
744 my $cpusecs_loop = Mojo::IOLoop->recurring(5 => sub {my @t = times; $clssecs = $t[0]+$t[1]; $cldsecs = $t[2]+$t[3]});
745 my $persec = Mojo::IOLoop->recurring(1 => \&per_sec);
746 my $per10sec = Mojo::IOLoop->recurring(10 => \&per_10_sec);
747 my $permin = Mojo::IOLoop->recurring(60 => \&per_minute);
748 my $per10min = Mojo::IOLoop->recurring(600 => \&per_10_minute);
749 my $perhour = Mojo::IOLoop->recurring(3600 => \&per_hour);
750 my $perday = Mojo::IOLoop->recurring(86400 => \&per_day);