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