]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiToMail.pm
lei_to_mail: support for non-seekable outputs
[public-inbox.git] / lib / PublicInbox / LeiToMail.pm
1 # Copyright (C) 2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # Writes PublicInbox::Eml objects atomically to a mbox variant or Maildir
5 package PublicInbox::LeiToMail;
6 use strict;
7 use v5.10.1;
8 use PublicInbox::Eml;
9 use PublicInbox::Lock;
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);
16
17 my %kw2char = ( # Maildir characters
18         draft => 'D',
19         flagged => 'F',
20         answered => 'R',
21         seen => 'S'
22 );
23
24 my %kw2status = (
25         flagged => [ 'X-Status' => 'F' ],
26         answered => [ 'X-Status' => 'A' ],
27         seen => [ 'Status' => 'R' ],
28         draft => [ 'X-Status' => 'T' ],
29 );
30
31 sub _mbox_hdr_buf ($$$) {
32         my ($eml, $type, $kw) = @_;
33         $eml->header_set($_) for (qw(Lines Bytes Content-Length));
34         my %hdr; # set Status, X-Status
35         for my $k (@$kw) {
36                 if (my $ent = $kw2status{$k}) {
37                         push @{$hdr{$ent->[0]}}, $ent->[1];
38                 } else { # X-Label?
39                         warn "TODO: keyword `$k' not supported for mbox\n";
40                 }
41         }
42         while (my ($name, $chars) = each %hdr) {
43                 $eml->header_set($name, join('', sort @$chars));
44         }
45         my $buf = delete $eml->{hdr};
46
47         # fixup old bug from import (pre-a0c07cba0e5d8b6a)
48         $$buf =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
49
50         substr($$buf, 0, 0, # prepend From line
51                 "From lei\@$type Thu Jan  1 00:00:00 1970$eml->{crlf}");
52         $buf;
53 }
54
55 sub write_in_full ($$$) {
56         my ($fh, $buf, $atomic) = @_;
57         if ($atomic) {
58                 defined(my $w = syswrite($fh, $$buf)) or die "write: $!";
59                 $w == length($$buf) or die "short write: $w != ".length($$buf);
60         } else {
61                 print $fh $$buf or die "print: $!";
62         }
63 }
64
65 sub eml2mboxrd ($;$) {
66         my ($eml, $kw) = @_;
67         my $buf = _mbox_hdr_buf($eml, 'mboxrd', $kw);
68         if (my $bdy = delete $eml->{bdy}) {
69                 $$bdy =~ s/^(>*From )/>$1/gm;
70                 $$buf .= $eml->{crlf};
71                 substr($$bdy, 0, 0, $$buf); # prepend header
72                 $buf = $bdy;
73         }
74         $$buf .= $eml->{crlf};
75         $buf;
76 }
77
78 sub eml2mboxo {
79         my ($eml, $kw) = @_;
80         my $buf = _mbox_hdr_buf($eml, 'mboxo', $kw);
81         if (my $bdy = delete $eml->{bdy}) {
82                 $$bdy =~ s/^From />From /gm;
83                 $$buf .= $eml->{crlf};
84                 substr($$bdy, 0, 0, $$buf); # prepend header
85                 $buf = $bdy;
86         }
87         $$buf .= $eml->{crlf};
88         $buf;
89 }
90
91 # mboxcl still escapes "From " lines
92 sub eml2mboxcl {
93         my ($eml, $kw) = @_;
94         my $buf = _mbox_hdr_buf($eml, 'mboxcl', $kw);
95         my $crlf = $eml->{crlf};
96         if (my $bdy = delete $eml->{bdy}) {
97                 $$bdy =~ s/^From />From /gm;
98                 $$buf .= 'Content-Length: '.length($$bdy).$crlf.$crlf;
99                 substr($$bdy, 0, 0, $$buf); # prepend header
100                 $buf = $bdy;
101         }
102         $$buf .= $crlf;
103         $buf;
104 }
105
106 # mboxcl2 has no "From " escaping
107 sub eml2mboxcl2 {
108         my ($eml, $kw) = @_;
109         my $buf = _mbox_hdr_buf($eml, 'mboxcl2', $kw);
110         my $crlf = $eml->{crlf};
111         if (my $bdy = delete $eml->{bdy}) {
112                 $$buf .= 'Content-Length: '.length($$bdy).$crlf.$crlf;
113                 substr($$bdy, 0, 0, $$buf); # prepend header
114                 $buf = $bdy;
115         }
116         $$buf .= $crlf;
117         $buf;
118 }
119
120 sub mkmaildir ($) {
121         my ($maildir) = @_;
122         for (qw(new tmp cur)) {
123                 my $d = "$maildir/$_";
124                 next if -d $d;
125                 require File::Path;
126                 if (!File::Path::mkpath($d) && !-d $d) {
127                         die "failed to mkpath($d): $!\n";
128                 }
129         }
130 }
131
132 sub git_to_mail { # git->cat_async callback
133         my ($bref, $oid, $type, $size, $arg) = @_;
134         if ($type ne 'blob') {
135                 if ($type eq 'missing') {
136                         warn "missing $oid\n";
137                 } else {
138                         warn "unexpected type=$type for $oid\n";
139                 }
140         }
141         if ($size > 0) {
142                 my ($write_cb, $kw) = @$arg;
143                 $write_cb->($bref, $oid, $kw);
144         }
145 }
146
147 sub reap_compress { # dwaitpid callback
148         my ($lei, $pid) = @_;
149         my $cmd = delete $lei->{"pid.$pid"};
150         return if $? == 0;
151         $lei->fail("@$cmd failed", $? >> 8);
152 }
153
154 # all of these support -c for stdout and -d for decompression,
155 # mutt is commonly distributed with hooks for gz, bz2 and xz, at least
156 # { foo => '' } means "--foo" is passed to the command-line,
157 # otherwise { foo => '--bar' } passes "--bar"
158 our %zsfx2cmd = (
159         gz => [ qw(GZIP pigz gzip), {
160                 rsyncable => '', threads => '-p' } ],
161         bz2 => [ 'bzip2', {} ],
162         xz => [ 'xz', { threads => '-T' } ],
163         # XXX does anybody care for these?  I prefer zstd on entire FSes,
164         # so it's probably not necessary on a per-file basis
165         # zst => [ 'zstd', { -default => [ qw(-q) ], # it's noisy by default
166         #       rsyncable => '', threads => '-T' } ],
167         # zz => [ 'pigz', { -default => [ '--zlib' ],
168         #       rsyncable => '', threads => '-p' }],
169         # lzo => [ 'lzop', {} ],
170         # lzma => [ 'lzma', {} ],
171 );
172
173 sub zsfx2cmd ($$$) {
174         my ($zsfx, $decompress, $lei) = @_;
175         my $x = $zsfx2cmd{$zsfx} // die "no support for suffix=.$zsfx";
176         my @info = @$x;
177         my $cmd_opt = pop @info;
178         my @cmd = (undef, $decompress ? qw(-dc) : qw(-c));
179         for my $exe (@info) {
180                 # I think respecting client's ENV{GZIP} is OK, not sure
181                 # about ENV overrides for other, less-common compressors
182                 if ($exe eq uc($exe)) {
183                         $exe = $lei->{env}->{$exe} or next;
184                 }
185                 $cmd[0] = which($exe) and last;
186         }
187         $cmd[0] // die join(' or ', @info)." missing for .$zsfx";
188         # push @cmd, @{$cmd_opt->{-default}} if $cmd_opt->{-default};
189         for my $bool (qw(rsyncable)) {
190                 my $switch = $cmd_opt->{rsyncable} // next;
191                 push @cmd, '--'.($switch || $bool);
192         }
193         for my $key (qw(threads)) { # support compression level?
194                 my $switch = $cmd_opt->{$key} // next;
195                 my $val = $lei->{opt}->{$key} // next;
196                 push @cmd, $switch, $val;
197         }
198         \@cmd;
199 }
200
201 sub compress_dst {
202         my ($out, $zsfx, $lei) = @_;
203         my $cmd = zsfx2cmd($zsfx, undef, $lei);
204         pipe(my ($r, $w)) or die "pipe: $!";
205         my $rdr = { 0 => $r, 1 => $out, 2 => $lei->{2} };
206         my $pid = spawn($cmd, $lei->{env}, $rdr);
207         $lei->{"pid.$pid"} = $cmd;
208         my $pp = gensym;
209         tie *$pp, 'PublicInbox::ProcessPipe', $pid, $w, \&reap_compress, $lei;
210         my $pipe_lk = ($lei->{opt}->{jobs} // 0) > 1 ?
211                         PublicInbox::Lock->new_tmp($zsfx) : undef;
212         ($pp, $pipe_lk);
213 }
214
215 sub decompress_src ($$$) {
216         my ($in, $zsfx, $lei) = @_;
217         my $cmd = zsfx2cmd($zsfx, 1, $lei);
218         my $rdr = { 0 => $in, 2 => $lei->{2} };
219         popen_rd($cmd, $lei->{env}, $rdr);
220 }
221
222 sub dup_src ($) {
223         my ($in) = @_;
224         open my $dup, '+>>&', $in or die "dup: $!";
225         $dup;
226 }
227
228 # --augment existing output destination, with deduplication
229 sub _augment { # MboxReader eml_cb
230         my ($eml, $lei) = @_;
231         # ignore return value, just populate the skv
232         $lei->{dedupe_cb}->is_dup($eml);
233 }
234
235 sub _mbox_write_cb ($$$$) {
236         my ($cls, $mbox, $dst, $lei) = @_;
237         my $m = "eml2$mbox";
238         my $eml2mbox = $cls->can($m) or die "$cls->$m missing";
239         my ($out, $pipe_lk, $seekable);
240         # XXX should we support /dev/stdout.gz ?
241         if ($dst eq '/dev/stdout') {
242                 $out = $lei->{1};
243         } else { # TODO: mbox locking
244                 open $out, '+>>', $dst or die "open $dst: $!";
245                 # Perl does SEEK_END even with O_APPEND :<
246                 $seekable = seek($out, 0, SEEK_SET);
247                 die "seek $dst: $!\n" if !$seekable && !$!{ESPIPE};
248         }
249         my $jobs = $lei->{opt}->{jobs} // 0;
250         my $atomic = $jobs > 1;
251         my $dedupe = $lei->{dedupe} = PublicInbox::LeiDedupe->new($lei);
252         state $zsfx_allow = join('|', keys %zsfx2cmd);
253         my ($zsfx) = ($dst =~ /\.($zsfx_allow)\z/);
254         if ($lei->{opt}->{augment}) {
255                 if ($seekable && -s $out && $dedupe->prepare_dedupe) {
256                         my $rd = $zsfx ? decompress_src($out, $zsfx, $lei) :
257                                         dup_src($out);
258                         PublicInbox::MboxReader->$mbox($rd, \&_augment, $lei);
259                 } elsif ($seekable && !$atomic) {
260                         seek($out, 0, SEEK_END) or die "seek: $!";
261                 }
262                 $dedupe->pause_dedupe if $jobs; # are we forking?
263         } elsif ($seekable) {
264                 truncate($out, 0) or die "truncate $dst: $!";
265         }
266         $dedupe->prepare_dedupe if !$jobs;
267         ($out, $pipe_lk) = compress_dst($out, $zsfx, $lei) if $zsfx;
268         sub {
269                 my ($buf, $oid, $kw) = @_;
270                 my $eml = PublicInbox::Eml->new($buf);
271                 if (!$lei->{dedupe}->is_dup($eml, $oid)) {
272                         $buf = $eml2mbox->($eml, $kw);
273                         my $lock = $pipe_lk->lock_for_scope if $pipe_lk;
274                         write_in_full($out, $buf, $atomic);
275                 }
276         }
277 }
278
279 sub write_cb { # returns a callback for git_to_mail
280         my ($cls, $dst, $lei) = @_;
281         require PublicInbox::LeiDedupe;
282         if ($dst =~ s!\A(mbox(?:rd|cl|cl2|o))?:!!) {
283                 _mbox_write_cb($cls, $1, $dst, $lei);
284         }
285         # TODO: Maildir, MH, IMAP, JMAP ...
286 }
287
288 1;