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