]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiToMail.pm
update copyrights for 2021
[public-inbox.git] / lib / PublicInbox / LeiToMail.pm
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>
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 O_CREAT O_EXCL O_WRONLY);
16 use Errno qw(EEXIST ESPIPE ENOENT);
17
18 my %kw2char = ( # Maildir characters
19         draft => 'D',
20         flagged => 'F',
21         answered => 'R',
22         seen => 'S'
23 );
24
25 my %kw2status = (
26         flagged => [ 'X-Status' => 'F' ],
27         answered => [ 'X-Status' => 'A' ],
28         seen => [ 'Status' => 'R' ],
29         draft => [ 'X-Status' => 'T' ],
30 );
31
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
36         for my $k (@$kw) {
37                 if (my $ent = $kw2status{$k}) {
38                         push @{$hdr{$ent->[0]}}, $ent->[1];
39                 } else { # X-Label?
40                         warn "TODO: keyword `$k' not supported for mbox\n";
41                 }
42         }
43         while (my ($name, $chars) = each %hdr) {
44                 $eml->header_set($name, join('', sort @$chars));
45         }
46         my $buf = delete $eml->{hdr};
47
48         # fixup old bug from import (pre-a0c07cba0e5d8b6a)
49         $$buf =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
50
51         substr($$buf, 0, 0, # prepend From line
52                 "From lei\@$type Thu Jan  1 00:00:00 1970$eml->{crlf}");
53         $buf;
54 }
55
56 sub atomic_append { # for on-disk destinations (O_APPEND, or O_EXCL)
57         my ($fh, $buf) = @_;
58         defined(my $w = syswrite($fh, $$buf)) or die "write: $!";
59         $w == length($$buf) or die "short write: $w != ".length($$buf);
60 }
61
62 sub _print_full {
63         my ($fh, $buf) = @_;
64         print $fh $$buf or die "print: $!";
65 }
66
67 sub eml2mboxrd ($;$) {
68         my ($eml, $kw) = @_;
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
74                 $buf = $bdy;
75         }
76         $$buf .= $eml->{crlf};
77         $buf;
78 }
79
80 sub eml2mboxo {
81         my ($eml, $kw) = @_;
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
87                 $buf = $bdy;
88         }
89         $$buf .= $eml->{crlf};
90         $buf;
91 }
92
93 # mboxcl still escapes "From " lines
94 sub eml2mboxcl {
95         my ($eml, $kw) = @_;
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
102                 $buf = $bdy;
103         }
104         $$buf .= $crlf;
105         $buf;
106 }
107
108 # mboxcl2 has no "From " escaping
109 sub eml2mboxcl2 {
110         my ($eml, $kw) = @_;
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
116                 $buf = $bdy;
117         }
118         $$buf .= $crlf;
119         $buf;
120 }
121
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";
127                 } else {
128                         warn "unexpected type=$type for $oid\n";
129                 }
130         }
131         if ($size > 0) {
132                 my ($write_cb, $kw) = @$arg;
133                 $write_cb->($bref, $oid, $kw);
134         }
135 }
136
137 sub reap_compress { # dwaitpid callback
138         my ($lei, $pid) = @_;
139         my $cmd = delete $lei->{"pid.$pid"};
140         return if $? == 0;
141         $lei->fail("@$cmd failed", $? >> 8);
142 }
143
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"
148 our %zsfx2cmd = (
149         gz => [ qw(GZIP pigz gzip), {
150                 rsyncable => '', threads => '-p' } ],
151         bz2 => [ 'bzip2', {} ],
152         xz => [ 'xz', { threads => '-T' } ],
153         # XXX does anybody care for these?  I prefer zstd on entire FSes,
154         # so it's probably not necessary on a per-file basis
155         # zst => [ 'zstd', { -default => [ qw(-q) ], # it's noisy by default
156         #       rsyncable => '', threads => '-T' } ],
157         # zz => [ 'pigz', { -default => [ '--zlib' ],
158         #       rsyncable => '', threads => '-p' }],
159         # lzo => [ 'lzop', {} ],
160         # lzma => [ 'lzma', {} ],
161 );
162
163 sub zsfx2cmd ($$$) {
164         my ($zsfx, $decompress, $lei) = @_;
165         my $x = $zsfx2cmd{$zsfx} // die "no support for suffix=.$zsfx";
166         my @info = @$x;
167         my $cmd_opt = pop @info;
168         my @cmd = (undef, $decompress ? qw(-dc) : qw(-c));
169         for my $exe (@info) {
170                 # I think respecting client's ENV{GZIP} is OK, not sure
171                 # about ENV overrides for other, less-common compressors
172                 if ($exe eq uc($exe)) {
173                         $exe = $lei->{env}->{$exe} or next;
174                 }
175                 $cmd[0] = which($exe) and last;
176         }
177         $cmd[0] // die join(' or ', @info)." missing for .$zsfx";
178         # push @cmd, @{$cmd_opt->{-default}} if $cmd_opt->{-default};
179         for my $bool (qw(rsyncable)) {
180                 my $switch = $cmd_opt->{rsyncable} // next;
181                 push @cmd, '--'.($switch || $bool);
182         }
183         for my $key (qw(threads)) { # support compression level?
184                 my $switch = $cmd_opt->{$key} // next;
185                 my $val = $lei->{opt}->{$key} // next;
186                 push @cmd, $switch, $val;
187         }
188         \@cmd;
189 }
190
191 sub compress_dst {
192         my ($out, $zsfx, $lei) = @_;
193         my $cmd = zsfx2cmd($zsfx, undef, $lei);
194         pipe(my ($r, $w)) or die "pipe: $!";
195         my $rdr = { 0 => $r, 1 => $out, 2 => $lei->{2} };
196         my $pid = spawn($cmd, $lei->{env}, $rdr);
197         $lei->{"pid.$pid"} = $cmd;
198         my $pp = gensym;
199         tie *$pp, 'PublicInbox::ProcessPipe', $pid, $w, \&reap_compress, $lei;
200         my $pipe_lk = ($lei->{opt}->{jobs} // 0) > 1 ?
201                         PublicInbox::Lock->new_tmp($zsfx) : undef;
202         ($pp, $pipe_lk);
203 }
204
205 sub decompress_src ($$$) {
206         my ($in, $zsfx, $lei) = @_;
207         my $cmd = zsfx2cmd($zsfx, 1, $lei);
208         my $rdr = { 0 => $in, 2 => $lei->{2} };
209         popen_rd($cmd, $lei->{env}, $rdr);
210 }
211
212 sub dup_src ($) {
213         my ($in) = @_;
214         open my $dup, '+>>&', $in or die "dup: $!";
215         $dup;
216 }
217
218 # --augment existing output destination, with deduplication
219 sub _augment { # MboxReader eml_cb
220         my ($eml, $lei) = @_;
221         # ignore return value, just populate the skv
222         $lei->{dedupe}->is_dup($eml);
223 }
224
225 sub _mbox_write_cb ($$$$) {
226         my ($cls, $mbox, $dst, $lei) = @_;
227         my $m = "eml2$mbox";
228         my $eml2mbox = $cls->can($m) or die "$cls->$m missing";
229         my ($out, $pipe_lk, $seekable);
230         # XXX should we support /dev/stdout.gz ?
231         if ($dst eq '/dev/stdout') {
232                 $out = $lei->{1};
233         } else { # TODO: mbox locking (but mairix doesn't...)
234                 my $mode = -p $dst ? '>' : '+>>';
235                 if (-f _ && !$lei->{opt}->{augment} and !unlink($dst)) {
236                         die "unlink $dst: $!" if $! != ENOENT;
237                 }
238                 open $out, $mode, $dst or die "open $dst: $!";
239                 # Perl does SEEK_END even with O_APPEND :<
240                 $seekable = seek($out, 0, SEEK_SET);
241                 die "seek $dst: $!\n" if !$seekable && $! != ESPIPE;
242         }
243         my $jobs = $lei->{opt}->{jobs} // 0;
244         state $zsfx_allow = join('|', keys %zsfx2cmd);
245         my ($zsfx) = ($dst =~ /\.($zsfx_allow)\z/);
246         my $write = $jobs > 1 && !$zsfx ? \&atomic_append : \&_print_full;
247         my $dedupe = $lei->{dedupe} = PublicInbox::LeiDedupe->new($lei);
248         if ($lei->{opt}->{augment}) {
249                 die "cannot augment $dst, not seekable\n" if !$seekable;
250                 if (-s $out && $dedupe->prepare_dedupe) {
251                         my $rd = $zsfx ? decompress_src($out, $zsfx, $lei) :
252                                         dup_src($out);
253                         PublicInbox::MboxReader->$mbox($rd, \&_augment, $lei);
254                 }
255                 # maybe some systems don't honor O_APPEND, Perl does this:
256                 seek($out, 0, SEEK_END) or die "seek $dst: $!";
257                 $dedupe->pause_dedupe if $jobs; # are we forking?
258         }
259         $dedupe->prepare_dedupe if !$jobs;
260         ($out, $pipe_lk) = compress_dst($out, $zsfx, $lei) if $zsfx;
261         sub { # for git_to_mail
262                 my ($buf, $oid, $kw) = @_;
263                 my $eml = PublicInbox::Eml->new($buf);
264                 if (!$dedupe->is_dup($eml, $oid)) {
265                         $buf = $eml2mbox->($eml, $kw);
266                         my $lock = $pipe_lk->lock_for_scope if $pipe_lk;
267                         $write->($out, $buf);
268                 }
269         }
270 }
271
272 sub _maildir_each_file ($$;@) {
273         my ($dir, $cb, @arg) = @_;
274         for my $d (qw(new/ cur/)) {
275                 my $pfx = $dir.$d;
276                 opendir my $dh, $pfx or next;
277                 while (defined(my $fn = readdir($dh))) {
278                         $cb->($pfx.$fn, @arg) if $fn =~ /:2,[A-Za-z]*\z/;
279                 }
280         }
281 }
282
283 sub _augment_file { # _maildir_each_file cb
284         my ($f, $lei) = @_;
285         my $eml = PublicInbox::InboxWritable::eml_from_path($f) or return;
286         _augment($eml, $lei);
287 }
288
289 # _maildir_each_file callback, \&CORE::unlink doesn't work with it
290 sub _unlink { unlink($_[0]) }
291
292 sub _buf2maildir {
293         my ($dst, $buf, $oid, $kw) = @_;
294         my $sfx = join('', sort(map { $kw2char{$_} // () } @$kw));
295         my $rand = ''; # chosen by die roll :P
296         my ($tmp, $fh, $final);
297         do {
298                 $tmp = $dst.'tmp/'.$rand."oid=$oid";
299         } while (!sysopen($fh, $tmp, O_CREAT|O_EXCL|O_WRONLY) &&
300                 $! == EEXIST && ($rand = int(rand 0x7fffffff).','));
301         if (print $fh $$buf and close($fh)) {
302                 $dst .= $sfx eq '' ? 'new/' : 'cur/';
303                 $rand = '';
304                 do {
305                         $final = $dst.$rand."oid=$oid:2,$sfx";
306                 } while (!link($tmp, $final) && $! == EEXIST &&
307                         ($rand = int(rand 0x7fffffff).','));
308                 unlink($tmp) or warn "W: failed to unlink $tmp: $!\n";
309         } else {
310                 my $err = $!;
311                 unlink($tmp);
312                 die "Error writing $oid to $dst: $err";
313         }
314 }
315
316
317 sub _maildir_write_cb ($$) {
318         my ($dst, $lei) = @_;
319         $dst .= '/' unless substr($dst, -1) eq '/';
320         my $dedupe = $lei->{dedupe} = PublicInbox::LeiDedupe->new($lei, $dst);
321         my $jobs = $lei->{opt}->{jobs} // 0;
322         if ($lei->{opt}->{augment}) {
323                 if ($dedupe && $dedupe->prepare_dedupe) {
324                         require PublicInbox::InboxWritable; # eml_from_path
325                         _maildir_each_file($dst, \&_augment_file, $lei);
326                         $dedupe->pause_dedupe if $jobs; # are we forking?
327                 }
328         } else { # clobber existing Maildir
329                 _maildir_each_file($dst, \&_unlink);
330         }
331         for my $x (qw(tmp new cur)) {
332                 my $d = $dst.$x;
333                 next if -d $d;
334                 require File::Path;
335                 if (!File::Path::mkpath($d) && !-d $d) {
336                         die "failed to mkpath($d): $!\n";
337                 }
338         }
339         $dedupe->prepare_dedupe if $dedupe && !$jobs;
340         sub { # for git_to_mail
341                 my ($buf, $oid, $kw) = @_;
342                 return _buf2maildir($dst, $buf, $oid, $kw) if !$dedupe;
343                 my $eml = PublicInbox::Eml->new($$buf); # copy buf
344                 return if $dedupe->is_dup($eml, $oid);
345                 undef $eml;
346                 _buf2maildir($dst, $buf, $oid, $kw);
347         }
348 }
349
350 sub write_cb { # returns a callback for git_to_mail
351         my ($cls, $dst, $lei) = @_;
352         require PublicInbox::LeiDedupe;
353         if ($dst =~ s!\A(mbox(?:rd|cl|cl2|o))?:!!) {
354                 _mbox_write_cb($cls, $1, $dst, $lei);
355         } elsif ($dst =~ s!\A[Mm]aildir:!!) { # typically capitalized
356                 _maildir_write_cb($dst, $lei);
357         }
358         # TODO: Maildir, MH, IMAP, JMAP ...
359 }
360
361 1;