fixed problem where two consoles with same call stopped the cluster
[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 = 5*60;          # run the queue every 5 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                         $work{"$f[2]$stream"} = $ref; # store in work
350                         $self->send(DXProt::pc30($f[2], $f[1], $stream)); # send ack 
351                         
352                         last SWITCH;
353                 }
354                 
355                 if ($pcno == 42) {              # abort transfer
356                         dbg('msg', "stream $f[3]: abort received\n");
357                         my $ref = $work{"$f[2]$f[3]"};
358                         if ($ref) {
359                                 $ref->stop_msg($self->call);
360                                 $ref = undef;
361                         }
362                         
363                         last SWITCH;
364                 }
365
366                 if ($pcno == 49) {      # global delete on subject
367                         for (@msg) {
368                                 if ($_->{from} eq $f[1] && $_->{subject} eq $f[2]) {
369                                         $_->del_msg();
370                                         Log('msg', "Message $_->{msgno} from $_->{from} ($_->{subject}) fully deleted");
371                                         DXProt::broadcast_ak1a($line, $self);
372                                 }
373                         }
374                 }
375         }
376 }
377
378
379 # store a message away on disc or whatever
380 #
381 # NOTE the second arg is a REFERENCE not a list
382 sub store
383 {
384         my $ref = shift;
385         my $lines = shift;
386         
387         # we only proceed if there are actually any lines in the file
388         if (!$lines || @{$lines} == 0) {
389                 return;
390         }
391         
392         if ($ref->{file}) {                     # a file
393                 dbg('msg', "To be stored in $ref->{to}\n");
394                 
395                 my $fh = new IO::File "$ref->{to}", "w";
396                 if (defined $fh) {
397                         my $line;
398                         foreach $line (@{$lines}) {
399                                 print $fh "$line\n";
400                         }
401                         $fh->close;
402                         dbg('msg', "file $ref->{to} stored\n");
403                         Log('msg', "file $ref->{to} from $ref->{from} stored" );
404                 } else {
405                         confess "can't open file $ref->{to} $!";  
406                 }
407         } else {                                        # a normal message
408
409                 # attempt to open the message file
410                 my $fn = filename($ref->{msgno});
411                 
412                 dbg('msg', "To be stored in $fn\n");
413                 
414                 # now save the file, overwriting what's there, YES I KNOW OK! (I will change it if it's a problem)
415                 my $fh = new IO::File "$fn", "w";
416                 if (defined $fh) {
417                         my $rr = $ref->{rrreq} ? '1' : '0';
418                         my $priv = $ref->{private} ? '1': '0';
419                         print $fh "=== $ref->{msgno}^$ref->{to}^$ref->{from}^$ref->{t}^$priv^$ref->{subject}^$ref->{origin}^$ref->{'read'}^$rr\n";
420                         print $fh "=== ", join('^', @{$ref->{gotit}}), "\n";
421                         my $line;
422                         $ref->{size} = 0;
423                         foreach $line (@{$lines}) {
424                                 $ref->{size} += (length $line) + 1;
425                                 print $fh "$line\n";
426                         }
427                         $fh->close;
428                         dbg('msg', "msg $ref->{msgno} stored\n");
429                         Log('msg', "msg $ref->{msgno} from $ref->{from} to $ref->{to} stored" );
430                 } else {
431                         confess "can't open msg file $fn $!";  
432                 }
433         }
434 }
435
436 # delete a message
437 sub del_msg
438 {
439         my $self = shift;
440         
441         # remove it from the active message list
442         @msg = map { $_ != $self ? $_ : () } @msg;
443         
444         # belt and braces (one day I will ask someone if this is REALLY necessary)
445         delete $self->{gotit};
446         delete $self->{list};
447         
448         # remove the file
449         unlink filename($self->{msgno});
450         dbg('msg', "deleting $self->{msgno}\n");
451 }
452
453 # clean out old messages from the message queue
454 sub clean_old
455 {
456         my $ref;
457         
458         # mark old messages for deletion
459         foreach $ref (@msg) {
460                 if (!$ref->{keep} && $ref->{t} < $main::systime - $maxage) {
461                         $ref->{deleteme} = 1;
462                         delete $ref->{gotit};
463                         delete $ref->{list};
464                         unlink filename($ref->{msgno});
465                         dbg('msg', "deleting old $ref->{msgno}\n");
466                 }
467         }
468         
469         # remove them all from the active message list
470         @msg = map { $_->{deleteme} ? () : $_ } @msg;
471         $last_clean = $main::systime;
472 }
473
474 # read in a message header
475 sub read_msg_header
476
477         my $fn = shift;
478         my $file;
479         my $line;
480         my $ref;
481         my @f;
482         my $size;
483         
484         $file = new IO::File;
485         if (!open($file, $fn)) {
486                 print "Error reading $fn $!\n";
487                 return undef;
488         }
489         $size = -s $fn;
490         $line = <$file>;                        # first line
491         chomp $line;
492         $size -= length $line;
493         if (! $line =~ /^===/o) {
494                 print "corrupt first line in $fn ($line)\n";
495                 return undef;
496         }
497         $line =~ s/^=== //o;
498         @f = split /\^/, $line;
499         $ref = DXMsg->alloc(@f);
500         
501         $line = <$file>;                        # second line
502         chomp $line;
503         $size -= length $line;
504         if (! $line =~ /^===/o) {
505                 print "corrupt second line in $fn ($line)\n";
506                 return undef;
507         }
508         $line =~ s/^=== //o;
509         $ref->{gotit} = [];
510         @f = split /\^/, $line;
511         push @{$ref->{gotit}}, @f;
512         $ref->{size} = $size;
513         
514         close($file);
515         
516         return $ref;
517 }
518
519 # read in a message header
520 sub read_msg_body
521 {
522         my $self = shift;
523         my $msgno = $self->{msgno};
524         my $file;
525         my $line;
526         my $fn = filename($msgno);
527         my @out;
528         
529         $file = new IO::File;
530         if (!open($file, $fn)) {
531                 print "Error reading $fn $!\n";
532                 return undef;
533         }
534         chomp (@out = <$file>);
535         close($file);
536         
537         shift @out if $out[0] =~ /^=== /;
538         shift @out if $out[0] =~ /^=== /;
539         return @out;
540 }
541
542 # send a tranche of lines to the other end
543 sub send_tranche
544 {
545         my ($self, $dxchan) = @_;
546         my @out;
547         my $to = $self->{tonode};
548         my $from = $self->{fromnode};
549         my $stream = $self->{stream};
550         my $lines = $self->{lines};
551         my ($c, $i);
552         
553         for ($i = 0, $c = $self->{count}; $i < $self->{linesreq} && $c < @$lines; $i++, $c++) {
554                 push @out, DXProt::pc29($to, $from, $stream, $lines->[$c]);
555     }
556     $self->{count} = $c;
557
558     push @out, DXProt::pc32($to, $from, $stream) if $i < $self->{linesreq};
559         $dxchan->send(@out);
560 }
561
562         
563 # find a message to send out and start the ball rolling
564 sub queue_msg
565 {
566         my $sort = shift;
567         my $call = shift;
568         my $ref;
569         my $clref;
570         my $dxchan;
571         my @nodelist = DXProt::get_all_ak1a();
572         
573         # bat down the message list looking for one that needs to go off site and whose
574         # nearest node is not busy.
575
576         dbg('msg', "queue msg ($sort)\n");
577         foreach $ref (@msg) {
578                 # firstly, is it private and unread? if so can I find the recipient
579                 # in my cluster node list offsite?
580
581                 # ignore 'delayed' messages until their waiting time has expired
582                 if (exists $ref->{waitt}) {
583                         next if $ref->{waitt} < $main::systime;
584                         delete $ref->{waitt};
585                 } 
586                 
587                 if ($ref->{private}) {
588                         if ($ref->{'read'} == 0) {
589                                 $clref = DXCluster->get_exact($ref->{to});
590                                 unless ($clref) {             # otherwise look for a homenode
591                                         my $uref = DXUser->get($ref->{to});
592                                         my $hnode =  $uref->homenode if $uref;
593                                         $clref = DXCluster->get_exact($hnode) if $hnode;
594                                 }
595                                 if ($clref && !grep { $clref->{dxchan} == $_ } DXCommandmode::get_all) {
596                                         $dxchan = $clref->{dxchan};
597                                         $ref->start_msg($dxchan) if $dxchan && $clref && !get_busy($dxchan->call) && $dxchan->state eq 'normal';
598                                 }
599                         }
600                 } elsif (!$sort) {
601                         # otherwise we are dealing with a bulletin, compare the gotit list with
602                         # the nodelist up above, if there are sites that haven't got it yet
603                         # then start sending it - what happens when we get loops is anyone's
604                         # guess, use (to, from, time, subject) tuple?
605                         my $noderef;
606                         foreach $noderef (@nodelist) {
607                                 next if $noderef->call eq $main::mycall;
608                                 next if grep { $_ eq $noderef->call } @{$ref->{gotit}};
609                                 next unless $ref->forward_it($noderef->call);           # check the forwarding file
610                                 # next if $noderef->isolate;               # maybe add code for stuff originated here?
611                                 # next if DXUser->get( ${$ref->{gotit}}[0] )->isolate;  # is the origin isolated?
612                                 
613                                 # if we are here we have a node that doesn't have this message
614                                 $ref->start_msg($noderef) if !get_busy($noderef->call)  && $noderef->state eq 'normal';
615                                 last;
616                         }
617                 }
618                 
619                 # if all the available nodes are busy then stop
620                 last if @nodelist == scalar grep { get_busy($_->call) } @nodelist;
621         }
622 }
623
624 # is there a message for me?
625 sub for_me
626 {
627         my $call = uc shift;
628         my $ref;
629         
630         foreach $ref (@msg) {
631                 # is it for me, private and unread? 
632                 if ($ref->{to} eq $call && $ref->{private}) {
633                         return 1 if !$ref->{'read'};
634                 }
635         }
636         return 0;
637 }
638
639 # start the message off on its travels with a PC28
640 sub start_msg
641 {
642         my ($self, $dxchan) = @_;
643         
644         dbg('msg', "start msg $self->{msgno}\n");
645         $self->{linesreq} = 5;
646         $self->{count} = 0;
647         $self->{tonode} = $dxchan->call;
648         $self->{fromnode} = $main::mycall;
649         $busy{$self->{tonode}} = $self;
650         $work{$self->{tonode}} = $self;
651         $dxchan->send(DXProt::pc28($self->{tonode}, $self->{fromnode}, $self->{to}, $self->{from}, $self->{t}, $self->{private}, $self->{subject}, $self->{origin}, $self->{rrreq}));
652 }
653
654 # get the ref of a busy node
655 sub get_busy
656 {
657         my $call = shift;
658         return $busy{$call};
659 }
660
661 # get the busy queue
662 sub get_all_busy
663 {
664         return values %busy;
665 }
666
667 # get the forwarding queue
668 sub get_fwq
669 {
670         return values %work;
671 }
672
673 # stop a message from continuing, clean it out, unlock interlocks etc
674 sub stop_msg
675 {
676         my $self = shift;
677         my $node = shift;
678         my $stream = $self->{stream} if exists $self->{stream};
679         
680         
681         dbg('msg', "stop msg $self->{msgno} -> node $node\n");
682         delete $work{$node};
683         delete $work{"$node$stream"} if $stream;
684         $self->workclean;
685         delete $busy{$node};
686 }
687
688 # get a new transaction number from the file specified
689 sub next_transno
690 {
691         my $name = shift;
692         $name =~ s/\W//og;                      # remove non-word characters
693         my $fn = "$msgdir/$name";
694         my $msgno;
695         
696         my $fh = new IO::File;
697         if (sysopen($fh, $fn, O_RDWR|O_CREAT, 0666)) {
698                 $fh->autoflush(1);
699                 $msgno = $fh->getline;
700                 chomp $msgno;
701                 $msgno++;
702                 seek $fh, 0, 0;
703                 $fh->print("$msgno\n");
704                 dbg('msg', "msgno $msgno allocated for $name\n");
705                 $fh->close;
706         } else {
707                 confess "can't open $fn $!";
708         }
709         return $msgno;
710 }
711
712 # initialise the message 'system', read in all the message headers
713 sub init
714 {
715         my $dir = new IO::File;
716         my @dir;
717         my $ref;
718
719         # load various control files
720         my @in = load_badmsg();
721         print "@in\n" if @in;
722         @in = load_forward();
723         print "@in\n" if @in;
724
725         # read in the directory
726         opendir($dir, $msgdir) or confess "can't open $msgdir $!";
727         @dir = readdir($dir);
728         closedir($dir);
729
730         @msg = ();
731         for (sort @dir) {
732                 next unless /^m\d+$/o;
733                 
734                 $ref = read_msg_header("$msgdir/$_");
735                 next unless $ref;
736                 
737                 # delete any messages to 'badmsg.pl' places
738                 if (grep $ref->{to} eq $_, @badmsg) {
739                         dbg('msg', "'Bad' TO address $ref->{to}");
740                         Log('msg', "'Bad' TO address $ref->{to}");
741                         $ref->del_msg;
742                         next;
743                 }
744
745                 # add the message to the available queue
746                 add_dir($ref); 
747         }
748 }
749
750 # add the message to the directory listing
751 sub add_dir
752 {
753         my $ref = shift;
754         confess "tried to add a non-ref to the msg directory" if !ref $ref;
755         push @msg, $ref;
756 }
757
758 # return all the current messages
759 sub get_all
760 {
761         return @msg;
762 }
763
764 # get a particular message
765 sub get
766 {
767         my $msgno = shift;
768         for (@msg) {
769                 return $_ if $_->{msgno} == $msgno;
770                 last if $_->{msgno} > $msgno;
771         }
772         return undef;
773 }
774
775 # return the official filename for a message no
776 sub filename
777 {
778         return sprintf "$msgdir/m%06d", shift;
779 }
780
781 #
782 # return a list of valid elements 
783
784
785 sub fields
786 {
787         return keys(%valid);
788 }
789
790 #
791 # return a prompt for a field
792 #
793
794 sub field_prompt
795
796         my ($self, $ele) = @_;
797         return $valid{$ele};
798 }
799
800 #
801 # send a message state machine
802 sub do_send_stuff
803 {
804         my $self = shift;
805         my $line = shift;
806         my @out;
807         
808         if ($self->state eq 'send1') {
809                 #  $DB::single = 1;
810                 confess "local var gone missing" if !ref $self->{loc};
811                 my $loc = $self->{loc};
812                 $loc->{subject} = $line;
813                 $loc->{lines} = [];
814                 $self->state('sendbody');
815                 #push @out, $self->msg('sendbody');
816                 push @out, $self->msg('m8');
817         } elsif ($self->state eq 'sendbody') {
818                 confess "local var gone missing" if !ref $self->{loc};
819                 my $loc = $self->{loc};
820                 if ($line eq "\032" || uc $line eq "/EX") {
821                         my $to;
822                         
823                         if (@{$loc->{lines}} > 0) {
824                                 foreach $to (@{$loc->{to}}) {
825                                         my $ref;
826                                         my $systime = $main::systime;
827                                         my $mycall = $main::mycall;
828                                         $ref = DXMsg->alloc(DXMsg::next_transno('Msgno'),
829                                                                                 uc $to,
830                                                                                 $self->call, 
831                                                                                 $systime,
832                                                                                 $loc->{private}, 
833                                                                                 $loc->{subject}, 
834                                                                                 $mycall,
835                                                                                 '0',
836                                                                                 $loc->{rrreq});
837                                         $ref->store($loc->{lines});
838                                         $ref->add_dir();
839                                         push @out, $self->msg('m11', $ref->{msgno}, $to);
840                                         #push @out, "msgno $ref->{msgno} sent to $to";
841                                         my $dxchan = DXChannel->get(uc $to);
842                                         if ($dxchan) {
843                                                 if ($dxchan->is_user()) {
844                                                         $dxchan->send($dxchan->msg('m9'));
845                                                 }
846                                         }
847                                 }
848                         }
849                         delete $loc->{lines};
850                         delete $loc->{to};
851                         delete $self->{loc};
852                         $self->func(undef);
853                         
854                         $self->state('prompt');
855                 } elsif ($line eq "\031" || uc $line eq "/ABORT" || uc $line eq "/QUIT") {
856                         #push @out, $self->msg('sendabort');
857                         push @out, $self->msg('m10');
858                         delete $loc->{lines};
859                         delete $loc->{to};
860                         delete $self->{loc};
861                         $self->func(undef);
862                         $self->state('prompt');
863                 } else {
864                         
865                         # i.e. it ain't and end or abort, therefore store the line
866                         push @{$loc->{lines}}, length($line) > 0 ? $line : " ";
867                 }
868         }
869         return (1, @out);
870 }
871
872 # return the standard directory line for this ref 
873 sub dir
874 {
875         my $ref = shift;
876         return sprintf "%6d%s%s%5d %8.8s %8.8s %-6.6s %5.5s %-30.30s", 
877                 $ref->msgno, $ref->read ? '-' : ' ', $ref->private ? 'p' : ' ', $ref->size,
878                         $ref->to, $ref->from, cldate($ref->t), ztime($ref->t), $ref->subject;
879 }
880
881 # load the forward table
882 sub load_forward
883 {
884         my @out;
885         do "$forwardfn" if -e "$forwardfn";
886         push @out, $@ if $@;
887         return @out;
888 }
889
890 # load the bad message table
891 sub load_badmsg
892 {
893         my @out;
894         do "$badmsgfn" if -e "$badmsgfn";
895         push @out, $@ if $@;
896         return @out;
897 }
898
899 #
900 # forward that message or not according to the forwarding table
901 # returns 1 for forward, 0 - to ignore
902 #
903
904 sub forward_it
905 {
906         my $ref = shift;
907         my $call = shift;
908         my $i;
909         
910         for ($i = 0; $i < @forward; $i += 5) {
911                 my ($sort, $field, $pattern, $action, $bbs) = @forward[$i..($i+4)]; 
912                 my $tested;
913                 
914                 # are we interested?
915                 last if $ref->{private} && $sort ne 'P';
916                 last if !$ref->{private} && $sort ne 'B';
917                 
918                 # select field
919                 $tested = $ref->{to} if $field eq 'T';
920                 $tested = $ref->{from} if $field eq 'F';
921                 $tested = $ref->{origin} if $field eq 'O';
922                 $tested = $ref->{subject} if $field eq 'S';
923
924                 if (!$pattern || $tested =~ m{$pattern}i) {
925                         return 0 if $action eq 'I';
926                         return 1 if !$bbs || grep $_ eq $call, @{$bbs};
927                 }
928         }
929         return 0;
930 }
931
932 no strict;
933 sub AUTOLOAD
934 {
935         my $self = shift;
936         my $name = $AUTOLOAD;
937         return if $name =~ /::DESTROY$/;
938         $name =~ s/.*:://o;
939         
940         confess "Non-existant field '$AUTOLOAD'" if !$valid{$name};
941         @_ ? $self->{$name} = shift : $self->{$name} ;
942 }
943
944 1;
945
946 __END__