add DXCIDR, fix version no tracking
[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 sub cease
276 {
277         my $dxchan;
278
279         unless ($is_win) {
280                 $SIG{'TERM'} = 'IGNORE';
281                 $SIG{'INT'} = 'IGNORE';
282         }
283
284         DXUser::sync;
285
286         if (defined &Local::finish) {
287                 eval {
288                         Local::finish();   # end local processing
289                 };
290                 dbg("Local::finish error $@") if $@;
291         }
292
293         # disconnect nodes
294         foreach $dxchan (DXChannel::get_all_nodes) {
295             $dxchan->disconnect(2) unless $dxchan == $main::me;
296         }
297         Msg->event_loop(100, 0.01);
298
299         # disconnect users
300         foreach $dxchan (DXChannel::get_all_users) {
301                 $dxchan->disconnect;
302         }
303
304         # disconnect AGW
305         AGWMsg::finish();
306         BPQMsg::finish();
307
308         # disconnect UDP customers
309         UDPMsg::finish();
310
311         # end everything else
312         Msg->event_loop(100, 0.01);
313         DXUser::finish();
314         DXDupe::finish();
315
316         # close all databases
317         DXDb::closeall;
318
319         # close all listeners
320         foreach my $l (@listeners) {
321                 $l->close_server;
322         }
323
324         LogDbg('cluster', "DXSpider v$version build $build (git: $gitbranch/$gitversion) using perl $^V on $^O ended");
325         dbgclose();
326         Logclose();
327
328         $dbh->finish if $dbh;
329
330         unlink $lockfn;
331 #       $SIG{__WARN__} = $SIG{__DIE__} =  sub {my $a = shift; cluck($a); };
332         exit(0);
333 }
334
335 # the reaper of children
336 sub reap
337 {
338         my $cpid;
339         while (($cpid = waitpid(-1, WNOHANG)) > 0) {
340                 dbg("cpid: $cpid") if isdbg('reap');
341 #               Msg->pid_gone($cpid);
342                 $zombies-- if $zombies > 0;
343         }
344         dbg("cpid: $cpid") if isdbg('reap');
345 }
346
347 # this is where the input queue is dealt with and things are dispatched off to other parts of
348 # the cluster
349
350 sub uptime
351 {
352         my $t = $systime - $starttime;
353         my $days = int $t / 86400;
354         $t -= $days * 86400;
355         my $hours = int $t / 3600;
356         $t -= $hours * 3600;
357         my $mins = int $t / 60;
358         return sprintf "%d %02d:%02d", $days, $hours, $mins;
359 }
360
361 sub AGWrestart
362 {
363         AGWMsg::init(\&new_channel);
364 }
365
366 #############################################################
367 #
368 # The start of the main line of code
369 #
370 #############################################################
371
372 chdir $root;
373
374 $starttime = $systime = time;
375 $systime_days = int ($systime / 86400);
376 $systime_daystart = $systime_days * 86400;
377 $lang = 'en' unless $lang;
378
379 unless ($DB::VERSION) {
380         $SIG{INT} = $SIG{TERM} = \&cease;
381 }
382
383 # open the debug file, set various FHs to be unbuffered
384 dbginit(\&DXCommandmode::broadcast_debug);
385 foreach (@debug) {
386         dbgadd($_);
387 }
388 STDOUT->autoflush(1);
389
390 # try to load the database
391 if (DXSql::init($dsn)) {
392         $dbh = DXSql->new($dsn);
393         $dbh = $dbh->connect($dsn, $dbuser, $dbpass) if $dbh;
394 }
395
396 # try to load Encode and Git
397 {
398         local $^W = 0;
399         my $w = $SIG{__DIE__};
400         $SIG{__DIE__} = 'IGNORE';
401         eval { require Encode; };
402         unless ($@) {
403                 import Encode;
404                 $can_encode = 1;
405         }
406         
407         $gitbranch = 'none';
408         $gitversion = 'none';
409
410         # determine the real Git build number and branch
411         my $desc;
412         eval {$desc = `git --git-dir=$root/.git describe --long`};
413         if (!$@ && $desc) {
414                 my ($v, $s, $b, $g) = $desc =~ /^([\d\.]+)(?:\.(\d+))?-(\d+)-g([0-9a-f]+)/;
415                 $version = $v;
416                 $subversion = $s || 0;
417                 $build = $b || 0;
418                 $gitversion = "$g\[r]";
419         }
420     if (!$@) {
421                 my @branch;
422                 
423                 eval {@branch = `git --git-dir=$root/.git branch`};
424                 unless ($@) {
425                         for (@branch) {
426                                 my ($star, $b) = split /\s+/;
427                                 if ($star eq '*') {
428                                         $gitbranch = $b;
429                                         last;
430                                 }
431                         }
432                 }
433         }
434
435         $SIG{__DIE__} = $w;
436 }
437
438 # try to load XML::Simple
439 DXXml::init();
440
441 # banner
442 my ($year) = (gmtime)[5];
443 $year += 1900;
444 LogDbg('cluster', "DXSpider v$version build $build (git: $gitbranch/$gitversion) using perl $^V on $^O started");
445 dbg("Copyright (c) 1998-$year Dirk Koopman G1TLH");
446
447 # load Prefixes
448 dbg("loading prefixes ...");
449 dbg(USDB::init());
450 my $r = Prefix::init();
451 confess $r if $r;
452
453 # load band data
454 dbg("loading band data ...");
455 Bands::load();
456
457 # initialise User file system
458 dbg("loading user file system ...");
459 DXUser->init($userfn, 1);
460
461
462 # look for the sysop and the alias user and complain if they aren't there
463 {
464         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;
465         my $ref = DXUser::get($mycall);
466         die "$mycall missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
467         my $oldsort = $ref->sort;
468         if ($oldsort ne 'S') {
469                 $ref->sort('S');
470                 dbg "Resetting node type from $oldsort -> DXSpider ('S')";
471         }
472         $ref = DXUser::get($myalias);
473         die "$myalias missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
474         $oldsort = $ref->sort;
475         if ($oldsort ne 'U') {
476                 $ref->sort('U');
477                 dbg "Resetting sysop user type from $oldsort -> User ('U')";
478         }
479 }
480
481 # get any bad IPs 
482 DXCIDR::init();
483
484 # start listening for incoming messages/connects
485 dbg("starting listeners ...");
486 my $conn = IntMsg->new_server($clusteraddr, $clusterport, \&login);
487 $conn->conns("Server $clusteraddr/$clusterport using IntMsg");
488 push @listeners, $conn;
489 dbg("Internal port: $clusteraddr $clusterport using IntMsg");
490 foreach my $l (@main::listen) {
491         no strict 'refs';
492         my $pkg = $l->[2] || 'ExtMsg';
493         my $login = $l->[3] || 'login';
494
495         $conn = $pkg->new_server($l->[0], $l->[1], \&{"${pkg}::${login}"});
496         $conn->conns("Server $l->[0]/$l->[1] using ${pkg}::${login}");
497         push @listeners, $conn;
498         dbg("External Port: $l->[0] $l->[1] using ${pkg}::${login}");
499 }
500
501 dbg("AGW Listener") if $AGWMsg::enable;
502 AGWrestart();
503
504 dbg("BPQ Listener") if $BPQMsg::enable;
505 BPQMsg::init(\&new_channel);
506
507 dbg("UDP Listener") if $UDPMsg::enable;
508 UDPMsg::init(\&new_channel);
509
510 # load bad words
511 dbg("load badwords: " . (BadWords::load or "Ok"));
512
513 # prime some signals
514 unless ($DB::VERSION) {
515         $SIG{INT} = $SIG{TERM} = sub { $decease = 1 };
516 }
517
518 unless ($is_win) {
519         $SIG{HUP} = 'IGNORE';
520         $SIG{CHLD} = sub { $zombies++ };
521
522         $SIG{PIPE} = sub {      dbg("Broken PIPE signal received"); };
523         $SIG{IO} = sub {        dbg("SIGIO received"); };
524         $SIG{WINCH} = $SIG{STOP} = $SIG{CONT} = 'IGNORE';
525         $SIG{KILL} = 'DEFAULT';     # as if it matters....
526
527         # catch the rest with a hopeful message
528         for (keys %SIG) {
529                 if (!$SIG{$_}) {
530                         #               dbg("Catching SIG $_") if isdbg('chan');
531                         $SIG{$_} = sub { my $sig = shift;       DXDebug::confess("Caught signal $sig");  };
532                 }
533         }
534 }
535
536 # start dupe system
537 dbg("Starting Dupe system");
538 DXDupe::init();
539
540 # read in system messages
541 dbg("Read in Messages");
542 DXM->init();
543
544 # read in command aliases
545 dbg("Read in Aliases");
546 CmdAlias->init();
547
548 # initialise the Geomagnetic data engine
549 dbg("Start WWV");
550 Geomag->init();
551 dbg("Start WCY");
552 WCY->init();
553
554 # initial the Spot stuff
555 dbg("Starting DX Spot system");
556 Spot->init();
557
558 # initialise the protocol engine
559 dbg("Start Protocol Engines ...");
560 DXProt->init();
561
562 # put in a DXCluster node for us here so we can add users and take them away
563 $routeroot = Route::Node->new($mycall, $version*100+5300, Route::here($main::me->here)|Route::conf($main::me->conf));
564 $routeroot->do_pc9x(1);
565 $routeroot->via_pc92(1);
566
567 # make sure that there is a routing OUTPUT node default file
568 #unless (Filter::read_in('route', 'node_default', 0)) {
569 #       my $dxcc = $main::me->dxcc;
570 #       $Route::filterdef->cmd($main::me, 'route', 'accept', "node_default call $mycall" );
571 #}
572
573 # read in any existing message headers and clean out old crap
574 dbg("reading existing message headers ...");
575 DXMsg->init();
576 DXMsg::clean_old();
577
578 # read in any cron jobs
579 dbg("reading cron jobs ...");
580 DXCron->init();
581
582 # read in database desriptors
583 dbg("reading database descriptors ...");
584 DXDb::load();
585
586 # starting local stuff
587 dbg("doing local initialisation ...");
588 QSL::init(1);
589 if (defined &Local::init) {
590         eval {
591                 Local::init();
592         };
593         dbg("Local::init error $@") if $@;
594 }
595
596
597 # this, such as it is, is the main loop!
598 dbg("orft we jolly well go ...");
599 my $script = new Script "startup";
600 $script->run($main::me) if $script;
601
602 #open(DB::OUT, "|tee /tmp/aa");
603
604 for (;;) {
605 #       $DB::trace = 1;
606
607         Msg->event_loop(10, 0.010);
608         my $timenow = time;
609
610         DXChannel::process();
611
612 #       $DB::trace = 0;
613
614         # do timed stuff, ongoing processing happens one a second
615         if ($timenow != $systime) {
616                 reap() if $zombies;
617                 $systime = $timenow;
618                 my $days = int ($systime / 86400);
619                 if ($systime_days != $days) {
620                         $systime_days = $days;
621                         $systime_daystart = $days * 86400;
622                 }
623                 IsoTime::update($systime);
624                 DXCron::process();      # do cron jobs
625                 DXCommandmode::process(); # process ongoing command mode stuff
626                 DXXml::process();
627                 DXProt::process();              # process ongoing ak1a pcxx stuff
628                 DXConnect::process();
629                 DXMsg::process();
630                 DXDb::process();
631                 DXUser::process();
632                 DXDupe::process();
633                 AGWMsg::process();
634                 BPQMsg::process();
635
636                 DXLog::flushall();
637                 
638                 if (defined &Local::process) {
639                         eval {
640                                 Local::process();       # do any localised processing
641                         };
642                         dbg("Local::process error $@") if $@;
643                 }
644         }
645         if ($decease) {
646                 last if --$decease <= 0;
647         }
648 }
649 cease(0);
650 exit(0);
651
652