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 Symbol qw(gensym);
18 use IO::Handle; # ->autoflush
19 use Fcntl qw(SEEK_SET SEEK_END O_CREAT O_EXCL O_WRONLY);
20 use Errno qw(EEXIST ESPIPE ENOENT EPIPE);
21 my ($maildir_each_file);
23 # struggles with short-lived repos, Gcf2Client makes little sense with lei;
24 # but we may use in-process libgit2 in the future.
25 $PublicInbox::GitAsyncCat::GCF2C = 0;
27 my %kw2char = ( # Maildir characters
35 flagged => [ 'X-Status' => 'F' ],
36 answered => [ 'X-Status' => 'A' ],
37 seen => [ 'Status' => 'R' ],
38 draft => [ 'X-Status' => 'T' ],
41 sub _mbox_hdr_buf ($$$) {
42 my ($eml, $type, $smsg) = @_;
43 $eml->header_set($_) for (qw(Lines Bytes Content-Length));
45 # Messages are always 'O' (non-\Recent in IMAP), it saves
46 # MUAs the trouble of rewriting the mbox if no other
48 my %hdr = (Status => [ 'O' ]); # set Status, X-Status
49 for my $k (@{$smsg->{kw} // []}) {
50 if (my $ent = $kw2status{$k}) {
51 push @{$hdr{$ent->[0]}}, $ent->[1];
53 warn "TODO: keyword `$k' not supported for mbox\n";
56 while (my ($name, $chars) = each %hdr) {
57 $eml->header_set($name, join('', sort @$chars));
59 my $buf = delete $eml->{hdr};
61 # fixup old bug from import (pre-a0c07cba0e5d8b6a)
62 $$buf =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
63 my $ident = $smsg->{blob} // 'lei';
64 if (defined(my $pct = $smsg->{pct})) { $ident .= "=$pct" }
66 substr($$buf, 0, 0, # prepend From line
67 "From $ident\@$type Thu Jan 1 00:00:00 1970$eml->{crlf}");
71 sub atomic_append { # for on-disk destinations (O_APPEND, or O_EXCL)
73 if (defined(my $w = syswrite($lei->{1} // return, $$buf))) {
74 return if $w == length($$buf);
75 $buf = "short atomic write: $w != ".length($$buf);
76 } elsif ($! == EPIPE) {
77 return $lei->note_sigpipe(1);
79 $buf = "atomic write: $!";
84 sub eml2mboxrd ($;$) {
85 my ($eml, $smsg) = @_;
86 my $buf = _mbox_hdr_buf($eml, 'mboxrd', $smsg);
87 if (my $bdy = delete $eml->{bdy}) {
88 $$bdy =~ s/^(>*From )/>$1/gm;
89 $$buf .= $eml->{crlf};
90 substr($$bdy, 0, 0, $$buf); # prepend header
93 $$buf .= $eml->{crlf};
98 my ($eml, $smsg) = @_;
99 my $buf = _mbox_hdr_buf($eml, 'mboxo', $smsg);
100 if (my $bdy = delete $eml->{bdy}) {
101 $$bdy =~ s/^From />From /gm;
102 $$buf .= $eml->{crlf};
103 substr($$bdy, 0, 0, $$buf); # prepend header
106 $$buf .= $eml->{crlf};
110 sub _mboxcl_common ($$$) {
111 my ($buf, $bdy, $crlf) = @_;
112 # add Lines: so mutt won't have to add it on MUA close
113 my $lines = $$bdy =~ tr!\n!\n!;
114 $$buf .= 'Content-Length: '.length($$bdy).$crlf.
115 'Lines: '.$lines.$crlf.$crlf;
116 substr($$bdy, 0, 0, $$buf); # prepend header
120 # mboxcl still escapes "From " lines
122 my ($eml, $smsg) = @_;
123 my $buf = _mbox_hdr_buf($eml, 'mboxcl', $smsg);
124 my $crlf = $eml->{crlf};
125 if (my $bdy = delete $eml->{bdy}) {
126 $$bdy =~ s/^From />From /gm;
127 _mboxcl_common($buf, $bdy, $crlf);
133 # mboxcl2 has no "From " escaping
135 my ($eml, $smsg) = @_;
136 my $buf = _mbox_hdr_buf($eml, 'mboxcl2', $smsg);
137 my $crlf = $eml->{crlf};
138 if (my $bdy = delete $eml->{bdy}) {
139 _mboxcl_common($buf, $bdy, $crlf);
145 sub git_to_mail { # git->cat_async callback
146 my ($bref, $oid, $type, $size, $arg) = @_;
147 if ($type ne 'blob') {
148 if ($type eq 'missing') {
149 warn "missing $oid\n";
151 warn "unexpected type=$type for $oid\n";
154 my ($write_cb, $smsg) = @$arg;
155 if ($smsg->{blob} ne $oid) {
156 die "BUG: expected=$smsg->{blob} got=$oid";
158 $write_cb->($bref, $smsg) if $size > 0;
161 sub reap_compress { # dwaitpid callback
162 my ($lei, $pid) = @_;
163 my $cmd = delete $lei->{"pid.$pid"};
165 $lei->fail("@$cmd failed", $? >> 8);
168 # all of these support -c for stdout and -d for decompression,
169 # mutt is commonly distributed with hooks for gz, bz2 and xz, at least
170 # { foo => '' } means "--foo" is passed to the command-line,
171 # otherwise { foo => '--bar' } passes "--bar"
173 gz => [ qw(GZIP pigz gzip), { rsyncable => '', threads => '-p' } ],
174 bz2 => [ 'bzip2', {} ],
175 xz => [ 'xz', { threads => '-T' } ],
176 # XXX does anybody care for these? I prefer zstd on entire FSes,
177 # so it's probably not necessary on a per-file basis
178 # zst => [ 'zstd', { -default => [ qw(-q) ], # it's noisy by default
179 # rsyncable => '', threads => '-T' } ],
180 # zz => [ 'pigz', { -default => [ '--zlib' ],
181 # rsyncable => '', threads => '-p' }],
182 # lzo => [ 'lzop', {} ],
183 # lzma => [ 'lzma', {} ],
187 my ($zsfx, $decompress, $lei) = @_;
188 my $x = $zsfx2cmd{$zsfx} // die "no support for suffix=.$zsfx";
190 my $cmd_opt = pop @info;
191 my @cmd = (undef, $decompress ? qw(-dc) : qw(-c));
192 for my $exe (@info) {
193 # I think respecting client's ENV{GZIP} is OK, not sure
194 # about ENV overrides for other, less-common compressors
195 if ($exe eq uc($exe)) {
196 $exe = $lei->{env}->{$exe} or next;
198 $cmd[0] = which($exe) and last;
200 $cmd[0] // die join(' or ', @info)." missing for .$zsfx";
201 # push @cmd, @{$cmd_opt->{-default}} if $cmd_opt->{-default};
202 for my $bool (qw(rsyncable)) {
203 my $switch = $cmd_opt->{rsyncable} // next;
204 push @cmd, '--'.($switch || $bool);
206 for my $key (qw(threads)) { # support compression level?
207 my $switch = $cmd_opt->{$key} // next;
208 my $val = $lei->{opt}->{$key} // next;
209 push @cmd, $switch, $val;
214 sub _post_augment_mbox { # open a compressor process
215 my ($self, $lei) = @_;
216 my $zsfx = $self->{zsfx} or return;
217 my $cmd = zsfx2cmd($zsfx, undef, $lei);
218 my ($r, $w) = @{delete $lei->{zpipe}};
219 my $rdr = { 0 => $r, 1 => $lei->{1}, 2 => $lei->{2} };
220 my $pid = spawn($cmd, $lei->{env}, $rdr);
222 my $dup = bless { "pid.$pid" => $cmd }, ref($lei);
223 $dup->{$_} = $lei->{$_} for qw(2 sock);
224 tie *$pp, 'PublicInbox::ProcessPipe', $pid, $w, \&reap_compress, $dup;
226 die 'BUG: unexpected {ovv}->{lock_path}' if $lei->{ovv}->{lock_path};
227 $lei->{ovv}->ovv_out_lk_init;
230 sub decompress_src ($$$) {
231 my ($in, $zsfx, $lei) = @_;
232 my $cmd = zsfx2cmd($zsfx, 1, $lei);
233 popen_rd($cmd, $lei->{env}, { 0 => $in, 2 => $lei->{2} });
238 open my $dup, '+>>&', $in or die "dup: $!";
242 # --augment existing output destination, with deduplication
243 sub _augment { # MboxReader eml_cb
244 my ($eml, $lei) = @_;
245 # ignore return value, just populate the skv
246 $lei->{dedupe}->is_dup($eml);
249 sub _mbox_write_cb ($$) {
250 my ($self, $lei) = @_;
251 my $ovv = $lei->{ovv};
252 my $m = 'eml2'.$ovv->{fmt};
253 my $eml2mbox = $self->can($m) or die "$self->$m missing";
254 $lei->{1} // die "no stdout ($m, $ovv->{dst})"; # redirected earlier
255 $lei->{1}->autoflush(1);
256 my $atomic_append = !defined($ovv->{lock_path});
257 my $dedupe = $lei->{dedupe};
258 $dedupe->prepare_dedupe;
259 sub { # for git_to_mail
260 my ($buf, $smsg, $eml) = @_;
261 $eml //= PublicInbox::Eml->new($buf);
262 return if $dedupe->is_dup($eml, $smsg->{blob});
263 $buf = $eml2mbox->($eml, $smsg);
264 return atomic_append($lei, $buf) if $atomic_append;
265 my $lk = $ovv->lock_for_scope;
270 sub _augment_file { # maildir_each_file cb
272 my $eml = PublicInbox::InboxWritable::eml_from_path($f) or return;
273 _augment($eml, $lei);
276 # maildir_each_file callback, \&CORE::unlink doesn't work with it
277 sub _unlink { unlink($_[0]) }
281 sprintf('%x,%x,%x,%x', rand(0xffffffff), time, $$, ++$seq);
285 my ($dst, $buf, $smsg) = @_;
286 my $kw = $smsg->{kw} // [];
287 my $sfx = join('', sort(map { $kw2char{$_} // () } @$kw));
288 my $rand = ''; # chosen by die roll :P
289 my ($tmp, $fh, $final, $ok);
290 my $common = $smsg->{blob} // _rand;
291 if (defined(my $pct = $smsg->{pct})) { $common .= "=$pct" }
293 $tmp = $dst.'tmp/'.$rand.$common;
294 } while (!($ok = sysopen($fh, $tmp, O_CREAT|O_EXCL|O_WRONLY)) &&
295 $! == EEXIST && ($rand = _rand.','));
296 if ($ok && print $fh $$buf and close($fh)) {
297 # ignore new/ and write only to cur/, otherwise MUAs
298 # with R/W access to the Maildir will end up doing
299 # a mass rename which can take a while with thousands
304 $final = $dst.$rand.$common.':2,'.$sfx;
305 } while (!($ok = link($tmp, $final)) && $! == EEXIST &&
306 ($rand = _rand.','));
307 die "link($tmp, $final): $!" unless $ok;
308 unlink($tmp) or warn "W: failed to unlink $tmp: $!\n";
310 my $err = "Error writing $smsg->{blob} to $dst: $!\n";
311 $_[0] = undef; # clobber dst
317 sub _maildir_write_cb ($$) {
318 my ($self, $lei) = @_;
319 my $dedupe = $lei->{dedupe};
320 $dedupe->prepare_dedupe if $dedupe;
321 my $dst = $lei->{ovv}->{dst};
322 sub { # for git_to_mail
323 my ($buf, $smsg, $eml) = @_;
324 $dst // return $lei->fail; # dst may be undef-ed in last run
325 $buf //= \($eml->as_string);
326 return _buf2maildir($dst, $buf, $smsg) if !$dedupe;
327 $eml //= PublicInbox::Eml->new($$buf); # copy buf
328 return if $dedupe->is_dup($eml, $smsg->{blob});
330 _buf2maildir($dst, $buf, $smsg);
334 sub _imap_write_cb ($$) {
335 my ($self, $lei) = @_;
336 my $dedupe = $lei->{dedupe};
337 $dedupe->prepare_dedupe if $dedupe;
338 my $imap_append = $lei->{nwr}->can('imap_append');
339 my $mic = $lei->{nwr}->mic_get($lei->{ovv}->{dst});
340 my $folder = $self->{uri}->mailbox;
341 sub { # for git_to_mail
342 my ($bref, $smsg, $eml) = @_;
343 $mic // return $lei->fail; # dst may be undef-ed in last run
345 $eml //= PublicInbox::Eml->new($$bref); # copy bref
346 return if $dedupe->is_dup($eml, $smsg->{blob});
348 eval { $imap_append->($mic, $folder, $bref, $smsg, $eml) };
356 sub write_cb { # returns a callback for git_to_mail
357 my ($self, $lei) = @_;
358 # _mbox_write_cb, _maildir_write_cb or _imap_write_cb
359 my $m = "_$self->{base_type}_write_cb";
364 my ($cls, $lei) = @_;
365 my $fmt = $lei->{ovv}->{fmt};
366 my $dst = $lei->{ovv}->{dst};
367 my $self = bless {}, $cls;
368 if ($fmt eq 'maildir') {
369 $maildir_each_file //= do {
370 require PublicInbox::MdirReader;
371 PublicInbox::MdirReader->can('maildir_each_file');
373 $lei->{opt}->{augment} and
374 require PublicInbox::InboxWritable; # eml_from_path
375 $self->{base_type} = 'maildir';
376 -e $dst && !-d _ and die
377 "$dst exists and is not a directory\n";
378 $lei->{ovv}->{dst} = $dst .= '/' if substr($dst, -1) ne '/';
379 } elsif (substr($fmt, 0, 4) eq 'mbox') {
380 require PublicInbox::MboxReader if $lei->{opt}->{augment};
381 (-d $dst || (-e _ && !-w _)) and die
382 "$dst exists and is not a writable file\n";
383 $self->can("eml2$fmt") or die "bad mbox format: $fmt\n";
384 $self->{base_type} = 'mbox';
385 } elsif ($fmt =~ /\Aimaps?\z/) { # TODO .onion support
386 require PublicInbox::NetWriter;
387 my $nwr = PublicInbox::NetWriter->new;
389 $nwr->{quiet} = $lei->{opt}->{quiet};
390 my $err = $nwr->errors($dst);
391 return $lei->fail($err) if $err;
392 require PublicInbox::URIimap; # TODO: URI cast early
393 $self->{uri} = PublicInbox::URIimap->new($dst);
394 $self->{uri}->mailbox or die "No mailbox: $dst";
396 $self->{base_type} = 'imap';
398 die "bad mail --format=$fmt\n";
401 $lei->{dedupe} = PublicInbox::LeiDedupe->new($lei);
405 sub _pre_augment_maildir {
406 my ($self, $lei) = @_;
407 my $dst = $lei->{ovv}->{dst};
408 for my $x (qw(tmp new cur)) {
412 File::Path::mkpath($d);
413 -d $d or die "$d is not a directory";
417 sub _do_augment_maildir {
418 my ($self, $lei) = @_;
419 my $dst = $lei->{ovv}->{dst};
420 if ($lei->{opt}->{augment}) {
421 my $dedupe = $lei->{dedupe};
422 if ($dedupe && $dedupe->prepare_dedupe) {
423 $maildir_each_file->($dst, \&_augment_file, $lei);
424 $dedupe->pause_dedupe;
426 } else { # clobber existing Maildir
427 $maildir_each_file->($dst, \&_unlink);
431 sub _augment_imap { # PublicInbox::NetReader::imap_each cb
432 my ($url, $uid, $kw, $eml, $lei) = @_;
433 _augment($eml, $lei);
436 sub _do_augment_imap {
437 my ($self, $lei) = @_;
438 my $dst = $lei->{ovv}->{dst};
439 my $nwr = $lei->{nwr};
440 if ($lei->{opt}->{augment}) {
441 my $dedupe = $lei->{dedupe};
442 if ($dedupe && $dedupe->prepare_dedupe) {
443 $nwr->imap_each($dst, \&_augment_imap, $lei);
444 $dedupe->pause_dedupe;
446 } else { # clobber existing IMAP folder
447 $nwr->imap_delete_all($dst);
451 sub _pre_augment_mbox {
452 my ($self, $lei) = @_;
453 my $dst = $lei->{ovv}->{dst};
454 if ($dst ne '/dev/stdout') {
455 my $mode = -p $dst ? '>' : '+>>';
456 if (-f _ && !$lei->{opt}->{augment} and !unlink($dst)) {
457 $! == ENOENT or die "unlink($dst): $!";
459 open my $out, $mode, $dst or die "open($dst): $!";
460 $lei->{old_1} = $lei->{1}; # keep for spawning MUA
463 # Perl does SEEK_END even with O_APPEND :<
464 $self->{seekable} = seek($lei->{1}, 0, SEEK_SET);
465 if (!$self->{seekable} && $! != ESPIPE && $dst ne '/dev/stdout') {
466 die "seek($dst): $!\n";
468 state $zsfx_allow = join('|', keys %zsfx2cmd);
469 ($self->{zsfx}) = ($dst =~ /\.($zsfx_allow)\z/) or return;
470 pipe(my ($r, $w)) or die "pipe: $!";
471 $lei->{zpipe} = [ $r, $w ];
474 sub _do_augment_mbox {
475 my ($self, $lei) = @_;
476 return if !$lei->{opt}->{augment};
477 my $dedupe = $lei->{dedupe};
478 my $dst = $lei->{ovv}->{dst};
479 die "cannot augment $dst, not seekable\n" if !$self->{seekable};
481 if (-s $out && $dedupe && $dedupe->prepare_dedupe) {
482 my $zsfx = $self->{zsfx};
483 my $rd = $zsfx ? decompress_src($out, $zsfx, $lei) :
485 my $fmt = $lei->{ovv}->{fmt};
486 PublicInbox::MboxReader->$fmt($rd, \&_augment, $lei);
488 # maybe some systems don't honor O_APPEND, Perl does this:
489 seek($out, 0, SEEK_END) or die "seek $dst: $!";
490 $dedupe->pause_dedupe if $dedupe;
493 sub pre_augment { # fast (1 disk seek), runs in same process as post_augment
494 my ($self, $lei) = @_;
495 # _pre_augment_maildir, _pre_augment_mbox
496 my $m = $self->can("_pre_augment_$self->{base_type}") or return;
500 sub do_augment { # slow, runs in wq worker
501 my ($self, $lei) = @_;
502 # _do_augment_maildir, _do_augment_mbox
503 my $m = "_do_augment_$self->{base_type}";
507 # fast (spawn compressor or mkdir), runs in same process as pre_augment
509 my ($self, $lei, @args) = @_;
511 my $m = $self->can("_post_augment_$self->{base_type}") or return;
512 $m->($self, $lei, @args);
515 sub ipc_atfork_child {
517 my $lei = delete $self->{lei};
518 $lei->lei_atfork_child;
519 if (my $zpipe = delete $lei->{zpipe}) {
520 $lei->{1} = $zpipe->[1];
523 $self->{wcb} = $self->write_cb($lei);
524 $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb();
525 $self->SUPER::ipc_atfork_child;
529 $_[0]->{base_type} =~ /\A(?:maildir|mh|imap|jmap)\z/ ? 1 : 0;
534 if ($self->{base_type} eq 'maildir') {
536 utime($t, $t, "$self->{dst}/cur");
540 sub write_mail { # via ->wq_io_do
541 my ($self, $git_dir, $smsg) = @_;
542 my $git = $self->{"$$\0$git_dir"} //= PublicInbox::Git->new($git_dir);
543 git_async_cat($git, $smsg->{blob}, \&git_to_mail,
544 [$self->{wcb}, $smsg]);
547 sub wq_atexit_child {
550 for my $git (delete @$self{grep(/\A$$\0/, keys %$self)}) {
551 $git->async_wait_all;
553 $SIG{__WARN__} = 'DEFAULT';