169900cc1afc5f674299d373244dafed42eba6f2
[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         # try to create and lock a lockfile (this isn't atomic but 
27         # should do for now
28         $lockfn = "$root/perl/cluster.lck";       # lock file name
29         if (-e $lockfn) {
30                 open(CLLOCK, "$lockfn") or die "Can't open Lockfile ($lockfn) $!";
31                 my $pid = <CLLOCK>;
32                 chomp $pid;
33                 die "Lockfile ($lockfn) and process $pid exist, another cluster running?" if kill 0, $pid;
34                 close CLLOCK;
35         }
36         open(CLLOCK, ">$lockfn") or die "Can't open Lockfile ($lockfn) $!";
37         print CLLOCK "$$\n";
38         close CLLOCK;
39
40         $is_win = ($^O =~ /^MS/ || $^O =~ /^OS-2/) ? 1 : 0; # is it Windows?
41         $systime = time;
42 }
43
44 use DXVars;
45 use Msg;
46 use IntMsg;
47 use Internet;
48 use Listeners;
49 use ExtMsg;
50 use AGWConnect;
51 use AGWMsg;
52 use DXDebug;
53 use DXLog;
54 use DXLogPrint;
55 use DXUtil;
56 use DXChannel;
57 use DXUser;
58 use DXM;
59 use DXCommandmode;
60 use DXProtVars;
61 use DXProtout;
62 use DXProt;
63 use QXProt;
64 use DXMsg;
65 use DXCron;
66 use DXConnect;
67 use DXBearing;
68 use DXDb;
69 use DXHash;
70 use DXDupe;
71 use Script;
72 use Prefix;
73 use Spot;
74 use Bands;
75 use Keps;
76 use Minimuf;
77 use Sun;
78 use Geomag;
79 use CmdAlias;
80 use Filter;
81 use AnnTalk;
82 use BBS;
83 use WCY;
84 use BadWords;
85 use Timer;
86 use Route;
87 use Route::Node;
88 use Route::User;
89
90 use Data::Dumper;
91 use IO::File;
92 use Fcntl ':flock'; 
93 use POSIX ":sys_wait_h";
94
95 use Local;
96
97 package main;
98
99 use strict;
100 use vars qw(@inqueue $systime $version $starttime $lockfn @outstanding_connects 
101                         $zombies $root @listeners $lang $myalias @debug $userfn $clusteraddr 
102                         $clusterport $mycall $decease $is_win $routeroot $me
103                    );
104
105 @inqueue = ();                                  # the main input queue, an array of hashes
106 $systime = 0;                                   # the time now (in seconds)
107 $version = "1.48";                              # the version no of the software
108 $starttime = 0;                 # the starting time of the cluster   
109 #@outstanding_connects = ();     # list of outstanding connects
110 @listeners = ();                                # list of listeners
111
112 use vars qw($VERSION $BRANCH $build $branch);
113 $VERSION = sprintf( "%d.%03d", q$Revision$ =~ /(\d+)\.(\d+)/ );
114 $BRANCH = sprintf( "%d.%03d", q$Revision$ =~ /\d+\.\d+\.(\d+)\.(\d+)/ ) || 0;
115 $main::build += 13;                             # add an offset to make it bigger than last system
116 $main::build += $VERSION;
117 $main::branch += $BRANCH;
118
119       
120 # send a message to call on conn and disconnect
121 sub already_conn
122 {
123         my ($conn, $call, $mess) = @_;
124
125         $conn->disable_read(1);
126         dbg("-> D $call $mess\n") if isdbg('chan'); 
127         $conn->send_now("D$call|$mess");
128         sleep(2);
129         $conn->disconnect;
130 }
131
132 sub error_handler
133 {
134         my $dxchan = shift;
135         $dxchan->{conn}->set_error(undef) if exists $dxchan->{conn};
136         $dxchan->disconnect(1);
137 }
138
139 # handle incoming messages
140 sub new_channel
141 {
142         my ($conn, $msg) = @_;
143         my ($sort, $call, $line) = DXChannel::decode_input(0, $msg);
144         return unless defined $sort;
145
146         unless (is_callsign($call)) {
147                 already_conn($conn, $call, DXM::msg($lang, "illcall", $call));
148                 return;
149         }
150
151         # set up the basic channel info
152         # is there one already connected to me - locally? 
153         my $user = DXUser->get($call);
154         my $dxchan = DXChannel->get($call);
155         if ($dxchan) {
156                 my $mess = DXM::msg($lang, ($user && $user->is_node) ? 'concluster' : 'conother', $call, $main::mycall);
157                 already_conn($conn, $call, $mess);
158                 return;
159         }
160
161         # is he locked out ?
162         my $basecall = $call;
163         $basecall =~ s/-\d+$//;
164         my $baseuser = DXUser->get($basecall);
165         my $lock = $user->lockout if $user;
166         if ($baseuser && $baseuser->lockout || $lock) {
167                 if (!$user || !defined $lock || $lock) {
168                         my $host = $conn->{peerhost} || "unknown";
169                         Log('DXCommand', "$call on $host is locked out, disconnected");
170                         $conn->disconnect;
171                         return;
172                 }
173         }
174         
175         if ($user) {
176                 $user->{lang} = $main::lang if !$user->{lang}; # to autoupdate old systems
177         } else {
178                 $user = DXUser->new($call);
179         }
180         
181
182         # create the channel
183         if ($user->is_spider) {
184                 $dxchan = QXProt->new($call, $conn, $user);
185         } elsif ($user->is_node) {
186                 $dxchan = DXProt->new($call, $conn, $user);
187         } elsif ($user->is_user) {
188                 $dxchan = DXCommandmode->new($call, $conn, $user);
189         } elsif ($user->is_bbs) {
190                 $dxchan = BBS->new($call, $conn, $user);
191         } else {
192                 die "Invalid sort of user on $call = $sort";
193         }
194
195         # check that the conn has a callsign
196         $conn->conns($call) if $conn->isa('IntMsg');
197
198         # set callbacks
199         $conn->set_error(sub {error_handler($dxchan)});
200         $conn->set_rproc(sub {my ($conn,$msg) = @_; rec($dxchan, $conn, $msg);});
201         rec($dxchan, $conn, $msg);
202 }
203
204 sub rec 
205 {
206         my ($dxchan, $conn, $msg) = @_;
207         
208         # queue the message and the channel object for later processing
209         if (defined $msg) {
210                 my $self = bless {}, "inqueue";
211                 $self->{dxchan} = $dxchan;
212                 $self->{data} = $msg;
213                 push @inqueue, $self;
214         }
215 }
216
217 sub login
218 {
219         return \&new_channel;
220 }
221
222 # cease running this program, close down all the connections nicely
223 sub cease
224 {
225         my $dxchan;
226
227         unless ($is_win) {
228                 $SIG{'TERM'} = 'IGNORE';
229                 $SIG{'INT'} = 'IGNORE';
230         }
231         
232         DXUser::sync;
233
234         eval {
235                 Local::finish();   # end local processing
236         };
237         dbg("Local::finish error $@") if $@;
238
239         # disconnect nodes
240         foreach $dxchan (DXChannel->get_all_nodes) {
241             $dxchan->disconnect(2) unless $dxchan == $main::me;
242         }
243         Msg->event_loop(100, 0.01);
244
245         # disconnect users
246         foreach $dxchan (DXChannel->get_all_users) {
247                 $dxchan->disconnect;
248         }
249
250         # disconnect AGW
251         AGWMsg::finish();
252
253         # end everything else
254         Msg->event_loop(100, 0.01);
255         DXUser::finish();
256         DXDupe::finish();
257
258         # close all databases
259         DXDb::closeall;
260
261         # close all listeners
262         foreach my $l (@listeners) {
263                 $l->close_server;
264         }
265
266         dbg("DXSpider version $version, build $build ended") if isdbg('chan');
267         Log('cluster', "DXSpider V$version, build $build ended");
268         dbgclose();
269         Logclose();
270         unlink $lockfn;
271 #       $SIG{__WARN__} = $SIG{__DIE__} =  sub {my $a = shift; cluck($a); };
272         exit(0);
273 }
274
275 # the reaper of children
276 sub reap
277 {
278         my $cpid;
279         while (($cpid = waitpid(-1, WNOHANG)) > 0) {
280                 dbg("cpid: $cpid") if isdbg('reap');
281 #               Msg->pid_gone($cpid);
282                 $zombies-- if $zombies > 0;
283         }
284         dbg("cpid: $cpid") if isdbg('reap');
285 }
286
287 # this is where the input queue is dealt with and things are dispatched off to other parts of
288 # the cluster
289 sub process_inqueue
290 {
291         while (@inqueue) {
292                 my $self = shift @inqueue;
293                 return if !$self;
294         
295                 my $data = $self->{data};
296                 my $dxchan = $self->{dxchan};
297                 my $error;
298                 my ($sort, $call, $line) = DXChannel::decode_input($dxchan, $data);
299                 return unless defined $sort;
300         
301                 # do the really sexy console interface bit! (Who is going to do the TK interface then?)
302                 dbg("<- $sort $call $line\n") if $sort ne 'D' && isdbg('chan');
303
304                 # handle A records
305                 my $user = $dxchan->user;
306                 if ($sort eq 'A' || $sort eq 'O') {
307                         $dxchan->start($line, $sort);  
308                 } elsif ($sort eq 'I') {
309                         die "\$user not defined for $call" if !defined $user;
310                         # normal input
311                         $dxchan->normal($line);
312                         $dxchan->disconnect if ($dxchan->{state} eq 'bye');
313                 } elsif ($sort eq 'Z') {
314                         $dxchan->disconnect;
315                 } elsif ($sort eq 'D') {
316                         ;                                       # ignored (an echo)
317                 } elsif ($sort eq 'G') {
318                         $dxchan->enhanced($line);
319                 } else {
320                         print STDERR atime, " Unknown command letter ($sort) received from $call\n";
321                 }
322         }
323 }
324
325 sub uptime
326 {
327         my $t = $systime - $starttime;
328         my $days = int $t / 86400;
329         $t -= $days * 86400;
330         my $hours = int $t / 3600;
331         $t -= $hours * 3600;
332         my $mins = int $t / 60;
333         return sprintf "%d %02d:%02d", $days, $hours, $mins;
334 }
335
336 sub AGWrestart
337 {
338         AGWMsg::init(\&new_channel);
339 }
340
341 #############################################################
342 #
343 # The start of the main line of code 
344 #
345 #############################################################
346
347 $starttime = $systime = time;
348 $lang = 'en' unless $lang;
349
350 # open the debug file, set various FHs to be unbuffered
351 dbginit(\&DXCommandmode::broadcast_debug);
352 foreach (@debug) {
353         dbgadd($_);
354 }
355 STDOUT->autoflush(1);
356
357 # calculate build number
358 $build += $main::version;
359 $build = "$build.$branch" if $branch;
360
361 Log('cluster', "DXSpider V$version, build $build started");
362
363 # banner
364 dbg("Copyright (c) 1998-2001 Dirk Koopman G1TLH");
365 dbg("DXSpider Version $version, build $build started");
366
367 # load Prefixes
368 dbg("loading prefixes ...");
369 Prefix::load();
370
371 # load band data
372 dbg("loading band data ...");
373 Bands::load();
374
375 # initialise User file system
376 dbg("loading user file system ..."); 
377 DXUser->init($userfn, 1);
378
379 # start listening for incoming messages/connects
380 dbg("starting listeners ...");
381 my $conn = IntMsg->new_server($clusteraddr, $clusterport, \&login);
382 $conn->conns("Server $clusteraddr/$clusterport");
383 push @listeners, $conn;
384 dbg("Internal port: $clusteraddr $clusterport");
385 foreach my $l (@main::listen) {
386         $conn = ExtMsg->new_server($l->[0], $l->[1], \&login);
387         $conn->conns("Server $l->[0]/$l->[1]");
388         push @listeners, $conn;
389         dbg("External Port: $l->[0] $l->[1]");
390 }
391 AGWrestart();
392
393 # load bad words
394 dbg("load badwords: " . (BadWords::load or "Ok"));
395
396 # prime some signals
397 unless ($DB::VERSION) {
398         $SIG{INT} = $SIG{TERM} = sub { $decease = 1 };
399 }
400
401 unless ($is_win) {
402         $SIG{HUP} = 'IGNORE';
403         $SIG{CHLD} = sub { $zombies++ };
404         
405         $SIG{PIPE} = sub {      dbg("Broken PIPE signal received"); };
406         $SIG{IO} = sub {        dbg("SIGIO received"); };
407         $SIG{WINCH} = $SIG{STOP} = $SIG{CONT} = 'IGNORE';
408         $SIG{KILL} = 'DEFAULT';     # as if it matters....
409
410         # catch the rest with a hopeful message
411         for (keys %SIG) {
412                 if (!$SIG{$_}) {
413                         #               dbg("Catching SIG $_") if isdbg('chan');
414                         $SIG{$_} = sub { my $sig = shift;       DXDebug::confess("Caught signal $sig");  }; 
415                 }
416         }
417 }
418
419 # start dupe system
420 DXDupe::init();
421
422 # read in system messages
423 DXM->init();
424
425 # read in command aliases
426 CmdAlias->init();
427
428 # initialise the Geomagnetic data engine
429 Geomag->init();
430 WCY->init();
431
432 # initial the Spot stuff
433 Spot->init();
434
435 # initialise the protocol engine
436 dbg("reading in duplicate spot and WWV info ...");
437 DXProt->init();
438
439 # put in a DXCluster node for us here so we can add users and take them away
440 $routeroot = Route::Node->new($mycall, $version*100+5300, Route::here($main::me->here)|Route::conf($main::me->conf));
441
442 # make sure that there is a routing OUTPUT node default file
443 #unless (Filter::read_in('route', 'node_default', 0)) {
444 #       my $dxcc = $main::me->dxcc;
445 #       $Route::filterdef->cmd($main::me, 'route', 'accept', "node_default call $mycall" );
446 #}
447
448 # read in any existing message headers and clean out old crap
449 dbg("reading existing message headers ...");
450 DXMsg->init();
451 DXMsg::clean_old();
452
453 # read in any cron jobs
454 dbg("reading cron jobs ...");
455 DXCron->init();
456
457 # read in database descriptors
458 dbg("reading database descriptors ...");
459 DXDb::load();
460
461 # starting local stuff
462 dbg("doing local initialisation ...");
463 eval {
464         Local::init();
465 };
466 dbg("Local::init error $@") if $@;
467
468 dbg("cleaning out old debug files");
469 DXDebug::dbgclean();
470
471 # print various flags
472 #dbg("seful info - \$^D: $^D \$^W: $^W \$^S: $^S \$^P: $^P");
473
474 # this, such as it is, is the main loop!
475 dbg("orft we jolly well go ...");
476 my $script = new Script "startup";
477 $script->run($main::me) if $script;
478
479 #open(DB::OUT, "|tee /tmp/aa");
480
481 for (;;) {
482 #       $DB::trace = 1;
483         
484         Msg->event_loop(10, 0.010);
485         my $timenow = time;
486         process_inqueue();                      # read in lines from the input queue and despatch them
487 #       $DB::trace = 0;
488         
489         # do timed stuff, ongoing processing happens one a second
490         if ($timenow != $systime) {
491                 reap if $zombies;
492                 $systime = $timenow;
493                 DXCron::process();      # do cron jobs
494                 DXCommandmode::process(); # process ongoing command mode stuff
495                 DXProt::process();              # process ongoing ak1a pcxx stuff
496                 QXProt::process();
497                 DXConnect::process();
498                 DXMsg::process();
499                 DXDb::process();
500                 DXUser::process();
501                 DXDupe::process();
502                 AGWMsg::process();
503                                 
504                 eval { 
505                         Local::process();       # do any localised processing
506                 };
507                 dbg("Local::process error $@") if $@;
508         }
509         if ($decease) {
510                 last if --$decease <= 0;
511         }
512 }
513 cease(0);
514 exit(0);
515
516