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