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 $yes = 'Yes'; # visual representation of yes
22 $no = 'No'; # ditto for no
23 $user_interval = 11*60; # the interval between unsolicited prompts if no traffic
26 # make sure that modules are searched in the order local then perl
30 # root of directory tree for this system
32 $root = $ENV{'DXSPIDER_ROOT'} if $ENV{'DXSPIDER_ROOT'};
34 unshift @INC, "$root/perl"; # this IS the right way round!
35 unshift @INC, "$root/local";
37 # do some validation of the input
38 die "The directory $root doesn't exist, please RTFM" unless -d $root;
39 die "$root/local doesn't exist, please RTFM" unless -d "$root/local";
40 die "$root/local/DXVars.pm doesn't exist, please RTFM" unless -e "$root/local/DXVars.pm";
42 mkdir "$root/local_cmd", 0777 unless -d "$root/local_cmd";
45 $system = "$root/sys";
47 $localcmd = "$root/local_cmd";
48 $userfn = "$data/users";
50 # try to create and lock a lockfile (this isn't atomic but
52 $lockfn = "$root/local/cluster.lck"; # lock file name
54 open(CLLOCK, "$lockfn") or die "Can't open Lockfile ($lockfn) $!";
58 die "Lockfile ($lockfn) and process $pid exist, another cluster running?" if kill 0, $pid;
63 open(CLLOCK, ">$lockfn") or die "Can't open Lockfile ($lockfn) $!";
67 $is_win = ($^O =~ /^MS/ || $^O =~ /^OS-2/) ? 1 : 0; # is it Windows?
129 use POSIX ":sys_wait_h";
136 use vars qw(@inqueue $systime $starttime $lockfn @outstanding_connects
137 $zombies $root @listeners $lang $myalias @debug $userfn
138 $mycall $decease $is_win $routeroot $me $reqreg $bumpexisting
139 $allowdxby $dbh $dsn $dbuser $dbpass $do_xml $systime_days $systime_daystart
140 $can_encode $maxconnect_user $maxconnect_node
144 $clusteraddr //= '127.0.0.1'; # cluster tcp host address - used for things like console.pl
145 $clusterport //= 27754; # cluster tcp port
146 @inqueue = (); # the main input queue, an array of hashes
147 $systime = 0; # the time now (in seconds)
148 $starttime = 0; # the starting time of the cluster
149 @outstanding_connects = (); # list of outstanding connects
150 @listeners = (); # list of listeners
151 $reqreg = 0; # 1 = registration required, 2 = deregister people
152 $bumpexisting = 1; # 1 = allow new connection to disconnect old, 0 - don't allow it
153 $allowdxby = 0; # 1 = allow "dx by <othercall>", 0 - don't allow it
154 $maxconnect_user = 3; # the maximum no of concurrent connections a user can have at a time
155 $maxconnect_node = 0; # Ditto but for nodes. In either case if a new incoming connection
156 # takes the no of references in the routing table above these numbers
157 # then the connection is refused. This only affects INCOMING connections.
159 use vars qw($version $subversion $build $gitversion $gitbranch);
161 # send a message to call on conn and disconnect
164 my ($conn, $call, $mess) = @_;
166 $conn->disable_read(1);
167 dbg("-> D $call $mess\n") if isdbg('chan');
168 $conn->send_now("D$call|$mess");
176 $dxchan->{conn}->set_error(undef) if exists $dxchan->{conn};
177 $dxchan->disconnect(1);
180 # handle incoming messages
183 my ($conn, $msg) = @_;
184 my ($sort, $call, $line) = DXChannel::decode_input(0, $msg);
185 return unless defined $sort;
187 unless (is_callsign($call)) {
188 already_conn($conn, $call, DXM::msg($lang, "illcall", $call));
192 # set up the basic channel info
193 # is there one already connected to me - locally?
194 my $user = DXUser::get_current($call);
195 my $dxchan = DXChannel::get($call);
197 if ($user && $user->is_node) {
198 already_conn($conn, $call, DXM::msg($lang, 'concluster', $call, $main::mycall));
202 my $ip = $conn->peerhost || 'unknown';
203 $dxchan->send_now('D', DXM::msg($lang, 'conbump', $call, $ip));
204 LogDbg('DXCommand', "$call bumped off by $ip, disconnected");
207 already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
212 # (fairly) politely disconnect people that are connected to too many other places at once
213 my $r = Route::get($call);
214 if ($conn->{sort} && $conn->{sort} =~ /^I/ && $r && $user) {
216 my $m = $r->isa('Route::Node') ? $maxconnect_node : $maxconnect_user;
217 my $c = $user->maxconnect;
219 $v = defined $c ? $c : $m;
220 if ($v && @n >= $v) {
221 my $nodes = join ',', @n;
222 LogDbg('DXCommand', "$call has too many connections ($v) at $nodes - disconnected");
223 already_conn($conn, $call, DXM::msg($lang, 'contomany', $call, $v, $nodes));
229 my $basecall = $call;
230 $basecall =~ s/-\d+$//;
231 my $baseuser = DXUser::get_current($basecall);
232 my $lock = $user->lockout if $user;
233 if ($baseuser && $baseuser->lockout || $lock) {
234 if (!$user || !defined $lock || $lock) {
235 my $host = $conn->peerhost || "unknown";
236 LogDbg('DXCommand', "$call on $host is locked out, disconnected");
243 $user->{lang} = $main::lang if !$user->{lang}; # to autoupdate old systems
245 $user = DXUser->new($call);
249 if ($user->is_node) {
250 $dxchan = DXProt->new($call, $conn, $user);
251 } elsif ($user->is_user) {
252 $dxchan = DXCommandmode->new($call, $conn, $user);
253 # } elsif ($user->is_bbs) { # there is no support so
254 # $dxchan = BBS->new($call, $conn, $user); # don't allow it!!!
256 die "Invalid sort of user on $call = $sort";
259 # check that the conn has a callsign
260 $conn->conns($call) if $conn->isa('IntMsg');
263 $conn->set_error(sub {error_handler($dxchan)});
264 $conn->set_rproc(sub {my ($conn,$msg) = @_; $dxchan->rec($msg);});
271 return \&new_channel;
274 # cease running this program, close down all the connections nicely
280 $SIG{'TERM'} = 'IGNORE';
281 $SIG{'INT'} = 'IGNORE';
286 if (defined &Local::finish) {
288 Local::finish(); # end local processing
290 dbg("Local::finish error $@") if $@;
294 foreach $dxchan (DXChannel::get_all_nodes) {
295 $dxchan->disconnect(2) unless $dxchan == $main::me;
297 Msg->event_loop(100, 0.01);
300 foreach $dxchan (DXChannel::get_all_users) {
308 # disconnect UDP customers
311 # end everything else
312 Msg->event_loop(100, 0.01);
316 # close all databases
319 # close all listeners
320 foreach my $l (@listeners) {
324 LogDbg('cluster', "DXSpider v$version build $build (git: $gitbranch/$gitversion) using perl $^V on $^O ended");
328 $dbh->finish if $dbh;
331 # $SIG{__WARN__} = $SIG{__DIE__} = sub {my $a = shift; cluck($a); };
335 # the reaper of children
339 while (($cpid = waitpid(-1, WNOHANG)) > 0) {
340 dbg("cpid: $cpid") if isdbg('reap');
341 # Msg->pid_gone($cpid);
342 $zombies-- if $zombies > 0;
344 dbg("cpid: $cpid") if isdbg('reap');
347 # this is where the input queue is dealt with and things are dispatched off to other parts of
352 my $t = $systime - $starttime;
353 my $days = int $t / 86400;
355 my $hours = int $t / 3600;
357 my $mins = int $t / 60;
358 return sprintf "%d %02d:%02d", $days, $hours, $mins;
363 AGWMsg::init(\&new_channel);
366 #############################################################
368 # The start of the main line of code
370 #############################################################
374 $starttime = $systime = time;
375 $systime_days = int ($systime / 86400);
376 $systime_daystart = $systime_days * 86400;
377 $lang = 'en' unless $lang;
379 unless ($DB::VERSION) {
380 $SIG{INT} = $SIG{TERM} = \&cease;
383 # open the debug file, set various FHs to be unbuffered
384 dbginit(\&DXCommandmode::broadcast_debug);
388 STDOUT->autoflush(1);
390 # try to load the database
391 if (DXSql::init($dsn)) {
392 $dbh = DXSql->new($dsn);
393 $dbh = $dbh->connect($dsn, $dbuser, $dbpass) if $dbh;
396 # try to load Encode and Git
399 my $w = $SIG{__DIE__};
400 $SIG{__DIE__} = 'IGNORE';
401 eval { require Encode; };
408 $gitversion = 'none';
410 # determine the real Git build number and branch
412 eval {$desc = `git --git-dir=$root/.git describe --long`};
414 my ($v, $s, $b, $g) = $desc =~ /^([\d\.]+)(?:\.(\d+))?-(\d+)-g([0-9a-f]+)/;
416 $subversion = $s || 0;
418 $gitversion = "$g\[r]";
423 eval {@branch = `git --git-dir=$root/.git branch`};
426 my ($star, $b) = split /\s+/;
438 # try to load XML::Simple
442 my ($year) = (gmtime)[5];
444 LogDbg('cluster', "DXSpider v$version build $build (git: $gitbranch/$gitversion) using perl $^V on $^O started");
445 dbg("Copyright (c) 1998-$year Dirk Koopman G1TLH");
448 dbg("loading prefixes ...");
450 my $r = Prefix::init();
454 dbg("loading band data ...");
457 # initialise User file system
458 dbg("loading user file system ...");
459 DXUser->init($userfn, 1);
462 # look for the sysop and the alias user and complain if they aren't there
464 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;
465 my $ref = DXUser::get($mycall);
466 die "$mycall missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
467 my $oldsort = $ref->sort;
468 if ($oldsort ne 'S') {
470 dbg "Resetting node type from $oldsort -> DXSpider ('S')";
472 $ref = DXUser::get($myalias);
473 die "$myalias missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
474 $oldsort = $ref->sort;
475 if ($oldsort ne 'U') {
477 dbg "Resetting sysop user type from $oldsort -> User ('U')";
484 # start listening for incoming messages/connects
485 dbg("starting listeners ...");
486 my $conn = IntMsg->new_server($clusteraddr, $clusterport, \&login);
487 $conn->conns("Server $clusteraddr/$clusterport using IntMsg");
488 push @listeners, $conn;
489 dbg("Internal port: $clusteraddr $clusterport using IntMsg");
490 foreach my $l (@main::listen) {
492 my $pkg = $l->[2] || 'ExtMsg';
493 my $login = $l->[3] || 'login';
495 $conn = $pkg->new_server($l->[0], $l->[1], \&{"${pkg}::${login}"});
496 $conn->conns("Server $l->[0]/$l->[1] using ${pkg}::${login}");
497 push @listeners, $conn;
498 dbg("External Port: $l->[0] $l->[1] using ${pkg}::${login}");
501 dbg("AGW Listener") if $AGWMsg::enable;
504 dbg("BPQ Listener") if $BPQMsg::enable;
505 BPQMsg::init(\&new_channel);
507 dbg("UDP Listener") if $UDPMsg::enable;
508 UDPMsg::init(\&new_channel);
511 dbg("load badwords: " . (BadWords::load or "Ok"));
514 unless ($DB::VERSION) {
515 $SIG{INT} = $SIG{TERM} = sub { $decease = 1 };
519 $SIG{HUP} = 'IGNORE';
520 $SIG{CHLD} = sub { $zombies++ };
522 $SIG{PIPE} = sub { dbg("Broken PIPE signal received"); };
523 $SIG{IO} = sub { dbg("SIGIO received"); };
524 $SIG{WINCH} = $SIG{STOP} = $SIG{CONT} = 'IGNORE';
525 $SIG{KILL} = 'DEFAULT'; # as if it matters....
527 # catch the rest with a hopeful message
530 # dbg("Catching SIG $_") if isdbg('chan');
531 $SIG{$_} = sub { my $sig = shift; DXDebug::confess("Caught signal $sig"); };
537 dbg("Starting Dupe system");
540 # read in system messages
541 dbg("Read in Messages");
544 # read in command aliases
545 dbg("Read in Aliases");
548 # initialise the Geomagnetic data engine
554 # initial the Spot stuff
555 dbg("Starting DX Spot system");
558 # initialise the protocol engine
559 dbg("Start Protocol Engines ...");
562 # put in a DXCluster node for us here so we can add users and take them away
563 $routeroot = Route::Node->new($mycall, $version*100+5300, Route::here($main::me->here)|Route::conf($main::me->conf));
564 $routeroot->do_pc9x(1);
565 $routeroot->via_pc92(1);
567 # make sure that there is a routing OUTPUT node default file
568 #unless (Filter::read_in('route', 'node_default', 0)) {
569 # my $dxcc = $main::me->dxcc;
570 # $Route::filterdef->cmd($main::me, 'route', 'accept', "node_default call $mycall" );
573 # read in any existing message headers and clean out old crap
574 dbg("reading existing message headers ...");
578 # read in any cron jobs
579 dbg("reading cron jobs ...");
582 # read in database desriptors
583 dbg("reading database descriptors ...");
586 # starting local stuff
587 dbg("doing local initialisation ...");
589 if (defined &Local::init) {
593 dbg("Local::init error $@") if $@;
597 # this, such as it is, is the main loop!
598 dbg("orft we jolly well go ...");
599 my $script = new Script "startup";
600 $script->run($main::me) if $script;
602 #open(DB::OUT, "|tee /tmp/aa");
607 Msg->event_loop(10, 0.010);
610 DXChannel::process();
614 # do timed stuff, ongoing processing happens one a second
615 if ($timenow != $systime) {
618 my $days = int ($systime / 86400);
619 if ($systime_days != $days) {
620 $systime_days = $days;
621 $systime_daystart = $days * 86400;
623 IsoTime::update($systime);
624 DXCron::process(); # do cron jobs
625 DXCommandmode::process(); # process ongoing command mode stuff
627 DXProt::process(); # process ongoing ak1a pcxx stuff
628 DXConnect::process();
638 if (defined &Local::process) {
640 Local::process(); # do any localised processing
642 dbg("Local::process error $@") if $@;
646 last if --$decease <= 0;