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