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->{in};
60 my ($in_r, $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 $in_r = $self->{in} = $git->popen(qw(fast-import
77 --quiet --done --date-format=raw),
78 undef, { 0 => $out_r });
80 $self->{out} = $out_w;
90 sub wfail () { die "write to fast-import failed: $!" }
92 sub now_raw () { time . ' +0000' }
96 my $b = $mime->body_raw;
97 $b =~ s/(\r?\n)+\z//s;
101 # only used for v1 (ssoma) inboxes
102 sub _check_path ($$$$) {
103 my ($r, $w, $tip, $path) = @_;
104 return if $tip eq '';
105 print $w "ls $tip $path\n" or wfail;
107 defined(my $info = <$r>) or die "EOF from fast-import: $!";
108 $info =~ /\Amissing / ? undef : $info;
111 sub _cat_blob ($$$) {
112 my ($r, $w, $oid) = @_;
113 print $w "cat-blob $oid\n" or wfail;
116 defined $info or die "EOF from fast-import / cat-blob: $!";
117 $info =~ /\A[a-f0-9]{40,} blob ([0-9]+)\n\z/ or return;
123 $n = read($r, $buf, $left, $offset);
124 defined($n) or die "read cat-blob failed: $!";
125 $n == 0 and die 'fast-export (cat-blob) died';
129 $n = read($r, my $lf, 1);
130 defined($n) or die "read final byte of cat-blob failed: $!";
131 die "bad read on final byte: <$lf>" if $lf ne "\n";
133 # fixup some bugginess in old versions:
134 $buf =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
139 my ($self, $oid) = @_;
140 my ($r, $w) = $self->gfi_start;
141 _cat_blob($r, $w, $oid);
144 sub check_remove_v1 {
145 my ($r, $w, $tip, $path, $mime) = @_;
147 my $info = _check_path($r, $w, $tip, $path) or return ('MISSING',undef);
148 $info =~ m!\A100644 blob ([a-f0-9]{40,})\t!s or die "not blob: $info";
150 my $msg = _cat_blob($r, $w, $oid) or die "BUG: cat-blob $1 failed";
151 my $cur = PublicInbox::Eml->new($msg);
152 my $cur_s = $cur->header('Subject');
153 $cur_s = '' unless defined $cur_s;
154 my $cur_m = $mime->header('Subject');
155 $cur_m = '' unless defined $cur_m;
156 if ($cur_s ne $cur_m || norm_body($cur) ne norm_body($mime)) {
157 return ('MISMATCH', $cur);
164 return unless $self->{in};
165 print { $self->{out} } "checkpoint\n" or wfail;
170 my ($self, $msg) = @_;
171 return unless $self->{in};
172 print { $self->{out} } "progress $msg\n" or wfail;
173 readline($self->{in}) eq "progress $msg\n" or die
174 "progress $msg not received\n";
178 sub _update_git_info ($$) {
179 my ($self, $do_gc) = @_;
180 # for compatibility with existing ssoma installations
181 # we can probably remove this entirely by 2020
182 my $git_dir = $self->{git}->{git_dir};
183 my @cmd = ('git', "--git-dir=$git_dir");
184 my $index = "$git_dir/ssoma.index";
185 if (-e $index && !$ENV{FAST}) {
186 my $env = { GIT_INDEX_FILE => $index };
187 run_die([@cmd, qw(read-tree -m -v -i), $self->{ref}], $env);
189 eval { run_die([@cmd, 'update-server-info']) };
190 my $ibx = $self->{ibx};
191 if ($ibx && $ibx->version == 1 && -d "$ibx->{inboxdir}/public-inbox" &&
192 eval { require PublicInbox::SearchIdx }) {
194 my $s = PublicInbox::SearchIdx->new($ibx);
195 $s->index_sync({ ref => $self->{ref} });
197 warn "$ibx->{inboxdir} index failed: $@\n" if $@;
199 eval { run_die([@cmd, qw(gc --auto)]) } if $do_gc;
205 # For safety, we ensure git checkpoint is complete before because
206 # the data in git is still more important than what is in Xapian
207 # in v2. Performance may be gained by delaying the ->progress
208 # call but we lose safety
211 $self->progress('checkpoint');
212 _update_git_info($self, 0);
219 my ($self, $mark) = @_;
220 die "not active\n" unless $self->{in};
221 my ($r, $w) = $self->gfi_start;
222 print $w "get-mark $mark\n" or wfail;
223 defined(my $oid = <$r>) or die "get-mark failed, need git 2.6.0+\n";
228 # returns undef on non-existent
229 # ('MISMATCH', PublicInbox::Eml) on mismatch
230 # (:MARK, PublicInbox::Eml) on success
232 # v2 callers should check with Xapian before calling this as
233 # it is not idempotent.
235 my ($self, $mime, $msg) = @_; # mime = PublicInbox::Eml or Email::MIME
237 my $path_type = $self->{path_type};
238 my ($path, $err, $cur, $blob);
240 my ($r, $w) = $self->gfi_start;
241 my $tip = $self->{tip};
242 if ($path_type eq '2/38') {
243 $path = mid2path(v1_mid0($mime));
244 ($err, $cur) = check_remove_v1($r, $w, $tip, $path, $mime);
245 return ($err, $cur) if $err;
248 if (ref($mime) eq 'SCALAR') { # optimization used by V2Writable
250 } else { # XXX should not be necessary:
251 my $str = $mime->as_string;
254 my $len = length($$sref);
255 $blob = $self->{mark}++;
256 print $w "blob\nmark :$blob\ndata $len\n",
257 $$sref, "\n" or wfail;
260 my $ref = $self->{ref};
261 my $commit = $self->{mark}++;
262 my $parent = $tip =~ /\A:/ ? $tip : undef;
264 print $w "reset $ref\n" or wfail;
266 my $ident = $self->{ident};
269 my $len = length($msg) + 1;
270 print $w "commit $ref\nmark :$commit\n",
271 "author $ident $now\n",
272 "committer $ident $now\n",
273 "data $len\n$msg\n\n",
274 'from ', ($parent ? $parent : $tip), "\n" or wfail;
276 print $w "D $path\n\n" or wfail;
278 clean_tree_v2($self, $w, 'd');
279 print $w "M 100644 :$blob d\n\n" or wfail;
282 (($self->{tip} = ":$commit"), $cur);
285 sub git_timestamp ($) {
286 my ($ts, $zone) = @{$_[0]};
287 $ts = 0 if $ts < 0; # git uses unsigned times
291 sub extract_cmt_info ($;$) {
292 my ($mime, $smsg) = @_;
293 # $mime is PublicInbox::Eml, but remains Email::MIME-compatible
294 $smsg //= bless {}, 'PublicInbox::Smsg';
296 $smsg->populate($mime);
299 my $from = delete($smsg->{From}) // '';
300 my ($email) = PublicInbox::Address::emails($from);
301 my ($name) = PublicInbox::Address::names($from);
302 if (!defined($name) || !defined($email)) {
303 $sender = $mime->header('Sender') // '';
304 $name //= (PublicInbox::Address::names($sender))[0];
305 $email //= (PublicInbox::Address::emails($sender))[0];
307 if (defined $email) {
308 # Email::Address::XS may leave quoted '<' in addresses,
309 # which git-fast-import doesn't like
312 # quiet down wide character warnings with utf8::encode
313 utf8::encode($email);
316 warn "no email in From: $from or Sender: $sender\n";
319 # git gets confused with:
320 # "'A U Thor <u@example.com>' via foo" <foo@example.com>
322 # <CAD0k6qSUYANxbjjbE4jTW4EeVwOYgBD=bXkSu=akiYC_CB7Ffw@mail.gmail.com>
328 warn "no name in From: $from or Sender: $sender\n";
331 my $subject = delete($smsg->{Subject}) // '(no subject)';
332 utf8::encode($subject);
333 my $at = git_timestamp(delete $smsg->{-ds});
334 my $ct = git_timestamp(delete $smsg->{-ts});
335 ("$name <$email>", $at, $ct, $subject);
338 # kill potentially confusing/misleading headers
339 our @UNWANTED_HEADERS = (qw(Bytes Lines Content-Length),
340 qw(Status X-Status));
341 sub drop_unwanted_headers ($) {
343 for (@UNWANTED_HEADERS, @PublicInbox::MDA::BAD_HEADERS) {
344 $eml->header_set($_);
348 # used by V2Writable, too
349 sub append_mid ($$) {
350 my ($hdr, $mid0) = @_;
351 # @cur is likely empty if we need to call this sub, but it could
352 # have random unparseable crap which we'll preserve, too.
353 my @cur = $hdr->header_raw('Message-ID');
354 $hdr->header_set('Message-ID', @cur, "<$mid0>");
359 my $mids = mids($eml);
361 if (!scalar(@$mids)) { # spam often has no Message-ID
362 my $mid0 = digest2mid(content_digest($eml), $eml);
363 append_mid($eml, $mid0);
368 sub clean_tree_v2 ($$$) {
369 my ($self, $w, $keep) = @_;
370 my $tree = $self->{-tree} or return; #v2 only
371 delete $tree->{$keep};
372 foreach (keys %$tree) {
373 print $w "D $_\n" or wfail;
375 %$tree = ($keep => 1);
378 # returns undef on duplicate
379 # returns the :MARK of the most recent commit
381 my ($self, $mime, $check_cb, $smsg) = @_;
383 my ($author, $at, $ct, $subject) = extract_cmt_info($mime, $smsg);
384 my $path_type = $self->{path_type};
386 if ($path_type eq '2/38') {
387 $path = mid2path(v1_mid0($mime));
388 } else { # v2 layout, one file:
392 my ($r, $w) = $self->gfi_start;
393 my $tip = $self->{tip};
394 if ($path_type eq '2/38') {
395 _check_path($r, $w, $tip, $path) and return;
398 drop_unwanted_headers($mime);
402 $mime = $check_cb->($mime, $self->{ibx}) or return;
405 my $blob = $self->{mark}++;
406 my $raw_email = $mime->{-public_inbox_raw} // $mime->as_string;
407 my $n = length($raw_email);
408 $self->{bytes_added} += $n;
409 print $w "blob\nmark :$blob\ndata ", $n, "\n" or wfail;
410 print $w $raw_email, "\n" or wfail;
412 # v2: we need this for Xapian
414 $smsg->{blob} = $self->get_mark(":$blob");
415 $smsg->set_bytes($raw_email, $n);
416 if (my $oidx = delete $smsg->{-oidx}) { # used by LeiStore
417 return if $oidx->blob_exists($smsg->{blob});
420 my $ref = $self->{ref};
421 my $commit = $self->{mark}++;
422 my $parent = $tip =~ /\A:/ ? $tip : undef;
425 print $w "reset $ref\n" or wfail;
428 print $w "commit $ref\nmark :$commit\n",
429 "author $author $at\n",
430 "committer $self->{ident} $ct\n" or wfail;
431 print $w "data ", (length($subject) + 1), "\n",
432 $subject, "\n\n" or wfail;
434 print $w 'from ', ($parent ? $parent : $tip), "\n" or wfail;
436 clean_tree_v2($self, $w, $path);
437 print $w "M 100644 :$blob $path\n\n" or wfail;
439 $self->{tip} = ":$commit";
442 my @INIT_FILES = ('HEAD' => undef, # filled in at runtime
443 'description' => <<EOD,
444 Unnamed repository; edit this file 'description' to name the repository.
448 repositoryFormatVersion = 0
456 my ($dir, $head) = @_; # or self
457 $dir = $dir->{git}->{git_dir} if ref($dir);
459 File::Path::mkpath([ map { "$dir/$_" } qw(objects/info refs/heads) ]);
460 $INIT_FILES[1] //= 'ref: '.default_branch."\n";
461 my @fn_contents = @INIT_FILES;
462 $fn_contents[1] = "ref: refs/heads/$head\n" if defined $head;
463 while (my ($fn, $contents) = splice(@fn_contents, 0, 2)) {
464 my $f = $dir.'/'.$fn;
466 open my $fh, '>', $f or die "open $f: $!";
467 print $fh $contents or die "print $f: $!";
468 close $fh or die "close $f: $!";
472 # true if locked and active
473 sub active { !!$_[0]->{out} }
477 my $w = delete $self->{out} or return;
479 my $r = delete $self->{in} or die 'BUG: missing {in} when done';
480 print $w "done\n" or wfail;
481 close $r or die "fast-import failed: $?"; # ProcessPipe::CLOSE
484 my $nchg = delete $self->{nchg};
485 if ($nchg && !$wait_err) {
486 eval { _update_git_info($self, 1) };
487 warn "E: $self->{git}->{git_dir} update info: $@\n" if $@;
489 $self->lock_release(!!$nchg);
490 $self->{git}->cleanup;
491 die $wait_err if $wait_err;
496 foreach my $f (qw(in out)) {
497 next unless defined($self->{$f});
498 close $self->{$f} or die "failed to close import[$f]: $!\n";
502 sub digest2mid ($$) {
503 my ($dig, $hdr) = @_;
504 my $b64 = $dig->clone->b64digest;
505 # Make our own URLs nicer:
506 # See "Base 64 Encoding with URL and Filename Safe Alphabet" in RFC4648
509 # Add a date prefix to prevent a leading '-' in case that trips
510 # up some tools (e.g. if a Message-ID were a expected as a
512 my $dt = msg_datestamp($hdr);
513 $dt = POSIX::strftime('%Y%m%d%H%M%S', gmtime($dt));
517 sub rewrite_commit ($$$$) {
518 my ($self, $oids, $buf, $mime) = @_;
519 my ($author, $at, $ct, $subject);
521 ($author, $at, $ct, $subject) = extract_cmt_info($mime);
524 $subject = 'purged '.join(' ', @$oids);
528 foreach my $i (0..$#$buf) {
530 if ($l =~ /^author .* ([0-9]+ [\+-]?[0-9]+)$/) {
532 $buf->[$i] = "author $author $at\n";
533 } elsif ($l =~ /^committer .* ([0-9]+ [\+-]?[0-9]+)$/) {
535 $buf->[$i] = "committer $self->{ident} $ct\n";
536 } elsif ($l =~ /^data ([0-9]+)/) {
537 $buf->[$i++] = "data " . length($subject) . "\n";
538 $buf->[$i] = $subject;
544 # returns the new commit OID if a replacement was done
545 # returns undef if nothing was done
547 my ($self, $mime, $replace_map) = @_; # oid => raw string
548 my $tmp = "refs/heads/replace-".((keys %$replace_map)[0]);
549 my $old = $self->{'ref'};
550 my $git = $self->{git};
551 my @export = (qw(fast-export --no-data --use-done-feature), $old);
552 my $rd = $git->popen(@export);
553 my ($r, $w) = $self->gfi_start;
558 my $tree = $self->{-tree};
560 if (/^reset (?:.+)/) {
561 push @buf, "reset $tmp\n";
562 } elsif (/^commit (?:.+)/) {
564 print $w @buf or wfail;
567 push @buf, "commit $tmp\n";
568 } elsif (/^data ([0-9]+)/) {
569 # only commit message, so $len is small:
570 my $len = $1; # + 1 for trailing "\n"
572 my $n = read($rd, my $buf, $len) or die "read: $!";
573 $len == $n or die "short read ($n < $len)";
575 } elsif (/^M 100644 ([a-f0-9]+) (\w+)/) {
576 my ($oid, $path) = ($1, $2);
578 my $sref = $replace_map->{$oid};
581 my $n = length($$sref);
582 push @buf, "M 100644 inline $path\ndata $n\n";
583 push @buf, $$sref; # hope CoW works...
588 } elsif (/^D (\w+)/) {
590 push @buf, $_ if $tree->{$path};
591 } elsif ($_ eq "\n") {
594 my $out = join('', @buf);
596 warn "purge rewriting\n", $out, "\n";
598 rewrite_commit($self, \@oids, \@buf, $mime);
601 print $w @buf, "\n" or wfail;
603 } elsif ($_ eq "done\n") {
605 } elsif (/^mark :([0-9]+)$/) {
612 close $rd or die "close fast-export failed: $?";
614 print $w @buf or wfail;
616 die 'done\n not seen from fast-export' unless $done;
617 chomp(my $cmt = $self->get_mark(":$mark")) if $nreplace;
618 $self->{nchg} = 0; # prevent _update_git_info until update-ref:
620 my @git = ('git', "--git-dir=$git->{git_dir}");
622 run_die([@git, qw(update-ref), $old, $tmp]) if $nreplace;
624 run_die([@git, qw(update-ref -d), $tmp]);
626 return if $nreplace == 0;
628 run_die([@git, qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
630 # check that old OIDs are gone
632 foreach my $oid (keys %$replace_map) {
633 my @info = $git->check($oid);
635 warn "$oid not replaced\n";
639 _update_git_info($self, 0);
640 die "Failed to replace $err object(s)\n" if $err;
650 PublicInbox::Import - message importer for public-inbox v1 inboxes
658 use PublicInbox::Eml;
659 # PublicInbox::Eml exists as of public-inbox 1.5.0,
660 # Email::MIME was used in older versions
662 use PublicInbox::Git;
663 use PublicInbox::Import;
665 chomp(my $git_dir = `git rev-parse --git-dir`);
666 $git_dir or die "GIT_DIR= must be specified\n";
667 my $git = PublicInbox::Git->new($git_dir);
668 my @committer = ('inbox', 'inbox@example.org');
669 my $im = PublicInbox::Import->new($git, @committer);
672 my $message = "From: <u\@example.org>\n".
673 "Subject: test message \n" .
674 "Date: Thu, 01 Jan 1970 00:00:00 +0000\n" .
675 "Message-ID: <m\@example.org>\n".
677 my $parsed = PublicInbox::Eml->new($message);
678 my $ret = $im->add($parsed);
680 warn "duplicate: ", $parsed->header_raw('Message-ID'), "\n";
682 print "imported at mark $ret\n";
686 # to remove a message
687 my $junk = PublicInbox::Eml->new($message);
688 my ($mark, $orig) = $im->remove($junk);
689 if ($mark eq 'MISSING') {
691 } elsif ($mark eq 'MISMATCH') {
692 print "Message exists but does not match\n\n",
693 $orig->as_string, "\n",;
695 print "removed at mark $mark\n\n",
696 $orig->as_string, "\n";
702 An importer and remover for public-inboxes which takes C<PublicInbox::Eml>
703 or L<Email::MIME> messages as input and stores them in a git repository as
704 documented in L<https://public-inbox.org/public-inbox-v1-format.txt>,
705 except it does not allow duplicate Message-IDs.
707 It requires L<git(1)> and L<git-fast-import(1)> to be installed.
715 my $im = PublicInbox::Import->new($git, @committer);
717 Initialize a new PublicInbox::Import object.
721 my $parsed = PublicInbox::Eml->new($message);
724 Adds a message to to the git repository. This will acquire
725 C<$GIT_DIR/ssoma.lock> and start L<git-fast-import(1)> if necessary.
727 Messages added will not be visible to other processes until L</done>
728 is called, but L</remove> may be called on them.
732 my $junk = PublicInbox::Eml->new($message);
733 my ($code, $orig) = $im->remove($junk);
735 Removes a message from the repository. On success, it returns
736 a ':'-prefixed numeric code representing the git-fast-import
737 mark and the original messages as a PublicInbox::Eml
738 (or Email::MIME) object.
739 If the message could not be found, the code is "MISSING"
740 and the original message is undef. If there is a mismatch where
741 the "Message-ID" is matched but the subject and body do not match,
742 the returned code is "MISMATCH" and the conflicting message
747 Finalizes the L<git-fast-import(1)> and unlocks the repository.
748 Calling this is required to finalize changes to a repository.
756 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
758 The mail archives are hosted at L<https://public-inbox.org/meta/>
762 Copyright (C) 2016-2020 all contributors L<mailto:meta@public-inbox.org>
764 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>