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, $smsg) = @_;
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
42 for my $k (@{$smsg->{kw} // []}) {
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;
56 my $ident = $smsg->{blob} // 'lei';
57 if (defined(my $pct = $smsg->{pct})) { $ident .= "=$pct" }
59 substr($$buf, 0, 0, # prepend From line
60 "From $ident\@$type Thu Jan 1 00:00:00 1970$eml->{crlf}");
64 sub atomic_append { # for on-disk destinations (O_APPEND, or O_EXCL)
66 defined(my $w = syswrite($fh, $$buf)) or die "write: $!";
67 $w == length($$buf) or die "short write: $w != ".length($$buf);
72 print $fh $$buf or die "print: $!";
75 sub eml2mboxrd ($;$) {
76 my ($eml, $smsg) = @_;
77 my $buf = _mbox_hdr_buf($eml, 'mboxrd', $smsg);
78 if (my $bdy = delete $eml->{bdy}) {
79 $$bdy =~ s/^(>*From )/>$1/gm;
80 $$buf .= $eml->{crlf};
81 substr($$bdy, 0, 0, $$buf); # prepend header
84 $$buf .= $eml->{crlf};
89 my ($eml, $smsg) = @_;
90 my $buf = _mbox_hdr_buf($eml, 'mboxo', $smsg);
91 if (my $bdy = delete $eml->{bdy}) {
92 $$bdy =~ s/^From />From /gm;
93 $$buf .= $eml->{crlf};
94 substr($$bdy, 0, 0, $$buf); # prepend header
97 $$buf .= $eml->{crlf};
101 sub _mboxcl_common ($$$) {
102 my ($buf, $bdy, $crlf) = @_;
103 # add Lines: so mutt won't have to add it on MUA close
104 my $lines = $$bdy =~ tr!\n!\n!;
105 $$buf .= 'Content-Length: '.length($$bdy).$crlf.
106 'Lines: '.$lines.$crlf.$crlf;
107 substr($$bdy, 0, 0, $$buf); # prepend header
111 # mboxcl still escapes "From " lines
113 my ($eml, $smsg) = @_;
114 my $buf = _mbox_hdr_buf($eml, 'mboxcl', $smsg);
115 my $crlf = $eml->{crlf};
116 if (my $bdy = delete $eml->{bdy}) {
117 $$bdy =~ s/^From />From /gm;
118 _mboxcl_common($buf, $bdy, $crlf);
124 # mboxcl2 has no "From " escaping
126 my ($eml, $smsg) = @_;
127 my $buf = _mbox_hdr_buf($eml, 'mboxcl2', $smsg);
128 my $crlf = $eml->{crlf};
129 if (my $bdy = delete $eml->{bdy}) {
130 _mboxcl_common($buf, $bdy, $crlf);
136 sub git_to_mail { # git->cat_async callback
137 my ($bref, $oid, $type, $size, $arg) = @_;
138 if ($type ne 'blob') {
139 if ($type eq 'missing') {
140 warn "missing $oid\n";
142 warn "unexpected type=$type for $oid\n";
145 my ($write_cb, $smsg) = @$arg;
146 if ($smsg->{blob} ne $oid) {
147 die "BUG: expected=$smsg->{blob} got=$oid";
149 $write_cb->($bref, $smsg) if $size > 0;
152 sub reap_compress { # dwaitpid callback
153 my ($lei, $pid) = @_;
154 my $cmd = delete $lei->{"pid.$pid"};
156 $lei->fail("@$cmd failed", $? >> 8);
159 # all of these support -c for stdout and -d for decompression,
160 # mutt is commonly distributed with hooks for gz, bz2 and xz, at least
161 # { foo => '' } means "--foo" is passed to the command-line,
162 # otherwise { foo => '--bar' } passes "--bar"
164 gz => [ qw(GZIP pigz gzip), { rsyncable => '', threads => '-p' } ],
165 bz2 => [ 'bzip2', {} ],
166 xz => [ 'xz', { threads => '-T' } ],
167 # XXX does anybody care for these? I prefer zstd on entire FSes,
168 # so it's probably not necessary on a per-file basis
169 # zst => [ 'zstd', { -default => [ qw(-q) ], # it's noisy by default
170 # rsyncable => '', threads => '-T' } ],
171 # zz => [ 'pigz', { -default => [ '--zlib' ],
172 # rsyncable => '', threads => '-p' }],
173 # lzo => [ 'lzop', {} ],
174 # lzma => [ 'lzma', {} ],
178 my ($zsfx, $decompress, $lei) = @_;
179 my $x = $zsfx2cmd{$zsfx} // die "no support for suffix=.$zsfx";
181 my $cmd_opt = pop @info;
182 my @cmd = (undef, $decompress ? qw(-dc) : qw(-c));
183 for my $exe (@info) {
184 # I think respecting client's ENV{GZIP} is OK, not sure
185 # about ENV overrides for other, less-common compressors
186 if ($exe eq uc($exe)) {
187 $exe = $lei->{env}->{$exe} or next;
189 $cmd[0] = which($exe) and last;
191 $cmd[0] // die join(' or ', @info)." missing for .$zsfx";
192 # push @cmd, @{$cmd_opt->{-default}} if $cmd_opt->{-default};
193 for my $bool (qw(rsyncable)) {
194 my $switch = $cmd_opt->{rsyncable} // next;
195 push @cmd, '--'.($switch || $bool);
197 for my $key (qw(threads)) { # support compression level?
198 my $switch = $cmd_opt->{$key} // next;
199 my $val = $lei->{opt}->{$key} // next;
200 push @cmd, $switch, $val;
205 sub _post_augment_mbox { # open a compressor process
206 my ($self, $lei, $zpipe) = @_;
207 my $zsfx = $self->{zsfx} or return;
208 my $cmd = zsfx2cmd($zsfx, undef, $lei);
209 my ($r, $w) = splice(@$zpipe, 0, 2);
210 my $rdr = { 0 => $r, 1 => $lei->{1}, 2 => $lei->{2} };
211 my $pid = spawn($cmd, $lei->{env}, $rdr);
213 my $dup = bless { "pid.$pid" => $cmd }, ref($lei);
214 $dup->{$_} = $lei->{$_} for qw(2 sock);
215 tie *$pp, 'PublicInbox::ProcessPipe', $pid, $w, \&reap_compress, $dup;
217 die 'BUG: unexpected {ovv}->{lock_path}' if $lei->{ovv}->{lock_path};
218 $lei->{ovv}->ovv_out_lk_init;
221 sub decompress_src ($$$) {
222 my ($in, $zsfx, $lei) = @_;
223 my $cmd = zsfx2cmd($zsfx, 1, $lei);
224 popen_rd($cmd, $lei->{env}, { 0 => $in, 2 => $lei->{2} });
229 # fileno needed because wq_set_recv_modes only used ">&=" for {1}
230 # and Perl blindly trusts that to reject the '+' (readability flag)
231 open my $dup, '+>>&=', fileno($in) or die "dup: $!";
235 # --augment existing output destination, with deduplication
236 sub _augment { # MboxReader eml_cb
237 my ($eml, $lei) = @_;
238 # ignore return value, just populate the skv
239 $lei->{dedupe}->is_dup($eml);
242 sub _mbox_write_cb ($$) {
243 my ($self, $lei) = @_;
244 my $ovv = $lei->{ovv};
245 my $m = 'eml2'.$ovv->{fmt};
246 my $eml2mbox = $self->can($m) or die "$self->$m missing";
247 my $out = $lei->{1} // die "no stdout ($m, $ovv->{dst})"; # redirected earlier
249 my $write = $ovv->{lock_path} ? \&_print_full : \&atomic_append;
250 my $dedupe = $lei->{dedupe};
251 $dedupe->prepare_dedupe;
252 sub { # for git_to_mail
253 my ($buf, $smsg) = @_;
255 my $eml = PublicInbox::Eml->new($buf);
256 if (!$dedupe->is_dup($eml, $smsg->{blob})) {
257 $buf = $eml2mbox->($eml, $smsg);
258 my $lk = $ovv->lock_for_scope;
259 eval { $write->($out, $buf) };
261 die $@ if ref($@) ne 'PublicInbox::SIGPIPE';
268 sub _maildir_each_file ($$;@) {
269 my ($dir, $cb, @arg) = @_;
270 for my $d (qw(new/ cur/)) {
272 opendir my $dh, $pfx or next;
273 while (defined(my $fn = readdir($dh))) {
274 $cb->($pfx.$fn, @arg) if $fn =~ /:2,[A-Za-z]*\z/;
279 sub _augment_file { # _maildir_each_file cb
281 my $eml = PublicInbox::InboxWritable::eml_from_path($f) or return;
282 _augment($eml, $lei);
285 # _maildir_each_file callback, \&CORE::unlink doesn't work with it
286 sub _unlink { unlink($_[0]) }
289 my ($dst, $buf, $smsg) = @_;
290 my $kw = $smsg->{kw} // [];
291 my $sfx = join('', sort(map { $kw2char{$_} // () } @$kw));
292 my $rand = ''; # chosen by die roll :P
293 my ($tmp, $fh, $final);
294 my $common = $smsg->{blob};
295 if (defined(my $pct = $smsg->{pct})) { $common .= "=$pct" }
297 $tmp = $dst.'tmp/'.$rand.$common;
298 } while (!sysopen($fh, $tmp, O_CREAT|O_EXCL|O_WRONLY) &&
299 $! == EEXIST && ($rand = int(rand 0x7fffffff).','));
300 if (print $fh $$buf and close($fh)) {
301 # ignore new/ and write only to cur/, otherwise MUAs
302 # with R/W access to the Maildir will end up doing
303 # a mass rename which can take a while with thousands
308 $final = $dst.$rand.$common.':2,'.$sfx;
309 } while (!link($tmp, $final) && $! == EEXIST &&
310 ($rand = int(rand 0x7fffffff).','));
311 unlink($tmp) or warn "W: failed to unlink $tmp: $!\n";
315 die "Error writing $smsg->{blob} to $dst: $err";
319 sub _maildir_write_cb ($$) {
320 my ($self, $lei) = @_;
321 my $dedupe = $lei->{dedupe};
322 $dedupe->prepare_dedupe;
323 my $dst = $lei->{ovv}->{dst};
324 sub { # for git_to_mail
325 my ($buf, $smsg) = @_;
326 return _buf2maildir($dst, $buf, $smsg) if !$dedupe;
327 my $eml = PublicInbox::Eml->new($$buf); # copy buf
328 return if $dedupe->is_dup($eml, $smsg->{blob});
330 _buf2maildir($dst, $buf, $smsg);
334 sub write_cb { # returns a callback for git_to_mail
335 my ($self, $lei) = @_;
336 # _mbox_write_cb or _maildir_write_cb
337 my $m = "_$self->{base_type}_write_cb";
342 my ($cls, $lei) = @_;
343 my $fmt = $lei->{ovv}->{fmt};
344 my $dst = $lei->{ovv}->{dst};
345 my $self = bless {}, $cls;
346 if ($fmt eq 'maildir') {
347 $self->{base_type} = 'maildir';
348 -e $dst && !-d _ and die
349 "$dst exists and is not a directory\n";
350 $lei->{ovv}->{dst} = $dst .= '/' if substr($dst, -1) ne '/';
351 } elsif (substr($fmt, 0, 4) eq 'mbox') {
352 (-d $dst || (-e _ && !-w _)) and die
353 "$dst exists and is not a writable file\n";
354 $self->can("eml2$fmt") or die "bad mbox --format=$fmt\n";
355 $self->{base_type} = 'mbox';
357 die "bad mail --format=$fmt\n";
359 $lei->{dedupe} = PublicInbox::LeiDedupe->new($lei);
363 sub _pre_augment_maildir {} # noop
365 sub _do_augment_maildir {
366 my ($self, $lei) = @_;
367 my $dst = $lei->{ovv}->{dst};
368 if ($lei->{opt}->{augment}) {
369 my $dedupe = $lei->{dedupe};
370 if ($dedupe && $dedupe->prepare_dedupe) {
371 require PublicInbox::InboxWritable; # eml_from_path
372 _maildir_each_file($dst, \&_augment_file, $lei);
373 $dedupe->pause_dedupe;
375 } else { # clobber existing Maildir
376 _maildir_each_file($dst, \&_unlink);
380 sub _post_augment_maildir {
381 my ($self, $lei) = @_;
382 my $dst = $lei->{ovv}->{dst};
383 for my $x (qw(tmp new cur)) {
387 File::Path::mkpath($d);
388 -d $d or die "$d is not a directory";
392 sub _pre_augment_mbox {
393 my ($self, $lei) = @_;
394 my $dst = $lei->{ovv}->{dst};
395 if ($dst ne '/dev/stdout') {
396 my $mode = -p $dst ? '>' : '+>>';
397 if (-f _ && !$lei->{opt}->{augment} and !unlink($dst)) {
398 $! == ENOENT or die "unlink($dst): $!";
400 open my $out, $mode, $dst or die "open($dst): $!";
403 # Perl does SEEK_END even with O_APPEND :<
404 $self->{seekable} = seek($lei->{1}, 0, SEEK_SET);
405 if (!$self->{seekable} && $! != ESPIPE && $dst ne '/dev/stdout') {
406 die "seek($dst): $!\n";
408 state $zsfx_allow = join('|', keys %zsfx2cmd);
409 ($self->{zsfx}) = ($dst =~ /\.($zsfx_allow)\z/) or return;
410 pipe(my ($r, $w)) or die "pipe: $!";
414 sub _do_augment_mbox {
415 my ($self, $lei) = @_;
416 return if !$lei->{opt}->{augment};
417 my $dedupe = $lei->{dedupe};
418 my $dst = $lei->{ovv}->{dst};
419 die "cannot augment $dst, not seekable\n" if !$self->{seekable};
421 if (-s $out && $dedupe && $dedupe->prepare_dedupe) {
422 my $zsfx = $self->{zsfx};
423 my $rd = $zsfx ? decompress_src($out, $zsfx, $lei) :
425 my $fmt = $lei->{ovv}->{fmt};
426 require PublicInbox::MboxReader;
427 PublicInbox::MboxReader->$fmt($rd, \&_augment, $lei);
429 # maybe some systems don't honor O_APPEND, Perl does this:
430 seek($out, 0, SEEK_END) or die "seek $dst: $!";
431 $dedupe->pause_dedupe if $dedupe;
434 sub pre_augment { # fast (1 disk seek), runs in main daemon
435 my ($self, $lei) = @_;
436 # _pre_augment_maildir, _pre_augment_mbox
437 my $m = "_pre_augment_$self->{base_type}";
441 sub do_augment { # slow, runs in wq worker
442 my ($self, $lei) = @_;
443 # _do_augment_maildir, _do_augment_mbox
444 my $m = "_do_augment_$self->{base_type}";
448 sub post_augment { # fast (spawn compressor or mkdir), runs in main daemon
449 my ($self, $lei, @args) = @_;
450 # _post_augment_maildir, _post_augment_mbox
451 my $m = "_post_augment_$self->{base_type}";
452 $self->$m($lei, @args);
455 sub write_mail { # via ->wq_do
456 my ($self, $git_dir, $smsg, $lei) = @_;
457 my $not_done = delete $self->{4}; # write end of {each_smsg_done}
458 my $wcb = $self->{wcb} //= do { # first message
459 my %sig = $lei->atfork_child_wq($self);
460 @SIG{keys %sig} = values %sig; # not local
461 $lei->{dedupe}->prepare_dedupe;
462 $self->write_cb($lei);
464 my $git = $self->{"$$\0$git_dir"} //= PublicInbox::Git->new($git_dir);
465 $git->cat_async($smsg->{blob}, \&git_to_mail, [$wcb, $smsg, $not_done]);
468 sub ipc_atfork_prepare {
470 # (qry_status_wr, stdout|mbox, stderr, 3: sock, 4: each_smsg_done_wr)
471 $self->wq_set_recv_modes(qw[+<&= >&= >&= +<&= >&=]);
472 $self->SUPER::ipc_atfork_prepare; # PublicInbox::IPC
477 for my $pid_git (grep(/\A$$\0/, keys %$self)) {
478 $self->{$pid_git}->async_wait_all;
480 $self->SUPER::DESTROY; # PublicInbox::IPC