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