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