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