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