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);
17 use Digest::SHA qw(sha256_hex);
19 my %kw2char = ( # Maildir characters
22 forwarded => 'P', # passed
28 flagged => [ 'X-Status' => 'F' ],
29 answered => [ 'X-Status' => 'A' ],
30 seen => [ 'Status' => 'R' ],
31 draft => [ 'X-Status' => 'T' ],
34 sub _mbox_hdr_buf ($$$) {
35 my ($eml, $type, $smsg) = @_;
36 $eml->header_set($_) for (qw(Lines Bytes Content-Length));
38 my %hdr = (Status => []); # set Status, X-Status
39 for my $k (@{$smsg->{kw} // []}) {
40 if (my $ent = $kw2status{$k}) {
41 push @{$hdr{$ent->[0]}}, $ent->[1];
43 warn "TODO: keyword `$k' not supported for mbox\n";
46 # Messages are always 'O' (non-\Recent in IMAP), it saves
47 # MUAs the trouble of rewriting the mbox if no other
48 # changes are made. We put 'O' at the end (e.g. "Status: RO")
49 # to match mutt(1) output.
50 $eml->header_set('Status', join('', sort(@{$hdr{Status}})). 'O');
51 if (my $chars = delete $hdr{'X-Status'}) {
52 $eml->header_set('X-Status', join('', sort(@$chars)));
54 my $buf = delete $eml->{hdr};
56 # fixup old bug from import (pre-a0c07cba0e5d8b6a)
57 $$buf =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
58 my $ident = $smsg->{blob} // 'lei';
59 if (defined(my $pct = $smsg->{pct})) { $ident .= "=$pct" }
61 substr($$buf, 0, 0, # prepend From line
62 "From $ident\@$type Thu Jan 1 00:00:00 1970$eml->{crlf}");
66 sub atomic_append { # for on-disk destinations (O_APPEND, or O_EXCL)
68 if (defined(my $w = syswrite($lei->{1} // return, $$buf))) {
69 return if $w == length($$buf);
70 $buf = "short atomic write: $w != ".length($$buf);
72 return $lei->note_sigpipe(1);
74 $buf = "atomic write: $!";
79 sub eml2mboxrd ($;$) {
80 my ($eml, $smsg) = @_;
81 my $buf = _mbox_hdr_buf($eml, 'mboxrd', $smsg);
82 if (my $bdy = delete $eml->{bdy}) {
83 $$bdy =~ s/^(>*From )/>$1/gm;
84 $$buf .= $eml->{crlf};
85 substr($$bdy, 0, 0, $$buf); # prepend header
88 $$buf .= $eml->{crlf};
93 my ($eml, $smsg) = @_;
94 my $buf = _mbox_hdr_buf($eml, 'mboxo', $smsg);
95 if (my $bdy = delete $eml->{bdy}) {
96 $$bdy =~ s/^From />From /gm;
97 $$buf .= $eml->{crlf};
98 substr($$bdy, 0, 0, $$buf); # prepend header
101 $$buf .= $eml->{crlf};
105 sub _mboxcl_common ($$$) {
106 my ($buf, $bdy, $crlf) = @_;
107 # add Lines: so mutt won't have to add it on MUA close
108 my $lines = $$bdy =~ tr!\n!\n!;
109 $$buf .= 'Content-Length: '.length($$bdy).$crlf.
110 'Lines: '.$lines.$crlf.$crlf;
111 substr($$bdy, 0, 0, $$buf); # prepend header
115 # mboxcl still escapes "From " lines
117 my ($eml, $smsg) = @_;
118 my $buf = _mbox_hdr_buf($eml, 'mboxcl', $smsg);
119 my $crlf = $eml->{crlf};
120 if (my $bdy = delete $eml->{bdy}) {
121 $$bdy =~ s/^From />From /gm;
122 _mboxcl_common($buf, $bdy, $crlf);
128 # mboxcl2 has no "From " escaping
130 my ($eml, $smsg) = @_;
131 my $buf = _mbox_hdr_buf($eml, 'mboxcl2', $smsg);
132 my $crlf = $eml->{crlf};
133 if (my $bdy = delete $eml->{bdy}) {
134 _mboxcl_common($buf, $bdy, $crlf);
140 sub git_to_mail { # git->cat_async callback
141 my ($bref, $oid, $type, $size, $arg) = @_;
142 if ($type ne 'blob') {
143 if ($type eq 'missing') {
144 warn "missing $oid\n";
146 warn "unexpected type=$type for $oid\n";
149 my ($write_cb, $smsg) = @$arg;
150 if ($smsg->{blob} ne $oid) {
151 die "BUG: expected=$smsg->{blob} got=$oid";
153 $write_cb->($bref, $smsg) if $size > 0;
156 sub reap_compress { # dwaitpid callback
157 my ($lei, $pid) = @_;
158 my $cmd = delete $lei->{"pid.$pid"};
160 $lei->fail("@$cmd failed", $? >> 8);
163 sub _post_augment_mbox { # open a compressor process
164 my ($self, $lei) = @_;
165 my $zsfx = $self->{zsfx} or return;
166 my $cmd = PublicInbox::MboxReader::zsfx2cmd($zsfx, undef, $lei);
167 my ($r, $w) = @{delete $lei->{zpipe}};
168 my $rdr = { 0 => $r, 1 => $lei->{1}, 2 => $lei->{2} };
169 my $pid = spawn($cmd, undef, $rdr);
171 my $dup = bless { "pid.$pid" => $cmd }, ref($lei);
172 $dup->{$_} = $lei->{$_} for qw(2 sock);
173 tie *$pp, 'PublicInbox::ProcessPipe', $pid, $w, \&reap_compress, $dup;
179 open my $dup, '+>>&', $in or die "dup: $!";
183 # --augment existing output destination, with deduplication
184 sub _augment { # MboxReader eml_cb
185 my ($eml, $lei) = @_;
186 # ignore return value, just populate the skv
187 $lei->{dedupe}->is_dup($eml);
190 sub _mbox_augment_kw_maybe {
191 my ($eml, $lei, $lse, $augment) = @_;
192 my $kw = PublicInbox::MboxReader::mbox_keywords($eml);
193 update_kw_maybe($lei, $lse, $eml, $kw);
194 _augment($eml, $lei) if $augment;
197 sub _mbox_write_cb ($$) {
198 my ($self, $lei) = @_;
199 my $ovv = $lei->{ovv};
200 my $m = 'eml2'.$ovv->{fmt};
201 my $eml2mbox = $self->can($m) or die "$self->$m missing";
202 $lei->{1} // die "no stdout ($m, $ovv->{dst})"; # redirected earlier
203 $lei->{1}->autoflush(1);
204 my $atomic_append = !defined($ovv->{lock_path});
205 my $dedupe = $lei->{dedupe};
206 $dedupe->prepare_dedupe;
207 my $lse = $lei->{lse}; # may be undef
208 sub { # for git_to_mail
209 my ($buf, $smsg, $eml) = @_;
210 $eml //= PublicInbox::Eml->new($buf);
211 return if $dedupe->is_dup($eml, $smsg->{blob});
212 $lse->xsmsg_vmd($smsg) if $lse;
213 $buf = $eml2mbox->($eml, $smsg);
214 return atomic_append($lei, $buf) if $atomic_append;
215 my $lk = $ovv->lock_for_scope;
220 sub update_kw_maybe ($$$$) {
221 my ($lei, $lse, $eml, $kw) = @_;
223 my $c = $lse->kw_changed($eml, $kw, my $docids = []);
224 my $vmd = { kw => $kw };
225 if (scalar @$docids) { # already in lei/store
226 $lei->{sto}->ipc_do('set_eml_vmd', undef, $vmd, $docids) if $c;
227 } elsif (my $xoids = $lei->{ale}->xoids_for($eml)) {
228 # it's in an external, only set kw, here
229 $lei->{sto}->ipc_do('set_xvmd', $xoids, $eml, $vmd);
230 } else { # never-before-seen, import the whole thing
231 # XXX this is critical in protecting against accidental
232 # data loss without --augment
233 $lei->{sto}->ipc_do('set_eml', $eml, $vmd);
237 sub _augment_or_unlink { # maildir_each_eml cb
238 my ($f, $kw, $eml, $lei, $lse, $mod, $shard, $unlink) = @_;
240 # can't get dirent.d_ino w/ pure Perl readdir, so we extract
241 # the OID if it looks like one instead of doing stat(2)
242 my $hex = $f =~ m!\b([a-f0-9]{40,})[^/]*\z! ?
244 my $recno = hex(substr($hex, 0, 8));
245 return if ($recno % $mod) != $shard;
246 update_kw_maybe($lei, $lse, $eml, $kw);
248 $unlink ? unlink($f) : _augment($eml, $lei);
251 # maildir_each_file callback, \&CORE::unlink doesn't work with it
252 sub _unlink { unlink($_[0]) }
256 sprintf('%x,%x,%x,%x', rand(0xffffffff), time, $$, ++$seq);
260 my ($dst, $buf, $smsg) = @_;
261 my $kw = $smsg->{kw} // [];
262 my $sfx = join('', sort(map { $kw2char{$_} // () } @$kw));
263 my $rand = ''; # chosen by die roll :P
264 my ($tmp, $fh, $final, $ok);
265 my $common = $smsg->{blob} // _rand;
266 if (defined(my $pct = $smsg->{pct})) { $common .= "=$pct" }
268 $tmp = $dst.'tmp/'.$rand.$common;
269 } while (!($ok = sysopen($fh, $tmp, O_CREAT|O_EXCL|O_WRONLY)) &&
270 $!{EEXIST} && ($rand = _rand.','));
271 if ($ok && print $fh $$buf and close($fh)) {
272 # ignore new/ and write only to cur/, otherwise MUAs
273 # with R/W access to the Maildir will end up doing
274 # a mass rename which can take a while with thousands
279 $final = $dst.$rand.$common.':2,'.$sfx;
280 } while (!($ok = link($tmp, $final)) && $!{EEXIST} &&
281 ($rand = _rand.','));
282 die "link($tmp, $final): $!" unless $ok;
283 unlink($tmp) or warn "W: failed to unlink $tmp: $!\n";
285 my $err = "Error writing $smsg->{blob} to $dst: $!\n";
286 $_[0] = undef; # clobber dst
292 sub _maildir_write_cb ($$) {
293 my ($self, $lei) = @_;
294 my $dedupe = $lei->{dedupe};
295 $dedupe->prepare_dedupe if $dedupe;
296 my $dst = $lei->{ovv}->{dst};
297 my $lse = $lei->{lse}; # may be undef
298 sub { # for git_to_mail
299 my ($buf, $smsg, $eml) = @_;
300 $dst // return $lei->fail; # dst may be undef-ed in last run
301 $buf //= \($eml->as_string);
302 $lse->xsmsg_vmd($smsg) if $lse;
303 return _buf2maildir($dst, $buf, $smsg) if !$dedupe;
304 $eml //= PublicInbox::Eml->new($$buf); # copy buf
305 return if $dedupe->is_dup($eml, $smsg->{blob});
307 _buf2maildir($dst, $buf, $smsg);
311 sub _imap_write_cb ($$) {
312 my ($self, $lei) = @_;
313 my $dedupe = $lei->{dedupe};
314 $dedupe->prepare_dedupe if $dedupe;
315 my $imap_append = $lei->{net}->can('imap_append');
316 my $mic = $lei->{net}->mic_get($self->{uri});
317 my $folder = $self->{uri}->mailbox;
318 my $lse = $lei->{lse}; # may be undef
319 sub { # for git_to_mail
320 my ($bref, $smsg, $eml) = @_;
321 $mic // return $lei->fail; # dst may be undef-ed in last run
323 $eml //= PublicInbox::Eml->new($$bref); # copy bref
324 return if $dedupe->is_dup($eml, $smsg->{blob});
326 $lse->xsmsg_vmd($smsg) if $lse;
327 eval { $imap_append->($mic, $folder, $bref, $smsg, $eml) };
335 sub write_cb { # returns a callback for git_to_mail
336 my ($self, $lei) = @_;
337 # _mbox_write_cb, _maildir_write_cb or _imap_write_cb
338 my $m = "_$self->{base_type}_write_cb";
343 my ($cls, $lei) = @_;
344 my $fmt = $lei->{ovv}->{fmt};
345 my $dst = $lei->{ovv}->{dst};
346 my $self = bless {}, $cls;
347 if ($fmt eq 'maildir') {
348 require PublicInbox::MdirReader;
349 $self->{base_type} = 'maildir';
350 -e $dst && !-d _ and die
351 "$dst exists and is not a directory\n";
352 $lei->{ovv}->{dst} = $dst .= '/' if substr($dst, -1) ne '/';
353 } elsif (substr($fmt, 0, 4) eq 'mbox') {
354 require PublicInbox::MboxReader;
355 (-d $dst || (-e _ && !-w _)) and die
356 "$dst exists and is not a writable file\n";
357 $self->can("eml2$fmt") or die "bad mbox format: $fmt\n";
358 $self->{base_type} = 'mbox';
359 } elsif ($fmt =~ /\Aimaps?\z/) { # TODO .onion support
360 require PublicInbox::NetWriter;
361 my $net = PublicInbox::NetWriter->new;
363 $net->{quiet} = $lei->{opt}->{quiet};
364 my $err = $net->errors($dst);
365 return $lei->fail($err) if $err;
366 require PublicInbox::URIimap; # TODO: URI cast early
367 $self->{uri} = PublicInbox::URIimap->new($dst);
368 $self->{uri}->mailbox or die "No mailbox: $dst";
370 $self->{base_type} = 'imap';
372 die "bad mail --format=$fmt\n";
375 $lei->{dedupe} = PublicInbox::LeiDedupe->new($lei);
379 sub _pre_augment_maildir {
380 my ($self, $lei) = @_;
381 my $dst = $lei->{ovv}->{dst};
382 for my $x (qw(tmp new cur)) {
386 File::Path::mkpath($d);
387 -d $d or die "$d is not a directory";
391 sub _do_augment_maildir {
392 my ($self, $lei) = @_;
393 my $dst = $lei->{ovv}->{dst};
394 my $lse = $lei->{opt}->{'import-before'} ? $lei->{lse} : undef;
395 my ($mod, $shard) = @{$self->{shard_info} // []};
396 if ($lei->{opt}->{augment}) {
397 my $dedupe = $lei->{dedupe};
398 if ($dedupe && $dedupe->prepare_dedupe) {
399 PublicInbox::MdirReader::maildir_each_eml($dst,
400 \&_augment_or_unlink,
401 $lei, $lse, $mod, $shard);
402 $dedupe->pause_dedupe;
405 PublicInbox::MdirReader::maildir_each_eml($dst,
406 \&_augment_or_unlink,
407 $lei, $lse, $mod, $shard, 1);
408 } else {# clobber existing Maildir
409 PublicInbox::MdirReader::maildir_each_file($dst, \&_unlink);
413 sub _imap_augment_or_delete { # PublicInbox::NetReader::imap_each cb
414 my ($url, $uid, $kw, $eml, $lei, $lse, $delete_mic) = @_;
415 update_kw_maybe($lei, $lse, $eml, $kw);
417 $lei->{net}->imap_delete_1($url, $uid, $delete_mic);
419 _augment($eml, $lei);
423 sub _do_augment_imap {
424 my ($self, $lei) = @_;
425 my $net = $lei->{net};
426 my $lse = $lei->{opt}->{'import-before'} ? $lei->{lse} : undef;
427 if ($lei->{opt}->{augment}) {
428 my $dedupe = $lei->{dedupe};
429 if ($dedupe && $dedupe->prepare_dedupe) {
430 $net->imap_each($self->{uri}, \&_imap_augment_or_delete,
432 $dedupe->pause_dedupe;
436 $net->imap_each($self->{uri}, \&_imap_augment_or_delete,
437 $lei, $lse, \$delete_mic);
438 $delete_mic->expunge if $delete_mic;
439 } elsif (!$self->{-wq_worker_nr}) { # undef or 0
440 # clobber existing IMAP folder
441 $net->imap_delete_all($self->{uri});
445 sub _pre_augment_mbox {
446 my ($self, $lei) = @_;
447 my $dst = $lei->{ovv}->{dst};
449 my $devfd = $lei->path_to_fd($dst) // die "bad $dst";
451 $out = $lei->{$devfd};
452 } else { # normal-looking path
454 open $out, '>', $dst or die "open($dst): $!";
455 } elsif (-f _ || !-e _) {
456 require PublicInbox::MboxLock;
457 my $m = $lei->{opt}->{'lock'} //
458 PublicInbox::MboxLock->defaults;
459 $self->{mbl} = PublicInbox::MboxLock->acq($dst, 1, $m);
460 $out = $self->{mbl}->{fh};
462 die "$dst is not a file or FIFO\n";
464 $lei->{old_1} = $lei->{1}; # keep for spawning MUA
466 # Perl does SEEK_END even with O_APPEND :<
467 $self->{seekable} = seek($out, 0, SEEK_SET);
468 if (!$self->{seekable} && !$!{ESPIPE} && !defined($devfd)) {
469 die "seek($dst): $!\n";
471 if (!$self->{seekable}) {
472 my $imp_before = $lei->{opt}->{'import-before'};
473 die "--import-before specified but $dst is not seekable\n"
474 if $imp_before && !ref($imp_before);
475 die "--augment specified but $dst is not seekable\n" if
476 $lei->{opt}->{augment};
478 if ($self->{zsfx} = PublicInbox::MboxReader::zsfx($dst)) {
479 pipe(my ($r, $w)) or die "pipe: $!";
480 $lei->{zpipe} = [ $r, $w ];
481 $lei->{ovv}->{lock_path} and
482 die 'BUG: unexpected {ovv}->{lock_path}';
483 $lei->{ovv}->ovv_out_lk_init;
484 } elsif (!$self->{seekable} && !$lei->{ovv}->{lock_path}) {
485 $lei->{ovv}->ovv_out_lk_init;
491 sub _do_augment_mbox {
492 my ($self, $lei) = @_;
493 return unless $self->{seekable};
494 my $opt = $lei->{opt};
496 my ($fmt, $dst) = @{$lei->{ovv}}{qw(fmt dst)};
497 return unless -s $out;
498 unless ($opt->{augment} || $opt->{'import-before'}) {
499 truncate($out, 0) or die "truncate($dst): $!";
502 my $zsfx = $self->{zsfx};
503 my $rd = $zsfx ? PublicInbox::MboxReader::zsfxcat($out, $zsfx, $lei)
506 if ($opt->{augment}) {
507 $dedupe = $lei->{dedupe};
508 $dedupe->prepare_dedupe if $dedupe;
510 if ($opt->{'import-before'}) { # the default
511 my $lse = $lei->{lse};
512 PublicInbox::MboxReader->$fmt($rd, \&_mbox_augment_kw_maybe,
513 $lei, $lse, $opt->{augment});
514 if (!$opt->{augment} and !truncate($out, 0)) {
515 die "truncate($dst): $!";
517 } else { # --augment --no-import-before
518 PublicInbox::MboxReader->$fmt($rd, \&_augment, $lei);
520 # maybe some systems don't honor O_APPEND, Perl does this:
521 seek($out, 0, SEEK_END) or die "seek $dst: $!";
522 $dedupe->pause_dedupe if $dedupe;
525 sub pre_augment { # fast (1 disk seek), runs in same process as post_augment
526 my ($self, $lei) = @_;
527 # _pre_augment_maildir, _pre_augment_mbox
528 my $m = $self->can("_pre_augment_$self->{base_type}") or return;
532 sub do_augment { # slow, runs in wq worker
533 my ($self, $lei) = @_;
534 # _do_augment_maildir, _do_augment_mbox, or _do_augment_imap
535 my $m = "_do_augment_$self->{base_type}";
539 # fast (spawn compressor or mkdir), runs in same process as pre_augment
541 my ($self, $lei, @args) = @_;
542 my $wait = $lei->{opt}->{'import-before'} ?
543 $lei->{sto}->ipc_do('checkpoint', 1) : 0;
545 my $m = $self->can("_post_augment_$self->{base_type}") or return;
546 $m->($self, $lei, @args);
551 my $lei = $self->{lei};
552 # lei_xsearch can start as soon as all l2m workers get here
553 pkt_do($lei->{pkt_op_p}, 'incr_start_query') or
554 die "incr_start_query: $!";
556 if (lock_free($self)) {
557 my $mod = $self->{-wq_nr_workers};
558 my $shard = $self->{-wq_worker_nr};
559 if (my $net = $lei->{net}) {
560 $net->{shard_info} = [ $mod, $shard ];
562 $self->{shard_info} = [ $mod, $shard ];
564 $aug = '+'; # incr_post_augment
565 } elsif ($self->{-wq_worker_nr} == 0) {
566 $aug = '.'; # do_post_augment
569 local $0 = 'do_augment';
570 eval { do_augment($self, $lei) };
571 $lei->fail($@) if $@;
572 pkt_do($lei->{pkt_op_p}, $aug) == 1 or
573 die "do_post_augment trigger: $!";
575 if (my $zpipe = delete $lei->{zpipe}) {
576 $lei->{1} = $zpipe->[1];
579 $self->{wcb} = $self->write_cb($lei);
582 sub ipc_atfork_child {
584 my $lei = $self->{lei};
585 $lei->_lei_atfork_child;
586 $lei->{auth}->do_auth_atfork($self) if $lei->{auth};
587 $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb();
588 $self->SUPER::ipc_atfork_child;
592 $_[0]->{base_type} =~ /\A(?:maildir|imap|jmap)\z/ ? 1 : 0;
597 if ($self->{base_type} eq 'maildir') {
599 utime($t, $t, $self->{dst} . 'cur');
603 sub write_mail { # via ->wq_io_do
604 my ($self, $smsg) = @_;
605 $self->{lei}->{ale}->git->cat_async($smsg->{blob}, \&git_to_mail,
606 [$self->{wcb}, $smsg]);
609 sub wq_atexit_child {
612 $self->{lei}->{ale}->git->async_wait_all;
613 $SIG{__WARN__} = 'DEFAULT';
616 # called in top-level lei-daemon when LeiAuth is done
617 sub net_merge_complete {
619 $self->wq_broadcast('do_post_auth');
623 no warnings 'once'; # the following works even when LeiAuth is lazy-loaded
624 *net_merge_all = \&PublicInbox::LeiAuth::net_merge_all;