]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiToMail.pm
ipc: switch wq to use the event loop
[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);
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 ($fh, $buf) = @_;
72         defined(my $w = syswrite($fh, $$buf)) or die "write: $!";
73         $w == length($$buf) or die "short write: $w != ".length($$buf);
74 }
75
76 sub _print_full {
77         my ($fh, $buf) = @_;
78         print $fh $$buf or die "print: $!";
79 }
80
81 sub eml2mboxrd ($;$) {
82         my ($eml, $smsg) = @_;
83         my $buf = _mbox_hdr_buf($eml, 'mboxrd', $smsg);
84         if (my $bdy = delete $eml->{bdy}) {
85                 $$bdy =~ s/^(>*From )/>$1/gm;
86                 $$buf .= $eml->{crlf};
87                 substr($$bdy, 0, 0, $$buf); # prepend header
88                 $buf = $bdy;
89         }
90         $$buf .= $eml->{crlf};
91         $buf;
92 }
93
94 sub eml2mboxo {
95         my ($eml, $smsg) = @_;
96         my $buf = _mbox_hdr_buf($eml, 'mboxo', $smsg);
97         if (my $bdy = delete $eml->{bdy}) {
98                 $$bdy =~ s/^From />From /gm;
99                 $$buf .= $eml->{crlf};
100                 substr($$bdy, 0, 0, $$buf); # prepend header
101                 $buf = $bdy;
102         }
103         $$buf .= $eml->{crlf};
104         $buf;
105 }
106
107 sub _mboxcl_common ($$$) {
108         my ($buf, $bdy, $crlf) = @_;
109         # add Lines: so mutt won't have to add it on MUA close
110         my $lines = $$bdy =~ tr!\n!\n!;
111         $$buf .= 'Content-Length: '.length($$bdy).$crlf.
112                 'Lines: '.$lines.$crlf.$crlf;
113         substr($$bdy, 0, 0, $$buf); # prepend header
114         $_[0] = $bdy;
115 }
116
117 # mboxcl still escapes "From " lines
118 sub eml2mboxcl {
119         my ($eml, $smsg) = @_;
120         my $buf = _mbox_hdr_buf($eml, 'mboxcl', $smsg);
121         my $crlf = $eml->{crlf};
122         if (my $bdy = delete $eml->{bdy}) {
123                 $$bdy =~ s/^From />From /gm;
124                 _mboxcl_common($buf, $bdy, $crlf);
125         }
126         $$buf .= $crlf;
127         $buf;
128 }
129
130 # mboxcl2 has no "From " escaping
131 sub eml2mboxcl2 {
132         my ($eml, $smsg) = @_;
133         my $buf = _mbox_hdr_buf($eml, 'mboxcl2', $smsg);
134         my $crlf = $eml->{crlf};
135         if (my $bdy = delete $eml->{bdy}) {
136                 _mboxcl_common($buf, $bdy, $crlf);
137         }
138         $$buf .= $crlf;
139         $buf;
140 }
141
142 sub git_to_mail { # git->cat_async callback
143         my ($bref, $oid, $type, $size, $arg) = @_;
144         if ($type ne 'blob') {
145                 if ($type eq 'missing') {
146                         warn "missing $oid\n";
147                 } else {
148                         warn "unexpected type=$type for $oid\n";
149                 }
150         }
151         my ($write_cb, $smsg) = @$arg;
152         if ($smsg->{blob} ne $oid) {
153                 die "BUG: expected=$smsg->{blob} got=$oid";
154         }
155         $write_cb->($bref, $smsg) if $size > 0;
156 }
157
158 sub reap_compress { # dwaitpid callback
159         my ($lei, $pid) = @_;
160         my $cmd = delete $lei->{"pid.$pid"};
161         return if $? == 0;
162         $lei->fail("@$cmd failed", $? >> 8);
163 }
164
165 # all of these support -c for stdout and -d for decompression,
166 # mutt is commonly distributed with hooks for gz, bz2 and xz, at least
167 # { foo => '' } means "--foo" is passed to the command-line,
168 # otherwise { foo => '--bar' } passes "--bar"
169 our %zsfx2cmd = (
170         gz => [ qw(GZIP pigz gzip), { rsyncable => '', threads => '-p' } ],
171         bz2 => [ 'bzip2', {} ],
172         xz => [ 'xz', { threads => '-T' } ],
173         # XXX does anybody care for these?  I prefer zstd on entire FSes,
174         # so it's probably not necessary on a per-file basis
175         # zst => [ 'zstd', { -default => [ qw(-q) ], # it's noisy by default
176         #       rsyncable => '', threads => '-T' } ],
177         # zz => [ 'pigz', { -default => [ '--zlib' ],
178         #       rsyncable => '', threads => '-p' }],
179         # lzo => [ 'lzop', {} ],
180         # lzma => [ 'lzma', {} ],
181 );
182
183 sub zsfx2cmd ($$$) {
184         my ($zsfx, $decompress, $lei) = @_;
185         my $x = $zsfx2cmd{$zsfx} // die "no support for suffix=.$zsfx";
186         my @info = @$x;
187         my $cmd_opt = pop @info;
188         my @cmd = (undef, $decompress ? qw(-dc) : qw(-c));
189         for my $exe (@info) {
190                 # I think respecting client's ENV{GZIP} is OK, not sure
191                 # about ENV overrides for other, less-common compressors
192                 if ($exe eq uc($exe)) {
193                         $exe = $lei->{env}->{$exe} or next;
194                 }
195                 $cmd[0] = which($exe) and last;
196         }
197         $cmd[0] // die join(' or ', @info)." missing for .$zsfx";
198         # push @cmd, @{$cmd_opt->{-default}} if $cmd_opt->{-default};
199         for my $bool (qw(rsyncable)) {
200                 my $switch = $cmd_opt->{rsyncable} // next;
201                 push @cmd, '--'.($switch || $bool);
202         }
203         for my $key (qw(threads)) { # support compression level?
204                 my $switch = $cmd_opt->{$key} // next;
205                 my $val = $lei->{opt}->{$key} // next;
206                 push @cmd, $switch, $val;
207         }
208         \@cmd;
209 }
210
211 sub _post_augment_mbox { # open a compressor process
212         my ($self, $lei, $zpipe) = @_;
213         my $zsfx = $self->{zsfx} or return;
214         my $cmd = zsfx2cmd($zsfx, undef, $lei);
215         my ($r, $w) = splice(@$zpipe, 0, 2);
216         my $rdr = { 0 => $r, 1 => $lei->{1}, 2 => $lei->{2} };
217         my $pid = spawn($cmd, $lei->{env}, $rdr);
218         my $pp = gensym;
219         my $dup = bless { "pid.$pid" => $cmd }, ref($lei);
220         $dup->{$_} = $lei->{$_} for qw(2 sock);
221         tie *$pp, 'PublicInbox::ProcessPipe', $pid, $w, \&reap_compress, $dup;
222         $lei->{1} = $pp;
223         die 'BUG: unexpected {ovv}->{lock_path}' if $lei->{ovv}->{lock_path};
224         $lei->{ovv}->ovv_out_lk_init;
225 }
226
227 sub decompress_src ($$$) {
228         my ($in, $zsfx, $lei) = @_;
229         my $cmd = zsfx2cmd($zsfx, 1, $lei);
230         popen_rd($cmd, $lei->{env}, { 0 => $in, 2 => $lei->{2} });
231 }
232
233 sub dup_src ($) {
234         my ($in) = @_;
235         open my $dup, '+>>&', $in or die "dup: $!";
236         $dup;
237 }
238
239 # --augment existing output destination, with deduplication
240 sub _augment { # MboxReader eml_cb
241         my ($eml, $lei) = @_;
242         # ignore return value, just populate the skv
243         $lei->{dedupe}->is_dup($eml);
244 }
245
246 sub _mbox_write_cb ($$) {
247         my ($self, $lei) = @_;
248         my $ovv = $lei->{ovv};
249         my $m = 'eml2'.$ovv->{fmt};
250         my $eml2mbox = $self->can($m) or die "$self->$m missing";
251         my $out = $lei->{1} // die "no stdout ($m, $ovv->{dst})"; # redirected earlier
252         $out->autoflush(1);
253         my $write = $ovv->{lock_path} ? \&_print_full : \&atomic_append;
254         my $dedupe = $lei->{dedupe};
255         $dedupe->prepare_dedupe;
256         sub { # for git_to_mail
257                 my ($buf, $smsg, $eml) = @_;
258                 return unless $out;
259                 $eml //= PublicInbox::Eml->new($buf);
260                 if (!$dedupe->is_dup($eml, $smsg->{blob})) {
261                         $buf = $eml2mbox->($eml, $smsg);
262                         my $lk = $ovv->lock_for_scope;
263                         eval { $write->($out, $buf) };
264                         if ($@) {
265                                 die $@ if ref($@) ne 'PublicInbox::SIGPIPE';
266                                 undef $out
267                         }
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 _rand () {
293         state $seq = 0;
294         sprintf('%x,%x,%x,%x', rand(0xffffffff), time, $$, ++$seq);
295 }
296
297 sub _buf2maildir {
298         my ($dst, $buf, $smsg) = @_;
299         my $kw = $smsg->{kw} // [];
300         my $sfx = join('', sort(map { $kw2char{$_} // () } @$kw));
301         my $rand = ''; # chosen by die roll :P
302         my ($tmp, $fh, $final);
303         my $common = $smsg->{blob} // _rand;
304         if (defined(my $pct = $smsg->{pct})) { $common .= "=$pct" }
305         do {
306                 $tmp = $dst.'tmp/'.$rand.$common;
307         } while (!sysopen($fh, $tmp, O_CREAT|O_EXCL|O_WRONLY) &&
308                 $! == EEXIST && ($rand = _rand.','));
309         if (print $fh $$buf and close($fh)) {
310                 # ignore new/ and write only to cur/, otherwise MUAs
311                 # with R/W access to the Maildir will end up doing
312                 # a mass rename which can take a while with thousands
313                 # of messages.
314                 $dst .= 'cur/';
315                 $rand = '';
316                 do {
317                         $final = $dst.$rand.$common.':2,'.$sfx;
318                 } while (!link($tmp, $final) && $! == EEXIST &&
319                         ($rand = _rand.','));
320                 unlink($tmp) or warn "W: failed to unlink $tmp: $!\n";
321         } else {
322                 my $err = $!;
323                 unlink($tmp);
324                 die "Error writing $smsg->{blob} to $dst: $err";
325         }
326 }
327
328 sub _maildir_write_cb ($$) {
329         my ($self, $lei) = @_;
330         my $dedupe = $lei->{dedupe};
331         $dedupe->prepare_dedupe if $dedupe;
332         my $dst = $lei->{ovv}->{dst};
333         sub { # for git_to_mail
334                 my ($buf, $smsg, $eml) = @_;
335                 $buf //= \($eml->as_string);
336                 return _buf2maildir($dst, $buf, $smsg) if !$dedupe;
337                 $eml //= PublicInbox::Eml->new($$buf); # copy buf
338                 return if $dedupe->is_dup($eml, $smsg->{blob});
339                 undef $eml;
340                 _buf2maildir($dst, $buf, $smsg);
341         }
342 }
343
344 sub write_cb { # returns a callback for git_to_mail
345         my ($self, $lei) = @_;
346         # _mbox_write_cb or _maildir_write_cb
347         my $m = "_$self->{base_type}_write_cb";
348         $self->$m($lei);
349 }
350
351 sub new {
352         my ($cls, $lei) = @_;
353         my $fmt = $lei->{ovv}->{fmt};
354         my $dst = $lei->{ovv}->{dst};
355         my $self = bless {}, $cls;
356         if ($fmt eq 'maildir') {
357                 $self->{base_type} = 'maildir';
358                 -e $dst && !-d _ and die
359                                 "$dst exists and is not a directory\n";
360                 $lei->{ovv}->{dst} = $dst .= '/' if substr($dst, -1) ne '/';
361         } elsif (substr($fmt, 0, 4) eq 'mbox') {
362                 (-d $dst || (-e _ && !-w _)) and die
363                         "$dst exists and is not a writable file\n";
364                 $self->can("eml2$fmt") or die "bad mbox --format=$fmt\n";
365                 $self->{base_type} = 'mbox';
366         } else {
367                 die "bad mail --format=$fmt\n";
368         }
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};
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         [ $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 write_mail { # via ->wq_do
467         my ($self, $git_dir, $smsg, $lei) = @_;
468         my $not_done = delete $self->{$lei->{each_smsg_not_done}};
469         my $wcb = $self->{wcb} //= do { # first message
470                 my %sig = $lei->atfork_child_wq($self);
471                 @SIG{keys %sig} = values %sig; # not local
472                 $self->write_cb($lei);
473         };
474         my $git = $self->{"$$\0$git_dir"} //= PublicInbox::Git->new($git_dir);
475         git_async_cat($git, $smsg->{blob}, \&git_to_mail,
476                                 [$wcb, $smsg, $not_done]);
477 }
478
479 sub wq_atexit_child {
480         my ($self) = @_;
481         delete $self->{wcb};
482         for my $git (delete @$self{grep(/\A$$\0/, keys %$self)}) {
483                 $git->async_wait_all;
484         }
485         $SIG{__WARN__} = 'DEFAULT';
486         $SIG{PIPE} = 'DEFAULT';
487 }
488
489 1;