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 Symbol qw(gensym);
15 use IO::Handle; # ->autoflush
16 use Fcntl qw(SEEK_SET SEEK_END O_CREAT O_EXCL O_WRONLY);
17 use Errno qw(EEXIST ESPIPE ENOENT);
20 my %kw2char = ( # Maildir characters
28 flagged => [ 'X-Status' => 'F' ],
29 answered => [ 'X-Status' => 'A' ],
30 seen => [ 'Status' => 'R' ],
31 draft => [ 'X-Status' => 'T' ],
34 sub _mbox_hdr_buf ($$$) {
35 my ($eml, $type, $kw) = @_;
36 $eml->header_set($_) for (qw(Lines Bytes Content-Length));
37 my %hdr; # set Status, X-Status
39 if (my $ent = $kw2status{$k}) {
40 push @{$hdr{$ent->[0]}}, $ent->[1];
42 warn "TODO: keyword `$k' not supported for mbox\n";
45 while (my ($name, $chars) = each %hdr) {
46 $eml->header_set($name, join('', sort @$chars));
48 my $buf = delete $eml->{hdr};
50 # fixup old bug from import (pre-a0c07cba0e5d8b6a)
51 $$buf =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
53 substr($$buf, 0, 0, # prepend From line
54 "From lei\@$type Thu Jan 1 00:00:00 1970$eml->{crlf}");
58 sub atomic_append { # for on-disk destinations (O_APPEND, or O_EXCL)
60 defined(my $w = syswrite($fh, $$buf)) or die "write: $!";
61 $w == length($$buf) or die "short write: $w != ".length($$buf);
66 print $fh $$buf or die "print: $!";
69 sub eml2mboxrd ($;$) {
71 my $buf = _mbox_hdr_buf($eml, 'mboxrd', $kw);
72 if (my $bdy = delete $eml->{bdy}) {
73 $$bdy =~ s/^(>*From )/>$1/gm;
74 $$buf .= $eml->{crlf};
75 substr($$bdy, 0, 0, $$buf); # prepend header
78 $$buf .= $eml->{crlf};
84 my $buf = _mbox_hdr_buf($eml, 'mboxo', $kw);
85 if (my $bdy = delete $eml->{bdy}) {
86 $$bdy =~ s/^From />From /gm;
87 $$buf .= $eml->{crlf};
88 substr($$bdy, 0, 0, $$buf); # prepend header
91 $$buf .= $eml->{crlf};
95 # mboxcl still escapes "From " lines
98 my $buf = _mbox_hdr_buf($eml, 'mboxcl', $kw);
99 my $crlf = $eml->{crlf};
100 if (my $bdy = delete $eml->{bdy}) {
101 $$bdy =~ s/^From />From /gm;
102 $$buf .= 'Content-Length: '.length($$bdy).$crlf.$crlf;
103 substr($$bdy, 0, 0, $$buf); # prepend header
110 # mboxcl2 has no "From " escaping
113 my $buf = _mbox_hdr_buf($eml, 'mboxcl2', $kw);
114 my $crlf = $eml->{crlf};
115 if (my $bdy = delete $eml->{bdy}) {
116 $$buf .= 'Content-Length: '.length($$bdy).$crlf.$crlf;
117 substr($$bdy, 0, 0, $$buf); # prepend header
124 sub git_to_mail { # git->cat_async callback
125 my ($bref, $oid, $type, $size, $arg) = @_;
126 if ($type ne 'blob') {
127 if ($type eq 'missing') {
128 warn "missing $oid\n";
130 warn "unexpected type=$type for $oid\n";
134 my ($write_cb, $kw) = @$arg;
135 $write_cb->($bref, $oid, $kw);
139 sub reap_compress { # dwaitpid callback
140 my ($lei, $pid) = @_;
141 my $cmd = delete $lei->{"pid.$pid"};
143 $lei->fail("@$cmd failed", $? >> 8);
146 # all of these support -c for stdout and -d for decompression,
147 # mutt is commonly distributed with hooks for gz, bz2 and xz, at least
148 # { foo => '' } means "--foo" is passed to the command-line,
149 # otherwise { foo => '--bar' } passes "--bar"
151 gz => [ qw(GZIP pigz gzip), { rsyncable => '', threads => '-p' } ],
152 bz2 => [ 'bzip2', {} ],
153 xz => [ 'xz', { threads => '-T' } ],
154 # XXX does anybody care for these? I prefer zstd on entire FSes,
155 # so it's probably not necessary on a per-file basis
156 # zst => [ 'zstd', { -default => [ qw(-q) ], # it's noisy by default
157 # rsyncable => '', threads => '-T' } ],
158 # zz => [ 'pigz', { -default => [ '--zlib' ],
159 # rsyncable => '', threads => '-p' }],
160 # lzo => [ 'lzop', {} ],
161 # lzma => [ 'lzma', {} ],
165 my ($zsfx, $decompress, $lei) = @_;
166 my $x = $zsfx2cmd{$zsfx} // die "no support for suffix=.$zsfx";
168 my $cmd_opt = pop @info;
169 my @cmd = (undef, $decompress ? qw(-dc) : qw(-c));
170 for my $exe (@info) {
171 # I think respecting client's ENV{GZIP} is OK, not sure
172 # about ENV overrides for other, less-common compressors
173 if ($exe eq uc($exe)) {
174 $exe = $lei->{env}->{$exe} or next;
176 $cmd[0] = which($exe) and last;
178 $cmd[0] // die join(' or ', @info)." missing for .$zsfx";
179 # push @cmd, @{$cmd_opt->{-default}} if $cmd_opt->{-default};
180 for my $bool (qw(rsyncable)) {
181 my $switch = $cmd_opt->{rsyncable} // next;
182 push @cmd, '--'.($switch || $bool);
184 for my $key (qw(threads)) { # support compression level?
185 my $switch = $cmd_opt->{$key} // next;
186 my $val = $lei->{opt}->{$key} // next;
187 push @cmd, $switch, $val;
192 sub _post_augment_mbox { # open a compressor process
193 my ($self, $lei) = @_;
194 my $zsfx = $self->{zsfx} or return;
195 my $cmd = zsfx2cmd($zsfx, undef, $lei);
196 pipe(my ($r, $w)) or die "pipe: $!";
197 my $rdr = { 0 => $r, 1 => $lei->{1}, 2 => $lei->{2} };
198 my $pid = spawn($cmd, $lei->{env}, $rdr);
199 $lei->{"pid.$pid"} = $cmd;
201 tie *$pp, 'PublicInbox::ProcessPipe', $pid, $w, \&reap_compress, $lei;
203 die 'BUG: unexpected {ovv}->{lock_path}' if $lei->{ovv}->{lock_path};
204 $lei->{ovv}->ovv_out_lk_init if ($lei->{opt}->{jobs} // 2) > 1;
207 sub decompress_src ($$$) {
208 my ($in, $zsfx, $lei) = @_;
209 my $cmd = zsfx2cmd($zsfx, 1, $lei);
210 popen_rd($cmd, $lei->{env}, { 0 => $in, 2 => $lei->{2} });
215 # fileno needed because wq_set_recv_modes only used ">&=" for {1}
216 # and Perl blindly trusts that to reject the '+' (readability flag)
217 open my $dup, '+>>&=', fileno($in) or die "dup: $!";
221 # --augment existing output destination, with deduplication
222 sub _augment { # MboxReader eml_cb
223 my ($eml, $lei) = @_;
224 # ignore return value, just populate the skv
225 $lei->{dedupe}->is_dup($eml);
228 sub _mbox_write_cb ($$) {
229 my ($self, $lei) = @_;
230 my $ovv = $lei->{ovv};
231 my $m = 'eml2'.$ovv->{fmt};
232 my $eml2mbox = $self->can($m) or die "$self->$m missing";
233 my $out = $lei->{1} // die "no stdout ($m, $ovv->{dst})"; # redirected earlier
235 my $write = $ovv->{lock_path} ? \&_print_full : \&atomic_append;
236 my $dedupe = $lei->{dedupe};
237 $dedupe->prepare_dedupe;
238 sub { # for git_to_mail
239 my ($buf, $oid, $kw) = @_;
240 my $eml = PublicInbox::Eml->new($buf);
241 if (!$dedupe->is_dup($eml, $oid)) {
242 $buf = $eml2mbox->($eml, $kw);
243 my $lk = $ovv->lock_for_scope;
244 $write->($out, $buf);
249 sub _maildir_each_file ($$;@) {
250 my ($dir, $cb, @arg) = @_;
251 for my $d (qw(new/ cur/)) {
253 opendir my $dh, $pfx or next;
254 while (defined(my $fn = readdir($dh))) {
255 $cb->($pfx.$fn, @arg) if $fn =~ /:2,[A-Za-z]*\z/;
260 sub _augment_file { # _maildir_each_file cb
262 my $eml = PublicInbox::InboxWritable::eml_from_path($f) or return;
263 _augment($eml, $lei);
266 # _maildir_each_file callback, \&CORE::unlink doesn't work with it
267 sub _unlink { unlink($_[0]) }
270 my ($dst, $buf, $oid, $kw) = @_;
271 my $sfx = join('', sort(map { $kw2char{$_} // () } @$kw));
272 my $rand = ''; # chosen by die roll :P
273 my ($tmp, $fh, $final);
275 $tmp = $dst.'tmp/'.$rand."oid=$oid";
276 } while (!sysopen($fh, $tmp, O_CREAT|O_EXCL|O_WRONLY) &&
277 $! == EEXIST && ($rand = int(rand 0x7fffffff).','));
278 if (print $fh $$buf and close($fh)) {
279 $dst .= $sfx eq '' ? 'new/' : 'cur/';
282 $final = $dst.$rand."oid=$oid:2,$sfx";
283 } while (!link($tmp, $final) && $! == EEXIST &&
284 ($rand = int(rand 0x7fffffff).','));
285 unlink($tmp) or warn "W: failed to unlink $tmp: $!\n";
289 die "Error writing $oid to $dst: $err";
293 sub _maildir_write_cb ($$) {
294 my ($self, $lei) = @_;
295 my $dedupe = $lei->{dedupe};
296 $dedupe->prepare_dedupe;
297 my $dst = $lei->{ovv}->{dst};
298 sub { # for git_to_mail
299 my ($buf, $oid, $kw) = @_;
300 return _buf2maildir($dst, $buf, $oid, $kw) if !$dedupe;
301 my $eml = PublicInbox::Eml->new($$buf); # copy buf
302 return if $dedupe->is_dup($eml, $oid);
304 _buf2maildir($dst, $buf, $oid, $kw);
308 sub write_cb { # returns a callback for git_to_mail
309 my ($self, $lei) = @_;
310 # _mbox_write_cb or _maildir_write_cb
311 my $m = "_$self->{base_type}_write_cb";
316 my ($cls, $lei) = @_;
317 my $fmt = $lei->{ovv}->{fmt};
318 my $dst = $lei->{ovv}->{dst};
319 my $self = bless {}, $cls;
320 if ($fmt eq 'maildir') {
321 $self->{base_type} = 'maildir';
322 $lei->{ovv}->{dst} = $dst .= '/' if substr($dst, -1) ne '/';
323 } elsif (substr($fmt, 0, 4) eq 'mbox') {
324 $self->can("eml2$fmt") or die "bad mbox --format=$fmt\n";
325 $self->{base_type} = 'mbox';
327 die "bad mail --format=$fmt\n";
329 $lei->{dedupe} = PublicInbox::LeiDedupe->new($lei);
333 sub _pre_augment_maildir {} # noop
335 sub _do_augment_maildir {
336 my ($self, $lei) = @_;
337 my $dst = $lei->{ovv}->{dst};
338 if ($lei->{opt}->{augment}) {
339 my $dedupe = $lei->{dedupe};
340 if ($dedupe && $dedupe->prepare_dedupe) {
341 require PublicInbox::InboxWritable; # eml_from_path
342 _maildir_each_file($dst, \&_augment_file, $lei);
343 $dedupe->pause_dedupe;
345 } else { # clobber existing Maildir
346 _maildir_each_file($dst, \&_unlink);
350 sub _post_augment_maildir {
351 my ($self, $lei) = @_;
352 my $dst = $lei->{ovv}->{dst};
353 for my $x (qw(tmp new cur)) {
357 File::Path::mkpath($d) or die "mkpath($d): $!";
358 -d $d or die "$d is not a directory";
362 sub _pre_augment_mbox {
363 my ($self, $lei) = @_;
364 my $dst = $lei->{ovv}->{dst};
365 if ($dst ne '/dev/stdout') {
366 my $mode = -p $dst ? '>' : '+>>';
367 if (-f _ && !$lei->{opt}->{augment} and !unlink($dst)) {
368 $! == ENOENT or die "unlink($dst): $!";
370 open my $out, $mode, $dst or die "open($dst): $!";
373 # Perl does SEEK_END even with O_APPEND :<
374 $self->{seekable} = seek($lei->{1}, 0, SEEK_SET);
375 if (!$self->{seekable} && $! != ESPIPE && $dst ne '/dev/stdout') {
376 die "seek($dst): $!\n";
378 state $zsfx_allow = join('|', keys %zsfx2cmd);
379 ($self->{zsfx}) = ($dst =~ /\.($zsfx_allow)\z/);
382 sub _do_augment_mbox {
383 my ($self, $lei) = @_;
384 return if !$lei->{opt}->{augment};
385 my $dedupe = $lei->{dedupe};
386 my $dst = $lei->{ovv}->{dst};
387 die "cannot augment $dst, not seekable\n" if !$self->{seekable};
389 if (-s $out && $dedupe && $dedupe->prepare_dedupe) {
390 my $zsfx = $self->{zsfx};
391 my $rd = $zsfx ? decompress_src($out, $zsfx, $lei) :
393 my $fmt = $lei->{ovv}->{fmt};
394 require PublicInbox::MboxReader;
395 PublicInbox::MboxReader->$fmt($rd, \&_augment, $lei);
397 # maybe some systems don't honor O_APPEND, Perl does this:
398 seek($out, 0, SEEK_END) or die "seek $dst: $!";
399 $dedupe->pause_dedupe if $dedupe;
402 sub pre_augment { # fast (1 disk seek), runs in main daemon
403 my ($self, $lei) = @_;
404 # _pre_augment_maildir, _pre_augment_mbox
405 my $m = "_pre_augment_$self->{base_type}";
409 sub do_augment { # slow, runs in wq worker
410 my ($self, $lei) = @_;
411 # _do_augment_maildir, _do_augment_mbox
412 my $m = "_do_augment_$self->{base_type}";
416 sub post_augment { # fast (spawn compressor or mkdir), runs in main daemon
417 my ($self, $lei) = @_;
418 # _post_augment_maildir, _post_augment_mbox
419 my $m = "_post_augment_$self->{base_type}";
424 $_[0]->{base_type} =~ /\A(?:maildir|mh|imap|jmap)\z/ ? 1 : 0;
427 sub write_mail { # via ->wq_do
428 my ($self, $git_dir, $oid, $lei, $kw) = @_;
429 my $wcb = $self->{wcb} //= do { # first message
430 my %sig = $lei->atfork_child_wq($self);
431 @SIG{keys %sig} = values %sig; # not local
432 $lei->{dedupe}->prepare_dedupe;
433 $self->write_cb($lei);
435 my $git = $self->{"$$\0$git_dir"} //= PublicInbox::Git->new($git_dir);
436 $git->cat_async($oid, \&git_to_mail, [ $wcb, $kw ]);
439 sub ipc_atfork_prepare {
441 # (qry_status_wr, stdout|mbox, stderr, 3: sock, 4: each_smsg_done_wr)
442 $self->wq_set_recv_modes(qw[+<&= >&= >&= +<&= >&=]);
443 $self->SUPER::ipc_atfork_prepare; # PublicInbox::IPC
448 for my $pid_git (grep(/\A$$\0/, keys %$self)) {
449 $self->{$pid_git}->async_wait_all;