fix EOF detection of incoming nodes
[spider.git] / perl / cluster.pl
1 #!/usr/bin/perl -w
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 require 5.10.1;
14
15 # make sure that modules are searched in the order local then perl
16 BEGIN {
17         umask 002;
18
19         # root of directory tree for this system
20         $root = "/spider";
21         $root = $ENV{'DXSPIDER_ROOT'} if $ENV{'DXSPIDER_ROOT'};
22
23         unshift @INC, "$root/perl";     # this IS the right way round!
24         unshift @INC, "$root/local";
25
26         # do some validation of the input
27         die "The directory $root doesn't exist, please RTFM" unless -d $root;
28         die "$root/local doesn't exist, please RTFM" unless -d "$root/local";
29         die "$root/local/DXVars.pm doesn't exist, please RTFM" unless -e "$root/local/DXVars.pm";
30
31         mkdir "$root/local_cmd", 0777 unless -d "$root/local_cmd";
32
33
34         # try to create and lock a lockfile (this isn't atomic but
35         # should do for now
36         $lockfn = "$root/local/cluster.lck";       # lock file name
37         if (-w $lockfn) {
38                 open(CLLOCK, "$lockfn") or die "Can't open Lockfile ($lockfn) $!";
39                 my $pid = <CLLOCK>;
40                 if ($pid) {
41                         chomp $pid;
42                         die "Lockfile ($lockfn) and process $pid exist, another cluster running?" if kill 0, $pid;
43                 }
44                 unlink $lockfn;
45                 close CLLOCK;
46         }
47         open(CLLOCK, ">$lockfn") or die "Can't open Lockfile ($lockfn) $!";
48         print CLLOCK "$$\n";
49         close CLLOCK;
50
51         $is_win = ($^O =~ /^MS/ || $^O =~ /^OS-2/) ? 1 : 0; # is it Windows?
52         $systime = time;
53 }
54
55 use Mojo::IOLoop;
56
57 use DXVars;
58 use Msg;
59 use IntMsg;
60 use Internet;
61 use Listeners;
62 use ExtMsg;
63 use AGWConnect;
64 use AGWMsg;
65 use DXDebug;
66 use DXLog;
67 use DXLogPrint;
68 use DXUtil;
69 use DXChannel;
70 use DXUser;
71 use DXM;
72 use DXCommandmode;
73 use DXProtVars;
74 use DXProtout;
75 use DXProt;
76 use DXMsg;
77 use DXCron;
78 use DXConnect;
79 use DXBearing;
80 use DXDb;
81 use DXHash;
82 use DXDupe;
83 use Script;
84 use Prefix;
85 use Spot;
86 use Bands;
87 use Keps;
88 use Minimuf;
89 use Sun;
90 use Geomag;
91 use CmdAlias;
92 use Filter;
93 use AnnTalk;
94 use BBS;
95 use WCY;
96 use BadWords;
97 use Timer;
98 use Route;
99 use Route::Node;
100 use Route::User;
101 use Editable;
102 use Mrtg;
103 use USDB;
104 use UDPMsg;
105 use QSL;
106 use DXXml;
107 use DXSql;
108 use IsoTime;
109 use BPQMsg;
110
111 use Data::Dumper;
112 use IO::File;
113 use Fcntl ':flock';
114 use POSIX ":sys_wait_h";
115 use Version;
116
117 use Local;
118
119 package main;
120
121 use strict;
122 use vars qw(@inqueue $systime $starttime $lockfn @outstanding_connects
123                         $zombies $root @listeners $lang $myalias @debug $userfn $clusteraddr
124                         $clusterport $mycall $decease $is_win $routeroot $me $reqreg $bumpexisting
125                         $allowdxby $dbh $dsn $dbuser $dbpass $do_xml $systime_days $systime_daystart
126                         $can_encode $maxconnect_user $maxconnect_node $idle_interval
127                    );
128
129 @inqueue = ();                                  # the main input queue, an array of hashes
130 $systime = 0;                                   # the time now (in seconds)
131 $starttime = 0;                 # the starting time of the cluster
132 @outstanding_connects = ();     # list of outstanding connects
133 @listeners = ();                                # list of listeners
134 $reqreg = 0;                                    # 1 = registration required, 2 = deregister people
135 $bumpexisting = 1;                              # 1 = allow new connection to disconnect old, 0 - don't allow it
136 $allowdxby = 0;                                 # 1 = allow "dx by <othercall>", 0 - don't allow it
137 $maxconnect_user = 3;                   # the maximum no of concurrent connections a user can have at a time
138 $maxconnect_node = 0;                   # Ditto but for nodes. In either case if a new incoming connection
139                                                                 # takes the no of references in the routing table above these numbers
140                                                                 # then the connection is refused. This only affects INCOMING connections.
141 $idle_interval = 0.100;                        # the wait between invocations of the main idle loop processing.
142 our $ending;                                                               # signal that we are ending;
143
144
145 # send a message to call on conn and disconnect
146 sub already_conn
147 {
148         my ($conn, $call, $mess) = @_;
149
150         $conn->disable_read(1);
151         dbg("-> D $call $mess\n") if isdbg('chan');
152         $conn->send_now("D$call|$mess");
153         sleep(2);
154         $conn->disconnect;
155 }
156
157 # handle incoming messages
158 sub new_channel
159 {
160         my ($conn, $msg) = @_;
161         my ($sort, $call, $line) = DXChannel::decode_input(0, $msg);
162         return unless defined $sort;
163
164         unless (is_callsign($call)) {
165                 already_conn($conn, $call, DXM::msg($lang, "illcall", $call));
166                 return;
167         }
168
169         # set up the basic channel info
170         # is there one already connected to me - locally?
171         my $user = DXUser::get_current($call);
172         my $dxchan = DXChannel::get($call);
173         if ($dxchan) {
174                 if ($user && $user->is_node) {
175                         already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
176                         return;
177                 }
178                 if ($bumpexisting) {
179                         my $ip = $conn->peerhost || 'unknown';
180                         $dxchan->send_now('D', DXM::msg($lang, 'conbump', $call, $ip));
181                         LogDbg('DXCommand', "$call bumped off by $ip, disconnected");
182                         $dxchan->disconnect;
183                 } else {
184                         already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
185                         return;
186                 }
187         }
188
189         # (fairly) politely disconnect people that are connected to too many other places at once
190         my $r = Route::get($call);
191         if ($conn->{sort} && $conn->{sort} =~ /^I/ && $r && $user) {
192                 my @n = $r->parents;
193                 my $m = $r->isa('Route::Node') ? $maxconnect_node : $maxconnect_user;
194                 my $c = $user->maxconnect;
195                 my $v;
196                 $v = defined $c ? $c : $m;
197                 if ($v && @n >= $v) {
198                         my $nodes = join ',', @n;
199                         LogDbg('DXCommand', "$call has too many connections ($v) at $nodes - disconnected");
200                         already_conn($conn, $call, DXM::msg($lang, 'contomany', $call, $v, $nodes));
201                         return;
202                 }
203         }
204
205         # is he locked out ?
206         my $basecall = $call;
207         $basecall =~ s/-\d+$//;
208         my $baseuser = DXUser::get_current($basecall);
209         my $lock = $user->lockout if $user;
210         if ($baseuser && $baseuser->lockout || $lock) {
211                 if (!$user || !defined $lock || $lock) {
212                         my $host = $conn->peerhost || "unknown";
213                         LogDbg('DXCommand', "$call on $host is locked out, disconnected");
214                         $conn->disconnect;
215                         return;
216                 }
217         }
218
219         if ($user) {
220                 $user->{lang} = $main::lang if !$user->{lang}; # to autoupdate old systems
221         } else {
222                 $user = DXUser->new($call);
223         }
224
225         # create the channel
226         if ($user->is_node) {
227                 $dxchan = DXProt->new($call, $conn, $user);
228         } elsif ($user->is_user) {
229                 $dxchan = DXCommandmode->new($call, $conn, $user);
230 #       } elsif ($user->is_bbs) {                                  # there is no support so
231 #               $dxchan = BBS->new($call, $conn, $user);               # don't allow it!!!
232         } else {
233                 die "Invalid sort of user on $call = $sort";
234         }
235
236         # check that the conn has a callsign
237         $conn->conns($call) if $conn->isa('IntMsg');
238
239         # set callbacks
240         $conn->set_error(sub {my $err = shift; error_handler($dxchan, $err)});
241         $conn->set_on_eof(sub {$dxchan->disconnect});
242         $conn->set_rproc(sub {my ($conn,$msg) = @_; $dxchan->rec($msg);});
243         $dxchan->rec($msg);
244 }
245
246
247 sub login
248 {
249         return \&new_channel;
250 }
251
252 our $ceasing;
253
254 # cease running this program, close down all the connections nicely
255 sub cease
256 {
257         my $dxchan;
258
259         cluck("ceasing") if $ceasing; 
260         
261         return if $ceasing++;
262         
263         unless ($is_win) {
264                 $SIG{'TERM'} = 'IGNORE';
265                 $SIG{'INT'} = 'IGNORE';
266         }
267
268         DXUser::sync;
269
270         if (defined &Local::finish) {
271                 eval {
272                         Local::finish();   # end local processing
273                 };
274                 dbg("Local::finish error $@") if $@;
275         }
276
277
278         # disconnect AGW
279         AGWMsg::finish();
280         BPQMsg::finish();
281
282         # disconnect UDP customers
283         UDPMsg::finish();
284
285         # end everything else
286         DXUser::finish();
287         DXDupe::finish();
288
289         # close all databases
290         DXDb::closeall;
291
292         # close all listeners
293         foreach my $l (@listeners) {
294                 $l->close_server;
295         }
296
297         LogDbg('cluster', "DXSpider V$version, build $build (git: $gitversion) ended");
298         dbg("bye bye everyone - bye bye");
299         dbgclose();
300         Logclose();
301
302         $dbh->finish if $dbh;
303
304         unlink $lockfn;
305 }
306
307 # the reaper of children
308 sub reap
309 {
310         my $cpid;
311         while (($cpid = waitpid(-1, WNOHANG)) > 0) {
312                 dbg("cpid: $cpid") if isdbg('reap');
313 #               Msg->pid_gone($cpid);
314                 $zombies-- if $zombies > 0;
315         }
316         dbg("cpid: $cpid") if isdbg('reap');
317 }
318
319 # this is where the input queue is dealt with and things are dispatched off to other parts of
320 # the cluster
321
322 sub uptime
323 {
324         my $t = $systime - $starttime;
325         my $days = int $t / 86400;
326         $t -= $days * 86400;
327         my $hours = int $t / 3600;
328         $t -= $hours * 3600;
329         my $mins = int $t / 60;
330         return sprintf "%d %02d:%02d", $days, $hours, $mins;
331 }
332
333 sub AGWrestart
334 {
335         AGWMsg::init(\&new_channel);
336 }
337
338 our $io_disconnected;
339
340 sub idle_loop
341 {
342         my $timenow = time;
343
344         DXChannel::process();
345
346         #      $DB::trace = 0;
347
348         # do timed stuff, ongoing processing happens one a second
349         if ($timenow != $systime) {
350                 reap() if $zombies;
351                 $systime = $timenow;
352                 my $days = int ($systime / 86400);
353                 if ($systime_days != $days) {
354                         $systime_days = $days;
355                         $systime_daystart = $days * 86400;
356                 }
357                 IsoTime::update($systime);
358                 DXCron::process();      # do cron jobs
359                 DXCommandmode::process(); # process ongoing command mode stuff
360                 DXXml::process();
361                 DXProt::process();              # process ongoing ak1a pcxx stuff
362                 DXConnect::process();
363                 DXMsg::process();
364                 DXDb::process();
365                 DXUser::process();
366                 DXDupe::process();
367                 $systime_days = $days;
368                 $systime_daystart = $days * 86400;
369         }
370         IsoTime::update($systime);
371         DXCron::process();                      # do cron jobs
372         DXCommandmode::process();       # process ongoing command mode stuff
373         DXXml::process();
374         DXProt::process();                      # process ongoing ak1a pcxx stuff
375         DXConnect::process();
376         DXMsg::process();
377         DXDb::process();
378         DXUser::process();
379         DXDupe::process();
380         AGWMsg::process();
381         BPQMsg::process();
382
383         Timer::handler();
384
385         if (defined &Local::process) {
386                 eval {
387                         Local::process();       # do any localised processing
388                 };
389                 dbg("Local::process error $@") if $@;
390         }
391
392         while ($ending) {
393                 my $dxchan;
394
395                 dbg("DXSpider Ending $ending");
396
397                 unless ($io_disconnected++) {
398
399                         # disconnect users
400                         foreach $dxchan (DXChannel::get_all_users) {
401                                 $dxchan->disconnect;
402                         }
403
404                         # disconnect nodes
405                         foreach $dxchan (DXChannel::get_all_nodes) {
406                                 next if $dxchan == $main::me;
407                                 $dxchan->disconnect(2);
408                         }
409                         $main::me->disconnect;
410                 }
411
412                 Mojo::IOLoop->stop if --$ending <= 0;
413         }
414 }
415
416
417 #############################################################
418 #
419 # The start of the main line of code
420 #
421 #############################################################
422
423 $starttime = $systime = time;
424 $systime_days = int ($systime / 86400);
425 $systime_daystart = $systime_days * 86400;
426 $lang = 'en' unless $lang;
427
428 unless ($DB::VERSION) {
429         $SIG{INT} = $SIG{TERM} = \&cease;
430 }
431
432 # open the debug file, set various FHs to be unbuffered
433 dbginit(\&DXCommandmode::broadcast_debug);
434 foreach (@debug) {
435         dbgadd($_);
436 }
437 STDOUT->autoflush(1);
438
439 # try to load the database
440 if (DXSql::init($dsn)) {
441         $dbh = DXSql->new($dsn);
442         $dbh = $dbh->connect($dsn, $dbuser, $dbpass) if $dbh;
443 }
444
445 # try to load Encode
446 {
447         local $^W = 0;
448         my $w = $SIG{__DIE__};
449         $SIG{__DIE__} = 'IGNORE';
450         eval { require Encode; };
451         unless ($@) {
452                 import Encode;
453                 $can_encode = 1;
454         }
455         $SIG{__DIE__} = $w;
456 }
457
458 # try to load XML::Simple
459 DXXml::init();
460
461 # banner
462 my ($year) = (gmtime)[5];
463 $year += 1900;
464 LogDbg('cluster', "DXSpider V$version, build $build (git: $gitversion) started");
465 dbg("Copyright (c) 1998-$year Dirk Koopman G1TLH");
466
467 # load Prefixes
468 dbg("loading prefixes ...");
469 dbg(USDB::init());
470 my $r = Prefix::init();
471 confess $r if $r;
472
473 # load band data
474 dbg("loading band data ...");
475 Bands::load();
476
477 # initialise User file system
478 dbg("loading user file system ...");
479 DXUser->init($userfn, 1);
480
481 # look for the sysop and the alias user and complain if they aren't there
482 {
483         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;
484         my $ref = DXUser::get($mycall);
485         die "$mycall missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
486         $ref = DXUser::get($myalias);
487         die "$myalias missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
488 }
489
490 # start listening for incoming messages/connects
491 dbg("starting listeners ...");
492 my $conn = IntMsg->new_server($clusteraddr, $clusterport, \&login);
493 $conn->conns("Server $clusteraddr/$clusterport using IntMsg");
494 push @listeners, $conn;
495 dbg("Internal port: $clusteraddr $clusterport using IntMsg");
496 foreach my $l (@main::listen) {
497         no strict 'refs';
498         my $pkg = $l->[2] || 'ExtMsg';
499         my $login = $l->[3] || 'login';
500
501         $conn = $pkg->new_server($l->[0], $l->[1], \&{"${pkg}::${login}"});
502         $conn->conns("Server $l->[0]/$l->[1] using ${pkg}::${login}");
503         push @listeners, $conn;
504         dbg("External Port: $l->[0] $l->[1] using ${pkg}::${login}");
505 }
506
507 dbg("AGW Listener") if $AGWMsg::enable;
508 AGWrestart();
509
510 dbg("BPQ Listener") if $BPQMsg::enable;
511 BPQMsg::init(\&new_channel);
512
513 dbg("UDP Listener") if $UDPMsg::enable;
514 UDPMsg::init(\&new_channel);
515
516 # load bad words
517 dbg("load badwords: " . (BadWords::load or "Ok"));
518
519 # prime some signals
520 unless ($DB::VERSION) {
521         $SIG{INT} = $SIG{TERM} = sub { $ending = 10; };
522 }
523
524 unless ($is_win) {
525         $SIG{HUP} = 'IGNORE';
526         $SIG{CHLD} = sub { $zombies++ };
527
528         $SIG{PIPE} = sub {      dbg("Broken PIPE signal received"); };
529         $SIG{IO} = sub {        dbg("SIGIO received"); };
530         $SIG{WINCH} = $SIG{STOP} = $SIG{CONT} = 'IGNORE';
531         $SIG{KILL} = 'DEFAULT';     # as if it matters....
532
533         # catch the rest with a hopeful message
534         for (keys %SIG) {
535                 if (!$SIG{$_}) {
536                         #               dbg("Catching SIG $_") if isdbg('chan');
537                         $SIG{$_} = sub { my $sig = shift;       DXDebug::confess("Caught signal $sig");  };
538                 }
539         }
540 }
541
542 # start dupe system
543 dbg("Starting Dupe system");
544 DXDupe::init();
545
546 # read in system messages
547 dbg("Read in Messages");
548 DXM->init();
549
550 # read in command aliases
551 dbg("Read in Aliases");
552 CmdAlias->init();
553
554 # initialise the Geomagnetic data engine
555 dbg("Start WWV");
556 Geomag->init();
557 dbg("Start WCY");
558 WCY->init();
559
560 # initial the Spot stuff
561 dbg("Starting DX Spot system");
562 Spot->init();
563
564 # initialise the protocol engine
565 dbg("Start Protocol Engines ...");
566 DXProt->init();
567
568 # put in a DXCluster node for us here so we can add users and take them away
569 $routeroot = Route::Node->new($mycall, $version*100+5300, Route::here($main::me->here)|Route::conf($main::me->conf));
570 $routeroot->do_pc9x(1);
571 $routeroot->via_pc92(1);
572
573 # make sure that there is a routing OUTPUT node default file
574 #unless (Filter::read_in('route', 'node_default', 0)) {
575 #       my $dxcc = $main::me->dxcc;
576 #       $Route::filterdef->cmd($main::me, 'route', 'accept', "node_default call $mycall" );
577 #}
578
579 # read in any existing message headers and clean out old crap
580 dbg("reading existing message headers ...");
581 DXMsg->init();
582 DXMsg::clean_old();
583
584 # read in any cron jobs
585 dbg("reading cron jobs ...");
586 DXCron->init();
587
588 # read in database desriptors
589 dbg("reading database descriptors ...");
590 DXDb::load();
591
592 # starting local stuff
593 dbg("doing local initialisation ...");
594 QSL::init(1);
595 if (defined &Local::init) {
596         eval {
597                 Local::init();
598         };
599         dbg("Local::init error $@") if $@;
600 }
601
602
603 # this, such as it is, is the main loop!
604 dbg("orft we jolly well go ...");
605 my $script = new Script "startup";
606 $script->run($main::me) if $script;
607
608 #open(DB::OUT, "|tee /tmp/aa");
609
610 my $main_loop = Mojo::IOLoop->recurring($idle_interval => \&idle_loop);
611
612 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
613
614 dbg("After Mojo::IOLoop");
615 cease(0);
616 exit(0);
617