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;
15 use Symbol qw(gensym);
16 use IO::Handle; # ->autoflush
17 use Fcntl qw(SEEK_SET SEEK_END O_CREAT O_EXCL O_WRONLY);
18 use Errno qw(EEXIST ESPIPE ENOENT);
21 my %kw2char = ( # Maildir characters
29 flagged => [ 'X-Status' => 'F' ],
30 answered => [ 'X-Status' => 'A' ],
31 seen => [ 'Status' => 'R' ],
32 draft => [ 'X-Status' => 'T' ],
35 sub _mbox_hdr_buf ($$$) {
36 my ($eml, $type, $smsg) = @_;
37 $eml->header_set($_) for (qw(Lines Bytes Content-Length));
39 # Messages are always 'O' (non-\Recent in IMAP), it saves
40 # MUAs the trouble of rewriting the mbox if no other
42 my %hdr = (Status => [ 'O' ]); # set Status, X-Status
43 for my $k (@{$smsg->{kw} // []}) {
44 if (my $ent = $kw2status{$k}) {
45 push @{$hdr{$ent->[0]}}, $ent->[1];
47 warn "TODO: keyword `$k' not supported for mbox\n";
50 while (my ($name, $chars) = each %hdr) {
51 $eml->header_set($name, 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 defined(my $w = syswrite($fh, $$buf)) or die "write: $!";
68 $w == length($$buf) or die "short write: $w != ".length($$buf);
73 print $fh $$buf or die "print: $!";
76 sub eml2mboxrd ($;$) {
77 my ($eml, $smsg) = @_;
78 my $buf = _mbox_hdr_buf($eml, 'mboxrd', $smsg);
79 if (my $bdy = delete $eml->{bdy}) {
80 $$bdy =~ s/^(>*From )/>$1/gm;
81 $$buf .= $eml->{crlf};
82 substr($$bdy, 0, 0, $$buf); # prepend header
85 $$buf .= $eml->{crlf};
90 my ($eml, $smsg) = @_;
91 my $buf = _mbox_hdr_buf($eml, 'mboxo', $smsg);
92 if (my $bdy = delete $eml->{bdy}) {
93 $$bdy =~ s/^From />From /gm;
94 $$buf .= $eml->{crlf};
95 substr($$bdy, 0, 0, $$buf); # prepend header
98 $$buf .= $eml->{crlf};
102 sub _mboxcl_common ($$$) {
103 my ($buf, $bdy, $crlf) = @_;
104 # add Lines: so mutt won't have to add it on MUA close
105 my $lines = $$bdy =~ tr!\n!\n!;
106 $$buf .= 'Content-Length: '.length($$bdy).$crlf.
107 'Lines: '.$lines.$crlf.$crlf;
108 substr($$bdy, 0, 0, $$buf); # prepend header
112 # mboxcl still escapes "From " lines
114 my ($eml, $smsg) = @_;
115 my $buf = _mbox_hdr_buf($eml, 'mboxcl', $smsg);
116 my $crlf = $eml->{crlf};
117 if (my $bdy = delete $eml->{bdy}) {
118 $$bdy =~ s/^From />From /gm;
119 _mboxcl_common($buf, $bdy, $crlf);
125 # mboxcl2 has no "From " escaping
127 my ($eml, $smsg) = @_;
128 my $buf = _mbox_hdr_buf($eml, 'mboxcl2', $smsg);
129 my $crlf = $eml->{crlf};
130 if (my $bdy = delete $eml->{bdy}) {
131 _mboxcl_common($buf, $bdy, $crlf);
137 sub git_to_mail { # git->cat_async callback
138 my ($bref, $oid, $type, $size, $arg) = @_;
139 if ($type ne 'blob') {
140 if ($type eq 'missing') {
141 warn "missing $oid\n";
143 warn "unexpected type=$type for $oid\n";
146 my ($write_cb, $smsg) = @$arg;
147 if ($smsg->{blob} ne $oid) {
148 die "BUG: expected=$smsg->{blob} got=$oid";
150 $write_cb->($bref, $smsg) if $size > 0;
153 sub reap_compress { # dwaitpid callback
154 my ($lei, $pid) = @_;
155 my $cmd = delete $lei->{"pid.$pid"};
157 $lei->fail("@$cmd failed", $? >> 8);
160 # all of these support -c for stdout and -d for decompression,
161 # mutt is commonly distributed with hooks for gz, bz2 and xz, at least
162 # { foo => '' } means "--foo" is passed to the command-line,
163 # otherwise { foo => '--bar' } passes "--bar"
165 gz => [ qw(GZIP pigz gzip), { rsyncable => '', threads => '-p' } ],
166 bz2 => [ 'bzip2', {} ],
167 xz => [ 'xz', { threads => '-T' } ],
168 # XXX does anybody care for these? I prefer zstd on entire FSes,
169 # so it's probably not necessary on a per-file basis
170 # zst => [ 'zstd', { -default => [ qw(-q) ], # it's noisy by default
171 # rsyncable => '', threads => '-T' } ],
172 # zz => [ 'pigz', { -default => [ '--zlib' ],
173 # rsyncable => '', threads => '-p' }],
174 # lzo => [ 'lzop', {} ],
175 # lzma => [ 'lzma', {} ],
179 my ($zsfx, $decompress, $lei) = @_;
180 my $x = $zsfx2cmd{$zsfx} // die "no support for suffix=.$zsfx";
182 my $cmd_opt = pop @info;
183 my @cmd = (undef, $decompress ? qw(-dc) : qw(-c));
184 for my $exe (@info) {
185 # I think respecting client's ENV{GZIP} is OK, not sure
186 # about ENV overrides for other, less-common compressors
187 if ($exe eq uc($exe)) {
188 $exe = $lei->{env}->{$exe} or next;
190 $cmd[0] = which($exe) and last;
192 $cmd[0] // die join(' or ', @info)." missing for .$zsfx";
193 # push @cmd, @{$cmd_opt->{-default}} if $cmd_opt->{-default};
194 for my $bool (qw(rsyncable)) {
195 my $switch = $cmd_opt->{rsyncable} // next;
196 push @cmd, '--'.($switch || $bool);
198 for my $key (qw(threads)) { # support compression level?
199 my $switch = $cmd_opt->{$key} // next;
200 my $val = $lei->{opt}->{$key} // next;
201 push @cmd, $switch, $val;
206 sub _post_augment_mbox { # open a compressor process
207 my ($self, $lei, $zpipe) = @_;
208 my $zsfx = $self->{zsfx} or return;
209 my $cmd = zsfx2cmd($zsfx, undef, $lei);
210 my ($r, $w) = splice(@$zpipe, 0, 2);
211 my $rdr = { 0 => $r, 1 => $lei->{1}, 2 => $lei->{2} };
212 my $pid = spawn($cmd, $lei->{env}, $rdr);
214 my $dup = bless { "pid.$pid" => $cmd }, ref($lei);
215 $dup->{$_} = $lei->{$_} for qw(2 sock);
216 tie *$pp, 'PublicInbox::ProcessPipe', $pid, $w, \&reap_compress, $dup;
218 die 'BUG: unexpected {ovv}->{lock_path}' if $lei->{ovv}->{lock_path};
219 $lei->{ovv}->ovv_out_lk_init;
222 sub decompress_src ($$$) {
223 my ($in, $zsfx, $lei) = @_;
224 my $cmd = zsfx2cmd($zsfx, 1, $lei);
225 popen_rd($cmd, $lei->{env}, { 0 => $in, 2 => $lei->{2} });
230 open my $dup, '+>>&', $in or die "dup: $!";
234 # --augment existing output destination, with deduplication
235 sub _augment { # MboxReader eml_cb
236 my ($eml, $lei) = @_;
237 # ignore return value, just populate the skv
238 $lei->{dedupe}->is_dup($eml);
241 sub _mbox_write_cb ($$) {
242 my ($self, $lei) = @_;
243 my $ovv = $lei->{ovv};
244 my $m = 'eml2'.$ovv->{fmt};
245 my $eml2mbox = $self->can($m) or die "$self->$m missing";
246 my $out = $lei->{1} // die "no stdout ($m, $ovv->{dst})"; # redirected earlier
248 my $write = $ovv->{lock_path} ? \&_print_full : \&atomic_append;
249 my $dedupe = $lei->{dedupe};
250 $dedupe->prepare_dedupe;
251 sub { # for git_to_mail
252 my ($buf, $smsg, $eml) = @_;
254 $eml //= PublicInbox::Eml->new($buf);
255 if (!$dedupe->is_dup($eml, $smsg->{blob})) {
256 $buf = $eml2mbox->($eml, $smsg);
257 my $lk = $ovv->lock_for_scope;
258 eval { $write->($out, $buf) };
260 die $@ if ref($@) ne 'PublicInbox::SIGPIPE';
267 sub _maildir_each_file ($$;@) {
268 my ($dir, $cb, @arg) = @_;
269 for my $d (qw(new/ cur/)) {
271 opendir my $dh, $pfx or next;
272 while (defined(my $fn = readdir($dh))) {
273 $cb->($pfx.$fn, @arg) if $fn =~ /:2,[A-Za-z]*\z/;
278 sub _augment_file { # _maildir_each_file cb
280 my $eml = PublicInbox::InboxWritable::eml_from_path($f) or return;
281 _augment($eml, $lei);
284 # _maildir_each_file callback, \&CORE::unlink doesn't work with it
285 sub _unlink { unlink($_[0]) }
289 sprintf('%x,%x,%x,%x', rand(0xffffffff), time, $$, ++$seq);
293 my ($dst, $buf, $smsg) = @_;
294 my $kw = $smsg->{kw} // [];
295 my $sfx = join('', sort(map { $kw2char{$_} // () } @$kw));
296 my $rand = ''; # chosen by die roll :P
297 my ($tmp, $fh, $final);
298 my $common = $smsg->{blob} // _rand;
299 if (defined(my $pct = $smsg->{pct})) { $common .= "=$pct" }
301 $tmp = $dst.'tmp/'.$rand.$common;
302 } while (!sysopen($fh, $tmp, O_CREAT|O_EXCL|O_WRONLY) &&
303 $! == EEXIST && ($rand = _rand.','));
304 if (print $fh $$buf and close($fh)) {
305 # ignore new/ and write only to cur/, otherwise MUAs
306 # with R/W access to the Maildir will end up doing
307 # a mass rename which can take a while with thousands
312 $final = $dst.$rand.$common.':2,'.$sfx;
313 } while (!link($tmp, $final) && $! == EEXIST &&
314 ($rand = _rand.','));
315 unlink($tmp) or warn "W: failed to unlink $tmp: $!\n";
319 die "Error writing $smsg->{blob} to $dst: $err";
323 sub _maildir_write_cb ($$) {
324 my ($self, $lei) = @_;
325 my $dedupe = $lei->{dedupe};
326 $dedupe->prepare_dedupe;
327 my $dst = $lei->{ovv}->{dst};
328 sub { # for git_to_mail
329 my ($buf, $smsg, $eml) = @_;
330 $buf //= \($eml->as_string);
331 return _buf2maildir($dst, $buf, $smsg) if !$dedupe;
332 $eml //= PublicInbox::Eml->new($$buf); # copy buf
333 return if $dedupe->is_dup($eml, $smsg->{blob});
335 _buf2maildir($dst, $buf, $smsg);
339 sub write_cb { # returns a callback for git_to_mail
340 my ($self, $lei) = @_;
341 # _mbox_write_cb or _maildir_write_cb
342 my $m = "_$self->{base_type}_write_cb";
347 my ($cls, $lei) = @_;
348 my $fmt = $lei->{ovv}->{fmt};
349 my $dst = $lei->{ovv}->{dst};
350 my $self = bless {}, $cls;
351 if ($fmt eq 'maildir') {
352 $self->{base_type} = 'maildir';
353 -e $dst && !-d _ and die
354 "$dst exists and is not a directory\n";
355 $lei->{ovv}->{dst} = $dst .= '/' if substr($dst, -1) ne '/';
356 } elsif (substr($fmt, 0, 4) eq 'mbox') {
357 (-d $dst || (-e _ && !-w _)) and die
358 "$dst exists and is not a writable file\n";
359 $self->can("eml2$fmt") or die "bad mbox --format=$fmt\n";
360 $self->{base_type} = 'mbox';
362 die "bad mail --format=$fmt\n";
364 $lei->{dedupe} = PublicInbox::LeiDedupe->new($lei);
368 sub _pre_augment_maildir {} # noop
370 sub _do_augment_maildir {
371 my ($self, $lei) = @_;
372 my $dst = $lei->{ovv}->{dst};
373 if ($lei->{opt}->{augment}) {
374 my $dedupe = $lei->{dedupe};
375 if ($dedupe && $dedupe->prepare_dedupe) {
376 require PublicInbox::InboxWritable; # eml_from_path
377 _maildir_each_file($dst, \&_augment_file, $lei);
378 $dedupe->pause_dedupe;
380 } else { # clobber existing Maildir
381 _maildir_each_file($dst, \&_unlink);
385 sub _post_augment_maildir {
386 my ($self, $lei) = @_;
387 my $dst = $lei->{ovv}->{dst};
388 for my $x (qw(tmp new cur)) {
392 File::Path::mkpath($d);
393 -d $d or die "$d is not a directory";
397 sub _pre_augment_mbox {
398 my ($self, $lei) = @_;
399 my $dst = $lei->{ovv}->{dst};
400 if ($dst ne '/dev/stdout') {
401 my $mode = -p $dst ? '>' : '+>>';
402 if (-f _ && !$lei->{opt}->{augment} and !unlink($dst)) {
403 $! == ENOENT or die "unlink($dst): $!";
405 open my $out, $mode, $dst or die "open($dst): $!";
406 $lei->{old_1} = $lei->{1};
409 # Perl does SEEK_END even with O_APPEND :<
410 $self->{seekable} = seek($lei->{1}, 0, SEEK_SET);
411 if (!$self->{seekable} && $! != ESPIPE && $dst ne '/dev/stdout') {
412 die "seek($dst): $!\n";
414 state $zsfx_allow = join('|', keys %zsfx2cmd);
415 ($self->{zsfx}) = ($dst =~ /\.($zsfx_allow)\z/) or return;
416 pipe(my ($r, $w)) or die "pipe: $!";
420 sub _do_augment_mbox {
421 my ($self, $lei) = @_;
422 return if !$lei->{opt}->{augment};
423 my $dedupe = $lei->{dedupe};
424 my $dst = $lei->{ovv}->{dst};
425 die "cannot augment $dst, not seekable\n" if !$self->{seekable};
427 if (-s $out && $dedupe && $dedupe->prepare_dedupe) {
428 my $zsfx = $self->{zsfx};
429 my $rd = $zsfx ? decompress_src($out, $zsfx, $lei) :
431 my $fmt = $lei->{ovv}->{fmt};
432 require PublicInbox::MboxReader;
433 PublicInbox::MboxReader->$fmt($rd, \&_augment, $lei);
435 # maybe some systems don't honor O_APPEND, Perl does this:
436 seek($out, 0, SEEK_END) or die "seek $dst: $!";
437 $dedupe->pause_dedupe if $dedupe;
440 sub pre_augment { # fast (1 disk seek), runs in main daemon
441 my ($self, $lei) = @_;
442 # _pre_augment_maildir, _pre_augment_mbox
443 my $m = "_pre_augment_$self->{base_type}";
447 sub do_augment { # slow, runs in wq worker
448 my ($self, $lei) = @_;
449 # _do_augment_maildir, _do_augment_mbox
450 my $m = "_do_augment_$self->{base_type}";
454 sub post_augment { # fast (spawn compressor or mkdir), runs in main daemon
455 my ($self, $lei, @args) = @_;
456 # _post_augment_maildir, _post_augment_mbox
457 my $m = "_post_augment_$self->{base_type}";
458 $self->$m($lei, @args);
461 sub write_mail { # via ->wq_do
462 my ($self, $git_dir, $smsg, $lei) = @_;
463 my $not_done = delete $self->{4}; # write end of {each_smsg_done}
464 my $wcb = $self->{wcb} //= do { # first message
465 my %sig = $lei->atfork_child_wq($self);
466 @SIG{keys %sig} = values %sig; # not local
467 $lei->{dedupe}->prepare_dedupe;
468 $self->write_cb($lei);
470 my $git = $self->{"$$\0$git_dir"} //= PublicInbox::Git->new($git_dir);
471 $git->cat_async($smsg->{blob}, \&git_to_mail, [$wcb, $smsg, $not_done]);
474 sub ipc_atfork_prepare {
476 # FDs: (done_wr, stdout|mbox, stderr, 3: sock, 4: each_smsg_done_wr)
477 $self->SUPER::ipc_atfork_prepare; # PublicInbox::IPC
480 # We rely on OnDestroy to run this before ->DESTROY, since ->DESTROY
481 # ordering is unstable at worker exit and may cause segfaults
485 for my $git (delete @$self{grep(/\A$$\0/, keys %$self)}) {
486 $git->async_wait_all;
490 sub DESTROY { delete $_[0]->{wcb} }
492 sub ipc_atfork_child { # runs after IPC::wq_worker_loop
494 $self->SUPER::ipc_atfork_child;
495 # reap_gits needs to run before $self->DESTROY,
496 # IPC.pm will ensure that.
497 PublicInbox::OnDestroy->new($$, \&reap_gits, $self);