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>
4 # Writes PublicInbox::Eml objects atomically to a mbox variant or Maildir
5 package PublicInbox::LeiToMail;
8 use parent qw(PublicInbox::IPC);
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;
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 use Digest::SHA qw(sha256_hex);
23 my ($maildir_each_file);
25 # struggles with short-lived repos, Gcf2Client makes little sense with lei;
26 # but we may use in-process libgit2 in the future.
27 $PublicInbox::GitAsyncCat::GCF2C = 0;
29 my %kw2char = ( # Maildir characters
37 flagged => [ 'X-Status' => 'F' ],
38 answered => [ 'X-Status' => 'A' ],
39 seen => [ 'Status' => 'R' ],
40 draft => [ 'X-Status' => 'T' ],
43 sub _mbox_hdr_buf ($$$) {
44 my ($eml, $type, $smsg) = @_;
45 $eml->header_set($_) for (qw(Lines Bytes Content-Length));
47 # Messages are always 'O' (non-\Recent in IMAP), it saves
48 # MUAs the trouble of rewriting the mbox if no other
50 my %hdr = (Status => [ 'O' ]); # set Status, X-Status
51 for my $k (@{$smsg->{kw} // []}) {
52 if (my $ent = $kw2status{$k}) {
53 push @{$hdr{$ent->[0]}}, $ent->[1];
55 warn "TODO: keyword `$k' not supported for mbox\n";
58 while (my ($name, $chars) = each %hdr) {
59 $eml->header_set($name, join('', sort @$chars));
61 my $buf = delete $eml->{hdr};
63 # fixup old bug from import (pre-a0c07cba0e5d8b6a)
64 $$buf =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
65 my $ident = $smsg->{blob} // 'lei';
66 if (defined(my $pct = $smsg->{pct})) { $ident .= "=$pct" }
68 substr($$buf, 0, 0, # prepend From line
69 "From $ident\@$type Thu Jan 1 00:00:00 1970$eml->{crlf}");
73 sub atomic_append { # for on-disk destinations (O_APPEND, or O_EXCL)
75 if (defined(my $w = syswrite($lei->{1} // return, $$buf))) {
76 return if $w == length($$buf);
77 $buf = "short atomic write: $w != ".length($$buf);
78 } elsif ($! == EPIPE) {
79 return $lei->note_sigpipe(1);
81 $buf = "atomic write: $!";
86 sub eml2mboxrd ($;$) {
87 my ($eml, $smsg) = @_;
88 my $buf = _mbox_hdr_buf($eml, 'mboxrd', $smsg);
89 if (my $bdy = delete $eml->{bdy}) {
90 $$bdy =~ s/^(>*From )/>$1/gm;
91 $$buf .= $eml->{crlf};
92 substr($$bdy, 0, 0, $$buf); # prepend header
95 $$buf .= $eml->{crlf};
100 my ($eml, $smsg) = @_;
101 my $buf = _mbox_hdr_buf($eml, 'mboxo', $smsg);
102 if (my $bdy = delete $eml->{bdy}) {
103 $$bdy =~ s/^From />From /gm;
104 $$buf .= $eml->{crlf};
105 substr($$bdy, 0, 0, $$buf); # prepend header
108 $$buf .= $eml->{crlf};
112 sub _mboxcl_common ($$$) {
113 my ($buf, $bdy, $crlf) = @_;
114 # add Lines: so mutt won't have to add it on MUA close
115 my $lines = $$bdy =~ tr!\n!\n!;
116 $$buf .= 'Content-Length: '.length($$bdy).$crlf.
117 'Lines: '.$lines.$crlf.$crlf;
118 substr($$bdy, 0, 0, $$buf); # prepend header
122 # mboxcl still escapes "From " lines
124 my ($eml, $smsg) = @_;
125 my $buf = _mbox_hdr_buf($eml, 'mboxcl', $smsg);
126 my $crlf = $eml->{crlf};
127 if (my $bdy = delete $eml->{bdy}) {
128 $$bdy =~ s/^From />From /gm;
129 _mboxcl_common($buf, $bdy, $crlf);
135 # mboxcl2 has no "From " escaping
137 my ($eml, $smsg) = @_;
138 my $buf = _mbox_hdr_buf($eml, 'mboxcl2', $smsg);
139 my $crlf = $eml->{crlf};
140 if (my $bdy = delete $eml->{bdy}) {
141 _mboxcl_common($buf, $bdy, $crlf);
147 sub git_to_mail { # git->cat_async callback
148 my ($bref, $oid, $type, $size, $arg) = @_;
149 if ($type ne 'blob') {
150 if ($type eq 'missing') {
151 warn "missing $oid\n";
153 warn "unexpected type=$type for $oid\n";
156 my ($write_cb, $smsg) = @$arg;
157 if ($smsg->{blob} ne $oid) {
158 die "BUG: expected=$smsg->{blob} got=$oid";
160 $write_cb->($bref, $smsg) if $size > 0;
163 sub reap_compress { # dwaitpid callback
164 my ($lei, $pid) = @_;
165 my $cmd = delete $lei->{"pid.$pid"};
167 $lei->fail("@$cmd failed", $? >> 8);
170 # all of these support -c for stdout and -d for decompression,
171 # mutt is commonly distributed with hooks for gz, bz2 and xz, at least
172 # { foo => '' } means "--foo" is passed to the command-line,
173 # otherwise { foo => '--bar' } passes "--bar"
175 gz => [ qw(GZIP pigz gzip), { rsyncable => '', threads => '-p' } ],
176 bz2 => [ 'bzip2', {} ],
177 xz => [ 'xz', { threads => '-T' } ],
178 # XXX does anybody care for these? I prefer zstd on entire FSes,
179 # so it's probably not necessary on a per-file basis
180 # zst => [ 'zstd', { -default => [ qw(-q) ], # it's noisy by default
181 # rsyncable => '', threads => '-T' } ],
182 # zz => [ 'pigz', { -default => [ '--zlib' ],
183 # rsyncable => '', threads => '-p' }],
184 # lzo => [ 'lzop', {} ],
185 # lzma => [ 'lzma', {} ],
189 my ($zsfx, $decompress, $lei) = @_;
190 my $x = $zsfx2cmd{$zsfx} // die "no support for suffix=.$zsfx";
192 my $cmd_opt = pop @info;
193 my @cmd = (undef, $decompress ? qw(-dc) : qw(-c));
194 for my $exe (@info) {
195 # I think respecting client's ENV{GZIP} is OK, not sure
196 # about ENV overrides for other, less-common compressors
197 if ($exe eq uc($exe)) {
198 $exe = $lei->{env}->{$exe} or next;
200 $cmd[0] = which($exe) and last;
202 $cmd[0] // die join(' or ', @info)." missing for .$zsfx";
203 # push @cmd, @{$cmd_opt->{-default}} if $cmd_opt->{-default};
204 for my $bool (qw(rsyncable)) {
205 my $switch = $cmd_opt->{rsyncable} // next;
206 push @cmd, '--'.($switch || $bool);
208 for my $key (qw(threads)) { # support compression level?
209 my $switch = $cmd_opt->{$key} // next;
210 my $val = $lei->{opt}->{$key} // next;
211 push @cmd, $switch, $val;
216 sub _post_augment_mbox { # open a compressor process
217 my ($self, $lei) = @_;
218 my $zsfx = $self->{zsfx} or return;
219 my $cmd = zsfx2cmd($zsfx, undef, $lei);
220 my ($r, $w) = @{delete $lei->{zpipe}};
221 my $rdr = { 0 => $r, 1 => $lei->{1}, 2 => $lei->{2} };
222 my $pid = spawn($cmd, $lei->{env}, $rdr);
224 my $dup = bless { "pid.$pid" => $cmd }, ref($lei);
225 $dup->{$_} = $lei->{$_} for qw(2 sock);
226 tie *$pp, 'PublicInbox::ProcessPipe', $pid, $w, \&reap_compress, $dup;
228 die 'BUG: unexpected {ovv}->{lock_path}' if $lei->{ovv}->{lock_path};
229 $lei->{ovv}->ovv_out_lk_init;
232 sub decompress_src ($$$) {
233 my ($in, $zsfx, $lei) = @_;
234 my $cmd = zsfx2cmd($zsfx, 1, $lei);
235 popen_rd($cmd, $lei->{env}, { 0 => $in, 2 => $lei->{2} });
240 open my $dup, '+>>&', $in or die "dup: $!";
244 # --augment existing output destination, with deduplication
245 sub _augment { # MboxReader eml_cb
246 my ($eml, $lei) = @_;
247 # ignore return value, just populate the skv
248 $lei->{dedupe}->is_dup($eml);
251 sub _mbox_write_cb ($$) {
252 my ($self, $lei) = @_;
253 my $ovv = $lei->{ovv};
254 my $m = 'eml2'.$ovv->{fmt};
255 my $eml2mbox = $self->can($m) or die "$self->$m missing";
256 $lei->{1} // die "no stdout ($m, $ovv->{dst})"; # redirected earlier
257 $lei->{1}->autoflush(1);
258 my $atomic_append = !defined($ovv->{lock_path});
259 my $dedupe = $lei->{dedupe};
260 $dedupe->prepare_dedupe;
261 sub { # for git_to_mail
262 my ($buf, $smsg, $eml) = @_;
263 $eml //= PublicInbox::Eml->new($buf);
264 return if $dedupe->is_dup($eml, $smsg->{blob});
265 $buf = $eml2mbox->($eml, $smsg);
266 return atomic_append($lei, $buf) if $atomic_append;
267 my $lk = $ovv->lock_for_scope;
272 sub _augment_file { # maildir_each_file cb
273 my ($f, $lei, $mod, $shard) = @_;
275 # can't get dirent.d_ino w/ pure Perl, so we extract the OID
276 # if it looks like one:
277 my $hex = $f =~ m!\b([a-f0-9]{40,})[^/]*\z! ?
279 my $recno = hex(substr($hex, 0, 8));
280 return if ($recno % $mod) != $shard;
282 my $eml = PublicInbox::InboxWritable::eml_from_path($f) or return;
283 _augment($eml, $lei);
286 # maildir_each_file callback, \&CORE::unlink doesn't work with it
287 sub _unlink { unlink($_[0]) }
291 sprintf('%x,%x,%x,%x', rand(0xffffffff), time, $$, ++$seq);
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" }
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
314 $final = $dst.$rand.$common.':2,'.$sfx;
315 } while (!($ok = link($tmp, $final)) && $! == EEXIST &&
316 ($rand = _rand.','));
317 die "link($tmp, $final): $!" unless $ok;
318 unlink($tmp) or warn "W: failed to unlink $tmp: $!\n";
320 my $err = "Error writing $smsg->{blob} to $dst: $!\n";
321 $_[0] = undef; # clobber dst
327 sub _maildir_write_cb ($$) {
328 my ($self, $lei) = @_;
329 my $dedupe = $lei->{dedupe};
330 $dedupe->prepare_dedupe if $dedupe;
331 my $dst = $lei->{ovv}->{dst};
332 sub { # for git_to_mail
333 my ($buf, $smsg, $eml) = @_;
334 $dst // return $lei->fail; # dst may be undef-ed in last run
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});
340 _buf2maildir($dst, $buf, $smsg);
344 sub _imap_write_cb ($$) {
345 my ($self, $lei) = @_;
346 my $dedupe = $lei->{dedupe};
347 $dedupe->prepare_dedupe if $dedupe;
348 my $imap_append = $lei->{net}->can('imap_append');
349 my $mic = $lei->{net}->mic_get($self->{uri});
350 my $folder = $self->{uri}->mailbox;
351 sub { # for git_to_mail
352 my ($bref, $smsg, $eml) = @_;
353 $mic // return $lei->fail; # dst may be undef-ed in last run
355 $eml //= PublicInbox::Eml->new($$bref); # copy bref
356 return if $dedupe->is_dup($eml, $smsg->{blob});
358 eval { $imap_append->($mic, $folder, $bref, $smsg, $eml) };
366 sub write_cb { # returns a callback for git_to_mail
367 my ($self, $lei) = @_;
368 # _mbox_write_cb, _maildir_write_cb or _imap_write_cb
369 my $m = "_$self->{base_type}_write_cb";
374 my ($cls, $lei) = @_;
375 my $fmt = $lei->{ovv}->{fmt};
376 my $dst = $lei->{ovv}->{dst};
377 my $self = bless {}, $cls;
378 if ($fmt eq 'maildir') {
379 $maildir_each_file //= do {
380 require PublicInbox::MdirReader;
381 PublicInbox::MdirReader->can('maildir_each_file');
383 $lei->{opt}->{augment} and
384 require PublicInbox::InboxWritable; # eml_from_path
385 $self->{base_type} = 'maildir';
386 -e $dst && !-d _ and die
387 "$dst exists and is not a directory\n";
388 $lei->{ovv}->{dst} = $dst .= '/' if substr($dst, -1) ne '/';
389 } elsif (substr($fmt, 0, 4) eq 'mbox') {
390 require PublicInbox::MboxReader if $lei->{opt}->{augment};
391 (-d $dst || (-e _ && !-w _)) and die
392 "$dst exists and is not a writable file\n";
393 $self->can("eml2$fmt") or die "bad mbox format: $fmt\n";
394 $self->{base_type} = 'mbox';
395 } elsif ($fmt =~ /\Aimaps?\z/) { # TODO .onion support
396 require PublicInbox::NetWriter;
397 my $net = PublicInbox::NetWriter->new;
399 $net->{quiet} = $lei->{opt}->{quiet};
400 my $err = $net->errors($dst);
401 return $lei->fail($err) if $err;
402 require PublicInbox::URIimap; # TODO: URI cast early
403 $self->{uri} = PublicInbox::URIimap->new($dst);
404 $self->{uri}->mailbox or die "No mailbox: $dst";
406 $self->{base_type} = 'imap';
408 die "bad mail --format=$fmt\n";
411 $lei->{dedupe} = PublicInbox::LeiDedupe->new($lei);
415 sub _pre_augment_maildir {
416 my ($self, $lei) = @_;
417 my $dst = $lei->{ovv}->{dst};
418 for my $x (qw(tmp new cur)) {
422 File::Path::mkpath($d);
423 -d $d or die "$d is not a directory";
427 sub _do_augment_maildir {
428 my ($self, $lei) = @_;
429 my $dst = $lei->{ovv}->{dst};
430 if ($lei->{opt}->{augment}) {
431 my $dedupe = $lei->{dedupe};
432 if ($dedupe && $dedupe->prepare_dedupe) {
433 my ($mod, $shard) = @{$self->{shard_info} // []};
434 $maildir_each_file->($dst, \&_augment_file,
436 $dedupe->pause_dedupe;
438 } else { # clobber existing Maildir
439 $maildir_each_file->($dst, \&_unlink);
443 sub _augment_imap { # PublicInbox::NetReader::imap_each cb
444 my ($url, $uid, $kw, $eml, $lei) = @_;
445 _augment($eml, $lei);
448 sub _do_augment_imap {
449 my ($self, $lei) = @_;
450 my $net = $lei->{net};
451 if ($lei->{opt}->{augment}) {
452 my $dedupe = $lei->{dedupe};
453 if ($dedupe && $dedupe->prepare_dedupe) {
454 $net->imap_each($self->{uri}, \&_augment_imap, $lei);
455 $dedupe->pause_dedupe;
457 } elsif (!$self->{-wq_worker_nr}) { # undef or 0
458 # clobber existing IMAP folder
459 $net->imap_delete_all($self->{uri});
463 sub _pre_augment_mbox {
464 my ($self, $lei) = @_;
465 my $dst = $lei->{ovv}->{dst};
466 if ($dst ne '/dev/stdout') {
467 my $mode = -p $dst ? '>' : '+>>';
468 if (-f _ && !$lei->{opt}->{augment} and !unlink($dst)) {
469 $! == ENOENT or die "unlink($dst): $!";
471 open my $out, $mode, $dst or die "open($dst): $!";
472 $lei->{old_1} = $lei->{1}; # keep for spawning MUA
475 # Perl does SEEK_END even with O_APPEND :<
476 $self->{seekable} = seek($lei->{1}, 0, SEEK_SET);
477 if (!$self->{seekable} && $! != ESPIPE && $dst ne '/dev/stdout') {
478 die "seek($dst): $!\n";
480 state $zsfx_allow = join('|', keys %zsfx2cmd);
481 ($self->{zsfx}) = ($dst =~ /\.($zsfx_allow)\z/) or return;
482 pipe(my ($r, $w)) or die "pipe: $!";
483 $lei->{zpipe} = [ $r, $w ];
486 sub _do_augment_mbox {
487 my ($self, $lei) = @_;
488 return if !$lei->{opt}->{augment};
489 my $dedupe = $lei->{dedupe};
490 my $dst = $lei->{ovv}->{dst};
491 die "cannot augment $dst, not seekable\n" if !$self->{seekable};
493 if (-s $out && $dedupe && $dedupe->prepare_dedupe) {
494 my $zsfx = $self->{zsfx};
495 my $rd = $zsfx ? decompress_src($out, $zsfx, $lei) :
497 my $fmt = $lei->{ovv}->{fmt};
498 PublicInbox::MboxReader->$fmt($rd, \&_augment, $lei);
500 # maybe some systems don't honor O_APPEND, Perl does this:
501 seek($out, 0, SEEK_END) or die "seek $dst: $!";
502 $dedupe->pause_dedupe if $dedupe;
505 sub pre_augment { # fast (1 disk seek), runs in same process as post_augment
506 my ($self, $lei) = @_;
507 # _pre_augment_maildir, _pre_augment_mbox
508 my $m = $self->can("_pre_augment_$self->{base_type}") or return;
512 sub do_augment { # slow, runs in wq worker
513 my ($self, $lei) = @_;
514 # _do_augment_maildir, _do_augment_mbox, or _do_augment_imap
515 my $m = "_do_augment_$self->{base_type}";
519 # fast (spawn compressor or mkdir), runs in same process as pre_augment
521 my ($self, $lei, @args) = @_;
523 my $m = $self->can("_post_augment_$self->{base_type}") or return;
524 $m->($self, $lei, @args);
529 my $lei = $self->{lei};
530 # lei_xsearch can start as soon as all l2m workers get here
531 pkt_do($lei->{pkt_op_p}, 'incr_start_query') or
532 die "incr_start_query: $!";
534 if (lock_free($self)) {
535 my $mod = $self->{-wq_nr_workers};
536 my $shard = $self->{-wq_worker_nr};
537 if (my $net = $lei->{net}) {
538 $net->{shard_info} = [ $mod, $shard ];
539 } else { # Maildir (MH?)
540 $self->{shard_info} = [ $mod, $shard ];
542 $aug = '+'; # incr_post_augment
543 } elsif ($self->{-wq_worker_nr} == 0) {
544 $aug = '.'; # do_post_augment
547 local $0 = 'do_augment';
548 eval { do_augment($self, $lei) };
549 $lei->fail($@) if $@;
550 pkt_do($lei->{pkt_op_p}, $aug) == 1 or
551 die "do_post_augment trigger: $!";
553 if (my $zpipe = delete $lei->{zpipe}) {
554 $lei->{1} = $zpipe->[1];
557 $self->{wcb} = $self->write_cb($lei);
560 sub ipc_atfork_child {
562 my $lei = $self->{lei};
563 $lei->lei_atfork_child;
564 $lei->{auth}->do_auth_atfork($self) if $lei->{auth};
565 $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb();
566 $self->SUPER::ipc_atfork_child;
570 $_[0]->{base_type} =~ /\A(?:maildir|mh|imap|jmap)\z/ ? 1 : 0;
575 if ($self->{base_type} eq 'maildir') {
577 utime($t, $t, "$self->{dst}/cur");
581 sub write_mail { # via ->wq_io_do
582 my ($self, $git_dir, $smsg) = @_;
583 my $git = $self->{"$$\0$git_dir"} //= PublicInbox::Git->new($git_dir);
584 git_async_cat($git, $smsg->{blob}, \&git_to_mail,
585 [$self->{wcb}, $smsg]);
588 sub wq_atexit_child {
591 for my $git (delete @$self{grep(/\A$$\0/, keys %$self)}) {
592 $git->async_wait_all;
594 $SIG{__WARN__} = 'DEFAULT';
597 # called in top-level lei-daemon when LeiAuth is done
598 sub net_merge_complete {
600 $self->wq_broadcast('do_post_auth');
604 no warnings 'once'; # the following works even when LeiAuth is lazy-loaded
605 *net_merge_all = \&PublicInbox::LeiAuth::net_merge_all;