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