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::MsgTime qw(msg_timestamp msg_datestamp);
16 use PublicInbox::ContentHash qw(content_digest);
19 use POSIX qw(strftime);
22 # we can't change arg order, this is documented in POD
23 # and external projects may rely on it:
24 my ($class, $git, $name, $email, $ibx) = @_;
25 my $ref = 'refs/heads/master';
27 $ref = $ibx->{ref_head} // 'refs/heads/master';
28 $name //= $ibx->{name};
29 $email //= $ibx->{-primary_address};
34 ident => "$name <$email>",
38 path_type => '2/38', # or 'v2'
39 lock_path => "$git->{git_dir}/ssoma.lock", # v2 changes this
44 # idempotent start function
48 return ($self->{in}, $self->{out}) if $self->{pid};
51 pipe($out_r, $out_w) or die "pipe failed: $!";
52 my $git = $self->{git};
57 my $ref = $self->{ref};
58 chomp($self->{tip} = $git->qx(qw(rev-parse --revs-only), $ref));
59 if ($self->{path_type} ne '2/38' && $self->{tip}) {
61 my @tree = $git->qx(qw(ls-tree -r -z --name-only), $ref);
63 $self->{-tree} = { map { $_ => 1 } @tree };
66 my $git_dir = $git->{git_dir};
67 my @cmd = ('git', "--git-dir=$git_dir", qw(fast-import
68 --quiet --done --date-format=raw));
69 my ($in_r, $pid) = popen_rd(\@cmd, undef, { 0 => $out_r });
72 $self->{out} = $out_w;
75 binmode $out_w, ':raw' or die "binmode :raw failed: $!";
76 binmode $in_r, ':raw' or die "binmode :raw failed: $!";
80 sub wfail () { die "write to fast-import failed: $!" }
82 sub now_raw () { time . ' +0000' }
86 my $b = $mime->body_raw;
87 $b =~ s/(\r?\n)+\z//s;
91 # only used for v1 (ssoma) inboxes
92 sub _check_path ($$$$) {
93 my ($r, $w, $tip, $path) = @_;
95 print $w "ls $tip $path\n" or wfail;
97 defined(my $info = <$r>) or die "EOF from fast-import: $!";
98 $info =~ /\Amissing / ? undef : $info;
101 sub _cat_blob ($$$) {
102 my ($r, $w, $oid) = @_;
103 print $w "cat-blob $oid\n" or wfail;
106 defined $info or die "EOF from fast-import / cat-blob: $!";
107 $info =~ /\A[a-f0-9]{40} blob ([0-9]+)\n\z/ or return;
113 $n = read($r, $buf, $left, $offset);
114 defined($n) or die "read cat-blob failed: $!";
115 $n == 0 and die 'fast-export (cat-blob) died';
119 $n = read($r, my $lf, 1);
120 defined($n) or die "read final byte of cat-blob failed: $!";
121 die "bad read on final byte: <$lf>" if $lf ne "\n";
123 # fixup some bugginess in old versions:
124 $buf =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
129 my ($self, $oid) = @_;
130 my ($r, $w) = $self->gfi_start;
131 _cat_blob($r, $w, $oid);
134 sub check_remove_v1 {
135 my ($r, $w, $tip, $path, $mime) = @_;
137 my $info = _check_path($r, $w, $tip, $path) or return ('MISSING',undef);
138 $info =~ m!\A100644 blob ([a-f0-9]{40})\t!s or die "not blob: $info";
140 my $msg = _cat_blob($r, $w, $oid) or die "BUG: cat-blob $1 failed";
141 my $cur = PublicInbox::Eml->new($msg);
142 my $cur_s = $cur->header('Subject');
143 $cur_s = '' unless defined $cur_s;
144 my $cur_m = $mime->header('Subject');
145 $cur_m = '' unless defined $cur_m;
146 if ($cur_s ne $cur_m || norm_body($cur) ne norm_body($mime)) {
147 return ('MISMATCH', $cur);
154 return unless $self->{pid};
155 print { $self->{out} } "checkpoint\n" or wfail;
160 my ($self, $msg) = @_;
161 return unless $self->{pid};
162 print { $self->{out} } "progress $msg\n" or wfail;
163 readline($self->{in}) eq "progress $msg\n" or die
164 "progress $msg not received\n";
168 sub _update_git_info ($$) {
169 my ($self, $do_gc) = @_;
170 # for compatibility with existing ssoma installations
171 # we can probably remove this entirely by 2020
172 my $git_dir = $self->{git}->{git_dir};
173 my @cmd = ('git', "--git-dir=$git_dir");
174 my $index = "$git_dir/ssoma.index";
175 if (-e $index && !$ENV{FAST}) {
176 my $env = { GIT_INDEX_FILE => $index };
177 run_die([@cmd, qw(read-tree -m -v -i), $self->{ref}], $env);
179 run_die([@cmd, 'update-server-info']);
180 my $ibx = $self->{-inbox};
181 ($ibx && $self->{path_type} eq '2/38') and eval {
182 require PublicInbox::SearchIdx;
183 my $s = PublicInbox::SearchIdx->new($ibx);
184 $s->index_sync({ ref => $self->{ref} });
186 eval { run_die([@cmd, qw(gc --auto)]) } if $do_gc;
192 # For safety, we ensure git checkpoint is complete before because
193 # the data in git is still more important than what is in Xapian
194 # in v2. Performance may be gained by delaying the ->progress
195 # call but we lose safety
198 $self->progress('checkpoint');
199 _update_git_info($self, 0);
206 my ($self, $mark) = @_;
207 die "not active\n" unless $self->{pid};
208 my ($r, $w) = $self->gfi_start;
209 print $w "get-mark $mark\n" or wfail;
210 defined(my $oid = <$r>) or die "get-mark failed, need git 2.6.0+\n";
215 # returns undef on non-existent
216 # ('MISMATCH', PublicInbox::Eml) on mismatch
217 # (:MARK, PublicInbox::Eml) on success
219 # v2 callers should check with Xapian before calling this as
220 # it is not idempotent.
222 my ($self, $mime, $msg) = @_; # mime = PublicInbox::Eml or Email::MIME
224 my $path_type = $self->{path_type};
225 my ($path, $err, $cur, $blob);
227 my ($r, $w) = $self->gfi_start;
228 my $tip = $self->{tip};
229 if ($path_type eq '2/38') {
230 $path = mid2path(v1_mid0($mime));
231 ($err, $cur) = check_remove_v1($r, $w, $tip, $path, $mime);
232 return ($err, $cur) if $err;
235 if (ref($mime) eq 'SCALAR') { # optimization used by V2Writable
237 } else { # XXX should not be necessary:
238 my $str = $mime->as_string;
241 my $len = length($$sref);
242 $blob = $self->{mark}++;
243 print $w "blob\nmark :$blob\ndata $len\n",
244 $$sref, "\n" or wfail;
247 my $ref = $self->{ref};
248 my $commit = $self->{mark}++;
249 my $parent = $tip =~ /\A:/ ? $tip : undef;
251 print $w "reset $ref\n" or wfail;
253 my $ident = $self->{ident};
256 my $len = length($msg) + 1;
257 print $w "commit $ref\nmark :$commit\n",
258 "author $ident $now\n",
259 "committer $ident $now\n",
260 "data $len\n$msg\n\n",
261 'from ', ($parent ? $parent : $tip), "\n" or wfail;
263 print $w "D $path\n\n" or wfail;
265 clean_tree_v2($self, $w, 'd');
266 print $w "M 100644 :$blob d\n\n" or wfail;
269 (($self->{tip} = ":$commit"), $cur);
273 my ($ts, $zone) = @_;
274 $ts = 0 if $ts < 0; # git uses unsigned times
278 sub extract_cmt_info ($;$) {
279 my ($mime, $smsg) = @_;
280 # $mime is PublicInbox::Eml, but remains Email::MIME-compatible
283 my $hdr = $mime->header_obj;
284 my $from = $hdr->header('From') // '';
285 my ($email) = PublicInbox::Address::emails($from);
286 my ($name) = PublicInbox::Address::names($from);
287 if (!defined($name) || !defined($email)) {
288 $sender = $hdr->header('Sender') // '';
289 $name //= (PublicInbox::Address::names($sender))[0];
290 $email //= (PublicInbox::Address::emails($sender))[0];
292 if (defined $email) {
293 # Email::Address::XS may leave quoted '<' in addresses,
294 # which git-fast-import doesn't like
297 # quiet down wide character warnings with utf8::encode
298 utf8::encode($email);
301 warn "no email in From: $from or Sender: $sender\n";
304 # git gets confused with:
305 # "'A U Thor <u@example.com>' via foo" <foo@example.com>
307 # <CAD0k6qSUYANxbjjbE4jTW4EeVwOYgBD=bXkSu=akiYC_CB7Ffw@mail.gmail.com>
313 warn "no name in From: $from or Sender: $sender\n";
316 my $subject = $hdr->header('Subject') // '(no subject)';
317 # MIME decoding can create nulls replace them with spaces to protect git
318 $subject =~ tr/\0/ /;
319 utf8::encode($subject);
320 my $at = git_timestamp(my @at = msg_datestamp($hdr));
321 my $ct = git_timestamp(my @ct = msg_timestamp($hdr));
323 $smsg->{ds} = $at[0];
324 $smsg->{ts} = $ct[0];
326 ($name, $email, $at, $ct, $subject);
329 # kill potentially confusing/misleading headers
330 sub drop_unwanted_headers ($) {
333 $mime->header_set($_) for qw(bytes lines content-length status);
334 $mime->header_set($_) for @PublicInbox::MDA::BAD_HEADERS;
337 # used by V2Writable, too
338 sub append_mid ($$) {
339 my ($hdr, $mid0) = @_;
340 # @cur is likely empty if we need to call this sub, but it could
341 # have random unparseable crap which we'll preserve, too.
342 my @cur = $hdr->header_raw('Message-ID');
343 $hdr->header_set('Message-ID', @cur, "<$mid0>");
348 my $hdr = $mime->header_obj;
349 my $mids = mids($hdr);
351 if (!scalar(@$mids)) { # spam often has no Message-ID
352 my $mid0 = digest2mid(content_digest($mime), $hdr);
353 append_mid($hdr, $mid0);
358 sub clean_tree_v2 ($$$) {
359 my ($self, $w, $keep) = @_;
360 my $tree = $self->{-tree} or return; #v2 only
361 delete $tree->{$keep};
362 foreach (keys %$tree) {
363 print $w "D $_\n" or wfail;
365 %$tree = ($keep => 1);
368 # returns undef on duplicate
369 # returns the :MARK of the most recent commit
371 my ($self, $mime, $check_cb, $smsg) = @_;
373 my ($name, $email, $at, $ct, $subject) = extract_cmt_info($mime, $smsg);
374 my $path_type = $self->{path_type};
376 if ($path_type eq '2/38') {
377 $path = mid2path(v1_mid0($mime));
378 } else { # v2 layout, one file:
382 my ($r, $w) = $self->gfi_start;
383 my $tip = $self->{tip};
384 if ($path_type eq '2/38') {
385 _check_path($r, $w, $tip, $path) and return;
388 drop_unwanted_headers($mime);
392 $mime = $check_cb->($mime) or return;
395 my $blob = $self->{mark}++;
396 my $raw_email = $mime->{-public_inbox_raw} // $mime->as_string;
397 my $n = length($raw_email);
398 $self->{bytes_added} += $n;
399 print $w "blob\nmark :$blob\ndata ", $n, "\n" or wfail;
400 print $w $raw_email, "\n" or wfail;
402 # v2: we need this for Xapian
404 $smsg->{blob} = $self->get_mark(":$blob");
406 $smsg->{-raw_email} = \$raw_email;
408 my $ref = $self->{ref};
409 my $commit = $self->{mark}++;
410 my $parent = $tip =~ /\A:/ ? $tip : undef;
413 print $w "reset $ref\n" or wfail;
416 print $w "commit $ref\nmark :$commit\n",
417 "author $name <$email> $at\n",
418 "committer $self->{ident} $ct\n" or wfail;
419 print $w "data ", (length($subject) + 1), "\n",
420 $subject, "\n\n" or wfail;
422 print $w 'from ', ($parent ? $parent : $tip), "\n" or wfail;
424 clean_tree_v2($self, $w, $path);
425 print $w "M 100644 :$blob $path\n\n" or wfail;
427 $self->{tip} = ":$commit";
431 my ($cmd, $env, $rdr) = @_;
432 my $pid = spawn($cmd, $env, $rdr);
433 waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
434 $? == 0 or die join(' ', @$cmd) . " failed: $?\n";
437 my @INIT_FILES = ('HEAD' => "ref: refs/heads/master\n",
438 'description' => <<EOD,
439 Unnamed repository; edit this file 'description' to name the repository.
443 repositoryFormatVersion = 0
451 my ($dir) = @_; # or self
452 $dir = $dir->{git}->{git_dir} if ref($dir);
454 File::Path::mkpath([ map { "$dir/$_" } qw(objects/info refs/heads) ]);
455 for (my $i = 0; $i < @INIT_FILES; $i++) {
456 my $f = $dir.'/'.$INIT_FILES[$i++];
458 open my $fh, '>', $f or die "open $f: $!";
459 print $fh $INIT_FILES[$i] or die "print $f: $!";
460 close $fh or die "close $f: $!";
466 my $w = delete $self->{out} or return;
467 my $r = delete $self->{in} or die 'BUG: missing {in} when done';
468 print $w "done\n" or wfail;
469 my $pid = delete $self->{pid} or die 'BUG: missing {pid} when done';
470 waitpid($pid, 0) == $pid or die 'fast-import did not finish';
471 $? == 0 or die "fast-import failed: $?";
473 _update_git_info($self, 1) if delete $self->{nchg};
477 $self->{git}->cleanup;
482 foreach my $f (qw(in out)) {
483 next unless defined($self->{$f});
484 close $self->{$f} or die "failed to close import[$f]: $!\n";
488 sub digest2mid ($$) {
489 my ($dig, $hdr) = @_;
490 my $b64 = $dig->clone->b64digest;
491 # Make our own URLs nicer:
492 # See "Base 64 Encoding with URL and Filename Safe Alphabet" in RFC4648
495 # Add a date prefix to prevent a leading '-' in case that trips
496 # up some tools (e.g. if a Message-ID were a expected as a
498 my $dt = msg_datestamp($hdr);
499 $dt = POSIX::strftime('%Y%m%d%H%M%S', gmtime($dt));
503 sub rewrite_commit ($$$$) {
504 my ($self, $oids, $buf, $mime) = @_;
505 my ($name, $email, $at, $ct, $subject);
507 ($name, $email, $at, $ct, $subject) = extract_cmt_info($mime);
510 $subject = 'purged '.join(' ', @$oids);
514 foreach my $i (0..$#$buf) {
516 if ($l =~ /^author .* ([0-9]+ [\+-]?[0-9]+)$/) {
518 $buf->[$i] = "author $name <$email> $at\n";
519 } elsif ($l =~ /^committer .* ([0-9]+ [\+-]?[0-9]+)$/) {
521 $buf->[$i] = "committer $self->{ident} $ct\n";
522 } elsif ($l =~ /^data ([0-9]+)/) {
523 $buf->[$i++] = "data " . length($subject) . "\n";
524 $buf->[$i] = $subject;
530 # returns the new commit OID if a replacement was done
531 # returns undef if nothing was done
533 my ($self, $mime, $replace_map) = @_; # oid => raw string
534 my $tmp = "refs/heads/replace-".((keys %$replace_map)[0]);
535 my $old = $self->{'ref'};
536 my $git = $self->{git};
537 my @export = (qw(fast-export --no-data --use-done-feature), $old);
538 my $rd = $git->popen(@export);
539 my ($r, $w) = $self->gfi_start;
544 my $tree = $self->{-tree};
546 if (/^reset (?:.+)/) {
547 push @buf, "reset $tmp\n";
548 } elsif (/^commit (?:.+)/) {
550 print $w @buf or wfail;
553 push @buf, "commit $tmp\n";
554 } elsif (/^data ([0-9]+)/) {
555 # only commit message, so $len is small:
556 my $len = $1; # + 1 for trailing "\n"
558 my $n = read($rd, my $buf, $len) or die "read: $!";
559 $len == $n or die "short read ($n < $len)";
561 } elsif (/^M 100644 ([a-f0-9]+) (\w+)/) {
562 my ($oid, $path) = ($1, $2);
564 my $sref = $replace_map->{$oid};
567 my $n = length($$sref);
568 push @buf, "M 100644 inline $path\ndata $n\n";
569 push @buf, $$sref; # hope CoW works...
574 } elsif (/^D (\w+)/) {
576 push @buf, $_ if $tree->{$path};
577 } elsif ($_ eq "\n") {
580 my $out = join('', @buf);
582 warn "purge rewriting\n", $out, "\n";
584 rewrite_commit($self, \@oids, \@buf, $mime);
587 print $w @buf, "\n" or wfail;
589 } elsif ($_ eq "done\n") {
591 } elsif (/^mark :([0-9]+)$/) {
598 close $rd or die "close fast-export failed: $?";
600 print $w @buf or wfail;
602 die 'done\n not seen from fast-export' unless $done;
603 chomp(my $cmt = $self->get_mark(":$mark")) if $nreplace;
604 $self->{nchg} = 0; # prevent _update_git_info until update-ref:
606 my @git = ('git', "--git-dir=$git->{git_dir}");
608 run_die([@git, qw(update-ref), $old, $tmp]) if $nreplace;
610 run_die([@git, qw(update-ref -d), $tmp]);
612 return if $nreplace == 0;
614 run_die([@git, qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
616 # check that old OIDs are gone
618 foreach my $oid (keys %$replace_map) {
619 my @info = $git->check($oid);
621 warn "$oid not replaced\n";
625 _update_git_info($self, 0);
626 die "Failed to replace $err object(s)\n" if $err;
636 PublicInbox::Import - message importer for public-inbox v1 inboxes
644 use PublicInbox::Eml;
645 # PublicInbox::Eml exists as of public-inbox 1.5.0,
646 # Email::MIME was used in older versions
648 use PublicInbox::Git;
649 use PublicInbox::Import;
651 chomp(my $git_dir = `git rev-parse --git-dir`);
652 $git_dir or die "GIT_DIR= must be specified\n";
653 my $git = PublicInbox::Git->new($git_dir);
654 my @committer = ('inbox', 'inbox@example.org');
655 my $im = PublicInbox::Import->new($git, @committer);
658 my $message = "From: <u\@example.org>\n".
659 "Subject: test message \n" .
660 "Date: Thu, 01 Jan 1970 00:00:00 +0000\n" .
661 "Message-ID: <m\@example.org>\n".
663 my $parsed = PublicInbox::Eml->new($message);
664 my $ret = $im->add($parsed);
667 $parsed->header_obj->header_raw('Message-ID'), "\n";
669 print "imported at mark $ret\n";
673 # to remove a message
674 my $junk = PublicInbox::Eml->new($message);
675 my ($mark, $orig) = $im->remove($junk);
676 if ($mark eq 'MISSING') {
678 } elsif ($mark eq 'MISMATCH') {
679 print "Message exists but does not match\n\n",
680 $orig->as_string, "\n",;
682 print "removed at mark $mark\n\n",
683 $orig->as_string, "\n";
689 An importer and remover for public-inboxes which takes C<PublicInbox::Eml>
690 or L<Email::MIME> messages as input and stores them in a git repository as
691 documented in L<https://public-inbox.org/public-inbox-v1-format.txt>,
692 except it does not allow duplicate Message-IDs.
694 It requires L<git(1)> and L<git-fast-import(1)> to be installed.
702 my $im = PublicInbox::Import->new($git, @committer);
704 Initialize a new PublicInbox::Import object.
708 my $parsed = PublicInbox::Eml->new($message);
711 Adds a message to to the git repository. This will acquire
712 C<$GIT_DIR/ssoma.lock> and start L<git-fast-import(1)> if necessary.
714 Messages added will not be visible to other processes until L</done>
715 is called, but L</remove> may be called on them.
719 my $junk = PublicInbox::Eml->new($message);
720 my ($code, $orig) = $im->remove($junk);
722 Removes a message from the repository. On success, it returns
723 a ':'-prefixed numeric code representing the git-fast-import
724 mark and the original messages as a PublicInbox::Eml
725 (or Email::MIME) object.
726 If the message could not be found, the code is "MISSING"
727 and the original message is undef. If there is a mismatch where
728 the "Message-ID" is matched but the subject and body do not match,
729 the returned code is "MISMATCH" and the conflicting message
734 Finalizes the L<git-fast-import(1)> and unlocks the repository.
735 Calling this is required to finalize changes to a repository.
743 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
745 The mail archives are hosted at L<https://public-inbox.org/meta/>
749 Copyright (C) 2016-2020 all contributors L<mailto:meta@public-inbox.org>
751 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>