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