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;
15 use PublicInbox::GitAsyncCat;
16 use PublicInbox::PktOp qw(pkt_do);
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 EPIPE);
21 use Digest::SHA qw(sha256_hex);
22 my ($maildir_each_file);
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;
28 my %kw2char = ( # Maildir characters
36 flagged => [ 'X-Status' => 'F' ],
37 answered => [ 'X-Status' => 'A' ],
38 seen => [ 'Status' => 'R' ],
39 draft => [ 'X-Status' => 'T' ],
42 sub _mbox_hdr_buf ($$$) {
43 my ($eml, $type, $smsg) = @_;
44 $eml->header_set($_) for (qw(Lines Bytes Content-Length));
46 # Messages are always 'O' (non-\Recent in IMAP), it saves
47 # MUAs the trouble of rewriting the mbox if no other
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];
54 warn "TODO: keyword `$k' not supported for mbox\n";
57 while (my ($name, $chars) = each %hdr) {
58 $eml->header_set($name, join('', sort @$chars));
60 my $buf = delete $eml->{hdr};
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" }
67 substr($$buf, 0, 0, # prepend From line
68 "From $ident\@$type Thu Jan 1 00:00:00 1970$eml->{crlf}");
72 sub atomic_append { # for on-disk destinations (O_APPEND, or O_EXCL)
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);
80 $buf = "atomic write: $!";
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
94 $$buf .= $eml->{crlf};
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
107 $$buf .= $eml->{crlf};
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
121 # mboxcl still escapes "From " lines
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);
134 # mboxcl2 has no "From " escaping
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);
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";
152 warn "unexpected type=$type for $oid\n";
155 my ($write_cb, $smsg) = @$arg;
156 if ($smsg->{blob} ne $oid) {
157 die "BUG: expected=$smsg->{blob} got=$oid";
159 $write_cb->($bref, $smsg) if $size > 0;
162 sub reap_compress { # dwaitpid callback
163 my ($lei, $pid) = @_;
164 my $cmd = delete $lei->{"pid.$pid"};
166 $lei->fail("@$cmd failed", $? >> 8);
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"
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', {} ],
188 my ($zsfx, $decompress, $lei) = @_;
189 my $x = $zsfx2cmd{$zsfx} // die "no support for suffix=.$zsfx";
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;
199 $cmd[0] = which($exe) and last;
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);
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;
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, undef, $rdr);
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;
227 die 'BUG: unexpected {ovv}->{lock_path}' if $lei->{ovv}->{lock_path};
228 $lei->{ovv}->ovv_out_lk_init;
231 sub decompress_src ($$$) {
232 my ($in, $zsfx, $lei) = @_;
233 my $cmd = zsfx2cmd($zsfx, 1, $lei);
234 popen_rd($cmd, undef, { 0 => $in, 2 => $lei->{2} });
239 open my $dup, '+>>&', $in or die "dup: $!";
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);
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;
271 sub _augment_file { # maildir_each_file cb
272 my ($f, $lei, $mod, $shard) = @_;
274 # can't get dirent.d_ino w/ pure Perl, so we extract the OID
275 # if it looks like one:
276 my $hex = $f =~ m!\b([a-f0-9]{40,})[^/]*\z! ?
278 my $recno = hex(substr($hex, 0, 8));
279 return if ($recno % $mod) != $shard;
281 my $eml = PublicInbox::InboxWritable::eml_from_path($f) or return;
282 _augment($eml, $lei);
285 # maildir_each_file callback, \&CORE::unlink doesn't work with it
286 sub _unlink { unlink($_[0]) }
290 sprintf('%x,%x,%x,%x', rand(0xffffffff), time, $$, ++$seq);
294 my ($dst, $buf, $smsg) = @_;
295 my $kw = $smsg->{kw} // [];
296 my $sfx = join('', sort(map { $kw2char{$_} // () } @$kw));
297 my $rand = ''; # chosen by die roll :P
298 my ($tmp, $fh, $final, $ok);
299 my $common = $smsg->{blob} // _rand;
300 if (defined(my $pct = $smsg->{pct})) { $common .= "=$pct" }
302 $tmp = $dst.'tmp/'.$rand.$common;
303 } while (!($ok = sysopen($fh, $tmp, O_CREAT|O_EXCL|O_WRONLY)) &&
304 $! == EEXIST && ($rand = _rand.','));
305 if ($ok && print $fh $$buf and close($fh)) {
306 # ignore new/ and write only to cur/, otherwise MUAs
307 # with R/W access to the Maildir will end up doing
308 # a mass rename which can take a while with thousands
313 $final = $dst.$rand.$common.':2,'.$sfx;
314 } while (!($ok = link($tmp, $final)) && $! == EEXIST &&
315 ($rand = _rand.','));
316 die "link($tmp, $final): $!" unless $ok;
317 unlink($tmp) or warn "W: failed to unlink $tmp: $!\n";
319 my $err = "Error writing $smsg->{blob} to $dst: $!\n";
320 $_[0] = undef; # clobber dst
326 sub _maildir_write_cb ($$) {
327 my ($self, $lei) = @_;
328 my $dedupe = $lei->{dedupe};
329 $dedupe->prepare_dedupe if $dedupe;
330 my $dst = $lei->{ovv}->{dst};
331 sub { # for git_to_mail
332 my ($buf, $smsg, $eml) = @_;
333 $dst // return $lei->fail; # dst may be undef-ed in last run
334 $buf //= \($eml->as_string);
335 return _buf2maildir($dst, $buf, $smsg) if !$dedupe;
336 $eml //= PublicInbox::Eml->new($$buf); # copy buf
337 return if $dedupe->is_dup($eml, $smsg->{blob});
339 _buf2maildir($dst, $buf, $smsg);
343 sub _imap_write_cb ($$) {
344 my ($self, $lei) = @_;
345 my $dedupe = $lei->{dedupe};
346 $dedupe->prepare_dedupe if $dedupe;
347 my $imap_append = $lei->{net}->can('imap_append');
348 my $mic = $lei->{net}->mic_get($self->{uri});
349 my $folder = $self->{uri}->mailbox;
350 sub { # for git_to_mail
351 my ($bref, $smsg, $eml) = @_;
352 $mic // return $lei->fail; # dst may be undef-ed in last run
354 $eml //= PublicInbox::Eml->new($$bref); # copy bref
355 return if $dedupe->is_dup($eml, $smsg->{blob});
357 eval { $imap_append->($mic, $folder, $bref, $smsg, $eml) };
365 sub write_cb { # returns a callback for git_to_mail
366 my ($self, $lei) = @_;
367 # _mbox_write_cb, _maildir_write_cb or _imap_write_cb
368 my $m = "_$self->{base_type}_write_cb";
373 my ($cls, $lei) = @_;
374 my $fmt = $lei->{ovv}->{fmt};
375 my $dst = $lei->{ovv}->{dst};
376 my $self = bless {}, $cls;
377 if ($fmt eq 'maildir') {
378 $maildir_each_file //= do {
379 require PublicInbox::MdirReader;
380 PublicInbox::MdirReader->can('maildir_each_file');
382 $lei->{opt}->{augment} and
383 require PublicInbox::InboxWritable; # eml_from_path
384 $self->{base_type} = 'maildir';
385 -e $dst && !-d _ and die
386 "$dst exists and is not a directory\n";
387 $lei->{ovv}->{dst} = $dst .= '/' if substr($dst, -1) ne '/';
388 } elsif (substr($fmt, 0, 4) eq 'mbox') {
389 require PublicInbox::MboxReader if $lei->{opt}->{augment};
390 (-d $dst || (-e _ && !-w _)) and die
391 "$dst exists and is not a writable file\n";
392 $self->can("eml2$fmt") or die "bad mbox format: $fmt\n";
393 $self->{base_type} = 'mbox';
394 } elsif ($fmt =~ /\Aimaps?\z/) { # TODO .onion support
395 require PublicInbox::NetWriter;
396 my $net = PublicInbox::NetWriter->new;
398 $net->{quiet} = $lei->{opt}->{quiet};
399 my $err = $net->errors($dst);
400 return $lei->fail($err) if $err;
401 require PublicInbox::URIimap; # TODO: URI cast early
402 $self->{uri} = PublicInbox::URIimap->new($dst);
403 $self->{uri}->mailbox or die "No mailbox: $dst";
405 $self->{base_type} = 'imap';
407 die "bad mail --format=$fmt\n";
410 $lei->{dedupe} = PublicInbox::LeiDedupe->new($lei);
414 sub _pre_augment_maildir {
415 my ($self, $lei) = @_;
416 my $dst = $lei->{ovv}->{dst};
417 for my $x (qw(tmp new cur)) {
421 File::Path::mkpath($d);
422 -d $d or die "$d is not a directory";
426 sub _do_augment_maildir {
427 my ($self, $lei) = @_;
428 my $dst = $lei->{ovv}->{dst};
429 if ($lei->{opt}->{augment}) {
430 my $dedupe = $lei->{dedupe};
431 if ($dedupe && $dedupe->prepare_dedupe) {
432 my ($mod, $shard) = @{$self->{shard_info} // []};
433 $maildir_each_file->($dst, \&_augment_file,
435 $dedupe->pause_dedupe;
437 } else { # clobber existing Maildir
438 $maildir_each_file->($dst, \&_unlink);
442 sub _augment_imap { # PublicInbox::NetReader::imap_each cb
443 my ($url, $uid, $kw, $eml, $lei) = @_;
444 _augment($eml, $lei);
447 sub _do_augment_imap {
448 my ($self, $lei) = @_;
449 my $net = $lei->{net};
450 if ($lei->{opt}->{augment}) {
451 my $dedupe = $lei->{dedupe};
452 if ($dedupe && $dedupe->prepare_dedupe) {
453 $net->imap_each($self->{uri}, \&_augment_imap, $lei);
454 $dedupe->pause_dedupe;
456 } elsif (!$self->{-wq_worker_nr}) { # undef or 0
457 # clobber existing IMAP folder
458 $net->imap_delete_all($self->{uri});
462 sub _pre_augment_mbox {
463 my ($self, $lei) = @_;
464 my $dst = $lei->{ovv}->{dst};
465 if ($dst ne '/dev/stdout') {
468 open $out, '>', $dst or die "open($dst): $!";
469 } elsif (-f _ || !-e _) {
470 require PublicInbox::MboxLock;
471 my $m = $lei->{opt}->{'lock'} //
472 PublicInbox::MboxLock->defaults;
473 $self->{mbl} = PublicInbox::MboxLock->acq($dst, 1, $m);
474 $out = $self->{mbl}->{fh};
475 if (!$lei->{opt}->{augment} and !truncate($out, 0)) {
476 die "truncate($dst): $!";
479 $lei->{old_1} = $lei->{1}; # keep for spawning MUA
482 # Perl does SEEK_END even with O_APPEND :<
483 $self->{seekable} = seek($lei->{1}, 0, SEEK_SET);
484 if (!$self->{seekable} && $! != ESPIPE && $dst ne '/dev/stdout') {
485 die "seek($dst): $!\n";
487 state $zsfx_allow = join('|', keys %zsfx2cmd);
488 ($self->{zsfx}) = ($dst =~ /\.($zsfx_allow)\z/) or return;
489 pipe(my ($r, $w)) or die "pipe: $!";
490 $lei->{zpipe} = [ $r, $w ];
493 sub _do_augment_mbox {
494 my ($self, $lei) = @_;
495 return if !$lei->{opt}->{augment};
496 my $dedupe = $lei->{dedupe};
497 my $dst = $lei->{ovv}->{dst};
498 die "cannot augment $dst, not seekable\n" if !$self->{seekable};
500 if (-s $out && $dedupe && $dedupe->prepare_dedupe) {
501 my $zsfx = $self->{zsfx};
502 my $rd = $zsfx ? decompress_src($out, $zsfx, $lei) :
504 my $fmt = $lei->{ovv}->{fmt};
505 PublicInbox::MboxReader->$fmt($rd, \&_augment, $lei);
507 # maybe some systems don't honor O_APPEND, Perl does this:
508 seek($out, 0, SEEK_END) or die "seek $dst: $!";
509 $dedupe->pause_dedupe if $dedupe;
512 sub pre_augment { # fast (1 disk seek), runs in same process as post_augment
513 my ($self, $lei) = @_;
514 # _pre_augment_maildir, _pre_augment_mbox
515 my $m = $self->can("_pre_augment_$self->{base_type}") or return;
519 sub do_augment { # slow, runs in wq worker
520 my ($self, $lei) = @_;
521 # _do_augment_maildir, _do_augment_mbox, or _do_augment_imap
522 my $m = "_do_augment_$self->{base_type}";
526 # fast (spawn compressor or mkdir), runs in same process as pre_augment
528 my ($self, $lei, @args) = @_;
530 my $m = $self->can("_post_augment_$self->{base_type}") or return;
531 $m->($self, $lei, @args);
536 my $lei = $self->{lei};
537 # lei_xsearch can start as soon as all l2m workers get here
538 pkt_do($lei->{pkt_op_p}, 'incr_start_query') or
539 die "incr_start_query: $!";
541 if (lock_free($self)) {
542 my $mod = $self->{-wq_nr_workers};
543 my $shard = $self->{-wq_worker_nr};
544 if (my $net = $lei->{net}) {
545 $net->{shard_info} = [ $mod, $shard ];
546 } else { # Maildir (MH?)
547 $self->{shard_info} = [ $mod, $shard ];
549 $aug = '+'; # incr_post_augment
550 } elsif ($self->{-wq_worker_nr} == 0) {
551 $aug = '.'; # do_post_augment
554 local $0 = 'do_augment';
555 eval { do_augment($self, $lei) };
556 $lei->fail($@) if $@;
557 pkt_do($lei->{pkt_op_p}, $aug) == 1 or
558 die "do_post_augment trigger: $!";
560 if (my $zpipe = delete $lei->{zpipe}) {
561 $lei->{1} = $zpipe->[1];
564 $self->{wcb} = $self->write_cb($lei);
567 sub ipc_atfork_child {
569 my $lei = $self->{lei};
570 $lei->lei_atfork_child;
571 $lei->{auth}->do_auth_atfork($self) if $lei->{auth};
572 $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb();
573 $self->SUPER::ipc_atfork_child;
577 $_[0]->{base_type} =~ /\A(?:maildir|mh|imap|jmap)\z/ ? 1 : 0;
582 if ($self->{base_type} eq 'maildir') {
584 utime($t, $t, "$self->{dst}/cur");
588 sub write_mail { # via ->wq_io_do
589 my ($self, $git_dir, $smsg) = @_;
590 my $git = $self->{"$$\0$git_dir"} //= PublicInbox::Git->new($git_dir);
591 git_async_cat($git, $smsg->{blob}, \&git_to_mail,
592 [$self->{wcb}, $smsg]);
595 sub wq_atexit_child {
598 for my $git (delete @$self{grep(/\A$$\0/, keys %$self)}) {
599 $git->async_wait_all;
601 $SIG{__WARN__} = 'DEFAULT';
604 # called in top-level lei-daemon when LeiAuth is done
605 sub net_merge_complete {
607 $self->wq_broadcast('do_post_auth');
611 no warnings 'once'; # the following works even when LeiAuth is lazy-loaded
612 *net_merge_all = \&PublicInbox::LeiAuth::net_merge_all;