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