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