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