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