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 # make sure that modules are searched in the order local then perl
22 # take into account any local::lib that might be present
26 import local::lib unless ($@);
28 # root of directory tree for this system
30 $root = $ENV{'DXSPIDER_ROOT'} if $ENV{'DXSPIDER_ROOT'};
32 unshift @INC, "$root/perl"; # this IS the right way round!
33 unshift @INC, "$root/local";
35 # do some validation of the input
36 die "The directory $root doesn't exist, please RTFM" unless -d $root;
37 die "$root/local doesn't exist, please RTFM" unless -d "$root/local";
38 die "$root/local/DXVars.pm doesn't exist, please RTFM" unless -e "$root/local/DXVars.pm";
40 # create some directories
41 mkdir "$root/local_cmd", 02777 unless -d "$root/local_cmd";
42 mkdir "$root/local_data", 02777 unless -d "$root/local_data";
44 # try to create and lock a lockfile (this isn't atomic but
46 $lockfn = "$root/local_data/cluster.lck"; # lock file name
48 open(CLLOCK, "$lockfn") or die "Can't open Lockfile ($lockfn) $!";
53 warn "Lockfile ($lockfn) and process $pid exist, another cluster running?\n";
60 open(CLLOCK, ">$lockfn") or die "Can't open Lockfile ($lockfn) $!";
64 $is_win = ($^O =~ /^MS/ || $^O =~ /^OS-2/) ? 1 : 0; # is it Windows?
129 use POSIX ":sys_wait_h";
138 use vars qw(@inqueue $systime $starttime $lockfn @outstanding_connects
139 $zombies $root @listeners $lang $myalias @debug $userfn $clusteraddr
140 $clusterport $mycall $decease $is_win $routeroot $me $reqreg $bumpexisting
141 $allowdxby $dbh $dsn $dbuser $dbpass $do_xml $systime_days $systime_daystart
142 $can_encode $maxconnect_user $maxconnect_node $idle_interval $log_flush_interval
146 @inqueue = (); # the main input queue, an array of hashes
147 $systime = 0; # the time now (in seconds)
148 $starttime = 0; # the starting time of the cluster
149 @outstanding_connects = (); # list of outstanding connects
150 @listeners = (); # list of listeners
151 $reqreg = 0; # 1 = registration required, 2 = deregister people
152 $bumpexisting = 1; # 1 = allow new connection to disconnect old, 0 - don't allow it
153 $allowdxby = 0; # 1 = allow "dx by <othercall>", 0 - don't allow it
154 $maxconnect_user = 3; # the maximum no of concurrent connections a user can have at a time
155 $maxconnect_node = 0; # Ditto but for nodes. In either case if a new incoming connection
156 # takes the no of references in the routing table above these numbers
157 # then the connection is refused. This only affects INCOMING connections.
158 $idle_interval = 0.500; # the wait between invocations of the main idle loop processing.
159 $log_flush_interval = 2; # interval to wait between log flushes
161 our $ending; # signal that we are ending;
162 our $broadcast_debug; # allow broadcasting of debug info down "enhanced" user connections
163 our $clssecs; # the amount of cpu time the DXSpider process have consumed
164 our $cldsecs; # the amount of cpu time any child processes have consumed
167 # send a message to call on conn and disconnect
170 my ($conn, $call, $mess) = @_;
172 $conn->disable_read(1);
173 dbg("-> D $call $mess\n") if isdbg('chan');
174 $conn->send_now("D$call|$mess");
179 # handle incoming messages
182 my ($conn, $msg) = @_;
183 my ($sort, $call, $line) = DXChannel::decode_input(0, $msg);
184 return unless defined $sort;
186 unless (is_callsign($call)) {
187 already_conn($conn, $call, DXM::msg($lang, "illcall", $call));
191 # set up the basic channel info
192 # is there one already connected to me - locally?
193 my $user = DXUser::get_current($call);
194 my $dxchan = DXChannel::get($call);
196 if ($user && $user->is_node) {
197 already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
201 my $ip = $conn->peerhost || 'unknown';
202 $dxchan->send_now('D', DXM::msg($lang, 'conbump', $call, $ip));
203 LogDbg('DXCommand', "$call bumped off by $ip, disconnected");
206 already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
211 # (fairly) politely disconnect people that are connected to too many other places at once
212 my $r = Route::get($call);
213 if ($conn->{sort} && $conn->{sort} =~ /^I/ && $r && $user) {
215 my $m = $r->isa('Route::Node') ? $maxconnect_node : $maxconnect_user;
216 my $c = $user->maxconnect;
218 $v = defined $c ? $c : $m;
219 if ($v && @n >= $v) {
220 my $nodes = join ',', @n;
221 LogDbg('DXCommand', "$call has too many connections ($v) at $nodes - disconnected");
222 already_conn($conn, $call, DXM::msg($lang, 'contomany', $call, $v, $nodes));
228 my $basecall = $call;
229 $basecall =~ s/-\d+$//;
230 my $baseuser = DXUser::get_current($basecall);
231 my $lock = $user->lockout if $user;
232 if ($baseuser && $baseuser->lockout || $lock) {
233 if (!$user || !defined $lock || $lock) {
234 my $host = $conn->peerhost || "unknown";
235 LogDbg('DXCommand', "$call on $host is locked out, disconnected");
242 $user->{lang} = $main::lang if !$user->{lang}; # to autoupdate old systems
244 $user = DXUser->new($call);
248 if ($user->is_node) {
249 $dxchan = DXProt->new($call, $conn, $user);
250 } elsif ($user->is_user) {
251 $dxchan = DXCommandmode->new($call, $conn, $user);
252 # } elsif ($user->is_bbs) { # there is no support so
253 # $dxchan = BBS->new($call, $conn, $user); # don't allow it!!!
255 die "Invalid sort of user on $call = $sort";
258 # check that the conn has a callsign
259 $conn->conns($call) if $conn->isa('IntMsg');
262 $conn->set_error(sub {my $err = shift; LogDbg('DXCommand', "Comms error '$err' received for call $dxchan->{call}"); $dxchan->disconnect(1);});
263 $conn->set_on_eof(sub {$dxchan->disconnect});
264 $conn->set_rproc(sub {my ($conn,$msg) = @_; $dxchan->rec($msg);});
271 return \&new_channel;
276 # cease running this program, close down all the connections nicely
281 cluck("ceasing") if $ceasing;
283 return if $ceasing++;
286 $SIG{'TERM'} = 'IGNORE';
287 $SIG{'INT'} = 'IGNORE';
292 if (defined &Local::finish) {
294 Local::finish(); # end local processing
296 dbg("Local::finish error $@") if $@;
304 # disconnect UDP customers
307 # end everything else
311 # close all databases
314 # close all listeners
315 foreach my $l (@listeners) {
319 LogDbg('cluster', "DXSpider V$version, build $build (git: $gitversion) ended");
320 dbg("bye bye everyone - bye bye");
324 $dbh->finish if $dbh;
329 # the reaper of children
333 while (($cpid = waitpid(-1, WNOHANG)) > 0) {
334 dbg("cpid: $cpid") if isdbg('reap');
335 # Msg->pid_gone($cpid);
336 $zombies-- if $zombies > 0;
338 dbg("cpid: $cpid") if isdbg('reap');
341 # this is where the input queue is dealt with and things are dispatched off to other parts of
346 my $t = $systime - $starttime;
347 my $days = int $t / 86400;
349 my $hours = int $t / 3600;
351 my $mins = int $t / 60;
352 return sprintf "%d %02d:%02d", $days, $hours, $mins;
357 AGWMsg::init(\&new_channel);
364 #############################################################
366 # The start of the main line of code
368 #############################################################
370 $starttime = $systime = time;
371 $systime_days = int ($systime / 86400);
372 $systime_daystart = $systime_days * 86400;
373 $lang = 'en' unless $lang;
375 unless ($DB::VERSION) {
376 $SIG{INT} = $SIG{TERM} = \&cease;
379 # open the debug file, set various FHs to be unbuffered
380 dbginit($broadcast_debug ? \&DXCommandmode::broadcast_debug : undef);
384 STDOUT->autoflush(1);
387 # try to load the database
388 if (DXSql::init($dsn)) {
389 $dbh = DXSql->new($dsn);
390 $dbh = $dbh->connect($dsn, $dbuser, $dbpass) if $dbh;
393 # try to load Encode and Git
396 my $w = $SIG{__DIE__};
397 $SIG{__DIE__} = 'IGNORE';
398 eval { require Encode; };
403 eval { require Git; };
407 # determine the real version number
408 my $repo = Git->repository(Directory => "$root/.git");
410 my $desc = $repo->command_oneline(['describe', '--long'], STDERR => 0);
412 my ($v, $s, $b, $g) = $desc =~ /^([\d.]+)(?:\.(\d+))?-(\d+)-g([0-9a-f]+)/;
415 $gitversion = "$g\[r]";
422 # try to load XML::Simple
426 my ($year) = (gmtime)[5];
428 LogDbg('cluster', "DXSpider V$version, build $build (git: $gitversion) started");
429 dbg("Copyright (c) 1998-$year Dirk Koopman G1TLH");
432 dbg("loading prefixes ...");
434 my $r = Prefix::init();
438 dbg("loading band data ...");
441 # initialise User file system
442 dbg("loading user file system ...");
445 # look for the sysop and the alias user and complain if they aren't there
447 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;
448 my $ref = DXUser::get($mycall);
449 die "$mycall missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
450 my $oldsort = $ref->sort;
451 if ($oldsort ne 'S') {
453 dbg "Resetting node type from $oldsort -> DXSpider ('S')";
455 $ref = DXUser::get($myalias);
456 die "$myalias missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
457 $oldsort = $ref->sort;
458 if ($oldsort ne 'U') {
460 dbg "Resetting sysop user type from $oldsort -> User ('U')";
464 # start listening for incoming messages/connects
465 dbg("starting listeners ...");
466 my $conn = IntMsg->new_server($clusteraddr, $clusterport, \&login);
467 $conn->conns("Server $clusteraddr/$clusterport using IntMsg");
468 push @listeners, $conn;
469 dbg("Internal port: $clusteraddr $clusterport using IntMsg");
470 foreach my $l (@main::listen) {
472 my $pkg = $l->[2] || 'ExtMsg';
473 my $login = $l->[3] || 'login';
475 $conn = $pkg->new_server($l->[0], $l->[1], \&{"${pkg}::${login}"});
476 $conn->conns("Server $l->[0]/$l->[1] using ${pkg}::${login}");
477 push @listeners, $conn;
478 dbg("External Port: $l->[0] $l->[1] using ${pkg}::${login}");
481 dbg("AGW Listener") if $AGWMsg::enable;
484 dbg("BPQ Listener") if $BPQMsg::enable;
485 BPQMsg::init(\&new_channel);
487 dbg("UDP Listener") if $UDPMsg::enable;
488 UDPMsg::init(\&new_channel);
491 dbg("load badwords: " . (BadWords::load or "Ok"));
494 unless ($DB::VERSION) {
495 $SIG{INT} = $SIG{TERM} = sub { $ending = 10; };
499 $SIG{HUP} = 'IGNORE';
500 $SIG{CHLD} = sub { $zombies++ };
502 $SIG{PIPE} = sub { dbg("Broken PIPE signal received"); };
503 $SIG{IO} = sub { dbg("SIGIO received"); };
504 $SIG{WINCH} = $SIG{STOP} = $SIG{CONT} = 'IGNORE';
505 $SIG{KILL} = 'DEFAULT'; # as if it matters....
507 # catch the rest with a hopeful message
510 # dbg("Catching SIG $_") if isdbg('chan');
511 $SIG{$_} = sub { my $sig = shift; DXDebug::confess("Caught signal $sig"); };
517 dbg("Starting Dupe system");
520 # read in system messages
521 dbg("Read in Messages");
524 # read in command aliases
525 dbg("Read in Aliases");
528 # initialise the Geomagnetic data engine
534 # initial the Spot stuff
535 dbg("Starting DX Spot system");
538 # initialise the protocol engine
539 dbg("Start Protocol Engines ...");
542 # put in a DXCluster node for us here so we can add users and take them away
543 $routeroot = Route::Node->new($mycall, $version*100+5300, Route::here($main::me->here)|Route::conf($main::me->conf));
544 $routeroot->do_pc9x(1);
545 $routeroot->via_pc92(1);
547 # make sure that there is a routing OUTPUT node default file
548 #unless (Filter::read_in('route', 'node_default', 0)) {
549 # my $dxcc = $main::me->dxcc;
550 # $Route::filterdef->cmd($main::me, 'route', 'accept', "node_default call $mycall" );
553 # read in any existing message headers and clean out old crap
554 dbg("reading existing message headers ...");
558 # read in any cron jobs
559 dbg("reading cron jobs ...");
562 # read in database desriptors
563 dbg("reading database descriptors ...");
566 # starting local stuff
567 dbg("doing local initialisation ...");
569 if (defined &Local::init) {
573 dbg("Local::init error $@") if $@;
577 # this, such as it is, is the main loop!
578 dbg("orft we jolly well go ...");
579 my $script = new Script "startup";
580 $script->run($main::me) if $script;
582 #open(DB::OUT, "|tee /tmp/aa");
585 our $io_disconnected;
591 if (defined &Local::process) {
593 Local::process(); # do any localised processing
595 dbg("Local::process error $@") if $@;
601 dbg("DXSpider Ending $ending");
603 unless ($io_disconnected++) {
606 foreach $dxchan (DXChannel::get_all_users) {
611 foreach $dxchan (DXChannel::get_all_nodes) {
612 next if $dxchan == $main::me;
613 $dxchan->disconnect(2);
615 $main::me->disconnect;
618 Mojo::IOLoop->stop if --$ending <= 0;
628 my $days = int ($systime / 86400);
629 if ($systime_days != $days) {
630 $systime_days = $days;
631 $systime_daystart = $days * 86400;
633 IsoTime::update($systime);
634 DXCron::process(); # do cron jobs
635 DXCommandmode::process(); # process ongoing command mode stuff
637 DXProt::process(); # process ongoing ak1a pcxx stuff
638 DXConnect::process();
643 DXCron::process(); # do cron jobs
644 IsoTime::update($systime);
645 DXProt::process(); # process ongoing ak1a pcxx stuff
646 DXConnect::process();
682 my $main_loop = Mojo::IOLoop->recurring($idle_interval => \&idle_loop);
683 my $log_flush_loop = Mojo::IOLoop->recurring($log_flush_interval => \&DXLog::flushall);
684 my $cpusecs_loop = Mojo::IOLoop->recurring(5 => sub {my @t = times; $clssecs = $t[0]+$t[1]; $cldsecs = $t[2]+$t[3]});
685 my $persec = Mojo::IOLoop->recurring(1 => \&per_sec);
686 my $per10sec = Mojo::IOLoop->recurring(10 => \&per_10_sec);
687 my $permin = Mojo::IOLoop->recurring(60 => \&per_minute);
688 my $per10min = Mojo::IOLoop->recurring(600 => \&per_10_minute);
689 my $perhour = Mojo::IOLoop->recurring(3600 => \&per_hour);
690 my $perday = Mojo::IOLoop->recurring(86400 => \&per_day);