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