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