Change DXUser->get* to DXUser::get*
[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 use BPQMsg;
106
107 use Data::Dumper;
108 use IO::File;
109 use Fcntl ':flock';
110 use POSIX ":sys_wait_h";
111 use Version;
112
113 use Local;
114
115 package main;
116
117 use strict;
118 use vars qw(@inqueue $systime $starttime $lockfn @outstanding_connects
119                         $zombies $root @listeners $lang $myalias @debug $userfn $clusteraddr
120                         $clusterport $mycall $decease $is_win $routeroot $me $reqreg $bumpexisting
121                         $allowdxby $dbh $dsn $dbuser $dbpass $do_xml $systime_days $systime_daystart
122                         $can_encode
123                    );
124
125 @inqueue = ();                                  # the main input queue, an array of hashes
126 $systime = 0;                                   # the time now (in seconds)
127 $starttime = 0;                 # the starting time of the cluster
128 @outstanding_connects = ();     # list of outstanding connects
129 @listeners = ();                                # list of listeners
130 $reqreg = 0;                                    # 1 = registration required, 2 = deregister people
131 $bumpexisting = 1;                              # 1 = allow new connection to disconnect old, 0 - don't allow it
132 $allowdxby = 0;                                 # 1 = allow "dx by <othercall>", 0 - don't allow it
133
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) {                                  # there is no support so
212 #               $dxchan = BBS->new($call, $conn, $user);               # don't allow it!!!
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         if (defined &Local::finish) {
245                 eval {
246                         Local::finish();   # end local processing
247                 };
248                 dbg("Local::finish error $@") if $@;
249         }
250
251         # disconnect nodes
252         foreach $dxchan (DXChannel::get_all_nodes) {
253             $dxchan->disconnect(2) unless $dxchan == $main::me;
254         }
255         Msg->event_loop(100, 0.01);
256
257         # disconnect users
258         foreach $dxchan (DXChannel::get_all_users) {
259                 $dxchan->disconnect;
260         }
261
262         # disconnect AGW
263         AGWMsg::finish();
264         BPQMsg::finish();
265
266         # disconnect UDP customers
267         UDPMsg::finish();
268
269         # end everything else
270         Msg->event_loop(100, 0.01);
271         DXUser::finish();
272         DXDupe::finish();
273
274         # close all databases
275         DXDb::closeall;
276
277         # close all listeners
278         foreach my $l (@listeners) {
279                 $l->close_server;
280         }
281
282         LogDbg('cluster', "DXSpider V$version, build $subversion.$build ended");
283         dbgclose();
284         Logclose();
285
286         $dbh->finish if $dbh;
287
288         unlink $lockfn;
289 #       $SIG{__WARN__} = $SIG{__DIE__} =  sub {my $a = shift; cluck($a); };
290         exit(0);
291 }
292
293 # the reaper of children
294 sub reap
295 {
296         my $cpid;
297         while (($cpid = waitpid(-1, WNOHANG)) > 0) {
298                 dbg("cpid: $cpid") if isdbg('reap');
299 #               Msg->pid_gone($cpid);
300                 $zombies-- if $zombies > 0;
301         }
302         dbg("cpid: $cpid") if isdbg('reap');
303 }
304
305 # this is where the input queue is dealt with and things are dispatched off to other parts of
306 # the cluster
307
308 sub uptime
309 {
310         my $t = $systime - $starttime;
311         my $days = int $t / 86400;
312         $t -= $days * 86400;
313         my $hours = int $t / 3600;
314         $t -= $hours * 3600;
315         my $mins = int $t / 60;
316         return sprintf "%d %02d:%02d", $days, $hours, $mins;
317 }
318
319 sub AGWrestart
320 {
321         AGWMsg::init(\&new_channel);
322 }
323
324 #############################################################
325 #
326 # The start of the main line of code
327 #
328 #############################################################
329
330 $starttime = $systime = time;
331 $systime_days = int ($systime / 86400);
332 $systime_daystart = $systime_days * 86400;
333 $lang = 'en' unless $lang;
334
335 unless ($DB::VERSION) {
336         $SIG{INT} = $SIG{TERM} = \&cease;
337 }
338
339 # open the debug file, set various FHs to be unbuffered
340 dbginit(\&DXCommandmode::broadcast_debug);
341 foreach (@debug) {
342         dbgadd($_);
343 }
344 STDOUT->autoflush(1);
345
346 # try to load the database
347 if (DXSql::init($dsn)) {
348         $dbh = DXSql->new($dsn);
349         $dbh = $dbh->connect($dsn, $dbuser, $dbpass) if $dbh;
350 }
351
352 # try to load Encode
353 {
354         local $^W = 0;
355         my $w = $SIG{__DIE__};
356         $SIG{__DIE__} = 'IGNORE';
357         eval { require Encode; };
358         unless ($@) {
359                 import Encode;
360                 $can_encode = 1;
361         }
362         $SIG{__DIE__} = $w;
363 }
364
365 # try to load XML::Simple
366 DXXml::init();
367
368 # banner
369 my ($year) = (gmtime)[5];
370 $year += 1900;
371 LogDbg('cluster', "DXSpider V$version, build $subversion.$build started");
372 dbg("Copyright (c) 1998-$year Dirk Koopman G1TLH");
373
374 # load Prefixes
375 dbg("loading prefixes ...");
376 dbg(USDB::init());
377 my $r = Prefix::init();
378 confess $r if $r;
379
380 # load band data
381 dbg("loading band data ...");
382 Bands::load();
383
384 # initialise User file system
385 dbg("loading user file system ...");
386 DXUser->init($userfn, 1);
387
388 # look for the sysop and the alias user and complain if they aren't there
389 {
390         my $ref = DXUser::get($mycall);
391         die "$mycall missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
392         $ref = DXUser::get($myalias);
393         die "$myalias missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
394 }
395
396 # start listening for incoming messages/connects
397 dbg("starting listeners ...");
398 my $conn = IntMsg->new_server($clusteraddr, $clusterport, \&login);
399 $conn->conns("Server $clusteraddr/$clusterport using IntMsg");
400 push @listeners, $conn;
401 dbg("Internal port: $clusteraddr $clusterport using IntMsg");
402 foreach my $l (@main::listen) {
403         no strict 'refs';
404         my $pkg = $l->[2] || 'ExtMsg';
405         my $login = $l->[3] || 'login';
406
407         $conn = $pkg->new_server($l->[0], $l->[1], \&{"${pkg}::${login}"});
408         $conn->conns("Server $l->[0]/$l->[1] using ${pkg}::${login}");
409         push @listeners, $conn;
410         dbg("External Port: $l->[0] $l->[1] using ${pkg}::${login}");
411 }
412
413 dbg("AGW Listener") if $AGWMsg::enable;
414 AGWrestart();
415
416 dbg("BPQ Listener") if $BPQMsg::enable;
417 BPQMsg::init(\&new_channel);
418
419 dbg("UDP Listener") if $UDPMsg::enable;
420 UDPMsg::init(\&new_channel);
421
422 # load bad words
423 dbg("load badwords: " . (BadWords::load or "Ok"));
424
425 # prime some signals
426 unless ($DB::VERSION) {
427         $SIG{INT} = $SIG{TERM} = sub { $decease = 1 };
428 }
429
430 unless ($is_win) {
431         $SIG{HUP} = 'IGNORE';
432         $SIG{CHLD} = sub { $zombies++ };
433
434         $SIG{PIPE} = sub {      dbg("Broken PIPE signal received"); };
435         $SIG{IO} = sub {        dbg("SIGIO received"); };
436         $SIG{WINCH} = $SIG{STOP} = $SIG{CONT} = 'IGNORE';
437         $SIG{KILL} = 'DEFAULT';     # as if it matters....
438
439         # catch the rest with a hopeful message
440         for (keys %SIG) {
441                 if (!$SIG{$_}) {
442                         #               dbg("Catching SIG $_") if isdbg('chan');
443                         $SIG{$_} = sub { my $sig = shift;       DXDebug::confess("Caught signal $sig");  };
444                 }
445         }
446 }
447
448 # start dupe system
449 dbg("Starting Dupe system");
450 DXDupe::init();
451
452 # read in system messages
453 dbg("Read in Messages");
454 DXM->init();
455
456 # read in command aliases
457 dbg("Read in Aliases");
458 CmdAlias->init();
459
460 # initialise the Geomagnetic data engine
461 dbg("Start WWV");
462 Geomag->init();
463 dbg("Start WCY");
464 WCY->init();
465
466 # initial the Spot stuff
467 dbg("Starting DX Spot system");
468 Spot->init();
469
470 # initialise the protocol engine
471 dbg("Start Protocol Engines ...");
472 DXProt->init();
473
474 # put in a DXCluster node for us here so we can add users and take them away
475 $routeroot = Route::Node->new($mycall, $version*100+5300, Route::here($main::me->here)|Route::conf($main::me->conf));
476 $routeroot->do_pc9x(1);
477 $routeroot->via_pc92(1);
478
479 # make sure that there is a routing OUTPUT node default file
480 #unless (Filter::read_in('route', 'node_default', 0)) {
481 #       my $dxcc = $main::me->dxcc;
482 #       $Route::filterdef->cmd($main::me, 'route', 'accept', "node_default call $mycall" );
483 #}
484
485 # read in any existing message headers and clean out old crap
486 dbg("reading existing message headers ...");
487 DXMsg->init();
488 DXMsg::clean_old();
489
490 # read in any cron jobs
491 dbg("reading cron jobs ...");
492 DXCron->init();
493
494 # read in database desriptors
495 dbg("reading database descriptors ...");
496 DXDb::load();
497
498 # starting local stuff
499 dbg("doing local initialisation ...");
500 QSL::init(1);
501 if (defined &Local::init) {
502         eval {
503                 Local::init();
504         };
505         dbg("Local::init error $@") if $@;
506 }
507
508
509 # this, such as it is, is the main loop!
510 dbg("orft we jolly well go ...");
511 my $script = new Script "startup";
512 $script->run($main::me) if $script;
513
514 #open(DB::OUT, "|tee /tmp/aa");
515
516 for (;;) {
517 #       $DB::trace = 1;
518
519         Msg->event_loop(10, 0.010);
520         my $timenow = time;
521
522         DXChannel::process();
523
524 #       $DB::trace = 0;
525
526         # do timed stuff, ongoing processing happens one a second
527         if ($timenow != $systime) {
528                 reap() if $zombies;
529                 $systime = $timenow;
530                 my $days = int ($systime / 86400);
531                 if ($systime_days != $days) {
532                         $systime_days = $days;
533                         $systime_daystart = $days * 86400;
534                 }
535                 IsoTime::update($systime);
536                 DXCron::process();      # do cron jobs
537                 DXCommandmode::process(); # process ongoing command mode stuff
538                 DXXml::process();
539                 DXProt::process();              # process ongoing ak1a pcxx stuff
540                 DXConnect::process();
541                 DXMsg::process();
542                 DXDb::process();
543                 DXUser::process();
544                 DXDupe::process();
545                 AGWMsg::process();
546                 BPQMsg::process();
547
548                 if (defined &Local::process) {
549                         eval {
550                                 Local::process();       # do any localised processing
551                         };
552                         dbg("Local::process error $@") if $@;
553                 }
554         }
555         if ($decease) {
556                 last if --$decease <= 0;
557         }
558 }
559 cease(0);
560 exit(0);
561
562