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);
20 # make sure that modules are searched in the order local then perl
24 # root of directory tree for this system
26 $root = $ENV{'DXSPIDER_ROOT'} if $ENV{'DXSPIDER_ROOT'};
28 unshift @INC, "$root/perl"; # this IS the right way round!
29 unshift @INC, "$root/local";
31 # do some validation of the input
32 die "The directory $root doesn't exist, please RTFM" unless -d $root;
33 die "$root/local doesn't exist, please RTFM" unless -d "$root/local";
34 die "$root/local/DXVars.pm doesn't exist, please RTFM" unless -e "$root/local/DXVars.pm";
36 # create some directories
37 mkdir "$root/local_cmd", 02774 unless -d "$root/local_cmd";
39 # locally stored data lives here
40 my $local_data = "$root/local_data";
41 mkdir $local_data, 02774 unless -d $local_data;
43 # try to create and lock a lockfile (this isn't atomic but
45 my $lockfn = "$root/local_data/cluster.lck"; # lock file name
47 open(CLLOCK, "$lockfn") or die "Can't open Lockfile ($lockfn) $!";
52 warn "Lockfile ($lockfn) and process $pid exist, another cluster running?\n";
59 open(CLLOCK, ">$lockfn") or die "Can't open Lockfile ($lockfn) $!";
63 $is_win = ($^O =~ /^MS/ || $^O =~ /^OS-2/) ? 1 : 0; # is it Windows?
131 use POSIX ":sys_wait_h";
137 use vars qw(@inqueue $starttime $lockfn @outstanding_connects
138 $zombies @listeners $lang $myalias @debug $userfn $clusteraddr
139 $clusterport $mycall $decease $routeroot $me $reqreg $bumpexisting
140 $allowdxby $dbh $dsn $dbuser $dbpass $do_xml $systime_days $systime_daystart
141 $can_encode $maxconnect_user $maxconnect_node $idle_interval $log_flush_interval
145 @inqueue = (); # the main input queue, an array of hashes
146 $systime = 0; # the time now (in seconds)
147 $starttime = 0; # the starting time of the cluster
148 @outstanding_connects = (); # list of outstanding connects
149 @listeners = (); # list of listeners
150 $reqreg = 0; # 1 = registration required, 2 = deregister people
151 $bumpexisting = 1; # 1 = allow new connection to disconnect old, 0 - don't allow it
152 $allowdxby = 0; # 1 = allow "dx by <othercall>", 0 - don't allow it
153 $maxconnect_user = 3; # the maximum no of concurrent connections a user can have at a time
154 $maxconnect_node = 0; # Ditto but for nodes. In either case if a new incoming connection
155 # takes the no of references in the routing table above these numbers
156 # then the connection is refused. This only affects INCOMING connections.
157 $idle_interval = 0.500; # the wait between invocations of the main idle loop processing.
158 $log_flush_interval = 2; # interval to wait between log flushes
160 our $ending; # signal that we are ending;
161 our $broadcast_debug; # allow broadcasting of debug info down "enhanced" user connections
162 our $clssecs; # the amount of cpu time the DXSpider process have consumed
163 our $cldsecs; # the amount of cpu time any child processes have consumed
166 # send a message to call on conn and disconnect
169 my ($conn, $call, $mess) = @_;
171 $conn->disable_read(1);
172 dbg("-> D $call $mess\n") if isdbg('chan');
173 $conn->send_now("D$call|$mess");
178 # handle incoming messages
181 my ($conn, $msg) = @_;
182 my ($sort, $call, $line) = DXChannel::decode_input(0, $msg);
183 return unless defined $sort;
185 unless (is_callsign($call)) {
186 already_conn($conn, $call, DXM::msg($lang, "illcall", $call));
190 # set up the basic channel info
191 # is there one already connected to me - locally?
192 my $user = DXUser::get_current($call);
193 my $dxchan = DXChannel::get($call);
195 if ($user && $user->is_node) {
196 already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
200 my $ip = $conn->peerhost || 'unknown';
201 $dxchan->send_now('D', DXM::msg($lang, 'conbump', $call, $ip));
202 LogDbg('DXCommand', "$call bumped off by $ip, disconnected");
205 already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
210 # (fairly) politely disconnect people that are connected to too many other places at once
211 my $r = Route::get($call);
212 if ($conn->{sort} && $conn->{sort} =~ /^I/ && $r && $user) {
214 my $m = $r->isa('Route::Node') ? $maxconnect_node : $maxconnect_user;
215 my $c = $user->maxconnect;
217 $v = defined $c ? $c : $m;
218 if ($v && @n >= $v) {
219 my $nodes = join ',', @n;
220 LogDbg('DXCommand', "$call has too many connections ($v) at $nodes - disconnected");
221 already_conn($conn, $call, DXM::msg($lang, 'contomany', $call, $v, $nodes));
227 my $basecall = $call;
228 $basecall =~ s/-\d+$//;
229 my $baseuser = DXUser::get_current($basecall);
230 my $lock = $user->lockout if $user;
231 if ($baseuser && $baseuser->lockout || $lock) {
232 if (!$user || !defined $lock || $lock) {
233 my $host = $conn->peerhost || "unknown";
234 LogDbg('DXCommand', "$call on $host is locked out, disconnected");
241 $user->{lang} = $main::lang if !$user->{lang}; # to autoupdate old systems
243 $user = DXUser->new($call);
247 if ($user->is_node) {
248 $dxchan = DXProt->new($call, $conn, $user);
249 } elsif ($user->is_user) {
250 $dxchan = DXCommandmode->new($call, $conn, $user);
251 # } elsif ($user->is_bbs) { # there is no support so
252 # $dxchan = BBS->new($call, $conn, $user); # don't allow it!!!
254 die "Invalid sort of user on $call = $sort";
257 # check that the conn has a callsign
258 $conn->conns($call) if $conn->isa('IntMsg');
261 $conn->set_error(sub {my $err = shift; LogDbg('DXCommand', "Comms error '$err' received for call $dxchan->{call}"); $dxchan->disconnect(1);});
262 $conn->set_on_eof(sub {$dxchan->disconnect});
263 $conn->set_rproc(sub {my ($conn,$msg) = @_; $dxchan->rec($msg);});
270 return \&new_channel;
275 # cease running this program, close down all the connections nicely
280 cluck("ceasing") if $ceasing;
282 return if $ceasing++;
285 $SIG{'TERM'} = 'IGNORE';
286 $SIG{'INT'} = 'IGNORE';
291 if (defined &Local::finish) {
293 Local::finish(); # end local processing
295 dbg("Local::finish error $@") if $@;
303 # disconnect UDP customers
306 # end everything else
310 # close all databases
313 # close all listeners
314 foreach my $l (@listeners) {
318 LogDbg('cluster', "DXSpider V$version, build $build (git: $gitversion) ended");
319 dbg("bye bye everyone - bye bye");
323 $dbh->finish if $dbh;
328 # the reaper of children
332 while (($cpid = waitpid(-1, WNOHANG)) > 0) {
333 dbg("cpid: $cpid") if isdbg('reap');
334 # Msg->pid_gone($cpid);
335 $zombies-- if $zombies > 0;
337 dbg("cpid: $cpid") if isdbg('reap');
340 # this is where the input queue is dealt with and things are dispatched off to other parts of
345 my $t = $systime - $starttime;
346 my $days = int $t / 86400;
348 my $hours = int $t / 3600;
350 my $mins = int $t / 60;
351 return sprintf "%d %02d:%02d", $days, $hours, $mins;
356 AGWMsg::init(\&new_channel);
363 #############################################################
365 # The start of the main line of code
367 #############################################################
369 $starttime = $systime = time;
370 $systime_days = int ($systime / 86400);
371 $systime_daystart = $systime_days * 86400;
372 $lang = 'en' unless $lang;
374 unless ($DB::VERSION) {
375 $SIG{INT} = $SIG{TERM} = \&cease;
378 # open the debug file, set various FHs to be unbuffered
379 dbginit($broadcast_debug ? \&DXCommandmode::broadcast_debug : undef);
383 STDOUT->autoflush(1);
386 # try to load the database
387 if (DXSql::init($dsn)) {
388 $dbh = DXSql->new($dsn);
389 $dbh = $dbh->connect($dsn, $dbuser, $dbpass) if $dbh;
392 # try to load Encode and Git
395 my $w = $SIG{__DIE__};
396 $SIG{__DIE__} = 'IGNORE';
397 eval { require Encode; };
402 eval { require Git; };
406 # determine the real version number
407 my $repo = Git->repository(Directory => "$root/.git");
409 my $desc = $repo->command_oneline(['describe', '--long'], STDERR => 0);
411 my ($v, $s, $b, $g) = $desc =~ /^([\d.]+)(?:\.(\d+))?-(\d+)-g([0-9a-f]+)/;
414 $gitversion = "$g\[r]";
421 # try to load XML::Simple
425 my ($year) = (gmtime)[5];
427 LogDbg('cluster', "DXSpider V$version, build $build (git: $gitversion) started");
428 dbg("Copyright (c) 1998-$year Dirk Koopman G1TLH");
431 dbg("loading prefixes ...");
433 my $r = Prefix::init();
437 dbg("loading band data ...");
440 # initialise User file system
441 dbg("loading user file system ...");
444 # look for the sysop and the alias user and complain if they aren't there
446 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;
447 my $ref = DXUser::get($mycall);
448 die "$mycall missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
449 my $oldsort = $ref->sort;
450 if ($oldsort ne 'S') {
452 dbg "Resetting node type from $oldsort -> DXSpider ('S')";
454 $ref = DXUser::get($myalias);
455 die "$myalias missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
456 $oldsort = $ref->sort;
457 if ($oldsort ne 'U') {
459 dbg "Resetting sysop user type from $oldsort -> User ('U')";
463 # start listening for incoming messages/connects
464 dbg("starting listeners ...");
465 my $conn = IntMsg->new_server($clusteraddr, $clusterport, \&login);
466 $conn->conns("Server $clusteraddr/$clusterport using IntMsg");
467 push @listeners, $conn;
468 dbg("Internal port: $clusteraddr $clusterport using IntMsg");
469 foreach my $l (@main::listen) {
471 my $pkg = $l->[2] || 'ExtMsg';
472 my $login = $l->[3] || 'login';
474 $conn = $pkg->new_server($l->[0], $l->[1], \&{"${pkg}::${login}"});
475 $conn->conns("Server $l->[0]/$l->[1] using ${pkg}::${login}");
476 push @listeners, $conn;
477 dbg("External Port: $l->[0] $l->[1] using ${pkg}::${login}");
480 dbg("AGW Listener") if $AGWMsg::enable;
483 dbg("BPQ Listener") if $BPQMsg::enable;
484 BPQMsg::init(\&new_channel);
486 dbg("UDP Listener") if $UDPMsg::enable;
487 UDPMsg::init(\&new_channel);
490 dbg("load badwords: " . (BadWords::load or "Ok"));
493 unless ($DB::VERSION) {
494 $SIG{INT} = $SIG{TERM} = sub { $ending = 10; };
498 $SIG{HUP} = 'IGNORE';
499 $SIG{CHLD} = sub { $zombies++ };
501 $SIG{PIPE} = sub { dbg("Broken PIPE signal received"); };
502 $SIG{IO} = sub { dbg("SIGIO received"); };
503 $SIG{WINCH} = $SIG{STOP} = $SIG{CONT} = 'IGNORE';
504 $SIG{KILL} = 'DEFAULT'; # as if it matters....
506 # catch the rest with a hopeful message
509 # dbg("Catching SIG $_") if isdbg('chan');
510 $SIG{$_} = sub { my $sig = shift; DXDebug::confess("Caught signal $sig"); };
516 dbg("Starting Dupe system");
519 # read in system messages
520 dbg("Read in Messages");
523 # read in command aliases
524 dbg("Read in Aliases");
527 # initialise the Geomagnetic data engine
533 # initial the Spot stuff
534 dbg("Starting DX Spot system");
537 # initialise the protocol engine
538 dbg("Start Protocol Engines ...");
541 # put in a DXCluster node for us here so we can add users and take them away
542 $routeroot = Route::Node->new($mycall, $version*100+5300, Route::here($main::me->here)|Route::conf($main::me->conf));
543 $routeroot->do_pc9x(1);
544 $routeroot->via_pc92(1);
546 # make sure that there is a routing OUTPUT node default file
547 #unless (Filter::read_in('route', 'node_default', 0)) {
548 # my $dxcc = $main::me->dxcc;
549 # $Route::filterdef->cmd($main::me, 'route', 'accept', "node_default call $mycall" );
552 # read in any existing message headers and clean out old crap
553 dbg("reading existing message headers ...");
557 # read in any cron jobs
558 dbg("reading cron jobs ...");
561 # read in database desriptors
562 dbg("reading database descriptors ...");
565 # starting local stuff
566 dbg("doing local initialisation ...");
568 if (defined &Local::init) {
572 dbg("Local::init error $@") if $@;
576 # this, such as it is, is the main loop!
577 dbg("orft we jolly well go ...");
578 my $script = new Script "startup";
579 $script->run($main::me) if $script;
581 #open(DB::OUT, "|tee /tmp/aa");
584 our $io_disconnected;
590 if (defined &Local::process) {
592 Local::process(); # do any localised processing
594 dbg("Local::process error $@") if $@;
600 dbg("DXSpider Ending $ending");
602 unless ($io_disconnected++) {
605 foreach $dxchan (DXChannel::get_all_users) {
610 foreach $dxchan (DXChannel::get_all_nodes) {
611 next if $dxchan == $main::me;
612 $dxchan->disconnect(2);
614 $main::me->disconnect;
617 Mojo::IOLoop->stop if --$ending <= 0;
627 my $days = int ($systime / 86400);
628 if ($systime_days != $days) {
629 $systime_days = $days;
630 $systime_daystart = $days * 86400;
632 IsoTime::update($systime);
633 DXCron::process(); # do cron jobs
634 DXCommandmode::process(); # process ongoing command mode stuff
636 DXProt::process(); # process ongoing ak1a pcxx stuff
637 DXConnect::process();
642 DXCron::process(); # do cron jobs
643 IsoTime::update($systime);
644 DXProt::process(); # process ongoing ak1a pcxx stuff
645 DXConnect::process();
681 my $main_loop = Mojo::IOLoop->recurring($idle_interval => \&idle_loop);
682 my $log_flush_loop = Mojo::IOLoop->recurring($log_flush_interval => \&DXLog::flushall);
683 my $cpusecs_loop = Mojo::IOLoop->recurring(5 => sub {my @t = times; $clssecs = $t[0]+$t[1]; $cldsecs = $t[2]+$t[3]});
684 my $persec = Mojo::IOLoop->recurring(1 => \&per_sec);
685 my $per10sec = Mojo::IOLoop->recurring(10 => \&per_10_sec);
686 my $permin = Mojo::IOLoop->recurring(60 => \&per_minute);
687 my $per10min = Mojo::IOLoop->recurring(600 => \&per_10_minute);
688 my $perhour = Mojo::IOLoop->recurring(3600 => \&per_hour);
689 my $perday = Mojo::IOLoop->recurring(86400 => \&per_day);