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