]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiToMail.pm
lei: test some likely errors due to misuse
[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, $zpipe) = @_;
204         my $zsfx = $self->{zsfx} or return;
205         my $cmd = zsfx2cmd($zsfx, undef, $lei);
206         my ($r, $w) = splice(@$zpipe, 0, 2);
207         my $rdr = { 0 => $r, 1 => $lei->{1}, 2 => $lei->{2} };
208         my $pid = spawn($cmd, $lei->{env}, $rdr);
209         my $pp = gensym;
210         my $dup = bless { "pid.$pid" => $cmd }, ref($lei);
211         $dup->{$_} = $lei->{$_} for qw(2 sock);
212         tie *$pp, 'PublicInbox::ProcessPipe', $pid, $w, \&reap_compress, $dup;
213         $lei->{1} = $pp;
214         die 'BUG: unexpected {ovv}->{lock_path}' if $lei->{ovv}->{lock_path};
215         $lei->{ovv}->ovv_out_lk_init;
216 }
217
218 sub decompress_src ($$$) {
219         my ($in, $zsfx, $lei) = @_;
220         my $cmd = zsfx2cmd($zsfx, 1, $lei);
221         popen_rd($cmd, $lei->{env}, { 0 => $in, 2 => $lei->{2} });
222 }
223
224 sub dup_src ($) {
225         my ($in) = @_;
226         # fileno needed because wq_set_recv_modes only used ">&=" for {1}
227         # and Perl blindly trusts that to reject the '+' (readability flag)
228         open my $dup, '+>>&=', fileno($in) or die "dup: $!";
229         $dup;
230 }
231
232 # --augment existing output destination, with deduplication
233 sub _augment { # MboxReader eml_cb
234         my ($eml, $lei) = @_;
235         # ignore return value, just populate the skv
236         $lei->{dedupe}->is_dup($eml);
237 }
238
239 sub _mbox_write_cb ($$) {
240         my ($self, $lei) = @_;
241         my $ovv = $lei->{ovv};
242         my $m = 'eml2'.$ovv->{fmt};
243         my $eml2mbox = $self->can($m) or die "$self->$m missing";
244         my $out = $lei->{1} // die "no stdout ($m, $ovv->{dst})"; # redirected earlier
245         $out->autoflush(1);
246         my $write = $ovv->{lock_path} ? \&_print_full : \&atomic_append;
247         my $dedupe = $lei->{dedupe};
248         $dedupe->prepare_dedupe;
249         sub { # for git_to_mail
250                 my ($buf, $oid, $kw) = @_;
251                 return unless $out;
252                 my $eml = PublicInbox::Eml->new($buf);
253                 if (!$dedupe->is_dup($eml, $oid)) {
254                         $buf = $eml2mbox->($eml, $kw);
255                         my $lk = $ovv->lock_for_scope;
256                         eval { $write->($out, $buf) };
257                         if ($@) {
258                                 die $@ if ref($@) ne 'PublicInbox::SIGPIPE';
259                                 undef $out
260                         }
261                 }
262         }
263 }
264
265 sub _maildir_each_file ($$;@) {
266         my ($dir, $cb, @arg) = @_;
267         for my $d (qw(new/ cur/)) {
268                 my $pfx = $dir.$d;
269                 opendir my $dh, $pfx or next;
270                 while (defined(my $fn = readdir($dh))) {
271                         $cb->($pfx.$fn, @arg) if $fn =~ /:2,[A-Za-z]*\z/;
272                 }
273         }
274 }
275
276 sub _augment_file { # _maildir_each_file cb
277         my ($f, $lei) = @_;
278         my $eml = PublicInbox::InboxWritable::eml_from_path($f) or return;
279         _augment($eml, $lei);
280 }
281
282 # _maildir_each_file callback, \&CORE::unlink doesn't work with it
283 sub _unlink { unlink($_[0]) }
284
285 sub _buf2maildir {
286         my ($dst, $buf, $oid, $kw) = @_;
287         my $sfx = join('', sort(map { $kw2char{$_} // () } @$kw));
288         my $rand = ''; # chosen by die roll :P
289         my ($tmp, $fh, $final);
290         do {
291                 $tmp = $dst.'tmp/'.$rand."oid=$oid";
292         } while (!sysopen($fh, $tmp, O_CREAT|O_EXCL|O_WRONLY) &&
293                 $! == EEXIST && ($rand = int(rand 0x7fffffff).','));
294         if (print $fh $$buf and close($fh)) {
295                 # ignore new/ and write only to cur/, otherwise MUAs
296                 # with R/W access to the Maildir will end up doing
297                 # a mass rename which can take a while with thousands
298                 # of messages.
299                 $dst .= 'cur/';
300                 $rand = '';
301                 do {
302                         $final = $dst.$rand."oid=$oid:2,$sfx";
303                 } while (!link($tmp, $final) && $! == EEXIST &&
304                         ($rand = int(rand 0x7fffffff).','));
305                 unlink($tmp) or warn "W: failed to unlink $tmp: $!\n";
306         } else {
307                 my $err = $!;
308                 unlink($tmp);
309                 die "Error writing $oid to $dst: $err";
310         }
311 }
312
313 sub _maildir_write_cb ($$) {
314         my ($self, $lei) = @_;
315         my $dedupe = $lei->{dedupe};
316         $dedupe->prepare_dedupe;
317         my $dst = $lei->{ovv}->{dst};
318         sub { # for git_to_mail
319                 my ($buf, $oid, $kw) = @_;
320                 return _buf2maildir($dst, $buf, $oid, $kw) if !$dedupe;
321                 my $eml = PublicInbox::Eml->new($$buf); # copy buf
322                 return if $dedupe->is_dup($eml, $oid);
323                 undef $eml;
324                 _buf2maildir($dst, $buf, $oid, $kw);
325         }
326 }
327
328 sub write_cb { # returns a callback for git_to_mail
329         my ($self, $lei) = @_;
330         # _mbox_write_cb or _maildir_write_cb
331         my $m = "_$self->{base_type}_write_cb";
332         $self->$m($lei);
333 }
334
335 sub new {
336         my ($cls, $lei) = @_;
337         my $fmt = $lei->{ovv}->{fmt};
338         my $dst = $lei->{ovv}->{dst};
339         my $self = bless {}, $cls;
340         if ($fmt eq 'maildir') {
341                 $self->{base_type} = 'maildir';
342                 -e $dst && !-d _ and die
343                                 "$dst exists and is not a directory\n";
344                 $lei->{ovv}->{dst} = $dst .= '/' if substr($dst, -1) ne '/';
345         } elsif (substr($fmt, 0, 4) eq 'mbox') {
346                 -e $dst && !-f _ && !-p _ and die
347                                 "$dst exists and is not a regular file\n";
348                 $self->can("eml2$fmt") or die "bad mbox --format=$fmt\n";
349                 $self->{base_type} = 'mbox';
350         } else {
351                 die "bad mail --format=$fmt\n";
352         }
353         $lei->{dedupe} = PublicInbox::LeiDedupe->new($lei);
354         $self;
355 }
356
357 sub _pre_augment_maildir {} # noop
358
359 sub _do_augment_maildir {
360         my ($self, $lei) = @_;
361         my $dst = $lei->{ovv}->{dst};
362         if ($lei->{opt}->{augment}) {
363                 my $dedupe = $lei->{dedupe};
364                 if ($dedupe && $dedupe->prepare_dedupe) {
365                         require PublicInbox::InboxWritable; # eml_from_path
366                         _maildir_each_file($dst, \&_augment_file, $lei);
367                         $dedupe->pause_dedupe;
368                 }
369         } else { # clobber existing Maildir
370                 _maildir_each_file($dst, \&_unlink);
371         }
372 }
373
374 sub _post_augment_maildir {
375         my ($self, $lei) = @_;
376         my $dst = $lei->{ovv}->{dst};
377         for my $x (qw(tmp new cur)) {
378                 my $d = $dst.$x;
379                 next if -d $d;
380                 require File::Path;
381                 File::Path::mkpath($d);
382                 -d $d or die "$d is not a directory";
383         }
384 }
385
386 sub _pre_augment_mbox {
387         my ($self, $lei) = @_;
388         my $dst = $lei->{ovv}->{dst};
389         if ($dst ne '/dev/stdout') {
390                 my $mode = -p $dst ? '>' : '+>>';
391                 if (-f _ && !$lei->{opt}->{augment} and !unlink($dst)) {
392                         $! == ENOENT or die "unlink($dst): $!";
393                 }
394                 open my $out, $mode, $dst or die "open($dst): $!";
395                 $lei->{1} = $out;
396         }
397         # Perl does SEEK_END even with O_APPEND :<
398         $self->{seekable} = seek($lei->{1}, 0, SEEK_SET);
399         if (!$self->{seekable} && $! != ESPIPE && $dst ne '/dev/stdout') {
400                 die "seek($dst): $!\n";
401         }
402         state $zsfx_allow = join('|', keys %zsfx2cmd);
403         ($self->{zsfx}) = ($dst =~ /\.($zsfx_allow)\z/) or return;
404         pipe(my ($r, $w)) or die "pipe: $!";
405         [ $r, $w ];
406 }
407
408 sub _do_augment_mbox {
409         my ($self, $lei) = @_;
410         return if !$lei->{opt}->{augment};
411         my $dedupe = $lei->{dedupe};
412         my $dst = $lei->{ovv}->{dst};
413         die "cannot augment $dst, not seekable\n" if !$self->{seekable};
414         my $out = $lei->{1};
415         if (-s $out && $dedupe && $dedupe->prepare_dedupe) {
416                 my $zsfx = $self->{zsfx};
417                 my $rd = $zsfx ? decompress_src($out, $zsfx, $lei) :
418                                 dup_src($out);
419                 my $fmt = $lei->{ovv}->{fmt};
420                 require PublicInbox::MboxReader;
421                 PublicInbox::MboxReader->$fmt($rd, \&_augment, $lei);
422         }
423         # maybe some systems don't honor O_APPEND, Perl does this:
424         seek($out, 0, SEEK_END) or die "seek $dst: $!";
425         $dedupe->pause_dedupe if $dedupe;
426 }
427
428 sub pre_augment { # fast (1 disk seek), runs in main daemon
429         my ($self, $lei) = @_;
430         # _pre_augment_maildir, _pre_augment_mbox
431         my $m = "_pre_augment_$self->{base_type}";
432         $self->$m($lei);
433 }
434
435 sub do_augment { # slow, runs in wq worker
436         my ($self, $lei) = @_;
437         # _do_augment_maildir, _do_augment_mbox
438         my $m = "_do_augment_$self->{base_type}";
439         $self->$m($lei);
440 }
441
442 sub post_augment { # fast (spawn compressor or mkdir), runs in main daemon
443         my ($self, $lei, @args) = @_;
444         # _post_augment_maildir, _post_augment_mbox
445         my $m = "_post_augment_$self->{base_type}";
446         $self->$m($lei, @args);
447 }
448
449 sub write_mail { # via ->wq_do
450         my ($self, $git_dir, $oid, $lei, $kw) = @_;
451         my $not_done = delete $self->{4}; # write end of {each_smsg_done}
452         my $wcb = $self->{wcb} //= do { # first message
453                 my %sig = $lei->atfork_child_wq($self);
454                 @SIG{keys %sig} = values %sig; # not local
455                 $lei->{dedupe}->prepare_dedupe;
456                 $self->write_cb($lei);
457         };
458         my $git = $self->{"$$\0$git_dir"} //= PublicInbox::Git->new($git_dir);
459         $git->cat_async($oid, \&git_to_mail, [ $wcb, $kw, $not_done ]);
460 }
461
462 sub ipc_atfork_prepare {
463         my ($self) = @_;
464         # (qry_status_wr, stdout|mbox, stderr, 3: sock, 4: each_smsg_done_wr)
465         $self->wq_set_recv_modes(qw[+<&= >&= >&= +<&= >&=]);
466         $self->SUPER::ipc_atfork_prepare; # PublicInbox::IPC
467 }
468
469 sub DESTROY {
470         my ($self) = @_;
471         for my $pid_git (grep(/\A$$\0/, keys %$self)) {
472                 $self->{$pid_git}->async_wait_all;
473         }
474 }
475
476 1;