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::Lock;
11 use PublicInbox::ProcessPipe;
12 use PublicInbox::Spawn qw(which spawn popen_rd);
13 use PublicInbox::LeiDedupe;
14 use PublicInbox::GitAsyncCat;
15 use PublicInbox::PktOp qw(pkt_do);
16 use Symbol qw(gensym);
17 use IO::Handle; # ->autoflush
18 use Fcntl qw(SEEK_SET SEEK_END O_CREAT O_EXCL O_WRONLY);
19 use Errno qw(EEXIST ESPIPE ENOENT EPIPE);
20 use Digest::SHA qw(sha256_hex);
22 # struggles with short-lived repos, Gcf2Client makes little sense with lei;
23 # but we may use in-process libgit2 in the future.
24 $PublicInbox::GitAsyncCat::GCF2C = 0;
26 my %kw2char = ( # Maildir characters
34 flagged => [ 'X-Status' => 'F' ],
35 answered => [ 'X-Status' => 'A' ],
36 seen => [ 'Status' => 'R' ],
37 draft => [ 'X-Status' => 'T' ],
40 sub _mbox_hdr_buf ($$$) {
41 my ($eml, $type, $smsg) = @_;
42 $eml->header_set($_) for (qw(Lines Bytes Content-Length));
44 # Messages are always 'O' (non-\Recent in IMAP), it saves
45 # MUAs the trouble of rewriting the mbox if no other
47 my %hdr = (Status => [ 'O' ]); # set Status, X-Status
48 for my $k (@{$smsg->{kw} // []}) {
49 if (my $ent = $kw2status{$k}) {
50 push @{$hdr{$ent->[0]}}, $ent->[1];
52 warn "TODO: keyword `$k' not supported for mbox\n";
55 while (my ($name, $chars) = each %hdr) {
56 $eml->header_set($name, join('', sort @$chars));
58 my $buf = delete $eml->{hdr};
60 # fixup old bug from import (pre-a0c07cba0e5d8b6a)
61 $$buf =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
62 my $ident = $smsg->{blob} // 'lei';
63 if (defined(my $pct = $smsg->{pct})) { $ident .= "=$pct" }
65 substr($$buf, 0, 0, # prepend From line
66 "From $ident\@$type Thu Jan 1 00:00:00 1970$eml->{crlf}");
70 sub atomic_append { # for on-disk destinations (O_APPEND, or O_EXCL)
72 if (defined(my $w = syswrite($lei->{1} // return, $$buf))) {
73 return if $w == length($$buf);
74 $buf = "short atomic write: $w != ".length($$buf);
75 } elsif ($! == EPIPE) {
76 return $lei->note_sigpipe(1);
78 $buf = "atomic write: $!";
83 sub eml2mboxrd ($;$) {
84 my ($eml, $smsg) = @_;
85 my $buf = _mbox_hdr_buf($eml, 'mboxrd', $smsg);
86 if (my $bdy = delete $eml->{bdy}) {
87 $$bdy =~ s/^(>*From )/>$1/gm;
88 $$buf .= $eml->{crlf};
89 substr($$bdy, 0, 0, $$buf); # prepend header
92 $$buf .= $eml->{crlf};
97 my ($eml, $smsg) = @_;
98 my $buf = _mbox_hdr_buf($eml, 'mboxo', $smsg);
99 if (my $bdy = delete $eml->{bdy}) {
100 $$bdy =~ s/^From />From /gm;
101 $$buf .= $eml->{crlf};
102 substr($$bdy, 0, 0, $$buf); # prepend header
105 $$buf .= $eml->{crlf};
109 sub _mboxcl_common ($$$) {
110 my ($buf, $bdy, $crlf) = @_;
111 # add Lines: so mutt won't have to add it on MUA close
112 my $lines = $$bdy =~ tr!\n!\n!;
113 $$buf .= 'Content-Length: '.length($$bdy).$crlf.
114 'Lines: '.$lines.$crlf.$crlf;
115 substr($$bdy, 0, 0, $$buf); # prepend header
119 # mboxcl still escapes "From " lines
121 my ($eml, $smsg) = @_;
122 my $buf = _mbox_hdr_buf($eml, 'mboxcl', $smsg);
123 my $crlf = $eml->{crlf};
124 if (my $bdy = delete $eml->{bdy}) {
125 $$bdy =~ s/^From />From /gm;
126 _mboxcl_common($buf, $bdy, $crlf);
132 # mboxcl2 has no "From " escaping
134 my ($eml, $smsg) = @_;
135 my $buf = _mbox_hdr_buf($eml, 'mboxcl2', $smsg);
136 my $crlf = $eml->{crlf};
137 if (my $bdy = delete $eml->{bdy}) {
138 _mboxcl_common($buf, $bdy, $crlf);
144 sub git_to_mail { # git->cat_async callback
145 my ($bref, $oid, $type, $size, $arg) = @_;
146 if ($type ne 'blob') {
147 if ($type eq 'missing') {
148 warn "missing $oid\n";
150 warn "unexpected type=$type for $oid\n";
153 my ($write_cb, $smsg) = @$arg;
154 if ($smsg->{blob} ne $oid) {
155 die "BUG: expected=$smsg->{blob} got=$oid";
157 $write_cb->($bref, $smsg) if $size > 0;
160 sub reap_compress { # dwaitpid callback
161 my ($lei, $pid) = @_;
162 my $cmd = delete $lei->{"pid.$pid"};
164 $lei->fail("@$cmd failed", $? >> 8);
167 # all of these support -c for stdout and -d for decompression,
168 # mutt is commonly distributed with hooks for gz, bz2 and xz, at least
169 # { foo => '' } means "--foo" is passed to the command-line,
170 # otherwise { foo => '--bar' } passes "--bar"
172 gz => [ qw(GZIP pigz gzip), { rsyncable => '' } ],
173 bz2 => [ 'bzip2', {} ],
175 # XXX does anybody care for these? I prefer zstd on entire FSes,
176 # so it's probably not necessary on a per-file basis
177 # zst => [ 'zstd', { -default => [ qw(-q) ], # it's noisy by default
178 # rsyncable => '', threads => '-T' } ],
179 # zz => [ 'pigz', { -default => [ '--zlib' ],
180 # rsyncable => '', threads => '-p' }],
181 # lzo => [ 'lzop', {} ],
182 # lzma => [ 'lzma', {} ],
186 my ($zsfx, $decompress, $lei) = @_;
187 my $x = $zsfx2cmd{$zsfx} // die "no support for suffix=.$zsfx";
189 my $cmd_opt = pop @info;
190 my @cmd = (undef, $decompress ? qw(-dc) : qw(-c));
191 for my $exe (@info) {
192 # I think respecting client's ENV{GZIP} is OK, not sure
193 # about ENV overrides for other, less-common compressors
194 if ($exe eq uc($exe)) {
195 $exe = $lei->{env}->{$exe} or next;
197 $cmd[0] = which($exe) and last;
199 $cmd[0] // die join(' or ', @info)." missing for .$zsfx";
200 # push @cmd, @{$cmd_opt->{-default}} if $cmd_opt->{-default};
201 for my $bool (qw(rsyncable)) {
202 my $switch = $cmd_opt->{rsyncable} // next;
203 push @cmd, '--'.($switch || $bool);
205 for my $key (qw(rsyncable)) { # support compression level?
206 my $switch = $cmd_opt->{$key} // next;
207 my $val = $lei->{opt}->{$key} // next;
208 push @cmd, $switch, $val;
213 sub _post_augment_mbox { # open a compressor process
214 my ($self, $lei) = @_;
215 my $zsfx = $self->{zsfx} or return;
216 my $cmd = zsfx2cmd($zsfx, undef, $lei);
217 my ($r, $w) = @{delete $lei->{zpipe}};
218 my $rdr = { 0 => $r, 1 => $lei->{1}, 2 => $lei->{2} };
219 my $pid = spawn($cmd, undef, $rdr);
221 my $dup = bless { "pid.$pid" => $cmd }, ref($lei);
222 $dup->{$_} = $lei->{$_} for qw(2 sock);
223 tie *$pp, 'PublicInbox::ProcessPipe', $pid, $w, \&reap_compress, $dup;
227 sub decompress_src ($$$) {
228 my ($in, $zsfx, $lei) = @_;
229 my $cmd = zsfx2cmd($zsfx, 1, $lei);
230 popen_rd($cmd, undef, { 0 => $in, 2 => $lei->{2} });
235 open my $dup, '+>>&', $in or die "dup: $!";
239 # --augment existing output destination, with deduplication
240 sub _augment { # MboxReader eml_cb
241 my ($eml, $lei) = @_;
242 # ignore return value, just populate the skv
243 $lei->{dedupe}->is_dup($eml);
246 sub _mbox_augment_kw_maybe {
247 my ($eml, $lei, $lse, $augment) = @_;
248 my $kw = PublicInbox::MboxReader::mbox_keywords($eml);
249 update_kw_maybe($lei, $lse, $eml, $kw);
250 _augment($eml, $lei) if $augment;
253 sub _mbox_write_cb ($$) {
254 my ($self, $lei) = @_;
255 my $ovv = $lei->{ovv};
256 my $m = 'eml2'.$ovv->{fmt};
257 my $eml2mbox = $self->can($m) or die "$self->$m missing";
258 $lei->{1} // die "no stdout ($m, $ovv->{dst})"; # redirected earlier
259 $lei->{1}->autoflush(1);
260 my $atomic_append = !defined($ovv->{lock_path});
261 my $dedupe = $lei->{dedupe};
262 $dedupe->prepare_dedupe;
263 sub { # for git_to_mail
264 my ($buf, $smsg, $eml) = @_;
265 $eml //= PublicInbox::Eml->new($buf);
266 return if $dedupe->is_dup($eml, $smsg->{blob});
267 $buf = $eml2mbox->($eml, $smsg);
268 return atomic_append($lei, $buf) if $atomic_append;
269 my $lk = $ovv->lock_for_scope;
274 sub update_kw_maybe ($$$$) {
275 my ($lei, $lse, $eml, $kw) = @_;
277 my $x = $lse->kw_changed($eml, $kw);
279 $lei->{sto}->ipc_do('set_eml', $eml, { kw => $kw });
280 } elsif (!defined($x)) {
281 $lei->{sto}->ipc_do('set_xkw', $eml, $kw);
285 sub _augment_or_unlink { # maildir_each_eml cb
286 my ($f, $kw, $eml, $lei, $lse, $mod, $shard, $unlink) = @_;
288 # can't get dirent.d_ino w/ pure Perl, so we extract the OID
289 # if it looks like one:
290 my $hex = $f =~ m!\b([a-f0-9]{40,})[^/]*\z! ?
292 my $recno = hex(substr($hex, 0, 8));
293 return if ($recno % $mod) != $shard;
294 update_kw_maybe($lei, $lse, $eml, $kw);
296 $unlink ? unlink($f) : _augment($eml, $lei);
299 # maildir_each_file callback, \&CORE::unlink doesn't work with it
300 sub _unlink { unlink($_[0]) }
304 sprintf('%x,%x,%x,%x', rand(0xffffffff), time, $$, ++$seq);
308 my ($dst, $buf, $smsg) = @_;
309 my $kw = $smsg->{kw} // [];
310 my $sfx = join('', sort(map { $kw2char{$_} // () } @$kw));
311 my $rand = ''; # chosen by die roll :P
312 my ($tmp, $fh, $final, $ok);
313 my $common = $smsg->{blob} // _rand;
314 if (defined(my $pct = $smsg->{pct})) { $common .= "=$pct" }
316 $tmp = $dst.'tmp/'.$rand.$common;
317 } while (!($ok = sysopen($fh, $tmp, O_CREAT|O_EXCL|O_WRONLY)) &&
318 $! == EEXIST && ($rand = _rand.','));
319 if ($ok && print $fh $$buf and close($fh)) {
320 # ignore new/ and write only to cur/, otherwise MUAs
321 # with R/W access to the Maildir will end up doing
322 # a mass rename which can take a while with thousands
327 $final = $dst.$rand.$common.':2,'.$sfx;
328 } while (!($ok = link($tmp, $final)) && $! == EEXIST &&
329 ($rand = _rand.','));
330 die "link($tmp, $final): $!" unless $ok;
331 unlink($tmp) or warn "W: failed to unlink $tmp: $!\n";
333 my $err = "Error writing $smsg->{blob} to $dst: $!\n";
334 $_[0] = undef; # clobber dst
340 sub _maildir_write_cb ($$) {
341 my ($self, $lei) = @_;
342 my $dedupe = $lei->{dedupe};
343 $dedupe->prepare_dedupe if $dedupe;
344 my $dst = $lei->{ovv}->{dst};
345 sub { # for git_to_mail
346 my ($buf, $smsg, $eml) = @_;
347 $dst // return $lei->fail; # dst may be undef-ed in last run
348 $buf //= \($eml->as_string);
349 return _buf2maildir($dst, $buf, $smsg) if !$dedupe;
350 $eml //= PublicInbox::Eml->new($$buf); # copy buf
351 return if $dedupe->is_dup($eml, $smsg->{blob});
353 _buf2maildir($dst, $buf, $smsg);
357 sub _imap_write_cb ($$) {
358 my ($self, $lei) = @_;
359 my $dedupe = $lei->{dedupe};
360 $dedupe->prepare_dedupe if $dedupe;
361 my $imap_append = $lei->{net}->can('imap_append');
362 my $mic = $lei->{net}->mic_get($self->{uri});
363 my $folder = $self->{uri}->mailbox;
364 sub { # for git_to_mail
365 my ($bref, $smsg, $eml) = @_;
366 $mic // return $lei->fail; # dst may be undef-ed in last run
368 $eml //= PublicInbox::Eml->new($$bref); # copy bref
369 return if $dedupe->is_dup($eml, $smsg->{blob});
371 eval { $imap_append->($mic, $folder, $bref, $smsg, $eml) };
379 sub write_cb { # returns a callback for git_to_mail
380 my ($self, $lei) = @_;
381 # _mbox_write_cb, _maildir_write_cb or _imap_write_cb
382 my $m = "_$self->{base_type}_write_cb";
387 my ($cls, $lei) = @_;
388 my $fmt = $lei->{ovv}->{fmt};
389 my $dst = $lei->{ovv}->{dst};
390 my $self = bless {}, $cls;
391 if ($fmt eq 'maildir') {
392 require PublicInbox::MdirReader;
393 $self->{base_type} = 'maildir';
394 -e $dst && !-d _ and die
395 "$dst exists and is not a directory\n";
396 $lei->{ovv}->{dst} = $dst .= '/' if substr($dst, -1) ne '/';
397 } elsif (substr($fmt, 0, 4) eq 'mbox') {
398 require PublicInbox::MboxReader;
399 (-d $dst || (-e _ && !-w _)) and die
400 "$dst exists and is not a writable file\n";
401 $self->can("eml2$fmt") or die "bad mbox format: $fmt\n";
402 $self->{base_type} = 'mbox';
403 } elsif ($fmt =~ /\Aimaps?\z/) { # TODO .onion support
404 require PublicInbox::NetWriter;
405 my $net = PublicInbox::NetWriter->new;
407 $net->{quiet} = $lei->{opt}->{quiet};
408 my $err = $net->errors($dst);
409 return $lei->fail($err) if $err;
410 require PublicInbox::URIimap; # TODO: URI cast early
411 $self->{uri} = PublicInbox::URIimap->new($dst);
412 $self->{uri}->mailbox or die "No mailbox: $dst";
414 $self->{base_type} = 'imap';
416 die "bad mail --format=$fmt\n";
419 $lei->{dedupe} = PublicInbox::LeiDedupe->new($lei);
423 sub _pre_augment_maildir {
424 my ($self, $lei) = @_;
425 my $dst = $lei->{ovv}->{dst};
426 for my $x (qw(tmp new cur)) {
430 File::Path::mkpath($d);
431 -d $d or die "$d is not a directory";
435 sub _do_augment_maildir {
436 my ($self, $lei) = @_;
437 my $dst = $lei->{ovv}->{dst};
438 my $lse = $lei->{sto}->search if $lei->{opt}->{'import-before'};
439 my ($mod, $shard) = @{$self->{shard_info} // []};
440 if ($lei->{opt}->{augment}) {
441 my $dedupe = $lei->{dedupe};
442 if ($dedupe && $dedupe->prepare_dedupe) {
443 PublicInbox::MdirReader::maildir_each_eml($dst,
444 \&_augment_or_unlink,
445 $lei, $lse, $mod, $shard);
446 $dedupe->pause_dedupe;
449 PublicInbox::MdirReader::maildir_each_eml($dst,
450 \&_augment_or_unlink,
451 $lei, $lse, $mod, $shard, 1);
452 } else {# clobber existing Maildir
453 PublicInbox::MdirReader::maildir_each_file($dst, \&_unlink);
457 sub _imap_augment_or_delete { # PublicInbox::NetReader::imap_each cb
458 my ($url, $uid, $kw, $eml, $lei, $lse, $delete_mic) = @_;
459 update_kw_maybe($lei, $lse, $eml, $kw);
461 $lei->{net}->imap_delete_1($url, $uid, $delete_mic);
463 _augment($eml, $lei);
467 sub _do_augment_imap {
468 my ($self, $lei) = @_;
469 my $net = $lei->{net};
470 my $lse = $lei->{sto}->search if $lei->{opt}->{'import-before'};
471 if ($lei->{opt}->{augment}) {
472 my $dedupe = $lei->{dedupe};
473 if ($dedupe && $dedupe->prepare_dedupe) {
474 $net->imap_each($self->{uri}, \&_imap_augment_or_delete,
476 $dedupe->pause_dedupe;
480 $net->imap_each($self->{uri}, \&_imap_augment_or_delete,
481 $lei, $lse, \$delete_mic);
482 $delete_mic->expunge if $delete_mic;
483 } elsif (!$self->{-wq_worker_nr}) { # undef or 0
484 # clobber existing IMAP folder
485 $net->imap_delete_all($self->{uri});
489 sub _pre_augment_mbox {
490 my ($self, $lei) = @_;
491 my $dst = $lei->{ovv}->{dst};
493 if ($dst ne '/dev/stdout') {
496 open $out, '>', $dst or die "open($dst): $!";
497 } elsif (-f _ || !-e _) {
498 require PublicInbox::MboxLock;
499 my $m = $lei->{opt}->{'lock'} //
500 PublicInbox::MboxLock->defaults;
501 $self->{mbl} = PublicInbox::MboxLock->acq($dst, 1, $m);
502 $out = $self->{mbl}->{fh};
504 $lei->{old_1} = $lei->{1}; # keep for spawning MUA
506 # Perl does SEEK_END even with O_APPEND :<
507 $self->{seekable} = seek($out, 0, SEEK_SET);
508 if (!$self->{seekable} && $! != ESPIPE && $dst ne '/dev/stdout') {
509 die "seek($dst): $!\n";
511 if (!$self->{seekable}) {
512 my $ia = $lei->{opt}->{'import-before'};
513 die "--import-before specified but $dst is not seekable\n"
515 die "--augment specified but $dst is not seekable\n" if
516 $lei->{opt}->{augment};
518 state $zsfx_allow = join('|', keys %zsfx2cmd);
519 if (($self->{zsfx}) = ($dst =~ /\.($zsfx_allow)\z/)) {
520 pipe(my ($r, $w)) or die "pipe: $!";
521 $lei->{zpipe} = [ $r, $w ];
522 $lei->{ovv}->{lock_path} and
523 die 'BUG: unexpected {ovv}->{lock_path}';
524 $lei->{ovv}->ovv_out_lk_init;
525 } elsif (!$self->{seekable} && !$lei->{ovv}->{lock_path}) {
526 $lei->{ovv}->ovv_out_lk_init;
532 sub _do_augment_mbox {
533 my ($self, $lei) = @_;
534 return unless $self->{seekable};
535 my $opt = $lei->{opt};
537 my ($fmt, $dst) = @{$lei->{ovv}}{qw(fmt dst)};
538 return unless -s $out;
539 unless ($opt->{augment} || $opt->{'import-before'}) {
540 truncate($out, 0) or die "truncate($dst): $!";
543 my $zsfx = $self->{zsfx};
544 my $rd = $zsfx ? decompress_src($out, $zsfx, $lei) : dup_src($out);
546 if ($opt->{augment}) {
547 $dedupe = $lei->{dedupe};
548 $dedupe->prepare_dedupe if $dedupe;
550 if ($opt->{'import-before'}) { # the default
551 my $lse = $lei->{sto}->search;
552 PublicInbox::MboxReader->$fmt($rd, \&_mbox_augment_kw_maybe,
553 $lei, $lse, $opt->{augment});
554 if (!$opt->{augment} and !truncate($out, 0)) {
555 die "truncate($dst): $!";
557 } else { # --augment --no-import-before
558 PublicInbox::MboxReader->$fmt($rd, \&_augment, $lei);
560 # maybe some systems don't honor O_APPEND, Perl does this:
561 seek($out, 0, SEEK_END) or die "seek $dst: $!";
562 $dedupe->pause_dedupe if $dedupe;
565 sub pre_augment { # fast (1 disk seek), runs in same process as post_augment
566 my ($self, $lei) = @_;
567 # _pre_augment_maildir, _pre_augment_mbox
568 my $m = $self->can("_pre_augment_$self->{base_type}") or return;
572 sub do_augment { # slow, runs in wq worker
573 my ($self, $lei) = @_;
574 # _do_augment_maildir, _do_augment_mbox, or _do_augment_imap
575 my $m = "_do_augment_$self->{base_type}";
579 # fast (spawn compressor or mkdir), runs in same process as pre_augment
581 my ($self, $lei, @args) = @_;
582 my $wait = $lei->{opt}->{'import-before'} ?
583 $lei->{sto}->ipc_do('checkpoint', 1) : 0;
585 my $m = $self->can("_post_augment_$self->{base_type}") or return;
586 $m->($self, $lei, @args);
591 my $lei = $self->{lei};
592 # lei_xsearch can start as soon as all l2m workers get here
593 pkt_do($lei->{pkt_op_p}, 'incr_start_query') or
594 die "incr_start_query: $!";
596 if (lock_free($self)) {
597 my $mod = $self->{-wq_nr_workers};
598 my $shard = $self->{-wq_worker_nr};
599 if (my $net = $lei->{net}) {
600 $net->{shard_info} = [ $mod, $shard ];
601 } else { # Maildir (MH?)
602 $self->{shard_info} = [ $mod, $shard ];
604 $aug = '+'; # incr_post_augment
605 } elsif ($self->{-wq_worker_nr} == 0) {
606 $aug = '.'; # do_post_augment
609 local $0 = 'do_augment';
610 eval { do_augment($self, $lei) };
611 $lei->fail($@) if $@;
612 pkt_do($lei->{pkt_op_p}, $aug) == 1 or
613 die "do_post_augment trigger: $!";
615 if (my $zpipe = delete $lei->{zpipe}) {
616 $lei->{1} = $zpipe->[1];
619 $self->{wcb} = $self->write_cb($lei);
622 sub ipc_atfork_child {
624 my $lei = $self->{lei};
625 $lei->lei_atfork_child;
626 $lei->{auth}->do_auth_atfork($self) if $lei->{auth};
627 $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb();
628 $self->SUPER::ipc_atfork_child;
632 $_[0]->{base_type} =~ /\A(?:maildir|mh|imap|jmap)\z/ ? 1 : 0;
637 if ($self->{base_type} eq 'maildir') {
639 utime($t, $t, $self->{dst} . 'cur');
643 sub write_mail { # via ->wq_io_do
644 my ($self, $smsg) = @_;
645 git_async_cat($self->{lei}->{ale}->git, $smsg->{blob}, \&git_to_mail,
646 [$self->{wcb}, $smsg]);
649 sub wq_atexit_child {
652 $self->{lei}->{ale}->git->async_wait_all;
653 $SIG{__WARN__} = 'DEFAULT';
656 # called in top-level lei-daemon when LeiAuth is done
657 sub net_merge_complete {
659 $self->wq_broadcast('do_post_auth');
663 no warnings 'once'; # the following works even when LeiAuth is lazy-loaded
664 *net_merge_all = \&PublicInbox::LeiAuth::net_merge_all;