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