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