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 @inqueue $starttime $lockfn @outstanding_connects
19 $zombies @listeners $lang $myalias @debug $userfn $clusteraddr
20 $clusterport $mycall $decease $routeroot $me $reqreg $bumpexisting
21 $allowdxby $dbh $dsn $dbuser $dbpass $do_xml $systime_days $systime_daystart
22 $can_encode $maxconnect_user $maxconnect_node $idle_interval $log_flush_interval
26 $lang = 'en'; # default language
27 $clusteraddr = '127.0.0.1'; # cluster tcp host address - used for things like console.pl
28 $clusterport = 27754; # cluster tcp port
29 $yes = 'Yes'; # visual representation of yes
30 $no = 'No'; # ditto for no
31 $user_interval = 11*60; # the interval between unsolicited prompts if no traffic
33 # make sure that modules are searched in the order local then perl
37 # take into account any local::lib that might be present
41 import local::lib unless ($@);
43 # root of directory tree for this system
45 $root = $ENV{'DXSPIDER_ROOT'} if $ENV{'DXSPIDER_ROOT'};
47 unshift @INC, "$root/perl"; # this IS the right way round!
48 unshift @INC, "$root/local";
50 # do some validation of the input
51 die "The directory $root doesn't exist, please RTFM" unless -d $root;
52 die "$root/local doesn't exist, please RTFM" unless -d "$root/local";
53 die "$root/local/DXVars.pm doesn't exist, please RTFM" unless -e "$root/local/DXVars.pm";
55 # create some directories
56 mkdir "$root/local_cmd", 02774 unless -d "$root/local_cmd";
58 # locally stored data lives here
59 my $local_data = "$root/local_data";
60 mkdir $local_data, 02774 unless -d $local_data;
62 # try to create and lock a lockfile (this isn't atomic but
64 $lockfn = "$root/local_data/cluster.lck"; # lock file name
66 open(CLLOCK, "$lockfn") or die "Can't open Lockfile ($lockfn) $!";
71 warn "Lockfile ($lockfn) and process $pid exist, another cluster running?\n";
78 open(CLLOCK, ">$lockfn") or die "Can't open Lockfile ($lockfn) $!";
82 $is_win = ($^O =~ /^MS/ || $^O =~ /^OS-2/) ? 1 : 0; # is it Windows?
152 use POSIX ":sys_wait_h";
159 @inqueue = (); # the main input queue, an array of hashes
160 $systime = 0; # the time now (in seconds)
161 $starttime = 0; # the starting time of the cluster
162 @outstanding_connects = (); # list of outstanding connects
163 @listeners = (); # list of listeners
164 $reqreg = 0; # 1 = registration required, 2 = deregister people
165 $bumpexisting = 1; # 1 = allow new connection to disconnect old, 0 - don't allow it
166 $allowdxby = 0; # 1 = allow "dx by <othercall>", 0 - don't allow it
167 $maxconnect_user = 3; # the maximum no of concurrent connections a user can have at a time
168 $maxconnect_node = 0; # Ditto but for nodes. In either case if a new incoming connection
169 # takes the no of references in the routing table above these numbers
170 # then the connection is refused. This only affects INCOMING connections.
171 $idle_interval = 0.500; # the wait between invocations of the main idle loop processing.
172 $log_flush_interval = 2; # interval to wait between log flushes
174 our $ending; # signal that we are ending;
175 our $broadcast_debug; # allow broadcasting of debug info down "enhanced" user connections
176 our $clssecs; # the amount of cpu time the DXSpider process have consumed
177 our $cldsecs; # the amount of cpu time any child processes have consumed
180 # send a message to call on conn and disconnect
183 my ($conn, $call, $mess) = @_;
185 $conn->disable_read(1);
186 dbg("-> D $call $mess\n") if isdbg('chan');
187 $conn->send_now("D$call|$mess");
192 # handle incoming messages
195 my ($conn, $msg) = @_;
196 my ($sort, $call, $line) = DXChannel::decode_input(0, $msg);
197 return unless defined $sort;
201 if (is_webcall($call) && $conn->isa('IntMsg')) {
202 my $newcall = find_next_webcall();
204 already_conn($conn, $call, "Maximum no of web connected connects ($Web::maxssid) exceeded");
208 $user = DXUser::get_current($call);
210 $user = DXUser->new($call);
214 $user->qth('on the web');
215 $user->homenode($main::mycall);
216 $user->lat($main::mylatitude);
217 $user->long($main::mylongitude);
218 $user->qra($main::mylocator);
221 $dxchan = Web->new($call, $conn, $user);
222 $dxchan->enhanced(1);
224 $msg =~ s/^A#WEB|/A$call|/;
225 $conn->send_now("C$call");
227 # "Normal" connections
228 unless (is_callsign($call)) {
229 already_conn($conn, $call, DXM::msg($lang, "illcall", $call));
233 # set up the basic channel info for "Normal" Users
234 # is there one already connected to me - locally?
236 $user = DXUser::get_current($call);
237 $dxchan = DXChannel::get($call);
239 if ($user && $user->is_node) {
240 already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
244 my $ip = $dxchan->hostname;
245 $dxchan->send_now('D', DXM::msg($lang, 'conbump', $call, $ip));
246 LogDbg('DXCommand', "$call bumped off by $ip, disconnected");
249 already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
254 # (fairly) politely disconnect people that are connected to too many other places at once
255 my $r = Route::get($call);
256 if ($conn->{sort} && $conn->{sort} =~ /^I/ && $r && $user) {
258 my $m = $r->isa('Route::Node') ? $maxconnect_node : $maxconnect_user;
259 my $c = $user->maxconnect;
261 $v = defined $c ? $c : $m;
262 if ($v && @n >= $v) {
263 my $nodes = join ',', @n;
264 LogDbg('DXCommand', "$call has too many connections ($v) at $nodes - disconnected");
265 already_conn($conn, $call, DXM::msg($lang, 'contomany', $call, $v, $nodes));
271 my $basecall = $call;
272 $basecall =~ s/-\d+$//;
273 my $baseuser = DXUser::get_current($basecall);
274 my $lock = $user->lockout if $user;
275 if ($baseuser && $baseuser->lockout || $lock) {
276 if (!$user || !defined $lock || $lock) {
277 my $host = $conn->peerhost;
278 LogDbg('DXCommand', "$call on $host is locked out, disconnected");
285 $user->{lang} = $main::lang if !$user->{lang}; # to autoupdate old systems
287 $user = DXUser->new($call);
291 if ($user->is_node) {
292 $dxchan = DXProt->new($call, $conn, $user);
293 } elsif ($user->is_user) {
294 $dxchan = DXCommandmode->new($call, $conn, $user);
296 die "Invalid sort of user on $call = $sort";
299 # check that the conn has a callsign
300 $conn->conns($call) if $conn->isa('IntMsg');
305 $conn->set_error(sub {my $err = shift; LogDbg('DXCommand', "Comms error '$err' received for call $dxchan->{call}"); $dxchan->disconnect(1);});
306 $conn->set_on_eof(sub {$dxchan->disconnect});
307 $conn->set_rproc(sub {my ($conn,$msg) = @_; $dxchan->rec($msg);});
309 $dxchan->enhanced(1);
318 return \&new_channel;
323 # cease running this program, close down all the connections nicely
328 cluck("ceasing") if $ceasing;
330 return if $ceasing++;
333 $SIG{'TERM'} = 'IGNORE';
334 $SIG{'INT'} = 'IGNORE';
339 if (defined &Local::finish) {
341 Local::finish(); # end local processing
343 dbg("Local::finish error $@") if $@;
351 # disconnect UDP customers
354 # end everything else
358 # close all databases
361 # close all listeners
362 foreach my $l (@listeners) {
366 LogDbg('cluster', "DXSpider V$version, build $build (git: $gitversion) ended");
367 dbg("bye bye everyone - bye bye");
371 $dbh->finish if $dbh;
376 # the reaper of children
380 while (($cpid = waitpid(-1, WNOHANG)) > 0) {
381 dbg("cpid: $cpid") if isdbg('reap');
382 # Msg->pid_gone($cpid);
383 $zombies-- if $zombies > 0;
385 dbg("cpid: $cpid") if isdbg('reap');
388 # this is where the input queue is dealt with and things are dispatched off to other parts of
393 my $t = $systime - $starttime;
394 my $days = int $t / 86400;
396 my $hours = int $t / 3600;
398 my $mins = int $t / 60;
399 return sprintf "%d %02d:%02d", $days, $hours, $mins;
404 AGWMsg::init(\&new_channel);
411 #############################################################
413 # The start of the main line of code
415 #############################################################
417 $starttime = $systime = time;
418 $systime_days = int ($systime / 86400);
419 $systime_daystart = $systime_days * 86400;
420 $lang = 'en' unless $lang;
422 unless ($DB::VERSION) {
423 $SIG{INT} = $SIG{TERM} = \&cease;
426 # open the debug file, set various FHs to be unbuffered
427 dbginit($broadcast_debug ? \&DXCommandmode::broadcast_debug : undef);
431 STDOUT->autoflush(1);
434 # try to load the database
435 if (DXSql::init($dsn)) {
436 $dbh = DXSql->new($dsn);
437 $dbh = $dbh->connect($dsn, $dbuser, $dbpass) if $dbh;
440 # try to load Encode and Git
443 my $w = $SIG{__DIE__};
444 $SIG{__DIE__} = 'IGNORE';
445 eval { require Encode; };
450 eval { require Git; };
454 # determine the real version number
455 my $repo = Git->repository(Directory => "$root/.git");
457 my $desc = $repo->command_oneline(['describe', '--long'], STDERR => 0);
459 my ($v, $s, $b, $g) = $desc =~ /^([\d.]+)(?:\.(\d+))?-(\d+)-g([0-9a-f]+)/;
462 $gitversion = "$g\[r]";
469 # try to load XML::Simple
473 my ($year) = (gmtime)[5];
475 LogDbg('cluster', "DXSpider V$version, build $build (git: $gitversion) started");
476 dbg("Copyright (c) 1998-$year Dirk Koopman G1TLH");
479 dbg("loading prefixes ...");
481 my $r = Prefix::init();
485 dbg("loading band data ...");
488 # initialise User file system
489 dbg("loading user file system ...");
492 # look for the sysop and the alias user and complain if they aren't there
494 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;
495 my $ref = DXUser::get($mycall);
496 die "$mycall missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
497 my $oldsort = $ref->sort;
498 if ($oldsort ne 'S') {
500 dbg "Resetting node type from $oldsort -> DXSpider ('S')";
502 $ref = DXUser::get($myalias);
503 die "$myalias missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
504 $oldsort = $ref->sort;
505 if ($oldsort ne 'U') {
507 dbg "Resetting sysop user type from $oldsort -> User ('U')";
511 # start listening for incoming messages/connects
512 dbg("starting listeners ...");
513 my $conn = IntMsg->new_server($clusteraddr, $clusterport, \&login);
514 $conn->conns("Server $clusteraddr/$clusterport using IntMsg");
515 push @listeners, $conn;
516 dbg("Internal port: $clusteraddr $clusterport using IntMsg");
517 foreach my $l (@main::listen) {
519 my $pkg = $l->[2] || 'ExtMsg';
520 my $login = $l->[3] || 'login';
522 $conn = $pkg->new_server($l->[0], $l->[1], \&{"${pkg}::${login}"});
523 $conn->conns("Server $l->[0]/$l->[1] using ${pkg}::${login}");
524 push @listeners, $conn;
525 dbg("External Port: $l->[0] $l->[1] using ${pkg}::${login}");
528 dbg("AGW Listener") if $AGWMsg::enable;
531 dbg("BPQ Listener") if $BPQMsg::enable;
532 BPQMsg::init(\&new_channel);
534 dbg("UDP Listener") if $UDPMsg::enable;
535 UDPMsg::init(\&new_channel);
538 dbg("load badwords: " . (BadWords::load or "Ok"));
541 unless ($DB::VERSION) {
542 $SIG{INT} = $SIG{TERM} = sub { $ending = 10; };
546 $SIG{HUP} = 'IGNORE';
547 $SIG{CHLD} = sub { $zombies++ };
549 $SIG{PIPE} = sub { dbg("Broken PIPE signal received"); };
550 $SIG{IO} = sub { dbg("SIGIO received"); };
551 $SIG{WINCH} = $SIG{STOP} = $SIG{CONT} = 'IGNORE';
552 $SIG{KILL} = 'DEFAULT'; # as if it matters....
554 # catch the rest with a hopeful message
557 # dbg("Catching SIG $_") if isdbg('chan');
558 $SIG{$_} = sub { my $sig = shift; DXDebug::confess("Caught signal $sig"); };
564 dbg("Starting Dupe system");
567 # read in system messages
568 dbg("Read in Messages");
571 # read in command aliases
572 dbg("Read in Aliases");
575 # initialise the Geomagnetic data engine
581 # initial the Spot stuff
582 dbg("Starting DX Spot system");
585 # initialise the protocol engine
586 dbg("Start Protocol Engines ...");
589 # put in a DXCluster node for us here so we can add users and take them away
590 $routeroot = Route::Node->new($mycall, $version*100+5300, Route::here($main::me->here)|Route::conf($main::me->conf));
591 $routeroot->do_pc9x(1);
592 $routeroot->via_pc92(1);
594 # make sure that there is a routing OUTPUT node default file
595 #unless (Filter::read_in('route', 'node_default', 0)) {
596 # my $dxcc = $main::me->dxcc;
597 # $Route::filterdef->cmd($main::me, 'route', 'accept', "node_default call $mycall" );
600 # read in any existing message headers and clean out old crap
601 dbg("reading existing message headers ...");
605 # read in any cron jobs
606 dbg("reading cron jobs ...");
609 # read in database desriptors
610 dbg("reading database descriptors ...");
613 # starting local stuff
614 dbg("doing local initialisation ...");
616 if (defined &Local::init) {
620 dbg("Local::init error $@") if $@;
624 # this, such as it is, is the main loop!
625 dbg("orft we jolly well go ...");
626 my $script = new Script "startup";
627 $script->run($main::me) if $script;
629 #open(DB::OUT, "|tee /tmp/aa");
632 our $io_disconnected;
637 DXCommandmode::process(); # process ongoing command mode stuff
638 DXProt::process(); # process ongoing ak1a pcxx stuff
640 if (defined &Local::process) {
642 Local::process(); # do any localised processing
644 dbg("Local::process error $@") if $@;
650 dbg("DXSpider Ending $ending");
652 unless ($io_disconnected++) {
655 foreach $dxchan (DXChannel::get_all_users) {
660 foreach $dxchan (DXChannel::get_all_nodes) {
661 next if $dxchan == $main::me;
662 $dxchan->disconnect(2);
664 $main::me->disconnect;
667 Mojo::IOLoop->stop if --$ending <= 0;
677 my $days = int ($systime / 86400);
678 if ($systime_days != $days) {
679 $systime_days = $days;
680 $systime_daystart = $days * 86400;
682 IsoTime::update($systime);
683 DXCron::process(); # do cron jobs
685 DXConnect::process();
690 DXCron::process(); # do cron jobs
691 IsoTime::update($systime);
692 DXConnect::process();
728 dbg("Before Web::start_node");
730 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
732 dbg("After Web::start_node");
737 my $main_loop = Mojo::IOLoop->recurring($idle_interval => \&idle_loop);
738 my $log_flush_loop = Mojo::IOLoop->recurring($log_flush_interval => \&DXLog::flushall);
739 my $cpusecs_loop = Mojo::IOLoop->recurring(5 => sub {my @t = times; $clssecs = $t[0]+$t[1]; $cldsecs = $t[2]+$t[3]});
740 my $persec = Mojo::IOLoop->recurring(1 => \&per_sec);
741 my $per10sec = Mojo::IOLoop->recurring(10 => \&per_10_sec);
742 my $permin = Mojo::IOLoop->recurring(60 => \&per_minute);
743 my $per10min = Mojo::IOLoop->recurring(600 => \&per_10_minute);
744 my $perhour = Mojo::IOLoop->recurring(3600 => \&per_hour);
745 my $perday = Mojo::IOLoop->recurring(86400 => \&per_day);