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));
38 # Messages are always 'O' (non-\Recent in IMAP), it saves
39 # MUAs the trouble of rewriting the mbox if no other
41 my %hdr = (Status => [ 'O' ]); # set Status, X-Status
43 if (my $ent = $kw2status{$k}) {
44 push @{$hdr{$ent->[0]}}, $ent->[1];
46 warn "TODO: keyword `$k' not supported for mbox\n";
49 while (my ($name, $chars) = each %hdr) {
50 $eml->header_set($name, join('', sort @$chars));
52 my $buf = delete $eml->{hdr};
54 # fixup old bug from import (pre-a0c07cba0e5d8b6a)
55 $$buf =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
57 substr($$buf, 0, 0, # prepend From line
58 "From lei\@$type Thu Jan 1 00:00:00 1970$eml->{crlf}");
62 sub atomic_append { # for on-disk destinations (O_APPEND, or O_EXCL)
64 defined(my $w = syswrite($fh, $$buf)) or die "write: $!";
65 $w == length($$buf) or die "short write: $w != ".length($$buf);
70 print $fh $$buf or die "print: $!";
73 sub eml2mboxrd ($;$) {
75 my $buf = _mbox_hdr_buf($eml, 'mboxrd', $kw);
76 if (my $bdy = delete $eml->{bdy}) {
77 $$bdy =~ s/^(>*From )/>$1/gm;
78 $$buf .= $eml->{crlf};
79 substr($$bdy, 0, 0, $$buf); # prepend header
82 $$buf .= $eml->{crlf};
88 my $buf = _mbox_hdr_buf($eml, 'mboxo', $kw);
89 if (my $bdy = delete $eml->{bdy}) {
90 $$bdy =~ s/^From />From /gm;
91 $$buf .= $eml->{crlf};
92 substr($$bdy, 0, 0, $$buf); # prepend header
95 $$buf .= $eml->{crlf};
99 sub _mboxcl_common ($$$) {
100 my ($buf, $bdy, $crlf) = @_;
101 # add Lines: so mutt won't have to add it on MUA close
102 my $lines = $$bdy =~ tr!\n!\n!;
103 $$buf .= 'Content-Length: '.length($$bdy).$crlf.
104 'Lines: '.$lines.$crlf.$crlf;
105 substr($$bdy, 0, 0, $$buf); # prepend header
109 # mboxcl still escapes "From " lines
112 my $buf = _mbox_hdr_buf($eml, 'mboxcl', $kw);
113 my $crlf = $eml->{crlf};
114 if (my $bdy = delete $eml->{bdy}) {
115 $$bdy =~ s/^From />From /gm;
116 _mboxcl_common($buf, $bdy, $crlf);
122 # mboxcl2 has no "From " escaping
125 my $buf = _mbox_hdr_buf($eml, 'mboxcl2', $kw);
126 my $crlf = $eml->{crlf};
127 if (my $bdy = delete $eml->{bdy}) {
128 _mboxcl_common($buf, $bdy, $crlf);
134 sub git_to_mail { # git->cat_async callback
135 my ($bref, $oid, $type, $size, $arg) = @_;
136 if ($type ne 'blob') {
137 if ($type eq 'missing') {
138 warn "missing $oid\n";
140 warn "unexpected type=$type for $oid\n";
144 my ($write_cb, $kw) = @$arg;
145 $write_cb->($bref, $oid, $kw);
149 sub reap_compress { # dwaitpid callback
150 my ($lei, $pid) = @_;
151 my $cmd = delete $lei->{"pid.$pid"};
153 $lei->fail("@$cmd failed", $? >> 8);
156 # all of these support -c for stdout and -d for decompression,
157 # mutt is commonly distributed with hooks for gz, bz2 and xz, at least
158 # { foo => '' } means "--foo" is passed to the command-line,
159 # otherwise { foo => '--bar' } passes "--bar"
161 gz => [ qw(GZIP pigz gzip), { rsyncable => '', threads => '-p' } ],
162 bz2 => [ 'bzip2', {} ],
163 xz => [ 'xz', { threads => '-T' } ],
164 # XXX does anybody care for these? I prefer zstd on entire FSes,
165 # so it's probably not necessary on a per-file basis
166 # zst => [ 'zstd', { -default => [ qw(-q) ], # it's noisy by default
167 # rsyncable => '', threads => '-T' } ],
168 # zz => [ 'pigz', { -default => [ '--zlib' ],
169 # rsyncable => '', threads => '-p' }],
170 # lzo => [ 'lzop', {} ],
171 # lzma => [ 'lzma', {} ],
175 my ($zsfx, $decompress, $lei) = @_;
176 my $x = $zsfx2cmd{$zsfx} // die "no support for suffix=.$zsfx";
178 my $cmd_opt = pop @info;
179 my @cmd = (undef, $decompress ? qw(-dc) : qw(-c));
180 for my $exe (@info) {
181 # I think respecting client's ENV{GZIP} is OK, not sure
182 # about ENV overrides for other, less-common compressors
183 if ($exe eq uc($exe)) {
184 $exe = $lei->{env}->{$exe} or next;
186 $cmd[0] = which($exe) and last;
188 $cmd[0] // die join(' or ', @info)." missing for .$zsfx";
189 # push @cmd, @{$cmd_opt->{-default}} if $cmd_opt->{-default};
190 for my $bool (qw(rsyncable)) {
191 my $switch = $cmd_opt->{rsyncable} // next;
192 push @cmd, '--'.($switch || $bool);
194 for my $key (qw(threads)) { # support compression level?
195 my $switch = $cmd_opt->{$key} // next;
196 my $val = $lei->{opt}->{$key} // next;
197 push @cmd, $switch, $val;
202 sub _post_augment_mbox { # open a compressor process
203 my ($self, $lei) = @_;
204 my $zsfx = $self->{zsfx} or return;
205 my $cmd = zsfx2cmd($zsfx, undef, $lei);
206 pipe(my ($r, $w)) or die "pipe: $!";
207 my $rdr = { 0 => $r, 1 => $lei->{1}, 2 => $lei->{2} };
208 my $pid = spawn($cmd, $lei->{env}, $rdr);
209 $lei->{"pid.$pid"} = $cmd;
211 tie *$pp, 'PublicInbox::ProcessPipe', $pid, $w, \&reap_compress, $lei;
213 die 'BUG: unexpected {ovv}->{lock_path}' if $lei->{ovv}->{lock_path};
214 $lei->{ovv}->ovv_out_lk_init if ($lei->{opt}->{jobs} // 2) > 1;
217 sub decompress_src ($$$) {
218 my ($in, $zsfx, $lei) = @_;
219 my $cmd = zsfx2cmd($zsfx, 1, $lei);
220 popen_rd($cmd, $lei->{env}, { 0 => $in, 2 => $lei->{2} });
225 # fileno needed because wq_set_recv_modes only used ">&=" for {1}
226 # and Perl blindly trusts that to reject the '+' (readability flag)
227 open my $dup, '+>>&=', fileno($in) or die "dup: $!";
231 # --augment existing output destination, with deduplication
232 sub _augment { # MboxReader eml_cb
233 my ($eml, $lei) = @_;
234 # ignore return value, just populate the skv
235 $lei->{dedupe}->is_dup($eml);
238 sub _mbox_write_cb ($$) {
239 my ($self, $lei) = @_;
240 my $ovv = $lei->{ovv};
241 my $m = 'eml2'.$ovv->{fmt};
242 my $eml2mbox = $self->can($m) or die "$self->$m missing";
243 my $out = $lei->{1} // die "no stdout ($m, $ovv->{dst})"; # redirected earlier
245 my $write = $ovv->{lock_path} ? \&_print_full : \&atomic_append;
246 my $dedupe = $lei->{dedupe};
247 $dedupe->prepare_dedupe;
248 sub { # for git_to_mail
249 my ($buf, $oid, $kw) = @_;
251 my $eml = PublicInbox::Eml->new($buf);
252 if (!$dedupe->is_dup($eml, $oid)) {
253 $buf = $eml2mbox->($eml, $kw);
254 my $lk = $ovv->lock_for_scope;
255 eval { $write->($out, $buf) };
257 die $@ if ref($@) ne 'PublicInbox::SIGPIPE';
264 sub _maildir_each_file ($$;@) {
265 my ($dir, $cb, @arg) = @_;
266 for my $d (qw(new/ cur/)) {
268 opendir my $dh, $pfx or next;
269 while (defined(my $fn = readdir($dh))) {
270 $cb->($pfx.$fn, @arg) if $fn =~ /:2,[A-Za-z]*\z/;
275 sub _augment_file { # _maildir_each_file cb
277 my $eml = PublicInbox::InboxWritable::eml_from_path($f) or return;
278 _augment($eml, $lei);
281 # _maildir_each_file callback, \&CORE::unlink doesn't work with it
282 sub _unlink { unlink($_[0]) }
285 my ($dst, $buf, $oid, $kw) = @_;
286 my $sfx = join('', sort(map { $kw2char{$_} // () } @$kw));
287 my $rand = ''; # chosen by die roll :P
288 my ($tmp, $fh, $final);
290 $tmp = $dst.'tmp/'.$rand."oid=$oid";
291 } while (!sysopen($fh, $tmp, O_CREAT|O_EXCL|O_WRONLY) &&
292 $! == EEXIST && ($rand = int(rand 0x7fffffff).','));
293 if (print $fh $$buf and close($fh)) {
294 # ignore new/ and write only to cur/, otherwise MUAs
295 # with R/W access to the Maildir will end up doing
296 # a mass rename which can take a while with thousands
301 $final = $dst.$rand."oid=$oid:2,$sfx";
302 } while (!link($tmp, $final) && $! == EEXIST &&
303 ($rand = int(rand 0x7fffffff).','));
304 unlink($tmp) or warn "W: failed to unlink $tmp: $!\n";
308 die "Error writing $oid to $dst: $err";
312 sub _maildir_write_cb ($$) {
313 my ($self, $lei) = @_;
314 my $dedupe = $lei->{dedupe};
315 $dedupe->prepare_dedupe;
316 my $dst = $lei->{ovv}->{dst};
317 sub { # for git_to_mail
318 my ($buf, $oid, $kw) = @_;
319 return _buf2maildir($dst, $buf, $oid, $kw) if !$dedupe;
320 my $eml = PublicInbox::Eml->new($$buf); # copy buf
321 return if $dedupe->is_dup($eml, $oid);
323 _buf2maildir($dst, $buf, $oid, $kw);
327 sub write_cb { # returns a callback for git_to_mail
328 my ($self, $lei) = @_;
329 # _mbox_write_cb or _maildir_write_cb
330 my $m = "_$self->{base_type}_write_cb";
335 my ($cls, $lei) = @_;
336 my $fmt = $lei->{ovv}->{fmt};
337 my $dst = $lei->{ovv}->{dst};
338 my $self = bless {}, $cls;
339 if ($fmt eq 'maildir') {
340 $self->{base_type} = 'maildir';
341 $lei->{ovv}->{dst} = $dst .= '/' if substr($dst, -1) ne '/';
342 } elsif (substr($fmt, 0, 4) eq 'mbox') {
343 $self->can("eml2$fmt") or die "bad mbox --format=$fmt\n";
344 $self->{base_type} = 'mbox';
346 die "bad mail --format=$fmt\n";
348 $lei->{dedupe} = PublicInbox::LeiDedupe->new($lei);
352 sub _pre_augment_maildir {} # noop
354 sub _do_augment_maildir {
355 my ($self, $lei) = @_;
356 my $dst = $lei->{ovv}->{dst};
357 if ($lei->{opt}->{augment}) {
358 my $dedupe = $lei->{dedupe};
359 if ($dedupe && $dedupe->prepare_dedupe) {
360 require PublicInbox::InboxWritable; # eml_from_path
361 _maildir_each_file($dst, \&_augment_file, $lei);
362 $dedupe->pause_dedupe;
364 } else { # clobber existing Maildir
365 _maildir_each_file($dst, \&_unlink);
369 sub _post_augment_maildir {
370 my ($self, $lei) = @_;
371 my $dst = $lei->{ovv}->{dst};
372 for my $x (qw(tmp new cur)) {
376 File::Path::mkpath($d) or die "mkpath($d): $!";
377 -d $d or die "$d is not a directory";
381 sub _pre_augment_mbox {
382 my ($self, $lei) = @_;
383 my $dst = $lei->{ovv}->{dst};
384 if ($dst ne '/dev/stdout') {
385 my $mode = -p $dst ? '>' : '+>>';
386 if (-f _ && !$lei->{opt}->{augment} and !unlink($dst)) {
387 $! == ENOENT or die "unlink($dst): $!";
389 open my $out, $mode, $dst or die "open($dst): $!";
392 # Perl does SEEK_END even with O_APPEND :<
393 $self->{seekable} = seek($lei->{1}, 0, SEEK_SET);
394 if (!$self->{seekable} && $! != ESPIPE && $dst ne '/dev/stdout') {
395 die "seek($dst): $!\n";
397 state $zsfx_allow = join('|', keys %zsfx2cmd);
398 ($self->{zsfx}) = ($dst =~ /\.($zsfx_allow)\z/);
401 sub _do_augment_mbox {
402 my ($self, $lei) = @_;
403 return if !$lei->{opt}->{augment};
404 my $dedupe = $lei->{dedupe};
405 my $dst = $lei->{ovv}->{dst};
406 die "cannot augment $dst, not seekable\n" if !$self->{seekable};
408 if (-s $out && $dedupe && $dedupe->prepare_dedupe) {
409 my $zsfx = $self->{zsfx};
410 my $rd = $zsfx ? decompress_src($out, $zsfx, $lei) :
412 my $fmt = $lei->{ovv}->{fmt};
413 require PublicInbox::MboxReader;
414 PublicInbox::MboxReader->$fmt($rd, \&_augment, $lei);
416 # maybe some systems don't honor O_APPEND, Perl does this:
417 seek($out, 0, SEEK_END) or die "seek $dst: $!";
418 $dedupe->pause_dedupe if $dedupe;
421 sub pre_augment { # fast (1 disk seek), runs in main daemon
422 my ($self, $lei) = @_;
423 # _pre_augment_maildir, _pre_augment_mbox
424 my $m = "_pre_augment_$self->{base_type}";
428 sub do_augment { # slow, runs in wq worker
429 my ($self, $lei) = @_;
430 # _do_augment_maildir, _do_augment_mbox
431 my $m = "_do_augment_$self->{base_type}";
435 sub post_augment { # fast (spawn compressor or mkdir), runs in main daemon
436 my ($self, $lei) = @_;
437 # _post_augment_maildir, _post_augment_mbox
438 my $m = "_post_augment_$self->{base_type}";
443 $_[0]->{base_type} =~ /\A(?:maildir|mh|imap|jmap)\z/ ? 1 : 0;
446 sub write_mail { # via ->wq_do
447 my ($self, $git_dir, $oid, $lei, $kw) = @_;
448 my $not_done = delete $self->{4}; # write end of {each_smsg_done}
449 my $wcb = $self->{wcb} //= do { # first message
450 my %sig = $lei->atfork_child_wq($self);
451 @SIG{keys %sig} = values %sig; # not local
452 $lei->{dedupe}->prepare_dedupe;
453 $self->write_cb($lei);
455 my $git = $self->{"$$\0$git_dir"} //= PublicInbox::Git->new($git_dir);
456 $git->cat_async($oid, \&git_to_mail, [ $wcb, $kw, $not_done ]);
459 sub ipc_atfork_prepare {
461 # (qry_status_wr, stdout|mbox, stderr, 3: sock, 4: each_smsg_done_wr)
462 $self->wq_set_recv_modes(qw[+<&= >&= >&= +<&= >&=]);
463 $self->SUPER::ipc_atfork_prepare; # PublicInbox::IPC
468 for my $pid_git (grep(/\A$$\0/, keys %$self)) {
469 $self->{$pid_git}->async_wait_all;