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;
10 use PublicInbox::ProcessPipe;
11 use PublicInbox::Spawn qw(which spawn popen_rd);
12 use PublicInbox::LeiDedupe;
13 use Symbol qw(gensym);
14 use IO::Handle; # ->autoflush
15 use Fcntl qw(SEEK_SET SEEK_END O_CREAT O_EXCL O_WRONLY);
16 use Errno qw(EEXIST ESPIPE ENOENT);
18 my %kw2char = ( # Maildir characters
26 flagged => [ 'X-Status' => 'F' ],
27 answered => [ 'X-Status' => 'A' ],
28 seen => [ 'Status' => 'R' ],
29 draft => [ 'X-Status' => 'T' ],
32 sub _mbox_hdr_buf ($$$) {
33 my ($eml, $type, $kw) = @_;
34 $eml->header_set($_) for (qw(Lines Bytes Content-Length));
35 my %hdr; # set Status, X-Status
37 if (my $ent = $kw2status{$k}) {
38 push @{$hdr{$ent->[0]}}, $ent->[1];
40 warn "TODO: keyword `$k' not supported for mbox\n";
43 while (my ($name, $chars) = each %hdr) {
44 $eml->header_set($name, join('', sort @$chars));
46 my $buf = delete $eml->{hdr};
48 # fixup old bug from import (pre-a0c07cba0e5d8b6a)
49 $$buf =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
51 substr($$buf, 0, 0, # prepend From line
52 "From lei\@$type Thu Jan 1 00:00:00 1970$eml->{crlf}");
56 sub atomic_append { # for on-disk destinations (O_APPEND, or O_EXCL)
58 defined(my $w = syswrite($fh, $$buf)) or die "write: $!";
59 $w == length($$buf) or die "short write: $w != ".length($$buf);
64 print $fh $$buf or die "print: $!";
67 sub eml2mboxrd ($;$) {
69 my $buf = _mbox_hdr_buf($eml, 'mboxrd', $kw);
70 if (my $bdy = delete $eml->{bdy}) {
71 $$bdy =~ s/^(>*From )/>$1/gm;
72 $$buf .= $eml->{crlf};
73 substr($$bdy, 0, 0, $$buf); # prepend header
76 $$buf .= $eml->{crlf};
82 my $buf = _mbox_hdr_buf($eml, 'mboxo', $kw);
83 if (my $bdy = delete $eml->{bdy}) {
84 $$bdy =~ s/^From />From /gm;
85 $$buf .= $eml->{crlf};
86 substr($$bdy, 0, 0, $$buf); # prepend header
89 $$buf .= $eml->{crlf};
93 # mboxcl still escapes "From " lines
96 my $buf = _mbox_hdr_buf($eml, 'mboxcl', $kw);
97 my $crlf = $eml->{crlf};
98 if (my $bdy = delete $eml->{bdy}) {
99 $$bdy =~ s/^From />From /gm;
100 $$buf .= 'Content-Length: '.length($$bdy).$crlf.$crlf;
101 substr($$bdy, 0, 0, $$buf); # prepend header
108 # mboxcl2 has no "From " escaping
111 my $buf = _mbox_hdr_buf($eml, 'mboxcl2', $kw);
112 my $crlf = $eml->{crlf};
113 if (my $bdy = delete $eml->{bdy}) {
114 $$buf .= 'Content-Length: '.length($$bdy).$crlf.$crlf;
115 substr($$bdy, 0, 0, $$buf); # prepend header
122 sub git_to_mail { # git->cat_async callback
123 my ($bref, $oid, $type, $size, $arg) = @_;
124 if ($type ne 'blob') {
125 if ($type eq 'missing') {
126 warn "missing $oid\n";
128 warn "unexpected type=$type for $oid\n";
132 my ($write_cb, $kw) = @$arg;
133 $write_cb->($bref, $oid, $kw);
137 sub reap_compress { # dwaitpid callback
138 my ($lei, $pid) = @_;
139 my $cmd = delete $lei->{"pid.$pid"};
141 $lei->fail("@$cmd failed", $? >> 8);
144 # all of these support -c for stdout and -d for decompression,
145 # mutt is commonly distributed with hooks for gz, bz2 and xz, at least
146 # { foo => '' } means "--foo" is passed to the command-line,
147 # otherwise { foo => '--bar' } passes "--bar"
149 gz => [ qw(GZIP pigz gzip), { rsyncable => '', threads => '-p' } ],
150 bz2 => [ 'bzip2', {} ],
151 xz => [ 'xz', { threads => '-T' } ],
152 # XXX does anybody care for these? I prefer zstd on entire FSes,
153 # so it's probably not necessary on a per-file basis
154 # zst => [ 'zstd', { -default => [ qw(-q) ], # it's noisy by default
155 # rsyncable => '', threads => '-T' } ],
156 # zz => [ 'pigz', { -default => [ '--zlib' ],
157 # rsyncable => '', threads => '-p' }],
158 # lzo => [ 'lzop', {} ],
159 # lzma => [ 'lzma', {} ],
163 my ($zsfx, $decompress, $lei) = @_;
164 my $x = $zsfx2cmd{$zsfx} // die "no support for suffix=.$zsfx";
166 my $cmd_opt = pop @info;
167 my @cmd = (undef, $decompress ? qw(-dc) : qw(-c));
168 for my $exe (@info) {
169 # I think respecting client's ENV{GZIP} is OK, not sure
170 # about ENV overrides for other, less-common compressors
171 if ($exe eq uc($exe)) {
172 $exe = $lei->{env}->{$exe} or next;
174 $cmd[0] = which($exe) and last;
176 $cmd[0] // die join(' or ', @info)." missing for .$zsfx";
177 # push @cmd, @{$cmd_opt->{-default}} if $cmd_opt->{-default};
178 for my $bool (qw(rsyncable)) {
179 my $switch = $cmd_opt->{rsyncable} // next;
180 push @cmd, '--'.($switch || $bool);
182 for my $key (qw(threads)) { # support compression level?
183 my $switch = $cmd_opt->{$key} // next;
184 my $val = $lei->{opt}->{$key} // next;
185 push @cmd, $switch, $val;
190 sub _post_augment_mbox { # open a compressor process
191 my ($self, $lei) = @_;
192 my $zsfx = $self->{zsfx} or return;
193 my $cmd = zsfx2cmd($zsfx, undef, $lei);
194 pipe(my ($r, $w)) or die "pipe: $!";
195 my $rdr = { 0 => $r, 1 => $lei->{1}, 2 => $lei->{2} };
196 my $pid = spawn($cmd, $lei->{env}, $rdr);
197 $lei->{"pid.$pid"} = $cmd;
199 tie *$pp, 'PublicInbox::ProcessPipe', $pid, $w, \&reap_compress, $lei;
201 die 'BUG: unexpected {ovv}->{lock_path}' if $lei->{ovv}->{lock_path};
202 $lei->{ovv}->ovv_out_lk_init if ($lei->{opt}->{jobs} // 2) > 1;
205 sub decompress_src ($$$) {
206 my ($in, $zsfx, $lei) = @_;
207 my $cmd = zsfx2cmd($zsfx, 1, $lei);
208 popen_rd($cmd, $lei->{env}, { 0 => $in, 2 => $lei->{2} });
213 # fileno needed because wq_set_recv_modes only used ">&=" for {1}
214 # and Perl blindly trusts that to reject the '+' (readability flag)
215 open my $dup, '+>>&=', fileno($in) or die "dup: $!";
219 # --augment existing output destination, with deduplication
220 sub _augment { # MboxReader eml_cb
221 my ($eml, $lei) = @_;
222 # ignore return value, just populate the skv
223 $lei->{dedupe}->is_dup($eml);
226 sub _mbox_write_cb ($$) {
227 my ($self, $lei) = @_;
228 my $ovv = $lei->{ovv};
229 my $m = 'eml2'.$ovv->{fmt};
230 my $eml2mbox = $self->can($m) or die "$self->$m missing";
231 my $out = $lei->{1} // die "no stdout ($m, $ovv->{dst})"; # redirected earlier
233 my $write = $ovv->{lock_path} ? \&_print_full : \&atomic_append;
234 my $dedupe = $lei->{dedupe};
235 $dedupe->prepare_dedupe;
236 sub { # for git_to_mail
237 my ($buf, $oid, $kw) = @_;
238 my $eml = PublicInbox::Eml->new($buf);
239 if (!$dedupe->is_dup($eml, $oid)) {
240 $buf = $eml2mbox->($eml, $kw);
241 my $lk = $ovv->lock_for_scope;
242 $write->($out, $buf);
247 sub _maildir_each_file ($$;@) {
248 my ($dir, $cb, @arg) = @_;
249 for my $d (qw(new/ cur/)) {
251 opendir my $dh, $pfx or next;
252 while (defined(my $fn = readdir($dh))) {
253 $cb->($pfx.$fn, @arg) if $fn =~ /:2,[A-Za-z]*\z/;
258 sub _augment_file { # _maildir_each_file cb
260 my $eml = PublicInbox::InboxWritable::eml_from_path($f) or return;
261 _augment($eml, $lei);
264 # _maildir_each_file callback, \&CORE::unlink doesn't work with it
265 sub _unlink { unlink($_[0]) }
268 my ($dst, $buf, $oid, $kw) = @_;
269 my $sfx = join('', sort(map { $kw2char{$_} // () } @$kw));
270 my $rand = ''; # chosen by die roll :P
271 my ($tmp, $fh, $final);
273 $tmp = $dst.'tmp/'.$rand."oid=$oid";
274 } while (!sysopen($fh, $tmp, O_CREAT|O_EXCL|O_WRONLY) &&
275 $! == EEXIST && ($rand = int(rand 0x7fffffff).','));
276 if (print $fh $$buf and close($fh)) {
277 $dst .= $sfx eq '' ? 'new/' : 'cur/';
280 $final = $dst.$rand."oid=$oid:2,$sfx";
281 } while (!link($tmp, $final) && $! == EEXIST &&
282 ($rand = int(rand 0x7fffffff).','));
283 unlink($tmp) or warn "W: failed to unlink $tmp: $!\n";
287 die "Error writing $oid to $dst: $err";
291 sub _maildir_write_cb ($$) {
292 my ($self, $lei) = @_;
293 my $dedupe = $lei->{dedupe};
294 $dedupe->prepare_dedupe;
295 my $dst = $lei->{ovv}->{dst};
296 sub { # for git_to_mail
297 my ($buf, $oid, $kw) = @_;
298 return _buf2maildir($dst, $buf, $oid, $kw) if !$dedupe;
299 my $eml = PublicInbox::Eml->new($$buf); # copy buf
300 return if $dedupe->is_dup($eml, $oid);
302 _buf2maildir($dst, $buf, $oid, $kw);
306 sub write_cb { # returns a callback for git_to_mail
307 my ($self, $lei) = @_;
308 # _mbox_write_cb or _maildir_write_cb
309 my $m = "_$self->{base_type}_write_cb";
314 my ($cls, $lei) = @_;
315 my $fmt = $lei->{ovv}->{fmt};
316 my $dst = $lei->{ovv}->{dst};
317 my $self = bless {}, $cls;
318 if ($fmt eq 'maildir') {
319 $self->{base_type} = 'maildir';
320 $lei->{ovv}->{dst} = $dst .= '/' if substr($dst, -1) ne '/';
321 } elsif (substr($fmt, 0, 4) eq 'mbox') {
322 $self->can("eml2$fmt") or die "bad mbox --format=$fmt\n";
323 $self->{base_type} = 'mbox';
325 die "bad mail --format=$fmt\n";
327 $lei->{dedupe} = PublicInbox::LeiDedupe->new($lei);
331 sub _pre_augment_maildir {} # noop
333 sub _do_augment_maildir {
334 my ($self, $lei) = @_;
335 my $dst = $lei->{ovv}->{dst};
336 if ($lei->{opt}->{augment}) {
337 my $dedupe = $lei->{dedupe};
338 if ($dedupe && $dedupe->prepare_dedupe) {
339 require PublicInbox::InboxWritable; # eml_from_path
340 _maildir_each_file($dst, \&_augment_file, $lei);
341 $dedupe->pause_dedupe;
343 } else { # clobber existing Maildir
344 _maildir_each_file($dst, \&_unlink);
348 sub _post_augment_maildir {
349 my ($self, $lei) = @_;
350 my $dst = $lei->{ovv}->{dst};
351 for my $x (qw(tmp new cur)) {
355 File::Path::mkpath($d) or die "mkpath($d): $!";
356 -d $d or die "$d is not a directory";
360 sub _pre_augment_mbox {
361 my ($self, $lei) = @_;
362 my $dst = $lei->{ovv}->{dst};
363 if ($dst ne '/dev/stdout') {
364 my $mode = -p $dst ? '>' : '+>>';
365 if (-f _ && !$lei->{opt}->{augment} and !unlink($dst)) {
366 $! == ENOENT or die "unlink($dst): $!";
368 open my $out, $mode, $dst or die "open($dst): $!";
371 # Perl does SEEK_END even with O_APPEND :<
372 $self->{seekable} = seek($lei->{1}, 0, SEEK_SET);
373 if (!$self->{seekable} && $! != ESPIPE && $dst ne '/dev/stdout') {
374 die "seek($dst): $!\n";
376 state $zsfx_allow = join('|', keys %zsfx2cmd);
377 ($self->{zsfx}) = ($dst =~ /\.($zsfx_allow)\z/);
380 sub _do_augment_mbox {
381 my ($self, $lei) = @_;
382 return if !$lei->{opt}->{augment};
383 my $dedupe = $lei->{dedupe};
384 my $dst = $lei->{ovv}->{dst};
385 die "cannot augment $dst, not seekable\n" if !$self->{seekable};
387 if (-s $out && $dedupe && $dedupe->prepare_dedupe) {
388 my $zsfx = $self->{zsfx};
389 my $rd = $zsfx ? decompress_src($out, $zsfx, $lei) :
391 my $fmt = $lei->{ovv}->{fmt};
392 require PublicInbox::MboxReader;
393 PublicInbox::MboxReader->$fmt($rd, \&_augment, $lei);
395 # maybe some systems don't honor O_APPEND, Perl does this:
396 seek($out, 0, SEEK_END) or die "seek $dst: $!";
397 $dedupe->pause_dedupe if $dedupe;
400 sub pre_augment { # fast (1 disk seek), runs in main daemon
401 my ($self, $lei) = @_;
402 # _pre_augment_maildir, _pre_augment_mbox
403 my $m = "_pre_augment_$self->{base_type}";
407 sub do_augment { # slow, runs in wq worker
408 my ($self, $lei) = @_;
409 # _do_augment_maildir, _do_augment_mbox
410 my $m = "_do_augment_$self->{base_type}";
414 sub post_augment { # fast (spawn compressor or mkdir), runs in main daemon
415 my ($self, $lei) = @_;
416 # _post_augment_maildir, _post_augment_mbox
417 my $m = "_post_augment_$self->{base_type}";
422 $_[0]->{base_type} =~ /\A(?:maildir|mh|imap|jmap)\z/ ? 1 : 0;