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