New improved route finding algorithm
[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 #
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 DXXml;
102 use DXSql;
103 use IsoTime;
104 use BPQMsg;
105
106 use Data::Dumper;
107 use IO::File;
108 use Fcntl ':flock';
109 use POSIX ":sys_wait_h";
110 use Version;
111
112 use Local;
113
114 package main;
115
116 use strict;
117 use vars qw(@inqueue $systime $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 $do_xml $systime_days $systime_daystart
121                         $can_encode
122                    );
123
124 @inqueue = ();                                  # the main input queue, an array of hashes
125 $systime = 0;                                   # the time now (in seconds)
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 # send a message to call on conn and disconnect
135 sub already_conn
136 {
137         my ($conn, $call, $mess) = @_;
138
139         $conn->disable_read(1);
140         dbg("-> D $call $mess\n") if isdbg('chan');
141         $conn->send_now("D$call|$mess");
142         sleep(2);
143         $conn->disconnect;
144 }
145
146 sub error_handler
147 {
148         my $dxchan = shift;
149         $dxchan->{conn}->set_error(undef) if exists $dxchan->{conn};
150         $dxchan->disconnect(1);
151 }
152
153 # handle incoming messages
154 sub new_channel
155 {
156         my ($conn, $msg) = @_;
157         my ($sort, $call, $line) = DXChannel::decode_input(0, $msg);
158         return unless defined $sort;
159
160         unless (is_callsign($call)) {
161                 already_conn($conn, $call, DXM::msg($lang, "illcall", $call));
162                 return;
163         }
164
165         # set up the basic channel info
166         # is there one already connected to me - locally?
167         my $user = DXUser::get_current($call);
168         my $dxchan = DXChannel::get($call);
169         if ($dxchan) {
170                 if ($user && $user->is_node) {
171                         already_conn($conn, $call, DXM::msg($lang, 'concluster', $call, $main::mycall));
172                         return;
173                 }
174                 if ($bumpexisting) {
175                         my $ip = $conn->{peerhost} || 'unknown';
176                         $dxchan->send_now('D', DXM::msg($lang, 'conbump', $call, $ip));
177                         LogDbg('DXCommand', "$call bumped off by $ip, disconnected");
178                         $dxchan->disconnect;
179                 } else {
180                         already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
181                         return;
182                 }
183         }
184
185         # is he locked out ?
186         my $basecall = $call;
187         $basecall =~ s/-\d+$//;
188         my $baseuser = DXUser::get_current($basecall);
189         my $lock = $user->lockout if $user;
190         if ($baseuser && $baseuser->lockout || $lock) {
191                 if (!$user || !defined $lock || $lock) {
192                         my $host = $conn->{peerhost} || "unknown";
193                         LogDbg('DXCommand', "$call on $host is locked out, disconnected");
194                         $conn->disconnect;
195                         return;
196                 }
197         }
198
199         if ($user) {
200                 $user->{lang} = $main::lang if !$user->{lang}; # to autoupdate old systems
201         } else {
202                 $user = DXUser->new($call);
203         }
204
205         # create the channel
206         if ($user->is_node) {
207                 $dxchan = DXProt->new($call, $conn, $user);
208         } elsif ($user->is_user) {
209                 $dxchan = DXCommandmode->new($call, $conn, $user);
210 #       } elsif ($user->is_bbs) {                                  # there is no support so
211 #               $dxchan = BBS->new($call, $conn, $user);               # don't allow it!!!
212         } else {
213                 die "Invalid sort of user on $call = $sort";
214         }
215
216         # check that the conn has a callsign
217         $conn->conns($call) if $conn->isa('IntMsg');
218
219         # set callbacks
220         $conn->set_error(sub {error_handler($dxchan)});
221         $conn->set_rproc(sub {my ($conn,$msg) = @_; $dxchan->rec($msg);});
222         $dxchan->rec($msg);
223 }
224
225
226 sub login
227 {
228         return \&new_channel;
229 }
230
231 # cease running this program, close down all the connections nicely
232 sub cease
233 {
234         my $dxchan;
235
236         unless ($is_win) {
237                 $SIG{'TERM'} = 'IGNORE';
238                 $SIG{'INT'} = 'IGNORE';
239         }
240
241         DXUser::sync;
242
243         if (defined &Local::finish) {
244                 eval {
245                         Local::finish();   # end local processing
246                 };
247                 dbg("Local::finish error $@") if $@;
248         }
249
250         # disconnect nodes
251         foreach $dxchan (DXChannel::get_all_nodes) {
252             $dxchan->disconnect(2) unless $dxchan == $main::me;
253         }
254         Msg->event_loop(100, 0.01);
255
256         # disconnect users
257         foreach $dxchan (DXChannel::get_all_users) {
258                 $dxchan->disconnect;
259         }
260
261         # disconnect AGW
262         AGWMsg::finish();
263         BPQMsg::finish();
264
265         # disconnect UDP customers
266         UDPMsg::finish();
267
268         # end everything else
269         Msg->event_loop(100, 0.01);
270         DXUser::finish();
271         DXDupe::finish();
272
273         # close all databases
274         DXDb::closeall;
275
276         # close all listeners
277         foreach my $l (@listeners) {
278                 $l->close_server;
279         }
280
281         LogDbg('cluster', "DXSpider V$version, build $subversion.$build ended");
282         dbgclose();
283         Logclose();
284
285         $dbh->finish if $dbh;
286
287         unlink $lockfn;
288 #       $SIG{__WARN__} = $SIG{__DIE__} =  sub {my $a = shift; cluck($a); };
289         exit(0);
290 }
291
292 # the reaper of children
293 sub reap
294 {
295         my $cpid;
296         while (($cpid = waitpid(-1, WNOHANG)) > 0) {
297                 dbg("cpid: $cpid") if isdbg('reap');
298 #               Msg->pid_gone($cpid);
299                 $zombies-- if $zombies > 0;
300         }
301         dbg("cpid: $cpid") if isdbg('reap');
302 }
303
304 # this is where the input queue is dealt with and things are dispatched off to other parts of
305 # the cluster
306
307 sub uptime
308 {
309         my $t = $systime - $starttime;
310         my $days = int $t / 86400;
311         $t -= $days * 86400;
312         my $hours = int $t / 3600;
313         $t -= $hours * 3600;
314         my $mins = int $t / 60;
315         return sprintf "%d %02d:%02d", $days, $hours, $mins;
316 }
317
318 sub AGWrestart
319 {
320         AGWMsg::init(\&new_channel);
321 }
322
323 #############################################################
324 #
325 # The start of the main line of code
326 #
327 #############################################################
328
329 $starttime = $systime = time;
330 $systime_days = int ($systime / 86400);
331 $systime_daystart = $systime_days * 86400;
332 $lang = 'en' unless $lang;
333
334 unless ($DB::VERSION) {
335         $SIG{INT} = $SIG{TERM} = \&cease;
336 }
337
338 # open the debug file, set various FHs to be unbuffered
339 dbginit(\&DXCommandmode::broadcast_debug);
340 foreach (@debug) {
341         dbgadd($_);
342 }
343 STDOUT->autoflush(1);
344
345 # try to load the database
346 if (DXSql::init($dsn)) {
347         $dbh = DXSql->new($dsn);
348         $dbh = $dbh->connect($dsn, $dbuser, $dbpass) if $dbh;
349 }
350
351 # try to load Encode
352 {
353         local $^W = 0;
354         my $w = $SIG{__DIE__};
355         $SIG{__DIE__} = 'IGNORE';
356         eval { require Encode; };
357         unless ($@) {
358                 import Encode;
359                 $can_encode = 1;
360         }
361         $SIG{__DIE__} = $w;
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 $subversion.$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("BPQ Listener") if $BPQMsg::enable;
416 BPQMsg::init(\&new_channel);
417
418 dbg("UDP Listener") if $UDPMsg::enable;
419 UDPMsg::init(\&new_channel);
420
421 # load bad words
422 dbg("load badwords: " . (BadWords::load or "Ok"));
423
424 # prime some signals
425 unless ($DB::VERSION) {
426         $SIG{INT} = $SIG{TERM} = sub { $decease = 1 };
427 }
428
429 unless ($is_win) {
430         $SIG{HUP} = 'IGNORE';
431         $SIG{CHLD} = sub { $zombies++ };
432
433         $SIG{PIPE} = sub {      dbg("Broken PIPE signal received"); };
434         $SIG{IO} = sub {        dbg("SIGIO received"); };
435         $SIG{WINCH} = $SIG{STOP} = $SIG{CONT} = 'IGNORE';
436         $SIG{KILL} = 'DEFAULT';     # as if it matters....
437
438         # catch the rest with a hopeful message
439         for (keys %SIG) {
440                 if (!$SIG{$_}) {
441                         #               dbg("Catching SIG $_") if isdbg('chan');
442                         $SIG{$_} = sub { my $sig = shift;       DXDebug::confess("Caught signal $sig");  };
443                 }
444         }
445 }
446
447 # start dupe system
448 dbg("Starting Dupe system");
449 DXDupe::init();
450
451 # read in system messages
452 dbg("Read in Messages");
453 DXM->init();
454
455 # read in command aliases
456 dbg("Read in Aliases");
457 CmdAlias->init();
458
459 # initialise the Geomagnetic data engine
460 dbg("Start WWV");
461 Geomag->init();
462 dbg("Start WCY");
463 WCY->init();
464
465 # initial the Spot stuff
466 dbg("Starting DX Spot system");
467 Spot->init();
468
469 # initialise the protocol engine
470 dbg("Start Protocol Engines ...");
471 DXProt->init();
472
473 # put in a DXCluster node for us here so we can add users and take them away
474 $routeroot = Route::Node->new($mycall, $version*100+5300, Route::here($main::me->here)|Route::conf($main::me->conf));
475 $routeroot->do_pc9x(1);
476 $routeroot->via_pc92(1);
477
478 # make sure that there is a routing OUTPUT node default file
479 #unless (Filter::read_in('route', 'node_default', 0)) {
480 #       my $dxcc = $main::me->dxcc;
481 #       $Route::filterdef->cmd($main::me, 'route', 'accept', "node_default call $mycall" );
482 #}
483
484 # read in any existing message headers and clean out old crap
485 dbg("reading existing message headers ...");
486 DXMsg->init();
487 DXMsg::clean_old();
488
489 # read in any cron jobs
490 dbg("reading cron jobs ...");
491 DXCron->init();
492
493 # read in database desriptors
494 dbg("reading database descriptors ...");
495 DXDb::load();
496
497 # starting local stuff
498 dbg("doing local initialisation ...");
499 QSL::init(1);
500 if (defined &Local::init) {
501         eval {
502                 Local::init();
503         };
504         dbg("Local::init error $@") if $@;
505 }
506
507
508 # this, such as it is, is the main loop!
509 dbg("orft we jolly well go ...");
510 my $script = new Script "startup";
511 $script->run($main::me) if $script;
512
513 #open(DB::OUT, "|tee /tmp/aa");
514
515 for (;;) {
516 #       $DB::trace = 1;
517
518         Msg->event_loop(10, 0.010);
519         my $timenow = time;
520
521         DXChannel::process();
522
523 #       $DB::trace = 0;
524
525         # do timed stuff, ongoing processing happens one a second
526         if ($timenow != $systime) {
527                 reap() if $zombies;
528                 $systime = $timenow;
529                 my $days = int ($systime / 86400);
530                 if ($systime_days != $days) {
531                         $systime_days = $days;
532                         $systime_daystart = $days * 86400;
533                 }
534                 IsoTime::update($systime);
535                 DXCron::process();      # do cron jobs
536                 DXCommandmode::process(); # process ongoing command mode stuff
537                 DXXml::process();
538                 DXProt::process();              # process ongoing ak1a pcxx stuff
539                 DXConnect::process();
540                 DXMsg::process();
541                 DXDb::process();
542                 DXUser::process();
543                 DXDupe::process();
544                 AGWMsg::process();
545                 BPQMsg::process();
546
547                 if (defined &Local::process) {
548                         eval {
549                                 Local::process();       # do any localised processing
550                         };
551                         dbg("Local::process error $@") if $@;
552                 }
553         }
554         if ($decease) {
555                 last if --$decease <= 0;
556         }
557 }
558 cease(0);
559 exit(0);
560
561