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