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