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