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;
11 use base 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::ContentId qw(content_digest);
18 use POSIX qw(strftime);
21 # we can't change arg order, this is documented in POD
22 # and external projects may rely on it:
23 my ($class, $git, $name, $email, $ibx) = @_;
24 my $ref = 'refs/heads/master';
26 $ref = $ibx->{ref_head} || 'refs/heads/master';
27 $name ||= $ibx->{name};
28 $email ||= $ibx->{-primary_address};
33 ident => "$name <$email>",
37 path_type => '2/38', # or 'v2'
38 lock_path => "$git->{git_dir}/ssoma.lock", # v2 changes this
43 # idempotent start function
47 return ($self->{in}, $self->{out}) if $self->{pid};
50 pipe($out_r, $out_w) or die "pipe failed: $!";
51 my $git = $self->{git};
56 my $ref = $self->{ref};
57 chomp($self->{tip} = $git->qx(qw(rev-parse --revs-only), $ref));
58 if ($self->{path_type} ne '2/38' && $self->{tip}) {
60 my @tree = $git->qx(qw(ls-tree -r -z --name-only), $ref);
62 $self->{-tree} = { map { $_ => 1 } @tree };
65 my $git_dir = $git->{git_dir};
66 my @cmd = ('git', "--git-dir=$git_dir", qw(fast-import
67 --quiet --done --date-format=raw));
68 my ($in_r, $pid) = popen_rd(\@cmd, undef, { 0 => $out_r });
71 $self->{out} = $out_w;
74 binmode $out_w, ':raw' or die "binmode :raw failed: $!";
75 binmode $in_r, ':raw' or die "binmode :raw failed: $!";
79 sub wfail () { die "write to fast-import failed: $!" }
81 sub now_raw () { time . ' +0000' }
85 my $b = $mime->body_raw;
86 $b =~ s/(\r?\n)+\z//s;
90 # only used for v1 (ssoma) inboxes
91 sub _check_path ($$$$) {
92 my ($r, $w, $tip, $path) = @_;
94 print $w "ls $tip $path\n" or wfail;
96 defined(my $info = <$r>) or die "EOF from fast-import: $!";
97 $info =~ /\Amissing / ? undef : $info;
100 sub _cat_blob ($$$) {
101 my ($r, $w, $oid) = @_;
102 print $w "cat-blob $oid\n" or wfail;
105 defined $info or die "EOF from fast-import / cat-blob: $!";
106 $info =~ /\A[a-f0-9]{40} blob ([0-9]+)\n\z/ or return;
112 $n = read($r, $buf, $left, $offset);
113 defined($n) or die "read cat-blob failed: $!";
114 $n == 0 and die 'fast-export (cat-blob) died';
118 $n = read($r, my $lf, 1);
119 defined($n) or die "read final byte of cat-blob failed: $!";
120 die "bad read on final byte: <$lf>" if $lf ne "\n";
122 # fixup some bugginess in old versions:
123 $buf =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
128 my ($self, $oid) = @_;
129 my ($r, $w) = $self->gfi_start;
130 _cat_blob($r, $w, $oid);
133 sub check_remove_v1 {
134 my ($r, $w, $tip, $path, $mime) = @_;
136 my $info = _check_path($r, $w, $tip, $path) or return ('MISSING',undef);
137 $info =~ m!\A100644 blob ([a-f0-9]{40})\t!s or die "not blob: $info";
139 my $msg = _cat_blob($r, $w, $oid) or die "BUG: cat-blob $1 failed";
140 my $cur = PublicInbox::MIME->new($msg);
141 my $cur_s = $cur->header('Subject');
142 $cur_s = '' unless defined $cur_s;
143 my $cur_m = $mime->header('Subject');
144 $cur_m = '' unless defined $cur_m;
145 if ($cur_s ne $cur_m || norm_body($cur) ne norm_body($mime)) {
146 return ('MISMATCH', $cur);
153 return unless $self->{pid};
154 print { $self->{out} } "checkpoint\n" or wfail;
159 my ($self, $msg) = @_;
160 return unless $self->{pid};
161 print { $self->{out} } "progress $msg\n" or wfail;
162 $self->{in}->getline eq "progress $msg\n" or die
163 "progress $msg not received\n";
167 sub _update_git_info ($$) {
168 my ($self, $do_gc) = @_;
169 # for compatibility with existing ssoma installations
170 # we can probably remove this entirely by 2020
171 my $git_dir = $self->{git}->{git_dir};
172 my @cmd = ('git', "--git-dir=$git_dir");
173 my $index = "$git_dir/ssoma.index";
174 if (-e $index && !$ENV{FAST}) {
175 my $env = { GIT_INDEX_FILE => $index };
176 run_die([@cmd, qw(read-tree -m -v -i), $self->{ref}], $env);
178 run_die([@cmd, 'update-server-info']);
179 my $ibx = $self->{-inbox};
180 ($ibx && $self->{path_type} eq '2/38') and eval {
181 require PublicInbox::SearchIdx;
182 my $s = PublicInbox::SearchIdx->new($ibx);
183 $s->index_sync({ ref => $self->{ref} });
185 eval { run_die([@cmd, qw(gc --auto)]) } if $do_gc;
191 # For safety, we ensure git checkpoint is complete before because
192 # the data in git is still more important than what is in Xapian
193 # in v2. Performance may be gained by delaying the ->progress
194 # call but we lose safety
197 $self->progress('checkpoint');
198 _update_git_info($self, 0);
205 my ($self, $mark) = @_;
206 die "not active\n" unless $self->{pid};
207 my ($r, $w) = $self->gfi_start;
208 print $w "get-mark $mark\n" or wfail;
209 defined(my $oid = <$r>) or die "get-mark failed, need git 2.6.0+\n";
214 # returns undef on non-existent
215 # ('MISMATCH', Email::MIME) on mismatch
216 # (:MARK, Email::MIME) on success
218 # v2 callers should check with Xapian before calling this as
219 # it is not idempotent.
221 my ($self, $mime, $msg) = @_; # mime = Email::MIME
223 my $path_type = $self->{path_type};
224 my ($path, $err, $cur, $blob);
226 my ($r, $w) = $self->gfi_start;
227 my $tip = $self->{tip};
228 if ($path_type eq '2/38') {
229 $path = mid2path(v1_mid0($mime));
230 ($err, $cur) = check_remove_v1($r, $w, $tip, $path, $mime);
231 return ($err, $cur) if $err;
234 if (ref($mime) eq 'SCALAR') { # optimization used by V2Writable
236 } else { # XXX should not be necessary:
237 my $str = $mime->as_string;
240 my $len = length($$sref);
241 $blob = $self->{mark}++;
242 print $w "blob\nmark :$blob\ndata $len\n",
243 $$sref, "\n" or wfail;
246 my $ref = $self->{ref};
247 my $commit = $self->{mark}++;
248 my $parent = $tip =~ /\A:/ ? $tip : undef;
250 print $w "reset $ref\n" or wfail;
252 my $ident = $self->{ident};
255 my $len = length($msg) + 1;
256 print $w "commit $ref\nmark :$commit\n",
257 "author $ident $now\n",
258 "committer $ident $now\n",
259 "data $len\n$msg\n\n",
260 'from ', ($parent ? $parent : $tip), "\n" or wfail;
262 print $w "D $path\n\n" or wfail;
264 clean_tree_v2($self, $w, 'd');
265 print $w "M 100644 :$blob d\n\n" or wfail;
268 (($self->{tip} = ":$commit"), $cur);
272 my ($ts, $zone) = @_;
273 $ts = 0 if $ts < 0; # git uses unsigned times
277 sub extract_cmt_info ($;$) {
278 my ($mime, $smsg) = @_;
281 my $from = $mime->header('From');
283 my ($email) = PublicInbox::Address::emails($from);
284 my ($name) = PublicInbox::Address::names($from);
285 if (!defined($name) || !defined($email)) {
286 $sender = $mime->header('Sender');
288 if (!defined($name)) {
289 ($name) = PublicInbox::Address::names($sender);
291 if (!defined($email)) {
292 ($email) = PublicInbox::Address::emails($sender);
295 if (defined $email) {
296 # Email::Address::XS may leave quoted '<' in addresses,
297 # which git-fast-import doesn't like
300 # quiet down wide character warnings with utf8::encode
301 utf8::encode($email);
304 warn "no email in From: $from or Sender: $sender\n";
307 # git gets confused with:
308 # "'A U Thor <u@example.com>' via foo" <foo@example.com>
310 # <CAD0k6qSUYANxbjjbE4jTW4EeVwOYgBD=bXkSu=akiYC_CB7Ffw@mail.gmail.com>
316 warn "no name in From: $from or Sender: $sender\n";
319 my $hdr = $mime->header_obj;
321 my $subject = $hdr->header('Subject');
322 $subject = '(no subject)' unless defined $subject;
323 # Mime decoding can create nulls replace them with spaces to protect git
324 $subject =~ tr/\0/ /;
325 utf8::encode($subject);
326 my $at = git_timestamp(my @at = msg_datestamp($hdr));
327 my $ct = git_timestamp(my @ct = msg_timestamp($hdr));
329 $smsg->{ds} = $at[0];
330 $smsg->{ts} = $ct[0];
332 ($name, $email, $at, $ct, $subject);
335 # kill potentially confusing/misleading headers
336 sub drop_unwanted_headers ($) {
339 $mime->header_set($_) for qw(bytes lines content-length status);
340 $mime->header_set($_) for @PublicInbox::MDA::BAD_HEADERS;
343 # used by V2Writable, too
344 sub append_mid ($$) {
345 my ($hdr, $mid0) = @_;
346 # @cur is likely empty if we need to call this sub, but it could
347 # have random unparseable crap which we'll preserve, too.
348 my @cur = $hdr->header_raw('Message-ID');
349 $hdr->header_set('Message-ID', @cur, "<$mid0>");
354 my $hdr = $mime->header_obj;
355 my $mids = mids($hdr);
357 if (!scalar(@$mids)) { # spam often has no Message-ID
358 my $mid0 = digest2mid(content_digest($mime), $hdr);
359 append_mid($hdr, $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) = @_; # mime = Email::MIME
379 my ($name, $email, $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) 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");
412 $smsg->{-raw_email} = \$raw_email;
414 my $ref = $self->{ref};
415 my $commit = $self->{mark}++;
416 my $parent = $tip =~ /\A:/ ? $tip : undef;
419 print $w "reset $ref\n" or wfail;
422 print $w "commit $ref\nmark :$commit\n",
423 "author $name <$email> $at\n",
424 "committer $self->{ident} $ct\n" or wfail;
425 print $w "data ", (length($subject) + 1), "\n",
426 $subject, "\n\n" or wfail;
428 print $w 'from ', ($parent ? $parent : $tip), "\n" or wfail;
430 clean_tree_v2($self, $w, $path);
431 print $w "M 100644 :$blob $path\n\n" or wfail;
433 $self->{tip} = ":$commit";
437 my ($cmd, $env, $rdr) = @_;
438 my $pid = spawn($cmd, $env, $rdr);
439 waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
440 $? == 0 or die join(' ', @$cmd) . " failed: $?\n";
443 my @INIT_FILES = ('HEAD' => "ref: refs/heads/master\n",
444 'description' => <<EOD,
445 Unnamed repository; edit this file 'description' to name the repository.
449 repositoryFormatVersion = 0
457 my ($dir) = @_; # or self
458 $dir = $dir->{git}->{git_dir} if ref($dir);
460 File::Path::mkpath([ map { "$dir/$_" } qw(objects/info refs/heads) ]);
461 for (my $i = 0; $i < @INIT_FILES; $i++) {
462 my $f = $dir.'/'.$INIT_FILES[$i++];
464 open my $fh, '>', $f or die "open $f: $!";
465 print $fh $INIT_FILES[$i] or die "print $f: $!";
466 close $fh or die "close $f: $!";
472 my $w = delete $self->{out} or return;
473 my $r = delete $self->{in} or die 'BUG: missing {in} when done';
474 print $w "done\n" or wfail;
475 my $pid = delete $self->{pid} or die 'BUG: missing {pid} when done';
476 waitpid($pid, 0) == $pid or die 'fast-import did not finish';
477 $? == 0 or die "fast-import failed: $?";
479 _update_git_info($self, 1) if delete $self->{nchg};
483 $self->{git}->cleanup;
488 foreach my $f (qw(in out)) {
489 next unless defined($self->{$f});
490 close $self->{$f} or die "failed to close import[$f]: $!\n";
494 sub digest2mid ($$) {
495 my ($dig, $hdr) = @_;
496 my $b64 = $dig->clone->b64digest;
497 # Make our own URLs nicer:
498 # See "Base 64 Encoding with URL and Filename Safe Alphabet" in RFC4648
501 # Add a date prefix to prevent a leading '-' in case that trips
502 # up some tools (e.g. if a Message-ID were a expected as a
504 my $dt = msg_datestamp($hdr);
505 $dt = POSIX::strftime('%Y%m%d%H%M%S', gmtime($dt));
509 sub rewrite_commit ($$$$) {
510 my ($self, $oids, $buf, $mime) = @_;
511 my ($name, $email, $at, $ct, $subject);
513 ($name, $email, $at, $ct, $subject) = extract_cmt_info($mime);
516 $subject = 'purged '.join(' ', @$oids);
520 foreach my $i (0..$#$buf) {
522 if ($l =~ /^author .* ([0-9]+ [\+-]?[0-9]+)$/) {
524 $buf->[$i] = "author $name <$email> $at\n";
525 } elsif ($l =~ /^committer .* ([0-9]+ [\+-]?[0-9]+)$/) {
527 $buf->[$i] = "committer $self->{ident} $ct\n";
528 } elsif ($l =~ /^data ([0-9]+)/) {
529 $buf->[$i++] = "data " . length($subject) . "\n";
530 $buf->[$i] = $subject;
536 # returns the new commit OID if a replacement was done
537 # returns undef if nothing was done
539 my ($self, $mime, $replace_map) = @_; # oid => raw string
540 my $tmp = "refs/heads/replace-".((keys %$replace_map)[0]);
541 my $old = $self->{'ref'};
542 my $git = $self->{git};
543 my @export = (qw(fast-export --no-data --use-done-feature), $old);
544 my $rd = $git->popen(@export);
545 my ($r, $w) = $self->gfi_start;
550 my $tree = $self->{-tree};
552 if (/^reset (?:.+)/) {
553 push @buf, "reset $tmp\n";
554 } elsif (/^commit (?:.+)/) {
556 $w->print(@buf) or wfail;
559 push @buf, "commit $tmp\n";
560 } elsif (/^data ([0-9]+)/) {
561 # only commit message, so $len is small:
562 my $len = $1; # + 1 for trailing "\n"
564 my $n = read($rd, my $buf, $len) or die "read: $!";
565 $len == $n or die "short read ($n < $len)";
567 } elsif (/^M 100644 ([a-f0-9]+) (\w+)/) {
568 my ($oid, $path) = ($1, $2);
570 my $sref = $replace_map->{$oid};
573 my $n = length($$sref);
574 push @buf, "M 100644 inline $path\ndata $n\n";
575 push @buf, $$sref; # hope CoW works...
580 } elsif (/^D (\w+)/) {
582 push @buf, $_ if $tree->{$path};
583 } elsif ($_ eq "\n") {
586 my $out = join('', @buf);
588 warn "purge rewriting\n", $out, "\n";
590 rewrite_commit($self, \@oids, \@buf, $mime);
593 $w->print(@buf, "\n") or wfail;
595 } elsif ($_ eq "done\n") {
597 } elsif (/^mark :([0-9]+)$/) {
604 close $rd or die "close fast-export failed: $?";
606 $w->print(@buf) or wfail;
608 die 'done\n not seen from fast-export' unless $done;
609 chomp(my $cmt = $self->get_mark(":$mark")) if $nreplace;
610 $self->{nchg} = 0; # prevent _update_git_info until update-ref:
612 my @git = ('git', "--git-dir=$git->{git_dir}");
614 run_die([@git, qw(update-ref), $old, $tmp]) if $nreplace;
616 run_die([@git, qw(update-ref -d), $tmp]);
618 return if $nreplace == 0;
620 run_die([@git, qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
622 # check that old OIDs are gone
624 foreach my $oid (keys %$replace_map) {
625 my @info = $git->check($oid);
627 warn "$oid not replaced\n";
631 _update_git_info($self, 0);
632 die "Failed to replace $err object(s)\n" if $err;
642 PublicInbox::Import - message importer for public-inbox v1 inboxes
651 use PublicInbox::Git;
652 use PublicInbox::Import;
654 chomp(my $git_dir = `git rev-parse --git-dir`);
655 $git_dir or die "GIT_DIR= must be specified\n";
656 my $git = PublicInbox::Git->new($git_dir);
657 my @committer = ('inbox', 'inbox@example.org');
658 my $im = PublicInbox::Import->new($git, @committer);
661 my $message = "From: <u\@example.org>\n".
662 "Subject: test message \n" .
663 "Date: Thu, 01 Jan 1970 00:00:00 +0000\n" .
664 "Message-ID: <m\@example.org>\n".
666 my $parsed = Email::MIME->new($message);
667 my $ret = $im->add($parsed);
670 $parsed->header_obj->header_raw('Message-ID'), "\n";
672 print "imported at mark $ret\n";
676 # to remove a message
677 my $junk = Email::MIME->new($message);
678 my ($mark, $orig) = $im->remove($junk);
679 if ($mark eq 'MISSING') {
681 } elsif ($mark eq 'MISMATCH') {
682 print "Message exists but does not match\n\n",
683 $orig->as_string, "\n",;
685 print "removed at mark $mark\n\n",
686 $orig->as_string, "\n";
692 An importer and remover for public-inboxes which takes L<Email::MIME>
693 messages as input and stores them in a git repository as
694 documented in L<https://public-inbox.org/public-inbox-v1-format.txt>,
695 except it does not allow duplicate Message-IDs.
697 It requires L<git(1)> and L<git-fast-import(1)> to be installed.
705 my $im = PublicInbox::Import->new($git, @committer);
707 Initialize a new PublicInbox::Import object.
711 my $parsed = Email::MIME->new($message);
714 Adds a message to to the git repository. This will acquire
715 C<$GIT_DIR/ssoma.lock> and start L<git-fast-import(1)> if necessary.
717 Messages added will not be visible to other processes until L</done>
718 is called, but L</remove> may be called on them.
722 my $junk = Email::MIME->new($message);
723 my ($code, $orig) = $im->remove($junk);
725 Removes a message from the repository. On success, it returns
726 a ':'-prefixed numeric code representing the git-fast-import
727 mark and the original messages as an Email::MIME object.
728 If the message could not be found, the code is "MISSING"
729 and the original message is undef. If there is a mismatch where
730 the "Message-ID" is matched but the subject and body do not match,
731 the returned code is "MISMATCH" and the conflicting message
736 Finalizes the L<git-fast-import(1)> and unlocks the repository.
737 Calling this is required to finalize changes to a repository.
745 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
747 The mail archives are hosted at L<https://public-inbox.org/meta/>
751 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
753 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>