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