added DXHash.pm
[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 ($ref->dump_it) {
291                                                         $ref->stop_msg($self->call);
292                                                         dbg('msg', "'Bad' message $ref->{to}");
293                                                         Log('msg', "'Bad' message $ref->{to}");
294                                                         return;
295                                                 }
296
297                                                 $ref->{msgno} = next_transno("Msgno");
298                                                 push @{$ref->{gotit}}, $f[2]; # mark this up as being received
299                                                 $ref->store($ref->{lines});
300                                                 add_dir($ref);
301                                                 my $dxchan = DXChannel->get($ref->{to});
302                                                 $dxchan->send($dxchan->msg('m9')) if $dxchan && $dxchan->is_user;
303                                                 Log('msg', "Message $ref->{msgno} from $ref->{from} received from $f[2] for $ref->{to}");
304                                         }
305                                 }
306                                 $ref->stop_msg($self->call);
307                         } else {
308                                 dbg('msg', "PC32 from unknown stream $f[3] from $f[2]" );
309                                 $self->send(DXProt::pc42($f[2], $f[1], $f[3])); # unknown stream
310                         }
311                         # queue_msg(0);
312                         last SWITCH;
313                 }
314                 
315                 if ($pcno == 33) {              # acknowledge the end of message
316                         my $ref = $work{"$f[2]$f[3]"};
317                         if ($ref) {
318                                 if ($ref->{private}) { # remove it if it private and gone off site#
319                                         Log('msg', "Message $ref->{msgno} from $ref->{from} sent to $f[2] and deleted");
320                                         $ref->del_msg;
321                                 } else {
322                                         Log('msg', "Message $ref->{msgno} from $ref->{from} sent to $f[2]");
323                                         push @{$ref->{gotit}}, $f[2]; # mark this up as being received
324                                         $ref->store($ref->{lines});     # re- store the file
325                                 }
326                                 $ref->stop_msg($self->call);
327                         } else {
328                                 dbg('msg', "PC33 from unknown stream $f[3] from $f[2]" );
329                                 $self->send(DXProt::pc42($f[2], $f[1], $f[3])); # unknown stream
330                         } 
331
332                         # send next one if present
333                         queue_msg(0);
334                         last SWITCH;
335                 }
336                 
337                 if ($pcno == 40) {              # this is a file request
338                         $f[3] =~ s/\\/\//og; # change the slashes
339                         $f[3] =~ s/\.//og;      # remove dots
340                         $f[3] =~ s/^\///o;   # remove the leading /
341                         $f[3] = lc $f[3];       # to lower case;
342                         dbg('msg', "incoming file $f[3]\n");
343                         $f[3] = 'packclus/' . $f[3] unless $f[3] =~ /^packclus\//o;
344                         
345                         # create any directories
346                         my @part = split /\//, $f[3];
347                         my $part;
348                         my $fn = "$main::root";
349                         pop @part;                      # remove last part
350                         foreach $part (@part) {
351                                 $fn .= "/$part";
352                                 next if -e $fn;
353                                 last SWITCH if !mkdir $fn, 0777;
354                                 dbg('msg', "created directory $fn\n");
355                         }
356                         my $stream = next_transno($f[2]);
357                         my $ref = DXMsg->alloc($stream, "$main::root/$f[3]", $self->call, time, !$f[4], $f[3], ' ', '0', '0');
358                         
359                         # forwarding variables
360                         $ref->{fromnode} = $f[1];
361                         $ref->{tonode} = $f[2];
362                         $ref->{linesreq} = $f[5];
363                         $ref->{stream} = $stream;
364                         $ref->{count} = 0;      # no of lines between PC31s
365                         $ref->{file} = 1;
366                         $ref->{lastt} = $main::systime;
367                         $work{"$f[2]$stream"} = $ref; # store in work
368                         $self->send(DXProt::pc30($f[2], $f[1], $stream)); # send ack 
369                         
370                         last SWITCH;
371                 }
372                 
373                 if ($pcno == 42) {              # abort transfer
374                         dbg('msg', "stream $f[3]: abort received\n");
375                         my $ref = $work{"$f[2]$f[3]"};
376                         if ($ref) {
377                                 $ref->stop_msg($self->call);
378                                 $ref = undef;
379                         }
380                         last SWITCH;
381                 }
382
383                 if ($pcno == 49) {      # global delete on subject
384                         for (@msg) {
385                                 if ($_->{from} eq $f[1] && $_->{subject} eq $f[2]) {
386                                         $_->del_msg();
387                                         Log('msg', "Message $_->{msgno} from $_->{from} ($_->{subject}) fully deleted");
388                                         DXProt::broadcast_ak1a($line, $self);
389                                 }
390                         }
391                 }
392         }
393 }
394
395
396 # store a message away on disc or whatever
397 #
398 # NOTE the second arg is a REFERENCE not a list
399 sub store
400 {
401         my $ref = shift;
402         my $lines = shift;
403
404         if ($ref->{file}) {                     # a file
405                 dbg('msg', "To be stored in $ref->{to}\n");
406                 
407                 my $fh = new IO::File "$ref->{to}", "w";
408                 if (defined $fh) {
409                         my $line;
410                         foreach $line (@{$lines}) {
411                                 print $fh "$line\n";
412                         }
413                         $fh->close;
414                         dbg('msg', "file $ref->{to} stored\n");
415                         Log('msg', "file $ref->{to} from $ref->{from} stored" );
416                 } else {
417                         confess "can't open file $ref->{to} $!";  
418                 }
419         } else {                                        # a normal message
420
421                 # attempt to open the message file
422                 my $fn = filename($ref->{msgno});
423                 
424                 dbg('msg', "To be stored in $fn\n");
425                 
426                 # now save the file, overwriting what's there, YES I KNOW OK! (I will change it if it's a problem)
427                 my $fh = new IO::File "$fn", "w";
428                 if (defined $fh) {
429                         my $rr = $ref->{rrreq} ? '1' : '0';
430                         my $priv = $ref->{private} ? '1': '0';
431                         print $fh "=== $ref->{msgno}^$ref->{to}^$ref->{from}^$ref->{t}^$priv^$ref->{subject}^$ref->{origin}^$ref->{'read'}^$rr\n";
432                         print $fh "=== ", join('^', @{$ref->{gotit}}), "\n";
433                         my $line;
434                         $ref->{size} = 0;
435                         foreach $line (@{$lines}) {
436                                 $ref->{size} += (length $line) + 1;
437                                 print $fh "$line\n";
438                         }
439                         $fh->close;
440                         dbg('msg', "msg $ref->{msgno} stored\n");
441                         Log('msg', "msg $ref->{msgno} from $ref->{from} to $ref->{to} stored" );
442                 } else {
443                         confess "can't open msg file $fn $!";  
444                 }
445         }
446 }
447
448 # delete a message
449 sub del_msg
450 {
451         my $self = shift;
452         
453         # remove it from the active message list
454         dbg('msg', "\@msg = " . scalar @msg . " before delete");
455         @msg = grep { $_ != $self } @msg;
456         
457         # remove the file
458         unlink filename($self->{msgno});
459         dbg('msg', "deleting $self->{msgno}\n");
460         dbg('msg', "\@msg = " . scalar @msg . " after delete");
461 }
462
463 # clean out old messages from the message queue
464 sub clean_old
465 {
466         my $ref;
467         
468         # mark old messages for deletion
469         dbg('msg', "\@msg = " . scalar @msg . " before delete");
470         foreach $ref (@msg) {
471                 if (ref($ref) && !$ref->{keep} && $ref->{t} < $main::systime - $maxage) {
472                         $ref->{deleteme} = 1;
473                         unlink filename($ref->{msgno});
474                         dbg('msg', "deleting old $ref->{msgno}\n");
475                 }
476         }
477         
478         # remove them all from the active message list
479         @msg = grep { !$_->{deleteme} } @msg;
480         dbg('msg', "\@msg = " . scalar @msg . " after delete");
481         $last_clean = $main::systime;
482 }
483
484 # read in a message header
485 sub read_msg_header
486
487         my $fn = shift;
488         my $file;
489         my $line;
490         my $ref;
491         my @f;
492         my $size;
493         
494         $file = new IO::File "$fn";
495         if (!$file) {
496             dbg('err', "Error reading $fn $!");
497             Log('err', "Error reading $fn $!");
498                 return undef;
499         }
500         $size = -s $fn;
501         $line = <$file>;                        # first line
502         if ($size == 0 || !$line) {
503             dbg('err', "Empty $fn $!");
504             Log('err', "Empty $fn $!");
505                 return undef;
506         }
507         chomp $line;
508         $size -= length $line;
509         if (! $line =~ /^===/o) {
510                 dbg('err', "corrupt first line in $fn ($line)");
511                 Log('err', "corrupt first line in $fn ($line)");
512                 return undef;
513         }
514         $line =~ s/^=== //o;
515         @f = split /\^/, $line;
516         $ref = DXMsg->alloc(@f);
517         
518         $line = <$file>;                        # second line
519         chomp $line;
520         $size -= length $line;
521         if (! $line =~ /^===/o) {
522             dbg('err', "corrupt second line in $fn ($line)");
523             Log('err', "corrupt second line in $fn ($line)");
524                 return undef;
525         }
526         $line =~ s/^=== //o;
527         $ref->{gotit} = [];
528         @f = split /\^/, $line;
529         push @{$ref->{gotit}}, @f;
530         $ref->{size} = $size;
531         
532         close($file);
533         
534         return $ref;
535 }
536
537 # read in a message header
538 sub read_msg_body
539 {
540         my $self = shift;
541         my $msgno = $self->{msgno};
542         my $file;
543         my $line;
544         my $fn = filename($msgno);
545         my @out;
546         
547         $file = new IO::File;
548         if (!open($file, $fn)) {
549                 dbg('err' ,"Error reading $fn $!");
550                 Log('err' ,"Error reading $fn $!");
551                 return undef;
552         }
553         @out = map {chomp; $_} <$file>;
554         close($file);
555         
556         shift @out if $out[0] =~ /^=== /;
557         shift @out if $out[0] =~ /^=== /;
558         return @out;
559 }
560
561 # send a tranche of lines to the other end
562 sub send_tranche
563 {
564         my ($self, $dxchan) = @_;
565         my @out;
566         my $to = $self->{tonode};
567         my $from = $self->{fromnode};
568         my $stream = $self->{stream};
569         my $lines = $self->{lines};
570         my ($c, $i);
571         
572         for ($i = 0, $c = $self->{count}; $i < $self->{linesreq} && $c < @$lines; $i++, $c++) {
573                 push @out, DXProt::pc29($to, $from, $stream, $lines->[$c]);
574     }
575     $self->{count} = $c;
576
577     push @out, DXProt::pc32($to, $from, $stream) if $i < $self->{linesreq};
578         $dxchan->send(@out);
579 }
580
581         
582 # find a message to send out and start the ball rolling
583 sub queue_msg
584 {
585         my $sort = shift;
586         my $call = shift;
587         my $ref;
588         my $clref;
589         
590         # bat down the message list looking for one that needs to go off site and whose
591         # nearest node is not busy.
592
593         dbg('msg', "queue msg ($sort)\n");
594         my @nodelist = DXChannel::get_all_nodes;
595         foreach $ref (@msg) {
596                 # firstly, is it private and unread? if so can I find the recipient
597                 # in my cluster node list offsite?
598
599                 # ignore 'delayed' messages until their waiting time has expired
600                 if (exists $ref->{waitt}) {
601                         next if $ref->{waitt} > $main::systime;
602                         delete $ref->{waitt};
603                 } 
604
605                 # deal with routed private messages
606                 my $dxchan;
607                 if ($ref->{private}) {
608                         next if $ref->{'read'};           # if it is read, it is stuck here
609                         $clref = DXCluster->get_exact($ref->{to});
610                         unless ($clref) {             # otherwise look for a homenode
611                                 my $uref = DXUser->get_current($ref->{to});
612                                 my $hnode =  $uref->homenode if $uref;
613                                 $clref = DXCluster->get_exact($hnode) if $hnode;
614                         }
615                         if ($clref && !grep { $clref->dxchan == $_ } DXCommandmode::get_all()) {
616                                 next if $clref->call eq $main::mycall;  # i.e. it lives here
617                                 $dxchan = $clref->dxchan;
618                                 $ref->start_msg($dxchan) if $dxchan && !get_busy($dxchan->call)  && $dxchan->state eq 'normal';
619                         }
620                 }
621                 
622                 # otherwise we are dealing with a bulletin or forwarded private message
623                 # compare the gotit list with
624                 # the nodelist up above, if there are sites that haven't got it yet
625                 # then start sending it - what happens when we get loops is anyone's
626                 # guess, use (to, from, time, subject) tuple?
627                 foreach $dxchan (@nodelist) {
628                         my $call = $dxchan->call;
629                         next unless $call;
630                         next if $call eq $main::mycall;
631                         next if ref $ref->{gotit} && grep $_ eq $call, @{$ref->{gotit}};
632                         next unless $ref->forward_it($call);           # check the forwarding file
633
634                         # if we are here we have a node that doesn't have this message
635                         $ref->start_msg($dxchan) if !get_busy($call)  && $dxchan->state eq 'normal';
636                         last;
637                 }
638
639                 # if all the available nodes are busy then stop
640                 last if @nodelist == scalar grep { get_busy($_->call) } @nodelist;
641         }
642 }
643
644 # is there a message for me?
645 sub for_me
646 {
647         my $call = uc shift;
648         my $ref;
649         
650         foreach $ref (@msg) {
651                 # is it for me, private and unread? 
652                 if ($ref->{to} eq $call && $ref->{private}) {
653                         return 1 if !$ref->{'read'};
654                 }
655         }
656         return 0;
657 }
658
659 # start the message off on its travels with a PC28
660 sub start_msg
661 {
662         my ($self, $dxchan) = @_;
663         
664         dbg('msg', "start msg $self->{msgno}\n");
665         $self->{linesreq} = 10;
666         $self->{count} = 0;
667         $self->{tonode} = $dxchan->call;
668         $self->{fromnode} = $main::mycall;
669         $busy{$self->{tonode}} = $self;
670         $work{$self->{tonode}} = $self;
671         $self->{lastt} = $main::systime;
672         $dxchan->send(DXProt::pc28($self->{tonode}, $self->{fromnode}, $self->{to}, $self->{from}, $self->{t}, $self->{private}, $self->{subject}, $self->{origin}, $self->{rrreq}));
673 }
674
675 # get the ref of a busy node
676 sub get_busy
677 {
678         my $call = shift;
679         return $busy{$call};
680 }
681
682 # get the busy queue
683 sub get_all_busy
684 {
685         return values %busy;
686 }
687
688 # get the forwarding queue
689 sub get_fwq
690 {
691         return values %work;
692 }
693
694 # stop a message from continuing, clean it out, unlock interlocks etc
695 sub stop_msg
696 {
697         my $self = shift;
698         my $node = shift;
699         my $stream = $self->{stream} if exists $self->{stream};
700         
701         
702         dbg('msg', "stop msg $self->{msgno} -> node $node\n");
703         delete $work{$node};
704         delete $work{"$node$stream"} if $stream;
705         $self->workclean;
706         delete $busy{$node};
707 }
708
709 # get a new transaction number from the file specified
710 sub next_transno
711 {
712         my $name = shift;
713         $name =~ s/\W//og;                      # remove non-word characters
714         my $fn = "$msgdir/$name";
715         my $msgno;
716         
717         my $fh = new IO::File;
718         if (sysopen($fh, $fn, O_RDWR|O_CREAT, 0666)) {
719                 $fh->autoflush(1);
720                 $msgno = $fh->getline;
721                 chomp $msgno;
722                 $msgno++;
723                 seek $fh, 0, 0;
724                 $fh->print("$msgno\n");
725                 dbg('msg', "msgno $msgno allocated for $name\n");
726                 $fh->close;
727         } else {
728                 confess "can't open $fn $!";
729         }
730         return $msgno;
731 }
732
733 # initialise the message 'system', read in all the message headers
734 sub init
735 {
736         my $dir = new IO::File;
737         my @dir;
738         my $ref;
739                 
740         # load various control files
741         dbg('err', "load badmsg: " . (load_badmsg() or "Ok"));
742         dbg('err', "load forward: " . (load_forward() or "Ok"));
743         dbg('err', "load swop: " . (load_swop() or "Ok"));
744
745         # read in the directory
746         opendir($dir, $msgdir) or confess "can't open $msgdir $!";
747         @dir = readdir($dir);
748         closedir($dir);
749
750         @msg = ();
751         for (sort @dir) {
752                 next unless /^m\d\d\d\d\d\d$/;
753                 
754                 $ref = read_msg_header("$msgdir/$_");
755                 unless ($ref) {
756                         dbg('err', "Deleting $_");
757                         Log('err', "Deleting $_");
758                         unlink "$msgdir/$_";
759                         next;
760                 }
761                 
762                 # delete any messages to 'badmsg.pl' places
763                 if ($ref->dump_it) {
764                         dbg('msg', "'Bad' TO address $ref->{to}");
765                         Log('msg', "'Bad' TO address $ref->{to}");
766                         $ref->del_msg;
767                         next;
768                 }
769
770                 # add the message to the available queue
771                 add_dir($ref); 
772         }
773 }
774
775 # add the message to the directory listing
776 sub add_dir
777 {
778         my $ref = shift;
779         confess "tried to add a non-ref to the msg directory" if !ref $ref;
780         push @msg, $ref;
781 }
782
783 # return all the current messages
784 sub get_all
785 {
786         return @msg;
787 }
788
789 # get a particular message
790 sub get
791 {
792         my $msgno = shift;
793         for (@msg) {
794                 return $_ if $_->{msgno} == $msgno;
795                 last if $_->{msgno} > $msgno;
796         }
797         return undef;
798 }
799
800 # return the official filename for a message no
801 sub filename
802 {
803         return sprintf "$msgdir/m%06d", shift;
804 }
805
806 #
807 # return a list of valid elements 
808
809
810 sub fields
811 {
812         return keys(%valid);
813 }
814
815 #
816 # return a prompt for a field
817 #
818
819 sub field_prompt
820
821         my ($self, $ele) = @_;
822         return $valid{$ele};
823 }
824
825 #
826 # send a message state machine
827 sub do_send_stuff
828 {
829         my $self = shift;
830         my $line = shift;
831         my @out;
832         
833         if ($self->state eq 'send1') {
834                 #  $DB::single = 1;
835                 confess "local var gone missing" if !ref $self->{loc};
836                 my $loc = $self->{loc};
837                 $loc->{subject} = $line;
838                 $loc->{lines} = [];
839                 $self->state('sendbody');
840                 #push @out, $self->msg('sendbody');
841                 push @out, $self->msg('m8');
842         } elsif ($self->state eq 'sendbody') {
843                 confess "local var gone missing" if !ref $self->{loc};
844                 my $loc = $self->{loc};
845                 if ($line eq "\032" || $line eq '%1A' || uc $line eq "/EX") {
846                         my $to;
847                         
848                         foreach $to (@{$loc->{to}}) {
849                                 my $ref;
850                                 my $systime = $main::systime;
851                                 my $mycall = $main::mycall;
852                                 $ref = DXMsg->alloc(DXMsg::next_transno('Msgno'),
853                                                                         uc $to,
854                                                                         exists $loc->{from} ? $loc->{from} : $self->call, 
855                                                                         $systime,
856                                                                         $loc->{private}, 
857                                                                         $loc->{subject}, 
858                                                                         exists $loc->{origin} ? $loc->{origin} : $mycall,
859                                                                         '0',
860                                                                         $loc->{rrreq});
861                                 $ref->swop_it($self->call);
862                                 $ref->store($loc->{lines});
863                                 $ref->add_dir();
864                                 push @out, $self->msg('m11', $ref->{msgno}, $to);
865                                 #push @out, "msgno $ref->{msgno} sent to $to";
866                                 my $dxchan = DXChannel->get(uc $to);
867                                 if ($dxchan) {
868                                         if ($dxchan->is_user()) {
869                                                 $dxchan->send($dxchan->msg('m9'));
870                                         }
871                                 }
872                         }
873
874                         delete $loc->{lines};
875                         delete $loc->{to};
876                         delete $self->{loc};
877                         $self->func(undef);
878                         
879                         $self->state('prompt');
880                 } elsif ($line eq "\031" || uc $line eq "/ABORT" || uc $line eq "/QUIT") {
881                         #push @out, $self->msg('sendabort');
882                         push @out, $self->msg('m10');
883                         delete $loc->{lines};
884                         delete $loc->{to};
885                         delete $self->{loc};
886                         $self->func(undef);
887                         $self->state('prompt');
888                 } else {
889                         
890                         # i.e. it ain't and end or abort, therefore store the line
891                         push @{$loc->{lines}}, length($line) > 0 ? $line : " ";
892                 }
893         }
894         return (1, @out);
895 }
896
897 # return the standard directory line for this ref 
898 sub dir
899 {
900         my $ref = shift;
901         return sprintf "%6d%s%s%5d %8.8s %8.8s %-6.6s %5.5s %-30.30s", 
902                 $ref->msgno, $ref->read ? '-' : ' ', $ref->private ? 'p' : ' ', $ref->size,
903                         $ref->to, $ref->from, cldate($ref->t), ztime($ref->t), $ref->subject;
904 }
905
906 # load the forward table
907 sub load_forward
908 {
909         my @out;
910         my $s = readfilestr($forwardfn);
911         if ($s) {
912                 eval $s;
913                 push @out, $@ if $@;
914         }
915         return @out;
916 }
917
918 # load the bad message table
919 sub load_badmsg
920 {
921         my @out;
922         my $s = readfilestr($badmsgfn);
923         if ($s) {
924                 eval $s;
925                 push @out, $@ if $@;
926         }
927         return @out;
928 }
929
930 # load the swop message table
931 sub load_swop
932 {
933         my @out;
934         my $s = readfilestr($swopfn);
935         if ($s) {
936                 eval $s;
937                 push @out, $@ if $@;
938         }
939         return @out;
940 }
941
942 #
943 # forward that message or not according to the forwarding table
944 # returns 1 for forward, 0 - to ignore
945 #
946
947 sub forward_it
948 {
949         my $ref = shift;
950         my $call = shift;
951         my $i;
952         
953         for ($i = 0; $i < @forward; $i += 5) {
954                 my ($sort, $field, $pattern, $action, $bbs) = @forward[$i..($i+4)]; 
955                 my $tested;
956                 
957                 # are we interested?
958                 next if $ref->{private} && $sort ne 'P';
959                 next if !$ref->{private} && $sort ne 'B';
960                 
961                 # select field
962                 $tested = $ref->{to} if $field eq 'T';
963                 $tested = $ref->{from} if $field eq 'F';
964                 $tested = $ref->{origin} if $field eq 'O';
965                 $tested = $ref->{subject} if $field eq 'S';
966
967                 if (!$pattern || $tested =~ m{$pattern}i) {
968                         return 0 if $action eq 'I';
969                         return 1 if !$bbs || grep $_ eq $call, @{$bbs};
970                 }
971         }
972         return 0;
973 }
974
975 sub dump_it
976 {
977         my $ref = shift;
978         my $i;
979         
980         for ($i = 0; $i < @badmsg; $i += 3) {
981                 my ($sort, $field, $pattern) = @badmsg[$i..($i+2)]; 
982                 my $tested;
983                 
984                 # are we interested?
985                 next if $ref->{private} && $sort ne 'P';
986                 next if !$ref->{private} && $sort ne 'B';
987                 
988                 # select field
989                 $tested = $ref->{to} if $field eq 'T';
990                 $tested = $ref->{from} if $field eq 'F';
991                 $tested = $ref->{origin} if $field eq 'O';
992                 $tested = $ref->{subject} if $field eq 'S';
993
994                 if (!$pattern || $tested =~ m{$pattern}i) {
995                         return 1;
996                 }
997         }
998         return 0;
999 }
1000
1001 sub swop_it
1002 {
1003         my $ref = shift;
1004         my $call = shift;
1005         my $i;
1006         my $count = 0;
1007         
1008         for ($i = 0; $i < @swop; $i += 5) {
1009                 my ($sort, $field, $pattern, $tfield, $topattern) = @swop[$i..($i+4)]; 
1010                 my $tested;
1011                 my $swop;
1012                 my $old;
1013                 
1014                 # are we interested?
1015                 next if $ref->{private} && $sort ne 'P';
1016                 next if !$ref->{private} && $sort ne 'B';
1017                 
1018                 # select field
1019                 $tested = $ref->{to} if $field eq 'T';
1020                 $tested = $ref->{from} if $field eq 'F';
1021                 $tested = $ref->{origin} if $field eq 'O';
1022                 $tested = $ref->{subject} if $field eq 'S';
1023
1024                 # select swop field
1025                 $old = $swop = $ref->{to} if $tfield eq 'T';
1026                 $old = $swop = $ref->{from} if $tfield eq 'F';
1027                 $old = $swop = $ref->{origin} if $tfield eq 'O';
1028                 $old = $swop = $ref->{subject} if $tfield eq 'S';
1029
1030                 if ($tested =~ m{$pattern}i) {
1031                         if ($tested eq $swop) {
1032                                 $swop =~ s{$pattern}{$topattern}i;
1033                         } else {
1034                                 $swop = $topattern;
1035                         }
1036                         Log('msg', "Msg $ref->{msgno}: $tfield $old -> $swop");
1037                         Log('dbg', "Msg $ref->{msgno}: $tfield $old -> $swop");
1038                         $ref->{to} = $swop if $tfield eq 'T';
1039                         $ref->{from} = $swop if $tfield eq 'F';
1040                         $ref->{origin} = $swop if $tfield eq 'O';
1041                         $ref->{subject} = $swop if $tfield eq 'S';
1042                         ++$count;
1043                 }
1044         }
1045         return $count;
1046 }
1047
1048 # import any msgs in the import directory
1049 # the messages are in BBS format (but may have cluster extentions
1050 # so SB UK < GB7TLH is legal
1051 sub import_msgs
1052 {
1053         # are there any to do in this directory?
1054         return unless -d $importfn;
1055         unless (opendir(DIR, $importfn)) {
1056                 dbg('msg', "can\'t open $importfn $!");
1057                 Log('msg', "can\'t open $importfn $!");
1058                 return;
1059         } 
1060
1061         my @names = readdir(DIR);
1062         closedir(DIR);
1063         my $name;
1064         foreach $name (@names) {
1065                 next if $name =~ /^\./;
1066                 my $splitit = $name =~ /^split/;
1067                 my $fn = "$importfn/$name";
1068                 next unless -f $fn;
1069                 unless (open(MSG, $fn)) {
1070                         dbg('msg', "can\'t open import file $fn $!");
1071                         Log('msg', "can\'t open import file $fn $!");
1072                         unlink($fn);
1073                         next;
1074                 }
1075                 my @msg = map { chomp; $_ } <MSG>;
1076                 close(MSG);
1077                 unlink($fn);
1078                 my @out = import_one($DXProt::me, \@msg, $splitit);
1079                 Log('msg', @out);
1080         }
1081 }
1082
1083 # import one message as a list in bbs (as extended) mode
1084 # takes a reference to an array containing the whole message
1085 sub import_one
1086 {
1087         my $dxchan = shift;
1088         my $ref = shift;
1089         my $splitit = shift;
1090         my $private = '1';
1091         my $rr = '0';
1092         my $notincalls = 1;
1093         my $from = $dxchan->call;
1094         my $origin = $main::mycall;
1095         my @to;
1096         my @out;
1097                                 
1098         # first line;
1099         my $line = shift @$ref;
1100         my @f = split /\s+/, $line;
1101         unless (@f && $f[0] =~ /^(:?S|SP|SB|SEND)$/ ) {
1102                 my $m = "invalid first line in import '$line'";
1103                 dbg('MSG', $m );
1104                 return (1, $m);
1105         }
1106         while (@f) {
1107                 my $f = uc shift @f;
1108                 next if $f eq 'SEND';
1109
1110                 # private / noprivate / rr
1111                 if ($notincalls && ($f eq 'B' || $f eq 'SB' || $f =~ /^NOP/oi)) {
1112                         $private = '0';
1113                 } elsif ($notincalls && ($f eq 'P' || $f eq 'SP' || $f =~ /^PRI/oi)) {
1114                         ;
1115                 } elsif ($notincalls && ($f eq 'RR')) {
1116                         $rr = '1';
1117                 } elsif ($f eq '@' && @f) {       # this is bbs syntax, for origin
1118                         $origin = uc shift @f;
1119                 } elsif ($f eq '<' && @f) {     # this is bbs syntax  for from call
1120                         $from = uc shift @f;
1121                 } elsif ($f =~ /^\$/) {     # this is bbs syntax  for a bid
1122                         next;
1123                 } elsif ($f =~ /^<\S+/) {     # this is bbs syntax  for from call
1124                         ($from) = $f =~ /^<(\S+)$/;
1125                 } elsif ($f =~ /^\@\S+/) {     # this is bbs syntax for origin
1126                         ($origin) = $f =~ /^\@(\S+)$/;
1127                 } else {
1128
1129                         # callsign ?
1130                         $notincalls = 0;
1131
1132                         # is this callsign a distro?
1133                         my $fn = "$msgdir/distro/$f.pl";
1134                         if (-e $fn) {
1135                                 my $fh = new IO::File $fn;
1136                                 if ($fh) {
1137                                         local $/ = undef;
1138                                         my $s = <$fh>;
1139                                         $fh->close;
1140                                         my @call;
1141                                         @call = eval $s;
1142                                         return (1, "Error in Distro $f.pl:", $@) if $@;
1143                                         if (@call > 0) {
1144                                                 push @f, @call;
1145                                                 next;
1146                                         }
1147                                 }
1148                         }
1149                         
1150                         if (grep $_ eq $f, @DXMsg::badmsg) {
1151                                 push @out, $dxchan->msg('m3', $f);
1152                         } else {
1153                                 push @to, $f;
1154                         }
1155                 }
1156         }
1157         
1158         # subject is the next line
1159         my $subject = shift @$ref;
1160         
1161         # strip off trailing lines 
1162         pop @$ref while (@$ref && $$ref[-1] =~ /^\s*$/);
1163         
1164         # strip off /EX or /ABORT
1165         return ("aborted") if @$ref && $$ref[-1] =~ m{^/ABORT$}i; 
1166         pop @$ref if (@$ref && $$ref[-1] =~ m{^/EX$}i);                                                                  
1167
1168         # sort out any splitting that needs to be done
1169         my @chunk;
1170         if ($splitit) {
1171                 my $lth = 0;
1172                 my $lines = [];
1173                 for (@$ref) {
1174                         if ($lth >= $maxchunk || ($lth > $minchunk && /^\s*$/)) {
1175                                 push @chunk, $lines;
1176                                 $lines = [];
1177                                 $lth = 0;
1178                         } 
1179                         push @$lines, $_;
1180                         $lth += length; 
1181                 }
1182                 push @chunk, $lines if @$lines;
1183         } else {
1184                 push @chunk, $ref;
1185         }
1186                                   
1187     # write all the messages away
1188         my $i;
1189         for ( $i = 0;  $i < @chunk; $i++) {
1190                 my $chunk = $chunk[$i];
1191                 my $ch_subject;
1192                 if (@chunk > 1) {
1193                         my $num = " [" . ($i+1) . "/" . scalar @chunk . "]";
1194                         $ch_subject = substr($subject, 0, 27 - length $num) .  $num;
1195                 } else {
1196                         $ch_subject = $subject;
1197                 }
1198                 my $to;
1199                 foreach $to (@to) {
1200                         my $systime = $main::systime;
1201                         my $mycall = $main::mycall;
1202                         my $mref = DXMsg->alloc(DXMsg::next_transno('Msgno'),
1203                                                                         $to,
1204                                                                         $from, 
1205                                                                         $systime,
1206                                                                         $private, 
1207                                                                         $ch_subject, 
1208                                                                         $origin,
1209                                                                         '0',
1210                                                                         $rr);
1211                         $mref->swop_it($main::mycall);
1212                         $mref->store($chunk);
1213                         $mref->add_dir();
1214                         push @out, $dxchan->msg('m11', $mref->{msgno}, $to);
1215                         #push @out, "msgno $ref->{msgno} sent to $to";
1216                         my $todxchan = DXChannel->get(uc $to);
1217                         if ($todxchan) {
1218                                 if ($todxchan->is_user()) {
1219                                         $todxchan->send($todxchan->msg('m9'));
1220                                 }
1221                         }
1222                 }
1223         }
1224         return @out;
1225 }
1226
1227 no strict;
1228 sub AUTOLOAD
1229 {
1230         my $self = shift;
1231         my $name = $AUTOLOAD;
1232         return if $name =~ /::DESTROY$/;
1233         $name =~ s/.*:://o;
1234         
1235         confess "Non-existant field '$AUTOLOAD'" if !$valid{$name};
1236         # this clever line of code creates a subroutine which takes over from autoload
1237         # from OO Perl - Conway
1238         *{$AUTOLOAD} = sub {@_ > 1 ? $_[0]->{$name} = $_[1] : $_[0]->{$name}} ;
1239         @_ ? $self->{$name} = shift : $self->{$name} ;
1240 }
1241
1242 1;
1243
1244 __END__