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