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