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