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