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