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