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