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