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