staging commt for badword and badip
[spider.git] / perl / cluster.pl
1 #!/usr/bin/env perl
2 #
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.
5 #
6 # Hence the name of 'spider' (although it may become 'dxspider')
7 #
8 # Copyright (c) 1998 Dirk Koopman G1TLH
9 #
10 #
11 #
12
13 package main;
14
15 require 5.16.1;
16
17 use warnings;
18
19 use vars qw($root $is_win $systime $lockfn @inqueue $starttime $lockfn @outstanding_connects
20                         $zombies @listeners $lang $myalias @debug $userfn $clusteraddr
21                         $clusterport $mycall $decease $routeroot $me $reqreg $bumpexisting
22                         $allowdxby $dbh $dsn $dbuser $dbpass $do_xml $systime_days $systime_daystart
23                         $can_encode $maxconnect_user $maxconnect_node $idle_interval $log_flush_interval
24                         $broadcast_debug $yes $no $user_interval
25                    );
26
27 #$lang = 'en';                                  # default language
28 #$clusteraddr = '127.0.0.1';            # cluster tcp host address - used for things like console.pl
29 #$clusterport = 27754;                  # cluster tcp port
30 #$yes = 'Yes';                                  # visual representation of yes
31 #$no = 'No';                                            # ditto for no
32 #$user_interval = 11*60;                        # the interval between unsolicited prompts if no traffic
33
34 package main;
35
36 # set default paths, these should be overwritten by DXVars.pm
37 use vars qw($data $system $cmd $localcmd $userfn $clusteraddr $clusterport $yes $no $user_interval $lang $local_data);
38
39 $lang = 'en';                   # default language
40 $yes = 'Yes';                   # visual representation of yes
41 $no = 'No';                     # ditto for no
42 $user_interval = 11*60;         # the interval between unsolicited prompts if no traffic
43
44
45 # make sure that modules are searched in the order local then perl
46 BEGIN {
47         umask 002;
48         $SIG{'__WARN__'} = sub { warn $_[0] if $DOWARN };
49                         
50         # take into account any local::lib that might be present
51         eval {
52                 require local::lib;
53         };
54         unless ($@) {
55 #               import local::lib;
56                 import local::lib qw(/spider/perl5lib);
57         } 
58
59         # root of directory tree for this system
60         $root = "/spider";
61         $root = $ENV{'DXSPIDER_ROOT'} if $ENV{'DXSPIDER_ROOT'};
62
63         unshift @INC, "$root/perl5lib" unless grep {$_ eq "$root/perl5lib"} @INC;
64         unshift @INC, "$root/perl";     # this IS the right way round!
65         unshift @INC, "$root/local";
66
67         # do some validation of the input
68         die "The directory $root doesn't exist, please RTFM" unless -d $root;
69         die "$root/local doesn't exist, please RTFM" unless -d "$root/local";
70         die "$root/local/DXVars.pm doesn't exist, please RTFM" unless -e "$root/local/DXVars.pm";
71
72         # create some directories
73         mkdir "$root/local_cmd", 02774 unless -d "$root/local_cmd";
74
75         # locally stored data lives here
76         $local_data = "$root/local_data";
77         mkdir $local_data, 02774 unless -d $local_data;
78         $data = "$root/data";
79         $system = "$root/sys";
80         $cmd = "$root/cmd";
81         $localcmd = "$root/local_cmd";
82         $userfn = "$data/users";
83
84         # try to create and lock a lockfile (this isn't atomic but
85         # should do for now
86         $lockfn = "$root/local_data/cluster.lck";       # lock file name
87         if (-w $lockfn) {
88                 open(CLLOCK, "$lockfn") or die "Can't open Lockfile ($lockfn) $!";
89                 my $pid = <CLLOCK>;
90                 if ($pid) {
91                         chomp $pid;
92                         if (kill 0, $pid) {
93                                 warn "Lockfile ($lockfn) and process $pid exist, another cluster running?\n";
94                                 exit 1;
95                         }
96                 }
97                 unlink $lockfn;
98                 close CLLOCK;
99         }
100         open(CLLOCK, ">$lockfn") or die "Can't open Lockfile ($lockfn) $!";
101         print CLLOCK "$$\n";
102         close CLLOCK;
103
104         $is_win = ($^O =~ /^MS/ || $^O =~ /^OS-2/) ? 1 : 0; # is it Windows?
105         $systime = time;
106         
107 }
108
109
110 use DXVars;
111 use SysVar;
112
113 # order here is important - DXDebug snarfs Carp et al so that Mojo errors go into the debug log
114 use Mojolicious 7.26;
115 use Mojo::IOLoop;
116 $DOWARN = 1;
117
118 use DXDebug;
119 use Msg;
120 use IntMsg;
121 use Internet;
122 use Listeners;
123 use ExtMsg;
124 use AGWConnect;
125 use AGWMsg;
126 use DXLog;
127 use DXLogPrint;
128 use DXUtil;
129 use DXChannel;
130 use DXUser;
131 use DXM;
132 use DXCommandmode;
133 use DXProtVars;
134 use DXProtout;
135 use DXProt;
136 use DXMsg;
137 use DXCron;
138 use DXConnect;
139 use DXBearing;
140 use DXDb;
141 use DXHash;
142 use DXDupe;
143 use Script;
144 use Prefix;
145 use Spot;
146 use Bands;
147 use Keps;
148 use Minimuf;
149 use Sun;
150 use Geomag;
151 use CmdAlias;
152 use Filter;
153 use AnnTalk;
154 use BBS;
155 use WCY;
156 use BadWords;
157 use DXTimer;
158 use Route;
159 use Route::Node;
160 use Route::User;
161 use Editable;
162 use Mrtg;
163 use USDB;
164 use UDPMsg;
165 use QSL;
166 use DXXml;
167 use DXSql;
168 use IsoTime;
169 use BPQMsg;
170 use RBN;
171 use DXCIDR;
172
173 use Data::Dumper;
174 use IO::File;
175 use Fcntl ':flock';
176 use POSIX ":sys_wait_h";
177 use Web;
178
179 use strict;
180
181 use Local;
182
183 $lang //= 'en';                                 # default language
184 $clusteraddr //= '127.0.0.1';   # cluster tcp host address - used for things like console.pl
185 $clusterport //= 27754;                 # cluster tcp port
186 $yes //= 'Yes';                                 # visual representation of yes
187 $no //= 'No';                               # ditto for no
188 $user_interval //= 11*60;               # the interval between unsolicited prompts if no traffic
189
190 @inqueue = ();                                  # the main input queue, an array of hashes
191 $systime = 0;                                   # the time now (in seconds)
192 $starttime = 0;                 # the starting time of the cluster
193 @outstanding_connects = ();     # list of outstanding connects
194 @listeners = ();                                # list of listeners
195 $reqreg = 0;                                    # 1 = registration required, 2 = deregister people
196 $bumpexisting = 1;                              # 1 = allow new connection to disconnect old, 0 - don't allow it
197 our $allowmultiple = 0;                         # This is used in conjunction with $bumpexisting, in a rather weird way.
198 our $min_reconnection_rate = 5*60;              # minimum value of seconds between connections per user to allow co-existing users
199 our $max_ssid = 15;                                     # highest ssid to be searched for a spare one on multiple connections
200
201 # If $allowmultiple > 0 and the $reconnection_rate is some value of seconds
202 # based on the average connection time calculated from the $user->conntimel entries / frequency is
203 # less than $reconnection_rate then we assume that there is more than one device (probably HRD) trying
204 # to connect "at once". In which case we probe for a spare SSID for a user callsign to allow up to 
205 # $allowmultiple connections per callsign. 
206
207 $allowdxby = 0;                                 # 1 = allow "dx by <othercall>", 0 - don't allow it
208 $maxconnect_user = 3;                   # the maximum no of concurrent connections a user can have at a time
209 $maxconnect_node = 0;                   # Ditto but for nodes. In either case if a new incoming connection
210                                                                 # takes the no of references in the routing table above these numbers
211                                                                 # then the connection is refused. This only affects INCOMING connections.
212 $idle_interval = 0.500;         # the wait between invocations of the main idle loop processing.
213 $log_flush_interval = 2;                # interval to wait between log flushes
214
215 our $ending;                                    # signal that we are ending;
216 our $broadcast_debug;                   # allow broadcasting of debug info down "enhanced" user connections
217 our $clssecs;                                   # the amount of cpu time the DXSpider process have consumed
218 our $cldsecs;                                   # the amount of cpu time any child processes have consumed
219 our $allowslashcall;                    # Allow / in connecting callsigns (ie PA0/G1TLH, or even PA0/G1TLH/2) 
220
221
222 use vars qw($version $subversion $build $gitversion $gitbranch);
223
224 # send a message to call on conn and disconnect
225 sub already_conn
226 {
227         my ($conn, $call, $mess) = @_;
228
229         $conn->disable_read(1);
230         dbg("-> D $call $mess\n") if isdbg('chan');
231         $conn->send_now("D$call|$mess");
232         sleep(2);
233         $conn->disconnect;
234 }
235
236 # handle incoming messages
237 sub new_channel
238 {
239         my ($conn, $msg) = @_;
240         my ($sort, $call, $line) = DXChannel::decode_input(0, $msg);
241         return unless defined $sort;
242
243         my ($dxchan, $user);
244         
245         if (is_webcall($call) && $conn->isa('IntMsg')) {
246                 my $newcall = find_next_webcall();
247                 unless ($newcall) {
248                         already_conn($conn, $call, "Maximum no of web connected connects ($Web::maxssid) exceeded");
249                         return;
250                 }
251                 $call = normalise_call($newcall);
252                 
253                 $user = DXUser::get_current($call);
254                 unless ($user) {
255                         $user = DXUser->new($call);
256                         $user->sort('W');
257                         $user->wantbeep(0);
258                         $user->name('web');
259                         $user->qth('on the web');
260                         $user->homenode($main::mycall);
261                         $user->lat($main::mylatitude);
262                         $user->long($main::mylongitude);
263                         $user->qra($main::mylocator);
264                 }
265                 $user->startt($main::systime);  
266                 $conn->conns($call);
267                 $dxchan = Web->new($call, $conn, $user);
268                 $dxchan->enhanced(1);
269                 $dxchan->ve7cc(1);
270                 $msg =~ s/^A#WEB|/A$call|/;
271                 $conn->send_now("C$call");
272         } else {
273                 # "Normal" connections
274
275                 # normalise calls like G1TST-0/G1TST-00/G1TST-01 to G1TST and G1TST-1 respectively
276                 my $ncall = normalise_call($call);
277                 if ($call ne $ncall) {
278                         LogDbg('err', "new_channel login invalid $call converted to $ncall");
279                         $msg =~ s/$call/$ncall/;
280                         $call = $ncall;
281                 }
282                 # is it a valid callsign (in format)?
283                 unless (is_callsign($call)) {
284                         already_conn($conn, $call, DXM::msg($lang, "illcall", $call));
285                         return;
286                 }
287
288                 # is he locked out ?
289                 my $lock;
290                 $conn->conns($call);
291                 $user = DXUser::get_current($call);
292                 my $basecall = $call;
293                 $basecall =~ s/-\d+$//; # remember this for later multiple user processing, it's used for other stuff than checking lockout status
294                 if ($user) {
295                         # make sure we act on any locked status that the actual incoming call has.
296                         $lock = $user->lockout;
297                 } elsif ($basecall ne $call) {
298                         # if there isn't a SSID on the $call, then try the base
299                         my $luser = DXUser::get_current($basecall);
300                         $lock = $luser->lockout if $luser;
301                 }
302
303                 # now deal with the lock
304                 my $host = $conn->peerhost;
305                 if ($lock) {
306                         LogDbg('', "$call on $host is locked out, disconnected");
307                         $conn->disconnect;
308                         return;
309                 }
310
311                 # Is he from a badip?
312                 if (DXCIDR::find($host)) {
313                         LogDbg('', "$call on $host is from a badip $host, disconnected");
314                         $conn->disconnect;
315                         return;
316                 }
317
318                 # set up the basic channel info for "Normal" Users
319                 # is there one already connected to me - locally?
320
321                 $dxchan = DXChannel::get($call);
322                 my $newcall = $call;
323                 if ($dxchan) {
324                         if ($user && $user->is_node) {
325                                 already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
326                                 return;
327                         }
328                         if ($allowmultiple && $user->is_user) {
329                                 # determine whether we are a candidate, have we flip-flopped frequently enough?
330                                 my @lastconns = @{$user->connlist} if $user->connlist;
331                                 my $allow = 0;
332                                 if (@lastconns >= $DXUser::maxconnlist) {
333                                         $allow = $lastconns[-1]->[0] - $lastconns[0]->[0] < $min_reconnection_rate;
334                                 } 
335                                 # search for a spare ssid
336                         L1:     for (my $count = $call =~ /-\d+$/?0:1; $allow && $count < $allowmultiple; ) { # remember we have one call already
337                                         my $lastid = 1;
338                                         for (; $lastid < $max_ssid && $count < $allowmultiple; ++$lastid) {
339                                                 my $chan = DXChannel::get("$basecall-$lastid");
340                                                 if ($chan) {
341                                                         ++$count;
342                                                         next;
343                                                 }
344                                                 # we have a free call-ssid, save it
345                                                 $newcall = "$basecall-$lastid";
346                                                 last L1;
347                                         }
348                                 }
349                         }
350
351                         # handle "normal" (non-multiple) connections in the existing way
352                         if ($call eq $newcall) {
353                                 if ($bumpexisting) {
354                                         my $ip = $dxchan->hostname;
355                                         $dxchan->send_now('D', DXM::msg($lang, 'conbump', $call, $ip));
356                                         LogDbg('', "$call bumped off by $ip, disconnected");
357                                         $dxchan->disconnect;
358                                 } else {
359                                         already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
360                                         return;
361                                 }
362                         }
363
364                         # make sure that the conn has the (possibly) new callsign
365                         $conn->conns($newcall);
366                         $msg =~ s/$call/$newcall/;
367                 }
368
369
370                 # (fairly) politely disconnect people that are connected to too many other places at once
371                 my $r = Route::get($call);
372                 if ($conn->{sort} && $conn->{sort} =~ /^I/ && $r && $user) {
373                         my @n = $r->parents;
374                         my $m = $r->isa('Route::Node') ? $maxconnect_node : $maxconnect_user;
375                         my $c = $user->maxconnect;
376                         my $v;
377                         $v = defined $c ? $c : $m;
378                         if ($v && @n >= $v+$allowmultiple) {
379                                 my $nodes = join ',', @n;
380                                 LogDbg('', "$call has too many connections ($v) at $nodes - disconnected");
381                                 already_conn($conn, $call, DXM::msg($lang, 'contomany', $call, $v, $nodes));
382                                 return;
383                         }
384                 }
385                 
386                 if ($user) {
387                         $user->{lang} = $main::lang if !$user->{lang}; # to autoupdate old systems
388                 } else {
389                         $user = DXUser->new($call);
390                 }
391
392                 # create the channel
393                 # NOTE we are SHARING the same $user if $allowmultiple is > 1
394                 
395                 $user->startt($systime); # mark the start time of this connection
396                 if ($user->is_node) {
397                         $dxchan = DXProt->new($call, $conn, $user);     
398                 } elsif ($user->is_rbn) {
399                         $dxchan = RBN->new($newcall, $conn, $user);
400                 } elsif ($user->is_user) {
401                         $dxchan = DXCommandmode->new($newcall, $conn, $user);
402                 } else {
403                         die "Invalid sort of user on $call = $sort";
404                 }
405         }
406         
407
408         # set callbacks
409         $conn->set_error(sub {my $err = shift; LogDbg('', "Comms error '$err' received for call $dxchan->{call}"); $dxchan->disconnect(1);});
410         $conn->set_on_eof(sub {$dxchan->disconnect});
411         $conn->set_rproc(sub {my ($conn,$msg) = @_; $dxchan->rec($msg);});
412         if ($sort eq 'W') {
413                 $dxchan->enhanced(1);
414                 $dxchan->sort('W');
415         }
416         $dxchan->rec($msg);
417 }
418
419
420 sub login
421 {
422         return \&new_channel;
423 }
424
425 my $ceasing;
426
427 # cease running this program, close down all the connections nicely
428 sub cease
429 {
430         my $dxchan;
431
432         cluck("ceasing") if $ceasing; 
433         
434         return if $ceasing++;
435
436         dbg("DXSpider Ceasing");
437         
438         unless ($is_win) {
439                 $SIG{'TERM'} = 'IGNORE';
440                 $SIG{'INT'} = 'IGNORE';
441         }
442
443
444         if (defined &Local::finish) {
445                 eval {
446                         Local::finish();   # end local processing
447                 };
448                 dbg("Local::finish error $@") if $@;
449         }
450
451
452         # disconnect AGW
453         AGWMsg::finish();
454         BPQMsg::finish();
455
456         # disconnect UDP customers
457         UDPMsg::finish();
458
459         # end everything else
460         QSL::finish();
461         RBN::finish();
462         DXDupe::finish();
463
464         # close all databases
465         DXDb::closeall;
466
467         # close all listeners
468         foreach my $l (@listeners) {
469                 $l->close_server;
470         }
471
472         DXUser::finish();
473
474         LogDbg('cluster', "DXSpider v$version build $build (git: $gitbranch/$gitversion) using perl $^V on $^O ended");
475         dbg("bye bye everyone - bye bye");
476         dbgclose();
477         Logclose();
478
479         $dbh->finish if $dbh;
480
481         unlink $lockfn;
482 }
483
484 # the reaper of children
485 sub reap
486 {
487         my $cpid;
488         while (($cpid = waitpid(-1, WNOHANG)) > 0) {
489                 dbg("cpid: $cpid") if isdbg('reap');
490 #               Msg->pid_gone($cpid);
491                 $zombies-- if $zombies > 0;
492         }
493         dbg("cpid: $cpid") if isdbg('reap');
494 }
495
496 # this is where the input queue is dealt with and things are dispatched off to other parts of
497 # the cluster
498
499 sub uptime
500 {
501         my $t = $systime - $starttime;
502         my $days = int $t / 86400;
503         $t -= $days * 86400;
504         my $hours = int $t / 3600;
505         $t -= $hours * 3600;
506         my $mins = int $t / 60;
507         return sprintf "%d %02d:%02d", $days, $hours, $mins;
508 }
509
510 sub AGWrestart
511 {
512         AGWMsg::init(\&new_channel);
513 }
514
515
516 sub setup_start
517 {
518         #############################################################
519         #
520         # The start of the main line of code
521         #
522         #############################################################
523
524         chdir $root;
525         
526         $starttime = $systime = time;
527         $systime_days = int ($systime / 86400);
528         $systime_daystart = $systime_days * 86400;
529         $lang = 'en' unless $lang;
530
531         unless ($DB::VERSION) {
532                 $SIG{INT} = $SIG{TERM} = \&cease;
533         }
534
535         # open the debug file, set various FHs to be unbuffered
536         dbginit(undef, $broadcast_debug ? \&DXCommandmode::broadcast_debug : undef);
537         foreach (@debug) {
538                 dbgadd($_);
539         }
540         STDOUT->autoflush(1);
541
542         # log our path
543         dbg "Perl path: " . join(':', @INC);
544         
545         # try to load the database
546         if (DXSql::init($dsn)) {
547                 $dbh = DXSql->new($dsn);
548                 $dbh = $dbh->connect($dsn, $dbuser, $dbpass) if $dbh;
549         }
550
551         # try to load Encode and Git
552         {
553                 local $^W = 0;
554                 my $w = $SIG{__DIE__};
555                 $SIG{__DIE__} = 'IGNORE';
556                 eval { require Encode; };
557                 unless ($@) {
558                         import Encode;
559                         $can_encode = 1;
560                 }
561
562                 $gitbranch = 'none';
563                 $gitversion = 'none';
564                 
565                 # determine the real Git build number and branch
566                 my $desc;
567                 eval {$desc = `git --git-dir=$root/.git describe --long`};
568                 if (!$@ && $desc) {
569                         my ($v, $s, $b, $g) = $desc =~ /^([\d\.]+)(?:\.(\d+))?-(\d+)-g([0-9a-f]+)/;
570                         $version = $v;
571                         my $subversion = $s || 0; # not used elsewhere
572                         $build = $b || 0;
573                         $gitversion = "$g\[r]";
574                 }
575                 if (!$@) {
576                         my @branch;
577
578                         eval {@branch = `git --git-dir=$root/.git branch`};
579                         unless ($@) {
580                                 for (@branch) {
581                                         my ($star, $b) = split /\s+/;
582                                         if ($star eq '*') {
583                                                 $gitbranch = $b;
584                                                 last;
585                                         }
586                                 }
587                         }
588                 }
589
590                 $SIG{__DIE__} = $w;
591         }
592
593
594         # setup location of motd & issue
595         localdata_mv($motd);
596         $motd = localdata($motd);
597         localdata_mv("issue");
598         
599
600         # try to load XML::Simple
601         DXXml::init();
602
603         # banner
604         my ($year) = (gmtime)[5];
605         $year += 1900;
606         LogDbg('cluster', "DXSpider v$version build $build (git: $gitbranch/$gitversion) using perl $^V on $^O started");
607         LogDbg('cluster', "Copyright (c) 1998-$year Dirk Koopman G1TLH");
608         LogDbg('cluster', "Capabilities: ve7cc rbn");
609
610         # load Prefixes
611         dbg("loading prefixes ...");
612         dbg(USDB::init());
613         my $r = Prefix::init();
614         confess $r if $r;
615
616         # load band data
617         dbg("loading band data ...");
618         Bands::load();
619
620         # initialise User file system
621         dbg("loading user file system ...");
622         DXUser::init(4);                        # version 4 == json format
623
624         Filter::init();                         # doesn't do much, but has to be done
625
626         AnnTalk::init();                        # initialise announce cache
627         
628         
629
630         # look for the sysop and the alias user and complain if they aren't there
631         {
632                 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;
633                 my $ref = DXUser::get($mycall);
634                 die "$mycall missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
635                 my $oldsort = $ref->sort;
636                 if ($oldsort ne 'S') {
637                         $ref->sort('S');
638                         dbg("Resetting node type from $oldsort -> DXSpider ('S')");
639                 }
640                 $ref = DXUser::get($myalias);
641                 die "$myalias missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
642                 $oldsort = $ref->sort;
643                 if ($oldsort ne 'U') {
644                         $ref->sort('U');
645                         dbg("Resetting sysop user type from $oldsort -> User ('U')");
646                 }
647         }
648
649
650         # start listening for incoming messages/connects
651         dbg("starting listeners ...");
652         my $conn = IntMsg->new_server($clusteraddr, $clusterport, \&login);
653         $conn->conns("Server $clusteraddr/$clusterport using IntMsg");
654         push @listeners, $conn;
655         dbg("Internal port: $clusteraddr $clusterport using IntMsg");
656         foreach my $l (@main::listen) {
657                 no strict 'refs';
658                 my $pkg = $l->[2] || 'ExtMsg';
659                 my $login = $l->[3] || 'login';
660
661                 $conn = $pkg->new_server($l->[0], $l->[1], \&{"${pkg}::${login}"});
662                 $conn->conns("Server $l->[0]/$l->[1] using ${pkg}::${login}");
663                 push @listeners, $conn;
664                 dbg("External Port: $l->[0] $l->[1] using ${pkg}::${login}");
665         }
666
667
668         dbg("AGW Listener") if $AGWMsg::enable;
669         AGWrestart();
670
671         dbg("BPQ Listener") if $BPQMsg::enable;
672         BPQMsg::init(\&new_channel);
673
674         dbg("UDP Listener") if $UDPMsg::enable;
675         UDPMsg::init(\&new_channel);
676
677         # load bad words
678         BadWords::load();
679
680         # prime some signals
681         unless ($DB::VERSION) {
682                 $SIG{INT} = $SIG{TERM} = sub { $ending = 10; };
683         }
684
685         # get any bad IPs 
686         DXCIDR::init();
687
688         unless ($is_win) {
689                 $SIG{HUP} = 'IGNORE';
690                 $SIG{CHLD} = sub { $zombies++ };
691
692                 $SIG{PIPE} = sub {      dbg("Broken PIPE signal received"); };
693                 $SIG{IO} = sub {        dbg("SIGIO received"); };
694                 $SIG{WINCH} = $SIG{STOP} = $SIG{CONT} = 'IGNORE';
695                 $SIG{KILL} = 'DEFAULT'; # as if it matters....
696
697                 # catch the rest with a hopeful message
698                 for (keys %SIG) {
699                         if (!$SIG{$_}) {
700                                 #               dbg("Catching SIG $_") if isdbg('chan');
701                                 $SIG{$_} = sub { my $sig = shift;       DXDebug::confess("Caught signal $sig");  };
702                         }
703                 }
704         }
705
706         # start dupe system
707         dbg("Starting Dupe system");
708         DXDupe::init();
709
710         # read in system messages
711         dbg("Read in Messages");
712         DXM->init();
713
714         # read in command aliases
715         dbg("Read in Aliases");
716         CmdAlias->init();
717
718         # initialise the Geomagnetic data engine
719         dbg("Start WWV");
720         Geomag->init();
721         dbg("Start WCY");
722         WCY->init();
723
724         # initialise the protocol engine
725         dbg("Start Protocol Engines ...");
726         DXProt->init();
727
728         # read startup script
729         my $script = new Script "startup";
730         $script->run($main::me) if $script;
731
732         # put in a DXCluster node for us here so we can add users and take them away
733         $routeroot = Route::Node->new($mycall, $version*100+5300, Route::here($main::me->here)|Route::conf($main::me->conf));
734         $routeroot->do_pc9x(1);
735         $routeroot->via_pc92(1);
736
737         # make sure that there is a routing OUTPUT node default file
738         #unless (Filter::read_in('route', 'node_default', 0)) {
739         #       my $dxcc = $main::me->dxcc;
740         #       $Route::filterdef->cmd($main::me, 'route', 'accept', "node_default call $mycall" );
741         #}
742
743         # initial the Spot stuff
744         dbg("Starting DX Spot system");
745         Spot->init();
746
747         # read in any existing message headers and clean out old crap
748         dbg("reading existing message headers ...");
749         DXMsg->init();
750         DXMsg::clean_old();
751
752         # read in any cron jobs
753         dbg("reading cron jobs ...");
754         DXCron->init();
755
756         # read in database desriptors
757         dbg("reading database descriptors ...");
758         DXDb::load();
759
760         dbg("starting RBN ...");
761         RBN::init();
762
763         # starting local stuff
764         dbg("doing local initialisation ...");
765         QSL::init(1);
766         if (defined &Local::init) {
767                 eval {
768                         Local::init();
769                 };
770                 dbg("Local::init error $@") if $@;
771         }
772
773
774         # this, such as it is, is the main loop!
775         dbg("orft we jolly well go ...");
776
777         #open(DB::OUT, "|tee /tmp/aa");
778 }
779
780 our $io_disconnected;
781
782 sub idle_loop
783 {
784         BPQMsg::process();
785 #       DXCommandmode::process(); # process ongoing command mode stuff
786 #       DXProt::process();              # process ongoing ak1a pcxx stuff
787
788         if (defined &Local::process) {
789                 eval {
790                         Local::process();       # do any localised processing
791                 };
792                 dbg("Local::process error $@") if $@;
793         }
794
795         while ($ending) {
796                 my $dxchan;
797
798                 dbg("DXSpider Ending $ending");
799
800                 unless ($io_disconnected++) {
801
802                         # disconnect users
803                         foreach $dxchan (DXChannel::get_all_users) {
804                                 $dxchan->disconnect;
805                         }
806
807                         # disconnect nodes
808                         foreach $dxchan (DXChannel::get_all_nodes) {
809                                 next if $dxchan == $main::me;
810                                 $dxchan->disconnect(2);
811                         }
812                         $main::me->disconnect;
813                 }
814
815                 Mojo::IOLoop->stop_gracefully if --$ending <= 0;
816         }
817 }
818
819 sub per_sec
820 {
821         my $timenow = time;
822
823         reap() if $zombies;
824         $systime = $timenow;
825         my $days = int ($systime / 86400);
826         if ($systime_days != $days) {
827                 $systime_days = $days;
828                 $systime_daystart = $days * 86400;
829         }
830         IsoTime::update($systime);
831         DXCommandmode::process(); # process ongoing command mode stuff
832         DXProt::process();              # process ongoing ak1a pcxx stuff
833         DXXml::process();
834         DXConnect::process();
835         DXMsg::process();
836         DXDb::process();
837         DXUser::process();
838         DXDupe::process();
839         IsoTime::update($systime);
840         DXConnect::process();
841         DXUser::process();
842         AGWMsg::process();
843         DXCron::process();                      # do cron jobs
844         RBN::process();
845
846         DXTimer::handler();
847         DXLog::flushall();
848 }
849
850 sub per_10_sec
851 {
852
853 }
854
855 sub per_minute
856 {
857         RBN::per_minute();
858 }
859
860 sub per_10_minute
861 {
862         RBN::per_10_minute();
863 }
864
865 sub per_hour
866 {
867         RBN::per_hour();
868 }
869
870 sub per_day
871 {
872
873 }
874
875 sub start_node
876 {
877         dbg("Before Web::start_node");
878
879         Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
880
881         dbg("After Web::start_node");
882
883 }
884
885 setup_start();
886
887 my $main_loop = Mojo::IOLoop->recurring($idle_interval => \&idle_loop);
888 my $log_flush_loop = Mojo::IOLoop->recurring($log_flush_interval => \&DXLog::flushall);
889 my $cpusecs_loop = Mojo::IOLoop->recurring(5 => sub {my @t = times; $clssecs = $t[0]+$t[1]; $cldsecs = $t[2]+$t[3]});
890 my $persec =  Mojo::IOLoop->recurring(1 => \&per_sec);
891 my $per10sec =  Mojo::IOLoop->recurring(10 => \&per_10_sec);
892 my $permin =  Mojo::IOLoop->recurring(60 => \&per_minute);
893 my $per10min =  Mojo::IOLoop->recurring(600 => \&per_10_minute);
894 my $perhour =  Mojo::IOLoop->recurring(3600 => \&per_hour);
895 my $perday =  Mojo::IOLoop->recurring(86400 => \&per_day);
896
897 start_node();
898
899 cease(0);
900
901 exit(0);
902
903 sub END
904 {
905         unless ($ceasing) {
906                 print "DXSpider Ending\n";
907                 cease();
908         }
909 }