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 $build (git: $gitbranch/$gitversion) using perl $^V on $^O 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 #############################################################
372 $starttime = $systime = time;
373 $systime_days = int ($systime / 86400);
374 $systime_daystart = $systime_days * 86400;
375 $lang = 'en' unless $lang;
377 unless ($DB::VERSION) {
378 $SIG{INT} = $SIG{TERM} = \&cease;
381 # open the debug file, set various FHs to be unbuffered
382 dbginit(\&DXCommandmode::broadcast_debug);
386 STDOUT->autoflush(1);
388 # try to load the database
389 if (DXSql::init($dsn)) {
390 $dbh = DXSql->new($dsn);
391 $dbh = $dbh->connect($dsn, $dbuser, $dbpass) if $dbh;
394 # try to load Encode and Git
397 my $w = $SIG{__DIE__};
398 $SIG{__DIE__} = 'IGNORE';
399 eval { require Encode; };
406 $gitversion = 'none';
408 # determine the real Git build number and branch
410 eval {$desc = `git --git-dir=$root/.git describe --long`};
412 my ($v, $s, $b, $g) = $desc =~ /^([\d\.]+)(?:\.(\d+))?-(\d+)-g([0-9a-f]+)/;
414 $subversion = $s || 0;
416 $gitversion = "$g\[r]";
421 eval {@branch = `git --git-dir=$root/.git branch`};
424 my ($star, $b) = split /\s+/;
436 # try to load XML::Simple
440 my ($year) = (gmtime)[5];
442 LogDbg('cluster', "DXSpider v$version build $build (git: $gitbranch/$gitversion) using perl $^V on $^O started");
443 dbg("Copyright (c) 1998-$year Dirk Koopman G1TLH");
446 dbg("loading prefixes ...");
448 my $r = Prefix::init();
452 dbg("loading band data ...");
455 # initialise User file system
456 dbg("loading user file system ...");
457 DXUser->init($userfn, 1);
460 # look for the sysop and the alias user and complain if they aren't there
462 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;
463 my $ref = DXUser::get($mycall);
464 die "$mycall missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
465 my $oldsort = $ref->sort;
466 if ($oldsort ne 'S') {
468 dbg "Resetting node type from $oldsort -> DXSpider ('S')";
470 $ref = DXUser::get($myalias);
471 die "$myalias missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
472 $oldsort = $ref->sort;
473 if ($oldsort ne 'U') {
475 dbg "Resetting sysop user type from $oldsort -> User ('U')";
479 # start listening for incoming messages/connects
480 dbg("starting listeners ...");
481 my $conn = IntMsg->new_server($clusteraddr, $clusterport, \&login);
482 $conn->conns("Server $clusteraddr/$clusterport using IntMsg");
483 push @listeners, $conn;
484 dbg("Internal port: $clusteraddr $clusterport using IntMsg");
485 foreach my $l (@main::listen) {
487 my $pkg = $l->[2] || 'ExtMsg';
488 my $login = $l->[3] || 'login';
490 $conn = $pkg->new_server($l->[0], $l->[1], \&{"${pkg}::${login}"});
491 $conn->conns("Server $l->[0]/$l->[1] using ${pkg}::${login}");
492 push @listeners, $conn;
493 dbg("External Port: $l->[0] $l->[1] using ${pkg}::${login}");
496 dbg("AGW Listener") if $AGWMsg::enable;
499 dbg("BPQ Listener") if $BPQMsg::enable;
500 BPQMsg::init(\&new_channel);
502 dbg("UDP Listener") if $UDPMsg::enable;
503 UDPMsg::init(\&new_channel);
506 dbg("load badwords: " . (BadWords::load or "Ok"));
509 unless ($DB::VERSION) {
510 $SIG{INT} = $SIG{TERM} = sub { $decease = 1 };
514 $SIG{HUP} = 'IGNORE';
515 $SIG{CHLD} = sub { $zombies++ };
517 $SIG{PIPE} = sub { dbg("Broken PIPE signal received"); };
518 $SIG{IO} = sub { dbg("SIGIO received"); };
519 $SIG{WINCH} = $SIG{STOP} = $SIG{CONT} = 'IGNORE';
520 $SIG{KILL} = 'DEFAULT'; # as if it matters....
522 # catch the rest with a hopeful message
525 # dbg("Catching SIG $_") if isdbg('chan');
526 $SIG{$_} = sub { my $sig = shift; DXDebug::confess("Caught signal $sig"); };
532 dbg("Starting Dupe system");
535 # read in system messages
536 dbg("Read in Messages");
539 # read in command aliases
540 dbg("Read in Aliases");
543 # initialise the Geomagnetic data engine
549 # initial the Spot stuff
550 dbg("Starting DX Spot system");
553 # initialise the protocol engine
554 dbg("Start Protocol Engines ...");
557 # put in a DXCluster node for us here so we can add users and take them away
558 $routeroot = Route::Node->new($mycall, $version*100+5300, Route::here($main::me->here)|Route::conf($main::me->conf));
559 $routeroot->do_pc9x(1);
560 $routeroot->via_pc92(1);
562 # make sure that there is a routing OUTPUT node default file
563 #unless (Filter::read_in('route', 'node_default', 0)) {
564 # my $dxcc = $main::me->dxcc;
565 # $Route::filterdef->cmd($main::me, 'route', 'accept', "node_default call $mycall" );
568 # read in any existing message headers and clean out old crap
569 dbg("reading existing message headers ...");
573 # read in any cron jobs
574 dbg("reading cron jobs ...");
577 # read in database desriptors
578 dbg("reading database descriptors ...");
581 # starting local stuff
582 dbg("doing local initialisation ...");
584 if (defined &Local::init) {
588 dbg("Local::init error $@") if $@;
592 # this, such as it is, is the main loop!
593 dbg("orft we jolly well go ...");
594 my $script = new Script "startup";
595 $script->run($main::me) if $script;
597 #open(DB::OUT, "|tee /tmp/aa");
602 Msg->event_loop(10, 0.010);
605 DXChannel::process();
609 # do timed stuff, ongoing processing happens one a second
610 if ($timenow != $systime) {
613 my $days = int ($systime / 86400);
614 if ($systime_days != $days) {
615 $systime_days = $days;
616 $systime_daystart = $days * 86400;
618 IsoTime::update($systime);
619 DXCron::process(); # do cron jobs
620 DXCommandmode::process(); # process ongoing command mode stuff
622 DXProt::process(); # process ongoing ak1a pcxx stuff
623 DXConnect::process();
633 if (defined &Local::process) {
635 Local::process(); # do any localised processing
637 dbg("Local::process error $@") if $@;
641 last if --$decease <= 0;