1 # Copyright (C) 2016-2020 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(spawn 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);
23 # we can't change arg order, this is documented in POD
24 # and external projects may rely on it:
25 my ($class, $git, $name, $email, $ibx) = @_;
26 my $ref = 'refs/heads/master';
28 $ref = $ibx->{ref_head} // 'refs/heads/master';
29 $name //= $ibx->{name};
30 $email //= $ibx->{-primary_address};
35 ident => "$name <$email>",
39 path_type => '2/38', # or 'v2'
40 lock_path => "$git->{git_dir}/ssoma.lock", # v2 changes this
45 # idempotent start function
49 return ($self->{in}, $self->{out}) if $self->{pid};
52 pipe($out_r, $out_w) or die "pipe failed: $!";
53 my $git = $self->{git};
58 my $ref = $self->{ref};
59 chomp($self->{tip} = $git->qx(qw(rev-parse --revs-only), $ref));
60 if ($self->{path_type} ne '2/38' && $self->{tip}) {
62 my @tree = $git->qx(qw(ls-tree -r -z --name-only), $ref);
64 $self->{-tree} = { map { $_ => 1 } @tree };
67 my $git_dir = $git->{git_dir};
68 my @cmd = ('git', "--git-dir=$git_dir", qw(fast-import
69 --quiet --done --date-format=raw));
70 my ($in_r, $pid) = popen_rd(\@cmd, undef, { 0 => $out_r });
73 $self->{out} = $out_w;
76 binmode $out_w, ':raw' or die "binmode :raw failed: $!";
77 binmode $in_r, ':raw' or die "binmode :raw failed: $!";
81 sub wfail () { die "write to fast-import failed: $!" }
83 sub now_raw () { time . ' +0000' }
87 my $b = $mime->body_raw;
88 $b =~ s/(\r?\n)+\z//s;
92 # only used for v1 (ssoma) inboxes
93 sub _check_path ($$$$) {
94 my ($r, $w, $tip, $path) = @_;
96 print $w "ls $tip $path\n" or wfail;
98 defined(my $info = <$r>) or die "EOF from fast-import: $!";
99 $info =~ /\Amissing / ? undef : $info;
102 sub _cat_blob ($$$) {
103 my ($r, $w, $oid) = @_;
104 print $w "cat-blob $oid\n" or wfail;
107 defined $info or die "EOF from fast-import / cat-blob: $!";
108 $info =~ /\A[a-f0-9]{40} blob ([0-9]+)\n\z/ or return;
114 $n = read($r, $buf, $left, $offset);
115 defined($n) or die "read cat-blob failed: $!";
116 $n == 0 and die 'fast-export (cat-blob) died';
120 $n = read($r, my $lf, 1);
121 defined($n) or die "read final byte of cat-blob failed: $!";
122 die "bad read on final byte: <$lf>" if $lf ne "\n";
124 # fixup some bugginess in old versions:
125 $buf =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
130 my ($self, $oid) = @_;
131 my ($r, $w) = $self->gfi_start;
132 _cat_blob($r, $w, $oid);
135 sub check_remove_v1 {
136 my ($r, $w, $tip, $path, $mime) = @_;
138 my $info = _check_path($r, $w, $tip, $path) or return ('MISSING',undef);
139 $info =~ m!\A100644 blob ([a-f0-9]{40})\t!s or die "not blob: $info";
141 my $msg = _cat_blob($r, $w, $oid) or die "BUG: cat-blob $1 failed";
142 my $cur = PublicInbox::Eml->new($msg);
143 my $cur_s = $cur->header('Subject');
144 $cur_s = '' unless defined $cur_s;
145 my $cur_m = $mime->header('Subject');
146 $cur_m = '' unless defined $cur_m;
147 if ($cur_s ne $cur_m || norm_body($cur) ne norm_body($mime)) {
148 return ('MISMATCH', $cur);
155 return unless $self->{pid};
156 print { $self->{out} } "checkpoint\n" or wfail;
161 my ($self, $msg) = @_;
162 return unless $self->{pid};
163 print { $self->{out} } "progress $msg\n" or wfail;
164 readline($self->{in}) eq "progress $msg\n" or die
165 "progress $msg not received\n";
169 sub _update_git_info ($$) {
170 my ($self, $do_gc) = @_;
171 # for compatibility with existing ssoma installations
172 # we can probably remove this entirely by 2020
173 my $git_dir = $self->{git}->{git_dir};
174 my @cmd = ('git', "--git-dir=$git_dir");
175 my $index = "$git_dir/ssoma.index";
176 if (-e $index && !$ENV{FAST}) {
177 my $env = { GIT_INDEX_FILE => $index };
178 run_die([@cmd, qw(read-tree -m -v -i), $self->{ref}], $env);
180 run_die([@cmd, 'update-server-info']);
181 my $ibx = $self->{-inbox};
182 ($ibx && $self->{path_type} eq '2/38') and eval {
183 require PublicInbox::SearchIdx;
184 my $s = PublicInbox::SearchIdx->new($ibx);
185 $s->index_sync({ ref => $self->{ref} });
187 eval { run_die([@cmd, qw(gc --auto)]) } if $do_gc;
193 # For safety, we ensure git checkpoint is complete before because
194 # the data in git is still more important than what is in Xapian
195 # in v2. Performance may be gained by delaying the ->progress
196 # call but we lose safety
199 $self->progress('checkpoint');
200 _update_git_info($self, 0);
207 my ($self, $mark) = @_;
208 die "not active\n" unless $self->{pid};
209 my ($r, $w) = $self->gfi_start;
210 print $w "get-mark $mark\n" or wfail;
211 defined(my $oid = <$r>) or die "get-mark failed, need git 2.6.0+\n";
216 # returns undef on non-existent
217 # ('MISMATCH', PublicInbox::Eml) on mismatch
218 # (:MARK, PublicInbox::Eml) on success
220 # v2 callers should check with Xapian before calling this as
221 # it is not idempotent.
223 my ($self, $mime, $msg) = @_; # mime = PublicInbox::Eml or Email::MIME
225 my $path_type = $self->{path_type};
226 my ($path, $err, $cur, $blob);
228 my ($r, $w) = $self->gfi_start;
229 my $tip = $self->{tip};
230 if ($path_type eq '2/38') {
231 $path = mid2path(v1_mid0($mime));
232 ($err, $cur) = check_remove_v1($r, $w, $tip, $path, $mime);
233 return ($err, $cur) if $err;
236 if (ref($mime) eq 'SCALAR') { # optimization used by V2Writable
238 } else { # XXX should not be necessary:
239 my $str = $mime->as_string;
242 my $len = length($$sref);
243 $blob = $self->{mark}++;
244 print $w "blob\nmark :$blob\ndata $len\n",
245 $$sref, "\n" or wfail;
248 my $ref = $self->{ref};
249 my $commit = $self->{mark}++;
250 my $parent = $tip =~ /\A:/ ? $tip : undef;
252 print $w "reset $ref\n" or wfail;
254 my $ident = $self->{ident};
257 my $len = length($msg) + 1;
258 print $w "commit $ref\nmark :$commit\n",
259 "author $ident $now\n",
260 "committer $ident $now\n",
261 "data $len\n$msg\n\n",
262 'from ', ($parent ? $parent : $tip), "\n" or wfail;
264 print $w "D $path\n\n" or wfail;
266 clean_tree_v2($self, $w, 'd');
267 print $w "M 100644 :$blob d\n\n" or wfail;
270 (($self->{tip} = ":$commit"), $cur);
273 sub git_timestamp ($) {
274 my ($ts, $zone) = @{$_[0]};
275 $ts = 0 if $ts < 0; # git uses unsigned times
279 sub extract_cmt_info ($;$) {
280 my ($mime, $smsg) = @_;
281 # $mime is PublicInbox::Eml, but remains Email::MIME-compatible
282 $smsg //= bless {}, 'PublicInbox::Smsg';
284 my $hdr = $mime->header_obj;
285 $smsg->populate($hdr);
288 my $from = delete($smsg->{From}) // '';
289 my ($email) = PublicInbox::Address::emails($from);
290 my ($name) = PublicInbox::Address::names($from);
291 if (!defined($name) || !defined($email)) {
292 $sender = $hdr->header('Sender') // '';
293 $name //= (PublicInbox::Address::names($sender))[0];
294 $email //= (PublicInbox::Address::emails($sender))[0];
296 if (defined $email) {
297 # Email::Address::XS may leave quoted '<' in addresses,
298 # which git-fast-import doesn't like
301 # quiet down wide character warnings with utf8::encode
302 utf8::encode($email);
305 warn "no email in From: $from or Sender: $sender\n";
308 # git gets confused with:
309 # "'A U Thor <u@example.com>' via foo" <foo@example.com>
311 # <CAD0k6qSUYANxbjjbE4jTW4EeVwOYgBD=bXkSu=akiYC_CB7Ffw@mail.gmail.com>
317 warn "no name in From: $from or Sender: $sender\n";
320 my $subject = delete($smsg->{Subject}) // '(no subject)';
321 utf8::encode($subject);
322 my $at = git_timestamp(delete $smsg->{-ds});
323 my $ct = git_timestamp(delete $smsg->{-ts});
324 ("$name <$email>", $at, $ct, $subject);
327 # kill potentially confusing/misleading headers
328 sub drop_unwanted_headers ($) {
331 $mime->header_set($_) for qw(bytes lines content-length status);
332 $mime->header_set($_) for @PublicInbox::MDA::BAD_HEADERS;
335 # used by V2Writable, too
336 sub append_mid ($$) {
337 my ($hdr, $mid0) = @_;
338 # @cur is likely empty if we need to call this sub, but it could
339 # have random unparseable crap which we'll preserve, too.
340 my @cur = $hdr->header_raw('Message-ID');
341 $hdr->header_set('Message-ID', @cur, "<$mid0>");
346 my $hdr = $mime->header_obj;
347 my $mids = mids($hdr);
349 if (!scalar(@$mids)) { # spam often has no Message-ID
350 my $mid0 = digest2mid(content_digest($mime), $hdr);
351 append_mid($hdr, $mid0);
356 sub clean_tree_v2 ($$$) {
357 my ($self, $w, $keep) = @_;
358 my $tree = $self->{-tree} or return; #v2 only
359 delete $tree->{$keep};
360 foreach (keys %$tree) {
361 print $w "D $_\n" or wfail;
363 %$tree = ($keep => 1);
366 # returns undef on duplicate
367 # returns the :MARK of the most recent commit
369 my ($self, $mime, $check_cb, $smsg) = @_;
371 my ($author, $at, $ct, $subject) = extract_cmt_info($mime, $smsg);
372 my $path_type = $self->{path_type};
374 if ($path_type eq '2/38') {
375 $path = mid2path(v1_mid0($mime));
376 } else { # v2 layout, one file:
380 my ($r, $w) = $self->gfi_start;
381 my $tip = $self->{tip};
382 if ($path_type eq '2/38') {
383 _check_path($r, $w, $tip, $path) and return;
386 drop_unwanted_headers($mime);
390 $mime = $check_cb->($mime) or return;
393 my $blob = $self->{mark}++;
394 my $raw_email = $mime->{-public_inbox_raw} // $mime->as_string;
395 my $n = length($raw_email);
396 $self->{bytes_added} += $n;
397 print $w "blob\nmark :$blob\ndata ", $n, "\n" or wfail;
398 print $w $raw_email, "\n" or wfail;
400 # v2: we need this for Xapian
402 $smsg->{blob} = $self->get_mark(":$blob");
403 $smsg->{raw_bytes} = $n;
404 $smsg->{-raw_email} = \$raw_email;
406 my $ref = $self->{ref};
407 my $commit = $self->{mark}++;
408 my $parent = $tip =~ /\A:/ ? $tip : undef;
411 print $w "reset $ref\n" or wfail;
414 print $w "commit $ref\nmark :$commit\n",
415 "author $author $at\n",
416 "committer $self->{ident} $ct\n" or wfail;
417 print $w "data ", (length($subject) + 1), "\n",
418 $subject, "\n\n" or wfail;
420 print $w 'from ', ($parent ? $parent : $tip), "\n" or wfail;
422 clean_tree_v2($self, $w, $path);
423 print $w "M 100644 :$blob $path\n\n" or wfail;
425 $self->{tip} = ":$commit";
429 my ($cmd, $env, $rdr) = @_;
430 my $pid = spawn($cmd, $env, $rdr);
431 waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
432 $? == 0 or die join(' ', @$cmd) . " failed: $?\n";
435 my @INIT_FILES = ('HEAD' => "ref: refs/heads/master\n",
436 'description' => <<EOD,
437 Unnamed repository; edit this file 'description' to name the repository.
441 repositoryFormatVersion = 0
449 my ($dir) = @_; # or self
450 $dir = $dir->{git}->{git_dir} if ref($dir);
452 File::Path::mkpath([ map { "$dir/$_" } qw(objects/info refs/heads) ]);
453 for (my $i = 0; $i < @INIT_FILES; $i++) {
454 my $f = $dir.'/'.$INIT_FILES[$i++];
456 open my $fh, '>', $f or die "open $f: $!";
457 print $fh $INIT_FILES[$i] or die "print $f: $!";
458 close $fh or die "close $f: $!";
464 my $w = delete $self->{out} or return;
465 my $r = delete $self->{in} or die 'BUG: missing {in} when done';
466 print $w "done\n" or wfail;
467 my $pid = delete $self->{pid} or die 'BUG: missing {pid} when done';
468 waitpid($pid, 0) == $pid or die 'fast-import did not finish';
469 $? == 0 or die "fast-import failed: $?";
471 my $nchg = delete $self->{nchg};
472 _update_git_info($self, 1) if $nchg;
473 $self->lock_release(!!$nchg);
475 $self->{git}->cleanup;
480 foreach my $f (qw(in out)) {
481 next unless defined($self->{$f});
482 close $self->{$f} or die "failed to close import[$f]: $!\n";
486 sub digest2mid ($$) {
487 my ($dig, $hdr) = @_;
488 my $b64 = $dig->clone->b64digest;
489 # Make our own URLs nicer:
490 # See "Base 64 Encoding with URL and Filename Safe Alphabet" in RFC4648
493 # Add a date prefix to prevent a leading '-' in case that trips
494 # up some tools (e.g. if a Message-ID were a expected as a
496 my $dt = msg_datestamp($hdr);
497 $dt = POSIX::strftime('%Y%m%d%H%M%S', gmtime($dt));
501 sub rewrite_commit ($$$$) {
502 my ($self, $oids, $buf, $mime) = @_;
503 my ($author, $at, $ct, $subject);
505 ($author, $at, $ct, $subject) = extract_cmt_info($mime);
508 $subject = 'purged '.join(' ', @$oids);
512 foreach my $i (0..$#$buf) {
514 if ($l =~ /^author .* ([0-9]+ [\+-]?[0-9]+)$/) {
516 $buf->[$i] = "author $author $at\n";
517 } elsif ($l =~ /^committer .* ([0-9]+ [\+-]?[0-9]+)$/) {
519 $buf->[$i] = "committer $self->{ident} $ct\n";
520 } elsif ($l =~ /^data ([0-9]+)/) {
521 $buf->[$i++] = "data " . length($subject) . "\n";
522 $buf->[$i] = $subject;
528 # returns the new commit OID if a replacement was done
529 # returns undef if nothing was done
531 my ($self, $mime, $replace_map) = @_; # oid => raw string
532 my $tmp = "refs/heads/replace-".((keys %$replace_map)[0]);
533 my $old = $self->{'ref'};
534 my $git = $self->{git};
535 my @export = (qw(fast-export --no-data --use-done-feature), $old);
536 my $rd = $git->popen(@export);
537 my ($r, $w) = $self->gfi_start;
542 my $tree = $self->{-tree};
544 if (/^reset (?:.+)/) {
545 push @buf, "reset $tmp\n";
546 } elsif (/^commit (?:.+)/) {
548 print $w @buf or wfail;
551 push @buf, "commit $tmp\n";
552 } elsif (/^data ([0-9]+)/) {
553 # only commit message, so $len is small:
554 my $len = $1; # + 1 for trailing "\n"
556 my $n = read($rd, my $buf, $len) or die "read: $!";
557 $len == $n or die "short read ($n < $len)";
559 } elsif (/^M 100644 ([a-f0-9]+) (\w+)/) {
560 my ($oid, $path) = ($1, $2);
562 my $sref = $replace_map->{$oid};
565 my $n = length($$sref);
566 push @buf, "M 100644 inline $path\ndata $n\n";
567 push @buf, $$sref; # hope CoW works...
572 } elsif (/^D (\w+)/) {
574 push @buf, $_ if $tree->{$path};
575 } elsif ($_ eq "\n") {
578 my $out = join('', @buf);
580 warn "purge rewriting\n", $out, "\n";
582 rewrite_commit($self, \@oids, \@buf, $mime);
585 print $w @buf, "\n" or wfail;
587 } elsif ($_ eq "done\n") {
589 } elsif (/^mark :([0-9]+)$/) {
596 close $rd or die "close fast-export failed: $?";
598 print $w @buf or wfail;
600 die 'done\n not seen from fast-export' unless $done;
601 chomp(my $cmt = $self->get_mark(":$mark")) if $nreplace;
602 $self->{nchg} = 0; # prevent _update_git_info until update-ref:
604 my @git = ('git', "--git-dir=$git->{git_dir}");
606 run_die([@git, qw(update-ref), $old, $tmp]) if $nreplace;
608 run_die([@git, qw(update-ref -d), $tmp]);
610 return if $nreplace == 0;
612 run_die([@git, qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
614 # check that old OIDs are gone
616 foreach my $oid (keys %$replace_map) {
617 my @info = $git->check($oid);
619 warn "$oid not replaced\n";
623 _update_git_info($self, 0);
624 die "Failed to replace $err object(s)\n" if $err;
634 PublicInbox::Import - message importer for public-inbox v1 inboxes
642 use PublicInbox::Eml;
643 # PublicInbox::Eml exists as of public-inbox 1.5.0,
644 # Email::MIME was used in older versions
646 use PublicInbox::Git;
647 use PublicInbox::Import;
649 chomp(my $git_dir = `git rev-parse --git-dir`);
650 $git_dir or die "GIT_DIR= must be specified\n";
651 my $git = PublicInbox::Git->new($git_dir);
652 my @committer = ('inbox', 'inbox@example.org');
653 my $im = PublicInbox::Import->new($git, @committer);
656 my $message = "From: <u\@example.org>\n".
657 "Subject: test message \n" .
658 "Date: Thu, 01 Jan 1970 00:00:00 +0000\n" .
659 "Message-ID: <m\@example.org>\n".
661 my $parsed = PublicInbox::Eml->new($message);
662 my $ret = $im->add($parsed);
665 $parsed->header_obj->header_raw('Message-ID'), "\n";
667 print "imported at mark $ret\n";
671 # to remove a message
672 my $junk = PublicInbox::Eml->new($message);
673 my ($mark, $orig) = $im->remove($junk);
674 if ($mark eq 'MISSING') {
676 } elsif ($mark eq 'MISMATCH') {
677 print "Message exists but does not match\n\n",
678 $orig->as_string, "\n",;
680 print "removed at mark $mark\n\n",
681 $orig->as_string, "\n";
687 An importer and remover for public-inboxes which takes C<PublicInbox::Eml>
688 or L<Email::MIME> messages as input and stores them in a git repository as
689 documented in L<https://public-inbox.org/public-inbox-v1-format.txt>,
690 except it does not allow duplicate Message-IDs.
692 It requires L<git(1)> and L<git-fast-import(1)> to be installed.
700 my $im = PublicInbox::Import->new($git, @committer);
702 Initialize a new PublicInbox::Import object.
706 my $parsed = PublicInbox::Eml->new($message);
709 Adds a message to to the git repository. This will acquire
710 C<$GIT_DIR/ssoma.lock> and start L<git-fast-import(1)> if necessary.
712 Messages added will not be visible to other processes until L</done>
713 is called, but L</remove> may be called on them.
717 my $junk = PublicInbox::Eml->new($message);
718 my ($code, $orig) = $im->remove($junk);
720 Removes a message from the repository. On success, it returns
721 a ':'-prefixed numeric code representing the git-fast-import
722 mark and the original messages as a PublicInbox::Eml
723 (or Email::MIME) object.
724 If the message could not be found, the code is "MISSING"
725 and the original message is undef. If there is a mismatch where
726 the "Message-ID" is matched but the subject and body do not match,
727 the returned code is "MISMATCH" and the conflicting message
732 Finalizes the L<git-fast-import(1)> and unlocks the repository.
733 Calling this is required to finalize changes to a repository.
741 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
743 The mail archives are hosted at L<https://public-inbox.org/meta/>
747 Copyright (C) 2016-2020 all contributors L<mailto:meta@public-inbox.org>
749 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>