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