1 # Copyright (C) 2016-2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # git fast-import-based ssoma-mda MDA replacement
5 # This is only ever run by public-inbox-mda, public-inbox-learn
6 # and public-inbox-watch. Not the WWW or NNTP code which only
7 # requires read-only access.
8 package PublicInbox::Import;
10 use parent qw(PublicInbox::Lock);
12 use PublicInbox::Spawn qw(run_die popen_rd);
13 use PublicInbox::MID qw(mids mid2path);
14 use PublicInbox::Address;
15 use PublicInbox::Smsg;
16 use PublicInbox::MsgTime qw(msg_datestamp);
17 use PublicInbox::ContentHash qw(content_digest);
20 use POSIX qw(strftime);
22 sub default_branch () {
23 state $default_branch = do {
24 delete local $ENV{GIT_CONFIG};
25 my $r = popen_rd([qw(git config --global init.defaultBranch)]);
26 chomp(my $h = <$r> // '');
27 $h eq '' ? 'refs/heads/master' : $h;
32 # we can't change arg order, this is documented in POD
33 # and external projects may rely on it:
34 my ($class, $git, $name, $email, $ibx) = @_;
37 $ref = $ibx->{ref_head};
38 $name //= $ibx->{name};
39 $email //= $ibx->{-primary_address};
44 ident => "$name <$email>",
46 ref => $ref // default_branch,
48 path_type => '2/38', # or 'v2'
49 lock_path => "$git->{git_dir}/ssoma.lock", # v2 changes this
54 # idempotent start function
58 return ($self->{in}, $self->{out}) if $self->{pid};
60 my ($in_r, $pid, $out_r, $out_w);
61 pipe($out_r, $out_w) or die "pipe failed: $!";
65 my ($git, $ref) = @$self{qw(git ref)};
67 chomp($self->{tip} = $git->qx(qw(rev-parse --revs-only), $ref));
68 die "fatal: rev-parse --revs-only $ref: \$?=$?" if $?;
69 if ($self->{path_type} ne '2/38' && $self->{tip}) {
71 my @t = $git->qx(qw(ls-tree -r -z --name-only), $ref);
72 die "fatal: ls-tree -r -z --name-only $ref: \$?=$?" if $?;
74 $self->{-tree} = { map { $_ => 1 } @t };
76 my @cmd = ('git', "--git-dir=$git->{git_dir}",
77 qw(fast-import --quiet --done --date-format=raw));
78 ($in_r, $pid) = popen_rd(\@cmd, undef, { 0 => $out_r });
81 $self->{out} = $out_w;
92 sub wfail () { die "write to fast-import failed: $!" }
94 sub now_raw () { time . ' +0000' }
98 my $b = $mime->body_raw;
99 $b =~ s/(\r?\n)+\z//s;
103 # only used for v1 (ssoma) inboxes
104 sub _check_path ($$$$) {
105 my ($r, $w, $tip, $path) = @_;
106 return if $tip eq '';
107 print $w "ls $tip $path\n" or wfail;
109 defined(my $info = <$r>) or die "EOF from fast-import: $!";
110 $info =~ /\Amissing / ? undef : $info;
113 sub _cat_blob ($$$) {
114 my ($r, $w, $oid) = @_;
115 print $w "cat-blob $oid\n" or wfail;
118 defined $info or die "EOF from fast-import / cat-blob: $!";
119 $info =~ /\A[a-f0-9]{40,} blob ([0-9]+)\n\z/ or return;
125 $n = read($r, $buf, $left, $offset);
126 defined($n) or die "read cat-blob failed: $!";
127 $n == 0 and die 'fast-export (cat-blob) died';
131 $n = read($r, my $lf, 1);
132 defined($n) or die "read final byte of cat-blob failed: $!";
133 die "bad read on final byte: <$lf>" if $lf ne "\n";
135 # fixup some bugginess in old versions:
136 $buf =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
141 my ($self, $oid) = @_;
142 my ($r, $w) = $self->gfi_start;
143 _cat_blob($r, $w, $oid);
146 sub check_remove_v1 {
147 my ($r, $w, $tip, $path, $mime) = @_;
149 my $info = _check_path($r, $w, $tip, $path) or return ('MISSING',undef);
150 $info =~ m!\A100644 blob ([a-f0-9]{40,})\t!s or die "not blob: $info";
152 my $msg = _cat_blob($r, $w, $oid) or die "BUG: cat-blob $1 failed";
153 my $cur = PublicInbox::Eml->new($msg);
154 my $cur_s = $cur->header('Subject');
155 $cur_s = '' unless defined $cur_s;
156 my $cur_m = $mime->header('Subject');
157 $cur_m = '' unless defined $cur_m;
158 if ($cur_s ne $cur_m || norm_body($cur) ne norm_body($mime)) {
159 return ('MISMATCH', $cur);
166 return unless $self->{pid};
167 print { $self->{out} } "checkpoint\n" or wfail;
172 my ($self, $msg) = @_;
173 return unless $self->{pid};
174 print { $self->{out} } "progress $msg\n" or wfail;
175 readline($self->{in}) eq "progress $msg\n" or die
176 "progress $msg not received\n";
180 sub _update_git_info ($$) {
181 my ($self, $do_gc) = @_;
182 # for compatibility with existing ssoma installations
183 # we can probably remove this entirely by 2020
184 my $git_dir = $self->{git}->{git_dir};
185 my @cmd = ('git', "--git-dir=$git_dir");
186 my $index = "$git_dir/ssoma.index";
187 if (-e $index && !$ENV{FAST}) {
188 my $env = { GIT_INDEX_FILE => $index };
189 run_die([@cmd, qw(read-tree -m -v -i), $self->{ref}], $env);
191 eval { run_die([@cmd, 'update-server-info']) };
192 my $ibx = $self->{ibx};
193 if ($ibx && $ibx->version == 1 && -d "$ibx->{inboxdir}/public-inbox" &&
194 eval { require PublicInbox::SearchIdx }) {
196 my $s = PublicInbox::SearchIdx->new($ibx);
197 $s->index_sync({ ref => $self->{ref} });
199 warn "$ibx->{inboxdir} index failed: $@\n" if $@;
201 eval { run_die([@cmd, qw(gc --auto)]) } if $do_gc;
207 # For safety, we ensure git checkpoint is complete before because
208 # the data in git is still more important than what is in Xapian
209 # in v2. Performance may be gained by delaying the ->progress
210 # call but we lose safety
213 $self->progress('checkpoint');
214 _update_git_info($self, 0);
221 my ($self, $mark) = @_;
222 die "not active\n" unless $self->{pid};
223 my ($r, $w) = $self->gfi_start;
224 print $w "get-mark $mark\n" or wfail;
225 defined(my $oid = <$r>) or die "get-mark failed, need git 2.6.0+\n";
230 # returns undef on non-existent
231 # ('MISMATCH', PublicInbox::Eml) on mismatch
232 # (:MARK, PublicInbox::Eml) on success
234 # v2 callers should check with Xapian before calling this as
235 # it is not idempotent.
237 my ($self, $mime, $msg) = @_; # mime = PublicInbox::Eml or Email::MIME
239 my $path_type = $self->{path_type};
240 my ($path, $err, $cur, $blob);
242 my ($r, $w) = $self->gfi_start;
243 my $tip = $self->{tip};
244 if ($path_type eq '2/38') {
245 $path = mid2path(v1_mid0($mime));
246 ($err, $cur) = check_remove_v1($r, $w, $tip, $path, $mime);
247 return ($err, $cur) if $err;
250 if (ref($mime) eq 'SCALAR') { # optimization used by V2Writable
252 } else { # XXX should not be necessary:
253 my $str = $mime->as_string;
256 my $len = length($$sref);
257 $blob = $self->{mark}++;
258 print $w "blob\nmark :$blob\ndata $len\n",
259 $$sref, "\n" or wfail;
262 my $ref = $self->{ref};
263 my $commit = $self->{mark}++;
264 my $parent = $tip =~ /\A:/ ? $tip : undef;
266 print $w "reset $ref\n" or wfail;
268 my $ident = $self->{ident};
271 my $len = length($msg) + 1;
272 print $w "commit $ref\nmark :$commit\n",
273 "author $ident $now\n",
274 "committer $ident $now\n",
275 "data $len\n$msg\n\n",
276 'from ', ($parent ? $parent : $tip), "\n" or wfail;
278 print $w "D $path\n\n" or wfail;
280 clean_tree_v2($self, $w, 'd');
281 print $w "M 100644 :$blob d\n\n" or wfail;
284 (($self->{tip} = ":$commit"), $cur);
287 sub git_timestamp ($) {
288 my ($ts, $zone) = @{$_[0]};
289 $ts = 0 if $ts < 0; # git uses unsigned times
293 sub extract_cmt_info ($;$) {
294 my ($mime, $smsg) = @_;
295 # $mime is PublicInbox::Eml, but remains Email::MIME-compatible
296 $smsg //= bless {}, 'PublicInbox::Smsg';
298 $smsg->populate($mime);
301 my $from = delete($smsg->{From}) // '';
302 my ($email) = PublicInbox::Address::emails($from);
303 my ($name) = PublicInbox::Address::names($from);
304 if (!defined($name) || !defined($email)) {
305 $sender = $mime->header('Sender') // '';
306 $name //= (PublicInbox::Address::names($sender))[0];
307 $email //= (PublicInbox::Address::emails($sender))[0];
309 if (defined $email) {
310 # Email::Address::XS may leave quoted '<' in addresses,
311 # which git-fast-import doesn't like
314 # quiet down wide character warnings with utf8::encode
315 utf8::encode($email);
318 warn "no email in From: $from or Sender: $sender\n";
321 # git gets confused with:
322 # "'A U Thor <u@example.com>' via foo" <foo@example.com>
324 # <CAD0k6qSUYANxbjjbE4jTW4EeVwOYgBD=bXkSu=akiYC_CB7Ffw@mail.gmail.com>
330 warn "no name in From: $from or Sender: $sender\n";
333 my $subject = delete($smsg->{Subject}) // '(no subject)';
334 utf8::encode($subject);
335 my $at = git_timestamp(delete $smsg->{-ds});
336 my $ct = git_timestamp(delete $smsg->{-ts});
337 ("$name <$email>", $at, $ct, $subject);
340 # kill potentially confusing/misleading headers
341 our @UNWANTED_HEADERS = (qw(Bytes Lines Content-Length),
342 qw(Status X-Status));
343 sub drop_unwanted_headers ($) {
345 for (@UNWANTED_HEADERS, @PublicInbox::MDA::BAD_HEADERS) {
346 $eml->header_set($_);
350 # used by V2Writable, too
351 sub append_mid ($$) {
352 my ($hdr, $mid0) = @_;
353 # @cur is likely empty if we need to call this sub, but it could
354 # have random unparseable crap which we'll preserve, too.
355 my @cur = $hdr->header_raw('Message-ID');
356 $hdr->header_set('Message-ID', @cur, "<$mid0>");
361 my $mids = mids($eml);
363 if (!scalar(@$mids)) { # spam often has no Message-ID
364 my $mid0 = digest2mid(content_digest($eml), $eml);
365 append_mid($eml, $mid0);
370 sub clean_tree_v2 ($$$) {
371 my ($self, $w, $keep) = @_;
372 my $tree = $self->{-tree} or return; #v2 only
373 delete $tree->{$keep};
374 foreach (keys %$tree) {
375 print $w "D $_\n" or wfail;
377 %$tree = ($keep => 1);
380 # returns undef on duplicate
381 # returns the :MARK of the most recent commit
383 my ($self, $mime, $check_cb, $smsg) = @_;
385 my ($author, $at, $ct, $subject) = extract_cmt_info($mime, $smsg);
386 my $path_type = $self->{path_type};
388 if ($path_type eq '2/38') {
389 $path = mid2path(v1_mid0($mime));
390 } else { # v2 layout, one file:
394 my ($r, $w) = $self->gfi_start;
395 my $tip = $self->{tip};
396 if ($path_type eq '2/38') {
397 _check_path($r, $w, $tip, $path) and return;
400 drop_unwanted_headers($mime);
404 $mime = $check_cb->($mime, $self->{ibx}) or return;
407 my $blob = $self->{mark}++;
408 my $raw_email = $mime->{-public_inbox_raw} // $mime->as_string;
409 my $n = length($raw_email);
410 $self->{bytes_added} += $n;
411 print $w "blob\nmark :$blob\ndata ", $n, "\n" or wfail;
412 print $w $raw_email, "\n" or wfail;
414 # v2: we need this for Xapian
416 $smsg->{blob} = $self->get_mark(":$blob");
417 $smsg->{raw_bytes} = $n;
418 if (my $oidx = delete $smsg->{-oidx}) { # used by LeiStore
419 return if $oidx->blob_exists($smsg->{blob});
421 # XXX do we need this? it's in git at this point
422 $smsg->{-raw_email} = \$raw_email;
424 my $ref = $self->{ref};
425 my $commit = $self->{mark}++;
426 my $parent = $tip =~ /\A:/ ? $tip : undef;
429 print $w "reset $ref\n" or wfail;
432 print $w "commit $ref\nmark :$commit\n",
433 "author $author $at\n",
434 "committer $self->{ident} $ct\n" or wfail;
435 print $w "data ", (length($subject) + 1), "\n",
436 $subject, "\n\n" or wfail;
438 print $w 'from ', ($parent ? $parent : $tip), "\n" or wfail;
440 clean_tree_v2($self, $w, $path);
441 print $w "M 100644 :$blob $path\n\n" or wfail;
443 $self->{tip} = ":$commit";
446 my @INIT_FILES = ('HEAD' => undef, # filled in at runtime
447 'description' => <<EOD,
448 Unnamed repository; edit this file 'description' to name the repository.
452 repositoryFormatVersion = 0
460 my ($dir, $head) = @_; # or self
461 $dir = $dir->{git}->{git_dir} if ref($dir);
463 File::Path::mkpath([ map { "$dir/$_" } qw(objects/info refs/heads) ]);
464 $INIT_FILES[1] //= 'ref: '.default_branch."\n";
465 my @fn_contents = @INIT_FILES;
466 $fn_contents[1] = "ref: refs/heads/$head\n" if defined $head;
467 while (my ($fn, $contents) = splice(@fn_contents, 0, 2)) {
468 my $f = $dir.'/'.$fn;
470 open my $fh, '>', $f or die "open $f: $!";
471 print $fh $contents or die "print $f: $!";
472 close $fh or die "close $f: $!";
476 # true if locked and active
477 sub active { !!$_[0]->{out} }
481 my $w = delete $self->{out} or return;
483 my $r = delete $self->{in} or die 'BUG: missing {in} when done';
484 print $w "done\n" or wfail;
485 my $pid = delete $self->{pid} or
486 die 'BUG: missing {pid} when done';
487 waitpid($pid, 0) == $pid or die 'fast-import did not finish';
488 $? == 0 or die "fast-import failed: $?";
491 my $nchg = delete $self->{nchg};
492 if ($nchg && !$wait_err) {
493 eval { _update_git_info($self, 1) };
494 warn "E: $self->{git}->{git_dir} update info: $@\n" if $@;
496 $self->lock_release(!!$nchg);
497 $self->{git}->cleanup;
498 die $wait_err if $wait_err;
503 foreach my $f (qw(in out)) {
504 next unless defined($self->{$f});
505 close $self->{$f} or die "failed to close import[$f]: $!\n";
509 sub digest2mid ($$) {
510 my ($dig, $hdr) = @_;
511 my $b64 = $dig->clone->b64digest;
512 # Make our own URLs nicer:
513 # See "Base 64 Encoding with URL and Filename Safe Alphabet" in RFC4648
516 # Add a date prefix to prevent a leading '-' in case that trips
517 # up some tools (e.g. if a Message-ID were a expected as a
519 my $dt = msg_datestamp($hdr);
520 $dt = POSIX::strftime('%Y%m%d%H%M%S', gmtime($dt));
524 sub rewrite_commit ($$$$) {
525 my ($self, $oids, $buf, $mime) = @_;
526 my ($author, $at, $ct, $subject);
528 ($author, $at, $ct, $subject) = extract_cmt_info($mime);
531 $subject = 'purged '.join(' ', @$oids);
535 foreach my $i (0..$#$buf) {
537 if ($l =~ /^author .* ([0-9]+ [\+-]?[0-9]+)$/) {
539 $buf->[$i] = "author $author $at\n";
540 } elsif ($l =~ /^committer .* ([0-9]+ [\+-]?[0-9]+)$/) {
542 $buf->[$i] = "committer $self->{ident} $ct\n";
543 } elsif ($l =~ /^data ([0-9]+)/) {
544 $buf->[$i++] = "data " . length($subject) . "\n";
545 $buf->[$i] = $subject;
551 # returns the new commit OID if a replacement was done
552 # returns undef if nothing was done
554 my ($self, $mime, $replace_map) = @_; # oid => raw string
555 my $tmp = "refs/heads/replace-".((keys %$replace_map)[0]);
556 my $old = $self->{'ref'};
557 my $git = $self->{git};
558 my @export = (qw(fast-export --no-data --use-done-feature), $old);
559 my $rd = $git->popen(@export);
560 my ($r, $w) = $self->gfi_start;
565 my $tree = $self->{-tree};
567 if (/^reset (?:.+)/) {
568 push @buf, "reset $tmp\n";
569 } elsif (/^commit (?:.+)/) {
571 print $w @buf or wfail;
574 push @buf, "commit $tmp\n";
575 } elsif (/^data ([0-9]+)/) {
576 # only commit message, so $len is small:
577 my $len = $1; # + 1 for trailing "\n"
579 my $n = read($rd, my $buf, $len) or die "read: $!";
580 $len == $n or die "short read ($n < $len)";
582 } elsif (/^M 100644 ([a-f0-9]+) (\w+)/) {
583 my ($oid, $path) = ($1, $2);
585 my $sref = $replace_map->{$oid};
588 my $n = length($$sref);
589 push @buf, "M 100644 inline $path\ndata $n\n";
590 push @buf, $$sref; # hope CoW works...
595 } elsif (/^D (\w+)/) {
597 push @buf, $_ if $tree->{$path};
598 } elsif ($_ eq "\n") {
601 my $out = join('', @buf);
603 warn "purge rewriting\n", $out, "\n";
605 rewrite_commit($self, \@oids, \@buf, $mime);
608 print $w @buf, "\n" or wfail;
610 } elsif ($_ eq "done\n") {
612 } elsif (/^mark :([0-9]+)$/) {
619 close $rd or die "close fast-export failed: $?";
621 print $w @buf or wfail;
623 die 'done\n not seen from fast-export' unless $done;
624 chomp(my $cmt = $self->get_mark(":$mark")) if $nreplace;
625 $self->{nchg} = 0; # prevent _update_git_info until update-ref:
627 my @git = ('git', "--git-dir=$git->{git_dir}");
629 run_die([@git, qw(update-ref), $old, $tmp]) if $nreplace;
631 run_die([@git, qw(update-ref -d), $tmp]);
633 return if $nreplace == 0;
635 run_die([@git, qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
637 # check that old OIDs are gone
639 foreach my $oid (keys %$replace_map) {
640 my @info = $git->check($oid);
642 warn "$oid not replaced\n";
646 _update_git_info($self, 0);
647 die "Failed to replace $err object(s)\n" if $err;
657 PublicInbox::Import - message importer for public-inbox v1 inboxes
665 use PublicInbox::Eml;
666 # PublicInbox::Eml exists as of public-inbox 1.5.0,
667 # Email::MIME was used in older versions
669 use PublicInbox::Git;
670 use PublicInbox::Import;
672 chomp(my $git_dir = `git rev-parse --git-dir`);
673 $git_dir or die "GIT_DIR= must be specified\n";
674 my $git = PublicInbox::Git->new($git_dir);
675 my @committer = ('inbox', 'inbox@example.org');
676 my $im = PublicInbox::Import->new($git, @committer);
679 my $message = "From: <u\@example.org>\n".
680 "Subject: test message \n" .
681 "Date: Thu, 01 Jan 1970 00:00:00 +0000\n" .
682 "Message-ID: <m\@example.org>\n".
684 my $parsed = PublicInbox::Eml->new($message);
685 my $ret = $im->add($parsed);
687 warn "duplicate: ", $parsed->header_raw('Message-ID'), "\n";
689 print "imported at mark $ret\n";
693 # to remove a message
694 my $junk = PublicInbox::Eml->new($message);
695 my ($mark, $orig) = $im->remove($junk);
696 if ($mark eq 'MISSING') {
698 } elsif ($mark eq 'MISMATCH') {
699 print "Message exists but does not match\n\n",
700 $orig->as_string, "\n",;
702 print "removed at mark $mark\n\n",
703 $orig->as_string, "\n";
709 An importer and remover for public-inboxes which takes C<PublicInbox::Eml>
710 or L<Email::MIME> messages as input and stores them in a git repository as
711 documented in L<https://public-inbox.org/public-inbox-v1-format.txt>,
712 except it does not allow duplicate Message-IDs.
714 It requires L<git(1)> and L<git-fast-import(1)> to be installed.
722 my $im = PublicInbox::Import->new($git, @committer);
724 Initialize a new PublicInbox::Import object.
728 my $parsed = PublicInbox::Eml->new($message);
731 Adds a message to to the git repository. This will acquire
732 C<$GIT_DIR/ssoma.lock> and start L<git-fast-import(1)> if necessary.
734 Messages added will not be visible to other processes until L</done>
735 is called, but L</remove> may be called on them.
739 my $junk = PublicInbox::Eml->new($message);
740 my ($code, $orig) = $im->remove($junk);
742 Removes a message from the repository. On success, it returns
743 a ':'-prefixed numeric code representing the git-fast-import
744 mark and the original messages as a PublicInbox::Eml
745 (or Email::MIME) object.
746 If the message could not be found, the code is "MISSING"
747 and the original message is undef. If there is a mismatch where
748 the "Message-ID" is matched but the subject and body do not match,
749 the returned code is "MISMATCH" and the conflicting message
754 Finalizes the L<git-fast-import(1)> and unlocks the repository.
755 Calling this is required to finalize changes to a repository.
763 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
765 The mail archives are hosted at L<https://public-inbox.org/meta/>
769 Copyright (C) 2016-2020 all contributors L<mailto:meta@public-inbox.org>
771 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>