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