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