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