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