remove autoflush from log objects
[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 $log_flush_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.500;         # the wait between invocations of the main idle loop processing.
142 $log_flush_interval = 2;                # interval to wait between log flushes
143
144 our $ending;                                                               # signal that we are ending;
145
146
147 # send a message to call on conn and disconnect
148 sub already_conn
149 {
150         my ($conn, $call, $mess) = @_;
151
152         $conn->disable_read(1);
153         dbg("-> D $call $mess\n") if isdbg('chan');
154         $conn->send_now("D$call|$mess");
155         sleep(2);
156         $conn->disconnect;
157 }
158
159 # handle incoming messages
160 sub new_channel
161 {
162         my ($conn, $msg) = @_;
163         my ($sort, $call, $line) = DXChannel::decode_input(0, $msg);
164         return unless defined $sort;
165
166         unless (is_callsign($call)) {
167                 already_conn($conn, $call, DXM::msg($lang, "illcall", $call));
168                 return;
169         }
170
171         # set up the basic channel info
172         # is there one already connected to me - locally?
173         my $user = DXUser::get_current($call);
174         my $dxchan = DXChannel::get($call);
175         if ($dxchan) {
176                 if ($user && $user->is_node) {
177                         already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
178                         return;
179                 }
180                 if ($bumpexisting) {
181                         my $ip = $conn->peerhost || 'unknown';
182                         $dxchan->send_now('D', DXM::msg($lang, 'conbump', $call, $ip));
183                         LogDbg('DXCommand', "$call bumped off by $ip, disconnected");
184                         $dxchan->disconnect;
185                 } else {
186                         already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
187                         return;
188                 }
189         }
190
191         # (fairly) politely disconnect people that are connected to too many other places at once
192         my $r = Route::get($call);
193         if ($conn->{sort} && $conn->{sort} =~ /^I/ && $r && $user) {
194                 my @n = $r->parents;
195                 my $m = $r->isa('Route::Node') ? $maxconnect_node : $maxconnect_user;
196                 my $c = $user->maxconnect;
197                 my $v;
198                 $v = defined $c ? $c : $m;
199                 if ($v && @n >= $v) {
200                         my $nodes = join ',', @n;
201                         LogDbg('DXCommand', "$call has too many connections ($v) at $nodes - disconnected");
202                         already_conn($conn, $call, DXM::msg($lang, 'contomany', $call, $v, $nodes));
203                         return;
204                 }
205         }
206
207         # is he locked out ?
208         my $basecall = $call;
209         $basecall =~ s/-\d+$//;
210         my $baseuser = DXUser::get_current($basecall);
211         my $lock = $user->lockout if $user;
212         if ($baseuser && $baseuser->lockout || $lock) {
213                 if (!$user || !defined $lock || $lock) {
214                         my $host = $conn->peerhost || "unknown";
215                         LogDbg('DXCommand', "$call on $host is locked out, disconnected");
216                         $conn->disconnect;
217                         return;
218                 }
219         }
220
221         if ($user) {
222                 $user->{lang} = $main::lang if !$user->{lang}; # to autoupdate old systems
223         } else {
224                 $user = DXUser->new($call);
225         }
226
227         # create the channel
228         if ($user->is_node) {
229                 $dxchan = DXProt->new($call, $conn, $user);
230         } elsif ($user->is_user) {
231                 $dxchan = DXCommandmode->new($call, $conn, $user);
232 #       } elsif ($user->is_bbs) {                                  # there is no support so
233 #               $dxchan = BBS->new($call, $conn, $user);               # don't allow it!!!
234         } else {
235                 die "Invalid sort of user on $call = $sort";
236         }
237
238         # check that the conn has a callsign
239         $conn->conns($call) if $conn->isa('IntMsg');
240
241         # set callbacks
242         $conn->set_error(sub {my $err = shift; LogDbg('DXCommand', "Comms error '$err' received for call $dxchan->{call}"); $dxchan->disconnect(1);});
243         $conn->set_on_eof(sub {$dxchan->disconnect});
244         $conn->set_rproc(sub {my ($conn,$msg) = @_; $dxchan->rec($msg);});
245         $dxchan->rec($msg);
246 }
247
248
249 sub login
250 {
251         return \&new_channel;
252 }
253
254 our $ceasing;
255
256 # cease running this program, close down all the connections nicely
257 sub cease
258 {
259         my $dxchan;
260
261         cluck("ceasing") if $ceasing; 
262         
263         return if $ceasing++;
264         
265         unless ($is_win) {
266                 $SIG{'TERM'} = 'IGNORE';
267                 $SIG{'INT'} = 'IGNORE';
268         }
269
270         DXUser::sync;
271
272         if (defined &Local::finish) {
273                 eval {
274                         Local::finish();   # end local processing
275                 };
276                 dbg("Local::finish error $@") if $@;
277         }
278
279
280         # disconnect AGW
281         AGWMsg::finish();
282         BPQMsg::finish();
283
284         # disconnect UDP customers
285         UDPMsg::finish();
286
287         # end everything else
288         DXUser::finish();
289         DXDupe::finish();
290
291         # close all databases
292         DXDb::closeall;
293
294         # close all listeners
295         foreach my $l (@listeners) {
296                 $l->close_server;
297         }
298
299         LogDbg('cluster', "DXSpider V$version, build $build (git: $gitversion) ended");
300         dbg("bye bye everyone - bye bye");
301         dbgclose();
302         Logclose();
303
304         $dbh->finish if $dbh;
305
306         unlink $lockfn;
307 }
308
309 # the reaper of children
310 sub reap
311 {
312         my $cpid;
313         while (($cpid = waitpid(-1, WNOHANG)) > 0) {
314                 dbg("cpid: $cpid") if isdbg('reap');
315 #               Msg->pid_gone($cpid);
316                 $zombies-- if $zombies > 0;
317         }
318         dbg("cpid: $cpid") if isdbg('reap');
319 }
320
321 # this is where the input queue is dealt with and things are dispatched off to other parts of
322 # the cluster
323
324 sub uptime
325 {
326         my $t = $systime - $starttime;
327         my $days = int $t / 86400;
328         $t -= $days * 86400;
329         my $hours = int $t / 3600;
330         $t -= $hours * 3600;
331         my $mins = int $t / 60;
332         return sprintf "%d %02d:%02d", $days, $hours, $mins;
333 }
334
335 sub AGWrestart
336 {
337         AGWMsg::init(\&new_channel);
338 }
339
340 our $io_disconnected;
341
342 sub idle_loop
343 {
344         my $timenow = time;
345
346         BPQMsg::process();
347 #       DXChannel::process();
348
349         #      $DB::trace = 0;
350
351         # do timed stuff, ongoing processing happens one a second
352         if ($timenow != $systime) {
353                 reap() if $zombies;
354                 $systime = $timenow;
355                 my $days = int ($systime / 86400);
356                 if ($systime_days != $days) {
357                         $systime_days = $days;
358                         $systime_daystart = $days * 86400;
359                 }
360                 IsoTime::update($systime);
361                 DXCron::process();      # do cron jobs
362                 DXCommandmode::process(); # process ongoing command mode stuff
363                 DXXml::process();
364                 DXProt::process();              # process ongoing ak1a pcxx stuff
365                 DXConnect::process();
366                 DXMsg::process();
367                 DXDb::process();
368                 DXUser::process();
369                 DXDupe::process();
370                 DXCron::process();                      # do cron jobs
371                 IsoTime::update($systime);
372                 DXProt::process();                      # process ongoing ak1a pcxx stuff
373                 DXConnect::process();
374                 DXUser::process();
375                 AGWMsg::process();
376                 
377                 Timer::handler();
378                 DXLog::flushall();
379         }
380
381         if (defined &Local::process) {
382                 eval {
383                         Local::process();       # do any localised processing
384                 };
385                 dbg("Local::process error $@") if $@;
386         }
387
388         while ($ending) {
389                 my $dxchan;
390
391                 dbg("DXSpider Ending $ending");
392
393                 unless ($io_disconnected++) {
394
395                         # disconnect users
396                         foreach $dxchan (DXChannel::get_all_users) {
397                                 $dxchan->disconnect;
398                         }
399
400                         # disconnect nodes
401                         foreach $dxchan (DXChannel::get_all_nodes) {
402                                 next if $dxchan == $main::me;
403                                 $dxchan->disconnect(2);
404                         }
405                         $main::me->disconnect;
406                 }
407
408                 Mojo::IOLoop->stop if --$ending <= 0;
409         }
410 }
411
412
413 #############################################################
414 #
415 # The start of the main line of code
416 #
417 #############################################################
418
419 $starttime = $systime = time;
420 $systime_days = int ($systime / 86400);
421 $systime_daystart = $systime_days * 86400;
422 $lang = 'en' unless $lang;
423
424 unless ($DB::VERSION) {
425         $SIG{INT} = $SIG{TERM} = \&cease;
426 }
427
428 # open the debug file, set various FHs to be unbuffered
429 dbginit(\&DXCommandmode::broadcast_debug);
430 foreach (@debug) {
431         dbgadd($_);
432 }
433 STDOUT->autoflush(1);
434
435 # try to load the database
436 if (DXSql::init($dsn)) {
437         $dbh = DXSql->new($dsn);
438         $dbh = $dbh->connect($dsn, $dbuser, $dbpass) if $dbh;
439 }
440
441 # try to load Encode
442 {
443         local $^W = 0;
444         my $w = $SIG{__DIE__};
445         $SIG{__DIE__} = 'IGNORE';
446         eval { require Encode; };
447         unless ($@) {
448                 import Encode;
449                 $can_encode = 1;
450         }
451         $SIG{__DIE__} = $w;
452 }
453
454 # try to load XML::Simple
455 DXXml::init();
456
457 # banner
458 my ($year) = (gmtime)[5];
459 $year += 1900;
460 LogDbg('cluster', "DXSpider V$version, build $build (git: $gitversion) started");
461 dbg("Copyright (c) 1998-$year Dirk Koopman G1TLH");
462
463 # load Prefixes
464 dbg("loading prefixes ...");
465 dbg(USDB::init());
466 my $r = Prefix::init();
467 confess $r if $r;
468
469 # load band data
470 dbg("loading band data ...");
471 Bands::load();
472
473 # initialise User file system
474 dbg("loading user file system ...");
475 DXUser->init($userfn, 1);
476
477 # look for the sysop and the alias user and complain if they aren't there
478 {
479         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;
480         my $ref = DXUser::get($mycall);
481         die "$mycall missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
482         $ref = DXUser::get($myalias);
483         die "$myalias missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
484 }
485
486 # start listening for incoming messages/connects
487 dbg("starting listeners ...");
488 my $conn = IntMsg->new_server($clusteraddr, $clusterport, \&login);
489 $conn->conns("Server $clusteraddr/$clusterport using IntMsg");
490 push @listeners, $conn;
491 dbg("Internal port: $clusteraddr $clusterport using IntMsg");
492 foreach my $l (@main::listen) {
493         no strict 'refs';
494         my $pkg = $l->[2] || 'ExtMsg';
495         my $login = $l->[3] || 'login';
496
497         $conn = $pkg->new_server($l->[0], $l->[1], \&{"${pkg}::${login}"});
498         $conn->conns("Server $l->[0]/$l->[1] using ${pkg}::${login}");
499         push @listeners, $conn;
500         dbg("External Port: $l->[0] $l->[1] using ${pkg}::${login}");
501 }
502
503 dbg("AGW Listener") if $AGWMsg::enable;
504 AGWrestart();
505
506 dbg("BPQ Listener") if $BPQMsg::enable;
507 BPQMsg::init(\&new_channel);
508
509 dbg("UDP Listener") if $UDPMsg::enable;
510 UDPMsg::init(\&new_channel);
511
512 # load bad words
513 dbg("load badwords: " . (BadWords::load or "Ok"));
514
515 # prime some signals
516 unless ($DB::VERSION) {
517         $SIG{INT} = $SIG{TERM} = sub { $ending = 10; };
518 }
519
520 unless ($is_win) {
521         $SIG{HUP} = 'IGNORE';
522         $SIG{CHLD} = sub { $zombies++ };
523
524         $SIG{PIPE} = sub {      dbg("Broken PIPE signal received"); };
525         $SIG{IO} = sub {        dbg("SIGIO received"); };
526         $SIG{WINCH} = $SIG{STOP} = $SIG{CONT} = 'IGNORE';
527         $SIG{KILL} = 'DEFAULT';     # as if it matters....
528
529         # catch the rest with a hopeful message
530         for (keys %SIG) {
531                 if (!$SIG{$_}) {
532                         #               dbg("Catching SIG $_") if isdbg('chan');
533                         $SIG{$_} = sub { my $sig = shift;       DXDebug::confess("Caught signal $sig");  };
534                 }
535         }
536 }
537
538 # start dupe system
539 dbg("Starting Dupe system");
540 DXDupe::init();
541
542 # read in system messages
543 dbg("Read in Messages");
544 DXM->init();
545
546 # read in command aliases
547 dbg("Read in Aliases");
548 CmdAlias->init();
549
550 # initialise the Geomagnetic data engine
551 dbg("Start WWV");
552 Geomag->init();
553 dbg("Start WCY");
554 WCY->init();
555
556 # initial the Spot stuff
557 dbg("Starting DX Spot system");
558 Spot->init();
559
560 # initialise the protocol engine
561 dbg("Start Protocol Engines ...");
562 DXProt->init();
563
564 # put in a DXCluster node for us here so we can add users and take them away
565 $routeroot = Route::Node->new($mycall, $version*100+5300, Route::here($main::me->here)|Route::conf($main::me->conf));
566 $routeroot->do_pc9x(1);
567 $routeroot->via_pc92(1);
568
569 # make sure that there is a routing OUTPUT node default file
570 #unless (Filter::read_in('route', 'node_default', 0)) {
571 #       my $dxcc = $main::me->dxcc;
572 #       $Route::filterdef->cmd($main::me, 'route', 'accept', "node_default call $mycall" );
573 #}
574
575 # read in any existing message headers and clean out old crap
576 dbg("reading existing message headers ...");
577 DXMsg->init();
578 DXMsg::clean_old();
579
580 # read in any cron jobs
581 dbg("reading cron jobs ...");
582 DXCron->init();
583
584 # read in database desriptors
585 dbg("reading database descriptors ...");
586 DXDb::load();
587
588 # starting local stuff
589 dbg("doing local initialisation ...");
590 QSL::init(1);
591 if (defined &Local::init) {
592         eval {
593                 Local::init();
594         };
595         dbg("Local::init error $@") if $@;
596 }
597
598
599 # this, such as it is, is the main loop!
600 dbg("orft we jolly well go ...");
601 my $script = new Script "startup";
602 $script->run($main::me) if $script;
603
604 #open(DB::OUT, "|tee /tmp/aa");
605
606 my $main_loop = Mojo::IOLoop->recurring($idle_interval => \&idle_loop);
607 my $log_flush_loop = Mojo::IOLoop->recurring($log_flush_interval => \&DXLog::flushall);
608
609 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
610
611 dbg("After Mojo::IOLoop");
612 cease(0);
613 exit(0);
614