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