merge various things from master
[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                                                 next if $dxchan->is_arcluster;                  # don't even go there, idiot people send the header in the wrong order and won't/can't fix it
790                                                 next if $dxchan->isolate;                               # there is no mechanism for sending messages to isolated nodes. 
791                                                 $ref->start_msg($dxchan) if !get_busy($dxchan->call)  && $dxchan->state eq 'normal';
792                                         }
793                                 } else {
794                                         dbg("Route: No dxchan for $ref->{to} " . ref($clref) ) if isdbg('msg');
795                                 }
796                         }
797                 } else {
798                         
799                         # otherwise we are dealing with a bulletin or forwarded private message
800                         # compare the gotit list with
801                         # the nodelist up above, if there are sites that haven't got it yet
802                         # then start sending it - what happens when we get loops is anyone's
803                         # guess, use (to, from, time, subject) tuple?
804                         foreach $dxchan (@nodelist) {
805                                 my $call = $dxchan->call;
806                                 next unless $call;
807                                 next if $call eq $main::mycall;
808                                 next if ref $ref->{gotit} && grep $_ eq $call, @{$ref->{gotit}};
809                                 next unless $ref->forward_it($call);    # check the forwarding file
810                                 next if $ref->{tonode};                 # ignore it if it already being processed
811                                 next if $dxchan->is_arcluster;                  # don't even go there, idiot people send the header in the wrong order and won't/can't fix it
812                                 next if $dxchan->isolate;                               # there is no mechanism for sending messages to isolated nodes. 
813                                 
814                                 # if we are here we have a node that doesn't have this message
815                                 if (!get_busy($call)  && $dxchan->state eq 'normal') {
816                                         $ref->start_msg($dxchan);
817                                         last;
818                                 }
819                         }
820                 }
821
822                 # if all the available nodes are busy then stop
823                 last if @nodelist == scalar grep { get_busy($_->call) } @nodelist;
824         }
825
826         
827 }
828
829 # is there a message for me?
830 sub for_me
831 {
832         my $call = uc shift;
833         my $ref;
834         my $count;
835         
836         foreach $ref (@msg) {
837                 # is it for me, private and unread? 
838                 if ($ref->{to} eq $call && $ref->{private}) {
839                    $count++ unless $ref->{'read'} || $ref->{delete};
840                 }
841         }
842         return $count;
843 }
844
845 # start the message off on its travels with a PC28
846 sub start_msg
847 {
848         my ($self, $dxchan) = @_;
849         
850         confess("trying to start started msg $self->{msgno} nodes: $self->{fromnode} -> $self->{tonode}") if $self->{tonode};
851         dbg("start msg $self->{msgno}\n") if isdbg('msg');
852         $self->{linesreq} = 10;
853         $self->{count} = 0;
854         $self->{tonode} = $dxchan->call;
855         $self->{fromnode} = $main::mycall;
856         set_busy($self->{tonode}, $self);
857         set_fwq($self->{tonode}, undef, $self);
858         $self->{lastt} = $main::systime;
859         my ($fromnode, $origin);
860         $fromnode = $self->{fromnode};
861         $origin = $self->{origin};
862         $dxchan->send(DXProt::pc28($self->{tonode}, $fromnode, $self->{to}, $self->{from}, $self->{t}, $self->{private}, $self->{subject}, $origin, $self->{rrreq}));
863 }
864
865 # get the ref of a busy node
866 sub get_busy
867 {
868         my $call = shift;
869         return $busy{$call};
870 }
871
872 sub set_busy
873 {
874         my $call = shift;
875         return $busy{$call} = shift;
876 }
877
878 sub del_busy
879 {
880         my $call = shift;
881         return delete $busy{$call};
882 }
883
884 # get the whole busy queue
885 sub get_all_busy
886 {
887         return keys %busy;
888 }
889
890 # get a forwarding queue entry
891 sub get_fwq
892 {
893         my $call = shift;
894         my $stream = shift || '0';
895         return $work{"$call,$stream"};
896 }
897
898 # delete a forwarding queue entry
899 sub del_fwq
900 {
901         my $call = shift;
902         my $stream = shift || '0';
903         return delete $work{"$call,$stream"};
904 }
905
906 # set a fwq entry
907 sub set_fwq
908 {
909         my $call = shift;
910         my $stream = shift || '0';
911         return $work{"$call,$stream"} = shift;
912 }
913
914 # get the whole forwarding queue
915 sub get_all_fwq
916 {
917         return keys %work;
918 }
919
920 # stop a message from continuing, clean it out, unlock interlocks etc
921 sub stop_msg
922 {
923         my $self = shift;
924         my $node = shift;
925         my $stream = $self->{stream};
926         
927         
928         dbg("stop msg $self->{msgno} -> node $node\n") if isdbg('msg');
929         del_fwq($node, $stream);
930         $self->workclean;
931         del_busy($node);
932 }
933
934 sub workclean
935 {
936         my $ref = shift;
937         delete $ref->{lines};
938         delete $ref->{linesreq};
939         delete $ref->{tonode};
940         delete $ref->{fromnode};
941         delete $ref->{stream};
942         delete $ref->{file};
943         delete $ref->{count};
944         delete $ref->{tempr};
945         delete $ref->{lastt};
946         delete $ref->{waitt};
947 }
948
949 # get a new transaction number from the file specified
950 sub next_transno
951 {
952         my $name = shift;
953         $name =~ s/\W//og;                      # remove non-word characters
954         my $fn = "$msgdir/$name";
955         my $msgno;
956         
957         my $fh = new IO::File;
958         if (sysopen($fh, $fn, O_RDWR|O_CREAT, 0666)) {
959                 $fh->autoflush(1);
960                 $msgno = $fh->getline || '0';
961                 chomp $msgno;
962                 $msgno++;
963                 seek $fh, 0, 0;
964                 $fh->print("$msgno\n");
965                 dbg("msgno $msgno allocated for $name\n") if isdbg('msg');
966                 $fh->close;
967         } else {
968                 confess "can't open $fn $!";
969         }
970         return $msgno;
971 }
972
973 # initialise the message 'system', read in all the message headers
974 sub init
975 {
976         my $dir = new IO::File;
977         my @dir;
978         my $ref;
979                 
980         # load various control files
981         dbg("load badmsg: " . (load_badmsg() or "Ok"));
982         dbg("load forward: " . (load_forward() or "Ok"));
983         dbg("load swop: " . (load_swop() or "Ok"));
984
985         # read in the directory
986         opendir($dir, $msgdir) or confess "can't open $msgdir $!";
987         @dir = readdir($dir);
988         closedir($dir);
989
990         @msg = ();
991         for (sort @dir) {
992                 next unless /^m\d\d\d\d\d\d$/;
993                 
994                 $ref = read_msg_header("$msgdir/$_");
995                 unless ($ref) {
996                         dbg("Deleting $_");
997                         Log('err', "Deleting $_");
998                         unlink "$msgdir/$_";
999                         next;
1000                 }
1001                 
1002                 # delete any messages to 'badmsg.pl' places
1003                 if ($ref->dump_it('')) {
1004                         dbg("'Bad' TO address $ref->{to}") if isdbg('msg');
1005                         Log('msg', "'Bad' TO address $ref->{to}");
1006                         $ref->del_msg;
1007                         next;
1008                 }
1009
1010                 # add the message to the available queue
1011                 add_dir($ref); 
1012         }
1013 }
1014
1015 # add the message to the directory listing
1016 sub add_dir
1017 {
1018         my $ref = shift;
1019         confess "tried to add a non-ref to the msg directory" if !ref $ref;
1020         push @msg, $ref;
1021 }
1022
1023 # return all the current messages
1024 sub get_all
1025 {
1026         return @msg;
1027 }
1028
1029 # get a particular message
1030 sub get
1031 {
1032         my $msgno = shift;
1033         for (@msg) {
1034                 return $_ if $_->{msgno} == $msgno;
1035                 last if $_->{msgno} > $msgno;
1036         }
1037         return undef;
1038 }
1039
1040 # return the official filename for a message no
1041 sub filename
1042 {
1043         return sprintf "$msgdir/m%06d", shift;
1044 }
1045
1046 #
1047 # return a list of valid elements 
1048
1049
1050 sub fields
1051 {
1052         return keys(%valid);
1053 }
1054
1055 #
1056 # return a prompt for a field
1057 #
1058
1059 sub field_prompt
1060
1061         my ($self, $ele) = @_;
1062         return $valid{$ele};
1063 }
1064
1065 #
1066 # send a message state machine
1067 sub do_send_stuff
1068 {
1069         my $self = shift;
1070         my $line = shift;
1071         my @out;
1072         
1073         if ($self->state eq 'send1') {
1074                 #  $DB::single = 1;
1075                 confess "local var gone missing" if !ref $self->{loc};
1076                 my $loc = $self->{loc};
1077                 if (my @ans = BadWords::check($line)) {
1078                         $self->{badcount} += @ans;
1079                         Log('msg', $self->call . " used badwords: @ans to @{$loc->{to}} in msg");
1080                         $loc->{reject}++;
1081                 }
1082                 $loc->{subject} = $line;
1083                 $loc->{lines} = [];
1084                 $self->state('sendbody');
1085                 #push @out, $self->msg('sendbody');
1086                 push @out, $self->msg('m8');
1087         } elsif ($self->state eq 'sendbody') {
1088                 confess "local var gone missing" if !ref $self->{loc};
1089                 my $loc = $self->{loc};
1090                 if ($line eq "\032" || $line eq '%1A' || uc $line eq "/EX") {
1091                         my $to;
1092                         unless ($loc->{reject}) {
1093                                 foreach $to (@{$loc->{to}}) {
1094                                         my $ref;
1095                                         my $systime = $main::systime;
1096                                         my $mycall = $main::mycall;
1097                                         $ref = DXMsg->alloc(DXMsg::next_transno('Msgno'),
1098                                                                                 uc $to,
1099                                                                                 exists $loc->{from} ? $loc->{from} : $self->call, 
1100                                                                                 $systime,
1101                                                                                 $loc->{private}, 
1102                                                                                 $loc->{subject}, 
1103                                                                                 exists $loc->{origin} ? $loc->{origin} : $mycall,
1104                                                                                 '0',
1105                                                                                 $loc->{rrreq});
1106                                         $ref->swop_it($self->call);
1107                                         $ref->store($loc->{lines});
1108                                         $ref->add_dir();
1109                                         push @out, $self->msg('m11', $ref->{msgno}, $to);
1110                                         #push @out, "msgno $ref->{msgno} sent to $to";
1111                                         $ref->notify;
1112                                 }
1113                         } else {
1114                                 LogDbg('msg', $self->call . " swore to @{$loc->{to}} subject: '$loc->{subject}' in msg, REJECTED");
1115                         }
1116                         
1117                         delete $loc->{lines};
1118                         delete $loc->{to};
1119                         delete $self->{loc};
1120                         $self->func(undef);
1121                         
1122                         $self->state('prompt');
1123                 } elsif ($line eq "\031" || uc $line eq "/ABORT" || uc $line eq "/QUIT") {
1124                         #push @out, $self->msg('sendabort');
1125                         push @out, $self->msg('m10');
1126                         delete $loc->{lines};
1127                         delete $loc->{to};
1128                         delete $self->{loc};
1129                         $self->func(undef);
1130                         $self->state('prompt');
1131                 } elsif ($line =~ m|^/+\w+|) {
1132                         # this is a command that you want display for your own reference
1133                         # or if it has TWO slashes is a command 
1134                         $line =~ s|^/||;
1135                         my $store = $line =~ s|^/+||;
1136                         my @in = $self->run_cmd($line);
1137                         push @out, @in;
1138                         if ($store) {
1139                                 foreach my $l (@in) {
1140                                         if (my @ans = BadWords::check($l)) {
1141                                                 $self->{badcount} += @ans;
1142                                                 Log('msg', $self->call . " used badwords: @ans to @{$loc->{to}} subject: '$loc->{subject}' in msg") unless $loc->{reject};
1143                                                 Log('msg', "line: $l");
1144                                                 $loc->{reject}++;
1145                                         } 
1146                                         push @{$loc->{lines}}, length($l) > 0 ? $l : " ";
1147                                 }
1148                         }
1149                 } else {
1150                         if (my @ans = BadWords::check($line)) {
1151                                 $self->{badcount} += @ans;
1152                                 Log('msg', $self->call . " used badwords: @ans to @{$loc->{to}} subject: '$loc->{subject}' in msg") unless $loc->{reject};
1153                                 Log('msg', "line: $line");
1154                                 $loc->{reject}++;
1155                         }
1156
1157                         if ($loc->{lines} && @{$loc->{lines}}) {
1158                                 push @{$loc->{lines}}, length($line) > 0 ? $line : " ";
1159                         } else {
1160                                 # temporarily store any R: lines so that we end up with 
1161                                 # only the first and last ones stored.
1162                                 if ($line =~ m|^R:\d{6}/\d{4}|) {
1163                                         push @{$loc->{tempr}}, $line;
1164                                 } else {
1165                                         if (exists $loc->{tempr}) {
1166                                                 push @{$loc->{lines}}, shift @{$loc->{tempr}};
1167                                                 push @{$loc->{lines}}, pop @{$loc->{tempr}} if @{$loc->{tempr}};
1168                                                 delete $loc->{tempr};
1169                                         }
1170                                         push @{$loc->{lines}}, length($line) > 0 ? $line : " ";
1171                                 } 
1172                         }
1173                         
1174                         # i.e. it ain't and end or abort, therefore store the line
1175                 }
1176         }
1177         return @out;
1178 }
1179
1180 # return the standard directory line for this ref 
1181 sub dir
1182 {
1183         my $ref = shift;
1184         my $flag = $ref->{private} && $ref->{read} ? '-' : ' ';
1185         if ($ref->{keep}) {
1186                 $flag = '!';
1187         } elsif ($ref->{delete}) {
1188                 $flag = $ref->{deletetime} > $main::systime ? 'D' : 'E'; 
1189         }
1190         return sprintf("%6d%s%s%5d %8.8s %8.8s %-6.6s %5.5s %-30.30s", 
1191                                    $ref->{msgno}, $flag, $ref->{private} ? 'p' : ' ', 
1192                                    $ref->{size}, $ref->{to}, $ref->{from}, cldate($ref->{t}), 
1193                                    ztime($ref->{t}), $ref->{subject});
1194 }
1195
1196 # load the forward table
1197 sub load_forward
1198 {
1199         my @out;
1200         my $s = readfilestr($forwardfn);
1201         if ($s) {
1202                 eval $s;
1203                 push @out, $@ if $@;
1204         }
1205         return @out;
1206 }
1207
1208 # load the bad message table
1209 sub load_badmsg
1210 {
1211         my @out;
1212         my $s = readfilestr($badmsgfn);
1213         if ($s) {
1214                 eval $s;
1215                 push @out, $@ if $@;
1216         }
1217         return @out;
1218 }
1219
1220 # load the swop message table
1221 sub load_swop
1222 {
1223         my @out;
1224         my $s = readfilestr($swopfn);
1225         if ($s) {
1226                 eval $s;
1227                 push @out, $@ if $@;
1228         }
1229         return @out;
1230 }
1231
1232 #
1233 # forward that message or not according to the forwarding table
1234 # returns 1 for forward, 0 - to ignore
1235 #
1236
1237 sub forward_it
1238 {
1239         my $ref = shift;
1240         my $call = shift;
1241         my $i;
1242         
1243         for ($i = 0; $i < @forward; $i += 5) {
1244                 my ($sort, $field, $pattern, $action, $bbs) = @forward[$i..($i+4)]; 
1245                 my $tested;
1246                 
1247                 # are we interested?
1248                 next if $ref->{private} && $sort ne 'P';
1249                 next if !$ref->{private} && $sort ne 'B';
1250                 
1251                 # select field
1252                 $tested = $ref->{to} if $field eq 'T';
1253                 $tested = $ref->{from} if $field eq 'F';
1254                 $tested = $ref->{origin} if $field eq 'O';
1255                 $tested = $ref->{subject} if $field eq 'S';
1256
1257                 if (!$pattern || $tested =~ m{$pattern}i) {
1258                         return 0 if $action eq 'I';
1259                         return 1 if !$bbs || grep $_ eq $call, @{$bbs};
1260                 }
1261         }
1262         return 0;
1263 }
1264
1265 #
1266 # look down the forward table to see whether this is a valid bull
1267 # or not (ie it will forward somewhere even if it is only here)
1268 #
1269 sub valid_bull_addr
1270 {
1271         my $call = shift;
1272         my $i;
1273         
1274         unless (@forward) {
1275                 return 1 if $call =~ /^ALL/;
1276                 return 1 if $call =~ /^DX/;
1277                 return 0;
1278         }
1279         
1280         for ($i = 0; $i < @forward; $i += 5) {
1281                 my ($sort, $field, $pattern, $action, $bbs) = @forward[$i..($i+4)]; 
1282                 if ($field eq 'T') {
1283                         if (!$pattern || $call =~ m{$pattern}i) {
1284                                 return 1;
1285                         }
1286                 }
1287         }
1288         return 0;
1289 }
1290
1291 sub dump_it
1292 {
1293         my $ref = shift;
1294         my $call = shift;
1295         my $i;
1296         
1297         for ($i = 0; $i < @badmsg; $i += 3) {
1298                 my ($sort, $field, $pattern) = @badmsg[$i..($i+2)]; 
1299                 my $tested;
1300                 
1301                 # are we interested?
1302                 next if $ref->{private} && $sort ne 'P';
1303                 next if !$ref->{private} && $sort ne 'B';
1304                 
1305                 # select field
1306                 $tested = $ref->{to} if $field eq 'T';
1307                 $tested = $ref->{from} if $field eq 'F';
1308                 $tested = $ref->{origin} if $field eq 'O';
1309                 $tested = $ref->{subject} if $field eq 'S';
1310                 $tested = $call if $field eq 'I';
1311
1312                 if (!$pattern || $tested =~ m{$pattern}i) {
1313                         return 1;
1314                 }
1315         }
1316         return 0;
1317 }
1318
1319 sub swop_it
1320 {
1321         my $ref = shift;
1322         my $call = shift;
1323         my $i;
1324         my $count = 0;
1325         
1326         for ($i = 0; $i < @swop; $i += 5) {
1327                 my ($sort, $field, $pattern, $tfield, $topattern) = @swop[$i..($i+4)]; 
1328                 my $tested;
1329                 my $swop;
1330                 my $old;
1331                 
1332                 # are we interested?
1333                 next if $ref->{private} && $sort ne 'P';
1334                 next if !$ref->{private} && $sort ne 'B';
1335                 
1336                 # select field
1337                 $tested = $ref->{to} if $field eq 'T';
1338                 $tested = $ref->{from} if $field eq 'F';
1339                 $tested = $ref->{origin} if $field eq 'O';
1340                 $tested = $ref->{subject} if $field eq 'S';
1341
1342                 # select swop field
1343                 $old = $swop = $ref->{to} if $tfield eq 'T';
1344                 $old = $swop = $ref->{from} if $tfield eq 'F';
1345                 $old = $swop = $ref->{origin} if $tfield eq 'O';
1346                 $old = $swop = $ref->{subject} if $tfield eq 'S';
1347
1348                 if ($tested =~ m{$pattern}i) {
1349                         if ($tested eq $swop) {
1350                                 $swop =~ s{$pattern}{$topattern}i;
1351                         } else {
1352                                 $swop = $topattern;
1353                         }
1354                         Log('msg', "Msg $ref->{msgno}: $tfield $old -> $swop");
1355                         Log('dbg', "Msg $ref->{msgno}: $tfield $old -> $swop");
1356                         $ref->{to} = $swop if $tfield eq 'T';
1357                         $ref->{from} = $swop if $tfield eq 'F';
1358                         $ref->{origin} = $swop if $tfield eq 'O';
1359                         $ref->{subject} = $swop if $tfield eq 'S';
1360                         ++$count;
1361                 }
1362         }
1363         return $count;
1364 }
1365
1366 # import any msgs in the import directory
1367 # the messages are in BBS format (but may have cluster extentions
1368 # so SB UK < GB7TLH is legal
1369 sub import_msgs
1370 {
1371         # are there any to do in this directory?
1372         return unless -d $importfn;
1373         unless (opendir(DIR, $importfn)) {
1374                 dbg("can\'t open $importfn $!") if isdbg('msg');
1375                 Log('msg', "can\'t open $importfn $!");
1376                 return;
1377         } 
1378
1379         my @names = readdir(DIR);
1380         closedir(DIR);
1381         my $name;
1382         foreach $name (@names) {
1383                 next if $name =~ /^\./;
1384                 my $splitit = $name =~ /^split/;
1385                 my $fn = "$importfn/$name";
1386                 next unless -f $fn;
1387                 unless (open(MSG, $fn)) {
1388                         dbg("can\'t open import file $fn $!") if isdbg('msg');
1389                         Log('msg', "can\'t open import file $fn $!");
1390                         unlink($fn);
1391                         next;
1392                 }
1393                 my @msg = map { chomp; $_ } <MSG>;
1394                 close(MSG);
1395                 unlink($fn);
1396                 my @out = import_one($main::me, \@msg, $splitit);
1397                 Log('msg', @out);
1398         }
1399 }
1400
1401 # import one message as a list in bbs (as extended) mode
1402 # takes a reference to an array containing the whole message
1403 sub import_one
1404 {
1405         my $dxchan = shift;
1406         my $ref = shift;
1407         my $splitit = shift;
1408         my $private = '1';
1409         my $rr = '0';
1410         my $notincalls = 1;
1411         my $from = $dxchan->call;
1412         my $origin = $main::mycall;
1413         my @to;
1414         my @out;
1415                                 
1416         # first line;
1417         my $line = shift @$ref;
1418         my @f = split /([\s\@\$])/, $line;
1419         @f = map {s/\s+//g; length $_ ? $_ : ()} @f;
1420
1421         unless (@f && $f[0] =~ /^(:?S|SP|SB|SEND)$/ ) {
1422                 my $m = "invalid first line in import '$line'";
1423                 dbg($m) if isdbg('msg');
1424                 return (1, $m);
1425         }
1426         while (@f) {
1427                 my $f = uc shift @f;
1428                 next if $f eq 'SEND';
1429
1430                 # private / noprivate / rr
1431                 if ($notincalls && ($f eq 'B' || $f eq 'SB' || $f =~ /^NOP/oi)) {
1432                         $private = '0';
1433                 } elsif ($notincalls && ($f eq 'P' || $f eq 'SP' || $f =~ /^PRI/oi)) {
1434                         ;
1435                 } elsif ($notincalls && ($f eq 'RR')) {
1436                         $rr = '1';
1437                 } elsif (($f =~ /^[\@\.\#\$]$/ || $f eq '.#') && @f) {       # this is bbs syntax, for AT
1438                         shift @f;
1439                 } elsif ($f eq '<' && @f) {     # this is bbs syntax  for from call
1440                         $from = uc shift @f;
1441                 } elsif ($f =~ /^\$/) {     # this is bbs syntax  for a bid
1442                         next;
1443                 } elsif ($f =~ /^<(\S+)/) {     # this is bbs syntax  for from call
1444                         $from = $1;
1445                 } elsif ($f =~ /^\$\S+/) {     # this is bbs syntax for bid
1446                         ;
1447                 } else {
1448
1449                         # callsign ?
1450                         $notincalls = 0;
1451
1452                         # is this callsign a distro?
1453                         my $fn = "$msgdir/distro/$f.pl";
1454                         if (-e $fn) {
1455                                 my $fh = new IO::File $fn;
1456                                 if ($fh) {
1457                                         local $/ = undef;
1458                                         my $s = <$fh>;
1459                                         $fh->close;
1460                                         my @call;
1461                                         @call = eval $s;
1462                                         return (1, "Error in Distro $f.pl:", $@) if $@;
1463                                         if (@call > 0) {
1464                                                 push @f, @call;
1465                                                 next;
1466                                         }
1467                                 }
1468                         }
1469                         
1470                         if (grep $_ eq $f, @DXMsg::badmsg) {
1471                                 push @out, $dxchan->msg('m3', $f);
1472                         } else {
1473                                 push @to, $f;
1474                         }
1475                 }
1476         }
1477         
1478         # subject is the next line
1479         my $subject = shift @$ref;
1480         
1481         # strip off trailing lines 
1482         pop @$ref while (@$ref && $$ref[-1] =~ /^\s*$/);
1483         
1484         # strip off /EX or /ABORT
1485         return ("aborted") if @$ref && $$ref[-1] =~ m{^/ABORT$}i; 
1486         pop @$ref if (@$ref && $$ref[-1] =~ m{^/EX$}i);                                                                  
1487
1488         # sort out any splitting that needs to be done
1489         my @chunk;
1490         if ($splitit) {
1491                 my $lth = 0;
1492                 my $lines = [];
1493                 for (@$ref) {
1494                         if ($lth >= $maxchunk || ($lth > $minchunk && /^\s*$/)) {
1495                                 push @chunk, $lines;
1496                                 $lines = [];
1497                                 $lth = 0;
1498                         } 
1499                         push @$lines, $_;
1500                         $lth += length; 
1501                 }
1502                 push @chunk, $lines if @$lines;
1503         } else {
1504                 push @chunk, $ref;
1505         }
1506
1507         # does an identical message already exist?
1508         my $m;
1509         for $m (@msg) {
1510                 if (substr($subject,0,28) eq substr($m->{subject},0,28) && $from eq $m->{from} && grep $m->{to} eq $_, @to) {
1511                         my $msgno = $m->{msgno};
1512                         dbg("duplicate message from $from -> $m->{to} to msg: $msgno") if isdbg('msg');
1513                         Log('msg', "duplicate message from $from -> $m->{to} to msg: $msgno");
1514                         return;
1515                 }
1516         }
1517
1518     # write all the messages away
1519         my $i;
1520         for ( $i = 0;  $i < @chunk; $i++) {
1521                 my $chunk = $chunk[$i];
1522                 my $ch_subject;
1523                 if (@chunk > 1) {
1524                         my $num = " [" . ($i+1) . "/" . scalar @chunk . "]";
1525                         $ch_subject = substr($subject, 0, 27 - length $num) .  $num;
1526                 } else {
1527                         $ch_subject = $subject;
1528                 }
1529                 my $to;
1530                 foreach $to (@to) {
1531                         my $systime = $main::systime;
1532                         my $mycall = $main::mycall;
1533                         my $mref = DXMsg->alloc(DXMsg::next_transno('Msgno'),
1534                                                                         $to,
1535                                                                         $from, 
1536                                                                         $systime,
1537                                                                         $private, 
1538                                                                         $ch_subject, 
1539                                                                         $origin,
1540                                                                         '0',
1541                                                                         $rr);
1542                         $mref->swop_it($main::mycall);
1543                         $mref->store($chunk);
1544                         $mref->add_dir();
1545                         push @out, $dxchan->msg('m11', $mref->{msgno}, $to);
1546                         #push @out, "msgno $ref->{msgno} sent to $to";
1547                         $mref->notify;
1548                 }
1549         }
1550         return @out;
1551 }
1552
1553 #no strict;
1554 sub AUTOLOAD
1555 {
1556         no strict;
1557         my $name = $AUTOLOAD;
1558         return if $name =~ /::DESTROY$/;
1559         $name =~ s/^.*:://o;
1560         
1561         confess "Non-existant field '$AUTOLOAD'" if !$valid{$name};
1562         # this clever line of code creates a subroutine which takes over from autoload
1563         # from OO Perl - Conway
1564         *$AUTOLOAD = sub {@_ > 1 ? $_[0]->{$name} = $_[1] : $_[0]->{$name}};
1565        goto &$AUTOLOAD;
1566 }
1567
1568 1;
1569
1570 __END__