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