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