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 # fileno needed because wq_set_recv_modes only used ">&=" for {1}
231 # and Perl blindly trusts that to reject the '+' (readability flag)
232 open my $dup, '+>>&=', fileno($in) or die "dup: $!";
236 # --augment existing output destination, with deduplication
237 sub _augment { # MboxReader eml_cb
238 my ($eml, $lei) = @_;
239 # ignore return value, just populate the skv
240 $lei->{dedupe}->is_dup($eml);
243 sub _mbox_write_cb ($$) {
244 my ($self, $lei) = @_;
245 my $ovv = $lei->{ovv};
246 my $m = 'eml2'.$ovv->{fmt};
247 my $eml2mbox = $self->can($m) or die "$self->$m missing";
248 my $out = $lei->{1} // die "no stdout ($m, $ovv->{dst})"; # redirected earlier
250 my $write = $ovv->{lock_path} ? \&_print_full : \&atomic_append;
251 my $dedupe = $lei->{dedupe};
252 $dedupe->prepare_dedupe;
253 sub { # for git_to_mail
254 my ($buf, $smsg, $eml) = @_;
256 $eml //= PublicInbox::Eml->new($buf);
257 if (!$dedupe->is_dup($eml, $smsg->{blob})) {
258 $buf = $eml2mbox->($eml, $smsg);
259 my $lk = $ovv->lock_for_scope;
260 eval { $write->($out, $buf) };
262 die $@ if ref($@) ne 'PublicInbox::SIGPIPE';
269 sub _maildir_each_file ($$;@) {
270 my ($dir, $cb, @arg) = @_;
271 for my $d (qw(new/ cur/)) {
273 opendir my $dh, $pfx or next;
274 while (defined(my $fn = readdir($dh))) {
275 $cb->($pfx.$fn, @arg) if $fn =~ /:2,[A-Za-z]*\z/;
280 sub _augment_file { # _maildir_each_file cb
282 my $eml = PublicInbox::InboxWritable::eml_from_path($f) or return;
283 _augment($eml, $lei);
286 # _maildir_each_file callback, \&CORE::unlink doesn't work with it
287 sub _unlink { unlink($_[0]) }
291 sprintf('%x,%x,%x,%x', rand(0xffffffff), time, $$, ++$seq);
295 my ($dst, $buf, $smsg) = @_;
296 my $kw = $smsg->{kw} // [];
297 my $sfx = join('', sort(map { $kw2char{$_} // () } @$kw));
298 my $rand = ''; # chosen by die roll :P
299 my ($tmp, $fh, $final);
300 my $common = $smsg->{blob} // _rand;
301 if (defined(my $pct = $smsg->{pct})) { $common .= "=$pct" }
303 $tmp = $dst.'tmp/'.$rand.$common;
304 } while (!sysopen($fh, $tmp, O_CREAT|O_EXCL|O_WRONLY) &&
305 $! == EEXIST && ($rand = _rand.','));
306 if (print $fh $$buf and close($fh)) {
307 # ignore new/ and write only to cur/, otherwise MUAs
308 # with R/W access to the Maildir will end up doing
309 # a mass rename which can take a while with thousands
314 $final = $dst.$rand.$common.':2,'.$sfx;
315 } while (!link($tmp, $final) && $! == EEXIST &&
316 ($rand = _rand.','));
317 unlink($tmp) or warn "W: failed to unlink $tmp: $!\n";
321 die "Error writing $smsg->{blob} to $dst: $err";
325 sub _maildir_write_cb ($$) {
326 my ($self, $lei) = @_;
327 my $dedupe = $lei->{dedupe};
328 $dedupe->prepare_dedupe;
329 my $dst = $lei->{ovv}->{dst};
330 sub { # for git_to_mail
331 my ($buf, $smsg, $eml) = @_;
332 $buf //= \($eml->as_string);
333 return _buf2maildir($dst, $buf, $smsg) if !$dedupe;
334 $eml //= PublicInbox::Eml->new($$buf); # copy buf
335 return if $dedupe->is_dup($eml, $smsg->{blob});
337 _buf2maildir($dst, $buf, $smsg);
341 sub write_cb { # returns a callback for git_to_mail
342 my ($self, $lei) = @_;
343 # _mbox_write_cb or _maildir_write_cb
344 my $m = "_$self->{base_type}_write_cb";
349 my ($cls, $lei) = @_;
350 my $fmt = $lei->{ovv}->{fmt};
351 my $dst = $lei->{ovv}->{dst};
352 my $self = bless {}, $cls;
353 if ($fmt eq 'maildir') {
354 $self->{base_type} = 'maildir';
355 -e $dst && !-d _ and die
356 "$dst exists and is not a directory\n";
357 $lei->{ovv}->{dst} = $dst .= '/' if substr($dst, -1) ne '/';
358 } elsif (substr($fmt, 0, 4) eq 'mbox') {
359 (-d $dst || (-e _ && !-w _)) and die
360 "$dst exists and is not a writable file\n";
361 $self->can("eml2$fmt") or die "bad mbox --format=$fmt\n";
362 $self->{base_type} = 'mbox';
364 die "bad mail --format=$fmt\n";
366 $lei->{dedupe} = PublicInbox::LeiDedupe->new($lei);
370 sub _pre_augment_maildir {} # noop
372 sub _do_augment_maildir {
373 my ($self, $lei) = @_;
374 my $dst = $lei->{ovv}->{dst};
375 if ($lei->{opt}->{augment}) {
376 my $dedupe = $lei->{dedupe};
377 if ($dedupe && $dedupe->prepare_dedupe) {
378 require PublicInbox::InboxWritable; # eml_from_path
379 _maildir_each_file($dst, \&_augment_file, $lei);
380 $dedupe->pause_dedupe;
382 } else { # clobber existing Maildir
383 _maildir_each_file($dst, \&_unlink);
387 sub _post_augment_maildir {
388 my ($self, $lei) = @_;
389 my $dst = $lei->{ovv}->{dst};
390 for my $x (qw(tmp new cur)) {
394 File::Path::mkpath($d);
395 -d $d or die "$d is not a directory";
399 sub _pre_augment_mbox {
400 my ($self, $lei) = @_;
401 my $dst = $lei->{ovv}->{dst};
402 if ($dst ne '/dev/stdout') {
403 my $mode = -p $dst ? '>' : '+>>';
404 if (-f _ && !$lei->{opt}->{augment} and !unlink($dst)) {
405 $! == ENOENT or die "unlink($dst): $!";
407 open my $out, $mode, $dst or die "open($dst): $!";
410 # Perl does SEEK_END even with O_APPEND :<
411 $self->{seekable} = seek($lei->{1}, 0, SEEK_SET);
412 if (!$self->{seekable} && $! != ESPIPE && $dst ne '/dev/stdout') {
413 die "seek($dst): $!\n";
415 state $zsfx_allow = join('|', keys %zsfx2cmd);
416 ($self->{zsfx}) = ($dst =~ /\.($zsfx_allow)\z/) or return;
417 pipe(my ($r, $w)) or die "pipe: $!";
421 sub _do_augment_mbox {
422 my ($self, $lei) = @_;
423 return if !$lei->{opt}->{augment};
424 my $dedupe = $lei->{dedupe};
425 my $dst = $lei->{ovv}->{dst};
426 die "cannot augment $dst, not seekable\n" if !$self->{seekable};
428 if (-s $out && $dedupe && $dedupe->prepare_dedupe) {
429 my $zsfx = $self->{zsfx};
430 my $rd = $zsfx ? decompress_src($out, $zsfx, $lei) :
432 my $fmt = $lei->{ovv}->{fmt};
433 require PublicInbox::MboxReader;
434 PublicInbox::MboxReader->$fmt($rd, \&_augment, $lei);
436 # maybe some systems don't honor O_APPEND, Perl does this:
437 seek($out, 0, SEEK_END) or die "seek $dst: $!";
438 $dedupe->pause_dedupe if $dedupe;
441 sub pre_augment { # fast (1 disk seek), runs in main daemon
442 my ($self, $lei) = @_;
443 # _pre_augment_maildir, _pre_augment_mbox
444 my $m = "_pre_augment_$self->{base_type}";
448 sub do_augment { # slow, runs in wq worker
449 my ($self, $lei) = @_;
450 # _do_augment_maildir, _do_augment_mbox
451 my $m = "_do_augment_$self->{base_type}";
455 sub post_augment { # fast (spawn compressor or mkdir), runs in main daemon
456 my ($self, $lei, @args) = @_;
457 # _post_augment_maildir, _post_augment_mbox
458 my $m = "_post_augment_$self->{base_type}";
459 $self->$m($lei, @args);
462 sub write_mail { # via ->wq_do
463 my ($self, $git_dir, $smsg, $lei) = @_;
464 my $not_done = delete $self->{4}; # write end of {each_smsg_done}
465 my $wcb = $self->{wcb} //= do { # first message
466 my %sig = $lei->atfork_child_wq($self);
467 @SIG{keys %sig} = values %sig; # not local
468 $lei->{dedupe}->prepare_dedupe;
469 $self->write_cb($lei);
471 my $git = $self->{"$$\0$git_dir"} //= PublicInbox::Git->new($git_dir);
472 $git->cat_async($smsg->{blob}, \&git_to_mail, [$wcb, $smsg, $not_done]);
475 sub ipc_atfork_prepare {
477 # (done_wr, stdout|mbox, stderr, 3: sock, 4: each_smsg_done_wr)
478 $self->wq_set_recv_modes(qw[+<&= >&= >&= +<&= >&=]);
479 $self->SUPER::ipc_atfork_prepare; # PublicInbox::IPC
482 # We rely on OnDestroy to run this before ->DESTROY, since ->DESTROY
483 # ordering is unstable at worker exit and may cause segfaults
487 for my $git (delete @$self{grep(/\A$$\0/, keys %$self)}) {
488 $git->async_wait_all;
492 sub DESTROY { delete $_[0]->{wcb} }
494 sub ipc_atfork_child { # runs after IPC::wq_worker_loop
496 $self->SUPER::ipc_atfork_child;
497 # reap_gits needs to run before $self->DESTROY,
498 # IPC.pm will ensure that.
499 PublicInbox::OnDestroy->new($$, \&reap_gits, $self);