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