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;
191 my ($self, $zsfx, $lei) = @_;
192 my $cmd = zsfx2cmd($zsfx, undef, $lei);
193 pipe(my ($r, $w)) or die "pipe: $!";
194 my $rdr = { 0 => $r, 1 => $lei->{1}, 2 => $lei->{2} };
195 my $pid = spawn($cmd, $lei->{env}, $rdr);
196 $lei->{"pid.$pid"} = $cmd;
198 tie *$pp, 'PublicInbox::ProcessPipe', $pid, $w, \&reap_compress, $lei;
200 die 'BUG: unexpected {ovv}->{lock_path}' if $lei->{ovv}->{lock_path};
201 $lei->{ovv}->ovv_out_lk_init if ($lei->{opt}->{jobs} // 2) > 1;
204 sub decompress_src ($$$) {
205 my ($in, $zsfx, $lei) = @_;
206 my $cmd = zsfx2cmd($zsfx, 1, $lei);
207 popen_rd($cmd, $lei->{env}, { 0 => $in, 2 => $lei->{2} });
212 open my $dup, '+>>&', $in or die "dup: $!";
216 # --augment existing output destination, with deduplication
217 sub _augment { # MboxReader eml_cb
218 my ($eml, $lei) = @_;
219 # ignore return value, just populate the skv
220 $lei->{dedupe}->is_dup($eml);
223 sub _mbox_write_cb ($$) {
224 my ($self, $lei) = @_;
225 my $ovv = $lei->{ovv};
226 my $m = 'eml2'.$ovv->{fmt};
227 my $eml2mbox = $self->can($m) or die "$self->$m missing";
228 my $out = $lei->{1} // die "no stdout ($m, $ovv->{dst})"; # redirected earlier
230 my $write = $ovv->{lock_path} ? \&_print_full : \&atomic_append;
231 my $dedupe = $lei->{dedupe};
232 $dedupe->prepare_dedupe;
233 sub { # for git_to_mail
234 my ($buf, $oid, $kw) = @_;
235 my $eml = PublicInbox::Eml->new($buf);
236 if (!$dedupe->is_dup($eml, $oid)) {
237 $buf = $eml2mbox->($eml, $kw);
238 my $lk = $ovv->lock_for_scope;
239 $write->($out, $buf);
244 sub _maildir_each_file ($$;@) {
245 my ($dir, $cb, @arg) = @_;
246 for my $d (qw(new/ cur/)) {
248 opendir my $dh, $pfx or next;
249 while (defined(my $fn = readdir($dh))) {
250 $cb->($pfx.$fn, @arg) if $fn =~ /:2,[A-Za-z]*\z/;
255 sub _augment_file { # _maildir_each_file cb
257 my $eml = PublicInbox::InboxWritable::eml_from_path($f) or return;
258 _augment($eml, $lei);
261 # _maildir_each_file callback, \&CORE::unlink doesn't work with it
262 sub _unlink { unlink($_[0]) }
265 my ($dst, $buf, $oid, $kw) = @_;
266 my $sfx = join('', sort(map { $kw2char{$_} // () } @$kw));
267 my $rand = ''; # chosen by die roll :P
268 my ($tmp, $fh, $final);
270 $tmp = $dst.'tmp/'.$rand."oid=$oid";
271 } while (!sysopen($fh, $tmp, O_CREAT|O_EXCL|O_WRONLY) &&
272 $! == EEXIST && ($rand = int(rand 0x7fffffff).','));
273 if (print $fh $$buf and close($fh)) {
274 $dst .= $sfx eq '' ? 'new/' : 'cur/';
277 $final = $dst.$rand."oid=$oid:2,$sfx";
278 } while (!link($tmp, $final) && $! == EEXIST &&
279 ($rand = int(rand 0x7fffffff).','));
280 unlink($tmp) or warn "W: failed to unlink $tmp: $!\n";
284 die "Error writing $oid to $dst: $err";
288 sub _maildir_write_cb ($$) {
289 my ($self, $lei) = @_;
290 my $dedupe = $lei->{dedupe};
291 $dedupe->prepare_dedupe;
292 my $dst = $lei->{ovv}->{dst};
293 sub { # for git_to_mail
294 my ($buf, $oid, $kw) = @_;
295 return _buf2maildir($dst, $buf, $oid, $kw) if !$dedupe;
296 my $eml = PublicInbox::Eml->new($$buf); # copy buf
297 return if $dedupe->is_dup($eml, $oid);
299 _buf2maildir($dst, $buf, $oid, $kw);
303 sub write_cb { # returns a callback for git_to_mail
304 my ($self, $lei) = @_;
305 # _mbox_write_cb or _maildir_write_cb
306 my $m = "_$self->{base_type}_write_cb";
311 my ($cls, $lei) = @_;
312 my $fmt = $lei->{ovv}->{fmt};
313 my $dst = $lei->{ovv}->{dst};
314 my $self = bless {}, $cls;
315 if ($fmt eq 'maildir') {
316 $self->{base_type} = 'maildir';
317 $lei->{ovv}->{dst} = $dst .= '/' if substr($dst, -1) ne '/';
318 } elsif (substr($fmt, 0, 4) eq 'mbox') {
319 $self->can("eml2$fmt") or die "bad mbox --format=$fmt\n";
320 $self->{base_type} = 'mbox';
322 die "bad mail --format=$fmt\n";
324 my $dedupe = $lei->{dedupe} //= PublicInbox::LeiDedupe->new($lei, $dst);
328 sub _prepare_maildir {
329 my ($self, $lei) = @_;
330 my $dst = $lei->{ovv}->{dst};
331 if ($lei->{opt}->{augment}) {
332 my $dedupe = $lei->{dedupe};
333 if ($dedupe && $dedupe->prepare_dedupe) {
334 require PublicInbox::InboxWritable; # eml_from_path
335 _maildir_each_file($dst, \&_augment_file, $lei);
336 $dedupe->pause_dedupe;
338 } else { # clobber existing Maildir
339 _maildir_each_file($dst, \&_unlink);
341 for my $x (qw(tmp new cur)) {
345 File::Path::mkpath($d) or die "mkpath($d): $!";
346 -d $d or die "$d is not a directory";
351 my ($self, $lei) = @_;
352 my $dst = $lei->{ovv}->{dst};
353 my ($out, $seekable);
354 if ($dst eq '/dev/stdout') {
357 my $mode = -p $dst ? '>' : '+>>';
358 if (-f _ && !$lei->{opt}->{augment} and !unlink($dst)) {
359 $! == ENOENT or die "unlink($dst): $!";
361 open $out, $mode, $dst or die "open($dst): $!";
362 # Perl does SEEK_END even with O_APPEND :<
363 $seekable = seek($out, 0, SEEK_SET);
364 die "seek($dst): $!\n" if !$seekable && $! != ESPIPE;
367 state $zsfx_allow = join('|', keys %zsfx2cmd);
368 my ($zsfx) = ($dst =~ /\.($zsfx_allow)\z/);
369 my $dedupe = $lei->{dedupe};
370 if ($lei->{opt}->{augment}) {
371 die "cannot augment $dst, not seekable\n" if !$seekable;
372 if (-s $out && $dedupe && $dedupe->prepare_dedupe) {
373 my $rd = $zsfx ? decompress_src($out, $zsfx, $lei) :
375 my $fmt = $lei->{ovv}->{fmt};
376 require PublicInbox::MboxReader;
377 PublicInbox::MboxReader->$fmt($rd, \&_augment, $lei);
379 # maybe some systems don't honor O_APPEND, Perl does this:
380 seek($out, 0, SEEK_END) or die "seek $dst: $!";
381 $dedupe->pause_dedupe if $dedupe;
383 compress_dst($self, $zsfx, $lei) if $zsfx;
387 my ($self, $lei) = @_;
388 my $m = "_prepare_$self->{base_type}";