move stuff about ready for web interface
[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.10.1;
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 Mojo::IOLoop;
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 use Web;
117
118 use Local;
119
120 package main;
121
122 use strict;
123 use vars qw(@inqueue $systime $starttime $lockfn @outstanding_connects
124                         $zombies $root @listeners $lang $myalias @debug $userfn $clusteraddr
125                         $clusterport $mycall $decease $is_win $routeroot $me $reqreg $bumpexisting
126                         $allowdxby $dbh $dsn $dbuser $dbpass $do_xml $systime_days $systime_daystart
127                         $can_encode $maxconnect_user $maxconnect_node $idle_interval $log_flush_interval
128                    );
129
130 @inqueue = ();                                  # the main input queue, an array of hashes
131 $systime = 0;                                   # the time now (in seconds)
132 $starttime = 0;                 # the starting time of the cluster
133 @outstanding_connects = ();     # list of outstanding connects
134 @listeners = ();                                # list of listeners
135 $reqreg = 0;                                    # 1 = registration required, 2 = deregister people
136 $bumpexisting = 1;                              # 1 = allow new connection to disconnect old, 0 - don't allow it
137 $allowdxby = 0;                                 # 1 = allow "dx by <othercall>", 0 - don't allow it
138 $maxconnect_user = 3;                   # the maximum no of concurrent connections a user can have at a time
139 $maxconnect_node = 0;                   # Ditto but for nodes. In either case if a new incoming connection
140                                                                 # takes the no of references in the routing table above these numbers
141                                                                 # then the connection is refused. This only affects INCOMING connections.
142 $idle_interval = 0.500;         # the wait between invocations of the main idle loop processing.
143 $log_flush_interval = 2;                # interval to wait between log flushes
144
145 our $ending;                                                               # signal that we are ending;
146
147
148 # send a message to call on conn and disconnect
149 sub already_conn
150 {
151         my ($conn, $call, $mess) = @_;
152
153         $conn->disable_read(1);
154         dbg("-> D $call $mess\n") if isdbg('chan');
155         $conn->send_now("D$call|$mess");
156         sleep(2);
157         $conn->disconnect;
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, 'conother', $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 {my $err = shift; LogDbg('DXCommand', "Comms error '$err' received for call $dxchan->{call}"); $dxchan->disconnect(1);});
244         $conn->set_on_eof(sub {$dxchan->disconnect});
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 our $ceasing;
256
257 # cease running this program, close down all the connections nicely
258 sub cease
259 {
260         my $dxchan;
261
262         cluck("ceasing") if $ceasing; 
263         
264         return if $ceasing++;
265         
266         unless ($is_win) {
267                 $SIG{'TERM'} = 'IGNORE';
268                 $SIG{'INT'} = 'IGNORE';
269         }
270
271         DXUser::sync;
272
273         if (defined &Local::finish) {
274                 eval {
275                         Local::finish();   # end local processing
276                 };
277                 dbg("Local::finish error $@") if $@;
278         }
279
280
281         # disconnect AGW
282         AGWMsg::finish();
283         BPQMsg::finish();
284
285         # disconnect UDP customers
286         UDPMsg::finish();
287
288         # end everything else
289         DXUser::finish();
290         DXDupe::finish();
291
292         # close all databases
293         DXDb::closeall;
294
295         # close all listeners
296         foreach my $l (@listeners) {
297                 $l->close_server;
298         }
299
300         LogDbg('cluster', "DXSpider V$version, build $build (git: $gitversion) ended");
301         dbg("bye bye everyone - bye bye");
302         dbgclose();
303         Logclose();
304
305         $dbh->finish if $dbh;
306
307         unlink $lockfn;
308 }
309
310 # the reaper of children
311 sub reap
312 {
313         my $cpid;
314         while (($cpid = waitpid(-1, WNOHANG)) > 0) {
315                 dbg("cpid: $cpid") if isdbg('reap');
316 #               Msg->pid_gone($cpid);
317                 $zombies-- if $zombies > 0;
318         }
319         dbg("cpid: $cpid") if isdbg('reap');
320 }
321
322 # this is where the input queue is dealt with and things are dispatched off to other parts of
323 # the cluster
324
325 sub uptime
326 {
327         my $t = $systime - $starttime;
328         my $days = int $t / 86400;
329         $t -= $days * 86400;
330         my $hours = int $t / 3600;
331         $t -= $hours * 3600;
332         my $mins = int $t / 60;
333         return sprintf "%d %02d:%02d", $days, $hours, $mins;
334 }
335
336 sub AGWrestart
337 {
338         AGWMsg::init(\&new_channel);
339 }
340
341 our $io_disconnected;
342
343 sub idle_loop
344 {
345         my $timenow = time;
346
347         BPQMsg::process();
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                 DXCron::process();                      # do cron jobs
372                 IsoTime::update($systime);
373                 DXProt::process();                      # process ongoing ak1a pcxx stuff
374                 DXConnect::process();
375                 DXUser::process();
376                 AGWMsg::process();
377                 
378                 Timer::handler();
379                 DXLog::flushall();
380         }
381
382         if (defined &Local::process) {
383                 eval {
384                         Local::process();       # do any localised processing
385                 };
386                 dbg("Local::process error $@") if $@;
387         }
388
389         while ($ending) {
390                 my $dxchan;
391
392                 dbg("DXSpider Ending $ending");
393
394                 unless ($io_disconnected++) {
395
396                         # disconnect users
397                         foreach $dxchan (DXChannel::get_all_users) {
398                                 $dxchan->disconnect;
399                         }
400
401                         # disconnect nodes
402                         foreach $dxchan (DXChannel::get_all_nodes) {
403                                 next if $dxchan == $main::me;
404                                 $dxchan->disconnect(2);
405                         }
406                         $main::me->disconnect;
407                 }
408
409                 Mojo::IOLoop->stop if --$ending <= 0;
410         }
411 }
412
413 sub setup_start
414 {
415
416         #############################################################
417         #
418         # The start of the main line of code
419         #
420         #############################################################
421
422         $starttime = $systime = time;
423         $systime_days = int ($systime / 86400);
424         $systime_daystart = $systime_days * 86400;
425         $lang = 'en' unless $lang;
426
427         unless ($DB::VERSION) {
428                 $SIG{INT} = $SIG{TERM} = \&cease;
429         }
430
431         # open the debug file, set various FHs to be unbuffered
432         dbginit(\&DXCommandmode::broadcast_debug);
433         foreach (@debug) {
434                 dbgadd($_);
435         }
436         STDOUT->autoflush(1);
437
438         # try to load the database
439         if (DXSql::init($dsn)) {
440                 $dbh = DXSql->new($dsn);
441                 $dbh = $dbh->connect($dsn, $dbuser, $dbpass) if $dbh;
442         }
443
444         # try to load Encode and Git
445         {
446                 local $^W = 0;
447                 my $w = $SIG{__DIE__};
448                 $SIG{__DIE__} = 'IGNORE';
449                 eval { require Encode; };
450                 unless ($@) {
451                         import Encode;
452                         $can_encode = 1;
453                 }
454                 eval { require Git; };
455                 unless ($@) {
456                         import Git;
457                 
458                         # determine the real version number
459                         my $repo = Git->repository(Directory => "$root/.git");
460                         if ($repo) {
461                                 my $desc = $repo->command_oneline(['describe', '--long'], STDERR => 0);
462                                 if ($desc) {
463                                         my ($v, $s, $b, $g) = $desc =~ /^([\d.]+)(?:\.(\d+))?-(\d+)-g([0-9a-f]+)/;
464                                         $version = $v;
465                                         $build = $b || 0;
466                                         $gitversion = "$g\[r]";
467                                 }
468                         }
469                 }
470                 $SIG{__DIE__} = $w;
471         }
472
473         # try to load XML::Simple
474         DXXml::init();
475
476         # banner
477         my ($year) = (gmtime)[5];
478         $year += 1900;
479         LogDbg('cluster', "DXSpider V$version, build $build (git: $gitversion) started");
480         dbg("Copyright (c) 1998-$year Dirk Koopman G1TLH");
481
482         # load Prefixes
483         dbg("loading prefixes ...");
484         dbg(USDB::init());
485         my $r = Prefix::init();
486         confess $r if $r;
487
488         # load band data
489         dbg("loading band data ...");
490         Bands::load();
491
492         # initialise User file system
493         dbg("loading user file system ...");
494         DXUser->init($userfn, 1);
495
496         # look for the sysop and the alias user and complain if they aren't there
497         {
498                 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;
499                 my $ref = DXUser::get($mycall);
500                 die "$mycall missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
501                 $ref = DXUser::get($myalias);
502                 die "$myalias missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
503         }
504
505         # start listening for incoming messages/connects
506         dbg("starting listeners ...");
507         my $conn = IntMsg->new_server($clusteraddr, $clusterport, \&login);
508         $conn->conns("Server $clusteraddr/$clusterport using IntMsg");
509         push @listeners, $conn;
510         dbg("Internal port: $clusteraddr $clusterport using IntMsg");
511         foreach my $l (@main::listen) {
512                 no strict 'refs';
513                 my $pkg = $l->[2] || 'ExtMsg';
514                 my $login = $l->[3] || 'login';
515
516                 $conn = $pkg->new_server($l->[0], $l->[1], \&{"${pkg}::${login}"});
517                 $conn->conns("Server $l->[0]/$l->[1] using ${pkg}::${login}");
518                 push @listeners, $conn;
519                 dbg("External Port: $l->[0] $l->[1] using ${pkg}::${login}");
520         }
521
522         dbg("AGW Listener") if $AGWMsg::enable;
523         AGWrestart();
524
525         dbg("BPQ Listener") if $BPQMsg::enable;
526         BPQMsg::init(\&new_channel);
527
528         dbg("UDP Listener") if $UDPMsg::enable;
529         UDPMsg::init(\&new_channel);
530
531         # load bad words
532         dbg("load badwords: " . (BadWords::load or "Ok"));
533
534         # prime some signals
535         unless ($DB::VERSION) {
536                 $SIG{INT} = $SIG{TERM} = sub { $ending = 10; };
537         }
538
539         unless ($is_win) {
540                 $SIG{HUP} = 'IGNORE';
541                 $SIG{CHLD} = sub { $zombies++ };
542
543                 $SIG{PIPE} = sub {      dbg("Broken PIPE signal received"); };
544                 $SIG{IO} = sub {        dbg("SIGIO received"); };
545                 $SIG{WINCH} = $SIG{STOP} = $SIG{CONT} = 'IGNORE';
546                 $SIG{KILL} = 'DEFAULT'; # as if it matters....
547
548                 # catch the rest with a hopeful message
549                 for (keys %SIG) {
550                         if (!$SIG{$_}) {
551                                 #               dbg("Catching SIG $_") if isdbg('chan');
552                                 $SIG{$_} = sub { my $sig = shift;       DXDebug::confess("Caught signal $sig");  };
553                         }
554                 }
555         }
556
557         # start dupe system
558         dbg("Starting Dupe system");
559         DXDupe::init();
560
561         # read in system messages
562         dbg("Read in Messages");
563         DXM->init();
564
565         # read in command aliases
566         dbg("Read in Aliases");
567         CmdAlias->init();
568
569         # initialise the Geomagnetic data engine
570         dbg("Start WWV");
571         Geomag->init();
572         dbg("Start WCY");
573         WCY->init();
574
575         # initial the Spot stuff
576         dbg("Starting DX Spot system");
577         Spot->init();
578
579         # initialise the protocol engine
580         dbg("Start Protocol Engines ...");
581         DXProt->init();
582
583         # put in a DXCluster node for us here so we can add users and take them away
584         $routeroot = Route::Node->new($mycall, $version*100+5300, Route::here($main::me->here)|Route::conf($main::me->conf));
585         $routeroot->do_pc9x(1);
586         $routeroot->via_pc92(1);
587
588         # make sure that there is a routing OUTPUT node default file
589         #unless (Filter::read_in('route', 'node_default', 0)) {
590         #       my $dxcc = $main::me->dxcc;
591         #       $Route::filterdef->cmd($main::me, 'route', 'accept', "node_default call $mycall" );
592         #}
593
594         # read in any existing message headers and clean out old crap
595         dbg("reading existing message headers ...");
596         DXMsg->init();
597         DXMsg::clean_old();
598
599         # read in any cron jobs
600         dbg("reading cron jobs ...");
601         DXCron->init();
602
603         # read in database desriptors
604         dbg("reading database descriptors ...");
605         DXDb::load();
606
607         # starting local stuff
608         dbg("doing local initialisation ...");
609         QSL::init(1);
610         if (defined &Local::init) {
611                 eval {
612                         Local::init();
613                 };
614                 dbg("Local::init error $@") if $@;
615         }
616
617
618         # this, such as it is, is the main loop!
619         dbg("orft we jolly well go ...");
620         my $script = new Script "startup";
621         $script->run($main::me) if $script;
622
623         #open(DB::OUT, "|tee /tmp/aa");
624 }
625
626
627 setup_start();
628
629 my $main_loop = Mojo::IOLoop->recurring($idle_interval => \&idle_loop);
630 my $log_flush_loop = Mojo::IOLoop->recurring($log_flush_interval => \&DXLog::flushall);
631
632 Web::start_node();
633
634 cease(0);
635 exit(0);
636