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 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 defined(my $info = <$r>) or 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;
115 defined $info or die "EOF from fast-import / cat-blob: $!";
116 $info =~ /\A[a-f0-9]{40,} blob ([0-9]+)\n\z/ or return;
122 $n = read($r, $buf, $left, $offset);
123 defined($n) or die "read cat-blob failed: $!";
124 $n == 0 and die 'fast-export (cat-blob) died';
128 $n = read($r, my $lf, 1);
129 defined($n) or die "read final byte of cat-blob failed: $!";
130 die "bad read on final byte: <$lf>" if $lf ne "\n";
132 # fixup some bugginess in old versions:
133 $buf =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
138 my ($self, $oid) = @_;
139 my ($r, $w) = $self->gfi_start;
140 _cat_blob($r, $w, $oid);
143 sub check_remove_v1 {
144 my ($r, $w, $tip, $path, $mime) = @_;
146 my $info = _check_path($r, $w, $tip, $path) or return ('MISSING',undef);
147 $info =~ m!\A100644 blob ([a-f0-9]{40,})\t!s or die "not blob: $info";
149 my $msg = _cat_blob($r, $w, $oid) or die "BUG: cat-blob $1 failed";
150 my $cur = PublicInbox::Eml->new($msg);
151 my $cur_s = $cur->header('Subject');
152 $cur_s = '' unless defined $cur_s;
153 my $cur_m = $mime->header('Subject');
154 $cur_m = '' unless defined $cur_m;
155 if ($cur_s ne $cur_m || norm_body($cur) ne norm_body($mime)) {
156 return ('MISMATCH', $cur);
163 return unless $self->{in};
164 print { $self->{out} } "checkpoint\n" or wfail;
169 my ($self, $msg) = @_;
170 return unless $self->{in};
171 print { $self->{out} } "progress $msg\n" or wfail;
172 readline($self->{in}) eq "progress $msg\n" or die
173 "progress $msg not received\n";
177 sub _update_git_info ($$) {
178 my ($self, $do_gc) = @_;
179 # for compatibility with existing ssoma installations
180 # we can probably remove this entirely by 2020
181 my $git_dir = $self->{git}->{git_dir};
182 my @cmd = ('git', "--git-dir=$git_dir");
183 my $index = "$git_dir/ssoma.index";
184 if (-e $index && !$ENV{FAST}) {
185 my $env = { GIT_INDEX_FILE => $index };
186 run_die([@cmd, qw(read-tree -m -v -i), $self->{ref}], $env);
188 eval { run_die([@cmd, 'update-server-info']) };
189 my $ibx = $self->{ibx};
190 if ($ibx && $ibx->version == 1 && -d "$ibx->{inboxdir}/public-inbox" &&
191 eval { require PublicInbox::SearchIdx }) {
193 my $s = PublicInbox::SearchIdx->new($ibx);
194 $s->index_sync({ ref => $self->{ref} });
196 warn "$ibx->{inboxdir} index failed: $@\n" if $@;
198 eval { run_die([@cmd, qw(gc --auto)]) } if $do_gc;
204 # For safety, we ensure git checkpoint is complete before because
205 # the data in git is still more important than what is in Xapian
206 # in v2. Performance may be gained by delaying the ->progress
207 # call but we lose safety
210 $self->progress('checkpoint');
211 _update_git_info($self, 0);
218 my ($self, $mark) = @_;
219 die "not active\n" unless $self->{in};
220 my ($r, $w) = $self->gfi_start;
221 print $w "get-mark $mark\n" or wfail;
222 defined(my $oid = <$r>) or die "get-mark failed, need git 2.6.0+\n";
227 # returns undef on non-existent
228 # ('MISMATCH', PublicInbox::Eml) on mismatch
229 # (:MARK, PublicInbox::Eml) on success
231 # v2 callers should check with Xapian before calling this as
232 # it is not idempotent.
234 my ($self, $mime, $msg) = @_; # mime = PublicInbox::Eml or Email::MIME
236 my $path_type = $self->{path_type};
237 my ($path, $err, $cur, $blob);
239 my ($r, $w) = $self->gfi_start;
240 my $tip = $self->{tip};
241 if ($path_type eq '2/38') {
242 $path = mid2path(v1_mid0($mime));
243 ($err, $cur) = check_remove_v1($r, $w, $tip, $path, $mime);
244 return ($err, $cur) if $err;
247 if (ref($mime) eq 'SCALAR') { # optimization used by V2Writable
249 } else { # XXX should not be necessary:
250 my $str = $mime->as_string;
253 my $len = length($$sref);
254 $blob = $self->{mark}++;
255 print $w "blob\nmark :$blob\ndata $len\n",
256 $$sref, "\n" or wfail;
259 my $ref = $self->{ref};
260 my $commit = $self->{mark}++;
261 my $parent = $tip =~ /\A:/ ? $tip : undef;
263 print $w "reset $ref\n" or wfail;
265 my $ident = $self->{ident};
268 my $len = length($msg) + 1;
269 print $w "commit $ref\nmark :$commit\n",
270 "author $ident $now\n",
271 "committer $ident $now\n",
272 "data $len\n$msg\n\n",
273 'from ', ($parent ? $parent : $tip), "\n" or wfail;
275 print $w "D $path\n\n" or wfail;
277 clean_tree_v2($self, $w, 'd');
278 print $w "M 100644 :$blob d\n\n" or wfail;
281 (($self->{tip} = ":$commit"), $cur);
284 sub git_timestamp ($) {
285 my ($ts, $zone) = @{$_[0]};
286 $ts = 0 if $ts < 0; # git uses unsigned times
290 sub extract_cmt_info ($;$) {
291 my ($mime, $smsg) = @_;
292 # $mime is PublicInbox::Eml, but remains Email::MIME-compatible
293 $smsg //= bless {}, 'PublicInbox::Smsg';
295 $smsg->populate($mime);
298 my $from = delete($smsg->{From}) // '';
299 my ($email) = PublicInbox::Address::emails($from);
300 my ($name) = PublicInbox::Address::names($from);
301 if (!defined($name) || !defined($email)) {
302 $sender = $mime->header('Sender') // '';
303 $name //= (PublicInbox::Address::names($sender))[0];
304 $email //= (PublicInbox::Address::emails($sender))[0];
306 if (defined $email) {
307 # Email::Address::XS may leave quoted '<' in addresses,
308 # which git-fast-import doesn't like
311 # quiet down wide character warnings with utf8::encode
312 utf8::encode($email);
315 warn "no email in From: $from or Sender: $sender\n";
318 # git gets confused with:
319 # "'A U Thor <u@example.com>' via foo" <foo@example.com>
321 # <CAD0k6qSUYANxbjjbE4jTW4EeVwOYgBD=bXkSu=akiYC_CB7Ffw@mail.gmail.com>
327 warn "no name in From: $from or Sender: $sender\n";
330 my $subject = delete($smsg->{Subject}) // '(no subject)';
331 utf8::encode($subject);
332 my $at = git_timestamp(delete $smsg->{-ds});
333 my $ct = git_timestamp(delete $smsg->{-ts});
334 ("$name <$email>", $at, $ct, $subject);
337 # kill potentially confusing/misleading headers
338 our @UNWANTED_HEADERS = (qw(Bytes Lines Content-Length),
339 qw(Status X-Status));
340 sub drop_unwanted_headers ($) {
342 for (@UNWANTED_HEADERS, @PublicInbox::MDA::BAD_HEADERS) {
343 $eml->header_set($_);
347 # used by V2Writable, too
348 sub append_mid ($$) {
349 my ($hdr, $mid0) = @_;
350 # @cur is likely empty if we need to call this sub, but it could
351 # have random unparseable crap which we'll preserve, too.
352 my @cur = $hdr->header_raw('Message-ID');
353 $hdr->header_set('Message-ID', @cur, "<$mid0>");
358 my $mids = mids($eml);
360 if (!scalar(@$mids)) { # spam often has no Message-ID
361 my $mid0 = digest2mid(content_digest($eml), $eml);
362 append_mid($eml, $mid0);
367 sub clean_tree_v2 ($$$) {
368 my ($self, $w, $keep) = @_;
369 my $tree = $self->{-tree} or return; #v2 only
370 delete $tree->{$keep};
371 foreach (keys %$tree) {
372 print $w "D $_\n" or wfail;
374 %$tree = ($keep => 1);
377 # returns undef on duplicate
378 # returns the :MARK of the most recent commit
380 my ($self, $mime, $check_cb, $smsg) = @_;
382 my ($author, $at, $ct, $subject) = extract_cmt_info($mime, $smsg);
383 my $path_type = $self->{path_type};
385 if ($path_type eq '2/38') {
386 $path = mid2path(v1_mid0($mime));
387 } else { # v2 layout, one file:
391 my ($r, $w) = $self->gfi_start;
392 my $tip = $self->{tip};
393 if ($path_type eq '2/38') {
394 _check_path($r, $w, $tip, $path) and return;
397 drop_unwanted_headers($mime);
401 $mime = $check_cb->($mime, $self->{ibx}) or return;
404 my $blob = $self->{mark}++;
405 my $raw_email = $mime->{-public_inbox_raw} // $mime->as_string;
406 my $n = length($raw_email);
407 $self->{bytes_added} += $n;
408 print $w "blob\nmark :$blob\ndata ", $n, "\n" or wfail;
409 print $w $raw_email, "\n" or wfail;
411 # v2: we need this for Xapian
413 $smsg->{blob} = $self->get_mark(":$blob");
414 $smsg->set_bytes($raw_email, $n);
415 if (my $oidx = delete $smsg->{-oidx}) { # used by LeiStore
416 my $eidx_git = delete $smsg->{-eidx_git};
418 # we need this sharedkv to dedupe blobs added in the
419 # same fast-import transaction
420 my $u = $self->{uniq_skv} //= do {
421 require PublicInbox::SharedKV;
422 my $x = PublicInbox::SharedKV->new;
426 return if !$u->set_maybe($smsg->oidbin, 1);
427 return if (!$oidx->vivify_xvmd($smsg) &&
428 $eidx_git->check($smsg->{blob}));
431 my $ref = $self->{ref};
432 my $commit = $self->{mark}++;
433 my $parent = $tip =~ /\A:/ ? $tip : undef;
436 print $w "reset $ref\n" or wfail;
439 print $w "commit $ref\nmark :$commit\n",
440 "author $author $at\n",
441 "committer $self->{ident} $ct\n" or wfail;
442 print $w "data ", (length($subject) + 1), "\n",
443 $subject, "\n\n" or wfail;
445 print $w 'from ', ($parent ? $parent : $tip), "\n" or wfail;
447 clean_tree_v2($self, $w, $path);
448 print $w "M 100644 :$blob $path\n\n" or wfail;
450 $self->{tip} = ":$commit";
453 my @INIT_FILES = ('HEAD' => undef, # filled in at runtime
456 repositoryFormatVersion = 0
464 my ($dir, $head) = @_; # or self
465 $dir = $dir->{git}->{git_dir} if ref($dir);
467 File::Path::mkpath([ map { "$dir/$_" } qw(objects/info refs/heads) ]);
468 $INIT_FILES[1] //= 'ref: '.default_branch."\n";
469 my @fn_contents = @INIT_FILES;
470 $fn_contents[1] = "ref: refs/heads/$head\n" if defined $head;
471 while (my ($fn, $contents) = splice(@fn_contents, 0, 2)) {
472 my $f = $dir.'/'.$fn;
474 open my $fh, '>', $f or die "open $f: $!";
475 print $fh $contents or die "print $f: $!";
476 close $fh or die "close $f: $!";
480 # true if locked and active
481 sub active { !!$_[0]->{out} }
485 my $w = delete $self->{out} or return;
487 my $r = delete $self->{in} or die 'BUG: missing {in} when done';
488 print $w "done\n" or wfail;
489 close $r or die "fast-import failed: $?"; # ProcessPipe::CLOSE
492 my $nchg = delete $self->{nchg};
493 if ($nchg && !$wait_err) {
494 eval { _update_git_info($self, 1) };
495 warn "E: $self->{git}->{git_dir} update info: $@\n" if $@;
497 $self->lock_release(!!$nchg);
498 $self->{git}->cleanup;
499 die $wait_err if $wait_err;
504 foreach my $f (qw(in out)) {
505 next unless defined($self->{$f});
506 close $self->{$f} or die "failed to close import[$f]: $!\n";
510 sub digest2mid ($$;$) {
511 my ($dig, $hdr, $fallback_time) = @_;
512 my $b64 = $dig->clone->b64digest;
513 # Make our own URLs nicer:
514 # See "Base 64 Encoding with URL and Filename Safe Alphabet" in RFC4648
517 # Add a date prefix to prevent a leading '-' in case that trips
518 # up some tools (e.g. if a Message-ID were a expected as a
520 my $dt = msg_datestamp($hdr, $fallback_time);
521 $dt = POSIX::strftime('%Y%m%d%H%M%S', gmtime($dt));
525 sub rewrite_commit ($$$$) {
526 my ($self, $oids, $buf, $mime) = @_;
527 my ($author, $at, $ct, $subject);
529 ($author, $at, $ct, $subject) = extract_cmt_info($mime);
532 $subject = 'purged '.join(' ', @$oids);
536 foreach my $i (0..$#$buf) {
538 if ($l =~ /^author .* ([0-9]+ [\+-]?[0-9]+)$/) {
540 $buf->[$i] = "author $author $at\n";
541 } elsif ($l =~ /^committer .* ([0-9]+ [\+-]?[0-9]+)$/) {
543 $buf->[$i] = "committer $self->{ident} $ct\n";
544 } elsif ($l =~ /^data ([0-9]+)/) {
545 $buf->[$i++] = "data " . length($subject) . "\n";
546 $buf->[$i] = $subject;
552 # returns the new commit OID if a replacement was done
553 # returns undef if nothing was done
555 my ($self, $mime, $replace_map) = @_; # oid => raw string
556 my $tmp = "refs/heads/replace-".((keys %$replace_map)[0]);
557 my $old = $self->{'ref'};
558 my $git = $self->{git};
559 my @export = (qw(fast-export --no-data --use-done-feature), $old);
560 my $rd = $git->popen(@export);
561 my ($r, $w) = $self->gfi_start;
566 my $tree = $self->{-tree};
568 if (/^reset (?:.+)/) {
569 push @buf, "reset $tmp\n";
570 } elsif (/^commit (?:.+)/) {
572 print $w @buf or wfail;
575 push @buf, "commit $tmp\n";
576 } elsif (/^data ([0-9]+)/) {
577 # only commit message, so $len is small:
578 my $len = $1; # + 1 for trailing "\n"
580 my $n = read($rd, my $buf, $len) or die "read: $!";
581 $len == $n or die "short read ($n < $len)";
583 } elsif (/^M 100644 ([a-f0-9]+) (\w+)/) {
584 my ($oid, $path) = ($1, $2);
586 my $sref = $replace_map->{$oid};
589 my $n = length($$sref);
590 push @buf, "M 100644 inline $path\ndata $n\n";
591 push @buf, $$sref; # hope CoW works...
596 } elsif (/^D (\w+)/) {
598 push @buf, $_ if $tree->{$path};
599 } elsif ($_ eq "\n") {
602 my $out = join('', @buf);
604 warn "purge rewriting\n", $out, "\n";
606 rewrite_commit($self, \@oids, \@buf, $mime);
609 print $w @buf, "\n" or wfail;
611 } elsif ($_ eq "done\n") {
613 } elsif (/^mark :([0-9]+)$/) {
620 close $rd or die "close fast-export failed: $?";
622 print $w @buf or wfail;
624 die 'done\n not seen from fast-export' unless $done;
625 chomp(my $cmt = $self->get_mark(":$mark")) if $nreplace;
626 $self->{nchg} = 0; # prevent _update_git_info until update-ref:
628 my @git = ('git', "--git-dir=$git->{git_dir}");
630 run_die([@git, qw(update-ref), $old, $tmp]) if $nreplace;
632 run_die([@git, qw(update-ref -d), $tmp]);
634 return if $nreplace == 0;
636 run_die([@git, qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
638 # check that old OIDs are gone
640 foreach my $oid (keys %$replace_map) {
641 my @info = $git->check($oid);
643 warn "$oid not replaced\n";
647 _update_git_info($self, 0);
648 die "Failed to replace $err object(s)\n" if $err;
658 PublicInbox::Import - message importer for public-inbox v1 inboxes
666 use PublicInbox::Eml;
667 # PublicInbox::Eml exists as of public-inbox 1.5.0,
668 # Email::MIME was used in older versions
670 use PublicInbox::Git;
671 use PublicInbox::Import;
673 chomp(my $git_dir = `git rev-parse --git-dir`);
674 $git_dir or die "GIT_DIR= must be specified\n";
675 my $git = PublicInbox::Git->new($git_dir);
676 my @committer = ('inbox', 'inbox@example.org');
677 my $im = PublicInbox::Import->new($git, @committer);
680 my $message = "From: <u\@example.org>\n".
681 "Subject: test message \n" .
682 "Date: Thu, 01 Jan 1970 00:00:00 +0000\n" .
683 "Message-ID: <m\@example.org>\n".
685 my $parsed = PublicInbox::Eml->new($message);
686 my $ret = $im->add($parsed);
688 warn "duplicate: ", $parsed->header_raw('Message-ID'), "\n";
690 print "imported at mark $ret\n";
694 # to remove a message
695 my $junk = PublicInbox::Eml->new($message);
696 my ($mark, $orig) = $im->remove($junk);
697 if ($mark eq 'MISSING') {
699 } elsif ($mark eq 'MISMATCH') {
700 print "Message exists but does not match\n\n",
701 $orig->as_string, "\n",;
703 print "removed at mark $mark\n\n",
704 $orig->as_string, "\n";
710 An importer and remover for public-inboxes which takes C<PublicInbox::Eml>
711 or L<Email::MIME> messages as input and stores them in a git repository as
712 documented in L<https://public-inbox.org/public-inbox-v1-format.txt>,
713 except it does not allow duplicate Message-IDs.
715 It requires L<git(1)> and L<git-fast-import(1)> to be installed.
723 my $im = PublicInbox::Import->new($git, @committer);
725 Initialize a new PublicInbox::Import object.
729 my $parsed = PublicInbox::Eml->new($message);
732 Adds a message to to the git repository. This will acquire
733 C<$GIT_DIR/ssoma.lock> and start L<git-fast-import(1)> if necessary.
735 Messages added will not be visible to other processes until L</done>
736 is called, but L</remove> may be called on them.
740 my $junk = PublicInbox::Eml->new($message);
741 my ($code, $orig) = $im->remove($junk);
743 Removes a message from the repository. On success, it returns
744 a ':'-prefixed numeric code representing the git-fast-import
745 mark and the original messages as a PublicInbox::Eml
746 (or Email::MIME) object.
747 If the message could not be found, the code is "MISSING"
748 and the original message is undef. If there is a mismatch where
749 the "Message-ID" is matched but the subject and body do not match,
750 the returned code is "MISMATCH" and the conflicting message
755 Finalizes the L<git-fast-import(1)> and unlocks the repository.
756 Calling this is required to finalize changes to a repository.
764 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
766 The mail archives are hosted at L<https://public-inbox.org/meta/>
770 Copyright (C) 2016-2020 all contributors L<mailto:meta@public-inbox.org>
772 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>