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