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