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