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