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