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