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