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?
128 use POSIX ":sys_wait_h";
135 use vars qw(@inqueue $systime $starttime $lockfn @outstanding_connects
136 $zombies $root @listeners $lang $myalias @debug $userfn
137 $mycall $decease $is_win $routeroot $me $reqreg $bumpexisting
138 $allowdxby $dbh $dsn $dbuser $dbpass $do_xml $systime_days $systime_daystart
139 $can_encode $maxconnect_user $maxconnect_node
143 $clusteraddr //= '127.0.0.1'; # cluster tcp host address - used for things like console.pl
144 $clusterport //= 27754; # cluster tcp port
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 use vars qw($version $subversion $build $gitversion $gitbranch);
160 # send a message to call on conn and disconnect
163 my ($conn, $call, $mess) = @_;
165 $conn->disable_read(1);
166 dbg("-> D $call $mess\n") if isdbg('chan');
167 $conn->send_now("D$call|$mess");
175 $dxchan->{conn}->set_error(undef) if exists $dxchan->{conn};
176 $dxchan->disconnect(1);
179 # handle incoming messages
182 my ($conn, $msg) = @_;
183 my ($sort, $call, $line) = DXChannel::decode_input(0, $msg);
184 return unless defined $sort;
186 unless (is_callsign($call)) {
187 already_conn($conn, $call, DXM::msg($lang, "illcall", $call));
191 # set up the basic channel info
192 # is there one already connected to me - locally?
193 my $user = DXUser::get_current($call);
194 my $dxchan = DXChannel::get($call);
196 if ($user && $user->is_node) {
197 already_conn($conn, $call, DXM::msg($lang, 'concluster', $call, $main::mycall));
201 my $ip = $conn->peerhost || 'unknown';
202 $dxchan->send_now('D', DXM::msg($lang, 'conbump', $call, $ip));
203 LogDbg('DXCommand', "$call bumped off by $ip, disconnected");
206 already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
211 # (fairly) politely disconnect people that are connected to too many other places at once
212 my $r = Route::get($call);
213 if ($conn->{sort} && $conn->{sort} =~ /^I/ && $r && $user) {
215 my $m = $r->isa('Route::Node') ? $maxconnect_node : $maxconnect_user;
216 my $c = $user->maxconnect;
218 $v = defined $c ? $c : $m;
219 if ($v && @n >= $v) {
220 my $nodes = join ',', @n;
221 LogDbg('DXCommand', "$call has too many connections ($v) at $nodes - disconnected");
222 already_conn($conn, $call, DXM::msg($lang, 'contomany', $call, $v, $nodes));
228 my $basecall = $call;
229 $basecall =~ s/-\d+$//;
230 my $baseuser = DXUser::get_current($basecall);
231 my $lock = $user->lockout if $user;
232 if ($baseuser && $baseuser->lockout || $lock) {
233 if (!$user || !defined $lock || $lock) {
234 my $host = $conn->peerhost || "unknown";
235 LogDbg('DXCommand', "$call on $host is locked out, disconnected");
242 $user->{lang} = $main::lang if !$user->{lang}; # to autoupdate old systems
244 $user = DXUser->new($call);
248 if ($user->is_node) {
249 $dxchan = DXProt->new($call, $conn, $user);
250 } elsif ($user->is_user) {
251 $dxchan = DXCommandmode->new($call, $conn, $user);
252 # } elsif ($user->is_bbs) { # there is no support so
253 # $dxchan = BBS->new($call, $conn, $user); # don't allow it!!!
255 die "Invalid sort of user on $call = $sort";
258 # check that the conn has a callsign
259 $conn->conns($call) if $conn->isa('IntMsg');
262 $conn->set_error(sub {error_handler($dxchan)});
263 $conn->set_rproc(sub {my ($conn,$msg) = @_; $dxchan->rec($msg);});
270 return \&new_channel;
273 # cease running this program, close down all the connections nicely
279 $SIG{'TERM'} = 'IGNORE';
280 $SIG{'INT'} = 'IGNORE';
285 if (defined &Local::finish) {
287 Local::finish(); # end local processing
289 dbg("Local::finish error $@") if $@;
293 foreach $dxchan (DXChannel::get_all_nodes) {
294 $dxchan->disconnect(2) unless $dxchan == $main::me;
296 Msg->event_loop(100, 0.01);
299 foreach $dxchan (DXChannel::get_all_users) {
307 # disconnect UDP customers
310 # end everything else
311 Msg->event_loop(100, 0.01);
315 # close all databases
318 # close all listeners
319 foreach my $l (@listeners) {
323 LogDbg('cluster', "DXSpider v$version build $build (git: $gitbranch/$gitversion) using perl $^V on $^O ended");
327 $dbh->finish if $dbh;
330 # $SIG{__WARN__} = $SIG{__DIE__} = sub {my $a = shift; cluck($a); };
334 # the reaper of children
338 while (($cpid = waitpid(-1, WNOHANG)) > 0) {
339 dbg("cpid: $cpid") if isdbg('reap');
340 # Msg->pid_gone($cpid);
341 $zombies-- if $zombies > 0;
343 dbg("cpid: $cpid") if isdbg('reap');
346 # this is where the input queue is dealt with and things are dispatched off to other parts of
351 my $t = $systime - $starttime;
352 my $days = int $t / 86400;
354 my $hours = int $t / 3600;
356 my $mins = int $t / 60;
357 return sprintf "%d %02d:%02d", $days, $hours, $mins;
362 AGWMsg::init(\&new_channel);
365 #############################################################
367 # The start of the main line of code
369 #############################################################
373 $starttime = $systime = time;
374 $systime_days = int ($systime / 86400);
375 $systime_daystart = $systime_days * 86400;
376 $lang = 'en' unless $lang;
378 unless ($DB::VERSION) {
379 $SIG{INT} = $SIG{TERM} = \&cease;
382 # open the debug file, set various FHs to be unbuffered
383 dbginit(\&DXCommandmode::broadcast_debug);
387 STDOUT->autoflush(1);
389 # try to load the database
390 if (DXSql::init($dsn)) {
391 $dbh = DXSql->new($dsn);
392 $dbh = $dbh->connect($dsn, $dbuser, $dbpass) if $dbh;
395 # try to load Encode and Git
398 my $w = $SIG{__DIE__};
399 $SIG{__DIE__} = 'IGNORE';
400 eval { require Encode; };
407 $gitversion = 'none';
409 # determine the real Git build number and branch
411 eval {$desc = `git --git-dir=$root/.git describe --long`};
413 my ($v, $s, $b, $g) = $desc =~ /^([\d\.]+)(?:\.(\d+))?-(\d+)-g([0-9a-f]+)/;
415 $subversion = $s || 0;
417 $gitversion = "$g\[r]";
422 eval {@branch = `git --git-dir=$root/.git branch`};
425 my ($star, $b) = split /\s+/;
437 # try to load XML::Simple
441 my ($year) = (gmtime)[5];
443 LogDbg('cluster', "DXSpider v$version build $build (git: $gitbranch/$gitversion) using perl $^V on $^O started");
444 dbg("Copyright (c) 1998-$year Dirk Koopman G1TLH");
447 dbg("loading prefixes ...");
449 my $r = Prefix::init();
453 dbg("loading band data ...");
456 # initialise User file system
457 dbg("loading user file system ...");
458 DXUser->init($userfn, 1);
461 # look for the sysop and the alias user and complain if they aren't there
463 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;
464 my $ref = DXUser::get($mycall);
465 die "$mycall missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
466 my $oldsort = $ref->sort;
467 if ($oldsort ne 'S') {
469 dbg "Resetting node type from $oldsort -> DXSpider ('S')";
471 $ref = DXUser::get($myalias);
472 die "$myalias missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
473 $oldsort = $ref->sort;
474 if ($oldsort ne 'U') {
476 dbg "Resetting sysop user type from $oldsort -> User ('U')";
480 # start listening for incoming messages/connects
481 dbg("starting listeners ...");
482 my $conn = IntMsg->new_server($clusteraddr, $clusterport, \&login);
483 $conn->conns("Server $clusteraddr/$clusterport using IntMsg");
484 push @listeners, $conn;
485 dbg("Internal port: $clusteraddr $clusterport using IntMsg");
486 foreach my $l (@main::listen) {
488 my $pkg = $l->[2] || 'ExtMsg';
489 my $login = $l->[3] || 'login';
491 $conn = $pkg->new_server($l->[0], $l->[1], \&{"${pkg}::${login}"});
492 $conn->conns("Server $l->[0]/$l->[1] using ${pkg}::${login}");
493 push @listeners, $conn;
494 dbg("External Port: $l->[0] $l->[1] using ${pkg}::${login}");
497 dbg("AGW Listener") if $AGWMsg::enable;
500 dbg("BPQ Listener") if $BPQMsg::enable;
501 BPQMsg::init(\&new_channel);
503 dbg("UDP Listener") if $UDPMsg::enable;
504 UDPMsg::init(\&new_channel);
507 dbg("load badwords: " . (BadWords::load or "Ok"));
510 unless ($DB::VERSION) {
511 $SIG{INT} = $SIG{TERM} = sub { $decease = 1 };
515 $SIG{HUP} = 'IGNORE';
516 $SIG{CHLD} = sub { $zombies++ };
518 $SIG{PIPE} = sub { dbg("Broken PIPE signal received"); };
519 $SIG{IO} = sub { dbg("SIGIO received"); };
520 $SIG{WINCH} = $SIG{STOP} = $SIG{CONT} = 'IGNORE';
521 $SIG{KILL} = 'DEFAULT'; # as if it matters....
523 # catch the rest with a hopeful message
526 # dbg("Catching SIG $_") if isdbg('chan');
527 $SIG{$_} = sub { my $sig = shift; DXDebug::confess("Caught signal $sig"); };
533 dbg("Starting Dupe system");
536 # read in system messages
537 dbg("Read in Messages");
540 # read in command aliases
541 dbg("Read in Aliases");
544 # initialise the Geomagnetic data engine
550 # initial the Spot stuff
551 dbg("Starting DX Spot system");
554 # initialise the protocol engine
555 dbg("Start Protocol Engines ...");
558 # put in a DXCluster node for us here so we can add users and take them away
559 $routeroot = Route::Node->new($mycall, $version*100+5300, Route::here($main::me->here)|Route::conf($main::me->conf));
560 $routeroot->do_pc9x(1);
561 $routeroot->via_pc92(1);
563 # make sure that there is a routing OUTPUT node default file
564 #unless (Filter::read_in('route', 'node_default', 0)) {
565 # my $dxcc = $main::me->dxcc;
566 # $Route::filterdef->cmd($main::me, 'route', 'accept', "node_default call $mycall" );
569 # read in any existing message headers and clean out old crap
570 dbg("reading existing message headers ...");
574 # read in any cron jobs
575 dbg("reading cron jobs ...");
578 # read in database desriptors
579 dbg("reading database descriptors ...");
582 # starting local stuff
583 dbg("doing local initialisation ...");
585 if (defined &Local::init) {
589 dbg("Local::init error $@") if $@;
593 # this, such as it is, is the main loop!
594 dbg("orft we jolly well go ...");
595 my $script = new Script "startup";
596 $script->run($main::me) if $script;
598 #open(DB::OUT, "|tee /tmp/aa");
603 Msg->event_loop(10, 0.010);
606 DXChannel::process();
610 # do timed stuff, ongoing processing happens one a second
611 if ($timenow != $systime) {
614 my $days = int ($systime / 86400);
615 if ($systime_days != $days) {
616 $systime_days = $days;
617 $systime_daystart = $days * 86400;
619 IsoTime::update($systime);
620 DXCron::process(); # do cron jobs
621 DXCommandmode::process(); # process ongoing command mode stuff
623 DXProt::process(); # process ongoing ak1a pcxx stuff
624 DXConnect::process();
634 if (defined &Local::process) {
636 Local::process(); # do any localised processing
638 dbg("Local::process error $@") if $@;
642 last if --$decease <= 0;