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