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