reduce offset
[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 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 use Mrtg;
99 use USDB;
100 use UDPMsg;
101 use QSL;
102 use Thingy;
103 use RouteDB;
104
105 use Data::Dumper;
106 use IO::File;
107 use Fcntl ':flock'; 
108 use POSIX ":sys_wait_h";
109
110 use Local;
111
112 package main;
113
114 use strict;
115 use vars qw(@inqueue $systime $version $starttime $lockfn @outstanding_connects 
116                         $zombies $root @listeners $lang $myalias @debug $userfn $clusteraddr 
117                         $clusterport $mycall $decease $is_win $routeroot $me $reqreg
118                    );
119
120 @inqueue = ();                                  # the main input queue, an array of hashes
121 $systime = 0;                                   # the time now (in seconds)
122 $version = "1.51";                              # the version no of the software
123 $starttime = 0;                 # the starting time of the cluster   
124 #@outstanding_connects = ();     # list of outstanding connects
125 @listeners = ();                                # list of listeners
126 $reqreg = 0;                                    # 1 = registration required, 2 = deregister people
127
128 use vars qw($VERSION $BRANCH $build $branch);
129 $VERSION = sprintf( "%d.%03d", q$Revision$ =~ /(\d+)\.(\d+)/ );
130 $BRANCH = sprintf( "%d.%03d", q$Revision$ =~ /\d+\.\d+\.(\d+)\.(\d+)/  || (0,0));
131 $main::build += 3;                              # add an offset to make it bigger than last system
132 $main::build += $VERSION;
133 $main::branch += $BRANCH;
134
135       
136 # send a message to call on conn and disconnect
137 sub already_conn
138 {
139         my ($conn, $call, $mess) = @_;
140
141         $conn->disable_read(1);
142         dbg("-> D $call $mess\n") if isdbg('chan'); 
143         $conn->send_now("D$call|$mess");
144         sleep(2);
145         $conn->disconnect;
146 }
147
148 sub error_handler
149 {
150         my $dxchan = shift;
151         $dxchan->{conn}->set_error(undef) if exists $dxchan->{conn};
152         $dxchan->disconnect(1);
153 }
154
155 # handle incoming messages
156 sub new_channel
157 {
158         my ($conn, $msg) = @_;
159         my ($sort, $call, $line) = DXChannel::decode_input(0, $msg);
160         return unless defined $sort;
161
162         unless (is_callsign($call)) {
163                 already_conn($conn, $call, DXM::msg($lang, "illcall", $call));
164                 return;
165         }
166
167         # set up the basic channel info
168         # is there one already connected to me - locally? 
169         my $user = DXUser->get_current($call);
170         my $dxchan = DXChannel->get($call);
171         if ($dxchan) {
172                 my $mess = DXM::msg($lang, ($user && $user->is_node) ? 'concluster' : 'conother', $call, $main::mycall);
173                 already_conn($conn, $call, $mess);
174                 return;
175         }
176
177         # is he locked out ?
178         my $basecall = $call;
179         $basecall =~ s/-\d+$//;
180         my $baseuser = DXUser->get_current($basecall);
181         my $lock = $user->lockout if $user;
182         if ($baseuser && $baseuser->lockout || $lock) {
183                 if (!$user || !defined $lock || $lock) {
184                         my $host = $conn->{peerhost} || "unknown";
185                         Log('DXCommand', "$call on $host is locked out, disconnected");
186                         $conn->disconnect;
187                         return;
188                 }
189         }
190         
191         if ($user) {
192                 $user->{lang} = $main::lang if !$user->{lang}; # to autoupdate old systems
193         } else {
194                 $user = DXUser->new($call);
195         }
196         
197
198         # create the channel
199         if ($user->wantnp) {
200                 if ($user->passphrase && $main::me->user->passphrase) {
201                         $dxchan = QXProt->new($call, $conn, $user);
202                 } else {
203                         unless ($user->passphrase) {
204                                 Log('DXCommand', "$call using NP but has no passphrase");
205                                 dbg("$call using NP but has no passphrase");
206                         }
207                         unless ($main::me->user->passphrase) {
208                                 Log('DXCommand', "$main::mycall using NP but has no passphrase");
209                                 dbg("$main::mycall using NP but has no passphrase");
210                         }
211                         already_conn($conn, $call, "Need to exchange passphrases");
212                         return;
213                 }
214         } elsif ($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) = @_; rec($dxchan, $conn, $msg);});
230         rec($dxchan, $conn, $msg);
231 }
232
233 sub rec 
234 {
235         my ($dxchan, $conn, $msg) = @_;
236         
237         # queue the message and the channel object for later processing
238         if (defined $msg) {
239                 my $self = bless {}, "inqueue";
240                 $self->{dxchan} = $dxchan;
241                 $self->{data} = $msg;
242                 push @inqueue, $self;
243         }
244 }
245
246 # remove any outstanding entries on the inqueue after a disconnection (usually)
247 sub clean_inqueue
248 {
249         my $dxchan = shift;
250         @inqueue = grep {$_->{dxchan} != $dxchan} @inqueue;
251 }
252
253 sub login
254 {
255         return \&new_channel;
256 }
257
258 # cease running this program, close down all the connections nicely
259 sub cease
260 {
261         my $dxchan;
262
263         unless ($is_win) {
264                 $SIG{'TERM'} = 'IGNORE';
265                 $SIG{'INT'} = 'IGNORE';
266         }
267         
268         DXUser::sync;
269
270         eval {
271                 Local::finish();   # end local processing
272         };
273         dbg("Local::finish error $@") if $@;
274
275         # disconnect nodes
276         foreach $dxchan (DXChannel->get_all_nodes) {
277             $dxchan->disconnect(2) unless $dxchan == $main::me;
278         }
279         Msg->event_loop(100, 0.01);
280
281         # disconnect users
282         foreach $dxchan (DXChannel->get_all_users) {
283                 $dxchan->disconnect;
284         }
285
286         # disconnect AGW
287         AGWMsg::finish();
288
289         # disconnect UDP customers
290         UDPMsg::finish();
291
292         # end everything else
293         Msg->event_loop(100, 0.01);
294         DXUser::finish();
295         DXDupe::finish();
296
297         # close all databases
298         DXDb::closeall;
299
300         # close all listeners
301         foreach my $l (@listeners) {
302                 $l->close_server;
303         }
304
305         dbg("DXSpider version $version, build $build ended") if isdbg('chan');
306         Log('cluster', "DXSpider V$version, build $build ended");
307         dbgclose();
308         Logclose();
309         unlink $lockfn;
310 #       $SIG{__WARN__} = $SIG{__DIE__} =  sub {my $a = shift; cluck($a); };
311         exit(0);
312 }
313
314 # the reaper of children
315 sub reap
316 {
317         my $cpid;
318         while (($cpid = waitpid(-1, WNOHANG)) > 0) {
319                 dbg("cpid: $cpid") if isdbg('reap');
320 #               Msg->pid_gone($cpid);
321                 $zombies-- if $zombies > 0;
322         }
323         dbg("cpid: $cpid") if isdbg('reap');
324 }
325
326 # this is where the input queue is dealt with and things are dispatched off to other parts of
327 # the cluster
328 sub process_inqueue
329 {
330         while (@inqueue) {
331                 my $self = shift @inqueue;
332                 return if !$self;
333
334                 my $data = $self->{data};
335                 my $dxchan = $self->{dxchan};
336                 my $error;
337                 my ($sort, $call, $line) = DXChannel::decode_input($dxchan, $data);
338                 return unless defined $sort;
339         
340                 # do the really sexy console interface bit! (Who is going to do the TK interface then?)
341                 dbg("<- $sort $call $line") if $sort ne 'D' && isdbg('chan');
342                 if ($self->{disconnecting}) {
343                         dbg('In disconnection, ignored');
344                         next;
345                 }
346                 
347                 # handle A records
348                 my $user = $dxchan->user;
349                 if ($sort eq 'A' || $sort eq 'O') {
350                         $dxchan->start($line, $sort);  
351                 } elsif ($sort eq 'I') {
352                         die "\$user not defined for $call" if !defined $user;
353
354                         # normal input
355                         $dxchan->normal($line);
356                 } elsif ($sort eq 'Z') {
357                         $dxchan->disconnect;
358                 } elsif ($sort eq 'D') {
359                         ;                                       # ignored (an echo)
360                 } elsif ($sort eq 'G') {
361                         $dxchan->enhanced($line);
362                 } else {
363                         print STDERR atime, " Unknown command letter ($sort) received from $call\n";
364                 }
365         }
366 }
367
368 sub uptime
369 {
370         my $t = $systime - $starttime;
371         my $days = int $t / 86400;
372         $t -= $days * 86400;
373         my $hours = int $t / 3600;
374         $t -= $hours * 3600;
375         my $mins = int $t / 60;
376         return sprintf "%d %02d:%02d", $days, $hours, $mins;
377 }
378
379 sub AGWrestart
380 {
381         AGWMsg::init(\&new_channel);
382 }
383
384 #############################################################
385 #
386 # The start of the main line of code 
387 #
388 #############################################################
389
390 $starttime = $systime = time;
391 $lang = 'en' unless $lang;
392
393 # open the debug file, set various FHs to be unbuffered
394 dbginit(\&DXCommandmode::broadcast_debug);
395 foreach (@debug) {
396         dbgadd($_);
397 }
398 STDOUT->autoflush(1);
399
400 # calculate build number
401 $build += $main::version;
402 $build = "$build.$branch" if $branch;
403
404 Log('cluster', "DXSpider V$version, build $build started");
405
406 # banner
407 dbg("Copyright (c) 1998-2002 Dirk Koopman G1TLH");
408 dbg("DXSpider Version $version, build $build started");
409
410 # load Prefixes
411 dbg("loading prefixes ...");
412 dbg(USDB::init());
413 my $r = Prefix::init();
414 confess $r if $r;
415
416 # load band data
417 dbg("loading band data ...");
418 Bands::load();
419
420 # initialise User file system
421 dbg("loading user file system ..."); 
422 DXUser->init($userfn, 1);
423
424 # look for the sysop and the alias user and complain if they aren't there
425 {
426         my $ref = DXUser->get($mycall);
427         die "$mycall missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
428         $ref = DXUser->get($myalias);
429         die "$myalias missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
430 }
431
432 # start listening for incoming messages/connects
433 dbg("starting listeners ...");
434 my $conn = IntMsg->new_server($clusteraddr, $clusterport, \&login);
435 $conn->conns("Server $clusteraddr/$clusterport");
436 push @listeners, $conn;
437 dbg("Internal port: $clusteraddr $clusterport");
438 foreach my $l (@main::listen) {
439         $conn = ExtMsg->new_server($l->[0], $l->[1], \&login);
440         $conn->conns("Server $l->[0]/$l->[1]");
441         push @listeners, $conn;
442         dbg("External Port: $l->[0] $l->[1]");
443 }
444
445 dbg("AGW Listener") if $AGWMsg::enable;
446 AGWrestart();
447
448 dbg("UDP Listener") if $UDPMsg::enable;
449 UDPMsg::init(\&new_channel);
450
451 # load bad words
452 dbg("load badwords: " . (BadWords::load or "Ok"));
453
454 # prime some signals
455 unless ($DB::VERSION) {
456         $SIG{INT} = $SIG{TERM} = sub { $decease = 1 };
457 }
458
459 unless ($is_win) {
460         $SIG{HUP} = 'IGNORE';
461         $SIG{CHLD} = sub { $zombies++ };
462         
463         $SIG{PIPE} = sub {      dbg("Broken PIPE signal received"); };
464         $SIG{IO} = sub {        dbg("SIGIO received"); };
465         $SIG{WINCH} = $SIG{STOP} = $SIG{CONT} = 'IGNORE';
466         $SIG{KILL} = 'DEFAULT';     # as if it matters....
467
468         # catch the rest with a hopeful message
469         for (keys %SIG) {
470                 if (!$SIG{$_}) {
471                         #               dbg("Catching SIG $_") if isdbg('chan');
472                         $SIG{$_} = sub { my $sig = shift;       DXDebug::confess("Caught signal $sig");  }; 
473                 }
474         }
475 }
476
477 # start dupe system
478 dbg("Starting Dupe system");
479 DXDupe::init();
480
481 # read in system messages
482 dbg("Read in Messages");
483 DXM->init();
484
485 # read in command aliases
486 dbg("Read in Aliases");
487 CmdAlias->init();
488
489 # initialise the Geomagnetic data engine
490 dbg("Start WWV");
491 Geomag->init();
492 dbg("Start WCY");
493 WCY->init();
494
495 # initial the Spot stuff
496 dbg("Starting DX Spot system");
497 Spot->init();
498
499 # initialise the protocol engine
500 dbg("Start Protocol Engines ...");
501 DXProt->init();
502 QXProt->init();
503
504 # put in a DXCluster node for us here so we can add users and take them away
505 $routeroot = Route::Node->new($mycall, $version*100+5300, Route::here($main::me->here)|Route::conf($main::me->conf));
506
507 # make sure that there is a routing OUTPUT node default file
508 #unless (Filter::read_in('route', 'node_default', 0)) {
509 #       my $dxcc = $main::me->dxcc;
510 #       $Route::filterdef->cmd($main::me, 'route', 'accept', "node_default call $mycall" );
511 #}
512
513 # read in any existing message headers and clean out old crap
514 dbg("reading existing message headers ...");
515 DXMsg->init();
516 DXMsg::clean_old();
517
518 # read in any cron jobs
519 dbg("reading cron jobs ...");
520 DXCron->init();
521
522 # read in database descriptors
523 dbg("reading database descriptors ...");
524 DXDb::load();
525
526 # starting local stuff
527 dbg("doing local initialisation ...");
528 QSL::init(1);
529 eval {
530         Local::init();
531 };
532 dbg("Local::init error $@") if $@;
533
534 # this, such as it is, is the main loop!
535 dbg("orft we jolly well go ...");
536 my $script = new Script "startup";
537 $script->run($main::me) if $script;
538
539 #open(DB::OUT, "|tee /tmp/aa");
540
541 for (;;) {
542 #       $DB::trace = 1;
543         
544         Msg->event_loop(10, 0.010);
545         my $timenow = time;
546         process_inqueue();                      # read in lines from the input queue and despatch them
547 #       $DB::trace = 0;
548         
549         # do timed stuff, ongoing processing happens one a second
550         if ($timenow != $systime) {
551                 reap if $zombies;
552                 $systime = $timenow;
553                 DXCron::process();      # do cron jobs
554                 DXCommandmode::process(); # process ongoing command mode stuff
555                 DXProt::process();              # process ongoing ak1a pcxx stuff
556                 QXProt::process();
557                 DXConnect::process();
558                 DXMsg::process();
559                 DXDb::process();
560                 DXUser::process();
561                 DXDupe::process();
562                 AGWMsg::process();
563
564                 # this where things really start to happen (in DXSpider 2)
565                 Thingy::process();
566                 
567                 eval { 
568                         Local::process();       # do any localised processing
569                 };
570                 dbg("Local::process error $@") if $@;
571         }
572         if ($decease) {
573                 last if --$decease <= 0;
574         }
575 }
576 cease(0);
577 exit(0);
578
579