2. Add full individual checking for all PC protocol fields in all messages
[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         # try to create and lock a lockfile (this isn't atomic but 
27         # should do for now
28         $lockfn = "$root/perl/cluster.lock";       # lock file name
29         if (-e $lockfn) {
30                 open(CLLOCK, "$lockfn") or die "Can't open Lockfile ($lockfn) $!";
31                 my $pid = <CLLOCK>;
32                 chomp $pid;
33                 die "Lockfile ($lockfn) and process $pid exist, another cluster running?" if kill 0, $pid;
34                 close CLLOCK;
35         }
36         open(CLLOCK, ">$lockfn") or die "Can't open Lockfile ($lockfn) $!";
37         print CLLOCK "$$\n";
38         close CLLOCK;
39 }
40
41 use Msg;
42 use DXVars;
43 use DXDebug;
44 use DXLog;
45 use DXLogPrint;
46 use DXUtil;
47 use DXChannel;
48 use DXUser;
49 use DXM;
50 use DXCommandmode;
51 use DXProt;
52 use DXMsg;
53 use DXCluster;
54 use DXCron;
55 use DXConnect;
56 use Prefix;
57 use Bands;
58 use Geomag;
59 use CmdAlias;
60 use Filter;
61 use DXDb;
62 use AnnTalk;
63 use WCY;
64
65 use Data::Dumper;
66 use Fcntl ':flock'; 
67
68 use Local;
69
70 package main;
71
72 @inqueue = ();                                  # the main input queue, an array of hashes
73 $systime = 0;                                   # the time now (in seconds)
74 $version = "1.44";                              # the version no of the software
75 $starttime = 0;                 # the starting time of the cluster   
76 $lockfn = "cluster.lock";       # lock file name
77 @outstanding_connects = ();     # list of outstanding connects
78       
79 # handle disconnections
80 sub disconnect
81 {
82         my $dxchan = shift;
83         return if !defined $dxchan;
84         $dxchan->disconnect();
85 }
86
87 # send a message to call on conn and disconnect
88 sub already_conn
89 {
90         my ($conn, $call, $mess) = @_;
91         
92         dbg('chan', "-> D $call $mess\n"); 
93         $conn->send_now("D$call|$mess");
94         sleep(1);
95         dbg('chan', "-> Z $call bye\n");
96         $conn->send_now("Z$call|bye"); # this will cause 'client' to disconnect
97         sleep(1);
98         $conn->disconnect();
99 }
100
101 # handle incoming messages
102 sub rec
103 {
104         my ($conn, $msg, $err) = @_;
105         my $dxchan = DXChannel->get_by_cnum($conn); # get the dxconnnect object for this message
106         
107         if (!defined $msg || (defined $err && $err)) {
108                 if ($dxchan) {
109                         if (defined $err) {
110                                 $conn->disconnect;
111                                 undef $conn;
112                                 $dxchan->conn(undef);
113                         }
114                         $dxchan->disconnect;
115                 } elsif ($conn) {
116                         $conn->disconnect;
117                 }
118                 return;
119         }
120         
121         # set up the basic channel info - this needs a bit more thought - there is duplication here
122         if (!defined $dxchan) {
123                 my ($sort, $call, $line) = DXChannel::decode_input(0, $msg);
124                 return unless defined $sort;
125  
126                 # is there one already connected to me - locally? 
127                 my $user = DXUser->get($call);
128                 if (DXChannel->get($call)) {
129                         my $mess = DXM::msg($lang, ($user && $user->is_node) ? 'concluster' : 'conother', $call);
130                         already_conn($conn, $call, $mess);
131                         return;
132                 }
133                 
134                 # is there one already connected elsewhere in the cluster?
135                 if ($user) {
136                         if (($user->is_node || $call eq $myalias) && !DXCluster->get_exact($call)) {
137                                 ;
138                         } else {
139                                 if (DXCluster->get_exact($call)) {
140                                         my $mess = DXM::msg($lang, $user->is_node ? 'concluster' : 'conother', $call);
141                                         already_conn($conn, $call, $mess);
142                                         return;
143                                 }
144                         }
145                         $user->{lang} = $main::lang if !$user->{lang}; # to autoupdate old systems
146                 } else {
147                         if (DXCluster->get_exact($call)) {
148                                 my $mess = DXM::msg($lang, 'conother', $call);
149                                 already_conn($conn, $call, $mess);
150                                 return;
151                         }
152                         $user = DXUser->new($call);
153                 }
154
155                 # is he locked out ?
156                 if ($user->lockout) {
157                         Log('DXCommand', "$call is locked out, disconnected");
158                         $conn->send_now("Z$call|bye"); # this will cause 'client' to disconnect
159                         return;
160                 }
161
162                 # create the channel
163                 $dxchan = DXCommandmode->new($call, $conn, $user) if $user->is_user;
164                 $dxchan = DXProt->new($call, $conn, $user) if $user->is_node;
165                 $dxchan = BBS->new($call, $conn, $user) if $user->is_bbs;
166                 die "Invalid sort of user on $call = $sort" if !$dxchan;
167         }
168         
169         # queue the message and the channel object for later processing
170         if (defined $msg) {
171                 my $self = bless {}, "inqueue";
172                 $self->{dxchan} = $dxchan;
173                 $self->{data} = $msg;
174                 push @inqueue, $self;
175         }
176 }
177
178 sub login
179 {
180         return \&rec;
181 }
182
183 # cease running this program, close down all the connections nicely
184 sub cease
185 {
186         my $dxchan;
187
188         $SIG{'TERM'} = 'IGNORE';
189         $SIG{'INT'} = 'IGNORE';
190         
191         DXUser::sync;
192
193         eval {
194                 Local::finish();   # end local processing
195         };
196         dbg('local', "Local::finish error $@") if $@;
197
198         # disconnect nodes
199         foreach $dxchan (DXChannel->get_all()) {
200                 next unless $dxchan->is_node;
201                 disconnect($dxchan) unless $dxchan == $DXProt::me;
202         }
203         Msg->event_loop(1, 0.05);
204         Msg->event_loop(1, 0.05);
205         Msg->event_loop(1, 0.05);
206         Msg->event_loop(1, 0.05);
207         Msg->event_loop(1, 0.05);
208         Msg->event_loop(1, 0.05);
209
210         # disconnect users
211         foreach $dxchan (DXChannel->get_all()) {
212                 next if $dxchan->is_node;
213                 disconnect($dxchan) unless $dxchan == $DXProt::me;
214         }
215         Msg->event_loop(1, 0.05);
216         Msg->event_loop(1, 0.05);
217         Msg->event_loop(1, 0.05);
218         Msg->event_loop(1, 0.05);
219         Msg->event_loop(1, 0.05);
220         Msg->event_loop(1, 0.05);
221         DXUser::finish();
222
223         # close all databases
224         DXDb::closeall;
225         
226         dbg('chan', "DXSpider version $version ended");
227         Log('cluster', "DXSpider V$version stopped");
228         dbgclose();
229         Logclose();
230         unlink $lockfn;
231 #       $SIG{__WARN__} = $SIG{__DIE__} =  sub {my $a = shift; cluck($a); };
232         exit(0);
233 }
234
235 # the reaper of children
236 sub reap
237 {
238         $SIG{'CHLD'} = \&reap;
239         my $cpid = wait;
240         @outstanding_connects = grep {$_->{pid} != $cpid} @outstanding_connects;
241 }
242
243 # this is where the input queue is dealt with and things are dispatched off to other parts of
244 # the cluster
245 sub process_inqueue
246 {
247         my $self = shift @inqueue;
248         return if !$self;
249         
250         my $data = $self->{data};
251         my $dxchan = $self->{dxchan};
252         my $error;
253         my ($sort, $call, $line) = DXChannel::decode_input($dxchan, $data);
254         return unless defined $sort;
255         
256         # do the really sexy console interface bit! (Who is going to do the TK interface then?)
257         dbg('chan', "<- $sort $call $line\n") unless $sort eq 'D';
258
259         # handle A records
260         my $user = $dxchan->user;
261         if ($sort eq 'A' || $sort eq 'O') {
262                 $dxchan->start($line, $sort);  
263         } elsif ($sort eq 'I') {
264                 die "\$user not defined for $call" if !defined $user;
265                 # normal input
266                 $dxchan->normal($line);
267                 disconnect($dxchan) if ($dxchan->{state} eq 'bye');
268         } elsif ($sort eq 'Z') {
269                 $dxchan->conn(undef);
270                 disconnect($dxchan);
271         } elsif ($sort eq 'D') {
272                 ;                       # ignored (an echo)
273         } else {
274                 print STDERR atime, " Unknown command letter ($sort) received from $call\n";
275         }
276 }
277
278 sub uptime
279 {
280         my $t = $systime - $starttime;
281         my $days = int $t / 86400;
282         $t -= $days * 86400;
283         my $hours = int $t / 3600;
284         $t -= $hours * 3600;
285         my $mins = int $t / 60;
286         return sprintf "%d %02d:%02d", $days, $hours, $mins;
287 }
288 #############################################################
289 #
290 # The start of the main line of code 
291 #
292 #############################################################
293
294 $starttime = $systime = time;
295
296 # open the debug file, set various FHs to be unbuffered
297 dbginit();
298 foreach (@debug) {
299         dbgadd($_);
300 }
301 STDOUT->autoflush(1);
302
303 Log('cluster', "DXSpider V$version started");
304
305 # banner
306 dbg('err', "DXSpider DX Cluster Version $version", "Copyright (c) 1998-2000 Dirk Koopman G1TLH");
307
308 # load Prefixes
309 dbg('err', "loading prefixes ...");
310 Prefix::load();
311
312 # load band data
313 dbg('err', "loading band data ...");
314 Bands::load();
315
316 # initialise User file system
317 dbg('err', "loading user file system ..."); 
318 DXUser->init($userfn, 1);
319
320 # start listening for incoming messages/connects
321 dbg('err', "starting listener ...");
322 Msg->new_server("$clusteraddr", $clusterport, \&login);
323
324 # prime some signals
325 $SIG{INT} = \&cease;
326 $SIG{TERM} = \&cease;
327 $SIG{HUP} = 'IGNORE';
328 $SIG{CHLD} = \&reap;
329
330 $SIG{PIPE} = sub {      dbg('err', "Broken PIPE signal received"); };
331 $SIG{IO} = sub {        dbg('err', "SIGIO received"); };
332 $SIG{WINCH} = $SIG{STOP} = $SIG{CONT} = 'IGNORE';
333 $SIG{KILL} = 'DEFAULT';     # as if it matters....
334
335 # catch the rest with a hopeful message
336 for (keys %SIG) {
337         if (!$SIG{$_}) {
338 #               dbg('chan', "Catching SIG $_");
339                 $SIG{$_} = sub { my $sig = shift;       DXDebug::confess("Caught signal $sig");  }; 
340         }
341 }
342
343 # read in system messages
344 DXM->init();
345
346 # read in command aliases
347 CmdAlias->init();
348
349 # initialise the Geomagnetic data engine
350 Geomag->init();
351 WCY->init();
352
353 # initial the Spot stuff
354 Spot->init();
355
356 # initialise the protocol engine
357 dbg('err', "reading in duplicate spot and WWV info ...");
358 DXProt->init();
359
360
361 # put in a DXCluster node for us here so we can add users and take them away
362 DXNode->new(0, $mycall, 0, 1, $DXProt::myprot_version); 
363
364 # read in any existing message headers and clean out old crap
365 dbg('err', "reading existing message headers ...");
366 DXMsg->init();
367 DXMsg::clean_old();
368
369 # read in any cron jobs
370 dbg('err', "reading cron jobs ...");
371 DXCron->init();
372
373 # read in database descriptors
374 dbg('err', "reading database descriptors ...");
375 DXDb::load();
376
377 # starting local stuff
378 dbg('err', "doing local initialisation ...");
379 eval {
380         Local::init();
381 };
382 dbg('local', "Local::init error $@") if $@;
383
384 # print various flags
385 #dbg('err', "seful info - \$^D: $^D \$^W: $^W \$^S: $^S \$^P: $^P");
386
387 # this, such as it is, is the main loop!
388 dbg('err', "orft we jolly well go ...");
389
390 #open(DB::OUT, "|tee /tmp/aa");
391
392 for (;;) {
393         my $timenow;
394 #       $DB::trace = 1;
395         
396         Msg->event_loop(1, 0.1);
397         $timenow = time;
398         process_inqueue();                      # read in lines from the input queue and despatch them
399 #       $DB::trace = 0;
400         
401         # do timed stuff, ongoing processing happens one a second
402         if ($timenow != $systime) {
403                 $systime = $timenow;
404                 $cldate = &cldate();
405                 $ztime = &ztime();
406                 DXCron::process();      # do cron jobs
407                 DXCommandmode::process(); # process ongoing command mode stuff
408                 DXProt::process();              # process ongoing ak1a pcxx stuff
409                 DXConnect::process();
410                 DXMsg::process();
411                 DXDb::process();
412                 DXUser::process();
413                 eval { 
414                         Local::process();       # do any localised processing
415                 };
416                 dbg('local', "Local::process error $@") if $@;
417         }
418         if ($decease) {
419                 last if --$decease <= 0;
420         }
421 }
422 cease(0);
423 exit(0);
424
425