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
17 # set default paths, these should be overwritten by DXVars.pm
18 use vars qw($data $system $cmd $localcmd $userfn $clusteraddr $clusterport $yes $no $user_interval $lang);
20 $lang = 'en'; # default language
21 $clusteraddr = '127.0.0.1'; # cluster tcp host address - used for things like console.pl
22 $clusterport = 27754; # cluster tcp port
23 $yes = 'Yes'; # visual representation of yes
24 $no = 'No'; # ditto for no
25 $user_interval = 11*60; # the interval between unsolicited prompts if no traffic
28 # make sure that modules are searched in the order local then perl
32 # root of directory tree for this system
34 $root = $ENV{'DXSPIDER_ROOT'} if $ENV{'DXSPIDER_ROOT'};
36 unshift @INC, "$root/perl"; # this IS the right way round!
37 unshift @INC, "$root/local";
39 # do some validation of the input
40 die "The directory $root doesn't exist, please RTFM" unless -d $root;
41 die "$root/local doesn't exist, please RTFM" unless -d "$root/local";
42 die "$root/local/DXVars.pm doesn't exist, please RTFM" unless -e "$root/local/DXVars.pm";
44 mkdir "$root/local_cmd", 0777 unless -d "$root/local_cmd";
47 $system = "$root/sys";
49 $localcmd = "$root/local_cmd";
50 $userfn = "$data/users";
52 # try to create and lock a lockfile (this isn't atomic but
54 $lockfn = "$root/local/cluster.lck"; # lock file name
56 open(CLLOCK, "$lockfn") or die "Can't open Lockfile ($lockfn) $!";
60 die "Lockfile ($lockfn) and process $pid exist, another cluster running?" if kill 0, $pid;
65 open(CLLOCK, ">$lockfn") or die "Can't open Lockfile ($lockfn) $!";
69 $is_win = ($^O =~ /^MS/ || $^O =~ /^OS-2/) ? 1 : 0; # is it Windows?
130 use POSIX ":sys_wait_h";
137 use vars qw(@inqueue $systime $starttime $lockfn @outstanding_connects
138 $zombies $root @listeners $lang $myalias @debug $userfn
139 $mycall $decease $is_win $routeroot $me $reqreg $bumpexisting
140 $allowdxby $dbh $dsn $dbuser $dbpass $do_xml $systime_days $systime_daystart
141 $can_encode $maxconnect_user $maxconnect_node
144 @inqueue = (); # the main input queue, an array of hashes
145 $systime = 0; # the time now (in seconds)
146 $starttime = 0; # the starting time of the cluster
147 @outstanding_connects = (); # list of outstanding connects
148 @listeners = (); # list of listeners
149 $reqreg = 0; # 1 = registration required, 2 = deregister people
150 $bumpexisting = 1; # 1 = allow new connection to disconnect old, 0 - don't allow it
151 $allowdxby = 0; # 1 = allow "dx by <othercall>", 0 - don't allow it
152 $maxconnect_user = 3; # the maximum no of concurrent connections a user can have at a time
153 $maxconnect_node = 0; # Ditto but for nodes. In either case if a new incoming connection
154 # takes the no of references in the routing table above these numbers
155 # then the connection is refused. This only affects INCOMING connections.
157 use vars qw($version $subversion $build $gitversion $gitbranch);
159 # send a message to call on conn and disconnect
162 my ($conn, $call, $mess) = @_;
164 $conn->disable_read(1);
165 dbg("-> D $call $mess\n") if isdbg('chan');
166 $conn->send_now("D$call|$mess");
174 $dxchan->{conn}->set_error(undef) if exists $dxchan->{conn};
175 $dxchan->disconnect(1);
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, 'concluster', $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 {error_handler($dxchan)});
262 $conn->set_rproc(sub {my ($conn,$msg) = @_; $dxchan->rec($msg);});
269 return \&new_channel;
272 # cease running this program, close down all the connections nicely
278 $SIG{'TERM'} = 'IGNORE';
279 $SIG{'INT'} = 'IGNORE';
284 if (defined &Local::finish) {
286 Local::finish(); # end local processing
288 dbg("Local::finish error $@") if $@;
292 foreach $dxchan (DXChannel::get_all_nodes) {
293 $dxchan->disconnect(2) unless $dxchan == $main::me;
295 Msg->event_loop(100, 0.01);
298 foreach $dxchan (DXChannel::get_all_users) {
306 # disconnect UDP customers
309 # end everything else
310 Msg->event_loop(100, 0.01);
314 # close all databases
317 # close all listeners
318 foreach my $l (@listeners) {
322 LogDbg('cluster', "DXSpider V$version, build $subversion.$build (git: $gitbranch/$gitversion) ended");
326 $dbh->finish if $dbh;
329 # $SIG{__WARN__} = $SIG{__DIE__} = sub {my $a = shift; cluck($a); };
333 # the reaper of children
337 while (($cpid = waitpid(-1, WNOHANG)) > 0) {
338 dbg("cpid: $cpid") if isdbg('reap');
339 # Msg->pid_gone($cpid);
340 $zombies-- if $zombies > 0;
342 dbg("cpid: $cpid") if isdbg('reap');
345 # this is where the input queue is dealt with and things are dispatched off to other parts of
350 my $t = $systime - $starttime;
351 my $days = int $t / 86400;
353 my $hours = int $t / 3600;
355 my $mins = int $t / 60;
356 return sprintf "%d %02d:%02d", $days, $hours, $mins;
361 AGWMsg::init(\&new_channel);
364 #############################################################
366 # The start of the main line of code
368 #############################################################
370 $starttime = $systime = time;
371 $systime_days = int ($systime / 86400);
372 $systime_daystart = $systime_days * 86400;
373 $lang = 'en' unless $lang;
375 unless ($DB::VERSION) {
376 $SIG{INT} = $SIG{TERM} = \&cease;
379 # open the debug file, set various FHs to be unbuffered
380 dbginit(\&DXCommandmode::broadcast_debug);
384 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
408 $gitversion = 'none';
409 my $repo = Git->repository(Directory => "$root/.git");
411 my $desc = $repo->command_oneline(['describe'], STDERR => 0);
413 my ($v, $s, $b, $g) = $desc =~ /^([\d.]+)(?:\.(\d+))?-(\d+)-g([0-9a-f]+)/;
415 $subversion = $s || 0;
417 $gitversion = "$g\[r]";
420 my @branch = $repo->command([qw{branch}], STDERR=>0);
422 my ($star, $b) = split /\s+/;
433 # try to load XML::Simple
437 my ($year) = (gmtime)[5];
439 LogDbg('cluster', "DXSpider V$version, build $subversion.$build (git: $gitbranch/$gitversion) started");
440 dbg("Copyright (c) 1998-$year Dirk Koopman G1TLH");
443 dbg("loading prefixes ...");
445 my $r = Prefix::init();
449 dbg("loading band data ...");
452 # initialise User file system
453 dbg("loading user file system ...");
454 DXUser->init($userfn, 1);
457 # look for the sysop and the alias user and complain if they aren't there
459 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;
460 my $ref = DXUser::get($mycall);
461 die "$mycall missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
462 my $oldsort = $ref->sort;
463 if ($oldsort ne 'S') {
465 dbg "Resetting node type from $oldsort -> DXSpider ('S')";
467 $ref = DXUser::get($myalias);
468 die "$myalias missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
469 $oldsort = $ref->sort;
470 if ($oldsort ne 'U') {
472 dbg "Resetting sysop user type from $oldsort -> User ('U')";
476 # start listening for incoming messages/connects
477 dbg("starting listeners ...");
478 my $conn = IntMsg->new_server($clusteraddr, $clusterport, \&login);
479 $conn->conns("Server $clusteraddr/$clusterport using IntMsg");
480 push @listeners, $conn;
481 dbg("Internal port: $clusteraddr $clusterport using IntMsg");
482 foreach my $l (@main::listen) {
484 my $pkg = $l->[2] || 'ExtMsg';
485 my $login = $l->[3] || 'login';
487 $conn = $pkg->new_server($l->[0], $l->[1], \&{"${pkg}::${login}"});
488 $conn->conns("Server $l->[0]/$l->[1] using ${pkg}::${login}");
489 push @listeners, $conn;
490 dbg("External Port: $l->[0] $l->[1] using ${pkg}::${login}");
493 dbg("AGW Listener") if $AGWMsg::enable;
496 dbg("BPQ Listener") if $BPQMsg::enable;
497 BPQMsg::init(\&new_channel);
499 dbg("UDP Listener") if $UDPMsg::enable;
500 UDPMsg::init(\&new_channel);
503 dbg("load badwords: " . (BadWords::load or "Ok"));
506 unless ($DB::VERSION) {
507 $SIG{INT} = $SIG{TERM} = sub { $decease = 1 };
511 $SIG{HUP} = 'IGNORE';
512 $SIG{CHLD} = sub { $zombies++ };
514 $SIG{PIPE} = sub { dbg("Broken PIPE signal received"); };
515 $SIG{IO} = sub { dbg("SIGIO received"); };
516 $SIG{WINCH} = $SIG{STOP} = $SIG{CONT} = 'IGNORE';
517 $SIG{KILL} = 'DEFAULT'; # as if it matters....
519 # catch the rest with a hopeful message
522 # dbg("Catching SIG $_") if isdbg('chan');
523 $SIG{$_} = sub { my $sig = shift; DXDebug::confess("Caught signal $sig"); };
529 dbg("Starting Dupe system");
532 # read in system messages
533 dbg("Read in Messages");
536 # read in command aliases
537 dbg("Read in Aliases");
540 # initialise the Geomagnetic data engine
546 # initial the Spot stuff
547 dbg("Starting DX Spot system");
550 # initialise the protocol engine
551 dbg("Start Protocol Engines ...");
554 # put in a DXCluster node for us here so we can add users and take them away
555 $routeroot = Route::Node->new($mycall, $version*100+5300, Route::here($main::me->here)|Route::conf($main::me->conf));
556 $routeroot->do_pc9x(1);
557 $routeroot->via_pc92(1);
559 # make sure that there is a routing OUTPUT node default file
560 #unless (Filter::read_in('route', 'node_default', 0)) {
561 # my $dxcc = $main::me->dxcc;
562 # $Route::filterdef->cmd($main::me, 'route', 'accept', "node_default call $mycall" );
565 # read in any existing message headers and clean out old crap
566 dbg("reading existing message headers ...");
570 # read in any cron jobs
571 dbg("reading cron jobs ...");
574 # read in database desriptors
575 dbg("reading database descriptors ...");
578 # starting local stuff
579 dbg("doing local initialisation ...");
581 if (defined &Local::init) {
585 dbg("Local::init error $@") if $@;
589 # this, such as it is, is the main loop!
590 dbg("orft we jolly well go ...");
591 my $script = new Script "startup";
592 $script->run($main::me) if $script;
594 #open(DB::OUT, "|tee /tmp/aa");
599 Msg->event_loop(10, 0.010);
602 DXChannel::process();
606 # do timed stuff, ongoing processing happens one a second
607 if ($timenow != $systime) {
610 my $days = int ($systime / 86400);
611 if ($systime_days != $days) {
612 $systime_days = $days;
613 $systime_daystart = $days * 86400;
615 IsoTime::update($systime);
616 DXCron::process(); # do cron jobs
617 DXCommandmode::process(); # process ongoing command mode stuff
619 DXProt::process(); # process ongoing ak1a pcxx stuff
620 DXConnect::process();
630 if (defined &Local::process) {
632 Local::process(); # do any localised processing
634 dbg("Local::process error $@") if $@;
638 last if --$decease <= 0;