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::OnDestroy;
16 use PublicInbox::GitAsyncCat;
17 use PublicInbox::PktOp qw(pkt_do);
18 use Symbol qw(gensym);
19 use IO::Handle; # ->autoflush
20 use Fcntl qw(SEEK_SET SEEK_END O_CREAT O_EXCL O_WRONLY);
21 use Errno qw(EEXIST ESPIPE ENOENT EPIPE);
22 my ($maildir_each_file);
24 # struggles with short-lived repos, Gcf2Client makes little sense with lei;
25 # but we may use in-process libgit2 in the future.
26 $PublicInbox::GitAsyncCat::GCF2C = 0;
28 my %kw2char = ( # Maildir characters
36 flagged => [ 'X-Status' => 'F' ],
37 answered => [ 'X-Status' => 'A' ],
38 seen => [ 'Status' => 'R' ],
39 draft => [ 'X-Status' => 'T' ],
42 sub _mbox_hdr_buf ($$$) {
43 my ($eml, $type, $smsg) = @_;
44 $eml->header_set($_) for (qw(Lines Bytes Content-Length));
46 # Messages are always 'O' (non-\Recent in IMAP), it saves
47 # MUAs the trouble of rewriting the mbox if no other
49 my %hdr = (Status => [ 'O' ]); # set Status, X-Status
50 for my $k (@{$smsg->{kw} // []}) {
51 if (my $ent = $kw2status{$k}) {
52 push @{$hdr{$ent->[0]}}, $ent->[1];
54 warn "TODO: keyword `$k' not supported for mbox\n";
57 while (my ($name, $chars) = each %hdr) {
58 $eml->header_set($name, join('', sort @$chars));
60 my $buf = delete $eml->{hdr};
62 # fixup old bug from import (pre-a0c07cba0e5d8b6a)
63 $$buf =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
64 my $ident = $smsg->{blob} // 'lei';
65 if (defined(my $pct = $smsg->{pct})) { $ident .= "=$pct" }
67 substr($$buf, 0, 0, # prepend From line
68 "From $ident\@$type Thu Jan 1 00:00:00 1970$eml->{crlf}");
72 sub atomic_append { # for on-disk destinations (O_APPEND, or O_EXCL)
74 if (defined(my $w = syswrite($lei->{1} // return, $$buf))) {
75 return if $w == length($$buf);
76 $buf = "short atomic write: $w != ".length($$buf);
77 } elsif ($! == EPIPE) {
78 return $lei->note_sigpipe(1);
80 $buf = "atomic write: $!";
85 sub eml2mboxrd ($;$) {
86 my ($eml, $smsg) = @_;
87 my $buf = _mbox_hdr_buf($eml, 'mboxrd', $smsg);
88 if (my $bdy = delete $eml->{bdy}) {
89 $$bdy =~ s/^(>*From )/>$1/gm;
90 $$buf .= $eml->{crlf};
91 substr($$bdy, 0, 0, $$buf); # prepend header
94 $$buf .= $eml->{crlf};
99 my ($eml, $smsg) = @_;
100 my $buf = _mbox_hdr_buf($eml, 'mboxo', $smsg);
101 if (my $bdy = delete $eml->{bdy}) {
102 $$bdy =~ s/^From />From /gm;
103 $$buf .= $eml->{crlf};
104 substr($$bdy, 0, 0, $$buf); # prepend header
107 $$buf .= $eml->{crlf};
111 sub _mboxcl_common ($$$) {
112 my ($buf, $bdy, $crlf) = @_;
113 # add Lines: so mutt won't have to add it on MUA close
114 my $lines = $$bdy =~ tr!\n!\n!;
115 $$buf .= 'Content-Length: '.length($$bdy).$crlf.
116 'Lines: '.$lines.$crlf.$crlf;
117 substr($$bdy, 0, 0, $$buf); # prepend header
121 # mboxcl still escapes "From " lines
123 my ($eml, $smsg) = @_;
124 my $buf = _mbox_hdr_buf($eml, 'mboxcl', $smsg);
125 my $crlf = $eml->{crlf};
126 if (my $bdy = delete $eml->{bdy}) {
127 $$bdy =~ s/^From />From /gm;
128 _mboxcl_common($buf, $bdy, $crlf);
134 # mboxcl2 has no "From " escaping
136 my ($eml, $smsg) = @_;
137 my $buf = _mbox_hdr_buf($eml, 'mboxcl2', $smsg);
138 my $crlf = $eml->{crlf};
139 if (my $bdy = delete $eml->{bdy}) {
140 _mboxcl_common($buf, $bdy, $crlf);
146 sub git_to_mail { # git->cat_async callback
147 my ($bref, $oid, $type, $size, $arg) = @_;
148 if ($type ne 'blob') {
149 if ($type eq 'missing') {
150 warn "missing $oid\n";
152 warn "unexpected type=$type for $oid\n";
155 my ($write_cb, $smsg) = @$arg;
156 if ($smsg->{blob} ne $oid) {
157 die "BUG: expected=$smsg->{blob} got=$oid";
159 $write_cb->($bref, $smsg) if $size > 0;
162 sub reap_compress { # dwaitpid callback
163 my ($lei, $pid) = @_;
164 my $cmd = delete $lei->{"pid.$pid"};
166 $lei->fail("@$cmd failed", $? >> 8);
169 # all of these support -c for stdout and -d for decompression,
170 # mutt is commonly distributed with hooks for gz, bz2 and xz, at least
171 # { foo => '' } means "--foo" is passed to the command-line,
172 # otherwise { foo => '--bar' } passes "--bar"
174 gz => [ qw(GZIP pigz gzip), { rsyncable => '', threads => '-p' } ],
175 bz2 => [ 'bzip2', {} ],
176 xz => [ 'xz', { threads => '-T' } ],
177 # XXX does anybody care for these? I prefer zstd on entire FSes,
178 # so it's probably not necessary on a per-file basis
179 # zst => [ 'zstd', { -default => [ qw(-q) ], # it's noisy by default
180 # rsyncable => '', threads => '-T' } ],
181 # zz => [ 'pigz', { -default => [ '--zlib' ],
182 # rsyncable => '', threads => '-p' }],
183 # lzo => [ 'lzop', {} ],
184 # lzma => [ 'lzma', {} ],
188 my ($zsfx, $decompress, $lei) = @_;
189 my $x = $zsfx2cmd{$zsfx} // die "no support for suffix=.$zsfx";
191 my $cmd_opt = pop @info;
192 my @cmd = (undef, $decompress ? qw(-dc) : qw(-c));
193 for my $exe (@info) {
194 # I think respecting client's ENV{GZIP} is OK, not sure
195 # about ENV overrides for other, less-common compressors
196 if ($exe eq uc($exe)) {
197 $exe = $lei->{env}->{$exe} or next;
199 $cmd[0] = which($exe) and last;
201 $cmd[0] // die join(' or ', @info)." missing for .$zsfx";
202 # push @cmd, @{$cmd_opt->{-default}} if $cmd_opt->{-default};
203 for my $bool (qw(rsyncable)) {
204 my $switch = $cmd_opt->{rsyncable} // next;
205 push @cmd, '--'.($switch || $bool);
207 for my $key (qw(threads)) { # support compression level?
208 my $switch = $cmd_opt->{$key} // next;
209 my $val = $lei->{opt}->{$key} // next;
210 push @cmd, $switch, $val;
215 sub _post_augment_mbox { # open a compressor process
216 my ($self, $lei) = @_;
217 my $zsfx = $self->{zsfx} or return;
218 my $cmd = zsfx2cmd($zsfx, undef, $lei);
219 my ($r, $w) = @{delete $lei->{zpipe}};
220 my $rdr = { 0 => $r, 1 => $lei->{1}, 2 => $lei->{2} };
221 my $pid = spawn($cmd, $lei->{env}, $rdr);
223 my $dup = bless { "pid.$pid" => $cmd }, ref($lei);
224 $dup->{$_} = $lei->{$_} for qw(2 sock);
225 tie *$pp, 'PublicInbox::ProcessPipe', $pid, $w, \&reap_compress, $dup;
227 die 'BUG: unexpected {ovv}->{lock_path}' if $lei->{ovv}->{lock_path};
228 $lei->{ovv}->ovv_out_lk_init;
231 sub decompress_src ($$$) {
232 my ($in, $zsfx, $lei) = @_;
233 my $cmd = zsfx2cmd($zsfx, 1, $lei);
234 popen_rd($cmd, $lei->{env}, { 0 => $in, 2 => $lei->{2} });
239 open my $dup, '+>>&', $in or die "dup: $!";
243 # --augment existing output destination, with deduplication
244 sub _augment { # MboxReader eml_cb
245 my ($eml, $lei) = @_;
246 # ignore return value, just populate the skv
247 $lei->{dedupe}->is_dup($eml);
250 sub _mbox_write_cb ($$) {
251 my ($self, $lei) = @_;
252 my $ovv = $lei->{ovv};
253 my $m = 'eml2'.$ovv->{fmt};
254 my $eml2mbox = $self->can($m) or die "$self->$m missing";
255 $lei->{1} // die "no stdout ($m, $ovv->{dst})"; # redirected earlier
256 $lei->{1}->autoflush(1);
257 my $atomic_append = !defined($ovv->{lock_path});
258 my $dedupe = $lei->{dedupe};
259 $dedupe->prepare_dedupe;
260 sub { # for git_to_mail
261 my ($buf, $smsg, $eml) = @_;
262 $eml //= PublicInbox::Eml->new($buf);
263 return if $dedupe->is_dup($eml, $smsg->{blob});
264 $buf = $eml2mbox->($eml, $smsg);
265 return atomic_append($lei, $buf) if $atomic_append;
266 my $lk = $ovv->lock_for_scope;
271 sub _augment_file { # maildir_each_file cb
273 my $eml = PublicInbox::InboxWritable::eml_from_path($f) or return;
274 _augment($eml, $lei);
277 # maildir_each_file callback, \&CORE::unlink doesn't work with it
278 sub _unlink { unlink($_[0]) }
282 sprintf('%x,%x,%x,%x', rand(0xffffffff), time, $$, ++$seq);
286 my ($dst, $buf, $smsg) = @_;
287 my $kw = $smsg->{kw} // [];
288 my $sfx = join('', sort(map { $kw2char{$_} // () } @$kw));
289 my $rand = ''; # chosen by die roll :P
290 my ($tmp, $fh, $final, $ok);
291 my $common = $smsg->{blob} // _rand;
292 if (defined(my $pct = $smsg->{pct})) { $common .= "=$pct" }
294 $tmp = $dst.'tmp/'.$rand.$common;
295 } while (!($ok = sysopen($fh, $tmp, O_CREAT|O_EXCL|O_WRONLY)) &&
296 $! == EEXIST && ($rand = _rand.','));
297 if ($ok && print $fh $$buf and close($fh)) {
298 # ignore new/ and write only to cur/, otherwise MUAs
299 # with R/W access to the Maildir will end up doing
300 # a mass rename which can take a while with thousands
305 $final = $dst.$rand.$common.':2,'.$sfx;
306 } while (!($ok = link($tmp, $final)) && $! == EEXIST &&
307 ($rand = _rand.','));
308 die "link($tmp, $final): $!" unless $ok;
309 unlink($tmp) or warn "W: failed to unlink $tmp: $!\n";
311 my $err = "Error writing $smsg->{blob} to $dst: $!\n";
312 $_[0] = undef; # clobber dst
318 sub _maildir_write_cb ($$) {
319 my ($self, $lei) = @_;
320 my $dedupe = $lei->{dedupe};
321 $dedupe->prepare_dedupe if $dedupe;
322 my $dst = $lei->{ovv}->{dst};
323 sub { # for git_to_mail
324 my ($buf, $smsg, $eml) = @_;
325 $dst // return $lei->fail; # dst may be undef-ed in last run
326 $buf //= \($eml->as_string);
327 return _buf2maildir($dst, $buf, $smsg) if !$dedupe;
328 $eml //= PublicInbox::Eml->new($$buf); # copy buf
329 return if $dedupe->is_dup($eml, $smsg->{blob});
331 _buf2maildir($dst, $buf, $smsg);
335 sub _imap_write_cb ($$) {
336 my ($self, $lei) = @_;
337 my $dedupe = $lei->{dedupe};
338 $dedupe->prepare_dedupe if $dedupe;
339 my $imap_append = $lei->{nwr}->can('imap_append');
340 my $mic = $lei->{nwr}->mic_get($lei->{ovv}->{dst});
341 my $folder = $self->{uri}->mailbox;
342 sub { # for git_to_mail
343 my ($bref, $smsg, $eml) = @_;
344 $mic // return $lei->fail; # dst may be undef-ed in last run
346 $eml //= PublicInbox::Eml->new($$bref); # copy bref
347 return if $dedupe->is_dup($eml, $smsg->{blob});
349 eval { $imap_append->($mic, $folder, $bref, $smsg, $eml) };
357 sub write_cb { # returns a callback for git_to_mail
358 my ($self, $lei) = @_;
359 # _mbox_write_cb, _maildir_write_cb or _imap_write_cb
360 my $m = "_$self->{base_type}_write_cb";
365 my ($cls, $lei) = @_;
366 my $fmt = $lei->{ovv}->{fmt};
367 my $dst = $lei->{ovv}->{dst};
368 my $self = bless {}, $cls;
369 if ($fmt eq 'maildir') {
370 $maildir_each_file //= do {
371 require PublicInbox::MdirReader;
372 PublicInbox::MdirReader->can('maildir_each_file');
374 $lei->{opt}->{augment} and
375 require PublicInbox::InboxWritable; # eml_from_path
376 $self->{base_type} = 'maildir';
377 -e $dst && !-d _ and die
378 "$dst exists and is not a directory\n";
379 $lei->{ovv}->{dst} = $dst .= '/' if substr($dst, -1) ne '/';
380 } elsif (substr($fmt, 0, 4) eq 'mbox') {
381 require PublicInbox::MboxReader if $lei->{opt}->{augment};
382 (-d $dst || (-e _ && !-w _)) and die
383 "$dst exists and is not a writable file\n";
384 $self->can("eml2$fmt") or die "bad mbox format: $fmt\n";
385 $self->{base_type} = 'mbox';
386 } elsif ($fmt =~ /\Aimaps?\z/) { # TODO .onion support
387 require PublicInbox::NetWriter;
388 my $nwr = PublicInbox::NetWriter->new;
390 $nwr->{quiet} = $lei->{opt}->{quiet};
391 my $err = $nwr->errors($dst);
392 return $lei->fail($err) if $err;
393 require PublicInbox::URIimap; # TODO: URI cast early
394 $self->{uri} = PublicInbox::URIimap->new($dst);
395 $self->{uri}->mailbox or die "No mailbox: $dst";
397 $self->{base_type} = 'imap';
399 die "bad mail --format=$fmt\n";
402 $lei->{dedupe} = PublicInbox::LeiDedupe->new($lei);
406 sub _pre_augment_maildir {
407 my ($self, $lei) = @_;
408 my $dst = $lei->{ovv}->{dst};
409 for my $x (qw(tmp new cur)) {
413 File::Path::mkpath($d);
414 -d $d or die "$d is not a directory";
418 sub _do_augment_maildir {
419 my ($self, $lei) = @_;
420 my $dst = $lei->{ovv}->{dst};
421 if ($lei->{opt}->{augment}) {
422 my $dedupe = $lei->{dedupe};
423 if ($dedupe && $dedupe->prepare_dedupe) {
424 $maildir_each_file->($dst, \&_augment_file, $lei);
425 $dedupe->pause_dedupe;
427 } else { # clobber existing Maildir
428 $maildir_each_file->($dst, \&_unlink);
432 sub _augment_imap { # PublicInbox::NetReader::imap_each cb
433 my ($url, $uid, $kw, $eml, $lei) = @_;
434 _augment($eml, $lei);
437 sub _do_augment_imap {
438 my ($self, $lei) = @_;
439 my $dst = $lei->{ovv}->{dst};
440 my $nwr = $lei->{nwr};
441 if ($lei->{opt}->{augment}) {
442 my $dedupe = $lei->{dedupe};
443 if ($dedupe && $dedupe->prepare_dedupe) {
444 $nwr->imap_each($dst, \&_augment_imap, $lei);
445 $dedupe->pause_dedupe;
447 } else { # clobber existing IMAP folder
448 $nwr->imap_delete_all($dst);
452 sub _pre_augment_mbox {
453 my ($self, $lei) = @_;
454 my $dst = $lei->{ovv}->{dst};
455 if ($dst ne '/dev/stdout') {
456 my $mode = -p $dst ? '>' : '+>>';
457 if (-f _ && !$lei->{opt}->{augment} and !unlink($dst)) {
458 $! == ENOENT or die "unlink($dst): $!";
460 open my $out, $mode, $dst or die "open($dst): $!";
461 $lei->{old_1} = $lei->{1}; # keep for spawning MUA
464 # Perl does SEEK_END even with O_APPEND :<
465 $self->{seekable} = seek($lei->{1}, 0, SEEK_SET);
466 if (!$self->{seekable} && $! != ESPIPE && $dst ne '/dev/stdout') {
467 die "seek($dst): $!\n";
469 state $zsfx_allow = join('|', keys %zsfx2cmd);
470 ($self->{zsfx}) = ($dst =~ /\.($zsfx_allow)\z/) or return;
471 pipe(my ($r, $w)) or die "pipe: $!";
472 $lei->{zpipe} = [ $r, $w ];
475 sub _do_augment_mbox {
476 my ($self, $lei) = @_;
477 return if !$lei->{opt}->{augment};
478 my $dedupe = $lei->{dedupe};
479 my $dst = $lei->{ovv}->{dst};
480 die "cannot augment $dst, not seekable\n" if !$self->{seekable};
482 if (-s $out && $dedupe && $dedupe->prepare_dedupe) {
483 my $zsfx = $self->{zsfx};
484 my $rd = $zsfx ? decompress_src($out, $zsfx, $lei) :
486 my $fmt = $lei->{ovv}->{fmt};
487 PublicInbox::MboxReader->$fmt($rd, \&_augment, $lei);
489 # maybe some systems don't honor O_APPEND, Perl does this:
490 seek($out, 0, SEEK_END) or die "seek $dst: $!";
491 $dedupe->pause_dedupe if $dedupe;
494 sub pre_augment { # fast (1 disk seek), runs in same process as post_augment
495 my ($self, $lei) = @_;
496 # _pre_augment_maildir, _pre_augment_mbox
497 my $m = $self->can("_pre_augment_$self->{base_type}") or return;
501 sub do_augment { # slow, runs in wq worker
502 my ($self, $lei) = @_;
503 # _do_augment_maildir, _do_augment_mbox, or _do_augment_imap
504 my $m = "_do_augment_$self->{base_type}";
508 # fast (spawn compressor or mkdir), runs in same process as pre_augment
510 my ($self, $lei, @args) = @_;
512 my $m = $self->can("_post_augment_$self->{base_type}") or return;
513 $m->($self, $lei, @args);
516 sub ipc_atfork_child {
518 my $lei = delete $self->{lei};
519 $lei->lei_atfork_child;
520 if ($self->{-wq_worker_nr} == 0) {
521 local $0 = 'do_augment';
522 eval { do_augment($self, $lei) };
523 $lei->fail($@) if $@;
524 pkt_do($lei->{pkt_op_p}, '.') == 1 or
525 die "do_post_augment trigger: $!";
527 if (my $zpipe = delete $lei->{zpipe}) {
528 $lei->{1} = $zpipe->[1];
531 $self->{wcb} = $self->write_cb($lei);
532 $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb();
533 $self->SUPER::ipc_atfork_child;
537 $_[0]->{base_type} =~ /\A(?:maildir|mh|imap|jmap)\z/ ? 1 : 0;
542 if ($self->{base_type} eq 'maildir') {
544 utime($t, $t, "$self->{dst}/cur");
548 sub write_mail { # via ->wq_io_do
549 my ($self, $git_dir, $smsg) = @_;
550 my $git = $self->{"$$\0$git_dir"} //= PublicInbox::Git->new($git_dir);
551 git_async_cat($git, $smsg->{blob}, \&git_to_mail,
552 [$self->{wcb}, $smsg]);
555 sub wq_atexit_child {
558 for my $git (delete @$self{grep(/\A$$\0/, keys %$self)}) {
559 $git->async_wait_all;
561 $SIG{__WARN__} = 'DEFAULT';