1 # Copyright (C) 2020-2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # Writes PublicInbox::Eml objects atomically to a mbox variant or Maildir
5 package PublicInbox::LeiToMail;
8 use parent qw(PublicInbox::IPC);
10 use PublicInbox::ProcessPipe;
11 use PublicInbox::Spawn qw(spawn);
12 use PublicInbox::LeiDedupe;
13 use PublicInbox::PktOp qw(pkt_do);
14 use Symbol qw(gensym);
15 use IO::Handle; # ->autoflush
16 use Fcntl qw(SEEK_SET SEEK_END O_CREAT O_EXCL O_WRONLY);
18 my %kw2char = ( # Maildir characters
21 forwarded => 'P', # passed
27 flagged => [ 'X-Status' => 'F' ],
28 answered => [ 'X-Status' => 'A' ],
29 seen => [ 'Status' => 'R' ],
30 draft => [ 'X-Status' => 'T' ],
33 sub _mbox_hdr_buf ($$$) {
34 my ($eml, $type, $smsg) = @_;
35 $eml->header_set($_) for (qw(Lines Bytes Content-Length));
37 my %hdr = (Status => []); # set Status, X-Status
38 for my $k (@{$smsg->{kw} // []}) {
39 if (my $ent = $kw2status{$k}) {
40 push @{$hdr{$ent->[0]}}, $ent->[1];
42 warn "TODO: keyword `$k' not supported for mbox\n";
45 # Messages are always 'O' (non-\Recent in IMAP), it saves
46 # MUAs the trouble of rewriting the mbox if no other
47 # changes are made. We put 'O' at the end (e.g. "Status: RO")
48 # to match mutt(1) output.
49 $eml->header_set('Status', join('', sort(@{$hdr{Status}})). 'O');
50 if (my $chars = delete $hdr{'X-Status'}) {
51 $eml->header_set('X-Status', join('', sort(@$chars)));
53 my $buf = delete $eml->{hdr};
55 # fixup old bug from import (pre-a0c07cba0e5d8b6a)
56 $$buf =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
57 my $ident = $smsg->{blob} // 'lei';
58 if (defined(my $pct = $smsg->{pct})) { $ident .= "=$pct" }
60 substr($$buf, 0, 0, # prepend From line
61 "From $ident\@$type Thu Jan 1 00:00:00 1970$eml->{crlf}");
65 sub atomic_append { # for on-disk destinations (O_APPEND, or O_EXCL)
67 if (defined(my $w = syswrite($lei->{1} // return, $$buf))) {
68 return if $w == length($$buf);
69 $buf = "short atomic write: $w != ".length($$buf);
71 return $lei->note_sigpipe(1);
73 $buf = "atomic write: $!";
78 sub eml2mboxrd ($;$) {
79 my ($eml, $smsg) = @_;
80 my $buf = _mbox_hdr_buf($eml, 'mboxrd', $smsg);
81 if (my $bdy = delete $eml->{bdy}) {
82 $$bdy =~ s/^(>*From )/>$1/gm;
83 $$buf .= $eml->{crlf};
84 substr($$bdy, 0, 0, $$buf); # prepend header
87 $$buf .= $eml->{crlf};
92 my ($eml, $smsg) = @_;
93 my $buf = _mbox_hdr_buf($eml, 'mboxo', $smsg);
94 if (my $bdy = delete $eml->{bdy}) {
95 $$bdy =~ s/^From />From /gm;
96 $$buf .= $eml->{crlf};
97 substr($$bdy, 0, 0, $$buf); # prepend header
100 $$buf .= $eml->{crlf};
104 sub _mboxcl_common ($$$) {
105 my ($buf, $bdy, $crlf) = @_;
106 # add Lines: so mutt won't have to add it on MUA close
107 my $lines = $$bdy =~ tr!\n!\n!;
108 $$buf .= 'Content-Length: '.length($$bdy).$crlf.
109 'Lines: '.$lines.$crlf.$crlf;
110 substr($$bdy, 0, 0, $$buf); # prepend header
114 # mboxcl still escapes "From " lines
116 my ($eml, $smsg) = @_;
117 my $buf = _mbox_hdr_buf($eml, 'mboxcl', $smsg);
118 my $crlf = $eml->{crlf};
119 if (my $bdy = delete $eml->{bdy}) {
120 $$bdy =~ s/^From />From /gm;
121 _mboxcl_common($buf, $bdy, $crlf);
127 # mboxcl2 has no "From " escaping
129 my ($eml, $smsg) = @_;
130 my $buf = _mbox_hdr_buf($eml, 'mboxcl2', $smsg);
131 my $crlf = $eml->{crlf};
132 if (my $bdy = delete $eml->{bdy}) {
133 _mboxcl_common($buf, $bdy, $crlf);
139 sub git_to_mail { # git->cat_async callback
140 my ($bref, $oid, $type, $size, $arg) = @_;
141 if ($type ne 'blob') {
142 if ($type eq 'missing') {
143 warn "missing $oid\n";
145 warn "unexpected type=$type for $oid\n";
148 my ($write_cb, $smsg) = @$arg;
149 if ($smsg->{blob} ne $oid) {
150 die "BUG: expected=$smsg->{blob} got=$oid";
152 $write_cb->($bref, $smsg) if $size > 0;
155 sub reap_compress { # dwaitpid callback
156 my ($lei, $pid) = @_;
157 my $cmd = delete $lei->{"pid.$pid"};
159 $lei->fail("@$cmd failed", $? >> 8);
162 sub _post_augment_mbox { # open a compressor process
163 my ($self, $lei) = @_;
164 my $zsfx = $self->{zsfx} or return;
165 my $cmd = PublicInbox::MboxReader::zsfx2cmd($zsfx, undef, $lei);
166 my ($r, $w) = @{delete $lei->{zpipe}};
167 my $rdr = { 0 => $r, 1 => $lei->{1}, 2 => $lei->{2} };
168 my $pid = spawn($cmd, undef, $rdr);
170 my $dup = bless { "pid.$pid" => $cmd }, ref($lei);
171 $dup->{$_} = $lei->{$_} for qw(2 sock);
172 tie *$pp, 'PublicInbox::ProcessPipe', $pid, $w, \&reap_compress, $dup;
178 open my $dup, '+>>&', $in or die "dup: $!";
182 # --augment existing output destination, with deduplication
183 sub _augment { # MboxReader eml_cb
184 my ($eml, $lei) = @_;
185 # ignore return value, just populate the skv
186 $lei->{dedupe}->is_dup($eml);
189 sub _mbox_augment_kw_maybe {
190 my ($eml, $lei, $lse, $augment) = @_;
191 my $kw = PublicInbox::MboxReader::mbox_keywords($eml);
192 update_kw_maybe($lei, $lse, $eml, $kw);
193 _augment($eml, $lei) if $augment;
196 sub _mbox_write_cb ($$) {
197 my ($self, $lei) = @_;
198 my $ovv = $lei->{ovv};
199 my $m = 'eml2'.$ovv->{fmt};
200 my $eml2mbox = $self->can($m) or die "$self->$m missing";
201 $lei->{1} // die "no stdout ($m, $ovv->{dst})"; # redirected earlier
202 $lei->{1}->autoflush(1);
203 my $atomic_append = !defined($ovv->{lock_path});
204 my $dedupe = $lei->{dedupe};
205 $dedupe->prepare_dedupe;
206 my $lse = $lei->{lse}; # may be undef
207 sub { # for git_to_mail
208 my ($buf, $smsg, $eml) = @_;
209 $eml //= PublicInbox::Eml->new($buf);
210 return if $dedupe->is_dup($eml, $smsg->{blob});
211 $lse->xsmsg_vmd($smsg) if $lse;
212 $buf = $eml2mbox->($eml, $smsg);
213 return atomic_append($lei, $buf) if $atomic_append;
214 my $lk = $ovv->lock_for_scope;
219 sub update_kw_maybe ($$$$) {
220 my ($lei, $lse, $eml, $kw) = @_;
222 my $c = $lse->kw_changed($eml, $kw, my $docids = []);
223 my $vmd = { kw => $kw };
224 if (scalar @$docids) { # already in lei/store
225 $lei->{sto}->ipc_do('set_eml_vmd', undef, $vmd, $docids) if $c;
226 } elsif (my $xoids = $lei->{ale}->xoids_for($eml)) {
227 # it's in an external, only set kw, here
228 $lei->{sto}->ipc_do('set_xvmd', $xoids, $eml, $vmd);
229 } else { # never-before-seen, import the whole thing
230 # XXX this is critical in protecting against accidental
231 # data loss without --augment
232 $lei->{sto}->ipc_do('set_eml', $eml, $vmd);
236 sub _md_update { # maildir_each_eml cb
237 my ($f, $kw, $eml, $lei, $lse, $unlink) = @_;
238 update_kw_maybe($lei, $lse, $eml, $kw);
239 $unlink ? unlink($f) : _augment($eml, $lei);
242 # maildir_each_file callback, \&CORE::unlink doesn't work with it
243 sub _unlink { unlink($_[0]) }
247 sprintf('%x,%x,%x,%x', rand(0xffffffff), time, $$, ++$seq);
251 my ($dst, $buf, $smsg) = @_;
252 my $kw = $smsg->{kw} // [];
253 my $sfx = join('', sort(map { $kw2char{$_} // () } @$kw));
254 my $rand = ''; # chosen by die roll :P
255 my ($tmp, $fh, $final, $ok);
256 my $common = $smsg->{blob} // _rand;
257 if (defined(my $pct = $smsg->{pct})) { $common .= "=$pct" }
259 $tmp = $dst.'tmp/'.$rand.$common;
260 } while (!($ok = sysopen($fh, $tmp, O_CREAT|O_EXCL|O_WRONLY)) &&
261 $!{EEXIST} && ($rand = _rand.','));
262 if ($ok && print $fh $$buf and close($fh)) {
263 # ignore new/ and write only to cur/, otherwise MUAs
264 # with R/W access to the Maildir will end up doing
265 # a mass rename which can take a while with thousands
270 $final = $dst.$rand.$common.':2,'.$sfx;
271 } while (!($ok = link($tmp, $final)) && $!{EEXIST} &&
272 ($rand = _rand.','));
273 die "link($tmp, $final): $!" unless $ok;
274 unlink($tmp) or warn "W: failed to unlink $tmp: $!\n";
276 my $err = "Error writing $smsg->{blob} to $dst: $!\n";
277 $_[0] = undef; # clobber dst
283 sub _maildir_write_cb ($$) {
284 my ($self, $lei) = @_;
285 my $dedupe = $lei->{dedupe};
286 $dedupe->prepare_dedupe if $dedupe;
287 my $dst = $lei->{ovv}->{dst};
288 my $lse = $lei->{lse}; # may be undef
289 sub { # for git_to_mail
290 my ($buf, $smsg, $eml) = @_;
291 $dst // return $lei->fail; # dst may be undef-ed in last run
292 $buf //= \($eml->as_string);
293 $lse->xsmsg_vmd($smsg) if $lse;
294 return _buf2maildir($dst, $buf, $smsg) if !$dedupe;
295 $eml //= PublicInbox::Eml->new($$buf); # copy buf
296 return if $dedupe->is_dup($eml, $smsg->{blob});
298 _buf2maildir($dst, $buf, $smsg);
302 sub _imap_write_cb ($$) {
303 my ($self, $lei) = @_;
304 my $dedupe = $lei->{dedupe};
305 $dedupe->prepare_dedupe if $dedupe;
306 my $imap_append = $lei->{net}->can('imap_append');
307 my $mic = $lei->{net}->mic_get($self->{uri});
308 my $folder = $self->{uri}->mailbox;
309 my $lse = $lei->{lse}; # may be undef
310 sub { # for git_to_mail
311 my ($bref, $smsg, $eml) = @_;
312 $mic // return $lei->fail; # dst may be undef-ed in last run
314 $eml //= PublicInbox::Eml->new($$bref); # copy bref
315 return if $dedupe->is_dup($eml, $smsg->{blob});
317 $lse->xsmsg_vmd($smsg) if $lse;
318 eval { $imap_append->($mic, $folder, $bref, $smsg, $eml) };
326 sub write_cb { # returns a callback for git_to_mail
327 my ($self, $lei) = @_;
328 # _mbox_write_cb, _maildir_write_cb or _imap_write_cb
329 my $m = "_$self->{base_type}_write_cb";
334 my ($cls, $lei) = @_;
335 my $fmt = $lei->{ovv}->{fmt};
336 my $dst = $lei->{ovv}->{dst};
337 my $self = bless {}, $cls;
338 if ($fmt eq 'maildir') {
339 require PublicInbox::MdirReader;
340 $self->{base_type} = 'maildir';
341 -e $dst && !-d _ and die
342 "$dst exists and is not a directory\n";
343 $lei->{ovv}->{dst} = $dst .= '/' if substr($dst, -1) ne '/';
344 } elsif (substr($fmt, 0, 4) eq 'mbox') {
345 require PublicInbox::MboxReader;
346 (-d $dst || (-e _ && !-w _)) and die
347 "$dst exists and is not a writable file\n";
348 $self->can("eml2$fmt") or die "bad mbox format: $fmt\n";
349 $self->{base_type} = 'mbox';
350 } elsif ($fmt =~ /\Aimaps?\z/) { # TODO .onion support
351 require PublicInbox::NetWriter;
352 my $net = PublicInbox::NetWriter->new;
354 $net->{quiet} = $lei->{opt}->{quiet};
355 my $err = $net->errors($dst);
356 return $lei->fail($err) if $err;
357 require PublicInbox::URIimap; # TODO: URI cast early
358 $self->{uri} = PublicInbox::URIimap->new($dst);
359 $self->{uri}->mailbox or die "No mailbox: $dst";
361 $self->{base_type} = 'imap';
363 die "bad mail --format=$fmt\n";
366 $lei->{dedupe} = PublicInbox::LeiDedupe->new($lei);
370 sub _pre_augment_maildir {
371 my ($self, $lei) = @_;
372 my $dst = $lei->{ovv}->{dst};
373 for my $x (qw(tmp new cur)) {
377 File::Path::mkpath($d);
378 -d $d or die "$d is not a directory";
382 sub _do_augment_maildir {
383 my ($self, $lei) = @_;
384 my $dst = $lei->{ovv}->{dst};
385 my $lse = $lei->{opt}->{'import-before'} ? $lei->{lse} : undef;
386 my $mdr = PublicInbox::MdirReader->new;
387 if ($lei->{opt}->{augment}) {
388 my $dedupe = $lei->{dedupe};
389 if ($dedupe && $dedupe->prepare_dedupe) {
390 $mdr->{shard_info} = $self->{shard_info};
391 $mdr->maildir_each_eml($dst, \&_md_update, $lei, $lse);
392 $dedupe->pause_dedupe;
395 $mdr->{shard_info} = $self->{shard_info};
396 $mdr->maildir_each_eml($dst, \&_md_update, $lei, $lse, 1);
397 } else {# clobber existing Maildir
398 $mdr->maildir_each_file($dst, \&_unlink);
402 sub _imap_augment_or_delete { # PublicInbox::NetReader::imap_each cb
403 my ($url, $uid, $kw, $eml, $lei, $lse, $delete_mic) = @_;
404 update_kw_maybe($lei, $lse, $eml, $kw);
406 $lei->{net}->imap_delete_1($url, $uid, $delete_mic);
408 _augment($eml, $lei);
412 sub _do_augment_imap {
413 my ($self, $lei) = @_;
414 my $net = $lei->{net};
415 my $lse = $lei->{opt}->{'import-before'} ? $lei->{lse} : undef;
416 if ($lei->{opt}->{augment}) {
417 my $dedupe = $lei->{dedupe};
418 if ($dedupe && $dedupe->prepare_dedupe) {
419 $net->imap_each($self->{uri}, \&_imap_augment_or_delete,
421 $dedupe->pause_dedupe;
425 $net->imap_each($self->{uri}, \&_imap_augment_or_delete,
426 $lei, $lse, \$delete_mic);
427 $delete_mic->expunge if $delete_mic;
428 } elsif (!$self->{-wq_worker_nr}) { # undef or 0
429 # clobber existing IMAP folder
430 $net->imap_delete_all($self->{uri});
434 sub _pre_augment_mbox {
435 my ($self, $lei) = @_;
436 my $dst = $lei->{ovv}->{dst};
438 my $devfd = $lei->path_to_fd($dst) // die "bad $dst";
440 $out = $lei->{$devfd};
441 } else { # normal-looking path
443 open $out, '>', $dst or die "open($dst): $!";
444 } elsif (-f _ || !-e _) {
445 require PublicInbox::MboxLock;
446 my $m = $lei->{opt}->{'lock'} //
447 PublicInbox::MboxLock->defaults;
448 $self->{mbl} = PublicInbox::MboxLock->acq($dst, 1, $m);
449 $out = $self->{mbl}->{fh};
451 die "$dst is not a file or FIFO\n";
453 $lei->{old_1} = $lei->{1}; # keep for spawning MUA
455 # Perl does SEEK_END even with O_APPEND :<
456 $self->{seekable} = seek($out, 0, SEEK_SET);
457 if (!$self->{seekable} && !$!{ESPIPE} && !defined($devfd)) {
458 die "seek($dst): $!\n";
460 if (!$self->{seekable}) {
461 my $imp_before = $lei->{opt}->{'import-before'};
462 die "--import-before specified but $dst is not seekable\n"
463 if $imp_before && !ref($imp_before);
464 die "--augment specified but $dst is not seekable\n" if
465 $lei->{opt}->{augment};
467 if ($self->{zsfx} = PublicInbox::MboxReader::zsfx($dst)) {
468 pipe(my ($r, $w)) or die "pipe: $!";
469 $lei->{zpipe} = [ $r, $w ];
470 $lei->{ovv}->{lock_path} and
471 die 'BUG: unexpected {ovv}->{lock_path}';
472 $lei->{ovv}->ovv_out_lk_init;
473 } elsif (!$self->{seekable} && !$lei->{ovv}->{lock_path}) {
474 $lei->{ovv}->ovv_out_lk_init;
480 sub _do_augment_mbox {
481 my ($self, $lei) = @_;
482 return unless $self->{seekable};
483 my $opt = $lei->{opt};
485 my ($fmt, $dst) = @{$lei->{ovv}}{qw(fmt dst)};
486 return unless -s $out;
487 unless ($opt->{augment} || $opt->{'import-before'}) {
488 truncate($out, 0) or die "truncate($dst): $!";
491 my $zsfx = $self->{zsfx};
492 my $rd = $zsfx ? PublicInbox::MboxReader::zsfxcat($out, $zsfx, $lei)
495 if ($opt->{augment}) {
496 $dedupe = $lei->{dedupe};
497 $dedupe->prepare_dedupe if $dedupe;
499 if ($opt->{'import-before'}) { # the default
500 my $lse = $lei->{lse};
501 PublicInbox::MboxReader->$fmt($rd, \&_mbox_augment_kw_maybe,
502 $lei, $lse, $opt->{augment});
503 if (!$opt->{augment} and !truncate($out, 0)) {
504 die "truncate($dst): $!";
506 } else { # --augment --no-import-before
507 PublicInbox::MboxReader->$fmt($rd, \&_augment, $lei);
509 # maybe some systems don't honor O_APPEND, Perl does this:
510 seek($out, 0, SEEK_END) or die "seek $dst: $!";
511 $dedupe->pause_dedupe if $dedupe;
514 sub pre_augment { # fast (1 disk seek), runs in same process as post_augment
515 my ($self, $lei) = @_;
516 # _pre_augment_maildir, _pre_augment_mbox
517 my $m = $self->can("_pre_augment_$self->{base_type}") or return;
521 sub do_augment { # slow, runs in wq worker
522 my ($self, $lei) = @_;
523 # _do_augment_maildir, _do_augment_mbox, or _do_augment_imap
524 my $m = "_do_augment_$self->{base_type}";
528 # fast (spawn compressor or mkdir), runs in same process as pre_augment
530 my ($self, $lei, @args) = @_;
531 my $wait = $lei->{opt}->{'import-before'} ?
532 $lei->{sto}->ipc_do('checkpoint', 1) : 0;
534 my $m = $self->can("_post_augment_$self->{base_type}") or return;
535 $m->($self, $lei, @args);
540 my $lei = $self->{lei};
541 # lei_xsearch can start as soon as all l2m workers get here
542 pkt_do($lei->{pkt_op_p}, 'incr_start_query') or
543 die "incr_start_query: $!";
545 if (lock_free($self)) {
546 my $mod = $self->{-wq_nr_workers};
547 my $shard = $self->{-wq_worker_nr};
548 if (my $net = $lei->{net}) {
549 $net->{shard_info} = [ $mod, $shard ];
551 $self->{shard_info} = [ $mod, $shard ];
553 $aug = '+'; # incr_post_augment
554 } elsif ($self->{-wq_worker_nr} == 0) {
555 $aug = '.'; # do_post_augment
558 local $0 = 'do_augment';
559 eval { do_augment($self, $lei) };
560 $lei->fail($@) if $@;
561 pkt_do($lei->{pkt_op_p}, $aug) == 1 or
562 die "do_post_augment trigger: $!";
564 if (my $zpipe = delete $lei->{zpipe}) {
565 $lei->{1} = $zpipe->[1];
568 $self->{wcb} = $self->write_cb($lei);
571 sub ipc_atfork_child {
573 my $lei = $self->{lei};
574 $lei->_lei_atfork_child;
575 $lei->{auth}->do_auth_atfork($self) if $lei->{auth};
576 $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb();
577 $self->SUPER::ipc_atfork_child;
581 $_[0]->{base_type} =~ /\A(?:maildir|imap|jmap)\z/ ? 1 : 0;
586 if ($self->{base_type} eq 'maildir') {
588 utime($t, $t, $self->{dst} . 'cur');
592 sub write_mail { # via ->wq_io_do
593 my ($self, $smsg) = @_;
594 $self->{lei}->{ale}->git->cat_async($smsg->{blob}, \&git_to_mail,
595 [$self->{wcb}, $smsg]);
598 sub wq_atexit_child {
601 $self->{lei}->{ale}->git->async_wait_all;
602 $SIG{__WARN__} = 'DEFAULT';
605 # called in top-level lei-daemon when LeiAuth is done
606 sub net_merge_complete {
608 $self->wq_broadcast('do_post_auth');
612 no warnings 'once'; # the following works even when LeiAuth is lazy-loaded
613 *net_merge_all = \&PublicInbox::LeiAuth::net_merge_all;