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