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
15 # make sure that modules are searched in the order local then perl
19 # root of directory tree for this system
21 $root = $ENV{'DXSPIDER_ROOT'} if $ENV{'DXSPIDER_ROOT'};
23 unshift @INC, "$root/perl"; # this IS the right way round!
24 unshift @INC, "$root/local";
26 # do some validation of the input
27 die "The directory $root doesn't exist, please RTFM" unless -d $root;
28 die "$root/local doesn't exist, please RTFM" unless -d "$root/local";
29 die "$root/local/DXVars.pm doesn't exist, please RTFM" unless -e "$root/local/DXVars.pm";
31 mkdir "$root/local_cmd", 0777 unless -d "$root/local_cmd";
34 # try to create and lock a lockfile (this isn't atomic but
36 $lockfn = "$root/local/cluster.lck"; # lock file name
38 open(CLLOCK, "$lockfn") or die "Can't open Lockfile ($lockfn) $!";
42 die "Lockfile ($lockfn) and process $pid exist, another cluster running?" if kill 0, $pid;
47 open(CLLOCK, ">$lockfn") or die "Can't open Lockfile ($lockfn) $!";
51 $is_win = ($^O =~ /^MS/ || $^O =~ /^OS-2/) ? 1 : 0; # is it Windows?
114 use POSIX ":sys_wait_h";
122 use vars qw(@inqueue $systime $starttime $lockfn @outstanding_connects
123 $zombies $root @listeners $lang $myalias @debug $userfn $clusteraddr
124 $clusterport $mycall $decease $is_win $routeroot $me $reqreg $bumpexisting
125 $allowdxby $dbh $dsn $dbuser $dbpass $do_xml $systime_days $systime_daystart
126 $can_encode $maxconnect_user $maxconnect_node $idle_interval $log_flush_interval
129 @inqueue = (); # the main input queue, an array of hashes
130 $systime = 0; # the time now (in seconds)
131 $starttime = 0; # the starting time of the cluster
132 @outstanding_connects = (); # list of outstanding connects
133 @listeners = (); # list of listeners
134 $reqreg = 0; # 1 = registration required, 2 = deregister people
135 $bumpexisting = 1; # 1 = allow new connection to disconnect old, 0 - don't allow it
136 $allowdxby = 0; # 1 = allow "dx by <othercall>", 0 - don't allow it
137 $maxconnect_user = 3; # the maximum no of concurrent connections a user can have at a time
138 $maxconnect_node = 0; # Ditto but for nodes. In either case if a new incoming connection
139 # takes the no of references in the routing table above these numbers
140 # then the connection is refused. This only affects INCOMING connections.
141 $idle_interval = 0.500; # the wait between invocations of the main idle loop processing.
142 $log_flush_interval = 2; # interval to wait between log flushes
144 our $ending; # signal that we are ending;
147 # send a message to call on conn and disconnect
150 my ($conn, $call, $mess) = @_;
152 $conn->disable_read(1);
153 dbg("-> D $call $mess\n") if isdbg('chan');
154 $conn->send_now("D$call|$mess");
159 # handle incoming messages
162 my ($conn, $msg) = @_;
163 my ($sort, $call, $line) = DXChannel::decode_input(0, $msg);
164 return unless defined $sort;
166 unless (is_callsign($call)) {
167 already_conn($conn, $call, DXM::msg($lang, "illcall", $call));
171 # set up the basic channel info
172 # is there one already connected to me - locally?
173 my $user = DXUser::get_current($call);
174 my $dxchan = DXChannel::get($call);
176 if ($user && $user->is_node) {
177 already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
181 my $ip = $conn->peerhost || 'unknown';
182 $dxchan->send_now('D', DXM::msg($lang, 'conbump', $call, $ip));
183 LogDbg('DXCommand', "$call bumped off by $ip, disconnected");
186 already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
191 # (fairly) politely disconnect people that are connected to too many other places at once
192 my $r = Route::get($call);
193 if ($conn->{sort} && $conn->{sort} =~ /^I/ && $r && $user) {
195 my $m = $r->isa('Route::Node') ? $maxconnect_node : $maxconnect_user;
196 my $c = $user->maxconnect;
198 $v = defined $c ? $c : $m;
199 if ($v && @n >= $v) {
200 my $nodes = join ',', @n;
201 LogDbg('DXCommand', "$call has too many connections ($v) at $nodes - disconnected");
202 already_conn($conn, $call, DXM::msg($lang, 'contomany', $call, $v, $nodes));
208 my $basecall = $call;
209 $basecall =~ s/-\d+$//;
210 my $baseuser = DXUser::get_current($basecall);
211 my $lock = $user->lockout if $user;
212 if ($baseuser && $baseuser->lockout || $lock) {
213 if (!$user || !defined $lock || $lock) {
214 my $host = $conn->peerhost || "unknown";
215 LogDbg('DXCommand', "$call on $host is locked out, disconnected");
222 $user->{lang} = $main::lang if !$user->{lang}; # to autoupdate old systems
224 $user = DXUser->new($call);
228 if ($user->is_node) {
229 $dxchan = DXProt->new($call, $conn, $user);
230 } elsif ($user->is_user) {
231 $dxchan = DXCommandmode->new($call, $conn, $user);
232 # } elsif ($user->is_bbs) { # there is no support so
233 # $dxchan = BBS->new($call, $conn, $user); # don't allow it!!!
235 die "Invalid sort of user on $call = $sort";
238 # check that the conn has a callsign
239 $conn->conns($call) if $conn->isa('IntMsg');
242 $conn->set_error(sub {my $err = shift; LogDbg('DXCommand', "Comms error '$err' received for call $dxchan->{call}"); $dxchan->disconnect(1);});
243 $conn->set_on_eof(sub {$dxchan->disconnect});
244 $conn->set_rproc(sub {my ($conn,$msg) = @_; $dxchan->rec($msg);});
251 return \&new_channel;
256 # cease running this program, close down all the connections nicely
261 cluck("ceasing") if $ceasing;
263 return if $ceasing++;
266 $SIG{'TERM'} = 'IGNORE';
267 $SIG{'INT'} = 'IGNORE';
272 if (defined &Local::finish) {
274 Local::finish(); # end local processing
276 dbg("Local::finish error $@") if $@;
284 # disconnect UDP customers
287 # end everything else
291 # close all databases
294 # close all listeners
295 foreach my $l (@listeners) {
299 LogDbg('cluster', "DXSpider V$version, build $build (git: $gitversion) ended");
300 dbg("bye bye everyone - bye bye");
304 $dbh->finish if $dbh;
309 # the reaper of children
313 while (($cpid = waitpid(-1, WNOHANG)) > 0) {
314 dbg("cpid: $cpid") if isdbg('reap');
315 # Msg->pid_gone($cpid);
316 $zombies-- if $zombies > 0;
318 dbg("cpid: $cpid") if isdbg('reap');
321 # this is where the input queue is dealt with and things are dispatched off to other parts of
326 my $t = $systime - $starttime;
327 my $days = int $t / 86400;
329 my $hours = int $t / 3600;
331 my $mins = int $t / 60;
332 return sprintf "%d %02d:%02d", $days, $hours, $mins;
337 AGWMsg::init(\&new_channel);
340 our $io_disconnected;
347 # DXChannel::process();
351 # do timed stuff, ongoing processing happens one a second
352 if ($timenow != $systime) {
355 my $days = int ($systime / 86400);
356 if ($systime_days != $days) {
357 $systime_days = $days;
358 $systime_daystart = $days * 86400;
360 IsoTime::update($systime);
361 DXCron::process(); # do cron jobs
362 DXCommandmode::process(); # process ongoing command mode stuff
364 DXProt::process(); # process ongoing ak1a pcxx stuff
365 DXConnect::process();
370 DXCron::process(); # do cron jobs
371 IsoTime::update($systime);
372 DXProt::process(); # process ongoing ak1a pcxx stuff
373 DXConnect::process();
381 if (defined &Local::process) {
383 Local::process(); # do any localised processing
385 dbg("Local::process error $@") if $@;
391 dbg("DXSpider Ending $ending");
393 unless ($io_disconnected++) {
396 foreach $dxchan (DXChannel::get_all_users) {
401 foreach $dxchan (DXChannel::get_all_nodes) {
402 next if $dxchan == $main::me;
403 $dxchan->disconnect(2);
405 $main::me->disconnect;
408 Mojo::IOLoop->stop if --$ending <= 0;
413 #############################################################
415 # The start of the main line of code
417 #############################################################
419 $starttime = $systime = time;
420 $systime_days = int ($systime / 86400);
421 $systime_daystart = $systime_days * 86400;
422 $lang = 'en' unless $lang;
424 unless ($DB::VERSION) {
425 $SIG{INT} = $SIG{TERM} = \&cease;
428 # open the debug file, set various FHs to be unbuffered
429 dbginit(\&DXCommandmode::broadcast_debug);
433 STDOUT->autoflush(1);
435 # try to load the database
436 if (DXSql::init($dsn)) {
437 $dbh = DXSql->new($dsn);
438 $dbh = $dbh->connect($dsn, $dbuser, $dbpass) if $dbh;
441 # try to load Encode and Git
444 my $w = $SIG{__DIE__};
445 $SIG{__DIE__} = 'IGNORE';
446 eval { require Encode; };
451 eval { require Git; };
455 # determine the real version number
456 my $repo = Git->repository(Directory => "$root/.git");
458 my $desc = $repo->command_oneline(['describe', '--long'], STDERR => 0);
460 my ($v, $s, $b, $g) = $desc =~ /^([\d.]+)(?:\.(\d+))?-(\d+)-g([0-9a-f]+)/;
463 $gitversion = "$g\[r]";
470 # try to load XML::Simple
474 my ($year) = (gmtime)[5];
476 LogDbg('cluster', "DXSpider V$version, build $build (git: $gitversion) started");
477 dbg("Copyright (c) 1998-$year Dirk Koopman G1TLH");
480 dbg("loading prefixes ...");
482 my $r = Prefix::init();
486 dbg("loading band data ...");
489 # initialise User file system
490 dbg("loading user file system ...");
491 DXUser->init($userfn, 1);
493 # look for the sysop and the alias user and complain if they aren't there
495 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;
496 my $ref = DXUser::get($mycall);
497 die "$mycall missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
498 $ref = DXUser::get($myalias);
499 die "$myalias missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
502 # start listening for incoming messages/connects
503 dbg("starting listeners ...");
504 my $conn = IntMsg->new_server($clusteraddr, $clusterport, \&login);
505 $conn->conns("Server $clusteraddr/$clusterport using IntMsg");
506 push @listeners, $conn;
507 dbg("Internal port: $clusteraddr $clusterport using IntMsg");
508 foreach my $l (@main::listen) {
510 my $pkg = $l->[2] || 'ExtMsg';
511 my $login = $l->[3] || 'login';
513 $conn = $pkg->new_server($l->[0], $l->[1], \&{"${pkg}::${login}"});
514 $conn->conns("Server $l->[0]/$l->[1] using ${pkg}::${login}");
515 push @listeners, $conn;
516 dbg("External Port: $l->[0] $l->[1] using ${pkg}::${login}");
519 dbg("AGW Listener") if $AGWMsg::enable;
522 dbg("BPQ Listener") if $BPQMsg::enable;
523 BPQMsg::init(\&new_channel);
525 dbg("UDP Listener") if $UDPMsg::enable;
526 UDPMsg::init(\&new_channel);
529 dbg("load badwords: " . (BadWords::load or "Ok"));
532 unless ($DB::VERSION) {
533 $SIG{INT} = $SIG{TERM} = sub { $ending = 10; };
537 $SIG{HUP} = 'IGNORE';
538 $SIG{CHLD} = sub { $zombies++ };
540 $SIG{PIPE} = sub { dbg("Broken PIPE signal received"); };
541 $SIG{IO} = sub { dbg("SIGIO received"); };
542 $SIG{WINCH} = $SIG{STOP} = $SIG{CONT} = 'IGNORE';
543 $SIG{KILL} = 'DEFAULT'; # as if it matters....
545 # catch the rest with a hopeful message
548 # dbg("Catching SIG $_") if isdbg('chan');
549 $SIG{$_} = sub { my $sig = shift; DXDebug::confess("Caught signal $sig"); };
555 dbg("Starting Dupe system");
558 # read in system messages
559 dbg("Read in Messages");
562 # read in command aliases
563 dbg("Read in Aliases");
566 # initialise the Geomagnetic data engine
572 # initial the Spot stuff
573 dbg("Starting DX Spot system");
576 # initialise the protocol engine
577 dbg("Start Protocol Engines ...");
580 # put in a DXCluster node for us here so we can add users and take them away
581 $routeroot = Route::Node->new($mycall, $version*100+5300, Route::here($main::me->here)|Route::conf($main::me->conf));
582 $routeroot->do_pc9x(1);
583 $routeroot->via_pc92(1);
585 # make sure that there is a routing OUTPUT node default file
586 #unless (Filter::read_in('route', 'node_default', 0)) {
587 # my $dxcc = $main::me->dxcc;
588 # $Route::filterdef->cmd($main::me, 'route', 'accept', "node_default call $mycall" );
591 # read in any existing message headers and clean out old crap
592 dbg("reading existing message headers ...");
596 # read in any cron jobs
597 dbg("reading cron jobs ...");
600 # read in database desriptors
601 dbg("reading database descriptors ...");
604 # starting local stuff
605 dbg("doing local initialisation ...");
607 if (defined &Local::init) {
611 dbg("Local::init error $@") if $@;
615 # this, such as it is, is the main loop!
616 dbg("orft we jolly well go ...");
617 my $script = new Script "startup";
618 $script->run($main::me) if $script;
620 #open(DB::OUT, "|tee /tmp/aa");
622 my $main_loop = Mojo::IOLoop->recurring($idle_interval => \&idle_loop);
623 my $log_flush_loop = Mojo::IOLoop->recurring($log_flush_interval => \&DXLog::flushall);
625 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
627 dbg("After Mojo::IOLoop");