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