1 # Copyright (C) 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 my $r = popen_rd([qw(git config --global init.defaultBranch)],
25 { GIT_CONFIG => undef });
26 chomp(my $h = <$r> // '');
28 $h eq '' ? 'refs/heads/master' : "refs/heads/$h";
33 # we can't change arg order, this is documented in POD
34 # and external projects may rely on it:
35 my ($class, $git, $name, $email, $ibx) = @_;
38 $ref = $ibx->{ref_head};
39 $name //= $ibx->{name};
40 $email //= $ibx->{-primary_address};
45 ident => "$name <$email>",
47 ref => $ref // default_branch,
49 path_type => '2/38', # or 'v2'
50 lock_path => "$git->{git_dir}/ssoma.lock", # v2 changes this
55 # idempotent start function
59 return ($self->{in}, $self->{out}) if $self->{in};
61 my ($in_r, $out_r, $out_w);
62 pipe($out_r, $out_w) or die "pipe failed: $!";
66 my ($git, $ref) = @$self{qw(git ref)};
68 chomp($self->{tip} = $git->qx(qw(rev-parse --revs-only), $ref));
69 die "fatal: rev-parse --revs-only $ref: \$?=$?" if $?;
70 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 $?;
73 $self->{-tree} = { map { $_ => 1 } split(/\0/, $t) };
75 $in_r = $self->{in} = $git->popen(qw(fast-import
76 --quiet --done --date-format=raw),
77 undef, { 0 => $out_r });
79 $self->{out} = $out_w;
89 sub wfail () { die "write to fast-import failed: $!" }
91 sub now_raw () { time . ' +0000' }
95 my $b = $mime->body_raw;
96 $b =~ s/(\r?\n)+\z//s;
100 # only used for v1 (ssoma) inboxes
101 sub _check_path ($$$$) {
102 my ($r, $w, $tip, $path) = @_;
103 return if $tip eq '';
104 print $w "ls $tip $path\n" or wfail;
106 my $info = <$r> // die "EOF from fast-import: $!";
107 $info =~ /\Amissing / ? undef : $info;
110 sub _cat_blob ($$$) {
111 my ($r, $w, $oid) = @_;
112 print $w "cat-blob $oid\n" or wfail;
114 my $info = <$r> // die "EOF from fast-import / cat-blob: $!";
115 $info =~ /\A[a-f0-9]{40,} blob ([0-9]+)\n\z/ or return;
121 $n = read($r, $buf, $left, $offset) //
122 die "read cat-blob failed: $!";
123 $n == 0 and die 'fast-export (cat-blob) died';
127 $n = read($r, my $lf, 1) //
128 die "read final byte of cat-blob failed: $!";
129 die "bad read on final byte: <$lf>" if $lf ne "\n";
131 # fixup some bugginess in old versions:
132 $buf =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
137 my ($self, $oid) = @_;
138 my ($r, $w) = $self->gfi_start;
139 _cat_blob($r, $w, $oid);
142 sub check_remove_v1 {
143 my ($r, $w, $tip, $path, $mime) = @_;
145 my $info = _check_path($r, $w, $tip, $path) or return ('MISSING',undef);
146 $info =~ m!\A100644 blob ([a-f0-9]{40,})\t!s or die "not blob: $info";
148 my $msg = _cat_blob($r, $w, $oid) or die "BUG: cat-blob $1 failed";
149 my $cur = PublicInbox::Eml->new($msg);
150 my $cur_s = $cur->header('Subject') // '';
151 my $cur_m = $mime->header('Subject') // '';
152 if ($cur_s ne $cur_m || norm_body($cur) ne norm_body($mime)) {
153 return ('MISMATCH', $cur);
160 return unless $self->{in};
161 print { $self->{out} } "checkpoint\n" or wfail;
166 my ($self, $msg) = @_;
167 return unless $self->{in};
168 print { $self->{out} } "progress $msg\n" or wfail;
169 readline($self->{in}) eq "progress $msg\n" or die
170 "progress $msg not received\n";
174 sub _update_git_info ($$) {
175 my ($self, $do_gc) = @_;
176 # for compatibility with existing ssoma installations
177 # we can probably remove this entirely by 2020
178 my $git_dir = $self->{git}->{git_dir};
179 my @cmd = ('git', "--git-dir=$git_dir");
180 my $index = "$git_dir/ssoma.index";
181 if (-e $index && !$ENV{FAST}) {
182 my $env = { GIT_INDEX_FILE => $index };
183 run_die([@cmd, qw(read-tree -m -v -i), $self->{ref}], $env);
185 eval { run_die([@cmd, 'update-server-info']) };
186 my $ibx = $self->{ibx};
187 if ($ibx && $ibx->version == 1 && -d "$ibx->{inboxdir}/public-inbox" &&
188 eval { require PublicInbox::SearchIdx }) {
190 my $s = PublicInbox::SearchIdx->new($ibx);
191 $s->index_sync({ ref => $self->{ref} });
193 warn "$ibx->{inboxdir} index failed: $@\n" if $@;
195 eval { run_die([@cmd, qw(gc --auto)]) } if $do_gc;
201 # For safety, we ensure git checkpoint is complete before because
202 # the data in git is still more important than what is in Xapian
203 # in v2. Performance may be gained by delaying the ->progress
204 # call but we lose safety
207 $self->progress('checkpoint');
208 _update_git_info($self, 0);
215 my ($self, $mark) = @_;
216 die "not active\n" unless $self->{in};
217 my ($r, $w) = $self->gfi_start;
218 print $w "get-mark $mark\n" or wfail;
219 my $oid = <$r> // die "get-mark failed, need git 2.6.0+\n";
224 # returns undef on non-existent
225 # ('MISMATCH', PublicInbox::Eml) on mismatch
226 # (:MARK, PublicInbox::Eml) on success
228 # v2 callers should check with Xapian before calling this as
229 # it is not idempotent.
231 my ($self, $mime, $msg) = @_; # mime = PublicInbox::Eml or Email::MIME
233 my $path_type = $self->{path_type};
234 my ($path, $err, $cur, $blob);
236 my ($r, $w) = $self->gfi_start;
237 my $tip = $self->{tip};
238 if ($path_type eq '2/38') {
239 $path = mid2path(v1_mid0($mime));
240 ($err, $cur) = check_remove_v1($r, $w, $tip, $path, $mime);
241 return ($err, $cur) if $err;
244 if (ref($mime) eq 'SCALAR') { # optimization used by V2Writable
246 } else { # XXX should not be necessary:
247 my $str = $mime->as_string;
250 my $len = length($$sref);
251 $blob = $self->{mark}++;
252 print $w "blob\nmark :$blob\ndata $len\n",
253 $$sref, "\n" or wfail;
256 my $ref = $self->{ref};
257 my $commit = $self->{mark}++;
258 my $parent = $tip =~ /\A:/ ? $tip : undef;
260 print $w "reset $ref\n" or wfail;
262 my $ident = $self->{ident};
265 my $len = length($msg) + 1;
266 print $w "commit $ref\nmark :$commit\n",
267 "author $ident $now\n",
268 "committer $ident $now\n",
269 "data $len\n$msg\n\n",
270 'from ', ($parent ? $parent : $tip), "\n" or wfail;
272 print $w "D $path\n\n" or wfail;
274 clean_tree_v2($self, $w, 'd');
275 print $w "M 100644 :$blob d\n\n" or wfail;
278 (($self->{tip} = ":$commit"), $cur);
281 sub git_timestamp ($) {
282 my ($ts, $zone) = @{$_[0]};
283 $ts = 0 if $ts < 0; # git uses unsigned times
287 sub extract_cmt_info ($;$) {
288 my ($mime, $smsg) = @_;
289 # $mime is PublicInbox::Eml, but remains Email::MIME-compatible
290 $smsg //= bless {}, 'PublicInbox::Smsg';
292 $smsg->populate($mime);
295 my $from = delete($smsg->{From}) // '';
296 my ($email) = PublicInbox::Address::emails($from);
297 my ($name) = PublicInbox::Address::names($from);
298 if (!defined($name) || !defined($email)) {
299 $sender = $mime->header('Sender') // '';
300 $name //= (PublicInbox::Address::names($sender))[0];
301 $email //= (PublicInbox::Address::emails($sender))[0];
303 if (defined $email) {
304 # Email::Address::XS may leave quoted '<' in addresses,
305 # which git-fast-import doesn't like
308 # quiet down wide character warnings with utf8::encode
309 utf8::encode($email);
312 warn "no email in From: $from or Sender: $sender\n";
315 # git gets confused with:
316 # "'A U Thor <u@example.com>' via foo" <foo@example.com>
318 # <CAD0k6qSUYANxbjjbE4jTW4EeVwOYgBD=bXkSu=akiYC_CB7Ffw@mail.gmail.com>
324 warn "no name in From: $from or Sender: $sender\n";
327 my $subject = delete($smsg->{Subject}) // '(no subject)';
328 utf8::encode($subject);
329 my $at = git_timestamp(delete $smsg->{-ds});
330 my $ct = git_timestamp(delete $smsg->{-ts});
331 ("$name <$email>", $at, $ct, $subject);
334 # kill potentially confusing/misleading headers
335 our @UNWANTED_HEADERS = (qw(Bytes Lines Content-Length),
336 qw(Status X-Status));
337 sub drop_unwanted_headers ($) {
339 for (@UNWANTED_HEADERS, @PublicInbox::MDA::BAD_HEADERS) {
340 $eml->header_set($_);
344 # used by V2Writable, too
345 sub append_mid ($$) {
346 my ($hdr, $mid0) = @_;
347 # @cur is likely empty if we need to call this sub, but it could
348 # have random unparseable crap which we'll preserve, too.
349 my @cur = $hdr->header_raw('Message-ID');
350 $hdr->header_set('Message-ID', @cur, "<$mid0>");
355 my $mids = mids($eml);
357 if (!scalar(@$mids)) { # spam often has no Message-ID
358 my $mid0 = digest2mid(content_digest($eml), $eml);
359 append_mid($eml, $mid0);
364 sub clean_tree_v2 ($$$) {
365 my ($self, $w, $keep) = @_;
366 my $tree = $self->{-tree} or return; #v2 only
367 delete $tree->{$keep};
368 foreach (keys %$tree) {
369 print $w "D $_\n" or wfail;
371 %$tree = ($keep => 1);
374 # returns undef on duplicate
375 # returns the :MARK of the most recent commit
377 my ($self, $mime, $check_cb, $smsg) = @_;
379 my ($author, $at, $ct, $subject) = extract_cmt_info($mime, $smsg);
380 my $path_type = $self->{path_type};
382 if ($path_type eq '2/38') {
383 $path = mid2path(v1_mid0($mime));
384 } else { # v2 layout, one file:
388 my ($r, $w) = $self->gfi_start;
389 my $tip = $self->{tip};
390 if ($path_type eq '2/38') {
391 _check_path($r, $w, $tip, $path) and return;
394 drop_unwanted_headers($mime);
398 $mime = $check_cb->($mime, $self->{ibx}) or return;
401 my $blob = $self->{mark}++;
402 my $raw_email = $mime->{-public_inbox_raw} // $mime->as_string;
403 my $n = length($raw_email);
404 $self->{bytes_added} += $n;
405 print $w "blob\nmark :$blob\ndata ", $n, "\n" or wfail;
406 print $w $raw_email, "\n" or wfail;
408 # v2: we need this for Xapian
410 $smsg->{blob} = $self->get_mark(":$blob");
411 $smsg->set_bytes($raw_email, $n);
412 if (my $oidx = delete $smsg->{-oidx}) { # used by LeiStore
413 my $eidx_git = delete $smsg->{-eidx_git};
415 # we need this sharedkv to dedupe blobs added in the
416 # same fast-import transaction
417 my $u = $self->{uniq_skv} //= do {
418 require PublicInbox::SharedKV;
419 my $x = PublicInbox::SharedKV->new;
423 return if !$u->set_maybe($smsg->oidbin, 1);
424 return if (!$oidx->vivify_xvmd($smsg) &&
425 $eidx_git->check($smsg->{blob}));
428 my $ref = $self->{ref};
429 my $commit = $self->{mark}++;
430 my $parent = $tip =~ /\A:/ ? $tip : undef;
433 print $w "reset $ref\n" or wfail;
436 print $w "commit $ref\nmark :$commit\n",
437 "author $author $at\n",
438 "committer $self->{ident} $ct\n" or wfail;
439 print $w "data ", (length($subject) + 1), "\n",
440 $subject, "\n\n" or wfail;
442 print $w 'from ', ($parent ? $parent : $tip), "\n" or wfail;
444 clean_tree_v2($self, $w, $path);
445 print $w "M 100644 :$blob $path\n\n" or wfail;
447 $self->{tip} = ":$commit";
450 my @INIT_FILES = ('HEAD' => undef, # filled in at runtime
453 repositoryFormatVersion = 0
461 my ($dir, $head) = @_; # or self
462 $dir = $dir->{git}->{git_dir} if ref($dir);
464 File::Path::mkpath([ map { "$dir/$_" } qw(objects/info refs/heads) ]);
465 $INIT_FILES[1] //= 'ref: '.default_branch."\n";
466 my @fn_contents = @INIT_FILES;
467 $fn_contents[1] = "ref: refs/heads/$head\n" if defined $head;
468 while (my ($fn, $contents) = splice(@fn_contents, 0, 2)) {
469 my $f = $dir.'/'.$fn;
471 open my $fh, '>', $f or die "open $f: $!";
472 print $fh $contents or die "print $f: $!";
473 close $fh or die "close $f: $!";
477 # true if locked and active
478 sub active { !!$_[0]->{out} }
482 my $w = delete $self->{out} or return;
484 my $r = delete $self->{in} or die 'BUG: missing {in} when done';
485 print $w "done\n" or wfail;
486 close $r or die "fast-import failed: $?"; # ProcessPipe::CLOSE
489 my $nchg = delete $self->{nchg};
490 if ($nchg && !$wait_err) {
491 eval { _update_git_info($self, 1) };
492 warn "E: $self->{git}->{git_dir} update info: $@\n" if $@;
494 $self->lock_release(!!$nchg);
495 $self->{git}->cleanup;
496 die $wait_err if $wait_err;
501 foreach my $f (qw(in out)) {
502 next unless defined($self->{$f});
503 close $self->{$f} or die "failed to close import[$f]: $!\n";
507 sub digest2mid ($$;$) {
508 my ($dig, $hdr, $fallback_time) = @_;
509 my $b64 = $dig->clone->b64digest;
510 # Make our own URLs nicer:
511 # See "Base 64 Encoding with URL and Filename Safe Alphabet" in RFC4648
514 # Add a date prefix to prevent a leading '-' in case that trips
515 # up some tools (e.g. if a Message-ID were a expected as a
517 my $dt = msg_datestamp($hdr, $fallback_time);
518 $dt = POSIX::strftime('%Y%m%d%H%M%S', gmtime($dt));
522 sub rewrite_commit ($$$$) {
523 my ($self, $oids, $buf, $mime) = @_;
524 my ($author, $at, $ct, $subject);
526 ($author, $at, $ct, $subject) = extract_cmt_info($mime);
529 $subject = 'purged '.join(' ', @$oids);
533 foreach my $i (0..$#$buf) {
535 if ($l =~ /^author .* ([0-9]+ [\+-]?[0-9]+)$/) {
537 $buf->[$i] = "author $author $at\n";
538 } elsif ($l =~ /^committer .* ([0-9]+ [\+-]?[0-9]+)$/) {
540 $buf->[$i] = "committer $self->{ident} $ct\n";
541 } elsif ($l =~ /^data ([0-9]+)/) {
542 $buf->[$i++] = "data " . length($subject) . "\n";
543 $buf->[$i] = $subject;
549 # returns the new commit OID if a replacement was done
550 # returns undef if nothing was done
552 my ($self, $mime, $replace_map) = @_; # oid => raw string
553 my $tmp = "refs/heads/replace-".((keys %$replace_map)[0]);
554 my $old = $self->{'ref'};
555 my $git = $self->{git};
556 my @export = (qw(fast-export --no-data --use-done-feature), $old);
557 my $rd = $git->popen(@export);
558 my ($r, $w) = $self->gfi_start;
563 my $tree = $self->{-tree};
565 if (/^reset (?:.+)/) {
566 push @buf, "reset $tmp\n";
567 } elsif (/^commit (?:.+)/) {
569 print $w @buf or wfail;
572 push @buf, "commit $tmp\n";
573 } elsif (/^data ([0-9]+)/) {
574 # only commit message, so $len is small:
575 my $len = $1; # + 1 for trailing "\n"
577 my $n = read($rd, my $buf, $len) or die "read: $!";
578 $len == $n or die "short read ($n < $len)";
580 } elsif (/^M 100644 ([a-f0-9]+) (\w+)/) {
581 my ($oid, $path) = ($1, $2);
583 my $sref = $replace_map->{$oid};
586 my $n = length($$sref);
587 push @buf, "M 100644 inline $path\ndata $n\n";
588 push @buf, $$sref; # hope CoW works...
593 } elsif (/^D (\w+)/) {
595 push @buf, $_ if $tree->{$path};
596 } elsif ($_ eq "\n") {
599 my $out = join('', @buf);
601 warn "purge rewriting\n", $out, "\n";
603 rewrite_commit($self, \@oids, \@buf, $mime);
606 print $w @buf, "\n" or wfail;
608 } elsif ($_ eq "done\n") {
610 } elsif (/^mark :([0-9]+)$/) {
617 close $rd or die "close fast-export failed: $?";
619 print $w @buf or wfail;
621 die 'done\n not seen from fast-export' unless $done;
622 chomp(my $cmt = $self->get_mark(":$mark")) if $nreplace;
623 $self->{nchg} = 0; # prevent _update_git_info until update-ref:
625 my @git = ('git', "--git-dir=$git->{git_dir}");
627 run_die([@git, qw(update-ref), $old, $tmp]) if $nreplace;
629 run_die([@git, qw(update-ref -d), $tmp]);
631 return if $nreplace == 0;
633 run_die([@git, qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
635 # check that old OIDs are gone
637 foreach my $oid (keys %$replace_map) {
638 my @info = $git->check($oid);
640 warn "$oid not replaced\n";
644 _update_git_info($self, 0);
645 die "Failed to replace $err object(s)\n" if $err;
655 PublicInbox::Import - message importer for public-inbox v1 inboxes
663 use PublicInbox::Eml;
664 # PublicInbox::Eml exists as of public-inbox 1.5.0,
665 # Email::MIME was used in older versions
667 use PublicInbox::Git;
668 use PublicInbox::Import;
670 chomp(my $git_dir = `git rev-parse --git-dir`);
671 $git_dir or die "GIT_DIR= must be specified\n";
672 my $git = PublicInbox::Git->new($git_dir);
673 my @committer = ('inbox', 'inbox@example.org');
674 my $im = PublicInbox::Import->new($git, @committer);
677 my $message = "From: <u\@example.org>\n".
678 "Subject: test message \n" .
679 "Date: Thu, 01 Jan 1970 00:00:00 +0000\n" .
680 "Message-ID: <m\@example.org>\n".
682 my $parsed = PublicInbox::Eml->new($message);
683 my $ret = $im->add($parsed);
685 warn "duplicate: ", $parsed->header_raw('Message-ID'), "\n";
687 print "imported at mark $ret\n";
691 # to remove a message
692 my $junk = PublicInbox::Eml->new($message);
693 my ($mark, $orig) = $im->remove($junk);
694 if ($mark eq 'MISSING') {
696 } elsif ($mark eq 'MISMATCH') {
697 print "Message exists but does not match\n\n",
698 $orig->as_string, "\n",;
700 print "removed at mark $mark\n\n",
701 $orig->as_string, "\n";
707 An importer and remover for public-inboxes which takes C<PublicInbox::Eml>
708 or L<Email::MIME> messages as input and stores them in a git repository as
709 documented in L<https://public-inbox.org/public-inbox-v1-format.txt>,
710 except it does not allow duplicate Message-IDs.
712 It requires L<git(1)> and L<git-fast-import(1)> to be installed.
720 my $im = PublicInbox::Import->new($git, @committer);
722 Initialize a new PublicInbox::Import object.
726 my $parsed = PublicInbox::Eml->new($message);
729 Adds a message to to the git repository. This will acquire
730 C<$GIT_DIR/ssoma.lock> and start L<git-fast-import(1)> if necessary.
732 Messages added will not be visible to other processes until L</done>
733 is called, but L</remove> may be called on them.
737 my $junk = PublicInbox::Eml->new($message);
738 my ($code, $orig) = $im->remove($junk);
740 Removes a message from the repository. On success, it returns
741 a ':'-prefixed numeric code representing the git-fast-import
742 mark and the original messages as a PublicInbox::Eml
743 (or Email::MIME) object.
744 If the message could not be found, the code is "MISSING"
745 and the original message is undef. If there is a mismatch where
746 the "Message-ID" is matched but the subject and body do not match,
747 the returned code is "MISMATCH" and the conflicting message
752 Finalizes the L<git-fast-import(1)> and unlocks the repository.
753 Calling this is required to finalize changes to a repository.
761 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
763 The mail archives are hosted at L<https://public-inbox.org/meta/>
767 Copyright (C) 2016-2020 all contributors L<mailto:meta@public-inbox.org>
769 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>