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";
138 use vars qw(@inqueue $systime $starttime $lockfn @outstanding_connects
139 $zombies $root @listeners $lang $myalias @debug $userfn
140 $mycall $decease $is_win $routeroot $me $reqreg $bumpexisting
141 $allowdxby $dbh $dsn $dbuser $dbpass $do_xml $systime_days $systime_daystart
142 $can_encode $maxconnect_user $maxconnect_node
145 @inqueue = (); # the main input queue, an array of hashes
146 $systime = 0; # the time now (in seconds)
147 $starttime = 0; # the starting time of the cluster
148 @outstanding_connects = (); # list of outstanding connects
149 @listeners = (); # list of listeners
150 $reqreg = 0; # 1 = registration required, 2 = deregister people
151 $bumpexisting = 1; # 1 = allow new connection to disconnect old, 0 - don't allow it
152 $allowdxby = 0; # 1 = allow "dx by <othercall>", 0 - don't allow it
153 $maxconnect_user = 3; # the maximum no of concurrent connections a user can have at a time
154 $maxconnect_node = 0; # Ditto but for nodes. In either case if a new incoming connection
155 # takes the no of references in the routing table above these numbers
156 # then the connection is refused. This only affects INCOMING connections.
158 # send a message to call on conn and disconnect
161 my ($conn, $call, $mess) = @_;
163 $conn->disable_read(1);
164 dbg("-> D $call $mess\n") if isdbg('chan');
165 $conn->send_now("D$call|$mess");
173 $dxchan->{conn}->set_error(undef) if exists $dxchan->{conn};
174 $dxchan->disconnect(1);
177 # handle incoming messages
180 my ($conn, $msg) = @_;
181 my ($sort, $call, $line) = DXChannel::decode_input(0, $msg);
182 return unless defined $sort;
184 unless (is_callsign($call)) {
185 already_conn($conn, $call, DXM::msg($lang, "illcall", $call));
189 # set up the basic channel info
190 # is there one already connected to me - locally?
191 my $user = DXUser::get_current($call);
192 my $dxchan = DXChannel::get($call);
194 if ($user && $user->is_node) {
195 already_conn($conn, $call, DXM::msg($lang, 'concluster', $call, $main::mycall));
199 my $ip = $conn->peerhost || 'unknown';
200 $dxchan->send_now('D', DXM::msg($lang, 'conbump', $call, $ip));
201 LogDbg('DXCommand', "$call bumped off by $ip, disconnected");
204 already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
209 # (fairly) politely disconnect people that are connected to too many other places at once
210 my $r = Route::get($call);
211 if ($conn->{sort} && $conn->{sort} =~ /^I/ && $r && $user) {
213 my $m = $r->isa('Route::Node') ? $maxconnect_node : $maxconnect_user;
214 my $c = $user->maxconnect;
216 $v = defined $c ? $c : $m;
217 if ($v && @n >= $v) {
218 my $nodes = join ',', @n;
219 LogDbg('DXCommand', "$call has too many connections ($v) at $nodes - disconnected");
220 already_conn($conn, $call, DXM::msg($lang, 'contomany', $call, $v, $nodes));
226 my $basecall = $call;
227 $basecall =~ s/-\d+$//;
228 my $baseuser = DXUser::get_current($basecall);
229 my $lock = $user->lockout if $user;
230 if ($baseuser && $baseuser->lockout || $lock) {
231 if (!$user || !defined $lock || $lock) {
232 my $host = $conn->peerhost || "unknown";
233 LogDbg('DXCommand', "$call on $host is locked out, disconnected");
240 $user->{lang} = $main::lang if !$user->{lang}; # to autoupdate old systems
242 $user = DXUser->new($call);
246 if ($user->is_node) {
247 $dxchan = DXProt->new($call, $conn, $user);
248 } elsif ($user->is_user) {
249 $dxchan = DXCommandmode->new($call, $conn, $user);
250 # } elsif ($user->is_bbs) { # there is no support so
251 # $dxchan = BBS->new($call, $conn, $user); # don't allow it!!!
253 die "Invalid sort of user on $call = $sort";
256 # check that the conn has a callsign
257 $conn->conns($call) if $conn->isa('IntMsg');
260 $conn->set_error(sub {error_handler($dxchan)});
261 $conn->set_rproc(sub {my ($conn,$msg) = @_; $dxchan->rec($msg);});
268 return \&new_channel;
271 # cease running this program, close down all the connections nicely
277 $SIG{'TERM'} = 'IGNORE';
278 $SIG{'INT'} = 'IGNORE';
283 if (defined &Local::finish) {
285 Local::finish(); # end local processing
287 dbg("Local::finish error $@") if $@;
291 foreach $dxchan (DXChannel::get_all_nodes) {
292 $dxchan->disconnect(2) unless $dxchan == $main::me;
294 Msg->event_loop(100, 0.01);
297 foreach $dxchan (DXChannel::get_all_users) {
305 # disconnect UDP customers
308 # end everything else
309 Msg->event_loop(100, 0.01);
313 # close all databases
316 # close all listeners
317 foreach my $l (@listeners) {
321 LogDbg('cluster', "DXSpider V$version, build $subversion.$build (git: $gitversion) ended");
325 $dbh->finish if $dbh;
328 # $SIG{__WARN__} = $SIG{__DIE__} = sub {my $a = shift; cluck($a); };
332 # the reaper of children
336 while (($cpid = waitpid(-1, WNOHANG)) > 0) {
337 dbg("cpid: $cpid") if isdbg('reap');
338 # Msg->pid_gone($cpid);
339 $zombies-- if $zombies > 0;
341 dbg("cpid: $cpid") if isdbg('reap');
344 # this is where the input queue is dealt with and things are dispatched off to other parts of
349 my $t = $systime - $starttime;
350 my $days = int $t / 86400;
352 my $hours = int $t / 3600;
354 my $mins = int $t / 60;
355 return sprintf "%d %02d:%02d", $days, $hours, $mins;
360 AGWMsg::init(\&new_channel);
363 #############################################################
365 # The start of the main line of code
367 #############################################################
369 $starttime = $systime = time;
370 $systime_days = int ($systime / 86400);
371 $systime_daystart = $systime_days * 86400;
372 $lang = 'en' unless $lang;
374 unless ($DB::VERSION) {
375 $SIG{INT} = $SIG{TERM} = \&cease;
378 # open the debug file, set various FHs to be unbuffered
379 dbginit(\&DXCommandmode::broadcast_debug);
383 STDOUT->autoflush(1);
385 # try to load the database
386 if (DXSql::init($dsn)) {
387 $dbh = DXSql->new($dsn);
388 $dbh = $dbh->connect($dsn, $dbuser, $dbpass) if $dbh;
391 # try to load Encode and Git
394 my $w = $SIG{__DIE__};
395 $SIG{__DIE__} = 'IGNORE';
396 eval { require Encode; };
401 eval { require Git; };
405 # determine the real version number
406 my $repo = Git->repository(Directory => "$root/.git");
408 my $desc = $repo->command_oneline(['describe'], STDERR => 0);
410 my ($v, $s, $b, $g) = $desc =~ /^([\d.]+)(?:\.(\d+))?-(\d+)-g([0-9a-f]+)/;
412 $subversion = $s || 0;
414 $gitversion = "$g\[r]";
421 # try to load XML::Simple
425 my ($year) = (gmtime)[5];
427 LogDbg('cluster', "DXSpider V$version, build $subversion.$build (git: $gitversion) started");
428 dbg("Copyright (c) 1998-$year Dirk Koopman G1TLH");
431 dbg("loading prefixes ...");
433 my $r = Prefix::init();
437 dbg("loading band data ...");
440 # initialise User file system
441 dbg("loading user file system ...");
442 DXUser->init($userfn, 1);
445 # look for the sysop and the alias user and complain if they aren't there
447 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;
448 my $ref = DXUser::get($mycall);
449 die "$mycall missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
450 my $oldsort = $ref->sort;
451 if ($oldsort ne 'S') {
453 dbg "Resetting node type from $oldsort -> DXSpider ('S')";
455 $ref = DXUser::get($myalias);
456 die "$myalias missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
457 $oldsort = $ref->sort;
458 if ($oldsort ne 'U') {
460 dbg "Resetting sysop user type from $oldsort -> User ('U')";
464 # start listening for incoming messages/connects
465 dbg("starting listeners ...");
466 my $conn = IntMsg->new_server($clusteraddr, $clusterport, \&login);
467 $conn->conns("Server $clusteraddr/$clusterport using IntMsg");
468 push @listeners, $conn;
469 dbg("Internal port: $clusteraddr $clusterport using IntMsg");
470 foreach my $l (@main::listen) {
472 my $pkg = $l->[2] || 'ExtMsg';
473 my $login = $l->[3] || 'login';
475 $conn = $pkg->new_server($l->[0], $l->[1], \&{"${pkg}::${login}"});
476 $conn->conns("Server $l->[0]/$l->[1] using ${pkg}::${login}");
477 push @listeners, $conn;
478 dbg("External Port: $l->[0] $l->[1] using ${pkg}::${login}");
481 dbg("AGW Listener") if $AGWMsg::enable;
484 dbg("BPQ Listener") if $BPQMsg::enable;
485 BPQMsg::init(\&new_channel);
487 dbg("UDP Listener") if $UDPMsg::enable;
488 UDPMsg::init(\&new_channel);
491 dbg("load badwords: " . (BadWords::load or "Ok"));
494 unless ($DB::VERSION) {
495 $SIG{INT} = $SIG{TERM} = sub { $decease = 1 };
499 $SIG{HUP} = 'IGNORE';
500 $SIG{CHLD} = sub { $zombies++ };
502 $SIG{PIPE} = sub { dbg("Broken PIPE signal received"); };
503 $SIG{IO} = sub { dbg("SIGIO received"); };
504 $SIG{WINCH} = $SIG{STOP} = $SIG{CONT} = 'IGNORE';
505 $SIG{KILL} = 'DEFAULT'; # as if it matters....
507 # catch the rest with a hopeful message
510 # dbg("Catching SIG $_") if isdbg('chan');
511 $SIG{$_} = sub { my $sig = shift; DXDebug::confess("Caught signal $sig"); };
517 dbg("Starting Dupe system");
520 # read in system messages
521 dbg("Read in Messages");
524 # read in command aliases
525 dbg("Read in Aliases");
528 # initialise the Geomagnetic data engine
534 # initial the Spot stuff
535 dbg("Starting DX Spot system");
538 # initialise the protocol engine
539 dbg("Start Protocol Engines ...");
542 # put in a DXCluster node for us here so we can add users and take them away
543 $routeroot = Route::Node->new($mycall, $version*100+5300, Route::here($main::me->here)|Route::conf($main::me->conf));
544 $routeroot->do_pc9x(1);
545 $routeroot->via_pc92(1);
547 # make sure that there is a routing OUTPUT node default file
548 #unless (Filter::read_in('route', 'node_default', 0)) {
549 # my $dxcc = $main::me->dxcc;
550 # $Route::filterdef->cmd($main::me, 'route', 'accept', "node_default call $mycall" );
553 # read in any existing message headers and clean out old crap
554 dbg("reading existing message headers ...");
558 # read in any cron jobs
559 dbg("reading cron jobs ...");
562 # read in database desriptors
563 dbg("reading database descriptors ...");
566 # starting local stuff
567 dbg("doing local initialisation ...");
569 if (defined &Local::init) {
573 dbg("Local::init error $@") if $@;
577 # this, such as it is, is the main loop!
578 dbg("orft we jolly well go ...");
579 my $script = new Script "startup";
580 $script->run($main::me) if $script;
582 #open(DB::OUT, "|tee /tmp/aa");
587 Msg->event_loop(10, 0.010);
590 DXChannel::process();
594 # do timed stuff, ongoing processing happens one a second
595 if ($timenow != $systime) {
598 my $days = int ($systime / 86400);
599 if ($systime_days != $days) {
600 $systime_days = $days;
601 $systime_daystart = $days * 86400;
603 IsoTime::update($systime);
604 DXCron::process(); # do cron jobs
605 DXCommandmode::process(); # process ongoing command mode stuff
607 DXProt::process(); # process ongoing ak1a pcxx stuff
608 DXConnect::process();
618 if (defined &Local::process) {
620 Local::process(); # do any localised processing
622 dbg("Local::process error $@") if $@;
626 last if --$decease <= 0;