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