b9031719718fc291e1ef18343a65b4639af872a8
[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 package main;
16
17 # set default paths, these should be overwritten by DXVars.pm
18 use vars qw($data $system $cmd $localcmd $userfn $clusteraddr $clusterport $yes $no $user_interval $lang);
19
20 $lang = 'en';                   # default language
21 $clusteraddr = '127.0.0.1';     # cluster tcp host address - used for things like console.pl
22 $clusterport = 27754;           # cluster tcp port
23 $yes = 'Yes';                   # visual representation of yes
24 $no = 'No';                     # ditto for no
25 $user_interval = 11*60;         # the interval between unsolicited prompts if no traffic
26
27
28 # make sure that modules are searched in the order local then perl
29 BEGIN {
30         umask 002;
31
32         # root of directory tree for this system
33         $root = "/spider";
34         $root = $ENV{'DXSPIDER_ROOT'} if $ENV{'DXSPIDER_ROOT'};
35
36         unshift @INC, "$root/perl";     # this IS the right way round!
37         unshift @INC, "$root/local";
38
39         # do some validation of the input
40         die "The directory $root doesn't exist, please RTFM" unless -d $root;
41         die "$root/local doesn't exist, please RTFM" unless -d "$root/local";
42         die "$root/local/DXVars.pm doesn't exist, please RTFM" unless -e "$root/local/DXVars.pm";
43
44         mkdir "$root/local_cmd", 0777 unless -d "$root/local_cmd";
45
46         $data = "$root/data";
47         $system = "$root/sys";
48         $cmd = "$root/cmd";
49         $localcmd = "$root/local_cmd";
50         $userfn = "$data/users";
51
52         # try to create and lock a lockfile (this isn't atomic but
53         # should do for now
54         $lockfn = "$root/local/cluster.lck";       # lock file name
55         if (-w $lockfn) {
56                 open(CLLOCK, "$lockfn") or die "Can't open Lockfile ($lockfn) $!";
57                 my $pid = <CLLOCK>;
58                 if ($pid) {
59                         chomp $pid;
60                         die "Lockfile ($lockfn) and process $pid exist, another cluster running?" if kill 0, $pid;
61                 }
62                 unlink $lockfn;
63                 close CLLOCK;
64         }
65         open(CLLOCK, ">$lockfn") or die "Can't open Lockfile ($lockfn) $!";
66         print CLLOCK "$$\n";
67         close CLLOCK;
68
69         $is_win = ($^O =~ /^MS/ || $^O =~ /^OS-2/) ? 1 : 0; # is it Windows?
70         $systime = time;
71 }
72
73 use DXVars;
74 use Msg;
75 use IntMsg;
76 use Internet;
77 use Listeners;
78 use ExtMsg;
79 use AGWConnect;
80 use AGWMsg;
81 use DXDebug;
82 use DXLog;
83 use DXLogPrint;
84 use DXUtil;
85 use DXChannel;
86 use DXUser;
87 use DXM;
88 use DXCommandmode;
89 use DXProtVars;
90 use DXProtout;
91 use DXProt;
92 use DXMsg;
93 use DXCron;
94 use DXConnect;
95 use DXBearing;
96 use DXDb;
97 use DXHash;
98 use DXDupe;
99 use Script;
100 use Prefix;
101 use Spot;
102 use Bands;
103 use Keps;
104 use Minimuf;
105 use Sun;
106 use Geomag;
107 use CmdAlias;
108 use Filter;
109 use AnnTalk;
110 use BBS;
111 use WCY;
112 use BadWords;
113 use Timer;
114 use Route;
115 use Route::Node;
116 use Route::User;
117 use Editable;
118 use Mrtg;
119 use USDB;
120 use UDPMsg;
121 use QSL;
122 use DXXml;
123 use DXSql;
124 use IsoTime;
125 use BPQMsg;
126
127 use Data::Dumper;
128 use IO::File;
129 use Fcntl ':flock';
130 use POSIX ":sys_wait_h";
131 use Version;
132
133 use Local;
134
135 package main;
136
137 use strict;
138 use vars qw(@inqueue $systime $starttime $lockfn @outstanding_connects
139                         $zombies $root @listeners $lang $myalias @debug $userfn
140                         $mycall $decease $is_win $routeroot $me $reqreg $bumpexisting
141                         $allowdxby $dbh $dsn $dbuser $dbpass $do_xml $systime_days $systime_daystart
142                         $can_encode $maxconnect_user $maxconnect_node
143                    );
144
145 @inqueue = ();                                  # the main input queue, an array of hashes
146 $systime = 0;                                   # the time now (in seconds)
147 $starttime = 0;                 # the starting time of the cluster
148 @outstanding_connects = ();     # list of outstanding connects
149 @listeners = ();                                # list of listeners
150 $reqreg = 0;                                    # 1 = registration required, 2 = deregister people
151 $bumpexisting = 1;                              # 1 = allow new connection to disconnect old, 0 - don't allow it
152 $allowdxby = 0;                                 # 1 = allow "dx by <othercall>", 0 - don't allow it
153 $maxconnect_user = 3;                   # the maximum no of concurrent connections a user can have at a time
154 $maxconnect_node = 0;                   # Ditto but for nodes. In either case if a new incoming connection
155                                                                 # takes the no of references in the routing table above these numbers
156                                                                 # then the connection is refused. This only affects INCOMING connections.
157
158 # send a message to call on conn and disconnect
159 sub already_conn
160 {
161         my ($conn, $call, $mess) = @_;
162
163         $conn->disable_read(1);
164         dbg("-> D $call $mess\n") if isdbg('chan');
165         $conn->send_now("D$call|$mess");
166         sleep(2);
167         $conn->disconnect;
168 }
169
170 sub error_handler
171 {
172         my $dxchan = shift;
173         $dxchan->{conn}->set_error(undef) if exists $dxchan->{conn};
174         $dxchan->disconnect(1);
175 }
176
177 # handle incoming messages
178 sub new_channel
179 {
180         my ($conn, $msg) = @_;
181         my ($sort, $call, $line) = DXChannel::decode_input(0, $msg);
182         return unless defined $sort;
183
184         unless (is_callsign($call)) {
185                 already_conn($conn, $call, DXM::msg($lang, "illcall", $call));
186                 return;
187         }
188
189         # set up the basic channel info
190         # is there one already connected to me - locally?
191         my $user = DXUser::get_current($call);
192         my $dxchan = DXChannel::get($call);
193         if ($dxchan) {
194                 if ($user && $user->is_node) {
195                         already_conn($conn, $call, DXM::msg($lang, 'concluster', $call, $main::mycall));
196                         return;
197                 }
198                 if ($bumpexisting) {
199                         my $ip = $conn->peerhost || 'unknown';
200                         $dxchan->send_now('D', DXM::msg($lang, 'conbump', $call, $ip));
201                         LogDbg('DXCommand', "$call bumped off by $ip, disconnected");
202                         $dxchan->disconnect;
203                 } else {
204                         already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
205                         return;
206                 }
207         }
208
209         # (fairly) politely disconnect people that are connected to too many other places at once
210         my $r = Route::get($call);
211         if ($conn->{sort} && $conn->{sort} =~ /^I/ && $r && $user) {
212                 my @n = $r->parents;
213                 my $m = $r->isa('Route::Node') ? $maxconnect_node : $maxconnect_user;
214                 my $c = $user->maxconnect;
215                 my $v;
216                 $v = defined $c ? $c : $m;
217                 if ($v && @n >= $v) {
218                         my $nodes = join ',', @n;
219                         LogDbg('DXCommand', "$call has too many connections ($v) at $nodes - disconnected");
220                         already_conn($conn, $call, DXM::msg($lang, 'contomany', $call, $v, $nodes));
221                         return;
222                 }
223         }
224
225         # is he locked out ?
226         my $basecall = $call;
227         $basecall =~ s/-\d+$//;
228         my $baseuser = DXUser::get_current($basecall);
229         my $lock = $user->lockout if $user;
230         if ($baseuser && $baseuser->lockout || $lock) {
231                 if (!$user || !defined $lock || $lock) {
232                         my $host = $conn->peerhost || "unknown";
233                         LogDbg('DXCommand', "$call on $host is locked out, disconnected");
234                         $conn->disconnect;
235                         return;
236                 }
237         }
238
239         if ($user) {
240                 $user->{lang} = $main::lang if !$user->{lang}; # to autoupdate old systems
241         } else {
242                 $user = DXUser->new($call);
243         }
244
245         # create the channel
246         if ($user->is_node) {
247                 $dxchan = DXProt->new($call, $conn, $user);
248         } elsif ($user->is_user) {
249                 $dxchan = DXCommandmode->new($call, $conn, $user);
250 #       } elsif ($user->is_bbs) {                                  # there is no support so
251 #               $dxchan = BBS->new($call, $conn, $user);               # don't allow it!!!
252         } else {
253                 die "Invalid sort of user on $call = $sort";
254         }
255
256         # check that the conn has a callsign
257         $conn->conns($call) if $conn->isa('IntMsg');
258
259         # set callbacks
260         $conn->set_error(sub {error_handler($dxchan)});
261         $conn->set_rproc(sub {my ($conn,$msg) = @_; $dxchan->rec($msg);});
262         $dxchan->rec($msg);
263 }
264
265
266 sub login
267 {
268         return \&new_channel;
269 }
270
271 # cease running this program, close down all the connections nicely
272 sub cease
273 {
274         my $dxchan;
275
276         unless ($is_win) {
277                 $SIG{'TERM'} = 'IGNORE';
278                 $SIG{'INT'} = 'IGNORE';
279         }
280
281         DXUser::sync;
282
283         if (defined &Local::finish) {
284                 eval {
285                         Local::finish();   # end local processing
286                 };
287                 dbg("Local::finish error $@") if $@;
288         }
289
290         # disconnect nodes
291         foreach $dxchan (DXChannel::get_all_nodes) {
292             $dxchan->disconnect(2) unless $dxchan == $main::me;
293         }
294         Msg->event_loop(100, 0.01);
295
296         # disconnect users
297         foreach $dxchan (DXChannel::get_all_users) {
298                 $dxchan->disconnect;
299         }
300
301         # disconnect AGW
302         AGWMsg::finish();
303         BPQMsg::finish();
304
305         # disconnect UDP customers
306         UDPMsg::finish();
307
308         # end everything else
309         Msg->event_loop(100, 0.01);
310         DXUser::finish();
311         DXDupe::finish();
312
313         # close all databases
314         DXDb::closeall;
315
316         # close all listeners
317         foreach my $l (@listeners) {
318                 $l->close_server;
319         }
320
321         LogDbg('cluster', "DXSpider V$version, build $subversion.$build (git: $gitversion) ended");
322         dbgclose();
323         Logclose();
324
325         $dbh->finish if $dbh;
326
327         unlink $lockfn;
328 #       $SIG{__WARN__} = $SIG{__DIE__} =  sub {my $a = shift; cluck($a); };
329         exit(0);
330 }
331
332 # the reaper of children
333 sub reap
334 {
335         my $cpid;
336         while (($cpid = waitpid(-1, WNOHANG)) > 0) {
337                 dbg("cpid: $cpid") if isdbg('reap');
338 #               Msg->pid_gone($cpid);
339                 $zombies-- if $zombies > 0;
340         }
341         dbg("cpid: $cpid") if isdbg('reap');
342 }
343
344 # this is where the input queue is dealt with and things are dispatched off to other parts of
345 # the cluster
346
347 sub uptime
348 {
349         my $t = $systime - $starttime;
350         my $days = int $t / 86400;
351         $t -= $days * 86400;
352         my $hours = int $t / 3600;
353         $t -= $hours * 3600;
354         my $mins = int $t / 60;
355         return sprintf "%d %02d:%02d", $days, $hours, $mins;
356 }
357
358 sub AGWrestart
359 {
360         AGWMsg::init(\&new_channel);
361 }
362
363 #############################################################
364 #
365 # The start of the main line of code
366 #
367 #############################################################
368
369 $starttime = $systime = time;
370 $systime_days = int ($systime / 86400);
371 $systime_daystart = $systime_days * 86400;
372 $lang = 'en' unless $lang;
373
374 unless ($DB::VERSION) {
375         $SIG{INT} = $SIG{TERM} = \&cease;
376 }
377
378 # open the debug file, set various FHs to be unbuffered
379 dbginit(\&DXCommandmode::broadcast_debug);
380 foreach (@debug) {
381         dbgadd($_);
382 }
383 STDOUT->autoflush(1);
384
385 # try to load the database
386 if (DXSql::init($dsn)) {
387         $dbh = DXSql->new($dsn);
388         $dbh = $dbh->connect($dsn, $dbuser, $dbpass) if $dbh;
389 }
390
391 # try to load Encode and Git
392 {
393         local $^W = 0;
394         my $w = $SIG{__DIE__};
395         $SIG{__DIE__} = 'IGNORE';
396         eval { require Encode; };
397         unless ($@) {
398                 import Encode;
399                 $can_encode = 1;
400         }
401         eval { require Git; };
402         unless ($@) {
403                 import Git;
404                 
405                 # determine the real version number
406                 my $repo = Git->repository(Directory => "$root/.git");
407                 if ($repo) {
408                         my $desc = $repo->command_oneline(['describe'], STDERR => 0);
409                         if ($desc) {
410                                 my ($v, $s, $b, $g) = $desc =~ /^([\d.]+)(?:\.(\d+))?-(\d+)-g([0-9a-f]+)/;
411                                 $version = $v;
412                                 $subversion = $s || 0;
413                                 $build = $b || 0;
414                                 $gitversion = "$g\[r]";
415                         }
416                 }
417         }
418         $SIG{__DIE__} = $w;
419 }
420
421 # try to load XML::Simple
422 DXXml::init();
423
424 # banner
425 my ($year) = (gmtime)[5];
426 $year += 1900;
427 LogDbg('cluster', "DXSpider V$version, build $subversion.$build (git: $gitversion) started");
428 dbg("Copyright (c) 1998-$year Dirk Koopman G1TLH");
429
430 # load Prefixes
431 dbg("loading prefixes ...");
432 dbg(USDB::init());
433 my $r = Prefix::init();
434 confess $r if $r;
435
436 # load band data
437 dbg("loading band data ...");
438 Bands::load();
439
440 # initialise User file system
441 dbg("loading user file system ...");
442 DXUser->init($userfn, 1);
443
444
445 # look for the sysop and the alias user and complain if they aren't there
446 {
447         die "\$myalias \& \$mycall are the same ($mycall)!, they must be different (hint: make \$mycall = '${mycall}-2';). Oh and don't forget to rerun create_sysop.pl!" if $mycall eq $myalias;
448         my $ref = DXUser::get($mycall);
449         die "$mycall missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
450         my $oldsort = $ref->sort;
451         if ($oldsort ne 'S') {
452                 $ref->sort('S');
453                 dbg "Resetting node type from $oldsort -> DXSpider ('S')";
454         }
455         $ref = DXUser::get($myalias);
456         die "$myalias missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
457         $oldsort = $ref->sort;
458         if ($oldsort ne 'U') {
459                 $ref->sort('U');
460                 dbg "Resetting sysop user type from $oldsort -> User ('U')";
461         }
462 }
463
464 # start listening for incoming messages/connects
465 dbg("starting listeners ...");
466 my $conn = IntMsg->new_server($clusteraddr, $clusterport, \&login);
467 $conn->conns("Server $clusteraddr/$clusterport using IntMsg");
468 push @listeners, $conn;
469 dbg("Internal port: $clusteraddr $clusterport using IntMsg");
470 foreach my $l (@main::listen) {
471         no strict 'refs';
472         my $pkg = $l->[2] || 'ExtMsg';
473         my $login = $l->[3] || 'login';
474
475         $conn = $pkg->new_server($l->[0], $l->[1], \&{"${pkg}::${login}"});
476         $conn->conns("Server $l->[0]/$l->[1] using ${pkg}::${login}");
477         push @listeners, $conn;
478         dbg("External Port: $l->[0] $l->[1] using ${pkg}::${login}");
479 }
480
481 dbg("AGW Listener") if $AGWMsg::enable;
482 AGWrestart();
483
484 dbg("BPQ Listener") if $BPQMsg::enable;
485 BPQMsg::init(\&new_channel);
486
487 dbg("UDP Listener") if $UDPMsg::enable;
488 UDPMsg::init(\&new_channel);
489
490 # load bad words
491 dbg("load badwords: " . (BadWords::load or "Ok"));
492
493 # prime some signals
494 unless ($DB::VERSION) {
495         $SIG{INT} = $SIG{TERM} = sub { $decease = 1 };
496 }
497
498 unless ($is_win) {
499         $SIG{HUP} = 'IGNORE';
500         $SIG{CHLD} = sub { $zombies++ };
501
502         $SIG{PIPE} = sub {      dbg("Broken PIPE signal received"); };
503         $SIG{IO} = sub {        dbg("SIGIO received"); };
504         $SIG{WINCH} = $SIG{STOP} = $SIG{CONT} = 'IGNORE';
505         $SIG{KILL} = 'DEFAULT';     # as if it matters....
506
507         # catch the rest with a hopeful message
508         for (keys %SIG) {
509                 if (!$SIG{$_}) {
510                         #               dbg("Catching SIG $_") if isdbg('chan');
511                         $SIG{$_} = sub { my $sig = shift;       DXDebug::confess("Caught signal $sig");  };
512                 }
513         }
514 }
515
516 # start dupe system
517 dbg("Starting Dupe system");
518 DXDupe::init();
519
520 # read in system messages
521 dbg("Read in Messages");
522 DXM->init();
523
524 # read in command aliases
525 dbg("Read in Aliases");
526 CmdAlias->init();
527
528 # initialise the Geomagnetic data engine
529 dbg("Start WWV");
530 Geomag->init();
531 dbg("Start WCY");
532 WCY->init();
533
534 # initial the Spot stuff
535 dbg("Starting DX Spot system");
536 Spot->init();
537
538 # initialise the protocol engine
539 dbg("Start Protocol Engines ...");
540 DXProt->init();
541
542 # put in a DXCluster node for us here so we can add users and take them away
543 $routeroot = Route::Node->new($mycall, $version*100+5300, Route::here($main::me->here)|Route::conf($main::me->conf));
544 $routeroot->do_pc9x(1);
545 $routeroot->via_pc92(1);
546
547 # make sure that there is a routing OUTPUT node default file
548 #unless (Filter::read_in('route', 'node_default', 0)) {
549 #       my $dxcc = $main::me->dxcc;
550 #       $Route::filterdef->cmd($main::me, 'route', 'accept', "node_default call $mycall" );
551 #}
552
553 # read in any existing message headers and clean out old crap
554 dbg("reading existing message headers ...");
555 DXMsg->init();
556 DXMsg::clean_old();
557
558 # read in any cron jobs
559 dbg("reading cron jobs ...");
560 DXCron->init();
561
562 # read in database desriptors
563 dbg("reading database descriptors ...");
564 DXDb::load();
565
566 # starting local stuff
567 dbg("doing local initialisation ...");
568 QSL::init(1);
569 if (defined &Local::init) {
570         eval {
571                 Local::init();
572         };
573         dbg("Local::init error $@") if $@;
574 }
575
576
577 # this, such as it is, is the main loop!
578 dbg("orft we jolly well go ...");
579 my $script = new Script "startup";
580 $script->run($main::me) if $script;
581
582 #open(DB::OUT, "|tee /tmp/aa");
583
584 for (;;) {
585 #       $DB::trace = 1;
586
587         Msg->event_loop(10, 0.010);
588         my $timenow = time;
589
590         DXChannel::process();
591
592 #       $DB::trace = 0;
593
594         # do timed stuff, ongoing processing happens one a second
595         if ($timenow != $systime) {
596                 reap() if $zombies;
597                 $systime = $timenow;
598                 my $days = int ($systime / 86400);
599                 if ($systime_days != $days) {
600                         $systime_days = $days;
601                         $systime_daystart = $days * 86400;
602                 }
603                 IsoTime::update($systime);
604                 DXCron::process();      # do cron jobs
605                 DXCommandmode::process(); # process ongoing command mode stuff
606                 DXXml::process();
607                 DXProt::process();              # process ongoing ak1a pcxx stuff
608                 DXConnect::process();
609                 DXMsg::process();
610                 DXDb::process();
611                 DXUser::process();
612                 DXDupe::process();
613                 AGWMsg::process();
614                 BPQMsg::process();
615
616                 DXLog::flushall();
617                 
618                 if (defined &Local::process) {
619                         eval {
620                                 Local::process();       # do any localised processing
621                         };
622                         dbg("Local::process error $@") if $@;
623                 }
624         }
625         if ($decease) {
626                 last if --$decease <= 0;
627         }
628 }
629 cease(0);
630 exit(0);
631
632