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