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