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