added logging
[spider.git] / perl / DXMsg.pm
1 #!/usr/bin/perl
2 #
3 # This module impliments the message handling for a dx cluster
4 #
5 # Copyright (c) 1998 Dirk Koopman G1TLH
6 #
7 # $Id$
8
9
10 package DXMsg;
11
12 @ISA = qw(DXProt DXChannel);
13
14 use DXUtil;
15 use DXChannel;
16 use DXUser;
17 use DXM;
18 use DXCluster;
19 use DXProtVars;
20 use DXProtout;
21 use DXDebug;
22 use DXLog;
23 use FileHandle;
24 use Carp;
25
26 use strict;
27 use vars qw(%work @msg $msgdir %valid %busy);
28
29 %work = ();                # outstanding jobs
30 @msg = ();                 # messages we have
31 %busy = ();                # station interlocks
32 $msgdir = "$main::root/msg";              # directory contain the msgs
33
34 %valid = (
35   fromnode => '9,From Node',
36   tonode => '9,To Node',
37   to => '0,To',
38   from => '0,From',
39   t => '0,Msg Time,cldatetime',
40   private => '9,Private',
41   subject => '0,Subject',
42   linesreq => '0,Lines per Gob',
43   rrreq => '9,Read Confirm',
44   origin => '0,Origin',
45   lines => '5,Data',
46   stream => '9,Stream No',
47   count => '9,Gob Linecnt',
48   file => '9,File?,yesno',
49   gotit => '9,Got it Nodes,parray',
50   lines => '9,Lines,parray',
51   read => '9,Times read',
52   size => '0,Size',
53   msgno => '0,Msgno',
54 );
55
56 # allocate a new object
57 # called fromnode, tonode, from, to, datetime, private?, subject, nolinesper  
58 sub alloc                  
59 {
60   my $pkg = shift;
61   my $self = bless {}, $pkg;
62   $self->{msgno} = shift;
63   $self->{to} = shift;
64   $self->{from} = shift;
65   $self->{t} = shift;
66   $self->{private} = shift;
67   $self->{subject} = shift;
68   $self->{origin} = shift;
69   $self->{read} = shift;
70   $self->{rrreq} = shift;
71   $self->{gotit} = [];
72     
73   return $self;
74 }
75
76 sub workclean
77 {
78   my $ref = shift;
79   delete $ref->{lines};
80   delete $ref->{linesreq};
81   delete $ref->{tonode};
82   delete $ref->{fromnode};
83   delete $ref->{stream};
84   delete $ref->{lines};
85   delete $ref->{file};
86   delete $ref->{count};
87 }
88
89 sub process
90 {
91   my ($self, $line) = @_;
92   my @f = split /[\^\~]/, $line;
93   my ($pcno) = $f[0] =~ /^PC(\d\d)/;          # just get the number
94   
95   SWITCH: {
96     if ($pcno == 28) {                        # incoming message
97           my $t = cltounix($f[5], $f[6]);
98           my $stream = next_transno($f[2]);
99           my $ref = DXMsg->alloc($stream, $f[3], $f[4], $t, $f[7], $f[8], $f[13], '0', $f[11]);
100           
101           # fill in various forwarding state variables
102       $ref->{fromnode} = $f[2];
103       $ref->{tonode} = $f[1];
104           $ref->{rrreq} = $f[11];
105           $ref->{linesreq} = $f[10];
106           $ref->{stream} = $stream;
107           $ref->{count} = 0;                      # no of lines between PC31s
108           dbg('msg', "new message from $f[4] to $f[3] '$f[8]' stream $stream\n");
109       $work{"$f[2]$stream"} = $ref;         # store in work
110           $busy{$f[2]} = $ref;                          # set interlock
111           $self->send(DXProt::pc30($f[2], $f[1], $stream)); # send ack
112           last SWITCH;
113         }
114         
115     if ($pcno == 29) {                        # incoming text
116           my $ref = $work{"$f[2]$f[3]"};
117           if ($ref) {
118             push @{$ref->{lines}}, $f[4];
119                 $ref->{count}++;
120                 if ($ref->{count} >= $ref->{linesreq}) {
121                   $self->send(DXProt::pc31($f[2], $f[1], $f[3]));
122                   dbg('msg', "stream $f[3]: $ref->{linereq} lines received\n");
123                   $ref->{count} = 0;
124                 }
125           }
126           last SWITCH;
127         }
128         
129     if ($pcno == 30) {                        # this is a incoming subject ack
130           my $ref = $work{$f[2]};          # note no stream at this stage
131           delete $work{$f[2]};
132           $ref->{stream} = $f[3];
133           $ref->{count} = 0;
134           $ref->{linesreq} = 5;
135           $work{"$f[2]$f[3]"} = $ref;        # new ref
136           dbg('msg', "incoming subject ack stream $f[3]\n");
137           $busy{$f[2]} = $ref;                       # interlock
138           $ref->{lines} = [];
139           push @{$ref->{lines}}, ($ref->read_msg_body);
140           $ref->send_tranche($self);
141           last SWITCH;
142         }
143         
144     if ($pcno == 31) {                        # acknowledge a tranche of lines
145           my $ref = $work{"$f[2]$f[3]"};
146           if ($ref) {
147             dbg('msg', "tranche ack stream $f[3]\n");
148             $ref->send_tranche($self);
149           } else {
150             $self->send(DXProt::pc42($f[2], $f[1], $f[3]));       # unknown stream
151           } 
152           last SWITCH;
153         }
154         
155     if ($pcno == 32) {                         # incoming EOM
156           dbg('msg', "stream $f[3]: EOM received\n");
157           my $ref = $work{"$f[2]$f[3]"};
158           if ($ref) {
159             $self->send(DXProt::pc33($f[2], $f[1], $f[3]));# acknowledge it
160                 
161                 # get the next msg no - note that this has NOTHING to do with the stream number in PC protocol
162                 # store the file or message
163                 # remove extraneous rubbish from the hash
164                 # remove it from the work in progress vector
165                 # stuff it on the msg queue
166                 if ($ref->{lines} && @{$ref->{lines}} > 0) {            # ignore messages with 0 lines
167                   $ref->{msgno} = next_transno("Msgno") if !$ref->{file};
168               push @{$ref->{gotit}}, $f[2];           # mark this up as being received
169                   $ref->store($ref->{lines});
170                   add_dir($ref);
171                   my $dxchan = DXChannel->get($ref->{to});
172                   $dxchan->send("New mail has arrived for you") if $dxchan;
173                 }
174                 $ref->stop_msg($self);
175                 queue_msg();
176           } else {
177             $self->send(DXProt::pc42($f[2], $f[1], $f[3]));       # unknown stream
178           }
179           queue_msg();
180           last SWITCH;
181         }
182         
183     if ($pcno == 33) {                         # acknowledge the end of message
184           my $ref = $work{"$f[2]$f[3]"};
185           if ($ref) {
186                 if ($ref->{private}) {                   # remove it if it private and gone off site#
187               $ref->del_msg;
188             } else {
189               push @{$ref->{gotit}}, $f[2];           # mark this up as being received
190                   $ref->store($ref->{lines});             # re- store the file
191             }
192         $ref->stop_msg($self);
193           } else {
194             $self->send(DXProt::pc42($f[2], $f[1], $f[3]));       # unknown stream
195           } 
196           queue_msg();
197           last SWITCH;
198         }
199         
200         if ($pcno == 40) {                         # this is a file request
201           $f[3] =~ s/\\/\//og;                     # change the slashes
202           $f[3] =~ s/\.//og;                       # remove dots
203           $f[3] = lc $f[3];                        # to lower case;
204           dbg('msg', "incoming file $f[3]\n");
205           last SWITCH if $f[3] =~ /^\/(perl|cmd|local_cmd|src|lib|include|sys|msg)\//;    # prevent access to executables
206           
207           # create any directories
208           my @part = split /\//, $f[3];
209           my $part;
210           my $fn = "$main::root";
211           pop @part;         # remove last part
212           foreach $part (@part) {
213             $fn .= "/$part";
214                 next if -e $fn;
215             last SWITCH if !mkdir $fn, 0777;
216         dbg('msg', "created directory $fn\n");
217           }
218           my $stream = next_transno($f[2]);
219           my $ref = DXMsg->alloc($stream, "$main::root/$f[3]", $self->call, time, !$f[4], $f[3], ' ', '0', '0');
220           
221           # forwarding variables
222       $ref->{fromnode} = $f[1];
223       $ref->{tonode} = $f[2];
224           $ref->{linesreq} = $f[5];
225           $ref->{stream} = $stream;
226           $ref->{count} = 0;                      # no of lines between PC31s
227           $ref->{file} = 1;
228       $work{"$f[2]$stream"} = $ref;         # store in work
229           $self->send(DXProt::pc30($f[2], $f[1], $stream));  # send ack 
230           
231           last SWITCH;
232         }
233         
234         if ($pcno == 42) {                        # abort transfer
235           dbg('msg', "stream $f[3]: abort received\n");
236           my $ref = $work{"$f[2]$f[3]"};
237           if ($ref) {
238             $ref->stop_msg($self);
239                 $ref = undef;
240           }
241           
242           last SWITCH;
243         }
244   }
245 }
246
247
248 # store a message away on disc or whatever
249 #
250 # NOTE the second arg is a REFERENCE not a list
251 sub store
252 {
253   my $ref = shift;
254   my $lines = shift;
255   
256   # we only proceed if there are actually any lines in the file
257   if (!$lines || @{$lines} == 0) {
258         return;
259   }
260   
261   if ($ref->{file}) {   # a file
262     dbg('msg', "To be stored in $ref->{to}\n");
263   
264     my $fh = new FileHandle "$ref->{to}", "w";
265         if (defined $fh) {
266           my $line;
267           foreach $line (@{$lines}) {
268                 print $fh "$line\n";
269           }
270           $fh->close;
271           dbg('msg', "file $ref->{to} stored\n");
272           Log('msg', "file $ref->{to} from $ref->{from} stored" );
273     } else {
274       confess "can't open file $ref->{to} $!";  
275     }
276 #       push @{$ref->{gotit}}, $ref->{fromnode} if $ref->{fromnode};
277   } else {              # a normal message
278
279     # attempt to open the message file
280         my $fn = filename($ref->{msgno});
281
282     dbg('msg', "To be stored in $fn\n");
283     
284         # now save the file, overwriting what's there, YES I KNOW OK! (I will change it if it's a problem)
285     my $fh = new FileHandle "$fn", "w";
286         if (defined $fh) {
287           my $rr = $ref->{rrreq} ? '1' : '0';
288           my $priv = $ref->{private} ? '1': '0';
289       print $fh "=== $ref->{msgno}^$ref->{to}^$ref->{from}^$ref->{t}^$priv^$ref->{subject}^$ref->{origin}^$ref->{read}^$rr\n";
290           print $fh "=== ", join('^', @{$ref->{gotit}}), "\n";
291           my $line;
292           $ref->{size} = 0;
293           foreach $line (@{$lines}) {
294         $ref->{size} += (length $line) + 1;
295                 print $fh "$line\n";
296           }
297           $fh->close;
298           dbg('msg', "msg $ref->{msgno} stored\n");
299           Log('msg', "msg $ref->{msgno} from $ref->{from} to $ref->{to} stored" );
300     } else {
301       confess "can't open msg file $fn $!";  
302     }
303   }
304 }
305
306 # delete a message
307 sub del_msg
308 {
309   my $self = shift;
310
311   # remove it from the active message list
312   @msg = map { $_ != $self ? $_ : () } @msg;
313   
314   # belt and braces (one day I will ask someone if this is REALLY necessary)
315   delete $self->{gotit};
316   delete $self->{list};
317   
318   # remove the file
319   unlink filename($self->{msgno});
320   dbg('msg', "deleting $self->{msgno}\n");
321 }
322
323 # read in a message header
324 sub read_msg_header
325
326   my $fn = shift;
327   my $file;
328   my $line;
329   my $ref;
330   my @f;
331   my $size;
332
333   $file = new FileHandle;
334   if (!open($file, $fn)) {
335     print "Error reading $fn $!\n";
336     return undef;
337   }
338   $size = -s $fn;
339   $line = <$file>;       # first line
340   chomp $line;
341   $size -= length $line;
342   if (! $line =~ /^===/o) {
343     print "corrupt first line in $fn ($line)\n";
344     return undef;
345   }
346   $line =~ s/^=== //o;
347   @f = split /\^/, $line;
348   $ref = DXMsg->alloc(@f);
349   
350   $line = <$file>;       # second line
351   chomp $line;
352   $size -= length $line;
353   if (! $line =~ /^===/o) {
354     print "corrupt second line in $fn ($line)\n";
355     return undef;
356   }
357   $line =~ s/^=== //o;
358   $ref->{gotit} = [];
359   @f = split /\^/, $line;
360   push @{$ref->{gotit}}, @f;
361   $ref->{size} = $size;
362  
363   close($file);
364   
365   return $ref;
366 }
367
368 # read in a message header
369 sub read_msg_body
370 {
371   my $self = shift;
372   my $msgno = $self->{msgno};
373   my $file;
374   my $line;
375   my $fn = filename($msgno);
376   my @out;
377
378   $file = new FileHandle;
379   if (!open($file, $fn)) {
380     print "Error reading $fn $!\n";
381     return undef;
382   }
383   chomp (@out = <$file>);
384   close($file);
385   
386   shift @out if $out[0] =~ /^=== /;
387   shift @out if $out[0] =~ /^=== /;
388   return @out;
389 }
390
391 # send a tranche of lines to the other end
392 sub send_tranche
393 {
394   my ($self, $dxchan) = @_;
395   my @out;
396   my $to = $self->{tonode};
397   my $from = $self->{fromnode};
398   my $stream = $self->{stream};
399   my $i;
400   
401   for ($i = 0; $i < $self->{linesreq} && $self->{count} < @{$self->{lines}}; $i++, $self->{count}++) {
402     push @out, DXProt::pc29($to, $from, $stream, ${$self->{lines}}[$self->{count}]);
403   }
404   push @out, DXProt::pc32($to, $from, $stream) if $i < $self->{linesreq};
405   $dxchan->send(@out);
406 }
407
408
409 # find a message to send out and start the ball rolling
410 sub queue_msg
411 {
412   my $sort = shift;
413   my @nodelist = DXProt::get_all_ak1a();
414   my $ref;
415   my $clref;
416   my $dxchan;
417   
418   # bat down the message list looking for one that needs to go off site and whose
419   # nearest node is not busy.
420
421   dbg('msg', "queue msg ($sort)\n");
422   foreach $ref (@msg) {
423     # firstly, is it private and unread? if so can I find the recipient
424         # in my cluster node list offsite?
425         if ($ref->{private}) {
426           if ($ref->{read} == 0) {
427             $clref = DXCluster->get($ref->{to});
428                 if ($clref && !grep { $clref->{dxchan} == $_ } DXCommandmode::get_all) {
429                   $dxchan = $clref->{dxchan};
430                   $ref->start_msg($dxchan) if $clref && !get_busy($dxchan->call);
431                 }
432           }
433         } elsif ($sort == undef) {
434       # otherwise we are dealing with a bulletin, compare the gotit list with
435           # the nodelist up above, if there are sites that haven't got it yet
436           # then start sending it - what happens when we get loops is anyone's
437           # guess, use (to, from, time, subject) tuple?
438           my $noderef;
439           foreach $noderef (@nodelist) {
440             next if $noderef->call eq $main::mycall;
441                 next if grep { $_ eq $noderef->call } @{$ref->{gotit}};
442                 
443                 # if we are here we have a node that doesn't have this message
444                 $ref->start_msg($noderef) if !get_busy($noderef->call);
445                 last;
446           } 
447         }
448         
449         # if all the available nodes are busy then stop
450         last if @nodelist == scalar grep { get_busy($_->call) } @nodelist;
451   }
452 }
453
454 # start the message off on its travels with a PC28
455 sub start_msg
456 {
457   my ($self, $dxchan) = @_;
458
459   dbg('msg', "start msg $self->{msgno}\n");
460   $self->{linesreq} = 5;
461   $self->{count} = 0;
462   $self->{tonode} = $dxchan->call;
463   $self->{fromnode} = $main::mycall;
464   $busy{$dxchan->call} = $self;
465   $work{"$self->{tonode}"} = $self;
466   $dxchan->send(DXProt::pc28($self->{tonode}, $self->{fromnode}, $self->{to}, $self->{from}, $self->{t}, $self->{private}, $self->{subject}, $self->{origin}, $self->{rrreq}));
467 }
468
469 # get the ref of a busy node
470 sub get_busy
471 {
472   my $call = shift;
473   return $busy{$call};
474 }
475
476 # get the busy queue
477 sub get_all_busy
478 {
479   return values %busy;
480 }
481
482 # get the forwarding queue
483 sub get_fwq
484 {
485   return values %work;
486 }
487
488 # stop a message from continuing, clean it out, unlock interlocks etc
489 sub stop_msg
490 {
491   my ($self, $dxchan) = @_;
492   my $node = $dxchan->call;
493
494   dbg('msg', "stop msg $self->{msgno} stream $self->{stream}\n");
495   delete $work{$node};
496   delete $work{"$node$self->{stream}"};
497   $self->workclean;
498   delete $busy{$node};
499 }
500
501 # get a new transaction number from the file specified
502 sub next_transno
503 {
504   my $name = shift;
505   $name =~ s/\W//og;      # remove non-word characters
506   my $fn = "$msgdir/$name";
507   my $msgno;
508   
509   my $fh = new FileHandle;
510   if (sysopen($fh, $fn, O_RDWR|O_CREAT, 0666)) {
511     $fh->autoflush(1);
512         $msgno = $fh->getline;
513         chomp $msgno;
514         $msgno++;
515         seek $fh, 0, 0;
516         $fh->print("$msgno\n");
517         dbg('msg', "msgno $msgno allocated for $name\n");
518         $fh->close;
519   } else {
520     confess "can't open $fn $!";
521   }
522   return $msgno;
523 }
524
525 # initialise the message 'system', read in all the message headers
526 sub init
527 {
528   my $dir = new FileHandle;
529   my @dir;
530   my $ref;
531
532   # read in the directory
533   opendir($dir, $msgdir) or confess "can't open $msgdir $!";
534   @dir = readdir($dir);
535   closedir($dir);
536   
537   for (sort @dir) {
538     next if /^\./o;
539         next if ! /^m\d+/o;
540
541     $ref = read_msg_header("$msgdir/$_");
542         next if !$ref;
543         
544         # add the message to the available queue
545         add_dir($ref); 
546         
547   }
548 }
549
550 # add the message to the directory listing
551 sub add_dir
552 {
553   my $ref = shift;
554   confess "tried to add a non-ref to the msg directory" if !ref $ref;
555   push @msg, $ref;
556 }
557
558 # return all the current messages
559 sub get_all
560 {
561   return @msg;
562 }
563
564 # get a particular message
565 sub get
566 {
567   my $msgno = shift;
568   for (@msg) {
569     return $_ if $_->{msgno} == $msgno;
570     last if $_->{msgno} > $msgno;
571   }
572   return undef;
573 }
574
575 # return the official filename for a message no
576 sub filename
577 {
578   return sprintf "$msgdir/m%06d", shift;
579 }
580
581 #
582 # return a list of valid elements 
583
584
585 sub fields
586 {
587   return keys(%valid);
588 }
589
590 #
591 # return a prompt for a field
592 #
593
594 sub field_prompt
595
596   my ($self, $ele) = @_;
597   return $valid{$ele};
598 }
599
600 #
601 # send a message state machine
602 sub do_send_stuff
603 {
604   my $self = shift;
605   my $line = shift;
606   my @out;
607   
608   if ($self->state eq 'send1') {
609 #  $DB::single = 1;
610     confess "local var gone missing" if !ref $self->{loc};
611         my $loc = $self->{loc};
612         $loc->{subject} = $line;
613         $loc->{lines} = [];
614         $self->state('sendbody');
615         #push @out, $self->msg('sendbody');
616         push @out, "Enter Message /EX (^Z) to send or /ABORT (^Y) to exit";
617   } elsif ($self->state eq 'sendbody') {
618     confess "local var gone missing" if !ref $self->{loc};
619         my $loc = $self->{loc};
620         if ($line eq "\032" || uc $line eq "/EX") {
621       my $to;
622
623       if (@{$loc->{lines}} > 0) {
624             foreach $to (@{$loc->{to}}) {
625               my $ref;
626                   my $systime = $main::systime;
627                   my $mycall = $main::mycall;
628                   $ref = DXMsg->alloc(DXMsg::next_transno('Msgno'),
629                                 uc $to,
630                                                         $self->call, 
631                                                         $systime,
632                                                         $loc->{private}, 
633                                                         $loc->{subject}, 
634                                                         $mycall,
635                                                         '0',
636                                                         $loc->{rrreq});
637               $ref->store($loc->{lines});
638                   $ref->add_dir();
639                   #push @out, $self->msg('sendsent', $to);
640                   push @out, "msgno $ref->{msgno} sent to $to";
641                   my $dxchan = DXChannel->get(uc $to);
642                   $dxchan->send("New mail has arrived for you") if $dxchan;
643             }
644           }
645           delete $loc->{lines};
646           delete $loc->{to};
647           delete $self->{loc};
648           $self->state('prompt');
649           $self->func(undef);
650           DXMsg::queue_msg();
651     } elsif ($line eq "\031" || uc $line eq "/ABORT" || uc $line eq "/QUIT") {
652       #push @out, $self->msg('sendabort');
653           push @out, "aborted";
654           delete $loc->{lines};
655           delete $loc->{to};
656           delete $self->{loc};
657           $self->func(undef);
658           $self->state('prompt');
659     } else {
660   
661       # i.e. it ain't and end or abort, therefore store the line
662       push @{$loc->{lines}}, $line;
663     }
664   }
665   return (1, @out);
666 }
667
668 # return the standard directory line for this ref 
669 sub dir
670 {
671   my $ref = shift;
672   return sprintf "%6d%s%s%5d %8.8s %8.8s %-6.6s %5.5s %-30.30s", 
673     $ref->msgno, $ref->read ? '-' : ' ', $ref->private ? 'p' : ' ', $ref->size,
674         $ref->to, $ref->from, cldate($ref->t), ztime($ref->t), $ref->subject;
675 }
676
677 no strict;
678 sub AUTOLOAD
679 {
680   my $self = shift;
681   my $name = $AUTOLOAD;
682   return if $name =~ /::DESTROY$/;
683   $name =~ s/.*:://o;
684   
685   confess "Non-existant field '$AUTOLOAD'" if !$valid{$name};
686   @_ ? $self->{$name} = shift : $self->{$name} ;
687 }
688
689 1;
690
691 __END__