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