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