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