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