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