put in fix for arcluster bug
[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 use DXUtil;
19 use DXChannel;
20 use DXUser;
21 use DXM;
22 use DXCluster;
23 use DXProtVars;
24 use DXProtout;
25 use DXDebug;
26 use DXLog;
27 use IO::File;
28 use Fcntl;
29
30 use strict;
31 use vars qw(%work @msg $msgdir %valid %busy $maxage $last_clean
32                         @badmsg @swop $swopfn $badmsgfn $forwardfn @forward $timeout $waittime
33                     $queueinterval $lastq $importfn $minchunk $maxchunk $bulltopriv);
34
35 %work = ();                                             # outstanding jobs
36 @msg = ();                                              # messages we have
37 %busy = ();                                             # station interlocks
38 $msgdir = "$main::root/msg";    # directory contain the msgs
39 $maxage = 30 * 86400;                   # the maximum age that a message shall live for if not marked 
40 $last_clean = 0;                                # last time we did a clean
41 @forward = ();                  # msg forward table
42 @badmsg = ();                                   # bad message table
43 @swop = ();                                             # swop table
44 $timeout = 30*60;               # forwarding timeout
45 $waittime = 30*60;              # time an aborted outgoing message waits before trying again
46 $queueinterval = 1*60;          # run the queue every 1 minute
47 $lastq = 0;
48
49 $minchunk = 4800;               # minimum chunk size for a split message
50 $maxchunk = 6000;               # maximum chunk size
51 $bulltopriv = 1;                                # convert msgs with callsigns to private if they are bulls
52
53
54 $badmsgfn = "$msgdir/badmsg.pl";    # list of TO address we wont store
55 $forwardfn = "$msgdir/forward.pl";  # the forwarding table
56 $swopfn = "$msgdir/swop.pl";        # the swopping table
57 $importfn = "$msgdir/import";       # import directory
58
59
60 %valid = (
61                   fromnode => '5,From Node',
62                   tonode => '5,To Node',
63                   to => '0,To',
64                   from => '0,From',
65                   t => '0,Msg Time,cldatetime',
66                   private => '5,Private',
67                   subject => '0,Subject',
68                   linesreq => '0,Lines per Gob',
69                   rrreq => '5,Read Confirm',
70                   origin => '0,Origin',
71                   lines => '5,Data',
72                   stream => '9,Stream No',
73                   count => '5,Gob Linecnt',
74                   file => '5,File?,yesno',
75                   gotit => '5,Got it Nodes,parray',
76                   lines => '5,Lines,parray',
77                   'read' => '5,Times read',
78                   size => '0,Size',
79                   msgno => '0,Msgno',
80                   keep => '0,Keep this?,yesno',
81                   lastt => '5,Last processed,cldatetime',
82                   waitt => '5,Wait until,cldatetime',
83                  );
84
85 # allocate a new object
86 # called fromnode, tonode, from, to, datetime, private?, subject, nolinesper  
87 sub alloc                  
88 {
89         my $pkg = shift;
90         my $self = bless {}, $pkg;
91         $self->{msgno} = shift;
92         my $to = shift;
93         #  $to =~ s/-\d+$//o;
94         $self->{to} = ($to eq $main::mycall) ? $main::myalias : $to;
95         my $from = shift;
96         $from =~ s/-\d+$//o;
97         $self->{from} = uc $from;
98         $self->{t} = shift;
99         $self->{private} = shift;
100         $self->{subject} = shift;
101         $self->{origin} = shift;
102         $self->{'read'} = shift;
103         $self->{rrreq} = shift;
104         $self->{gotit} = [];
105 #       $self->{lastt} = $main::systime;
106         $self->{lines} = [];
107         $self->{private} = 1 if $bulltopriv && DXUser->get_current($self->{to});
108     
109         return $self;
110 }
111
112 sub workclean
113 {
114         my $ref = shift;
115         delete $ref->{lines};
116         delete $ref->{linesreq};
117         delete $ref->{tonode};
118         delete $ref->{fromnode};
119         delete $ref->{stream};
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                 if ($main::systime >= $lastq + $queueinterval) {
134
135                         # queue some message if the interval timer has gone off
136                         queue_msg(0);
137
138                         # import any messages in the import directory
139                         import_msgs();
140                         
141                         $lastq = $main::systime;
142                 }
143
144                 # clean the message queue
145                 clean_old() if $main::systime - $last_clean > 3600 ;
146                 return;
147         }
148
149         my @f = split /\^/, $line;
150         my ($pcno) = $f[0] =~ /^PC(\d\d)/; # just get the number
151
152  SWITCH: {
153                 if ($pcno == 28) {              # incoming message
154
155                         # sort out various extant protocol errors that occur
156                         my ($fromnode, $origin);
157                         if ($self->is_arcluster && $f[13] eq $self->call) {
158                                 $fromnode = $f[13];
159                                 $origin = $f[2];
160                         } else {
161                                 $fromnode = $f[2];
162                             $origin = $f[13];
163                         }
164                         $origin = $self->call unless $origin && $origin gt ' ';
165
166                         # first look for any messages in the busy queue 
167                         # and cancel them this should both resolve timed out incoming messages
168                         # and crossing of message between nodes, incoming messages have priority
169                         if (exists $busy{$fromnode}) {
170                                 my $ref = $busy{$fromnode};
171                                 my $tonode = $ref->{tonode};
172                                 dbg('msg', "Busy, stopping msgno: $ref->{msgno} -> $fromnode");
173                                 $ref->stop_msg($self->call);
174                         }
175
176                         my $t = cltounix($f[5], $f[6]);
177                         my $stream = next_transno($fromnode);
178                         my $ref = DXMsg->alloc($stream, uc $f[3], $f[4], $t, $f[7], $f[8], $origin, '0', $f[11]);
179                         
180                         # fill in various forwarding state variables
181                         $ref->{fromnode} = $fromnode;
182                         $ref->{tonode} = $f[1];
183                         $ref->{rrreq} = $f[11];
184                         $ref->{linesreq} = $f[10];
185                         $ref->{stream} = $stream;
186                         $ref->{count} = 0;      # no of lines between PC31s
187                         dbg('msg', "new message from $f[4] to $f[3] '$f[8]' stream $stream\n");
188                         Log('msg', "Incoming message $f[4] to $f[3] '$f[8]'" );
189                         $work{"$fromnode$stream"} = $ref; # store in work
190                         $busy{$fromnode} = $ref; # set interlock
191                         $self->send(DXProt::pc30($fromnode, $f[1], $stream)); # send ack
192                         $ref->{lastt} = $main::systime;
193
194                         # look to see whether this is a non private message sent to a known callsign
195                         my $uref = DXUser->get_current($ref->{to});
196                         if (is_callsign($ref->{to}) && !$ref->{private} && $uref && $uref->homenode) {
197                                 $ref->{private} = 1;
198                                 dbg('msg', "set bull to $ref->{to} to private");
199                         }
200                         last SWITCH;
201                 }
202                 
203                 if ($pcno == 29) {              # incoming text
204                         my $ref = $work{"$f[2]$f[3]"};
205                         if ($ref) {
206                                 $f[4] =~ s/\%5E/^/g;
207                                 push @{$ref->{lines}}, $f[4];
208                                 $ref->{count}++;
209                                 if ($ref->{count} >= $ref->{linesreq}) {
210                                         $self->send(DXProt::pc31($f[2], $f[1], $f[3]));
211                                         dbg('msg', "stream $f[3]: $ref->{count} lines received\n");
212                                         $ref->{count} = 0;
213                                 }
214                                 $ref->{lastt} = $main::systime;
215                         } else {
216                                 dbg('msg', "PC29 from unknown stream $f[3] from $f[2]" );
217                                 $self->send(DXProt::pc42($f[2], $f[1], $f[3])); # unknown stream
218                         }
219                         last SWITCH;
220                 }
221                 
222                 if ($pcno == 30) {              # this is a incoming subject ack
223                         my $ref = $work{$f[2]}; # note no stream at this stage
224                         if ($ref) {
225                                 delete $work{$f[2]};
226                                 $ref->{stream} = $f[3];
227                                 $ref->{count} = 0;
228                                 $ref->{linesreq} = 5;
229                                 $work{"$f[2]$f[3]"} = $ref;     # new ref
230                                 dbg('msg', "incoming subject ack stream $f[3]\n");
231                                 $busy{$f[2]} = $ref; # interlock
232                                 push @{$ref->{lines}}, ($ref->read_msg_body);
233                                 $ref->send_tranche($self);
234                                 $ref->{lastt} = $main::systime;
235                         } else {
236                                 dbg('msg', "PC30 from unknown stream $f[3] from $f[2]" );
237                                 $self->send(DXProt::pc42($f[2], $f[1], $f[3])); # unknown stream
238                         } 
239                         last SWITCH;
240                 }
241                 
242                 if ($pcno == 31) {              # acknowledge a tranche of lines
243                         my $ref = $work{"$f[2]$f[3]"};
244                         if ($ref) {
245                                 dbg('msg', "tranche ack stream $f[3]\n");
246                                 $ref->send_tranche($self);
247                                 $ref->{lastt} = $main::systime;
248                         } else {
249                                 dbg('msg', "PC31 from unknown stream $f[3] from $f[2]" );
250                                 $self->send(DXProt::pc42($f[2], $f[1], $f[3])); # unknown stream
251                         } 
252                         last SWITCH;
253                 }
254                 
255                 if ($pcno == 32) {              # incoming EOM
256                         dbg('msg', "stream $f[3]: EOM received\n");
257                         my $ref = $work{"$f[2]$f[3]"};
258                         if ($ref) {
259                                 $self->send(DXProt::pc33($f[2], $f[1], $f[3])); # acknowledge it
260                                 
261                                 # get the next msg no - note that this has NOTHING to do with the stream number in PC protocol
262                                 # store the file or message
263                                 # remove extraneous rubbish from the hash
264                                 # remove it from the work in progress vector
265                                 # stuff it on the msg queue
266                                 if ($ref->{lines}) {
267                                         if ($ref->{file}) {
268                                                 $ref->store($ref->{lines});
269                                         } else {
270
271                                                 # does an identical message already exist?
272                                                 my $m;
273                                                 for $m (@msg) {
274                                                         if ($ref->{subject} eq $m->{subject} && $ref->{t} == $m->{t} && $ref->{from} eq $m->{from} && $ref->{to} eq $m->{to}) {
275                                                                 $ref->stop_msg($self->call);
276                                                                 my $msgno = $m->{msgno};
277                                                                 dbg('msg', "duplicate message from $ref->{from} -> $ref->{to} to $msgno");
278                                                                 Log('msg', "duplicate message from $ref->{from} -> $ref->{to} to $msgno");
279                                                                 return;
280                                                         }
281                                                 }
282
283                                                 # swop addresses
284                                                 $ref->swop_it($self->call);
285                                                 
286                                                 # look for 'bad' to addresses 
287                                                 if ($ref->dump_it) {
288                                                         $ref->stop_msg($self->call);
289                                                         dbg('msg', "'Bad' message $ref->{to}");
290                                                         Log('msg', "'Bad' message $ref->{to}");
291                                                         return;
292                                                 }
293
294                                                 $ref->{msgno} = next_transno("Msgno");
295                                                 push @{$ref->{gotit}}, $f[2]; # mark this up as being received
296                                                 $ref->store($ref->{lines});
297                                                 add_dir($ref);
298                                                 my $dxchan = DXChannel->get($ref->{to});
299                                                 $dxchan->send($dxchan->msg('m9')) if $dxchan && $dxchan->is_user;
300                                                 Log('msg', "Message $ref->{msgno} from $ref->{from} received from $f[2] for $ref->{to}");
301                                         }
302                                 }
303                                 $ref->stop_msg($self->call);
304                         } else {
305                                 dbg('msg', "PC32 from unknown stream $f[3] from $f[2]" );
306                                 $self->send(DXProt::pc42($f[2], $f[1], $f[3])); # unknown stream
307                         }
308                         # queue_msg(0);
309                         last SWITCH;
310                 }
311                 
312                 if ($pcno == 33) {              # acknowledge the end of message
313                         my $ref = $work{"$f[2]$f[3]"};
314                         if ($ref) {
315                                 if ($ref->{private}) { # remove it if it private and gone off site#
316                                         Log('msg', "Message $ref->{msgno} from $ref->{from} sent to $f[2] and deleted");
317                                         $ref->del_msg;
318                                 } else {
319                                         Log('msg', "Message $ref->{msgno} from $ref->{from} sent to $f[2]");
320                                         push @{$ref->{gotit}}, $f[2]; # mark this up as being received
321                                         $ref->store($ref->{lines});     # re- store the file
322                                 }
323                                 $ref->stop_msg($self->call);
324                         } else {
325                                 dbg('msg', "PC33 from unknown stream $f[3] from $f[2]" );
326                                 $self->send(DXProt::pc42($f[2], $f[1], $f[3])); # unknown stream
327                         } 
328
329                         # send next one if present
330                         queue_msg(0);
331                         last SWITCH;
332                 }
333                 
334                 if ($pcno == 40) {              # this is a file request
335                         $f[3] =~ s/\\/\//og; # change the slashes
336                         $f[3] =~ s/\.//og;      # remove dots
337                         $f[3] =~ s/^\///o;   # remove the leading /
338                         $f[3] = lc $f[3];       # to lower case;
339                         dbg('msg', "incoming file $f[3]\n");
340                         $f[3] = 'packclus/' . $f[3] unless $f[3] =~ /^packclus\//o;
341                         
342                         # create any directories
343                         my @part = split /\//, $f[3];
344                         my $part;
345                         my $fn = "$main::root";
346                         pop @part;                      # remove last part
347                         foreach $part (@part) {
348                                 $fn .= "/$part";
349                                 next if -e $fn;
350                                 last SWITCH if !mkdir $fn, 0777;
351                                 dbg('msg', "created directory $fn\n");
352                         }
353                         my $stream = next_transno($f[2]);
354                         my $ref = DXMsg->alloc($stream, "$main::root/$f[3]", $self->call, time, !$f[4], $f[3], ' ', '0', '0');
355                         
356                         # forwarding variables
357                         $ref->{fromnode} = $f[1];
358                         $ref->{tonode} = $f[2];
359                         $ref->{linesreq} = $f[5];
360                         $ref->{stream} = $stream;
361                         $ref->{count} = 0;      # no of lines between PC31s
362                         $ref->{file} = 1;
363                         $ref->{lastt} = $main::systime;
364                         $work{"$f[2]$stream"} = $ref; # store in work
365                         $self->send(DXProt::pc30($f[2], $f[1], $stream)); # send ack 
366                         
367                         last SWITCH;
368                 }
369                 
370                 if ($pcno == 42) {              # abort transfer
371                         dbg('msg', "stream $f[3]: abort received\n");
372                         my $ref = $work{"$f[2]$f[3]"};
373                         if ($ref) {
374                                 $ref->stop_msg($self->call);
375                                 $ref = undef;
376                         }
377                         last SWITCH;
378                 }
379
380                 if ($pcno == 49) {      # global delete on subject
381                         for (@msg) {
382                                 if ($_->{from} eq $f[1] && $_->{subject} eq $f[2]) {
383                                         $_->del_msg();
384                                         Log('msg', "Message $_->{msgno} from $_->{from} ($_->{subject}) fully deleted");
385                                         DXProt::broadcast_ak1a($line, $self);
386                                 }
387                         }
388                 }
389         }
390 }
391
392
393 # store a message away on disc or whatever
394 #
395 # NOTE the second arg is a REFERENCE not a list
396 sub store
397 {
398         my $ref = shift;
399         my $lines = shift;
400
401         if ($ref->{file}) {                     # a file
402                 dbg('msg', "To be stored in $ref->{to}\n");
403                 
404                 my $fh = new IO::File "$ref->{to}", "w";
405                 if (defined $fh) {
406                         my $line;
407                         foreach $line (@{$lines}) {
408                                 print $fh "$line\n";
409                         }
410                         $fh->close;
411                         dbg('msg', "file $ref->{to} stored\n");
412                         Log('msg', "file $ref->{to} from $ref->{from} stored" );
413                 } else {
414                         confess "can't open file $ref->{to} $!";  
415                 }
416         } else {                                        # a normal message
417
418                 # attempt to open the message file
419                 my $fn = filename($ref->{msgno});
420                 
421                 dbg('msg', "To be stored in $fn\n");
422                 
423                 # now save the file, overwriting what's there, YES I KNOW OK! (I will change it if it's a problem)
424                 my $fh = new IO::File "$fn", "w";
425                 if (defined $fh) {
426                         my $rr = $ref->{rrreq} ? '1' : '0';
427                         my $priv = $ref->{private} ? '1': '0';
428                         print $fh "=== $ref->{msgno}^$ref->{to}^$ref->{from}^$ref->{t}^$priv^$ref->{subject}^$ref->{origin}^$ref->{'read'}^$rr\n";
429                         print $fh "=== ", join('^', @{$ref->{gotit}}), "\n";
430                         my $line;
431                         $ref->{size} = 0;
432                         foreach $line (@{$lines}) {
433                                 $ref->{size} += (length $line) + 1;
434                                 print $fh "$line\n";
435                         }
436                         $fh->close;
437                         dbg('msg', "msg $ref->{msgno} stored\n");
438                         Log('msg', "msg $ref->{msgno} from $ref->{from} to $ref->{to} stored" );
439                 } else {
440                         confess "can't open msg file $fn $!";  
441                 }
442         }
443 }
444
445 # delete a message
446 sub del_msg
447 {
448         my $self = shift;
449         
450         # remove it from the active message list
451         dbg('msg', "\@msg = " . scalar @msg . " before delete");
452         @msg = grep { $_ != $self } @msg;
453         
454         # remove the file
455         unlink filename($self->{msgno});
456         dbg('msg', "deleting $self->{msgno}\n");
457         dbg('msg', "\@msg = " . scalar @msg . " after delete");
458 }
459
460 # clean out old messages from the message queue
461 sub clean_old
462 {
463         my $ref;
464         
465         # mark old messages for deletion
466         dbg('msg', "\@msg = " . scalar @msg . " before delete");
467         foreach $ref (@msg) {
468                 if (ref($ref) && !$ref->{keep} && $ref->{t} < $main::systime - $maxage) {
469                         $ref->{deleteme} = 1;
470                         unlink filename($ref->{msgno});
471                         dbg('msg', "deleting old $ref->{msgno}\n");
472                 }
473         }
474         
475         # remove them all from the active message list
476         @msg = grep { !$_->{deleteme} } @msg;
477         dbg('msg', "\@msg = " . scalar @msg . " after delete");
478         $last_clean = $main::systime;
479 }
480
481 # read in a message header
482 sub read_msg_header
483
484         my $fn = shift;
485         my $file;
486         my $line;
487         my $ref;
488         my @f;
489         my $size;
490         
491         $file = new IO::File "$fn";
492         if (!$file) {
493             dbg('err', "Error reading $fn $!");
494             Log('err', "Error reading $fn $!");
495                 return undef;
496         }
497         $size = -s $fn;
498         $line = <$file>;                        # first line
499         if ($size == 0 || !$line) {
500             dbg('err', "Empty $fn $!");
501             Log('err', "Empty $fn $!");
502                 return undef;
503         }
504         chomp $line;
505         $size -= length $line;
506         if (! $line =~ /^===/o) {
507                 dbg('err', "corrupt first line in $fn ($line)");
508                 Log('err', "corrupt first line in $fn ($line)");
509                 return undef;
510         }
511         $line =~ s/^=== //o;
512         @f = split /\^/, $line;
513         $ref = DXMsg->alloc(@f);
514         
515         $line = <$file>;                        # second line
516         chomp $line;
517         $size -= length $line;
518         if (! $line =~ /^===/o) {
519             dbg('err', "corrupt second line in $fn ($line)");
520             Log('err', "corrupt second line in $fn ($line)");
521                 return undef;
522         }
523         $line =~ s/^=== //o;
524         $ref->{gotit} = [];
525         @f = split /\^/, $line;
526         push @{$ref->{gotit}}, @f;
527         $ref->{size} = $size;
528         
529         close($file);
530         
531         return $ref;
532 }
533
534 # read in a message header
535 sub read_msg_body
536 {
537         my $self = shift;
538         my $msgno = $self->{msgno};
539         my $file;
540         my $line;
541         my $fn = filename($msgno);
542         my @out;
543         
544         $file = new IO::File;
545         if (!open($file, $fn)) {
546                 dbg('err' ,"Error reading $fn $!");
547                 Log('err' ,"Error reading $fn $!");
548                 return undef;
549         }
550         @out = map {chomp; $_} <$file>;
551         close($file);
552         
553         shift @out if $out[0] =~ /^=== /;
554         shift @out if $out[0] =~ /^=== /;
555         return @out;
556 }
557
558 # send a tranche of lines to the other end
559 sub send_tranche
560 {
561         my ($self, $dxchan) = @_;
562         my @out;
563         my $to = $self->{tonode};
564         my $from = $self->{fromnode};
565         my $stream = $self->{stream};
566         my $lines = $self->{lines};
567         my ($c, $i);
568         
569         for ($i = 0, $c = $self->{count}; $i < $self->{linesreq} && $c < @$lines; $i++, $c++) {
570                 push @out, DXProt::pc29($to, $from, $stream, $lines->[$c]);
571     }
572     $self->{count} = $c;
573
574     push @out, DXProt::pc32($to, $from, $stream) if $i < $self->{linesreq};
575         $dxchan->send(@out);
576 }
577
578         
579 # find a message to send out and start the ball rolling
580 sub queue_msg
581 {
582         my $sort = shift;
583         my $call = shift;
584         my $ref;
585         my $clref;
586         
587         # bat down the message list looking for one that needs to go off site and whose
588         # nearest node is not busy.
589
590         dbg('msg', "queue msg ($sort)\n");
591         my @nodelist = DXChannel::get_all_nodes;
592         foreach $ref (@msg) {
593
594                 # ignore 'delayed' messages until their waiting time has expired
595                 if (exists $ref->{waitt}) {
596                         next if $ref->{waitt} > $main::systime;
597                         delete $ref->{waitt};
598                 } 
599
600                 # any time outs?
601                 if (exists $ref->{lastt} && $main::systime >= $ref->{lastt} + $timeout) {
602                         my $node = $ref->{tonode};
603                         dbg('msg', "Timeout, stopping msgno: $ref->{msgno} -> $node");
604                         Log('msg', "Timeout, stopping msgno: $ref->{msgno} -> $node");
605                         $ref->stop_msg($node);
606                         
607                         # delay any outgoing messages that fail
608                         $ref->{waitt} = $main::systime + $waittime + rand(120) if $node ne $main::mycall;
609                         delete $ref->{lastt};
610                         next;
611                 }
612
613                 # firstly, is it private and unread? if so can I find the recipient
614                 # in my cluster node list offsite?
615
616                 # deal with routed private messages
617                 my $dxchan;
618                 if ($ref->{private}) {
619                         next if $ref->{'read'};           # if it is read, it is stuck here
620                         $clref = DXCluster->get_exact($ref->{to});
621                         unless ($clref) {             # otherwise look for a homenode
622                                 my $uref = DXUser->get_current($ref->{to});
623                                 my $hnode =  $uref->homenode if $uref;
624                                 $clref = DXCluster->get_exact($hnode) if $hnode;
625                         }
626                         if ($clref && !grep { $clref->dxchan == $_ } DXCommandmode::get_all()) {
627                                 next if $clref->call eq $main::mycall;  # i.e. it lives here
628                                 $dxchan = $clref->dxchan;
629                                 $ref->start_msg($dxchan) if $dxchan && !get_busy($dxchan->call)  && $dxchan->state eq 'normal';
630                         }
631                 }
632                 
633                 # otherwise we are dealing with a bulletin or forwarded private message
634                 # compare the gotit list with
635                 # the nodelist up above, if there are sites that haven't got it yet
636                 # then start sending it - what happens when we get loops is anyone's
637                 # guess, use (to, from, time, subject) tuple?
638                 foreach $dxchan (@nodelist) {
639                         my $call = $dxchan->call;
640                         next unless $call;
641                         next if $call eq $main::mycall;
642                         next if ref $ref->{gotit} && grep $_ eq $call, @{$ref->{gotit}};
643                         next unless $ref->forward_it($call);           # check the forwarding file
644
645                         # if we are here we have a node that doesn't have this message
646                         $ref->start_msg($dxchan) if !get_busy($call)  && $dxchan->state eq 'normal';
647                         last;
648                 }
649
650                 # if all the available nodes are busy then stop
651                 last if @nodelist == scalar grep { get_busy($_->call) } @nodelist;
652         }
653 }
654
655 # is there a message for me?
656 sub for_me
657 {
658         my $call = uc shift;
659         my $ref;
660         
661         foreach $ref (@msg) {
662                 # is it for me, private and unread? 
663                 if ($ref->{to} eq $call && $ref->{private}) {
664                         return 1 if !$ref->{'read'};
665                 }
666         }
667         return 0;
668 }
669
670 # start the message off on its travels with a PC28
671 sub start_msg
672 {
673         my ($self, $dxchan) = @_;
674         
675         dbg('msg', "start msg $self->{msgno}\n");
676         $self->{linesreq} = 10;
677         $self->{count} = 0;
678         $self->{tonode} = $dxchan->call;
679         $self->{fromnode} = $main::mycall;
680         $busy{$self->{tonode}} = $self;
681         $work{$self->{tonode}} = $self;
682         $self->{lastt} = $main::systime;
683         $dxchan->send(DXProt::pc28($self->{tonode}, $self->{fromnode}, $self->{to}, $self->{from}, $self->{t}, $self->{private}, $self->{subject}, $self->{origin}, $self->{rrreq}));
684 }
685
686 # get the ref of a busy node
687 sub get_busy
688 {
689         my $call = shift;
690         return $busy{$call};
691 }
692
693 # get the busy queue
694 sub get_all_busy
695 {
696         return values %busy;
697 }
698
699 # get the forwarding queue
700 sub get_fwq
701 {
702         return values %work;
703 }
704
705 # stop a message from continuing, clean it out, unlock interlocks etc
706 sub stop_msg
707 {
708         my $self = shift;
709         my $node = shift;
710         my $stream = $self->{stream} if exists $self->{stream};
711         
712         
713         dbg('msg', "stop msg $self->{msgno} -> node $node\n");
714         delete $work{$node};
715         delete $work{"$node$stream"} if $stream;
716         $self->workclean;
717         delete $busy{$node};
718 }
719
720 # get a new transaction number from the file specified
721 sub next_transno
722 {
723         my $name = shift;
724         $name =~ s/\W//og;                      # remove non-word characters
725         my $fn = "$msgdir/$name";
726         my $msgno;
727         
728         my $fh = new IO::File;
729         if (sysopen($fh, $fn, O_RDWR|O_CREAT, 0666)) {
730                 $fh->autoflush(1);
731                 $msgno = $fh->getline;
732                 chomp $msgno;
733                 $msgno++;
734                 seek $fh, 0, 0;
735                 $fh->print("$msgno\n");
736                 dbg('msg', "msgno $msgno allocated for $name\n");
737                 $fh->close;
738         } else {
739                 confess "can't open $fn $!";
740         }
741         return $msgno;
742 }
743
744 # initialise the message 'system', read in all the message headers
745 sub init
746 {
747         my $dir = new IO::File;
748         my @dir;
749         my $ref;
750                 
751         # load various control files
752         dbg('err', "load badmsg: " . (load_badmsg() or "Ok"));
753         dbg('err', "load forward: " . (load_forward() or "Ok"));
754         dbg('err', "load swop: " . (load_swop() or "Ok"));
755
756         # read in the directory
757         opendir($dir, $msgdir) or confess "can't open $msgdir $!";
758         @dir = readdir($dir);
759         closedir($dir);
760
761         @msg = ();
762         for (sort @dir) {
763                 next unless /^m\d\d\d\d\d\d$/;
764                 
765                 $ref = read_msg_header("$msgdir/$_");
766                 unless ($ref) {
767                         dbg('err', "Deleting $_");
768                         Log('err', "Deleting $_");
769                         unlink "$msgdir/$_";
770                         next;
771                 }
772                 
773                 # delete any messages to 'badmsg.pl' places
774                 if ($ref->dump_it) {
775                         dbg('msg', "'Bad' TO address $ref->{to}");
776                         Log('msg', "'Bad' TO address $ref->{to}");
777                         $ref->del_msg;
778                         next;
779                 }
780
781                 # add the message to the available queue
782                 add_dir($ref); 
783         }
784 }
785
786 # add the message to the directory listing
787 sub add_dir
788 {
789         my $ref = shift;
790         confess "tried to add a non-ref to the msg directory" if !ref $ref;
791         push @msg, $ref;
792 }
793
794 # return all the current messages
795 sub get_all
796 {
797         return @msg;
798 }
799
800 # get a particular message
801 sub get
802 {
803         my $msgno = shift;
804         for (@msg) {
805                 return $_ if $_->{msgno} == $msgno;
806                 last if $_->{msgno} > $msgno;
807         }
808         return undef;
809 }
810
811 # return the official filename for a message no
812 sub filename
813 {
814         return sprintf "$msgdir/m%06d", shift;
815 }
816
817 #
818 # return a list of valid elements 
819
820
821 sub fields
822 {
823         return keys(%valid);
824 }
825
826 #
827 # return a prompt for a field
828 #
829
830 sub field_prompt
831
832         my ($self, $ele) = @_;
833         return $valid{$ele};
834 }
835
836 #
837 # send a message state machine
838 sub do_send_stuff
839 {
840         my $self = shift;
841         my $line = shift;
842         my @out;
843         
844         if ($self->state eq 'send1') {
845                 #  $DB::single = 1;
846                 confess "local var gone missing" if !ref $self->{loc};
847                 my $loc = $self->{loc};
848                 $loc->{subject} = $line;
849                 $loc->{lines} = [];
850                 $self->state('sendbody');
851                 #push @out, $self->msg('sendbody');
852                 push @out, $self->msg('m8');
853         } elsif ($self->state eq 'sendbody') {
854                 confess "local var gone missing" if !ref $self->{loc};
855                 my $loc = $self->{loc};
856                 if ($line eq "\032" || $line eq '%1A' || uc $line eq "/EX") {
857                         my $to;
858                         
859                         foreach $to (@{$loc->{to}}) {
860                                 my $ref;
861                                 my $systime = $main::systime;
862                                 my $mycall = $main::mycall;
863                                 $ref = DXMsg->alloc(DXMsg::next_transno('Msgno'),
864                                                                         uc $to,
865                                                                         exists $loc->{from} ? $loc->{from} : $self->call, 
866                                                                         $systime,
867                                                                         $loc->{private}, 
868                                                                         $loc->{subject}, 
869                                                                         exists $loc->{origin} ? $loc->{origin} : $mycall,
870                                                                         '0',
871                                                                         $loc->{rrreq});
872                                 $ref->swop_it($self->call);
873                                 $ref->store($loc->{lines});
874                                 $ref->add_dir();
875                                 push @out, $self->msg('m11', $ref->{msgno}, $to);
876                                 #push @out, "msgno $ref->{msgno} sent to $to";
877                                 my $dxchan = DXChannel->get(uc $to);
878                                 if ($dxchan) {
879                                         if ($dxchan->is_user()) {
880                                                 $dxchan->send($dxchan->msg('m9'));
881                                         }
882                                 }
883                         }
884
885                         delete $loc->{lines};
886                         delete $loc->{to};
887                         delete $self->{loc};
888                         $self->func(undef);
889                         
890                         $self->state('prompt');
891                 } elsif ($line eq "\031" || uc $line eq "/ABORT" || uc $line eq "/QUIT") {
892                         #push @out, $self->msg('sendabort');
893                         push @out, $self->msg('m10');
894                         delete $loc->{lines};
895                         delete $loc->{to};
896                         delete $self->{loc};
897                         $self->func(undef);
898                         $self->state('prompt');
899                 } else {
900                         
901                         # i.e. it ain't and end or abort, therefore store the line
902                         push @{$loc->{lines}}, length($line) > 0 ? $line : " ";
903                 }
904         }
905         return (1, @out);
906 }
907
908 # return the standard directory line for this ref 
909 sub dir
910 {
911         my $ref = shift;
912         return sprintf "%6d%s%s%5d %8.8s %8.8s %-6.6s %5.5s %-30.30s", 
913                 $ref->msgno, $ref->read ? '-' : ' ', $ref->private ? 'p' : ' ', $ref->size,
914                         $ref->to, $ref->from, cldate($ref->t), ztime($ref->t), $ref->subject;
915 }
916
917 # load the forward table
918 sub load_forward
919 {
920         my @out;
921         my $s = readfilestr($forwardfn);
922         if ($s) {
923                 eval $s;
924                 push @out, $@ if $@;
925         }
926         return @out;
927 }
928
929 # load the bad message table
930 sub load_badmsg
931 {
932         my @out;
933         my $s = readfilestr($badmsgfn);
934         if ($s) {
935                 eval $s;
936                 push @out, $@ if $@;
937         }
938         return @out;
939 }
940
941 # load the swop message table
942 sub load_swop
943 {
944         my @out;
945         my $s = readfilestr($swopfn);
946         if ($s) {
947                 eval $s;
948                 push @out, $@ if $@;
949         }
950         return @out;
951 }
952
953 #
954 # forward that message or not according to the forwarding table
955 # returns 1 for forward, 0 - to ignore
956 #
957
958 sub forward_it
959 {
960         my $ref = shift;
961         my $call = shift;
962         my $i;
963         
964         for ($i = 0; $i < @forward; $i += 5) {
965                 my ($sort, $field, $pattern, $action, $bbs) = @forward[$i..($i+4)]; 
966                 my $tested;
967                 
968                 # are we interested?
969                 next if $ref->{private} && $sort ne 'P';
970                 next if !$ref->{private} && $sort ne 'B';
971                 
972                 # select field
973                 $tested = $ref->{to} if $field eq 'T';
974                 $tested = $ref->{from} if $field eq 'F';
975                 $tested = $ref->{origin} if $field eq 'O';
976                 $tested = $ref->{subject} if $field eq 'S';
977
978                 if (!$pattern || $tested =~ m{$pattern}i) {
979                         return 0 if $action eq 'I';
980                         return 1 if !$bbs || grep $_ eq $call, @{$bbs};
981                 }
982         }
983         return 0;
984 }
985
986 sub dump_it
987 {
988         my $ref = shift;
989         my $i;
990         
991         for ($i = 0; $i < @badmsg; $i += 3) {
992                 my ($sort, $field, $pattern) = @badmsg[$i..($i+2)]; 
993                 my $tested;
994                 
995                 # are we interested?
996                 next if $ref->{private} && $sort ne 'P';
997                 next if !$ref->{private} && $sort ne 'B';
998                 
999                 # select field
1000                 $tested = $ref->{to} if $field eq 'T';
1001                 $tested = $ref->{from} if $field eq 'F';
1002                 $tested = $ref->{origin} if $field eq 'O';
1003                 $tested = $ref->{subject} if $field eq 'S';
1004
1005                 if (!$pattern || $tested =~ m{$pattern}i) {
1006                         return 1;
1007                 }
1008         }
1009         return 0;
1010 }
1011
1012 sub swop_it
1013 {
1014         my $ref = shift;
1015         my $call = shift;
1016         my $i;
1017         my $count = 0;
1018         
1019         for ($i = 0; $i < @swop; $i += 5) {
1020                 my ($sort, $field, $pattern, $tfield, $topattern) = @swop[$i..($i+4)]; 
1021                 my $tested;
1022                 my $swop;
1023                 my $old;
1024                 
1025                 # are we interested?
1026                 next if $ref->{private} && $sort ne 'P';
1027                 next if !$ref->{private} && $sort ne 'B';
1028                 
1029                 # select field
1030                 $tested = $ref->{to} if $field eq 'T';
1031                 $tested = $ref->{from} if $field eq 'F';
1032                 $tested = $ref->{origin} if $field eq 'O';
1033                 $tested = $ref->{subject} if $field eq 'S';
1034
1035                 # select swop field
1036                 $old = $swop = $ref->{to} if $tfield eq 'T';
1037                 $old = $swop = $ref->{from} if $tfield eq 'F';
1038                 $old = $swop = $ref->{origin} if $tfield eq 'O';
1039                 $old = $swop = $ref->{subject} if $tfield eq 'S';
1040
1041                 if ($tested =~ m{$pattern}i) {
1042                         if ($tested eq $swop) {
1043                                 $swop =~ s{$pattern}{$topattern}i;
1044                         } else {
1045                                 $swop = $topattern;
1046                         }
1047                         Log('msg', "Msg $ref->{msgno}: $tfield $old -> $swop");
1048                         Log('dbg', "Msg $ref->{msgno}: $tfield $old -> $swop");
1049                         $ref->{to} = $swop if $tfield eq 'T';
1050                         $ref->{from} = $swop if $tfield eq 'F';
1051                         $ref->{origin} = $swop if $tfield eq 'O';
1052                         $ref->{subject} = $swop if $tfield eq 'S';
1053                         ++$count;
1054                 }
1055         }
1056         return $count;
1057 }
1058
1059 # import any msgs in the import directory
1060 # the messages are in BBS format (but may have cluster extentions
1061 # so SB UK < GB7TLH is legal
1062 sub import_msgs
1063 {
1064         # are there any to do in this directory?
1065         return unless -d $importfn;
1066         unless (opendir(DIR, $importfn)) {
1067                 dbg('msg', "can\'t open $importfn $!");
1068                 Log('msg', "can\'t open $importfn $!");
1069                 return;
1070         } 
1071
1072         my @names = readdir(DIR);
1073         closedir(DIR);
1074         my $name;
1075         foreach $name (@names) {
1076                 next if $name =~ /^\./;
1077                 my $splitit = $name =~ /^split/;
1078                 my $fn = "$importfn/$name";
1079                 next unless -f $fn;
1080                 unless (open(MSG, $fn)) {
1081                         dbg('msg', "can\'t open import file $fn $!");
1082                         Log('msg', "can\'t open import file $fn $!");
1083                         unlink($fn);
1084                         next;
1085                 }
1086                 my @msg = map { chomp; $_ } <MSG>;
1087                 close(MSG);
1088                 unlink($fn);
1089                 my @out = import_one($DXProt::me, \@msg, $splitit);
1090                 Log('msg', @out);
1091         }
1092 }
1093
1094 # import one message as a list in bbs (as extended) mode
1095 # takes a reference to an array containing the whole message
1096 sub import_one
1097 {
1098         my $dxchan = shift;
1099         my $ref = shift;
1100         my $splitit = shift;
1101         my $private = '1';
1102         my $rr = '0';
1103         my $notincalls = 1;
1104         my $from = $dxchan->call;
1105         my $origin = $main::mycall;
1106         my @to;
1107         my @out;
1108                                 
1109         # first line;
1110         my $line = shift @$ref;
1111         my @f = split /\s+/, $line;
1112         unless (@f && $f[0] =~ /^(:?S|SP|SB|SEND)$/ ) {
1113                 my $m = "invalid first line in import '$line'";
1114                 dbg('MSG', $m );
1115                 return (1, $m);
1116         }
1117         while (@f) {
1118                 my $f = uc shift @f;
1119                 next if $f eq 'SEND';
1120
1121                 # private / noprivate / rr
1122                 if ($notincalls && ($f eq 'B' || $f eq 'SB' || $f =~ /^NOP/oi)) {
1123                         $private = '0';
1124                 } elsif ($notincalls && ($f eq 'P' || $f eq 'SP' || $f =~ /^PRI/oi)) {
1125                         ;
1126                 } elsif ($notincalls && ($f eq 'RR')) {
1127                         $rr = '1';
1128                 } elsif ($f eq '@' && @f) {       # this is bbs syntax, for origin
1129                         $origin = uc shift @f;
1130                 } elsif ($f eq '<' && @f) {     # this is bbs syntax  for from call
1131                         $from = uc shift @f;
1132                 } elsif ($f =~ /^\$/) {     # this is bbs syntax  for a bid
1133                         next;
1134                 } elsif ($f =~ /^<\S+/) {     # this is bbs syntax  for from call
1135                         ($from) = $f =~ /^<(\S+)$/;
1136                 } elsif ($f =~ /^\@\S+/) {     # this is bbs syntax for origin
1137                         ($origin) = $f =~ /^\@(\S+)$/;
1138                 } else {
1139
1140                         # callsign ?
1141                         $notincalls = 0;
1142
1143                         # is this callsign a distro?
1144                         my $fn = "$msgdir/distro/$f.pl";
1145                         if (-e $fn) {
1146                                 my $fh = new IO::File $fn;
1147                                 if ($fh) {
1148                                         local $/ = undef;
1149                                         my $s = <$fh>;
1150                                         $fh->close;
1151                                         my @call;
1152                                         @call = eval $s;
1153                                         return (1, "Error in Distro $f.pl:", $@) if $@;
1154                                         if (@call > 0) {
1155                                                 push @f, @call;
1156                                                 next;
1157                                         }
1158                                 }
1159                         }
1160                         
1161                         if (grep $_ eq $f, @DXMsg::badmsg) {
1162                                 push @out, $dxchan->msg('m3', $f);
1163                         } else {
1164                                 push @to, $f;
1165                         }
1166                 }
1167         }
1168         
1169         # subject is the next line
1170         my $subject = shift @$ref;
1171         
1172         # strip off trailing lines 
1173         pop @$ref while (@$ref && $$ref[-1] =~ /^\s*$/);
1174         
1175         # strip off /EX or /ABORT
1176         return ("aborted") if @$ref && $$ref[-1] =~ m{^/ABORT$}i; 
1177         pop @$ref if (@$ref && $$ref[-1] =~ m{^/EX$}i);                                                                  
1178
1179         # sort out any splitting that needs to be done
1180         my @chunk;
1181         if ($splitit) {
1182                 my $lth = 0;
1183                 my $lines = [];
1184                 for (@$ref) {
1185                         if ($lth >= $maxchunk || ($lth > $minchunk && /^\s*$/)) {
1186                                 push @chunk, $lines;
1187                                 $lines = [];
1188                                 $lth = 0;
1189                         } 
1190                         push @$lines, $_;
1191                         $lth += length; 
1192                 }
1193                 push @chunk, $lines if @$lines;
1194         } else {
1195                 push @chunk, $ref;
1196         }
1197                                   
1198     # write all the messages away
1199         my $i;
1200         for ( $i = 0;  $i < @chunk; $i++) {
1201                 my $chunk = $chunk[$i];
1202                 my $ch_subject;
1203                 if (@chunk > 1) {
1204                         my $num = " [" . ($i+1) . "/" . scalar @chunk . "]";
1205                         $ch_subject = substr($subject, 0, 27 - length $num) .  $num;
1206                 } else {
1207                         $ch_subject = $subject;
1208                 }
1209                 my $to;
1210                 foreach $to (@to) {
1211                         my $systime = $main::systime;
1212                         my $mycall = $main::mycall;
1213                         my $mref = DXMsg->alloc(DXMsg::next_transno('Msgno'),
1214                                                                         $to,
1215                                                                         $from, 
1216                                                                         $systime,
1217                                                                         $private, 
1218                                                                         $ch_subject, 
1219                                                                         $origin,
1220                                                                         '0',
1221                                                                         $rr);
1222                         $mref->swop_it($main::mycall);
1223                         $mref->store($chunk);
1224                         $mref->add_dir();
1225                         push @out, $dxchan->msg('m11', $mref->{msgno}, $to);
1226                         #push @out, "msgno $ref->{msgno} sent to $to";
1227                         my $todxchan = DXChannel->get(uc $to);
1228                         if ($todxchan) {
1229                                 if ($todxchan->is_user()) {
1230                                         $todxchan->send($todxchan->msg('m9'));
1231                                 }
1232                         }
1233                 }
1234         }
1235         return @out;
1236 }
1237
1238 no strict;
1239 sub AUTOLOAD
1240 {
1241         my $self = shift;
1242         my $name = $AUTOLOAD;
1243         return if $name =~ /::DESTROY$/;
1244         $name =~ s/.*:://o;
1245         
1246         confess "Non-existant field '$AUTOLOAD'" if !$valid{$name};
1247         # this clever line of code creates a subroutine which takes over from autoload
1248         # from OO Perl - Conway
1249         *{$AUTOLOAD} = sub {@_ > 1 ? $_[0]->{$name} = $_[1] : $_[0]->{$name}} ;
1250         @_ ? $self->{$name} = shift : $self->{$name} ;
1251 }
1252
1253 1;
1254
1255 __END__