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