]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiToMail.pm
lei: use RENAME_NOREPLACE on Linux 3.15+
[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::ProcessPipe;
11 use PublicInbox::Spawn qw(spawn);
12 use Symbol qw(gensym);
13 use IO::Handle; # ->autoflush
14 use Fcntl qw(SEEK_SET SEEK_END O_CREAT O_EXCL O_WRONLY);
15 use PublicInbox::Syscall qw(rename_noreplace);
16
17 my %kw2char = ( # Maildir characters
18         draft => 'D',
19         flagged => 'F',
20         forwarded => 'P', # passed
21         answered => 'R',
22         seen => 'S',
23 );
24
25 my %kw2status = (
26         flagged => [ 'X-Status' => 'F' ],
27         answered => [ 'X-Status' => 'A' ],
28         seen => [ 'Status' => 'R' ],
29         draft => [ 'X-Status' => 'T' ],
30 );
31
32 sub _mbox_hdr_buf ($$$) {
33         my ($eml, $type, $smsg) = @_;
34         $eml->header_set($_) for (qw(Lines Bytes Content-Length));
35
36         my %hdr = (Status => []); # set Status, X-Status
37         for my $k (@{$smsg->{kw} // []}) {
38                 if (my $ent = $kw2status{$k}) {
39                         push @{$hdr{$ent->[0]}}, $ent->[1];
40                 } else { # X-Label?
41                         warn "# keyword `$k' not supported for mbox\n";
42                 }
43         }
44         # When writing to empty mboxes, messages are always 'O'
45         # (not-\Recent in IMAP), it saves MUAs the trouble of
46         # rewriting the mbox if no other changes are made.
47         # We put 'O' at the end (e.g. "Status: RO") to match mutt(1) output.
48         # We only set smsg->{-recent} if augmenting existing stores.
49         my $status = join('', sort(@{$hdr{Status}}));
50         $status .= 'O' unless $smsg->{-recent};
51         $eml->header_set('Status', $status) if $status;
52         if (my $chars = delete $hdr{'X-Status'}) {
53                 $eml->header_set('X-Status', join('', sort(@$chars)));
54         }
55         my $buf = delete $eml->{hdr};
56
57         # fixup old bug from import (pre-a0c07cba0e5d8b6a)
58         $$buf =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
59         my $ident = $smsg->{blob} // 'lei';
60         if (defined(my $pct = $smsg->{pct})) { $ident .= "=$pct" }
61
62         substr($$buf, 0, 0, # prepend From line
63                 "From $ident\@$type Thu Jan  1 00:00:00 1970$eml->{crlf}");
64         $buf;
65 }
66
67 sub atomic_append { # for on-disk destinations (O_APPEND, or O_EXCL)
68         my ($lei, $buf) = @_;
69         if (defined(my $w = syswrite($lei->{1} // return, $$buf))) {
70                 return if $w == length($$buf);
71                 $buf = "short atomic write: $w != ".length($$buf);
72         } elsif ($!{EPIPE}) {
73                 return $lei->note_sigpipe(1);
74         } else {
75                 $buf = "atomic write: $!";
76         }
77         $lei->fail($buf);
78 }
79
80 sub eml2mboxrd ($;$) {
81         my ($eml, $smsg) = @_;
82         my $buf = _mbox_hdr_buf($eml, 'mboxrd', $smsg);
83         if (my $bdy = delete $eml->{bdy}) {
84                 $$bdy =~ s/^(>*From )/>$1/gm;
85                 $$buf .= $eml->{crlf};
86                 substr($$bdy, 0, 0, $$buf); # prepend header
87                 $buf = $bdy;
88         }
89         $$buf .= $eml->{crlf};
90         $buf;
91 }
92
93 sub eml2mboxo {
94         my ($eml, $smsg) = @_;
95         my $buf = _mbox_hdr_buf($eml, 'mboxo', $smsg);
96         if (my $bdy = delete $eml->{bdy}) {
97                 $$bdy =~ s/^From />From /gm;
98                 $$buf .= $eml->{crlf};
99                 substr($$bdy, 0, 0, $$buf); # prepend header
100                 $buf = $bdy;
101         }
102         $$buf .= $eml->{crlf};
103         $buf;
104 }
105
106 sub _mboxcl_common ($$$) {
107         my ($buf, $bdy, $crlf) = @_;
108         # add Lines: so mutt won't have to add it on MUA close
109         my $lines = $$bdy =~ tr!\n!\n!;
110         $$buf .= 'Content-Length: '.length($$bdy).$crlf.
111                 'Lines: '.$lines.$crlf.$crlf;
112         substr($$bdy, 0, 0, $$buf); # prepend header
113         $$bdy .= $crlf;
114         $bdy;
115 }
116
117 # mboxcl still escapes "From " lines
118 sub eml2mboxcl {
119         my ($eml, $smsg) = @_;
120         my $buf = _mbox_hdr_buf($eml, 'mboxcl', $smsg);
121         my $bdy = delete($eml->{bdy}) // \(my $empty = '');
122         $$bdy =~ s/^From />From /gm;
123         _mboxcl_common($buf, $bdy, $eml->{crlf});
124 }
125
126 # mboxcl2 has no "From " escaping
127 sub eml2mboxcl2 {
128         my ($eml, $smsg) = @_;
129         my $buf = _mbox_hdr_buf($eml, 'mboxcl2', $smsg);
130         my $bdy = delete($eml->{bdy}) // \(my $empty = '');
131         _mboxcl_common($buf, $bdy, $eml->{crlf});
132 }
133
134 sub git_to_mail { # git->cat_async callback
135         my ($bref, $oid, $type, $size, $arg) = @_;
136         $type // return; # called by git->async_abort
137         my ($write_cb, $smsg) = @$arg;
138         if ($type eq 'missing' && $smsg->{-lms_ro}) {
139                 if ($bref = $smsg->{-lms_ro}->local_blob($oid, 1)) {
140                         $type = 'blob';
141                         $size = length($$bref);
142                 }
143         }
144         return warn("W: $oid is $type (!= blob)\n") if $type ne 'blob';
145         return warn("E: $oid is empty\n") unless $size;
146         die "BUG: expected=$smsg->{blob} got=$oid" if $smsg->{blob} ne $oid;
147         $write_cb->($bref, $smsg);
148 }
149
150 sub reap_compress { # dwaitpid callback
151         my ($lei, $pid) = @_;
152         my $cmd = delete $lei->{"pid.$pid"};
153         return if $? == 0;
154         $lei->fail("@$cmd failed", $? >> 8);
155 }
156
157 sub _post_augment_mbox { # open a compressor process from top-level process
158         my ($self, $lei) = @_;
159         my $zsfx = $self->{zsfx} or return;
160         my $cmd = PublicInbox::MboxReader::zsfx2cmd($zsfx, undef, $lei);
161         my ($r, $w) = @{delete $lei->{zpipe}};
162         my $rdr = { 0 => $r, 1 => $lei->{1}, 2 => $lei->{2}, pgid => 0 };
163         my $pid = spawn($cmd, undef, $rdr);
164         my $pp = gensym;
165         my $dup = bless { "pid.$pid" => $cmd }, ref($lei);
166         $dup->{$_} = $lei->{$_} for qw(2 sock);
167         tie *$pp, 'PublicInbox::ProcessPipe', $pid, $w, \&reap_compress, $dup;
168         $lei->{1} = $pp;
169 }
170
171 # --augment existing output destination, with deduplication
172 sub _augment { # MboxReader eml_cb
173         my ($eml, $lei) = @_;
174         # ignore return value, just populate the skv
175         $lei->{dedupe}->is_dup($eml);
176 }
177
178 sub _mbox_augment_kw_maybe {
179         my ($eml, $lei, $lse, $augment) = @_;
180         my $kw = PublicInbox::MboxReader::mbox_keywords($eml);
181         update_kw_maybe($lei, $lse, $eml, $kw);
182         _augment($eml, $lei) if $augment;
183 }
184
185 sub _mbox_write_cb ($$) {
186         my ($self, $lei) = @_;
187         my $ovv = $lei->{ovv};
188         my $m = 'eml2'.$ovv->{fmt};
189         my $eml2mbox = $self->can($m) or die "$self->$m missing";
190         $lei->{1} // die "no stdout ($m, $ovv->{dst})"; # redirected earlier
191         $lei->{1}->autoflush(1);
192         my $atomic_append = !defined($ovv->{lock_path});
193         my $dedupe = $lei->{dedupe};
194         $dedupe->prepare_dedupe;
195         my $lse = $lei->{lse}; # may be undef
196         my $set_recent = $dedupe->has_entries;
197         sub { # for git_to_mail
198                 my ($buf, $smsg, $eml) = @_;
199                 $eml //= PublicInbox::Eml->new($buf);
200                 return if $dedupe->is_dup($eml, $smsg);
201                 $lse->xsmsg_vmd($smsg) if $lse;
202                 $smsg->{-recent} = 1 if $set_recent;
203                 $buf = $eml2mbox->($eml, $smsg);
204                 if ($atomic_append) {
205                         atomic_append($lei, $buf);
206                 } else {
207                         my $lk = $ovv->lock_for_scope;
208                         $lei->out($$buf);
209                 }
210                 ++$lei->{-nr_write};
211         }
212 }
213
214 sub update_kw_maybe ($$$$) {
215         my ($lei, $lse, $eml, $kw) = @_;
216         return unless $lse;
217         my $c = $lse->kw_changed($eml, $kw, my $docids = []);
218         my $vmd = { kw => $kw };
219         if (scalar @$docids) { # already in lei/store
220                 $lei->{sto}->wq_do('set_eml_vmd', undef, $vmd, $docids) if $c;
221         } elsif (my $xoids = $lei->{ale}->xoids_for($eml)) {
222                 # it's in an external, only set kw, here
223                 $lei->{sto}->wq_do('set_xvmd', $xoids, $eml, $vmd);
224         } else { # never-before-seen, import the whole thing
225                 # XXX this is critical in protecting against accidental
226                 # data loss without --augment
227                 $lei->{sto}->wq_do('set_eml', $eml, $vmd);
228         }
229 }
230
231 sub _md_update { # maildir_each_eml cb
232         my ($f, $kw, $eml, $lei, $lse, $unlink) = @_;
233         update_kw_maybe($lei, $lse, $eml, $kw);
234         $unlink ? unlink($f) : _augment($eml, $lei);
235 }
236
237 # maildir_each_file callback, \&CORE::unlink doesn't work with it
238 sub _unlink { unlink($_[0]) }
239
240 sub _rand () {
241         state $seq = 0;
242         sprintf('%x,%x,%x,%x', rand(0xffffffff), time, $$, ++$seq);
243 }
244
245 sub kw2suffix ($;@) {
246         my $kw = shift;
247         join('', sort(map { $kw2char{$_} // () } @$kw, @_));
248 }
249
250 sub _buf2maildir ($$$$) {
251         my ($dst, $buf, $smsg, $dir) = @_;
252         my $kw = $smsg->{kw} // [];
253         my $rand = ''; # chosen by die roll :P
254         my ($tmp, $fh, $base, $ok);
255         my $common = $smsg->{blob} // _rand;
256         if (defined(my $pct = $smsg->{pct})) { $common .= "=$pct" }
257         do {
258                 $tmp = $dst.'tmp/'.$rand.$common;
259         } while (!($ok = sysopen($fh, $tmp, O_CREAT|O_EXCL|O_WRONLY)) &&
260                 $!{EEXIST} && ($rand = _rand.','));
261         if ($ok && print $fh $$buf and close($fh)) {
262                 $dst .= $dir; # 'new/' or 'cur/'
263                 $rand = '';
264                 do {
265                         $base = $rand.$common.':2,'.kw2suffix($kw);
266                 } while (!($ok = rename_noreplace($tmp, $dst.$base)) &&
267                         $!{EEXIST} && ($rand = _rand.','));
268                 \$base;
269         } else {
270                 my $err = "Error writing $smsg->{blob} to $dst: $!\n";
271                 $_[0] = undef; # clobber dst
272                 unlink($tmp);
273                 die $err;
274         }
275 }
276
277 sub _maildir_write_cb ($$) {
278         my ($self, $lei) = @_;
279         my $dedupe = $lei->{dedupe};
280         $dedupe->prepare_dedupe if $dedupe;
281         my $dst = $lei->{ovv}->{dst};
282         my $lse = $lei->{lse}; # may be undef
283         my $sto = $lei->{opt}->{'mail-sync'} ? $lei->{sto} : undef;
284         my $out = $sto ? 'maildir:'.$lei->abs_path($dst) : undef;
285
286         # Favor cur/ and only write to new/ when augmenting.  This
287         # saves MUAs from having to do a mass rename when the initial
288         # search result set is huge.
289         my $dir = $dedupe && $dedupe->has_entries ? 'new/' : 'cur/';
290         sub { # for git_to_mail
291                 my ($bref, $smsg, $eml) = @_;
292                 $dst // return $lei->fail; # dst may be undef-ed in last run
293                 return if $dedupe && $dedupe->is_dup($eml //
294                                                 PublicInbox::Eml->new($$bref),
295                                                 $smsg);
296                 $lse->xsmsg_vmd($smsg) if $lse;
297                 my $n = _buf2maildir($dst, $bref // \($eml->as_string),
298                                         $smsg, $dir);
299                 $sto->wq_do('set_sync_info', $smsg->{blob}, $out, $n) if $sto;
300                 ++$lei->{-nr_write};
301         }
302 }
303
304 sub _imap_write_cb ($$) {
305         my ($self, $lei) = @_;
306         my $dedupe = $lei->{dedupe};
307         $dedupe->prepare_dedupe if $dedupe;
308         my $append = $lei->{net}->can('imap_append');
309         my $uri = $self->{uri};
310         my $mic = $lei->{net}->mic_get($uri);
311         my $folder = $uri->mailbox;
312         $uri->uidvalidity($mic->uidvalidity($folder));
313         my $lse = $lei->{lse}; # may be undef
314         my $sto = $lei->{opt}->{'mail-sync'} ? $lei->{sto} : undef;
315         sub { # for git_to_mail
316                 my ($bref, $smsg, $eml) = @_;
317                 $mic // return $lei->fail; # mic may be undef-ed in last run
318                 return if $dedupe && $dedupe->is_dup($eml //
319                                                 PublicInbox::Eml->new($$bref),
320                                                 $smsg);
321                 $lse->xsmsg_vmd($smsg) if $lse;
322                 my $uid = eval { $append->($mic, $folder, $bref, $smsg, $eml) };
323                 if (my $err = $@) {
324                         undef $mic;
325                         die $err;
326                 }
327                 # imap_append returns UID if IMAP server has UIDPLUS extension
328                 ($sto && $uid =~ /\A[0-9]+\z/) and
329                         $sto->wq_do('set_sync_info',
330                                         $smsg->{blob}, $$uri, $uid + 0);
331                 ++$lei->{-nr_write};
332         }
333 }
334
335 sub _text_write_cb ($$) {
336         my ($self, $lei) = @_;
337         my $dedupe = $lei->{dedupe};
338         $dedupe->prepare_dedupe if $dedupe;
339         my $lvt = $lei->{lvt};
340         my $ovv = $lei->{ovv};
341         $lei->{1} // die "no stdout ($ovv->{dst})"; # redirected earlier
342         $lei->{1}->autoflush(1);
343         binmode $lei->{1}, ':utf8';
344         my $lse = $lei->{lse}; # may be undef
345         sub { # for git_to_mail
346                 my ($bref, $smsg, $eml) = @_;
347                 $lse->xsmsg_vmd($smsg) if $lse;
348                 $eml //= PublicInbox::Eml->new($bref);
349                 return if $dedupe && $dedupe->is_dup($eml, $smsg);
350                 my $lk = $ovv->lock_for_scope;
351                 $lei->out(${$lvt->eml_to_text($smsg, $eml)}, "\n");
352         }
353 }
354
355 sub _v2_write_cb ($$) {
356         my ($self, $lei) = @_;
357         my $dedupe = $lei->{dedupe};
358         $dedupe->prepare_dedupe if $dedupe;
359         sub { # for git_to_mail
360                 my ($bref, $smsg, $eml) = @_;
361                 $eml //= PublicInbox::Eml->new($bref);
362                 return if $dedupe && $dedupe->is_dup($eml, $smsg);
363                 $lei->{v2w}->wq_do('add', $eml); # V2Writable->add
364                 ++$lei->{-nr_write};
365         }
366 }
367
368 sub write_cb { # returns a callback for git_to_mail
369         my ($self, $lei) = @_;
370         # _mbox_write_cb, _maildir_write_cb, _imap_write_cb, _v2_write_cb
371         my $m = "_$self->{base_type}_write_cb";
372         $self->$m($lei);
373 }
374
375 sub new {
376         my ($cls, $lei) = @_;
377         my $fmt = $lei->{ovv}->{fmt};
378         my $dst = $lei->{ovv}->{dst};
379         my $self = bless {}, $cls;
380         my @conflict;
381         if ($fmt eq 'maildir') {
382                 require PublicInbox::MdirReader;
383                 $self->{base_type} = 'maildir';
384                 -e $dst && !-d _ and die
385                                 "$dst exists and is not a directory\n";
386                 $lei->{ovv}->{dst} = $dst .= '/' if substr($dst, -1) ne '/';
387                 $lei->{opt}->{save} //= \1 if $lei->{cmd} eq 'q';
388         } elsif (substr($fmt, 0, 4) eq 'mbox') {
389                 require PublicInbox::MboxReader;
390                 $self->can("eml2$fmt") or die "bad mbox format: $fmt\n";
391                 $self->{base_type} = 'mbox';
392                 if ($lei->{cmd} eq 'q' &&
393                                 (($lei->path_to_fd($dst) // -1) < 0) &&
394                                 (-f $dst || !-e _)) {
395                         $lei->{opt}->{save} //= \1;
396                 }
397         } elsif ($fmt =~ /\Aimaps?\z/) {
398                 require PublicInbox::NetWriter;
399                 require PublicInbox::URIimap;
400                 # {net} may exist from "lei up" for auth
401                 my $net = $lei->{net} // PublicInbox::NetWriter->new;
402                 $net->{quiet} = $lei->{opt}->{quiet};
403                 my $uri = PublicInbox::URIimap->new($dst)->canonical;
404                 $net->add_url($$uri);
405                 my $err = $net->errors($lei);
406                 return $lei->fail($err) if $err;
407                 $uri->mailbox or return $lei->fail("No mailbox: $dst");
408                 $self->{uri} = $uri;
409                 $dst = $lei->{ovv}->{dst} = $$uri; # canonicalized
410                 $lei->{net} = $net;
411                 $self->{base_type} = 'imap';
412                 $lei->{opt}->{save} //= \1 if $lei->{cmd} eq 'q';
413         } elsif ($fmt eq 'text' || $fmt eq 'reply') {
414                 require PublicInbox::LeiViewText;
415                 $lei->{lvt} = PublicInbox::LeiViewText->new($lei, $fmt);
416                 $self->{base_type} = 'text';
417                 @conflict = qw(mua save);
418         } elsif ($fmt eq 'v2') {
419                 die "--dedupe=oid and v2 are incompatible\n" if
420                         ($lei->{opt}->{dedupe}//'') eq 'oid';
421                 $self->{base_type} = 'v2';
422                 $lei->{opt}->{save} = \1;
423                 $dst = $lei->{ovv}->{dst} = $lei->abs_path($dst);
424                 @conflict = qw(mua sort);
425         } else {
426                 die "bad mail --format=$fmt\n";
427         }
428         if ($self->{base_type} =~ /\A(?:text|mbox)\z/) {
429                 (-d $dst || (-e _ && !-w _)) and die
430                         "$dst exists and is not a writable file\n";
431         }
432         my @err = map { defined($lei->{opt}->{$_}) ? "--$_" : () } @conflict;
433         die "@err incompatible with $fmt\n" if @err;
434         $self->{dst} = $dst;
435         $lei->{dedupe} = $lei->{lss} // do {
436                 my $dd_cls = 'PublicInbox::'.
437                         ($lei->{opt}->{save} ? 'LeiSavedSearch' : 'LeiDedupe');
438                 eval "require $dd_cls";
439                 die "$dd_cls: $@" if $@;
440                 my $dd = $dd_cls->new($lei);
441                 $lei->{lss} //= $dd if $dd && $dd->can('cfg_set');
442                 $dd;
443         };
444         $self;
445 }
446
447 sub _pre_augment_maildir {
448         my ($self, $lei) = @_;
449         my $dst = $lei->{ovv}->{dst};
450         for my $x (qw(tmp new cur)) {
451                 my $d = $dst.$x;
452                 next if -d $d;
453                 require File::Path;
454                 File::Path::mkpath($d);
455                 -d $d or die "$d is not a directory";
456         }
457         # for utime, so no opendir
458         open $self->{poke_dh}, '<', "${dst}cur" or die "open ${dst}cur: $!";
459 }
460
461 sub clobber_dst_prepare ($;$) {
462         my ($lei, $f) = @_;
463         if (my $lms = defined($f) ? $lei->lms : undef) {
464                 $lms->lms_write_prepare;
465                 $lms->forget_folders($f);
466         }
467         my $dedupe = $lei->{dedupe} or return;
468         $dedupe->reset_dedupe if $dedupe->can('reset_dedupe');
469 }
470
471 sub _do_augment_maildir {
472         my ($self, $lei) = @_;
473         return if $lei->{cmd} eq 'up';
474         my $dst = $lei->{ovv}->{dst};
475         my $lse = $lei->{opt}->{'import-before'} ? $lei->{lse} : undef;
476         my $mdr = PublicInbox::MdirReader->new;
477         if ($lei->{opt}->{augment}) {
478                 my $dedupe = $lei->{dedupe};
479                 if ($dedupe && $dedupe->prepare_dedupe) {
480                         $mdr->{shard_info} = $self->{shard_info};
481                         $mdr->maildir_each_eml($dst, \&_md_update, $lei, $lse);
482                         $dedupe->pause_dedupe;
483                 }
484         } elsif ($lse) {
485                 clobber_dst_prepare($lei, "maildir:$dst");
486                 $mdr->{shard_info} = $self->{shard_info};
487                 $mdr->maildir_each_eml($dst, \&_md_update, $lei, $lse, 1);
488         } else {# clobber existing Maildir
489                 clobber_dst_prepare($lei, "maildir:$dst");
490                 $mdr->maildir_each_file($dst, \&_unlink);
491         }
492 }
493
494 sub _imap_augment_or_delete { # PublicInbox::NetReader::imap_each cb
495         my ($uri, $uid, $kw, $eml, $lei, $lse, $delete_mic) = @_;
496         update_kw_maybe($lei, $lse, $eml, $kw);
497         if ($delete_mic) {
498                 $lei->{net}->imap_delete_1($uri, $uid, $delete_mic);
499         } else {
500                 _augment($eml, $lei);
501         }
502 }
503
504 sub _do_augment_imap {
505         my ($self, $lei) = @_;
506         return if $lei->{cmd} eq 'up';
507         my $net = $lei->{net};
508         my $lse = $lei->{opt}->{'import-before'} ? $lei->{lse} : undef;
509         if ($lei->{opt}->{augment}) {
510                 my $dedupe = $lei->{dedupe};
511                 if ($dedupe && $dedupe->prepare_dedupe) {
512                         $net->imap_each($self->{uri}, \&_imap_augment_or_delete,
513                                         $lei, $lse);
514                         $dedupe->pause_dedupe;
515                 }
516         } elsif ($lse) {
517                 my $delete_mic;
518                 clobber_dst_prepare($lei, "$self->{uri}");
519                 $net->imap_each($self->{uri}, \&_imap_augment_or_delete,
520                                         $lei, $lse, \$delete_mic);
521                 $delete_mic->expunge if $delete_mic;
522         } elsif (!$self->{-wq_worker_nr}) { # undef or 0
523                 # clobber existing IMAP folder
524                 clobber_dst_prepare($lei, "$self->{uri}");
525                 $net->imap_delete_all($self->{uri});
526         }
527 }
528
529 sub _pre_augment_text {
530         my ($self, $lei) = @_;
531         my $dst = $lei->{ovv}->{dst};
532         my $out;
533         my $devfd = $lei->path_to_fd($dst) // die "bad $dst";
534         if ($devfd >= 0) {
535                 $out = $lei->{$devfd};
536         } else { # normal-looking path
537                 if (-p $dst) {
538                         open $out, '>', $dst or die "open($dst): $!";
539                 } elsif (-f _ || !-e _) {
540                         # text allows augment, HTML/Atom won't
541                         my $mode = $lei->{opt}->{augment} ? '>>' : '>';
542                         open $out, $mode, $dst or die "open($mode, $dst): $!";
543                 } else {
544                         die "$dst is not a file or FIFO\n";
545                 }
546         }
547         $lei->{ovv}->ovv_out_lk_init if !$lei->{ovv}->{lock_path};
548         $lei->{1} = $out;
549         undef;
550 }
551
552 sub _pre_augment_mbox {
553         my ($self, $lei) = @_;
554         my $dst = $lei->{ovv}->{dst};
555         my $out;
556         my $devfd = $lei->path_to_fd($dst) // die "bad $dst";
557         if ($devfd >= 0) {
558                 $out = $lei->{$devfd};
559         } else { # normal-looking path
560                 if (-p $dst) {
561                         open $out, '>', $dst or die "open($dst): $!";
562                 } elsif (-f _ || !-e _) {
563                         require PublicInbox::MboxLock;
564                         my $m = $lei->{opt}->{'lock'} //
565                                         PublicInbox::MboxLock->defaults;
566                         $self->{mbl} = PublicInbox::MboxLock->acq($dst, 1, $m);
567                         $out = $self->{mbl}->{fh};
568                 } else {
569                         die "$dst is not a file or FIFO\n";
570                 }
571                 $lei->{old_1} = $lei->{1}; # keep for spawning MUA
572         }
573         # Perl does SEEK_END even with O_APPEND :<
574         $self->{seekable} = seek($out, 0, SEEK_SET);
575         if (!$self->{seekable} && !$!{ESPIPE} && !defined($devfd)) {
576                 die "seek($dst): $!\n";
577         }
578         if (!$self->{seekable}) {
579                 my $imp_before = $lei->{opt}->{'import-before'};
580                 die "--import-before specified but $dst is not seekable\n"
581                         if $imp_before && !ref($imp_before);
582                 die "--augment specified but $dst is not seekable\n" if
583                         $lei->{opt}->{augment};
584                 die "cannot --save with unseekable $dst\n" if
585                         $lei->{dedupe} && $lei->{dedupe}->can('reset_dedupe');
586         }
587         if ($self->{zsfx} = PublicInbox::MboxReader::zsfx($dst)) {
588                 pipe(my ($r, $w)) or die "pipe: $!";
589                 $lei->{zpipe} = [ $r, $w ];
590                 $lei->{ovv}->{lock_path} and
591                         die 'BUG: unexpected {ovv}->{lock_path}';
592                 $lei->{ovv}->ovv_out_lk_init;
593         } elsif (!$self->{seekable} && !$lei->{ovv}->{lock_path}) {
594                 $lei->{ovv}->ovv_out_lk_init;
595         }
596         $lei->{1} = $out;
597         undef;
598 }
599
600 sub _do_augment_mbox {
601         my ($self, $lei) = @_;
602         return unless $self->{seekable};
603         my $opt = $lei->{opt};
604         return if $lei->{cmd} eq 'up';
605         my $out = $lei->{1};
606         my ($fmt, $dst) = @{$lei->{ovv}}{qw(fmt dst)};
607         return clobber_dst_prepare($lei) unless -s $out;
608         unless ($opt->{augment} || $opt->{'import-before'}) {
609                 truncate($out, 0) or die "truncate($dst): $!";
610                 return;
611         }
612         my $rd;
613         if (my $zsfx = $self->{zsfx}) {
614                 $rd = PublicInbox::MboxReader::zsfxcat($out, $zsfx, $lei);
615         } else {
616                 open($rd, '+>>&', $out) or die "dup: $!";
617         }
618         my $dedupe;
619         if ($opt->{augment}) {
620                 $dedupe = $lei->{dedupe};
621                 $dedupe->prepare_dedupe if $dedupe;
622         } else {
623                 clobber_dst_prepare($lei);
624         }
625         if ($opt->{'import-before'}) { # the default
626                 my $lse = $lei->{lse};
627                 PublicInbox::MboxReader->$fmt($rd, \&_mbox_augment_kw_maybe,
628                                                 $lei, $lse, $opt->{augment});
629                 if (!$opt->{augment} and !truncate($out, 0)) {
630                         die "truncate($dst): $!";
631                 }
632         } else { # --augment --no-import-before
633                 PublicInbox::MboxReader->$fmt($rd, \&_augment, $lei);
634         }
635         # maybe some systems don't honor O_APPEND, Perl does this:
636         seek($out, 0, SEEK_END) or die "seek $dst: $!";
637         $dedupe->pause_dedupe if $dedupe;
638 }
639
640 sub v2w_done_wait { # dwaitpid callback
641         my ($arg, $pid) = @_;
642         my ($v2w, $lei) = @$arg;
643         $lei->child_error($?, "error for $v2w->{ibx}->{inboxdir}") if $?;
644 }
645
646 sub _pre_augment_v2 {
647         my ($self, $lei) = @_;
648         my $dir = $self->{dst};
649         require PublicInbox::InboxWritable;
650         my ($ibx, @creat);
651         if (-d $dir) {
652                 my $opt = { -min_inbox_version => 2 };
653                 require PublicInbox::Admin;
654                 my @ibx = PublicInbox::Admin::resolve_inboxes([ $dir ], $opt);
655                 $ibx = $ibx[0] or die "$dir is not a v2 inbox\n";
656         } else {
657                 $creat[0] = {};
658                 $ibx = PublicInbox::Inbox->new({
659                         name => 'lei-result', # XXX configurable
660                         inboxdir => $dir,
661                         version => 2,
662                         address => [ 'lei@example.com' ],
663                 });
664         }
665         PublicInbox::InboxWritable->new($ibx, @creat);
666         $ibx->init_inbox if @creat;
667         my $v2w = $ibx->importer;
668         $v2w->wq_workers_start("lei/v2w $dir", 1, $lei->oldset, {lei => $lei});
669         $v2w->wq_wait_async(\&v2w_done_wait, $lei);
670         $lei->{v2w} = $v2w;
671         return if !$lei->{opt}->{shared};
672         my $d = "$lei->{ale}->{git}->{git_dir}/objects";
673         my $al = "$dir/git/0.git/objects/info/alternates";
674         open my $fh, '+>>', $al or die "open($al): $!";
675         seek($fh, 0, SEEK_SET) or die "seek($al): $!";
676         grep(/\A\Q$d\E\n/, <$fh>) and return;
677         print $fh "$d\n" or die "print($al): $!";
678         close $fh or die "close($al): $!";
679 }
680
681 sub pre_augment { # fast (1 disk seek), runs in same process as post_augment
682         my ($self, $lei) = @_;
683         # _pre_augment_maildir, _pre_augment_mbox, _pre_augment_v2
684         my $m = $self->can("_pre_augment_$self->{base_type}") or return;
685         $m->($self, $lei);
686 }
687
688 sub do_augment { # slow, runs in wq worker
689         my ($self, $lei) = @_;
690         # _do_augment_maildir, _do_augment_mbox, or _do_augment_imap
691         my $m = $self->can("_do_augment_$self->{base_type}") or return;
692         $m->($self, $lei);
693 }
694
695 # fast (spawn compressor or mkdir), runs in same process as pre_augment
696 sub post_augment {
697         my ($self, $lei, @args) = @_;
698         $self->{-au_noted}++ and $lei->qerr("# writing to $self->{dst} ...");
699
700         my $wait = $lei->{opt}->{'import-before'} ?
701                         $lei->{sto}->wq_do('checkpoint', 1) : 0;
702         # _post_augment_mbox
703         my $m = $self->can("_post_augment_$self->{base_type}") or return;
704         $m->($self, $lei, @args);
705 }
706
707 # called by every single l2m worker process
708 sub do_post_auth {
709         my ($self) = @_;
710         my $lei = $self->{lei};
711         # lei_xsearch can start as soon as all l2m workers get here
712         $lei->{pkt_op_p}->pkt_do('incr_start_query') or
713                 die "incr_start_query: $!";
714         my $aug;
715         if (lock_free($self)) { # all workers do_augment
716                 my $mod = $self->{-wq_nr_workers};
717                 my $shard = $self->{-wq_worker_nr};
718                 if (my $net = $lei->{net}) {
719                         $net->{shard_info} = [ $mod, $shard ];
720                 } else { # Maildir
721                         $self->{shard_info} = [ $mod, $shard ];
722                 }
723                 $aug = 'incr_post_augment';
724         } elsif ($self->{-wq_worker_nr} == 0) { # 1st worker do_augment
725                 $aug = 'do_post_augment';
726         }
727         if ($aug) {
728                 local $0 = 'do_augment';
729                 eval { do_augment($self, $lei) };
730                 $lei->fail($@) if $@;
731                 $lei->{pkt_op_p}->pkt_do($aug) or die "pkt_do($aug): $!";
732         }
733         # done augmenting, connect the compressor pipe for each worker
734         if (my $zpipe = delete $lei->{zpipe}) {
735                 $lei->{1} = $zpipe->[1];
736                 close $zpipe->[0];
737         }
738         my $au_peers = delete $self->{au_peers};
739         if ($au_peers) { # wait for peer l2m to finish augmenting:
740                 $au_peers->[1] = undef;
741                 sysread($au_peers->[0], my $barrier1, 1);
742         }
743         $self->{wcb} = $self->write_cb($lei);
744         if ($au_peers) { # wait for peer l2m to set write_cb
745                 $au_peers->[3] = undef;
746                 sysread($au_peers->[2], my $barrier2, 1);
747         }
748 }
749
750 sub ipc_atfork_child {
751         my ($self) = @_;
752         my $lei = $self->{lei};
753         $lei->_lei_atfork_child;
754         if (my $lse = $lei->{lse}) {
755                 $self->{-lms_ro} = $lse->{-lms_ro} //= $lse->lms;
756         }
757         $lei->{auth}->do_auth_atfork($self) if $lei->{auth};
758         $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb();
759         $self->SUPER::ipc_atfork_child;
760 }
761
762 sub lock_free {
763         $_[0]->{base_type} =~ /\A(?:maildir|imap|jmap)\z/ ? 1 : 0;
764 }
765
766 # wakes up the MUA when complete so it can refresh messages list
767 sub poke_dst {
768         my ($self) = @_;
769         if ($self->{base_type} eq 'maildir') {
770                 my $t = time + 1;
771                 utime($t, $t, $self->{poke_dh}) or warn "futimes: $!";
772         }
773 }
774
775 sub write_mail { # via ->wq_io_do
776         my ($self, $smsg, $eml) = @_;
777         return $self->{wcb}->(undef, $smsg, $eml) if $eml;
778         $smsg->{-lms_ro} = $self->{-lms_ro};
779         $self->{lei}->{ale}->git->cat_async($smsg->{blob}, \&git_to_mail,
780                                 [$self->{wcb}, $smsg]);
781 }
782
783 sub wq_atexit_child {
784         my ($self) = @_;
785         local $PublicInbox::DS::in_loop = 0; # waitpid synchronously
786         my $lei = $self->{lei};
787         delete $self->{wcb};
788         $lei->{ale}->git->async_wait_all;
789         my $nr = delete($lei->{-nr_write}) or return;
790         return if $lei->{early_mua} || !$lei->{-progress} || !$lei->{pkt_op_p};
791         $lei->{pkt_op_p}->pkt_do('l2m_progress', $nr);
792 }
793
794 # runs on a 1s timer in lei-daemon
795 sub augment_inprogress {
796         my ($err, $opt, $dst, $au_noted) = @_;
797         eval {
798                 return if $$au_noted++ || !$err || !defined(fileno($err));
799                 print $err '# '.($opt->{'import-before'} ?
800                                 "importing non-external contents of $dst" : (
801                                 ($opt->{dedupe} // 'content') ne 'none') ?
802                                 "scanning old contents of $dst for dedupe" :
803                                 "removing old contents of $dst")." ...\n";
804         };
805         warn "E: $@ ($dst)" if $@;
806 }
807
808 # called in top-level lei-daemon when LeiAuth is done
809 sub net_merge_all_done {
810         my ($self, $lei) = @_;
811         if ($PublicInbox::DS::in_loop &&
812                         $self->can("_do_augment_$self->{base_type}") &&
813                         !$lei->{opt}->{quiet}) {
814                 $self->{-au_noted} = 0;
815                 PublicInbox::DS::add_timer(1, \&augment_inprogress,
816                                 $lei->{2}, $lei->{opt},
817                                 $self->{dst}, \$self->{-au_noted});
818         }
819         $self->wq_broadcast('do_post_auth');
820         $self->wq_close;
821 }
822
823 1;