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