]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiToMail.pm
lei q: fix SIGPIPE handling from lei2mail workers
[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 parent qw(PublicInbox::IPC);
9 use PublicInbox::Eml;
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);
18 use PublicInbox::Git;
19
20 my %kw2char = ( # Maildir characters
21         draft => 'D',
22         flagged => 'F',
23         answered => 'R',
24         seen => 'S'
25 );
26
27 my %kw2status = (
28         flagged => [ 'X-Status' => 'F' ],
29         answered => [ 'X-Status' => 'A' ],
30         seen => [ 'Status' => 'R' ],
31         draft => [ 'X-Status' => 'T' ],
32 );
33
34 sub _mbox_hdr_buf ($$$) {
35         my ($eml, $type, $kw) = @_;
36         $eml->header_set($_) for (qw(Lines Bytes Content-Length));
37
38         # Messages are always 'O' (non-\Recent in IMAP), it saves
39         # MUAs the trouble of rewriting the mbox if no other
40         # changes are made
41         my %hdr = (Status => [ 'O' ]); # set Status, X-Status
42         for my $k (@$kw) {
43                 if (my $ent = $kw2status{$k}) {
44                         push @{$hdr{$ent->[0]}}, $ent->[1];
45                 } else { # X-Label?
46                         warn "TODO: keyword `$k' not supported for mbox\n";
47                 }
48         }
49         while (my ($name, $chars) = each %hdr) {
50                 $eml->header_set($name, join('', sort @$chars));
51         }
52         my $buf = delete $eml->{hdr};
53
54         # fixup old bug from import (pre-a0c07cba0e5d8b6a)
55         $$buf =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
56
57         substr($$buf, 0, 0, # prepend From line
58                 "From lei\@$type Thu Jan  1 00:00:00 1970$eml->{crlf}");
59         $buf;
60 }
61
62 sub atomic_append { # for on-disk destinations (O_APPEND, or O_EXCL)
63         my ($fh, $buf) = @_;
64         defined(my $w = syswrite($fh, $$buf)) or die "write: $!";
65         $w == length($$buf) or die "short write: $w != ".length($$buf);
66 }
67
68 sub _print_full {
69         my ($fh, $buf) = @_;
70         print $fh $$buf or die "print: $!";
71 }
72
73 sub eml2mboxrd ($;$) {
74         my ($eml, $kw) = @_;
75         my $buf = _mbox_hdr_buf($eml, 'mboxrd', $kw);
76         if (my $bdy = delete $eml->{bdy}) {
77                 $$bdy =~ s/^(>*From )/>$1/gm;
78                 $$buf .= $eml->{crlf};
79                 substr($$bdy, 0, 0, $$buf); # prepend header
80                 $buf = $bdy;
81         }
82         $$buf .= $eml->{crlf};
83         $buf;
84 }
85
86 sub eml2mboxo {
87         my ($eml, $kw) = @_;
88         my $buf = _mbox_hdr_buf($eml, 'mboxo', $kw);
89         if (my $bdy = delete $eml->{bdy}) {
90                 $$bdy =~ s/^From />From /gm;
91                 $$buf .= $eml->{crlf};
92                 substr($$bdy, 0, 0, $$buf); # prepend header
93                 $buf = $bdy;
94         }
95         $$buf .= $eml->{crlf};
96         $buf;
97 }
98
99 sub _mboxcl_common ($$$) {
100         my ($buf, $bdy, $crlf) = @_;
101         # add Lines: so mutt won't have to add it on MUA close
102         my $lines = $$bdy =~ tr!\n!\n!;
103         $$buf .= 'Content-Length: '.length($$bdy).$crlf.
104                 'Lines: '.$lines.$crlf.$crlf;
105         substr($$bdy, 0, 0, $$buf); # prepend header
106         $_[0] = $bdy;
107 }
108
109 # mboxcl still escapes "From " lines
110 sub eml2mboxcl {
111         my ($eml, $kw) = @_;
112         my $buf = _mbox_hdr_buf($eml, 'mboxcl', $kw);
113         my $crlf = $eml->{crlf};
114         if (my $bdy = delete $eml->{bdy}) {
115                 $$bdy =~ s/^From />From /gm;
116                 _mboxcl_common($buf, $bdy, $crlf);
117         }
118         $$buf .= $crlf;
119         $buf;
120 }
121
122 # mboxcl2 has no "From " escaping
123 sub eml2mboxcl2 {
124         my ($eml, $kw) = @_;
125         my $buf = _mbox_hdr_buf($eml, 'mboxcl2', $kw);
126         my $crlf = $eml->{crlf};
127         if (my $bdy = delete $eml->{bdy}) {
128                 _mboxcl_common($buf, $bdy, $crlf);
129         }
130         $$buf .= $crlf;
131         $buf;
132 }
133
134 sub git_to_mail { # git->cat_async callback
135         my ($bref, $oid, $type, $size, $arg) = @_;
136         if ($type ne 'blob') {
137                 if ($type eq 'missing') {
138                         warn "missing $oid\n";
139                 } else {
140                         warn "unexpected type=$type for $oid\n";
141                 }
142         }
143         if ($size > 0) {
144                 my ($write_cb, $kw) = @$arg;
145                 $write_cb->($bref, $oid, $kw);
146         }
147 }
148
149 sub reap_compress { # dwaitpid callback
150         my ($lei, $pid) = @_;
151         my $cmd = delete $lei->{"pid.$pid"};
152         return if $? == 0;
153         $lei->fail("@$cmd failed", $? >> 8);
154 }
155
156 # all of these support -c for stdout and -d for decompression,
157 # mutt is commonly distributed with hooks for gz, bz2 and xz, at least
158 # { foo => '' } means "--foo" is passed to the command-line,
159 # otherwise { foo => '--bar' } passes "--bar"
160 our %zsfx2cmd = (
161         gz => [ qw(GZIP pigz gzip), { rsyncable => '', threads => '-p' } ],
162         bz2 => [ 'bzip2', {} ],
163         xz => [ 'xz', { threads => '-T' } ],
164         # XXX does anybody care for these?  I prefer zstd on entire FSes,
165         # so it's probably not necessary on a per-file basis
166         # zst => [ 'zstd', { -default => [ qw(-q) ], # it's noisy by default
167         #       rsyncable => '', threads => '-T' } ],
168         # zz => [ 'pigz', { -default => [ '--zlib' ],
169         #       rsyncable => '', threads => '-p' }],
170         # lzo => [ 'lzop', {} ],
171         # lzma => [ 'lzma', {} ],
172 );
173
174 sub zsfx2cmd ($$$) {
175         my ($zsfx, $decompress, $lei) = @_;
176         my $x = $zsfx2cmd{$zsfx} // die "no support for suffix=.$zsfx";
177         my @info = @$x;
178         my $cmd_opt = pop @info;
179         my @cmd = (undef, $decompress ? qw(-dc) : qw(-c));
180         for my $exe (@info) {
181                 # I think respecting client's ENV{GZIP} is OK, not sure
182                 # about ENV overrides for other, less-common compressors
183                 if ($exe eq uc($exe)) {
184                         $exe = $lei->{env}->{$exe} or next;
185                 }
186                 $cmd[0] = which($exe) and last;
187         }
188         $cmd[0] // die join(' or ', @info)." missing for .$zsfx";
189         # push @cmd, @{$cmd_opt->{-default}} if $cmd_opt->{-default};
190         for my $bool (qw(rsyncable)) {
191                 my $switch = $cmd_opt->{rsyncable} // next;
192                 push @cmd, '--'.($switch || $bool);
193         }
194         for my $key (qw(threads)) { # support compression level?
195                 my $switch = $cmd_opt->{$key} // next;
196                 my $val = $lei->{opt}->{$key} // next;
197                 push @cmd, $switch, $val;
198         }
199         \@cmd;
200 }
201
202 sub _post_augment_mbox { # open a compressor process
203         my ($self, $lei) = @_;
204         my $zsfx = $self->{zsfx} or return;
205         my $cmd = zsfx2cmd($zsfx, undef, $lei);
206         pipe(my ($r, $w)) or die "pipe: $!";
207         my $rdr = { 0 => $r, 1 => $lei->{1}, 2 => $lei->{2} };
208         my $pid = spawn($cmd, $lei->{env}, $rdr);
209         $lei->{"pid.$pid"} = $cmd;
210         my $pp = gensym;
211         tie *$pp, 'PublicInbox::ProcessPipe', $pid, $w, \&reap_compress, $lei;
212         $lei->{1} = $pp;
213         die 'BUG: unexpected {ovv}->{lock_path}' if $lei->{ovv}->{lock_path};
214         $lei->{ovv}->ovv_out_lk_init if ($lei->{opt}->{jobs} // 2) > 1;
215 }
216
217 sub decompress_src ($$$) {
218         my ($in, $zsfx, $lei) = @_;
219         my $cmd = zsfx2cmd($zsfx, 1, $lei);
220         popen_rd($cmd, $lei->{env}, { 0 => $in, 2 => $lei->{2} });
221 }
222
223 sub dup_src ($) {
224         my ($in) = @_;
225         # fileno needed because wq_set_recv_modes only used ">&=" for {1}
226         # and Perl blindly trusts that to reject the '+' (readability flag)
227         open my $dup, '+>>&=', fileno($in) or die "dup: $!";
228         $dup;
229 }
230
231 # --augment existing output destination, with deduplication
232 sub _augment { # MboxReader eml_cb
233         my ($eml, $lei) = @_;
234         # ignore return value, just populate the skv
235         $lei->{dedupe}->is_dup($eml);
236 }
237
238 sub _mbox_write_cb ($$) {
239         my ($self, $lei) = @_;
240         my $ovv = $lei->{ovv};
241         my $m = 'eml2'.$ovv->{fmt};
242         my $eml2mbox = $self->can($m) or die "$self->$m missing";
243         my $out = $lei->{1} // die "no stdout ($m, $ovv->{dst})"; # redirected earlier
244         $out->autoflush(1);
245         my $write = $ovv->{lock_path} ? \&_print_full : \&atomic_append;
246         my $dedupe = $lei->{dedupe};
247         $dedupe->prepare_dedupe;
248         sub { # for git_to_mail
249                 my ($buf, $oid, $kw) = @_;
250                 return unless $out;
251                 my $eml = PublicInbox::Eml->new($buf);
252                 if (!$dedupe->is_dup($eml, $oid)) {
253                         $buf = $eml2mbox->($eml, $kw);
254                         my $lk = $ovv->lock_for_scope;
255                         eval { $write->($out, $buf) };
256                         if ($@) {
257                                 die $@ if ref($@) ne 'PublicInbox::SIGPIPE';
258                                 undef $out
259                         }
260                 }
261         }
262 }
263
264 sub _maildir_each_file ($$;@) {
265         my ($dir, $cb, @arg) = @_;
266         for my $d (qw(new/ cur/)) {
267                 my $pfx = $dir.$d;
268                 opendir my $dh, $pfx or next;
269                 while (defined(my $fn = readdir($dh))) {
270                         $cb->($pfx.$fn, @arg) if $fn =~ /:2,[A-Za-z]*\z/;
271                 }
272         }
273 }
274
275 sub _augment_file { # _maildir_each_file cb
276         my ($f, $lei) = @_;
277         my $eml = PublicInbox::InboxWritable::eml_from_path($f) or return;
278         _augment($eml, $lei);
279 }
280
281 # _maildir_each_file callback, \&CORE::unlink doesn't work with it
282 sub _unlink { unlink($_[0]) }
283
284 sub _buf2maildir {
285         my ($dst, $buf, $oid, $kw) = @_;
286         my $sfx = join('', sort(map { $kw2char{$_} // () } @$kw));
287         my $rand = ''; # chosen by die roll :P
288         my ($tmp, $fh, $final);
289         do {
290                 $tmp = $dst.'tmp/'.$rand."oid=$oid";
291         } while (!sysopen($fh, $tmp, O_CREAT|O_EXCL|O_WRONLY) &&
292                 $! == EEXIST && ($rand = int(rand 0x7fffffff).','));
293         if (print $fh $$buf and close($fh)) {
294                 # ignore new/ and write only to cur/, otherwise MUAs
295                 # with R/W access to the Maildir will end up doing
296                 # a mass rename which can take a while with thousands
297                 # of messages.
298                 $dst .= 'cur/';
299                 $rand = '';
300                 do {
301                         $final = $dst.$rand."oid=$oid:2,$sfx";
302                 } while (!link($tmp, $final) && $! == EEXIST &&
303                         ($rand = int(rand 0x7fffffff).','));
304                 unlink($tmp) or warn "W: failed to unlink $tmp: $!\n";
305         } else {
306                 my $err = $!;
307                 unlink($tmp);
308                 die "Error writing $oid to $dst: $err";
309         }
310 }
311
312 sub _maildir_write_cb ($$) {
313         my ($self, $lei) = @_;
314         my $dedupe = $lei->{dedupe};
315         $dedupe->prepare_dedupe;
316         my $dst = $lei->{ovv}->{dst};
317         sub { # for git_to_mail
318                 my ($buf, $oid, $kw) = @_;
319                 return _buf2maildir($dst, $buf, $oid, $kw) if !$dedupe;
320                 my $eml = PublicInbox::Eml->new($$buf); # copy buf
321                 return if $dedupe->is_dup($eml, $oid);
322                 undef $eml;
323                 _buf2maildir($dst, $buf, $oid, $kw);
324         }
325 }
326
327 sub write_cb { # returns a callback for git_to_mail
328         my ($self, $lei) = @_;
329         # _mbox_write_cb or _maildir_write_cb
330         my $m = "_$self->{base_type}_write_cb";
331         $self->$m($lei);
332 }
333
334 sub new {
335         my ($cls, $lei) = @_;
336         my $fmt = $lei->{ovv}->{fmt};
337         my $dst = $lei->{ovv}->{dst};
338         my $self = bless {}, $cls;
339         if ($fmt eq 'maildir') {
340                 $self->{base_type} = 'maildir';
341                 $lei->{ovv}->{dst} = $dst .= '/' if substr($dst, -1) ne '/';
342         } elsif (substr($fmt, 0, 4) eq 'mbox') {
343                 $self->can("eml2$fmt") or die "bad mbox --format=$fmt\n";
344                 $self->{base_type} = 'mbox';
345         } else {
346                 die "bad mail --format=$fmt\n";
347         }
348         $lei->{dedupe} = PublicInbox::LeiDedupe->new($lei);
349         $self;
350 }
351
352 sub _pre_augment_maildir {} # noop
353
354 sub _do_augment_maildir {
355         my ($self, $lei) = @_;
356         my $dst = $lei->{ovv}->{dst};
357         if ($lei->{opt}->{augment}) {
358                 my $dedupe = $lei->{dedupe};
359                 if ($dedupe && $dedupe->prepare_dedupe) {
360                         require PublicInbox::InboxWritable; # eml_from_path
361                         _maildir_each_file($dst, \&_augment_file, $lei);
362                         $dedupe->pause_dedupe;
363                 }
364         } else { # clobber existing Maildir
365                 _maildir_each_file($dst, \&_unlink);
366         }
367 }
368
369 sub _post_augment_maildir {
370         my ($self, $lei) = @_;
371         my $dst = $lei->{ovv}->{dst};
372         for my $x (qw(tmp new cur)) {
373                 my $d = $dst.$x;
374                 next if -d $d;
375                 require File::Path;
376                 File::Path::mkpath($d) or die "mkpath($d): $!";
377                 -d $d or die "$d is not a directory";
378         }
379 }
380
381 sub _pre_augment_mbox {
382         my ($self, $lei) = @_;
383         my $dst = $lei->{ovv}->{dst};
384         if ($dst ne '/dev/stdout') {
385                 my $mode = -p $dst ? '>' : '+>>';
386                 if (-f _ && !$lei->{opt}->{augment} and !unlink($dst)) {
387                         $! == ENOENT or die "unlink($dst): $!";
388                 }
389                 open my $out, $mode, $dst or die "open($dst): $!";
390                 $lei->{1} = $out;
391         }
392         # Perl does SEEK_END even with O_APPEND :<
393         $self->{seekable} = seek($lei->{1}, 0, SEEK_SET);
394         if (!$self->{seekable} && $! != ESPIPE && $dst ne '/dev/stdout') {
395                 die "seek($dst): $!\n";
396         }
397         state $zsfx_allow = join('|', keys %zsfx2cmd);
398         ($self->{zsfx}) = ($dst =~ /\.($zsfx_allow)\z/);
399 }
400
401 sub _do_augment_mbox {
402         my ($self, $lei) = @_;
403         return if !$lei->{opt}->{augment};
404         my $dedupe = $lei->{dedupe};
405         my $dst = $lei->{ovv}->{dst};
406         die "cannot augment $dst, not seekable\n" if !$self->{seekable};
407         my $out = $lei->{1};
408         if (-s $out && $dedupe && $dedupe->prepare_dedupe) {
409                 my $zsfx = $self->{zsfx};
410                 my $rd = $zsfx ? decompress_src($out, $zsfx, $lei) :
411                                 dup_src($out);
412                 my $fmt = $lei->{ovv}->{fmt};
413                 require PublicInbox::MboxReader;
414                 PublicInbox::MboxReader->$fmt($rd, \&_augment, $lei);
415         }
416         # maybe some systems don't honor O_APPEND, Perl does this:
417         seek($out, 0, SEEK_END) or die "seek $dst: $!";
418         $dedupe->pause_dedupe if $dedupe;
419 }
420
421 sub pre_augment { # fast (1 disk seek), runs in main daemon
422         my ($self, $lei) = @_;
423         # _pre_augment_maildir, _pre_augment_mbox
424         my $m = "_pre_augment_$self->{base_type}";
425         $self->$m($lei);
426 }
427
428 sub do_augment { # slow, runs in wq worker
429         my ($self, $lei) = @_;
430         # _do_augment_maildir, _do_augment_mbox
431         my $m = "_do_augment_$self->{base_type}";
432         $self->$m($lei);
433 }
434
435 sub post_augment { # fast (spawn compressor or mkdir), runs in main daemon
436         my ($self, $lei) = @_;
437         # _post_augment_maildir, _post_augment_mbox
438         my $m = "_post_augment_$self->{base_type}";
439         $self->$m($lei);
440 }
441
442 sub lock_free {
443         $_[0]->{base_type} =~ /\A(?:maildir|mh|imap|jmap)\z/ ? 1 : 0;
444 }
445
446 sub write_mail { # via ->wq_do
447         my ($self, $git_dir, $oid, $lei, $kw) = @_;
448         my $not_done = delete $self->{4}; # write end of {each_smsg_done}
449         my $wcb = $self->{wcb} //= do { # first message
450                 my %sig = $lei->atfork_child_wq($self);
451                 @SIG{keys %sig} = values %sig; # not local
452                 $lei->{dedupe}->prepare_dedupe;
453                 $self->write_cb($lei);
454         };
455         my $git = $self->{"$$\0$git_dir"} //= PublicInbox::Git->new($git_dir);
456         $git->cat_async($oid, \&git_to_mail, [ $wcb, $kw, $not_done ]);
457 }
458
459 sub ipc_atfork_prepare {
460         my ($self) = @_;
461         # (qry_status_wr, stdout|mbox, stderr, 3: sock, 4: each_smsg_done_wr)
462         $self->wq_set_recv_modes(qw[+<&= >&= >&= +<&= >&=]);
463         $self->SUPER::ipc_atfork_prepare; # PublicInbox::IPC
464 }
465
466 sub DESTROY {
467         my ($self) = @_;
468         for my $pid_git (grep(/\A$$\0/, keys %$self)) {
469                 $self->{$pid_git}->async_wait_all;
470         }
471 }
472
473 1;