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