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
16 # make sure that modules are searched in the order local then perl
20 # root of directory tree for this system
22 $root = $ENV{'DXSPIDER_ROOT'} if $ENV{'DXSPIDER_ROOT'};
24 unshift @INC, "$root/perl"; # this IS the right way round!
25 unshift @INC, "$root/local";
27 # do some validation of the input
28 die "The directory $root doesn't exist, please RTFM" unless -d $root;
29 die "$root/local doesn't exist, please RTFM" unless -d "$root/local";
30 die "$root/local/DXVars.pm doesn't exist, please RTFM" unless -e "$root/local/DXVars.pm";
32 mkdir "$root/local_cmd", 0777 unless -d "$root/local_cmd";
35 # try to create and lock a lockfile (this isn't atomic but
37 $lockfn = "$root/local/cluster.lck"; # lock file name
39 open(CLLOCK, "$lockfn") or die "Can't open Lockfile ($lockfn) $!";
43 die "Lockfile ($lockfn) and process $pid exist, another cluster running?" if kill 0, $pid;
48 open(CLLOCK, ">$lockfn") or die "Can't open Lockfile ($lockfn) $!";
52 $is_win = ($^O =~ /^MS/ || $^O =~ /^OS-2/) ? 1 : 0; # is it Windows?
115 use POSIX ":sys_wait_h";
124 use vars qw(@inqueue $systime $starttime $lockfn @outstanding_connects
125 $zombies $root @listeners $lang $myalias @debug $userfn $clusteraddr
126 $clusterport $mycall $decease $is_win $routeroot $me $reqreg $bumpexisting
127 $allowdxby $dbh $dsn $dbuser $dbpass $do_xml $systime_days $systime_daystart
128 $can_encode $maxconnect_user $maxconnect_node $idle_interval $log_flush_interval
132 @inqueue = (); # the main input queue, an array of hashes
133 $systime = 0; # the time now (in seconds)
134 $starttime = 0; # the starting time of the cluster
135 @outstanding_connects = (); # list of outstanding connects
136 @listeners = (); # list of listeners
137 $reqreg = 0; # 1 = registration required, 2 = deregister people
138 $bumpexisting = 1; # 1 = allow new connection to disconnect old, 0 - don't allow it
139 $allowdxby = 0; # 1 = allow "dx by <othercall>", 0 - don't allow it
140 $maxconnect_user = 3; # the maximum no of concurrent connections a user can have at a time
141 $maxconnect_node = 0; # Ditto but for nodes. In either case if a new incoming connection
142 # takes the no of references in the routing table above these numbers
143 # then the connection is refused. This only affects INCOMING connections.
144 $idle_interval = 0.500; # the wait between invocations of the main idle loop processing.
145 $log_flush_interval = 2; # interval to wait between log flushes
147 our $ending; # signal that we are ending;
148 our $broadcast_debug; # allow broadcasting of debug info down "enhanced" user connections
152 # send a message to call on conn and disconnect
155 my ($conn, $call, $mess) = @_;
157 $conn->disable_read(1);
158 dbg("-> D $call $mess\n") if isdbg('chan');
159 $conn->send_now("D$call|$mess");
164 # handle incoming messages
167 my ($conn, $msg) = @_;
168 my ($sort, $call, $line) = DXChannel::decode_input(0, $msg);
169 return unless defined $sort;
171 unless (is_callsign($call)) {
172 already_conn($conn, $call, DXM::msg($lang, "illcall", $call));
176 # set up the basic channel info
177 # is there one already connected to me - locally?
178 my $user = DXUser::get_current($call);
179 my $dxchan = DXChannel::get($call);
181 if ($user && $user->is_node) {
182 already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
186 my $ip = $conn->peerhost || 'unknown';
187 $dxchan->send_now('D', DXM::msg($lang, 'conbump', $call, $ip));
188 LogDbg('DXCommand', "$call bumped off by $ip, disconnected");
191 already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
196 # (fairly) politely disconnect people that are connected to too many other places at once
197 my $r = Route::get($call);
198 if ($conn->{sort} && $conn->{sort} =~ /^I/ && $r && $user) {
200 my $m = $r->isa('Route::Node') ? $maxconnect_node : $maxconnect_user;
201 my $c = $user->maxconnect;
203 $v = defined $c ? $c : $m;
204 if ($v && @n >= $v) {
205 my $nodes = join ',', @n;
206 LogDbg('DXCommand', "$call has too many connections ($v) at $nodes - disconnected");
207 already_conn($conn, $call, DXM::msg($lang, 'contomany', $call, $v, $nodes));
213 my $basecall = $call;
214 $basecall =~ s/-\d+$//;
215 my $baseuser = DXUser::get_current($basecall);
216 my $lock = $user->lockout if $user;
217 if ($baseuser && $baseuser->lockout || $lock) {
218 if (!$user || !defined $lock || $lock) {
219 my $host = $conn->peerhost || "unknown";
220 LogDbg('DXCommand', "$call on $host is locked out, disconnected");
227 $user->{lang} = $main::lang if !$user->{lang}; # to autoupdate old systems
229 $user = DXUser->new($call);
233 if ($user->is_node) {
234 $dxchan = DXProt->new($call, $conn, $user);
235 } elsif ($user->is_user) {
236 $dxchan = DXCommandmode->new($call, $conn, $user);
237 # } elsif ($user->is_bbs) { # there is no support so
238 # $dxchan = BBS->new($call, $conn, $user); # don't allow it!!!
240 die "Invalid sort of user on $call = $sort";
243 # check that the conn has a callsign
244 $conn->conns($call) if $conn->isa('IntMsg');
247 $conn->set_error(sub {my $err = shift; LogDbg('DXCommand', "Comms error '$err' received for call $dxchan->{call}"); $dxchan->disconnect(1);});
248 $conn->set_on_eof(sub {$dxchan->disconnect});
249 $conn->set_rproc(sub {my ($conn,$msg) = @_; $dxchan->rec($msg);});
256 return \&new_channel;
261 # cease running this program, close down all the connections nicely
266 cluck("ceasing") if $ceasing;
268 return if $ceasing++;
271 $SIG{'TERM'} = 'IGNORE';
272 $SIG{'INT'} = 'IGNORE';
277 if (defined &Local::finish) {
279 Local::finish(); # end local processing
281 dbg("Local::finish error $@") if $@;
289 # disconnect UDP customers
292 # end everything else
296 # close all databases
299 # close all listeners
300 foreach my $l (@listeners) {
304 LogDbg('cluster', "DXSpider V$version, build $build (git: $gitversion) ended");
305 dbg("bye bye everyone - bye bye");
309 $dbh->finish if $dbh;
314 # the reaper of children
318 while (($cpid = waitpid(-1, WNOHANG)) > 0) {
319 dbg("cpid: $cpid") if isdbg('reap');
320 # Msg->pid_gone($cpid);
321 $zombies-- if $zombies > 0;
323 dbg("cpid: $cpid") if isdbg('reap');
326 # this is where the input queue is dealt with and things are dispatched off to other parts of
331 my $t = $systime - $starttime;
332 my $days = int $t / 86400;
334 my $hours = int $t / 3600;
336 my $mins = int $t / 60;
337 return sprintf "%d %02d:%02d", $days, $hours, $mins;
342 AGWMsg::init(\&new_channel);
345 our $io_disconnected;
352 # DXChannel::process();
356 # do timed stuff, ongoing processing happens one a second
357 if ($timenow != $systime) {
360 my $days = int ($systime / 86400);
361 if ($systime_days != $days) {
362 $systime_days = $days;
363 $systime_daystart = $days * 86400;
365 IsoTime::update($systime);
366 DXCron::process(); # do cron jobs
367 DXCommandmode::process(); # process ongoing command mode stuff
369 DXProt::process(); # process ongoing ak1a pcxx stuff
370 DXConnect::process();
375 DXCron::process(); # do cron jobs
376 IsoTime::update($systime);
377 DXProt::process(); # process ongoing ak1a pcxx stuff
378 DXConnect::process();
386 if (defined &Local::process) {
388 Local::process(); # do any localised processing
390 dbg("Local::process error $@") if $@;
396 dbg("DXSpider Ending $ending");
398 unless ($io_disconnected++) {
401 foreach $dxchan (DXChannel::get_all_users) {
406 foreach $dxchan (DXChannel::get_all_nodes) {
407 next if $dxchan == $main::me;
408 $dxchan->disconnect(2);
410 $main::me->disconnect;
413 Mojo::IOLoop->stop if --$ending <= 0;
420 #############################################################
422 # The start of the main line of code
424 #############################################################
426 $starttime = $systime = time;
427 $systime_days = int ($systime / 86400);
428 $systime_daystart = $systime_days * 86400;
429 $lang = 'en' unless $lang;
431 unless ($DB::VERSION) {
432 $SIG{INT} = $SIG{TERM} = \&cease;
435 # open the debug file, set various FHs to be unbuffered
436 dbginit($broadcast_debug ? \&DXCommandmode::broadcast_debug : undef);
440 STDOUT->autoflush(1);
442 # try to load the database
443 if (DXSql::init($dsn)) {
444 $dbh = DXSql->new($dsn);
445 $dbh = $dbh->connect($dsn, $dbuser, $dbpass) if $dbh;
448 # try to load Encode and Git
451 my $w = $SIG{__DIE__};
452 $SIG{__DIE__} = 'IGNORE';
453 eval { require Encode; };
458 eval { require Git; };
462 # determine the real version number
463 my $repo = Git->repository(Directory => "$root/.git");
465 my $desc = $repo->command_oneline(['describe', '--long'], STDERR => 0);
467 my ($v, $s, $b, $g) = $desc =~ /^([\d.]+)(?:\.(\d+))?-(\d+)-g([0-9a-f]+)/;
470 $gitversion = "$g\[r]";
477 # try to load XML::Simple
481 my ($year) = (gmtime)[5];
483 LogDbg('cluster', "DXSpider V$version, build $build (git: $gitversion) started");
484 dbg("Copyright (c) 1998-$year Dirk Koopman G1TLH");
487 dbg("loading prefixes ...");
489 my $r = Prefix::init();
493 dbg("loading band data ...");
496 # initialise User file system
497 dbg("loading user file system ...");
498 DXUser->init($userfn, 1);
500 # look for the sysop and the alias user and complain if they aren't there
502 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;
503 my $ref = DXUser::get($mycall);
504 die "$mycall missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
505 my $oldsort = $ref->sort;
506 if ($oldsort ne 'S') {
508 dbg "Resetting node type from $oldsort -> DXSpider ('S')";
510 $ref = DXUser::get($myalias);
511 die "$myalias missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
512 $oldsort = $ref->sort;
513 if ($oldsort ne 'U') {
515 dbg "Resetting sysop user type from $oldsort -> User ('U')";
519 # start listening for incoming messages/connects
520 dbg("starting listeners ...");
521 my $conn = IntMsg->new_server($clusteraddr, $clusterport, \&login);
522 $conn->conns("Server $clusteraddr/$clusterport using IntMsg");
523 push @listeners, $conn;
524 dbg("Internal port: $clusteraddr $clusterport using IntMsg");
525 foreach my $l (@main::listen) {
527 my $pkg = $l->[2] || 'ExtMsg';
528 my $login = $l->[3] || 'login';
530 $conn = $pkg->new_server($l->[0], $l->[1], \&{"${pkg}::${login}"});
531 $conn->conns("Server $l->[0]/$l->[1] using ${pkg}::${login}");
532 push @listeners, $conn;
533 dbg("External Port: $l->[0] $l->[1] using ${pkg}::${login}");
536 dbg("AGW Listener") if $AGWMsg::enable;
539 dbg("BPQ Listener") if $BPQMsg::enable;
540 BPQMsg::init(\&new_channel);
542 dbg("UDP Listener") if $UDPMsg::enable;
543 UDPMsg::init(\&new_channel);
546 dbg("load badwords: " . (BadWords::load or "Ok"));
549 unless ($DB::VERSION) {
550 $SIG{INT} = $SIG{TERM} = sub { $ending = 10; };
554 $SIG{HUP} = 'IGNORE';
555 $SIG{CHLD} = sub { $zombies++ };
557 $SIG{PIPE} = sub { dbg("Broken PIPE signal received"); };
558 $SIG{IO} = sub { dbg("SIGIO received"); };
559 $SIG{WINCH} = $SIG{STOP} = $SIG{CONT} = 'IGNORE';
560 $SIG{KILL} = 'DEFAULT'; # as if it matters....
562 # catch the rest with a hopeful message
565 # dbg("Catching SIG $_") if isdbg('chan');
566 $SIG{$_} = sub { my $sig = shift; DXDebug::confess("Caught signal $sig"); };
572 dbg("Starting Dupe system");
575 # read in system messages
576 dbg("Read in Messages");
579 # read in command aliases
580 dbg("Read in Aliases");
583 # initialise the Geomagnetic data engine
589 # initial the Spot stuff
590 dbg("Starting DX Spot system");
593 # initialise the protocol engine
594 dbg("Start Protocol Engines ...");
597 # put in a DXCluster node for us here so we can add users and take them away
598 $routeroot = Route::Node->new($mycall, $version*100+5300, Route::here($main::me->here)|Route::conf($main::me->conf));
599 $routeroot->do_pc9x(1);
600 $routeroot->via_pc92(1);
602 # make sure that there is a routing OUTPUT node default file
603 #unless (Filter::read_in('route', 'node_default', 0)) {
604 # my $dxcc = $main::me->dxcc;
605 # $Route::filterdef->cmd($main::me, 'route', 'accept', "node_default call $mycall" );
608 # read in any existing message headers and clean out old crap
609 dbg("reading existing message headers ...");
613 # read in any cron jobs
614 dbg("reading cron jobs ...");
617 # read in database desriptors
618 dbg("reading database descriptors ...");
621 # starting local stuff
622 dbg("doing local initialisation ...");
624 if (defined &Local::init) {
628 dbg("Local::init error $@") if $@;
632 # this, such as it is, is the main loop!
633 dbg("orft we jolly well go ...");
634 my $script = new Script "startup";
635 $script->run($main::me) if $script;
637 #open(DB::OUT, "|tee /tmp/aa");
643 my $main_loop = Mojo::IOLoop->recurring($idle_interval => \&idle_loop);
644 my $log_flush_loop = Mojo::IOLoop->recurring($log_flush_interval => \&DXLog::flushall);