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