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