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