disable use of DBI for sh/dx as default, if active.
[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 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 $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) {
211                 $dxchan = BBS->new($call, $conn, $user);
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         eval {
244                 Local::finish();   # end local processing
245         };
246         dbg("Local::finish error $@") if $@;
247
248         # disconnect nodes
249         foreach $dxchan (DXChannel::get_all_nodes) {
250             $dxchan->disconnect(2) unless $dxchan == $main::me;
251         }
252         Msg->event_loop(100, 0.01);
253
254         # disconnect users
255         foreach $dxchan (DXChannel::get_all_users) {
256                 $dxchan->disconnect;
257         }
258
259         # disconnect AGW
260         AGWMsg::finish();
261
262         # disconnect UDP customers
263         UDPMsg::finish();
264
265         # end everything else
266         Msg->event_loop(100, 0.01);
267         DXUser::finish();
268         DXDupe::finish();
269
270         # close all databases
271         DXDb::closeall;
272
273         # close all listeners
274         foreach my $l (@listeners) {
275                 $l->close_server;
276         }
277
278         LogDbg('cluster', "DXSpider V$version, build $subversion.$build ended");
279         dbgclose();
280         Logclose();
281
282         $dbh->finish if $dbh;
283
284         unlink $lockfn;
285 #       $SIG{__WARN__} = $SIG{__DIE__} =  sub {my $a = shift; cluck($a); };
286         exit(0);
287 }
288
289 # the reaper of children
290 sub reap
291 {
292         my $cpid;
293         while (($cpid = waitpid(-1, WNOHANG)) > 0) {
294                 dbg("cpid: $cpid") if isdbg('reap');
295 #               Msg->pid_gone($cpid);
296                 $zombies-- if $zombies > 0;
297         }
298         dbg("cpid: $cpid") if isdbg('reap');
299 }
300
301 # this is where the input queue is dealt with and things are dispatched off to other parts of
302 # the cluster
303
304 sub uptime
305 {
306         my $t = $systime - $starttime;
307         my $days = int $t / 86400;
308         $t -= $days * 86400;
309         my $hours = int $t / 3600;
310         $t -= $hours * 3600;
311         my $mins = int $t / 60;
312         return sprintf "%d %02d:%02d", $days, $hours, $mins;
313 }
314
315 sub AGWrestart
316 {
317         AGWMsg::init(\&new_channel);
318 }
319
320 #############################################################
321 #
322 # The start of the main line of code
323 #
324 #############################################################
325
326 $starttime = $systime = time;
327 $systime_days = int ($systime / 86400);
328 $systime_daystart = $systime_days * 86400;
329 $lang = 'en' unless $lang;
330
331 unless ($DB::VERSION) {
332         $SIG{INT} = $SIG{TERM} = \&cease;
333 }
334
335 # open the debug file, set various FHs to be unbuffered
336 dbginit(\&DXCommandmode::broadcast_debug);
337 foreach (@debug) {
338         dbgadd($_);
339 }
340 STDOUT->autoflush(1);
341
342 # try to load the database
343 if (DXSql::init($dsn)) {
344         $dbh = DXSql->new($dsn);
345         $dbh = $dbh->connect($dsn, $dbuser, $dbpass) if $dbh;
346 }
347
348 # try to load Encode
349 {
350         local $^W = 0;
351         my $w = $SIG{__DIE__};
352         $SIG{__DIE__} = 'IGNORE';
353         eval { require Encode; };
354         unless ($@) {
355                 import Encode;
356                 $can_encode = 1;
357         }
358         $SIG{__DIE__} = $w;
359 }
360
361 # try to load XML::Simple
362 DXXml::init();
363
364 # banner
365 my ($year) = (gmtime)[5];
366 $year += 1900;
367 LogDbg('cluster', "DXSpider V$version, build $subversion.$build started");
368 dbg("Copyright (c) 1998-$year Dirk Koopman G1TLH");
369
370 # load Prefixes
371 dbg("loading prefixes ...");
372 dbg(USDB::init());
373 my $r = Prefix::init();
374 confess $r if $r;
375
376 # load band data
377 dbg("loading band data ...");
378 Bands::load();
379
380 # initialise User file system
381 dbg("loading user file system ...");
382 DXUser->init($userfn, 1);
383
384 # look for the sysop and the alias user and complain if they aren't there
385 {
386         my $ref = DXUser->get($mycall);
387         die "$mycall missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
388         $ref = DXUser->get($myalias);
389         die "$myalias missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
390 }
391
392 # start listening for incoming messages/connects
393 dbg("starting listeners ...");
394 my $conn = IntMsg->new_server($clusteraddr, $clusterport, \&login);
395 $conn->conns("Server $clusteraddr/$clusterport using IntMsg");
396 push @listeners, $conn;
397 dbg("Internal port: $clusteraddr $clusterport using IntMsg");
398 foreach my $l (@main::listen) {
399         no strict 'refs';
400         my $pkg = $l->[2] || 'ExtMsg';
401         my $login = $l->[3] || 'login';
402
403         $conn = $pkg->new_server($l->[0], $l->[1], \&{"${pkg}::${login}"});
404         $conn->conns("Server $l->[0]/$l->[1] using ${pkg}::${login}");
405         push @listeners, $conn;
406         dbg("External Port: $l->[0] $l->[1] using ${pkg}::${login}");
407 }
408
409 dbg("AGW Listener") if $AGWMsg::enable;
410 AGWrestart();
411
412 dbg("UDP Listener") if $UDPMsg::enable;
413 UDPMsg::init(\&new_channel);
414
415 # load bad words
416 dbg("load badwords: " . (BadWords::load or "Ok"));
417
418 # prime some signals
419 unless ($DB::VERSION) {
420         $SIG{INT} = $SIG{TERM} = sub { $decease = 1 };
421 }
422
423 unless ($is_win) {
424         $SIG{HUP} = 'IGNORE';
425         $SIG{CHLD} = sub { $zombies++ };
426
427         $SIG{PIPE} = sub {      dbg("Broken PIPE signal received"); };
428         $SIG{IO} = sub {        dbg("SIGIO received"); };
429         $SIG{WINCH} = $SIG{STOP} = $SIG{CONT} = 'IGNORE';
430         $SIG{KILL} = 'DEFAULT';     # as if it matters....
431
432         # catch the rest with a hopeful message
433         for (keys %SIG) {
434                 if (!$SIG{$_}) {
435                         #               dbg("Catching SIG $_") if isdbg('chan');
436                         $SIG{$_} = sub { my $sig = shift;       DXDebug::confess("Caught signal $sig");  };
437                 }
438         }
439 }
440
441 # start dupe system
442 dbg("Starting Dupe system");
443 DXDupe::init();
444
445 # read in system messages
446 dbg("Read in Messages");
447 DXM->init();
448
449 # read in command aliases
450 dbg("Read in Aliases");
451 CmdAlias->init();
452
453 # initialise the Geomagnetic data engine
454 dbg("Start WWV");
455 Geomag->init();
456 dbg("Start WCY");
457 WCY->init();
458
459 # initial the Spot stuff
460 dbg("Starting DX Spot system");
461 Spot->init();
462
463 # initialise the protocol engine
464 dbg("Start Protocol Engines ...");
465 DXProt->init();
466
467 # put in a DXCluster node for us here so we can add users and take them away
468 $routeroot = Route::Node->new($mycall, $version*100+5300, Route::here($main::me->here)|Route::conf($main::me->conf));
469 $routeroot->do_pc9x(1);
470 $routeroot->via_pc92(1);
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 desriptors
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                 my $days = int ($systime / 86400);
521                 if ($systime_days != $days) {
522                         $systime_days = $days;
523                         $systime_daystart = $days * 86400;
524                 }
525                 IsoTime::update($systime);
526                 DXCron::process();      # do cron jobs
527                 DXCommandmode::process(); # process ongoing command mode stuff
528                 DXXml::process();
529                 DXProt::process();              # process ongoing ak1a pcxx stuff
530                 DXConnect::process();
531                 DXMsg::process();
532                 DXDb::process();
533                 DXUser::process();
534                 DXDupe::process();
535                 AGWMsg::process();
536
537                 eval {
538                         Local::process();       # do any localised processing
539                 };
540                 dbg("Local::process error $@") if $@;
541         }
542         if ($decease) {
543                 last if --$decease <= 0;
544         }
545 }
546 cease(0);
547 exit(0);
548
549