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