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::ProcessPipe;
11 use PublicInbox::Spawn qw(spawn);
12 use PublicInbox::LeiDedupe;
13 use PublicInbox::PktOp qw(pkt_do);
14 use Symbol qw(gensym);
15 use IO::Handle; # ->autoflush
16 use Fcntl qw(SEEK_SET SEEK_END O_CREAT O_EXCL O_WRONLY);
18 my %kw2char = ( # Maildir characters
21 forwarded => 'P', # passed
27 flagged => [ 'X-Status' => 'F' ],
28 answered => [ 'X-Status' => 'A' ],
29 seen => [ 'Status' => 'R' ],
30 draft => [ 'X-Status' => 'T' ],
33 sub _mbox_hdr_buf ($$$) {
34 my ($eml, $type, $smsg) = @_;
35 $eml->header_set($_) for (qw(Lines Bytes Content-Length));
37 my %hdr = (Status => []); # set Status, X-Status
38 for my $k (@{$smsg->{kw} // []}) {
39 if (my $ent = $kw2status{$k}) {
40 push @{$hdr{$ent->[0]}}, $ent->[1];
42 warn "TODO: keyword `$k' not supported for mbox\n";
45 # Messages are always 'O' (non-\Recent in IMAP), it saves
46 # MUAs the trouble of rewriting the mbox if no other
47 # changes are made. We put 'O' at the end (e.g. "Status: RO")
48 # to match mutt(1) output.
49 $eml->header_set('Status', join('', sort(@{$hdr{Status}})). 'O');
50 if (my $chars = delete $hdr{'X-Status'}) {
51 $eml->header_set('X-Status', join('', sort(@$chars)));
53 my $buf = delete $eml->{hdr};
55 # fixup old bug from import (pre-a0c07cba0e5d8b6a)
56 $$buf =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
57 my $ident = $smsg->{blob} // 'lei';
58 if (defined(my $pct = $smsg->{pct})) { $ident .= "=$pct" }
60 substr($$buf, 0, 0, # prepend From line
61 "From $ident\@$type Thu Jan 1 00:00:00 1970$eml->{crlf}");
65 sub atomic_append { # for on-disk destinations (O_APPEND, or O_EXCL)
67 if (defined(my $w = syswrite($lei->{1} // return, $$buf))) {
68 return if $w == length($$buf);
69 $buf = "short atomic write: $w != ".length($$buf);
71 return $lei->note_sigpipe(1);
73 $buf = "atomic write: $!";
78 sub eml2mboxrd ($;$) {
79 my ($eml, $smsg) = @_;
80 my $buf = _mbox_hdr_buf($eml, 'mboxrd', $smsg);
81 if (my $bdy = delete $eml->{bdy}) {
82 $$bdy =~ s/^(>*From )/>$1/gm;
83 $$buf .= $eml->{crlf};
84 substr($$bdy, 0, 0, $$buf); # prepend header
87 $$buf .= $eml->{crlf};
92 my ($eml, $smsg) = @_;
93 my $buf = _mbox_hdr_buf($eml, 'mboxo', $smsg);
94 if (my $bdy = delete $eml->{bdy}) {
95 $$bdy =~ s/^From />From /gm;
96 $$buf .= $eml->{crlf};
97 substr($$bdy, 0, 0, $$buf); # prepend header
100 $$buf .= $eml->{crlf};
104 sub _mboxcl_common ($$$) {
105 my ($buf, $bdy, $crlf) = @_;
106 # add Lines: so mutt won't have to add it on MUA close
107 my $lines = $$bdy =~ tr!\n!\n!;
108 $$buf .= 'Content-Length: '.length($$bdy).$crlf.
109 'Lines: '.$lines.$crlf.$crlf;
110 substr($$bdy, 0, 0, $$buf); # prepend header
114 # mboxcl still escapes "From " lines
116 my ($eml, $smsg) = @_;
117 my $buf = _mbox_hdr_buf($eml, 'mboxcl', $smsg);
118 my $crlf = $eml->{crlf};
119 if (my $bdy = delete $eml->{bdy}) {
120 $$bdy =~ s/^From />From /gm;
121 _mboxcl_common($buf, $bdy, $crlf);
127 # mboxcl2 has no "From " escaping
129 my ($eml, $smsg) = @_;
130 my $buf = _mbox_hdr_buf($eml, 'mboxcl2', $smsg);
131 my $crlf = $eml->{crlf};
132 if (my $bdy = delete $eml->{bdy}) {
133 _mboxcl_common($buf, $bdy, $crlf);
139 sub git_to_mail { # git->cat_async callback
140 my ($bref, $oid, $type, $size, $arg) = @_;
141 return warn("W: $oid is $type (!= blob)\n") if $type ne 'blob';
142 return warn("E: $oid is empty\n") unless $size;
143 my ($write_cb, $smsg) = @$arg;
144 die "BUG: expected=$smsg->{blob} got=$oid" if $smsg->{blob} ne $oid;
145 $write_cb->($bref, $smsg);
148 sub reap_compress { # dwaitpid callback
149 my ($lei, $pid) = @_;
150 my $cmd = delete $lei->{"pid.$pid"};
152 $lei->fail("@$cmd failed", $? >> 8);
155 sub _post_augment_mbox { # open a compressor process from top-level process
156 my ($self, $lei) = @_;
157 my $zsfx = $self->{zsfx} or return;
158 my $cmd = PublicInbox::MboxReader::zsfx2cmd($zsfx, undef, $lei);
159 my ($r, $w) = @{delete $lei->{zpipe}};
160 my $rdr = { 0 => $r, 1 => $lei->{1}, 2 => $lei->{2} };
161 my $pid = spawn($cmd, undef, $rdr);
163 my $dup = bless { "pid.$pid" => $cmd }, ref($lei);
164 $dup->{$_} = $lei->{$_} for qw(2 sock);
165 tie *$pp, 'PublicInbox::ProcessPipe', $pid, $w, \&reap_compress, $dup;
169 # --augment existing output destination, with deduplication
170 sub _augment { # MboxReader eml_cb
171 my ($eml, $lei) = @_;
172 # ignore return value, just populate the skv
173 $lei->{dedupe}->is_dup($eml);
176 sub _mbox_augment_kw_maybe {
177 my ($eml, $lei, $lse, $augment) = @_;
178 my $kw = PublicInbox::MboxReader::mbox_keywords($eml);
179 update_kw_maybe($lei, $lse, $eml, $kw);
180 _augment($eml, $lei) if $augment;
183 sub _mbox_write_cb ($$) {
184 my ($self, $lei) = @_;
185 my $ovv = $lei->{ovv};
186 my $m = 'eml2'.$ovv->{fmt};
187 my $eml2mbox = $self->can($m) or die "$self->$m missing";
188 $lei->{1} // die "no stdout ($m, $ovv->{dst})"; # redirected earlier
189 $lei->{1}->autoflush(1);
190 my $atomic_append = !defined($ovv->{lock_path});
191 my $dedupe = $lei->{dedupe};
192 $dedupe->prepare_dedupe;
193 my $lse = $lei->{lse}; # may be undef
194 sub { # for git_to_mail
195 my ($buf, $smsg, $eml) = @_;
196 $eml //= PublicInbox::Eml->new($buf);
197 return if $dedupe->is_dup($eml, $smsg->{blob});
198 $lse->xsmsg_vmd($smsg) if $lse;
199 $buf = $eml2mbox->($eml, $smsg);
200 return atomic_append($lei, $buf) if $atomic_append;
201 my $lk = $ovv->lock_for_scope;
206 sub update_kw_maybe ($$$$) {
207 my ($lei, $lse, $eml, $kw) = @_;
209 my $c = $lse->kw_changed($eml, $kw, my $docids = []);
210 my $vmd = { kw => $kw };
211 if (scalar @$docids) { # already in lei/store
212 $lei->{sto}->ipc_do('set_eml_vmd', undef, $vmd, $docids) if $c;
213 } elsif (my $xoids = $lei->{ale}->xoids_for($eml)) {
214 # it's in an external, only set kw, here
215 $lei->{sto}->ipc_do('set_xvmd', $xoids, $eml, $vmd);
216 } else { # never-before-seen, import the whole thing
217 # XXX this is critical in protecting against accidental
218 # data loss without --augment
219 $lei->{sto}->ipc_do('set_eml', $eml, $vmd);
223 sub _md_update { # maildir_each_eml cb
224 my ($f, $kw, $eml, $lei, $lse, $unlink) = @_;
225 update_kw_maybe($lei, $lse, $eml, $kw);
226 $unlink ? unlink($f) : _augment($eml, $lei);
229 # maildir_each_file callback, \&CORE::unlink doesn't work with it
230 sub _unlink { unlink($_[0]) }
234 sprintf('%x,%x,%x,%x', rand(0xffffffff), time, $$, ++$seq);
238 my ($dst, $buf, $smsg) = @_;
239 my $kw = $smsg->{kw} // [];
240 my $sfx = join('', sort(map { $kw2char{$_} // () } @$kw));
241 my $rand = ''; # chosen by die roll :P
242 my ($tmp, $fh, $final, $ok);
243 my $common = $smsg->{blob} // _rand;
244 if (defined(my $pct = $smsg->{pct})) { $common .= "=$pct" }
246 $tmp = $dst.'tmp/'.$rand.$common;
247 } while (!($ok = sysopen($fh, $tmp, O_CREAT|O_EXCL|O_WRONLY)) &&
248 $!{EEXIST} && ($rand = _rand.','));
249 if ($ok && print $fh $$buf and close($fh)) {
250 # ignore new/ and write only to cur/, otherwise MUAs
251 # with R/W access to the Maildir will end up doing
252 # a mass rename which can take a while with thousands
257 $final = $dst.$rand.$common.':2,'.$sfx;
258 } while (!($ok = link($tmp, $final)) && $!{EEXIST} &&
259 ($rand = _rand.','));
260 die "link($tmp, $final): $!" unless $ok;
261 unlink($tmp) or warn "W: failed to unlink $tmp: $!\n";
263 my $err = "Error writing $smsg->{blob} to $dst: $!\n";
264 $_[0] = undef; # clobber dst
270 sub _maildir_write_cb ($$) {
271 my ($self, $lei) = @_;
272 my $dedupe = $lei->{dedupe};
273 $dedupe->prepare_dedupe if $dedupe;
274 my $dst = $lei->{ovv}->{dst};
275 my $lse = $lei->{lse}; # may be undef
276 sub { # for git_to_mail
277 my ($buf, $smsg, $eml) = @_;
278 $dst // return $lei->fail; # dst may be undef-ed in last run
279 $buf //= \($eml->as_string);
280 $lse->xsmsg_vmd($smsg) if $lse;
281 return _buf2maildir($dst, $buf, $smsg) if !$dedupe;
282 $eml //= PublicInbox::Eml->new($$buf); # copy buf
283 return if $dedupe->is_dup($eml, $smsg->{blob});
285 _buf2maildir($dst, $buf, $smsg);
289 sub _imap_write_cb ($$) {
290 my ($self, $lei) = @_;
291 my $dedupe = $lei->{dedupe};
292 $dedupe->prepare_dedupe if $dedupe;
293 my $imap_append = $lei->{net}->can('imap_append');
294 my $mic = $lei->{net}->mic_get($self->{uri});
295 my $folder = $self->{uri}->mailbox;
296 my $lse = $lei->{lse}; # may be undef
297 sub { # for git_to_mail
298 my ($bref, $smsg, $eml) = @_;
299 $mic // return $lei->fail; # mic may be undef-ed in last run
301 $eml //= PublicInbox::Eml->new($$bref); # copy bref
302 return if $dedupe->is_dup($eml, $smsg->{blob});
304 $lse->xsmsg_vmd($smsg) if $lse;
305 eval { $imap_append->($mic, $folder, $bref, $smsg, $eml) };
313 sub write_cb { # returns a callback for git_to_mail
314 my ($self, $lei) = @_;
315 # _mbox_write_cb, _maildir_write_cb or _imap_write_cb
316 my $m = "_$self->{base_type}_write_cb";
321 my ($cls, $lei) = @_;
322 my $fmt = $lei->{ovv}->{fmt};
323 my $dst = $lei->{ovv}->{dst};
324 my $self = bless {}, $cls;
325 if ($fmt eq 'maildir') {
326 require PublicInbox::MdirReader;
327 $self->{base_type} = 'maildir';
328 -e $dst && !-d _ and die
329 "$dst exists and is not a directory\n";
330 $lei->{ovv}->{dst} = $dst .= '/' if substr($dst, -1) ne '/';
331 } elsif (substr($fmt, 0, 4) eq 'mbox') {
332 require PublicInbox::MboxReader;
333 (-d $dst || (-e _ && !-w _)) and die
334 "$dst exists and is not a writable file\n";
335 $self->can("eml2$fmt") or die "bad mbox format: $fmt\n";
336 $self->{base_type} = 'mbox';
337 } elsif ($fmt =~ /\Aimaps?\z/) { # TODO .onion support
338 require PublicInbox::NetWriter;
339 my $net = PublicInbox::NetWriter->new;
341 $net->{quiet} = $lei->{opt}->{quiet};
342 my $err = $net->errors($dst);
343 return $lei->fail($err) if $err;
344 require PublicInbox::URIimap; # TODO: URI cast early
345 $self->{uri} = PublicInbox::URIimap->new($dst);
346 $self->{uri}->mailbox or die "No mailbox: $dst";
348 $self->{base_type} = 'imap';
350 die "bad mail --format=$fmt\n";
353 $lei->{dedupe} = PublicInbox::LeiDedupe->new($lei);
357 sub _pre_augment_maildir {
358 my ($self, $lei) = @_;
359 my $dst = $lei->{ovv}->{dst};
360 for my $x (qw(tmp new cur)) {
364 File::Path::mkpath($d);
365 -d $d or die "$d is not a directory";
369 sub _do_augment_maildir {
370 my ($self, $lei) = @_;
371 my $dst = $lei->{ovv}->{dst};
372 my $lse = $lei->{opt}->{'import-before'} ? $lei->{lse} : undef;
373 my $mdr = PublicInbox::MdirReader->new;
374 if ($lei->{opt}->{augment}) {
375 my $dedupe = $lei->{dedupe};
376 if ($dedupe && $dedupe->prepare_dedupe) {
377 $mdr->{shard_info} = $self->{shard_info};
378 $mdr->maildir_each_eml($dst, \&_md_update, $lei, $lse);
379 $dedupe->pause_dedupe;
382 $mdr->{shard_info} = $self->{shard_info};
383 $mdr->maildir_each_eml($dst, \&_md_update, $lei, $lse, 1);
384 } else {# clobber existing Maildir
385 $mdr->maildir_each_file($dst, \&_unlink);
389 sub _imap_augment_or_delete { # PublicInbox::NetReader::imap_each cb
390 my ($url, $uid, $kw, $eml, $lei, $lse, $delete_mic) = @_;
391 update_kw_maybe($lei, $lse, $eml, $kw);
393 $lei->{net}->imap_delete_1($url, $uid, $delete_mic);
395 _augment($eml, $lei);
399 sub _do_augment_imap {
400 my ($self, $lei) = @_;
401 my $net = $lei->{net};
402 my $lse = $lei->{opt}->{'import-before'} ? $lei->{lse} : undef;
403 if ($lei->{opt}->{augment}) {
404 my $dedupe = $lei->{dedupe};
405 if ($dedupe && $dedupe->prepare_dedupe) {
406 $net->imap_each($self->{uri}, \&_imap_augment_or_delete,
408 $dedupe->pause_dedupe;
412 $net->imap_each($self->{uri}, \&_imap_augment_or_delete,
413 $lei, $lse, \$delete_mic);
414 $delete_mic->expunge if $delete_mic;
415 } elsif (!$self->{-wq_worker_nr}) { # undef or 0
416 # clobber existing IMAP folder
417 $net->imap_delete_all($self->{uri});
421 sub _pre_augment_mbox {
422 my ($self, $lei) = @_;
423 my $dst = $lei->{ovv}->{dst};
425 my $devfd = $lei->path_to_fd($dst) // die "bad $dst";
427 $out = $lei->{$devfd};
428 } else { # normal-looking path
430 open $out, '>', $dst or die "open($dst): $!";
431 } elsif (-f _ || !-e _) {
432 require PublicInbox::MboxLock;
433 my $m = $lei->{opt}->{'lock'} //
434 PublicInbox::MboxLock->defaults;
435 $self->{mbl} = PublicInbox::MboxLock->acq($dst, 1, $m);
436 $out = $self->{mbl}->{fh};
438 die "$dst is not a file or FIFO\n";
440 $lei->{old_1} = $lei->{1}; # keep for spawning MUA
442 # Perl does SEEK_END even with O_APPEND :<
443 $self->{seekable} = seek($out, 0, SEEK_SET);
444 if (!$self->{seekable} && !$!{ESPIPE} && !defined($devfd)) {
445 die "seek($dst): $!\n";
447 if (!$self->{seekable}) {
448 my $imp_before = $lei->{opt}->{'import-before'};
449 die "--import-before specified but $dst is not seekable\n"
450 if $imp_before && !ref($imp_before);
451 die "--augment specified but $dst is not seekable\n" if
452 $lei->{opt}->{augment};
454 if ($self->{zsfx} = PublicInbox::MboxReader::zsfx($dst)) {
455 pipe(my ($r, $w)) or die "pipe: $!";
456 $lei->{zpipe} = [ $r, $w ];
457 $lei->{ovv}->{lock_path} and
458 die 'BUG: unexpected {ovv}->{lock_path}';
459 $lei->{ovv}->ovv_out_lk_init;
460 } elsif (!$self->{seekable} && !$lei->{ovv}->{lock_path}) {
461 $lei->{ovv}->ovv_out_lk_init;
467 sub _do_augment_mbox {
468 my ($self, $lei) = @_;
469 return unless $self->{seekable};
470 my $opt = $lei->{opt};
472 my ($fmt, $dst) = @{$lei->{ovv}}{qw(fmt dst)};
473 return unless -s $out;
474 unless ($opt->{augment} || $opt->{'import-before'}) {
475 truncate($out, 0) or die "truncate($dst): $!";
479 if (my $zsfx = $self->{zsfx}) {
480 $rd = PublicInbox::MboxReader::zsfxcat($out, $zsfx, $lei);
482 open($rd, '+>>&', $out) or die "dup: $!";
485 if ($opt->{augment}) {
486 $dedupe = $lei->{dedupe};
487 $dedupe->prepare_dedupe if $dedupe;
489 if ($opt->{'import-before'}) { # the default
490 my $lse = $lei->{lse};
491 PublicInbox::MboxReader->$fmt($rd, \&_mbox_augment_kw_maybe,
492 $lei, $lse, $opt->{augment});
493 if (!$opt->{augment} and !truncate($out, 0)) {
494 die "truncate($dst): $!";
496 } else { # --augment --no-import-before
497 PublicInbox::MboxReader->$fmt($rd, \&_augment, $lei);
499 # maybe some systems don't honor O_APPEND, Perl does this:
500 seek($out, 0, SEEK_END) or die "seek $dst: $!";
501 $dedupe->pause_dedupe if $dedupe;
504 sub pre_augment { # fast (1 disk seek), runs in same process as post_augment
505 my ($self, $lei) = @_;
506 # _pre_augment_maildir, _pre_augment_mbox
507 my $m = $self->can("_pre_augment_$self->{base_type}") or return;
511 sub do_augment { # slow, runs in wq worker
512 my ($self, $lei) = @_;
513 # _do_augment_maildir, _do_augment_mbox, or _do_augment_imap
514 my $m = "_do_augment_$self->{base_type}";
518 # fast (spawn compressor or mkdir), runs in same process as pre_augment
520 my ($self, $lei, @args) = @_;
521 my $wait = $lei->{opt}->{'import-before'} ?
522 $lei->{sto}->ipc_do('checkpoint', 1) : 0;
524 my $m = $self->can("_post_augment_$self->{base_type}") or return;
525 $m->($self, $lei, @args);
528 # called by every single l2m worker process
531 my $lei = $self->{lei};
532 # lei_xsearch can start as soon as all l2m workers get here
533 pkt_do($lei->{pkt_op_p}, 'incr_start_query') or
534 die "incr_start_query: $!";
536 if (lock_free($self)) { # all workers do_augment
537 my $mod = $self->{-wq_nr_workers};
538 my $shard = $self->{-wq_worker_nr};
539 if (my $net = $lei->{net}) {
540 $net->{shard_info} = [ $mod, $shard ];
542 $self->{shard_info} = [ $mod, $shard ];
544 $aug = '+'; # incr_post_augment
545 } elsif ($self->{-wq_worker_nr} == 0) { # 1st worker do_augment
546 $aug = '.'; # do_post_augment
549 local $0 = 'do_augment';
550 eval { do_augment($self, $lei) };
551 $lei->fail($@) if $@;
552 pkt_do($lei->{pkt_op_p}, $aug) == 1 or
553 die "do_post_augment trigger: $!";
555 # done augmenting, connect the compressor pipe for each worker
556 if (my $zpipe = delete $lei->{zpipe}) {
557 $lei->{1} = $zpipe->[1];
560 $self->{wcb} = $self->write_cb($lei);
563 sub ipc_atfork_child {
565 my $lei = $self->{lei};
566 $lei->_lei_atfork_child;
567 $lei->{auth}->do_auth_atfork($self) if $lei->{auth};
568 $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb();
569 $self->SUPER::ipc_atfork_child;
573 $_[0]->{base_type} =~ /\A(?:maildir|imap|jmap)\z/ ? 1 : 0;
576 # wakes up the MUA when complete so it can refresh messages list
579 if ($self->{base_type} eq 'maildir') {
581 utime($t, $t, $self->{dst} . 'cur');
585 sub write_mail { # via ->wq_io_do
586 my ($self, $smsg, $eml) = @_;
587 return $self->{wcb}->(undef, $smsg, $eml) if $eml;
588 $self->{lei}->{ale}->git->cat_async($smsg->{blob}, \&git_to_mail,
589 [$self->{wcb}, $smsg]);
592 sub wq_atexit_child {
595 $self->{lei}->{ale}->git->async_wait_all;
598 # called in top-level lei-daemon when LeiAuth is done
599 sub net_merge_complete {
601 $self->wq_broadcast('do_post_auth');
605 no warnings 'once'; # the following works even when LeiAuth is lazy-loaded
606 *net_merge_all = \&PublicInbox::LeiAuth::net_merge_all;