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