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