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