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) $!";
46 die "Lockfile ($lockfn) and process $pid exist, another cluster running?" if kill 0, $pid;
51 open(CLLOCK, ">$lockfn") or die "Can't open Lockfile ($lockfn) $!";
55 $is_win = ($^O =~ /^MS/ || $^O =~ /^OS-2/) ? 1 : 0; # is it Windows?
120 use POSIX ":sys_wait_h";
129 use vars qw(@inqueue $systime $starttime $lockfn @outstanding_connects
130 $zombies $root @listeners $lang $myalias @debug $userfn $clusteraddr
131 $clusterport $mycall $decease $is_win $routeroot $me $reqreg $bumpexisting
132 $allowdxby $dbh $dsn $dbuser $dbpass $do_xml $systime_days $systime_daystart
133 $can_encode $maxconnect_user $maxconnect_node $idle_interval $log_flush_interval
137 @inqueue = (); # the main input queue, an array of hashes
138 $systime = 0; # the time now (in seconds)
139 $starttime = 0; # the starting time of the cluster
140 @outstanding_connects = (); # list of outstanding connects
141 @listeners = (); # list of listeners
142 $reqreg = 0; # 1 = registration required, 2 = deregister people
143 $bumpexisting = 1; # 1 = allow new connection to disconnect old, 0 - don't allow it
144 $allowdxby = 0; # 1 = allow "dx by <othercall>", 0 - don't allow it
145 $maxconnect_user = 3; # the maximum no of concurrent connections a user can have at a time
146 $maxconnect_node = 0; # Ditto but for nodes. In either case if a new incoming connection
147 # takes the no of references in the routing table above these numbers
148 # then the connection is refused. This only affects INCOMING connections.
149 $idle_interval = 0.500; # the wait between invocations of the main idle loop processing.
150 $log_flush_interval = 2; # interval to wait between log flushes
152 our $ending; # signal that we are ending;
153 our $broadcast_debug; # allow broadcasting of debug info down "enhanced" user connections
156 # send a message to call on conn and disconnect
159 my ($conn, $call, $mess) = @_;
161 $conn->disable_read(1);
162 dbg("-> D $call $mess\n") if isdbg('chan');
163 $conn->send_now("D$call|$mess");
168 # handle incoming messages
171 my ($conn, $msg) = @_;
172 my ($sort, $call, $line) = DXChannel::decode_input(0, $msg);
173 return unless defined $sort;
175 unless (is_callsign($call)) {
176 already_conn($conn, $call, DXM::msg($lang, "illcall", $call));
180 # set up the basic channel info
181 # is there one already connected to me - locally?
182 my $user = DXUser::get_current($call);
183 my $dxchan = DXChannel::get($call);
185 if ($user && $user->is_node) {
186 already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
190 my $ip = $conn->peerhost || 'unknown';
191 $dxchan->send_now('D', DXM::msg($lang, 'conbump', $call, $ip));
192 LogDbg('DXCommand', "$call bumped off by $ip, disconnected");
195 already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
200 # (fairly) politely disconnect people that are connected to too many other places at once
201 my $r = Route::get($call);
202 if ($conn->{sort} && $conn->{sort} =~ /^I/ && $r && $user) {
204 my $m = $r->isa('Route::Node') ? $maxconnect_node : $maxconnect_user;
205 my $c = $user->maxconnect;
207 $v = defined $c ? $c : $m;
208 if ($v && @n >= $v) {
209 my $nodes = join ',', @n;
210 LogDbg('DXCommand', "$call has too many connections ($v) at $nodes - disconnected");
211 already_conn($conn, $call, DXM::msg($lang, 'contomany', $call, $v, $nodes));
217 my $basecall = $call;
218 $basecall =~ s/-\d+$//;
219 my $baseuser = DXUser::get_current($basecall);
220 my $lock = $user->lockout if $user;
221 if ($baseuser && $baseuser->lockout || $lock) {
222 if (!$user || !defined $lock || $lock) {
223 my $host = $conn->peerhost || "unknown";
224 LogDbg('DXCommand', "$call on $host is locked out, disconnected");
231 $user->{lang} = $main::lang if !$user->{lang}; # to autoupdate old systems
233 $user = DXUser->new($call);
237 if ($user->is_node) {
238 $dxchan = DXProt->new($call, $conn, $user);
239 } elsif ($user->is_user) {
240 $dxchan = DXCommandmode->new($call, $conn, $user);
241 # } elsif ($user->is_bbs) { # there is no support so
242 # $dxchan = BBS->new($call, $conn, $user); # don't allow it!!!
244 die "Invalid sort of user on $call = $sort";
247 # check that the conn has a callsign
248 $conn->conns($call) if $conn->isa('IntMsg');
251 $conn->set_error(sub {my $err = shift; LogDbg('DXCommand', "Comms error '$err' received for call $dxchan->{call}"); $dxchan->disconnect(1);});
252 $conn->set_on_eof(sub {$dxchan->disconnect});
253 $conn->set_rproc(sub {my ($conn,$msg) = @_; $dxchan->rec($msg);});
260 return \&new_channel;
265 # cease running this program, close down all the connections nicely
270 cluck("ceasing") if $ceasing;
272 return if $ceasing++;
275 $SIG{'TERM'} = 'IGNORE';
276 $SIG{'INT'} = 'IGNORE';
281 if (defined &Local::finish) {
283 Local::finish(); # end local processing
285 dbg("Local::finish error $@") if $@;
293 # disconnect UDP customers
296 # end everything else
300 # close all databases
303 # close all listeners
304 foreach my $l (@listeners) {
308 LogDbg('cluster', "DXSpider V$version, build $build (git: $gitversion) ended");
309 dbg("bye bye everyone - bye bye");
313 $dbh->finish if $dbh;
318 # the reaper of children
322 while (($cpid = waitpid(-1, WNOHANG)) > 0) {
323 dbg("cpid: $cpid") if isdbg('reap');
324 # Msg->pid_gone($cpid);
325 $zombies-- if $zombies > 0;
327 dbg("cpid: $cpid") if isdbg('reap');
330 # this is where the input queue is dealt with and things are dispatched off to other parts of
335 my $t = $systime - $starttime;
336 my $days = int $t / 86400;
338 my $hours = int $t / 3600;
340 my $mins = int $t / 60;
341 return sprintf "%d %02d:%02d", $days, $hours, $mins;
346 AGWMsg::init(\&new_channel);
349 our $io_disconnected;
356 # DXChannel::process();
360 # do timed stuff, ongoing processing happens one a second
361 if ($timenow != $systime) {
364 my $days = int ($systime / 86400);
365 if ($systime_days != $days) {
366 $systime_days = $days;
367 $systime_daystart = $days * 86400;
369 IsoTime::update($systime);
370 DXCron::process(); # do cron jobs
371 DXCommandmode::process(); # process ongoing command mode stuff
373 DXProt::process(); # process ongoing ak1a pcxx stuff
374 DXConnect::process();
379 DXCron::process(); # do cron jobs
380 IsoTime::update($systime);
381 DXProt::process(); # process ongoing ak1a pcxx stuff
382 DXConnect::process();
390 if (defined &Local::process) {
392 Local::process(); # do any localised processing
394 dbg("Local::process error $@") if $@;
400 dbg("DXSpider Ending $ending");
402 unless ($io_disconnected++) {
405 foreach $dxchan (DXChannel::get_all_users) {
410 foreach $dxchan (DXChannel::get_all_nodes) {
411 next if $dxchan == $main::me;
412 $dxchan->disconnect(2);
414 $main::me->disconnect;
417 Mojo::IOLoop->stop if --$ending <= 0;
424 #############################################################
426 # The start of the main line of code
428 #############################################################
430 $starttime = $systime = time;
431 $systime_days = int ($systime / 86400);
432 $systime_daystart = $systime_days * 86400;
433 $lang = 'en' unless $lang;
435 unless ($DB::VERSION) {
436 $SIG{INT} = $SIG{TERM} = \&cease;
439 # open the debug file, set various FHs to be unbuffered
440 dbginit($broadcast_debug ? \&DXCommandmode::broadcast_debug : undef);
444 STDOUT->autoflush(1);
447 # try to load the database
448 if (DXSql::init($dsn)) {
449 $dbh = DXSql->new($dsn);
450 $dbh = $dbh->connect($dsn, $dbuser, $dbpass) if $dbh;
453 # try to load Encode and Git
456 my $w = $SIG{__DIE__};
457 $SIG{__DIE__} = 'IGNORE';
458 eval { require Encode; };
463 eval { require Git; };
467 # determine the real version number
468 my $repo = Git->repository(Directory => "$root/.git");
470 my $desc = $repo->command_oneline(['describe', '--long'], STDERR => 0);
472 my ($v, $s, $b, $g) = $desc =~ /^([\d.]+)(?:\.(\d+))?-(\d+)-g([0-9a-f]+)/;
475 $gitversion = "$g\[r]";
482 # try to load XML::Simple
486 my ($year) = (gmtime)[5];
488 LogDbg('cluster', "DXSpider V$version, build $build (git: $gitversion) started");
489 dbg("Copyright (c) 1998-$year Dirk Koopman G1TLH");
492 dbg("loading prefixes ...");
494 my $r = Prefix::init();
498 dbg("loading band data ...");
501 # initialise User file system
502 dbg("loading user file system ...");
505 # look for the sysop and the alias user and complain if they aren't there
507 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;
508 my $ref = DXUser::get($mycall);
509 die "$mycall missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
510 my $oldsort = $ref->sort;
511 if ($oldsort ne 'S') {
513 dbg "Resetting node type from $oldsort -> DXSpider ('S')";
515 $ref = DXUser::get($myalias);
516 die "$myalias missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
517 $oldsort = $ref->sort;
518 if ($oldsort ne 'U') {
520 dbg "Resetting sysop user type from $oldsort -> User ('U')";
524 # start listening for incoming messages/connects
525 dbg("starting listeners ...");
526 my $conn = IntMsg->new_server($clusteraddr, $clusterport, \&login);
527 $conn->conns("Server $clusteraddr/$clusterport using IntMsg");
528 push @listeners, $conn;
529 dbg("Internal port: $clusteraddr $clusterport using IntMsg");
530 foreach my $l (@main::listen) {
532 my $pkg = $l->[2] || 'ExtMsg';
533 my $login = $l->[3] || 'login';
535 $conn = $pkg->new_server($l->[0], $l->[1], \&{"${pkg}::${login}"});
536 $conn->conns("Server $l->[0]/$l->[1] using ${pkg}::${login}");
537 push @listeners, $conn;
538 dbg("External Port: $l->[0] $l->[1] using ${pkg}::${login}");
541 dbg("AGW Listener") if $AGWMsg::enable;
544 dbg("BPQ Listener") if $BPQMsg::enable;
545 BPQMsg::init(\&new_channel);
547 dbg("UDP Listener") if $UDPMsg::enable;
548 UDPMsg::init(\&new_channel);
551 dbg("load badwords: " . (BadWords::load or "Ok"));
554 unless ($DB::VERSION) {
555 $SIG{INT} = $SIG{TERM} = sub { $ending = 10; };
559 $SIG{HUP} = 'IGNORE';
560 $SIG{CHLD} = sub { $zombies++ };
562 $SIG{PIPE} = sub { dbg("Broken PIPE signal received"); };
563 $SIG{IO} = sub { dbg("SIGIO received"); };
564 $SIG{WINCH} = $SIG{STOP} = $SIG{CONT} = 'IGNORE';
565 $SIG{KILL} = 'DEFAULT'; # as if it matters....
567 # catch the rest with a hopeful message
570 # dbg("Catching SIG $_") if isdbg('chan');
571 $SIG{$_} = sub { my $sig = shift; DXDebug::confess("Caught signal $sig"); };
577 dbg("Starting Dupe system");
580 # read in system messages
581 dbg("Read in Messages");
584 # read in command aliases
585 dbg("Read in Aliases");
588 # initialise the Geomagnetic data engine
594 # initial the Spot stuff
595 dbg("Starting DX Spot system");
598 # initialise the protocol engine
599 dbg("Start Protocol Engines ...");
602 # put in a DXCluster node for us here so we can add users and take them away
603 $routeroot = Route::Node->new($mycall, $version*100+5300, Route::here($main::me->here)|Route::conf($main::me->conf));
604 $routeroot->do_pc9x(1);
605 $routeroot->via_pc92(1);
607 # make sure that there is a routing OUTPUT node default file
608 #unless (Filter::read_in('route', 'node_default', 0)) {
609 # my $dxcc = $main::me->dxcc;
610 # $Route::filterdef->cmd($main::me, 'route', 'accept', "node_default call $mycall" );
613 # read in any existing message headers and clean out old crap
614 dbg("reading existing message headers ...");
618 # read in any cron jobs
619 dbg("reading cron jobs ...");
622 # read in database desriptors
623 dbg("reading database descriptors ...");
626 # starting local stuff
627 dbg("doing local initialisation ...");
629 if (defined &Local::init) {
633 dbg("Local::init error $@") if $@;
637 # this, such as it is, is the main loop!
638 dbg("orft we jolly well go ...");
639 my $script = new Script "startup";
640 $script->run($main::me) if $script;
642 #open(DB::OUT, "|tee /tmp/aa");
648 my $main_loop = Mojo::IOLoop->recurring($idle_interval => \&idle_loop);
649 my $log_flush_loop = Mojo::IOLoop->recurring($log_flush_interval => \&DXLog::flushall);