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