146392f44f970a83eb269167c1590a29b71cb414
[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 # Notes for implementors:-
11 #
12 # PC28 field 11 is the RR required flag
13 # PC28 field 12 is a VIA routing (ie it is a node call) 
14 #
15
16 package DXMsg;
17
18 @ISA = qw(DXProt DXChannel);
19
20 use DXUtil;
21 use DXChannel;
22 use DXUser;
23 use DXM;
24 use DXCluster;
25 use DXProtVars;
26 use DXProtout;
27 use DXDebug;
28 use DXLog;
29 use IO::File;
30 use Fcntl;
31 use Carp;
32
33 use strict;
34 use vars qw(%work @msg $msgdir %valid %busy $maxage $last_clean
35                         @badmsg $badmsgfn $forwardfn @forward $timeout $waittime);
36
37 %work = ();                                             # outstanding jobs
38 @msg = ();                                              # messages we have
39 %busy = ();                                             # station interlocks
40 $msgdir = "$main::root/msg";    # directory contain the msgs
41 $maxage = 30 * 86400;                   # the maximum age that a message shall live for if not marked 
42 $last_clean = 0;                                # last time we did a clean
43 @forward = ();                  # msg forward table
44 $timeout = 30*60;               # forwarding timeout
45 $waittime = 60*60;              # time an aborted outgoing message waits before trying again
46
47 $badmsgfn = "$msgdir/badmsg.pl";  # list of TO address we wont store
48 $forwardfn = "$msgdir/forward.pl";  # the forwarding table
49
50 %valid = (
51                   fromnode => '9,From Node',
52                   tonode => '9,To Node',
53                   to => '0,To',
54                   from => '0,From',
55                   t => '0,Msg Time,cldatetime',
56                   private => '9,Private',
57                   subject => '0,Subject',
58                   linesreq => '0,Lines per Gob',
59                   rrreq => '9,Read Confirm',
60                   origin => '0,Origin',
61                   lines => '5,Data',
62                   stream => '9,Stream No',
63                   count => '9,Gob Linecnt',
64                   file => '9,File?,yesno',
65                   gotit => '9,Got it Nodes,parray',
66                   lines => '9,Lines,parray',
67                   'read' => '9,Times read',
68                   size => '0,Size',
69                   msgno => '0,Msgno',
70                   keep => '0,Keep this?,yesno',
71                   lastt => '9,Last processed,cldatetime',
72                   waitt => '9,Wait until,cldatetime',
73                  );
74
75 sub DESTROY
76 {
77         my $self = shift;
78         undef $self->{lines};
79         undef $self->{gotit};
80 }
81
82 # allocate a new object
83 # called fromnode, tonode, from, to, datetime, private?, subject, nolinesper  
84 sub alloc                  
85 {
86         my $pkg = shift;
87         my $self = bless {}, $pkg;
88         $self->{msgno} = shift;
89         my $to = shift;
90         #  $to =~ s/-\d+$//o;
91         $self->{to} = ($to eq $main::mycall) ? $main::myalias : $to;
92         my $from = shift;
93         $from =~ s/-\d+$//o;
94         $self->{from} = uc $from;
95         $self->{t} = shift;
96         $self->{private} = shift;
97         $self->{subject} = shift;
98         $self->{origin} = shift;
99         $self->{'read'} = shift;
100         $self->{rrreq} = shift;
101         $self->{gotit} = [];
102         $self->{lastt} = $main::systime;
103     
104         return $self;
105 }
106
107 sub workclean
108 {
109         my $ref = shift;
110         delete $ref->{lines};
111         delete $ref->{linesreq};
112         delete $ref->{tonode};
113         delete $ref->{fromnode};
114         delete $ref->{stream};
115         delete $ref->{lines};
116         delete $ref->{file};
117         delete $ref->{count};
118         delete $ref->{lastt} if exists $ref->{lastt};
119         delete $ref->{waitt} if exists $ref->{waitt};
120 }
121
122 sub process
123 {
124         my ($self, $line) = @_;
125
126         # this is periodic processing
127         if (!$self || !$line) {
128
129                 # wander down the work queue stopping any messages that have timed out
130                 for (keys %busy) {
131                         my $node = $_;
132                         my $ref = $busy{$_};
133                         if ($main::systime > $ref->{lastt} + $timeout) {
134                                 $ref->stop_msg($node);
135
136                                 # delay any outgoing messages that fail
137                                 $ref->{waitt} = $main::systime + $waittime if $node ne $main::mycall;
138                         }
139                 }
140                 
141                 # clean the message queue
142                 clean_old() if $main::systime - $last_clean > 3600 ;
143                 return;
144         }
145
146         my @f = split /\^/, $line;
147         my ($pcno) = $f[0] =~ /^PC(\d\d)/; # just get the number
148
149  SWITCH: {
150                 if ($pcno == 28) {              # incoming message
151
152                         # first look for any messages in the busy queue 
153                         # and cancel them this should both resolve timed out incoming messages
154                         # and crossing of message between nodes, incoming messages have priority
155                         if (exists $busy{$f[2]}) {
156                                 my $ref = $busy{$f[2]};
157                                 my $tonode = $ref->{tonode};
158                                 $ref->stop_msg($self->call);
159                         }
160
161                         my $t = cltounix($f[5], $f[6]);
162                         my $stream = next_transno($f[2]);
163                         my $ref = DXMsg->alloc($stream, uc $f[3], $f[4], $t, $f[7], $f[8], $f[13], '0', $f[11]);
164                         
165                         # fill in various forwarding state variables
166                         $ref->{fromnode} = $f[2];
167                         $ref->{tonode} = $f[1];
168                         $ref->{rrreq} = $f[11];
169                         $ref->{linesreq} = $f[10];
170                         $ref->{stream} = $stream;
171                         $ref->{count} = 0;      # no of lines between PC31s
172                         dbg('msg', "new message from $f[4] to $f[3] '$f[8]' stream $stream\n");
173                         $work{"$f[2]$stream"} = $ref; # store in work
174                         $busy{$f[2]} = $ref; # set interlock
175                         $self->send(DXProt::pc30($f[2], $f[1], $stream)); # send ack
176                         last SWITCH;
177                 }
178                 
179                 if ($pcno == 29) {              # incoming text
180                         my $ref = $work{"$f[2]$f[3]"};
181                         if ($ref) {
182                                 push @{$ref->{lines}}, $f[4];
183                                 $ref->{count}++;
184                                 if ($ref->{count} >= $ref->{linesreq}) {
185                                         $self->send(DXProt::pc31($f[2], $f[1], $f[3]));
186                                         dbg('msg', "stream $f[3]: $ref->{count} lines received\n");
187                                         $ref->{count} = 0;
188                                 }
189                                 $ref->{lastt} = $main::systime;
190                         }
191                         last SWITCH;
192                 }
193                 
194                 if ($pcno == 30) {              # this is a incoming subject ack
195                         my $ref = $work{$f[2]}; # note no stream at this stage
196                         if ($ref) {
197                                 delete $work{$f[2]};
198                                 $ref->{stream} = $f[3];
199                                 $ref->{count} = 0;
200                                 $ref->{linesreq} = 5;
201                                 $work{"$f[2]$f[3]"} = $ref;     # new ref
202                                 dbg('msg', "incoming subject ack stream $f[3]\n");
203                                 $busy{$f[2]} = $ref; # interlock
204                                 $ref->{lines} = [];
205                                 push @{$ref->{lines}}, ($ref->read_msg_body);
206                                 $ref->send_tranche($self);
207                                 $ref->{lastt} = $main::systime;
208                         } else {
209                                 $self->send(DXProt::pc42($f[2], $f[1], $f[3])); # unknown stream
210                         } 
211                         last SWITCH;
212                 }
213                 
214                 if ($pcno == 31) {              # acknowledge a tranche of lines
215                         my $ref = $work{"$f[2]$f[3]"};
216                         if ($ref) {
217                                 dbg('msg', "tranche ack stream $f[3]\n");
218                                 $ref->send_tranche($self);
219                                 $ref->{lastt} = $main::systime;
220                         } else {
221                                 $self->send(DXProt::pc42($f[2], $f[1], $f[3])); # unknown stream
222                         } 
223                         last SWITCH;
224                 }
225                 
226                 if ($pcno == 32) {              # incoming EOM
227                         dbg('msg', "stream $f[3]: EOM received\n");
228                         my $ref = $work{"$f[2]$f[3]"};
229                         if ($ref) {
230                                 $self->send(DXProt::pc33($f[2], $f[1], $f[3])); # acknowledge it
231                                 
232                                 # get the next msg no - note that this has NOTHING to do with the stream number in PC protocol
233                                 # store the file or message
234                                 # remove extraneous rubbish from the hash
235                                 # remove it from the work in progress vector
236                                 # stuff it on the msg queue
237                                 if ($ref->{lines} && @{$ref->{lines}} > 0) { # ignore messages with 0 lines
238                                         if ($ref->{file}) {
239                                                 $ref->store($ref->{lines});
240                                         } else {
241
242                                                 # does an identical message already exist?
243                                                 my $m;
244                                                 for $m (@msg) {
245                                                         if ($ref->{subject} eq $m->{subject} && $ref->{t} == $m->{t} && $ref->{from} eq $m->{from}) {
246                                                                 $ref->stop_msg($self->call);
247                                                                 my $msgno = $m->{msgno};
248                                                                 dbg('msg', "duplicate message to $msgno\n");
249                                                                 Log('msg', "duplicate message to $msgno");
250                                                                 return;
251                                                         }
252                                                 }
253                                                         
254                                                 # look for 'bad' to addresses 
255                                                 if (grep $ref->{to} eq $_, @badmsg) {
256                                                         $ref->stop_msg($self->call);
257                                                         dbg('msg', "'Bad' TO address $ref->{to}");
258                                                         Log('msg', "'Bad' TO address $ref->{to}");
259                                                         return;
260                                                 }
261
262                                                 $ref->{msgno} = next_transno("Msgno");
263                                                 push @{$ref->{gotit}}, $f[2]; # mark this up as being received
264                                                 $ref->store($ref->{lines});
265                                                 add_dir($ref);
266                                                 my $dxchan = DXChannel->get($ref->{to});
267                                                 $dxchan->send($dxchan->msg('m9')) if $dxchan;
268                                                 Log('msg', "Message $ref->{msgno} from $ref->{from} received from $f[2] for $ref->{to}");
269                                         }
270                                 }
271                                 $ref->stop_msg($self->call);
272                                 queue_msg(0);
273                         } else {
274                                 $self->send(DXProt::pc42($f[2], $f[1], $f[3])); # unknown stream
275                         }
276                         queue_msg(0);
277                         last SWITCH;
278                 }
279                 
280                 if ($pcno == 33) {              # acknowledge the end of message
281                         my $ref = $work{"$f[2]$f[3]"};
282                         if ($ref) {
283                                 if ($ref->{private}) { # remove it if it private and gone off site#
284                                         Log('msg', "Message $ref->{msgno} from $ref->{from} sent to $f[2] and deleted");
285                                         $ref->del_msg;
286                                 } else {
287                                         Log('msg', "Message $ref->{msgno} from $ref->{from} sent to $f[2]");
288                                         push @{$ref->{gotit}}, $f[2]; # mark this up as being received
289                                         $ref->store($ref->{lines});     # re- store the file
290                                 }
291                                 $ref->stop_msg($self->call);
292                         } else {
293                                 $self->send(DXProt::pc42($f[2], $f[1], $f[3])); # unknown stream
294                         } 
295                         queue_msg(0);
296                         last SWITCH;
297                 }
298                 
299                 if ($pcno == 40) {              # this is a file request
300                         $f[3] =~ s/\\/\//og; # change the slashes
301                         $f[3] =~ s/\.//og;      # remove dots
302                         $f[3] =~ s/^\///o;   # remove the leading /
303                         $f[3] = lc $f[3];       # to lower case;
304                         dbg('msg', "incoming file $f[3]\n");
305                         $f[3] = 'packclus/' . $f[3] unless $f[3] =~ /^packclus\//o;
306                         
307                         # create any directories
308                         my @part = split /\//, $f[3];
309                         my $part;
310                         my $fn = "$main::root";
311                         pop @part;                      # remove last part
312                         foreach $part (@part) {
313                                 $fn .= "/$part";
314                                 next if -e $fn;
315                                 last SWITCH if !mkdir $fn, 0777;
316                                 dbg('msg', "created directory $fn\n");
317                         }
318                         my $stream = next_transno($f[2]);
319                         my $ref = DXMsg->alloc($stream, "$main::root/$f[3]", $self->call, time, !$f[4], $f[3], ' ', '0', '0');
320                         
321                         # forwarding variables
322                         $ref->{fromnode} = $f[1];
323                         $ref->{tonode} = $f[2];
324                         $ref->{linesreq} = $f[5];
325                         $ref->{stream} = $stream;
326                         $ref->{count} = 0;      # no of lines between PC31s
327                         $ref->{file} = 1;
328                         $work{"$f[2]$stream"} = $ref; # store in work
329                         $self->send(DXProt::pc30($f[2], $f[1], $stream)); # send ack 
330                         
331                         last SWITCH;
332                 }
333                 
334                 if ($pcno == 42) {              # abort transfer
335                         dbg('msg', "stream $f[3]: abort received\n");
336                         my $ref = $work{"$f[2]$f[3]"};
337                         if ($ref) {
338                                 $ref->stop_msg($self->call);
339                                 $ref = undef;
340                         }
341                         
342                         last SWITCH;
343                 }
344
345                 if ($pcno == 49) {      # global delete on subject
346                         for (@msg) {
347                                 if ($_->{from} eq $f[1] && $_->{subject} eq $f[2]) {
348                                         $_->del_msg();
349                                         Log('msg', "Message $_->{msgno} from $_->{from} ($_->{subject}) fully deleted");
350                                         DXProt::broadcast_ak1a($line, $self);
351                                 }
352                         }
353                 }
354         }
355 }
356
357
358 # store a message away on disc or whatever
359 #
360 # NOTE the second arg is a REFERENCE not a list
361 sub store
362 {
363         my $ref = shift;
364         my $lines = shift;
365         
366         # we only proceed if there are actually any lines in the file
367         if (!$lines || @{$lines} == 0) {
368                 return;
369         }
370         
371         if ($ref->{file}) {                     # a file
372                 dbg('msg', "To be stored in $ref->{to}\n");
373                 
374                 my $fh = new IO::File "$ref->{to}", "w";
375                 if (defined $fh) {
376                         my $line;
377                         foreach $line (@{$lines}) {
378                                 print $fh "$line\n";
379                         }
380                         $fh->close;
381                         dbg('msg', "file $ref->{to} stored\n");
382                         Log('msg', "file $ref->{to} from $ref->{from} stored" );
383                 } else {
384                         confess "can't open file $ref->{to} $!";  
385                 }
386         } else {                                        # a normal message
387
388                 # attempt to open the message file
389                 my $fn = filename($ref->{msgno});
390                 
391                 dbg('msg', "To be stored in $fn\n");
392                 
393                 # now save the file, overwriting what's there, YES I KNOW OK! (I will change it if it's a problem)
394                 my $fh = new IO::File "$fn", "w";
395                 if (defined $fh) {
396                         my $rr = $ref->{rrreq} ? '1' : '0';
397                         my $priv = $ref->{private} ? '1': '0';
398                         print $fh "=== $ref->{msgno}^$ref->{to}^$ref->{from}^$ref->{t}^$priv^$ref->{subject}^$ref->{origin}^$ref->{'read'}^$rr\n";
399                         print $fh "=== ", join('^', @{$ref->{gotit}}), "\n";
400                         my $line;
401                         $ref->{size} = 0;
402                         foreach $line (@{$lines}) {
403                                 $ref->{size} += (length $line) + 1;
404                                 print $fh "$line\n";
405                         }
406                         $fh->close;
407                         dbg('msg', "msg $ref->{msgno} stored\n");
408                         Log('msg', "msg $ref->{msgno} from $ref->{from} to $ref->{to} stored" );
409                 } else {
410                         confess "can't open msg file $fn $!";  
411                 }
412         }
413 }
414
415 # delete a message
416 sub del_msg
417 {
418         my $self = shift;
419         
420         # remove it from the active message list
421         @msg = map { $_ != $self ? $_ : () } @msg;
422         
423         # belt and braces (one day I will ask someone if this is REALLY necessary)
424         delete $self->{gotit};
425         delete $self->{list};
426         
427         # remove the file
428         unlink filename($self->{msgno});
429         dbg('msg', "deleting $self->{msgno}\n");
430 }
431
432 # clean out old messages from the message queue
433 sub clean_old
434 {
435         my $ref;
436         
437         # mark old messages for deletion
438         foreach $ref (@msg) {
439                 if (!$ref->{keep} && $ref->{t} < $main::systime - $maxage) {
440                         $ref->{deleteme} = 1;
441                         delete $ref->{gotit};
442                         delete $ref->{list};
443                         unlink filename($ref->{msgno});
444                         dbg('msg', "deleting old $ref->{msgno}\n");
445                 }
446         }
447         
448         # remove them all from the active message list
449         @msg = map { $_->{deleteme} ? () : $_ } @msg;
450         $last_clean = $main::systime;
451 }
452
453 # read in a message header
454 sub read_msg_header
455
456         my $fn = shift;
457         my $file;
458         my $line;
459         my $ref;
460         my @f;
461         my $size;
462         
463         $file = new IO::File;
464         if (!open($file, $fn)) {
465                 print "Error reading $fn $!\n";
466                 return undef;
467         }
468         $size = -s $fn;
469         $line = <$file>;                        # first line
470         chomp $line;
471         $size -= length $line;
472         if (! $line =~ /^===/o) {
473                 print "corrupt first line in $fn ($line)\n";
474                 return undef;
475         }
476         $line =~ s/^=== //o;
477         @f = split /\^/, $line;
478         $ref = DXMsg->alloc(@f);
479         
480         $line = <$file>;                        # second line
481         chomp $line;
482         $size -= length $line;
483         if (! $line =~ /^===/o) {
484                 print "corrupt second line in $fn ($line)\n";
485                 return undef;
486         }
487         $line =~ s/^=== //o;
488         $ref->{gotit} = [];
489         @f = split /\^/, $line;
490         push @{$ref->{gotit}}, @f;
491         $ref->{size} = $size;
492         
493         close($file);
494         
495         return $ref;
496 }
497
498 # read in a message header
499 sub read_msg_body
500 {
501         my $self = shift;
502         my $msgno = $self->{msgno};
503         my $file;
504         my $line;
505         my $fn = filename($msgno);
506         my @out;
507         
508         $file = new IO::File;
509         if (!open($file, $fn)) {
510                 print "Error reading $fn $!\n";
511                 return undef;
512         }
513         chomp (@out = <$file>);
514         close($file);
515         
516         shift @out if $out[0] =~ /^=== /;
517         shift @out if $out[0] =~ /^=== /;
518         return @out;
519 }
520
521 # send a tranche of lines to the other end
522 sub send_tranche
523 {
524         my ($self, $dxchan) = @_;
525         my @out;
526         my $to = $self->{tonode};
527         my $from = $self->{fromnode};
528         my $stream = $self->{stream};
529         my $lines = $self->{lines};
530         my ($c, $i);
531         
532         for ($i = 0, $c = $self->{count}; $i < $self->{linesreq} && $c < @$lines; $i++, $c++) {
533                 push @out, DXProt::pc29($to, $from, $stream, $lines->[$c]);
534     }
535     $self->{count} = $c;
536
537     push @out, DXProt::pc32($to, $from, $stream) if $i < $self->{linesreq};
538         $dxchan->send(@out);
539 }
540
541         
542 # find a message to send out and start the ball rolling
543 sub queue_msg
544 {
545         my $sort = shift;
546         my $call = shift;
547         my $ref;
548         my $clref;
549         my $dxchan;
550         my @nodelist = DXProt::get_all_ak1a();
551         
552         # bat down the message list looking for one that needs to go off site and whose
553         # nearest node is not busy.
554
555         dbg('msg', "queue msg ($sort)\n");
556         foreach $ref (@msg) {
557                 # firstly, is it private and unread? if so can I find the recipient
558                 # in my cluster node list offsite?
559
560                 # ignore 'delayed' messages until their waiting time has expired
561                 if (exists $ref->{waitt}) {
562                         next if $ref->{waitt} < $main::systime;
563                         delete $ref->{waitt};
564                 } 
565                 
566                 if ($ref->{private}) {
567                         if ($ref->{'read'} == 0) {
568                                 $clref = DXCluster->get_exact($ref->{to});
569                                 unless ($clref) {             # otherwise look for a homenode
570                                         my $uref = DXUser->get($ref->{to});
571                                         my $hnode =  $uref->homenode if $uref;
572                                         $clref = DXCluster->get_exact($hnode) if $hnode;
573                                 }
574                                 if ($clref && !grep { $clref->{dxchan} == $_ } DXCommandmode::get_all) {
575                                         $dxchan = $clref->{dxchan};
576                                         $ref->start_msg($dxchan) if $dxchan && $clref && !get_busy($dxchan->call) && $dxchan->state eq 'normal';
577                                 }
578                         }
579                 } elsif (!$sort) {
580                         # otherwise we are dealing with a bulletin, compare the gotit list with
581                         # the nodelist up above, if there are sites that haven't got it yet
582                         # then start sending it - what happens when we get loops is anyone's
583                         # guess, use (to, from, time, subject) tuple?
584                         my $noderef;
585                         foreach $noderef (@nodelist) {
586                                 next if $noderef->call eq $main::mycall;
587                                 next if grep { $_ eq $noderef->call } @{$ref->{gotit}};
588                                 next unless $ref->forward_it($noderef->call);           # check the forwarding file
589                                 # next if $noderef->isolate;               # maybe add code for stuff originated here?
590                                 # next if DXUser->get( ${$ref->{gotit}}[0] )->isolate;  # is the origin isolated?
591                                 
592                                 # if we are here we have a node that doesn't have this message
593                                 $ref->start_msg($noderef) if !get_busy($noderef->call)  && $noderef->state eq 'normal';
594                                 last;
595                         }
596                 }
597                 
598                 # if all the available nodes are busy then stop
599                 last if @nodelist == scalar grep { get_busy($_->call) } @nodelist;
600         }
601 }
602
603 # is there a message for me?
604 sub for_me
605 {
606         my $call = uc shift;
607         my $ref;
608         
609         foreach $ref (@msg) {
610                 # is it for me, private and unread? 
611                 if ($ref->{to} eq $call && $ref->{private}) {
612                         return 1 if !$ref->{'read'};
613                 }
614         }
615         return 0;
616 }
617
618 # start the message off on its travels with a PC28
619 sub start_msg
620 {
621         my ($self, $dxchan) = @_;
622         
623         dbg('msg', "start msg $self->{msgno}\n");
624         $self->{linesreq} = 5;
625         $self->{count} = 0;
626         $self->{tonode} = $dxchan->call;
627         $self->{fromnode} = $main::mycall;
628         $busy{$self->{tonode}} = $self;
629         $work{$self->{tonode}} = $self;
630         $dxchan->send(DXProt::pc28($self->{tonode}, $self->{fromnode}, $self->{to}, $self->{from}, $self->{t}, $self->{private}, $self->{subject}, $self->{origin}, $self->{rrreq}));
631 }
632
633 # get the ref of a busy node
634 sub get_busy
635 {
636         my $call = shift;
637         return $busy{$call};
638 }
639
640 # get the busy queue
641 sub get_all_busy
642 {
643         return values %busy;
644 }
645
646 # get the forwarding queue
647 sub get_fwq
648 {
649         return values %work;
650 }
651
652 # stop a message from continuing, clean it out, unlock interlocks etc
653 sub stop_msg
654 {
655         my $self = shift;
656         my $node = shift;
657         my $stream = $self->{stream} if exists $self->{stream};
658         
659         
660         dbg('msg', "stop msg $self->{msgno} -> node $node\n");
661         delete $work{$node};
662         delete $work{"$node$stream"} if $stream;
663         $self->workclean;
664         delete $busy{$node};
665 }
666
667 # get a new transaction number from the file specified
668 sub next_transno
669 {
670         my $name = shift;
671         $name =~ s/\W//og;                      # remove non-word characters
672         my $fn = "$msgdir/$name";
673         my $msgno;
674         
675         my $fh = new IO::File;
676         if (sysopen($fh, $fn, O_RDWR|O_CREAT, 0666)) {
677                 $fh->autoflush(1);
678                 $msgno = $fh->getline;
679                 chomp $msgno;
680                 $msgno++;
681                 seek $fh, 0, 0;
682                 $fh->print("$msgno\n");
683                 dbg('msg', "msgno $msgno allocated for $name\n");
684                 $fh->close;
685         } else {
686                 confess "can't open $fn $!";
687         }
688         return $msgno;
689 }
690
691 # initialise the message 'system', read in all the message headers
692 sub init
693 {
694         my $dir = new IO::File;
695         my @dir;
696         my $ref;
697
698         # load various control files
699         my @in = load_badmsg();
700         print "@in\n" if @in;
701         @in = load_forward();
702         print "@in\n" if @in;
703
704         # read in the directory
705         opendir($dir, $msgdir) or confess "can't open $msgdir $!";
706         @dir = readdir($dir);
707         closedir($dir);
708
709         @msg = ();
710         for (sort @dir) {
711                 next unless /^m\d+$/o;
712                 
713                 $ref = read_msg_header("$msgdir/$_");
714                 next unless $ref;
715                 
716                 # delete any messages to 'badmsg.pl' places
717                 if (grep $ref->{to} eq $_, @badmsg) {
718                         dbg('msg', "'Bad' TO address $ref->{to}");
719                         Log('msg', "'Bad' TO address $ref->{to}");
720                         $ref->del_msg;
721                         next;
722                 }
723
724                 # add the message to the available queue
725                 add_dir($ref); 
726         }
727 }
728
729 # add the message to the directory listing
730 sub add_dir
731 {
732         my $ref = shift;
733         confess "tried to add a non-ref to the msg directory" if !ref $ref;
734         push @msg, $ref;
735 }
736
737 # return all the current messages
738 sub get_all
739 {
740         return @msg;
741 }
742
743 # get a particular message
744 sub get
745 {
746         my $msgno = shift;
747         for (@msg) {
748                 return $_ if $_->{msgno} == $msgno;
749                 last if $_->{msgno} > $msgno;
750         }
751         return undef;
752 }
753
754 # return the official filename for a message no
755 sub filename
756 {
757         return sprintf "$msgdir/m%06d", shift;
758 }
759
760 #
761 # return a list of valid elements 
762
763
764 sub fields
765 {
766         return keys(%valid);
767 }
768
769 #
770 # return a prompt for a field
771 #
772
773 sub field_prompt
774
775         my ($self, $ele) = @_;
776         return $valid{$ele};
777 }
778
779 #
780 # send a message state machine
781 sub do_send_stuff
782 {
783         my $self = shift;
784         my $line = shift;
785         my @out;
786         
787         if ($self->state eq 'send1') {
788                 #  $DB::single = 1;
789                 confess "local var gone missing" if !ref $self->{loc};
790                 my $loc = $self->{loc};
791                 $loc->{subject} = $line;
792                 $loc->{lines} = [];
793                 $self->state('sendbody');
794                 #push @out, $self->msg('sendbody');
795                 push @out, $self->msg('m8');
796         } elsif ($self->state eq 'sendbody') {
797                 confess "local var gone missing" if !ref $self->{loc};
798                 my $loc = $self->{loc};
799                 if ($line eq "\032" || uc $line eq "/EX") {
800                         my $to;
801                         
802                         if (@{$loc->{lines}} > 0) {
803                                 foreach $to (@{$loc->{to}}) {
804                                         my $ref;
805                                         my $systime = $main::systime;
806                                         my $mycall = $main::mycall;
807                                         $ref = DXMsg->alloc(DXMsg::next_transno('Msgno'),
808                                                                                 uc $to,
809                                                                                 $self->call, 
810                                                                                 $systime,
811                                                                                 $loc->{private}, 
812                                                                                 $loc->{subject}, 
813                                                                                 $mycall,
814                                                                                 '0',
815                                                                                 $loc->{rrreq});
816                                         $ref->store($loc->{lines});
817                                         $ref->add_dir();
818                                         push @out, $self->msg('m11', $ref->{msgno}, $to);
819                                         #push @out, "msgno $ref->{msgno} sent to $to";
820                                         my $dxchan = DXChannel->get(uc $to);
821                                         if ($dxchan) {
822                                                 if ($dxchan->is_user()) {
823                                                         $dxchan->send($dxchan->msg('m9'));
824                                                 }
825                                         }
826                                 }
827                         }
828                         delete $loc->{lines};
829                         delete $loc->{to};
830                         delete $self->{loc};
831                         $self->func(undef);
832                         
833                         DXMsg::queue_msg(0);
834                         $self->state('prompt');
835                 } elsif ($line eq "\031" || uc $line eq "/ABORT" || uc $line eq "/QUIT") {
836                         #push @out, $self->msg('sendabort');
837                         push @out, $self->msg('m10');
838                         delete $loc->{lines};
839                         delete $loc->{to};
840                         delete $self->{loc};
841                         $self->func(undef);
842                         $self->state('prompt');
843                 } else {
844                         
845                         # i.e. it ain't and end or abort, therefore store the line
846                         push @{$loc->{lines}}, length($line) > 0 ? $line : " ";
847                 }
848         }
849         return (1, @out);
850 }
851
852 # return the standard directory line for this ref 
853 sub dir
854 {
855         my $ref = shift;
856         return sprintf "%6d%s%s%5d %8.8s %8.8s %-6.6s %5.5s %-30.30s", 
857                 $ref->msgno, $ref->read ? '-' : ' ', $ref->private ? 'p' : ' ', $ref->size,
858                         $ref->to, $ref->from, cldate($ref->t), ztime($ref->t), $ref->subject;
859 }
860
861 # load the forward table
862 sub load_forward
863 {
864         my @out;
865         do "$forwardfn" if -e "$forwardfn";
866         push @out, $@ if $@;
867         return @out;
868 }
869
870 # load the bad message table
871 sub load_badmsg
872 {
873         my @out;
874         do "$badmsgfn" if -e "$badmsgfn";
875         push @out, $@ if $@;
876         return @out;
877 }
878
879 #
880 # forward that message or not according to the forwarding table
881 # returns 1 for forward, 0 - to ignore
882 #
883
884 sub forward_it
885 {
886         my $ref = shift;
887         my $call = shift;
888         my $i;
889         
890         for ($i = 0; $i < @forward; $i += 5) {
891                 my ($sort, $field, $pattern, $action, $bbs) = @forward[$i..($i+4)]; 
892                 my $tested;
893                 
894                 # are we interested?
895                 last if $ref->{private} && $sort ne 'P';
896                 last if !$ref->{private} && $sort ne 'B';
897                 
898                 # select field
899                 $tested = $ref->{to} if $field eq 'T';
900                 $tested = $ref->{from} if $field eq 'F';
901                 $tested = $ref->{origin} if $field eq 'O';
902                 $tested = $ref->{subject} if $field eq 'S';
903
904                 if (!$pattern || $tested =~ m{$pattern}i) {
905                         return 0 if $action eq 'I';
906                         return 1 if !$bbs || grep $_ eq $call, @{$bbs};
907                 }
908         }
909         return 0;
910 }
911
912 no strict;
913 sub AUTOLOAD
914 {
915         my $self = shift;
916         my $name = $AUTOLOAD;
917         return if $name =~ /::DESTROY$/;
918         $name =~ s/.*:://o;
919         
920         confess "Non-existant field '$AUTOLOAD'" if !$valid{$name};
921         @_ ? $self->{$name} = shift : $self->{$name} ;
922 }
923
924 1;
925
926 __END__