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