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 # root of directory tree for this system
24 $root = $ENV{'DXSPIDER_ROOT'} if $ENV{'DXSPIDER_ROOT'};
26 unshift @INC, "$root/perl"; # this IS the right way round!
27 unshift @INC, "$root/local";
29 # do some validation of the input
30 die "The directory $root doesn't exist, please RTFM" unless -d $root;
31 die "$root/local doesn't exist, please RTFM" unless -d "$root/local";
32 die "$root/local/DXVars.pm doesn't exist, please RTFM" unless -e "$root/local/DXVars.pm";
34 # create some directories
35 mkdir "$root/local_cmd", 02777 unless -d "$root/local_cmd";
36 mkdir "$root/local_data", 02777 unless -d "$root/local_data";
38 # try to create and lock a lockfile (this isn't atomic but
40 $lockfn = "$root/local_data/cluster.lck"; # lock file name
42 open(CLLOCK, "$lockfn") or die "Can't open Lockfile ($lockfn) $!";
47 warn "Lockfile ($lockfn) and process $pid exist, another cluster running?\n";
54 open(CLLOCK, ">$lockfn") or die "Can't open Lockfile ($lockfn) $!";
58 $is_win = ($^O =~ /^MS/ || $^O =~ /^OS-2/) ? 1 : 0; # is it Windows?
124 use POSIX ":sys_wait_h";
133 use vars qw(@inqueue $systime $starttime $lockfn @outstanding_connects
134 $zombies $root @listeners $lang $myalias @debug $userfn $clusteraddr
135 $clusterport $mycall $decease $is_win $routeroot $me $reqreg $bumpexisting
136 $allowdxby $dbh $dsn $dbuser $dbpass $do_xml $systime_days $systime_daystart
137 $can_encode $maxconnect_user $maxconnect_node $idle_interval $log_flush_interval
141 @inqueue = (); # the main input queue, an array of hashes
142 $systime = 0; # the time now (in seconds)
143 $starttime = 0; # the starting time of the cluster
144 @outstanding_connects = (); # list of outstanding connects
145 @listeners = (); # list of listeners
146 $reqreg = 0; # 1 = registration required, 2 = deregister people
147 $bumpexisting = 1; # 1 = allow new connection to disconnect old, 0 - don't allow it
148 $allowdxby = 0; # 1 = allow "dx by <othercall>", 0 - don't allow it
149 $maxconnect_user = 3; # the maximum no of concurrent connections a user can have at a time
150 $maxconnect_node = 0; # Ditto but for nodes. In either case if a new incoming connection
151 # takes the no of references in the routing table above these numbers
152 # then the connection is refused. This only affects INCOMING connections.
153 $idle_interval = 0.500; # the wait between invocations of the main idle loop processing.
154 $log_flush_interval = 2; # interval to wait between log flushes
156 our $ending; # signal that we are ending;
157 our $broadcast_debug; # allow broadcasting of debug info down "enhanced" user connections
158 our $clssecs; # the amount of cpu time the DXSpider process have consumed
159 our $cldsecs; # the amount of cpu time any child processes have consumed
162 # send a message to call on conn and disconnect
165 my ($conn, $call, $mess) = @_;
167 $conn->disable_read(1);
168 dbg("-> D $call $mess\n") if isdbg('chan');
169 $conn->send_now("D$call|$mess");
174 # handle incoming messages
177 my ($conn, $msg) = @_;
178 my ($sort, $call, $line) = DXChannel::decode_input(0, $msg);
179 return unless defined $sort;
181 unless (is_callsign($call)) {
182 already_conn($conn, $call, DXM::msg($lang, "illcall", $call));
186 # set up the basic channel info
187 # is there one already connected to me - locally?
188 my $user = DXUser::get_current($call);
189 my $dxchan = DXChannel::get($call);
191 if ($user && $user->is_node) {
192 already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
196 my $ip = $conn->peerhost || 'unknown';
197 $dxchan->send_now('D', DXM::msg($lang, 'conbump', $call, $ip));
198 LogDbg('DXCommand', "$call bumped off by $ip, disconnected");
201 already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
206 # (fairly) politely disconnect people that are connected to too many other places at once
207 my $r = Route::get($call);
208 if ($conn->{sort} && $conn->{sort} =~ /^I/ && $r && $user) {
210 my $m = $r->isa('Route::Node') ? $maxconnect_node : $maxconnect_user;
211 my $c = $user->maxconnect;
213 $v = defined $c ? $c : $m;
214 if ($v && @n >= $v) {
215 my $nodes = join ',', @n;
216 LogDbg('DXCommand', "$call has too many connections ($v) at $nodes - disconnected");
217 already_conn($conn, $call, DXM::msg($lang, 'contomany', $call, $v, $nodes));
223 my $basecall = $call;
224 $basecall =~ s/-\d+$//;
225 my $baseuser = DXUser::get_current($basecall);
226 my $lock = $user->lockout if $user;
227 if ($baseuser && $baseuser->lockout || $lock) {
228 if (!$user || !defined $lock || $lock) {
229 my $host = $conn->peerhost || "unknown";
230 LogDbg('DXCommand', "$call on $host is locked out, disconnected");
237 $user->{lang} = $main::lang if !$user->{lang}; # to autoupdate old systems
239 $user = DXUser->new($call);
243 if ($user->is_node) {
244 $dxchan = DXProt->new($call, $conn, $user);
245 } elsif ($user->is_user) {
246 $dxchan = DXCommandmode->new($call, $conn, $user);
247 # } elsif ($user->is_bbs) { # there is no support so
248 # $dxchan = BBS->new($call, $conn, $user); # don't allow it!!!
250 die "Invalid sort of user on $call = $sort";
253 # check that the conn has a callsign
254 $conn->conns($call) if $conn->isa('IntMsg');
257 $conn->set_error(sub {my $err = shift; LogDbg('DXCommand', "Comms error '$err' received for call $dxchan->{call}"); $dxchan->disconnect(1);});
258 $conn->set_on_eof(sub {$dxchan->disconnect});
259 $conn->set_rproc(sub {my ($conn,$msg) = @_; $dxchan->rec($msg);});
266 return \&new_channel;
271 # cease running this program, close down all the connections nicely
276 cluck("ceasing") if $ceasing;
278 return if $ceasing++;
281 $SIG{'TERM'} = 'IGNORE';
282 $SIG{'INT'} = 'IGNORE';
287 if (defined &Local::finish) {
289 Local::finish(); # end local processing
291 dbg("Local::finish error $@") if $@;
299 # disconnect UDP customers
302 # end everything else
306 # close all databases
309 # close all listeners
310 foreach my $l (@listeners) {
314 LogDbg('cluster', "DXSpider V$version, build $build (git: $gitversion) ended");
315 dbg("bye bye everyone - bye bye");
319 $dbh->finish if $dbh;
324 # the reaper of children
328 while (($cpid = waitpid(-1, WNOHANG)) > 0) {
329 dbg("cpid: $cpid") if isdbg('reap');
330 # Msg->pid_gone($cpid);
331 $zombies-- if $zombies > 0;
333 dbg("cpid: $cpid") if isdbg('reap');
336 # this is where the input queue is dealt with and things are dispatched off to other parts of
341 my $t = $systime - $starttime;
342 my $days = int $t / 86400;
344 my $hours = int $t / 3600;
346 my $mins = int $t / 60;
347 return sprintf "%d %02d:%02d", $days, $hours, $mins;
352 AGWMsg::init(\&new_channel);
359 #############################################################
361 # The start of the main line of code
363 #############################################################
365 $starttime = $systime = time;
366 $systime_days = int ($systime / 86400);
367 $systime_daystart = $systime_days * 86400;
368 $lang = 'en' unless $lang;
370 unless ($DB::VERSION) {
371 $SIG{INT} = $SIG{TERM} = \&cease;
374 # open the debug file, set various FHs to be unbuffered
375 dbginit($broadcast_debug ? \&DXCommandmode::broadcast_debug : undef);
379 STDOUT->autoflush(1);
382 # try to load the database
383 if (DXSql::init($dsn)) {
384 $dbh = DXSql->new($dsn);
385 $dbh = $dbh->connect($dsn, $dbuser, $dbpass) if $dbh;
388 # try to load Encode and Git
391 my $w = $SIG{__DIE__};
392 $SIG{__DIE__} = 'IGNORE';
393 eval { require Encode; };
398 eval { require Git; };
402 # determine the real version number
403 my $repo = Git->repository(Directory => "$root/.git");
405 my $desc = $repo->command_oneline(['describe', '--long'], STDERR => 0);
407 my ($v, $s, $b, $g) = $desc =~ /^([\d.]+)(?:\.(\d+))?-(\d+)-g([0-9a-f]+)/;
410 $gitversion = "$g\[r]";
417 # try to load XML::Simple
421 my ($year) = (gmtime)[5];
423 LogDbg('cluster', "DXSpider V$version, build $build (git: $gitversion) started");
424 dbg("Copyright (c) 1998-$year Dirk Koopman G1TLH");
427 dbg("loading prefixes ...");
429 my $r = Prefix::init();
433 dbg("loading band data ...");
436 # initialise User file system
437 dbg("loading user file system ...");
440 # look for the sysop and the alias user and complain if they aren't there
442 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;
443 my $ref = DXUser::get($mycall);
444 die "$mycall missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
445 my $oldsort = $ref->sort;
446 if ($oldsort ne 'S') {
448 dbg "Resetting node type from $oldsort -> DXSpider ('S')";
450 $ref = DXUser::get($myalias);
451 die "$myalias missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
452 $oldsort = $ref->sort;
453 if ($oldsort ne 'U') {
455 dbg "Resetting sysop user type from $oldsort -> User ('U')";
459 # start listening for incoming messages/connects
460 dbg("starting listeners ...");
461 my $conn = IntMsg->new_server($clusteraddr, $clusterport, \&login);
462 $conn->conns("Server $clusteraddr/$clusterport using IntMsg");
463 push @listeners, $conn;
464 dbg("Internal port: $clusteraddr $clusterport using IntMsg");
465 foreach my $l (@main::listen) {
467 my $pkg = $l->[2] || 'ExtMsg';
468 my $login = $l->[3] || 'login';
470 $conn = $pkg->new_server($l->[0], $l->[1], \&{"${pkg}::${login}"});
471 $conn->conns("Server $l->[0]/$l->[1] using ${pkg}::${login}");
472 push @listeners, $conn;
473 dbg("External Port: $l->[0] $l->[1] using ${pkg}::${login}");
476 dbg("AGW Listener") if $AGWMsg::enable;
479 dbg("BPQ Listener") if $BPQMsg::enable;
480 BPQMsg::init(\&new_channel);
482 dbg("UDP Listener") if $UDPMsg::enable;
483 UDPMsg::init(\&new_channel);
486 dbg("load badwords: " . (BadWords::load or "Ok"));
489 unless ($DB::VERSION) {
490 $SIG{INT} = $SIG{TERM} = sub { $ending = 10; };
494 $SIG{HUP} = 'IGNORE';
495 $SIG{CHLD} = sub { $zombies++ };
497 $SIG{PIPE} = sub { dbg("Broken PIPE signal received"); };
498 $SIG{IO} = sub { dbg("SIGIO received"); };
499 $SIG{WINCH} = $SIG{STOP} = $SIG{CONT} = 'IGNORE';
500 $SIG{KILL} = 'DEFAULT'; # as if it matters....
502 # catch the rest with a hopeful message
505 # dbg("Catching SIG $_") if isdbg('chan');
506 $SIG{$_} = sub { my $sig = shift; DXDebug::confess("Caught signal $sig"); };
512 dbg("Starting Dupe system");
515 # read in system messages
516 dbg("Read in Messages");
519 # read in command aliases
520 dbg("Read in Aliases");
523 # initialise the Geomagnetic data engine
529 # initial the Spot stuff
530 dbg("Starting DX Spot system");
533 # initialise the protocol engine
534 dbg("Start Protocol Engines ...");
537 # put in a DXCluster node for us here so we can add users and take them away
538 $routeroot = Route::Node->new($mycall, $version*100+5300, Route::here($main::me->here)|Route::conf($main::me->conf));
539 $routeroot->do_pc9x(1);
540 $routeroot->via_pc92(1);
542 # make sure that there is a routing OUTPUT node default file
543 #unless (Filter::read_in('route', 'node_default', 0)) {
544 # my $dxcc = $main::me->dxcc;
545 # $Route::filterdef->cmd($main::me, 'route', 'accept', "node_default call $mycall" );
548 # read in any existing message headers and clean out old crap
549 dbg("reading existing message headers ...");
553 # read in any cron jobs
554 dbg("reading cron jobs ...");
557 # read in database desriptors
558 dbg("reading database descriptors ...");
561 # starting local stuff
562 dbg("doing local initialisation ...");
564 if (defined &Local::init) {
568 dbg("Local::init error $@") if $@;
572 # this, such as it is, is the main loop!
573 dbg("orft we jolly well go ...");
574 my $script = new Script "startup";
575 $script->run($main::me) if $script;
577 #open(DB::OUT, "|tee /tmp/aa");
580 our $io_disconnected;
586 if (defined &Local::process) {
588 Local::process(); # do any localised processing
590 dbg("Local::process error $@") if $@;
596 dbg("DXSpider Ending $ending");
598 unless ($io_disconnected++) {
601 foreach $dxchan (DXChannel::get_all_users) {
606 foreach $dxchan (DXChannel::get_all_nodes) {
607 next if $dxchan == $main::me;
608 $dxchan->disconnect(2);
610 $main::me->disconnect;
613 Mojo::IOLoop->stop if --$ending <= 0;
623 my $days = int ($systime / 86400);
624 if ($systime_days != $days) {
625 $systime_days = $days;
626 $systime_daystart = $days * 86400;
628 IsoTime::update($systime);
629 DXCron::process(); # do cron jobs
630 DXCommandmode::process(); # process ongoing command mode stuff
632 DXProt::process(); # process ongoing ak1a pcxx stuff
633 DXConnect::process();
638 DXCron::process(); # do cron jobs
639 IsoTime::update($systime);
640 DXProt::process(); # process ongoing ak1a pcxx stuff
641 DXConnect::process();
677 my $main_loop = Mojo::IOLoop->recurring($idle_interval => \&idle_loop);
678 my $log_flush_loop = Mojo::IOLoop->recurring($log_flush_interval => \&DXLog::flushall);
679 my $cpusecs_loop = Mojo::IOLoop->recurring(5 => sub {my @t = times; $clssecs = $t[0]+$t[1]; $cldsecs = $t[2]+$t[3]});
680 my $persec = Mojo::IOLoop->recurring(1 => \&per_sec);
681 my $per10sec = Mojo::IOLoop->recurring(10 => \&per_10_sec);
682 my $permin = Mojo::IOLoop->recurring(60 => \&per_minute);
683 my $per10min = Mojo::IOLoop->recurring(600 => \&per_10_minute);
684 my $perhour = Mojo::IOLoop->recurring(3600 => \&per_hour);
685 my $perday = Mojo::IOLoop->recurring(86400 => \&per_day);