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);
20 # make sure that modules are searched in the order local then perl
24 # take into account any local::lib that might be present
28 import local::lib unless ($@);
30 # root of directory tree for this system
32 $root = $ENV{'DXSPIDER_ROOT'} if $ENV{'DXSPIDER_ROOT'};
34 unshift @INC, "$root/perl"; # this IS the right way round!
35 unshift @INC, "$root/local";
37 # do some validation of the input
38 die "The directory $root doesn't exist, please RTFM" unless -d $root;
39 die "$root/local doesn't exist, please RTFM" unless -d "$root/local";
40 die "$root/local/DXVars.pm doesn't exist, please RTFM" unless -e "$root/local/DXVars.pm";
42 # create some directories
43 mkdir "$root/local_cmd", 02774 unless -d "$root/local_cmd";
45 # locally stored data lives here
46 my $local_data = "$root/local_data";
47 mkdir $local_data, 02774 unless -d $local_data;
49 # try to create and lock a lockfile (this isn't atomic but
51 $lockfn = "$root/local_data/cluster.lck"; # lock file name
53 open(CLLOCK, "$lockfn") or die "Can't open Lockfile ($lockfn) $!";
58 warn "Lockfile ($lockfn) and process $pid exist, another cluster running?\n";
65 open(CLLOCK, ">$lockfn") or die "Can't open Lockfile ($lockfn) $!";
69 $is_win = ($^O =~ /^MS/ || $^O =~ /^OS-2/) ? 1 : 0; # is it Windows?
137 use POSIX ":sys_wait_h";
143 use vars qw(@inqueue $starttime $lockfn @outstanding_connects
144 $zombies @listeners $lang $myalias @debug $userfn $clusteraddr
145 $clusterport $mycall $decease $routeroot $me $reqreg $bumpexisting
146 $allowdxby $dbh $dsn $dbuser $dbpass $do_xml $systime_days $systime_daystart
147 $can_encode $maxconnect_user $maxconnect_node $idle_interval $log_flush_interval
151 @inqueue = (); # the main input queue, an array of hashes
152 $systime = 0; # the time now (in seconds)
153 $starttime = 0; # the starting time of the cluster
154 @outstanding_connects = (); # list of outstanding connects
155 @listeners = (); # list of listeners
156 $reqreg = 0; # 1 = registration required, 2 = deregister people
157 $bumpexisting = 1; # 1 = allow new connection to disconnect old, 0 - don't allow it
158 $allowdxby = 0; # 1 = allow "dx by <othercall>", 0 - don't allow it
159 $maxconnect_user = 3; # the maximum no of concurrent connections a user can have at a time
160 $maxconnect_node = 0; # Ditto but for nodes. In either case if a new incoming connection
161 # takes the no of references in the routing table above these numbers
162 # then the connection is refused. This only affects INCOMING connections.
163 $idle_interval = 0.500; # the wait between invocations of the main idle loop processing.
164 $log_flush_interval = 2; # interval to wait between log flushes
166 our $ending; # signal that we are ending;
167 our $broadcast_debug; # allow broadcasting of debug info down "enhanced" user connections
168 our $clssecs; # the amount of cpu time the DXSpider process have consumed
169 our $cldsecs; # the amount of cpu time any child processes have consumed
172 # send a message to call on conn and disconnect
175 my ($conn, $call, $mess) = @_;
177 $conn->disable_read(1);
178 dbg("-> D $call $mess\n") if isdbg('chan');
179 $conn->send_now("D$call|$mess");
184 # handle incoming messages
187 my ($conn, $msg) = @_;
188 my ($sort, $call, $line) = DXChannel::decode_input(0, $msg);
189 return unless defined $sort;
191 unless (is_callsign($call)) {
192 already_conn($conn, $call, DXM::msg($lang, "illcall", $call));
196 # set up the basic channel info
197 # is there one already connected to me - locally?
198 my $user = DXUser::get_current($call);
199 my $dxchan = DXChannel::get($call);
201 if ($user && $user->is_node) {
202 already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
206 my $ip = $conn->peerhost || 'unknown';
207 $dxchan->send_now('D', DXM::msg($lang, 'conbump', $call, $ip));
208 LogDbg('DXCommand', "$call bumped off by $ip, disconnected");
211 already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
216 # (fairly) politely disconnect people that are connected to too many other places at once
217 my $r = Route::get($call);
218 if ($conn->{sort} && $conn->{sort} =~ /^I/ && $r && $user) {
220 my $m = $r->isa('Route::Node') ? $maxconnect_node : $maxconnect_user;
221 my $c = $user->maxconnect;
223 $v = defined $c ? $c : $m;
224 if ($v && @n >= $v) {
225 my $nodes = join ',', @n;
226 LogDbg('DXCommand', "$call has too many connections ($v) at $nodes - disconnected");
227 already_conn($conn, $call, DXM::msg($lang, 'contomany', $call, $v, $nodes));
233 my $basecall = $call;
234 $basecall =~ s/-\d+$//;
235 my $baseuser = DXUser::get_current($basecall);
236 my $lock = $user->lockout if $user;
237 if ($baseuser && $baseuser->lockout || $lock) {
238 if (!$user || !defined $lock || $lock) {
239 my $host = $conn->peerhost || "unknown";
240 LogDbg('DXCommand', "$call on $host is locked out, disconnected");
247 $user->{lang} = $main::lang if !$user->{lang}; # to autoupdate old systems
249 $user = DXUser->new($call);
253 if ($user->is_node) {
254 $dxchan = DXProt->new($call, $conn, $user);
255 } elsif ($user->is_user) {
256 $dxchan = DXCommandmode->new($call, $conn, $user);
257 # } elsif ($user->is_bbs) { # there is no support so
258 # $dxchan = BBS->new($call, $conn, $user); # don't allow it!!!
260 die "Invalid sort of user on $call = $sort";
263 # check that the conn has a callsign
264 $conn->conns($call) if $conn->isa('IntMsg');
267 $conn->set_error(sub {my $err = shift; LogDbg('DXCommand', "Comms error '$err' received for call $dxchan->{call}"); $dxchan->disconnect(1);});
268 $conn->set_on_eof(sub {$dxchan->disconnect});
269 $conn->set_rproc(sub {my ($conn,$msg) = @_; $dxchan->rec($msg);});
276 return \&new_channel;
281 # cease running this program, close down all the connections nicely
286 cluck("ceasing") if $ceasing;
288 return if $ceasing++;
291 $SIG{'TERM'} = 'IGNORE';
292 $SIG{'INT'} = 'IGNORE';
297 if (defined &Local::finish) {
299 Local::finish(); # end local processing
301 dbg("Local::finish error $@") if $@;
309 # disconnect UDP customers
312 # end everything else
316 # close all databases
319 # close all listeners
320 foreach my $l (@listeners) {
324 LogDbg('cluster', "DXSpider V$version, build $build (git: $gitversion) ended");
325 dbg("bye bye everyone - bye bye");
329 $dbh->finish if $dbh;
334 # the reaper of children
338 while (($cpid = waitpid(-1, WNOHANG)) > 0) {
339 dbg("cpid: $cpid") if isdbg('reap');
340 # Msg->pid_gone($cpid);
341 $zombies-- if $zombies > 0;
343 dbg("cpid: $cpid") if isdbg('reap');
346 # this is where the input queue is dealt with and things are dispatched off to other parts of
351 my $t = $systime - $starttime;
352 my $days = int $t / 86400;
354 my $hours = int $t / 3600;
356 my $mins = int $t / 60;
357 return sprintf "%d %02d:%02d", $days, $hours, $mins;
362 AGWMsg::init(\&new_channel);
369 #############################################################
371 # The start of the main line of code
373 #############################################################
375 $starttime = $systime = time;
376 $systime_days = int ($systime / 86400);
377 $systime_daystart = $systime_days * 86400;
378 $lang = 'en' unless $lang;
380 unless ($DB::VERSION) {
381 $SIG{INT} = $SIG{TERM} = \&cease;
384 # open the debug file, set various FHs to be unbuffered
385 dbginit($broadcast_debug ? \&DXCommandmode::broadcast_debug : undef);
389 STDOUT->autoflush(1);
392 # try to load the database
393 if (DXSql::init($dsn)) {
394 $dbh = DXSql->new($dsn);
395 $dbh = $dbh->connect($dsn, $dbuser, $dbpass) if $dbh;
398 # try to load Encode and Git
401 my $w = $SIG{__DIE__};
402 $SIG{__DIE__} = 'IGNORE';
403 eval { require Encode; };
408 eval { require Git; };
412 # determine the real version number
413 my $repo = Git->repository(Directory => "$root/.git");
415 my $desc = $repo->command_oneline(['describe', '--long'], STDERR => 0);
417 my ($v, $s, $b, $g) = $desc =~ /^([\d.]+)(?:\.(\d+))?-(\d+)-g([0-9a-f]+)/;
420 $gitversion = "$g\[r]";
427 # try to load XML::Simple
431 my ($year) = (gmtime)[5];
433 LogDbg('cluster', "DXSpider V$version, build $build (git: $gitversion) started");
434 dbg("Copyright (c) 1998-$year Dirk Koopman G1TLH");
437 dbg("loading prefixes ...");
439 my $r = Prefix::init();
443 dbg("loading band data ...");
446 # initialise User file system
447 dbg("loading user file system ...");
450 # look for the sysop and the alias user and complain if they aren't there
452 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;
453 my $ref = DXUser::get($mycall);
454 die "$mycall missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
455 my $oldsort = $ref->sort;
456 if ($oldsort ne 'S') {
458 dbg "Resetting node type from $oldsort -> DXSpider ('S')";
460 $ref = DXUser::get($myalias);
461 die "$myalias missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
462 $oldsort = $ref->sort;
463 if ($oldsort ne 'U') {
465 dbg "Resetting sysop user type from $oldsort -> User ('U')";
469 # start listening for incoming messages/connects
470 dbg("starting listeners ...");
471 my $conn = IntMsg->new_server($clusteraddr, $clusterport, \&login);
472 $conn->conns("Server $clusteraddr/$clusterport using IntMsg");
473 push @listeners, $conn;
474 dbg("Internal port: $clusteraddr $clusterport using IntMsg");
475 foreach my $l (@main::listen) {
477 my $pkg = $l->[2] || 'ExtMsg';
478 my $login = $l->[3] || 'login';
480 $conn = $pkg->new_server($l->[0], $l->[1], \&{"${pkg}::${login}"});
481 $conn->conns("Server $l->[0]/$l->[1] using ${pkg}::${login}");
482 push @listeners, $conn;
483 dbg("External Port: $l->[0] $l->[1] using ${pkg}::${login}");
486 dbg("AGW Listener") if $AGWMsg::enable;
489 dbg("BPQ Listener") if $BPQMsg::enable;
490 BPQMsg::init(\&new_channel);
492 dbg("UDP Listener") if $UDPMsg::enable;
493 UDPMsg::init(\&new_channel);
496 dbg("load badwords: " . (BadWords::load or "Ok"));
499 unless ($DB::VERSION) {
500 $SIG{INT} = $SIG{TERM} = sub { $ending = 10; };
504 $SIG{HUP} = 'IGNORE';
505 $SIG{CHLD} = sub { $zombies++ };
507 $SIG{PIPE} = sub { dbg("Broken PIPE signal received"); };
508 $SIG{IO} = sub { dbg("SIGIO received"); };
509 $SIG{WINCH} = $SIG{STOP} = $SIG{CONT} = 'IGNORE';
510 $SIG{KILL} = 'DEFAULT'; # as if it matters....
512 # catch the rest with a hopeful message
515 # dbg("Catching SIG $_") if isdbg('chan');
516 $SIG{$_} = sub { my $sig = shift; DXDebug::confess("Caught signal $sig"); };
522 dbg("Starting Dupe system");
525 # read in system messages
526 dbg("Read in Messages");
529 # read in command aliases
530 dbg("Read in Aliases");
533 # initialise the Geomagnetic data engine
539 # initial the Spot stuff
540 dbg("Starting DX Spot system");
543 # initialise the protocol engine
544 dbg("Start Protocol Engines ...");
547 # put in a DXCluster node for us here so we can add users and take them away
548 $routeroot = Route::Node->new($mycall, $version*100+5300, Route::here($main::me->here)|Route::conf($main::me->conf));
549 $routeroot->do_pc9x(1);
550 $routeroot->via_pc92(1);
552 # make sure that there is a routing OUTPUT node default file
553 #unless (Filter::read_in('route', 'node_default', 0)) {
554 # my $dxcc = $main::me->dxcc;
555 # $Route::filterdef->cmd($main::me, 'route', 'accept', "node_default call $mycall" );
558 # read in any existing message headers and clean out old crap
559 dbg("reading existing message headers ...");
563 # read in any cron jobs
564 dbg("reading cron jobs ...");
567 # read in database desriptors
568 dbg("reading database descriptors ...");
571 # starting local stuff
572 dbg("doing local initialisation ...");
574 if (defined &Local::init) {
578 dbg("Local::init error $@") if $@;
582 # this, such as it is, is the main loop!
583 dbg("orft we jolly well go ...");
584 my $script = new Script "startup";
585 $script->run($main::me) if $script;
587 #open(DB::OUT, "|tee /tmp/aa");
590 our $io_disconnected;
596 if (defined &Local::process) {
598 Local::process(); # do any localised processing
600 dbg("Local::process error $@") if $@;
606 dbg("DXSpider Ending $ending");
608 unless ($io_disconnected++) {
611 foreach $dxchan (DXChannel::get_all_users) {
616 foreach $dxchan (DXChannel::get_all_nodes) {
617 next if $dxchan == $main::me;
618 $dxchan->disconnect(2);
620 $main::me->disconnect;
623 Mojo::IOLoop->stop if --$ending <= 0;
633 my $days = int ($systime / 86400);
634 if ($systime_days != $days) {
635 $systime_days = $days;
636 $systime_daystart = $days * 86400;
638 IsoTime::update($systime);
639 DXCron::process(); # do cron jobs
640 DXCommandmode::process(); # process ongoing command mode stuff
642 DXProt::process(); # process ongoing ak1a pcxx stuff
643 DXConnect::process();
648 DXCron::process(); # do cron jobs
649 IsoTime::update($systime);
650 DXProt::process(); # process ongoing ak1a pcxx stuff
651 DXConnect::process();
687 my $main_loop = Mojo::IOLoop->recurring($idle_interval => \&idle_loop);
688 my $log_flush_loop = Mojo::IOLoop->recurring($log_flush_interval => \&DXLog::flushall);
689 my $cpusecs_loop = Mojo::IOLoop->recurring(5 => sub {my @t = times; $clssecs = $t[0]+$t[1]; $cldsecs = $t[2]+$t[3]});
690 my $persec = Mojo::IOLoop->recurring(1 => \&per_sec);
691 my $per10sec = Mojo::IOLoop->recurring(10 => \&per_10_sec);
692 my $permin = Mojo::IOLoop->recurring(60 => \&per_minute);
693 my $per10min = Mojo::IOLoop->recurring(600 => \&per_10_minute);
694 my $perhour = Mojo::IOLoop->recurring(3600 => \&per_hour);
695 my $perday = Mojo::IOLoop->recurring(86400 => \&per_day);