1 # Copyright (C) 2016-2019 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);
13 use PublicInbox::MID qw(mids mid_mime 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};
49 my ($in_r, $in_w, $out_r, $out_w);
50 pipe($in_r, $in_w) or die "pipe failed: $!";
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 $rdr = { 0 => fileno($out_r), 1 => fileno($in_w) };
70 my $pid = spawn(\@cmd, undef, $rdr);
71 die "spawn fast-import failed: $!" unless defined $pid;
74 $self->{out} = $out_w;
77 binmode $out_w, ':raw' or die "binmode :raw failed: $!";
78 binmode $in_r, ':raw' or die "binmode :raw failed: $!";
82 sub wfail () { die "write to fast-import failed: $!" }
84 sub now_raw () { time . ' +0000' }
88 my $b = $mime->body_raw;
89 $b =~ s/(\r?\n)+\z//s;
93 # only used for v1 (ssoma) inboxes
94 sub _check_path ($$$$) {
95 my ($r, $w, $tip, $path) = @_;
97 print $w "ls $tip $path\n" or wfail;
99 defined(my $info = <$r>) or die "EOF from fast-import: $!";
100 $info =~ /\Amissing / ? undef : $info;
103 sub _cat_blob ($$$) {
104 my ($r, $w, $oid) = @_;
105 print $w "cat-blob $oid\n" or wfail;
108 defined $info or die "EOF from fast-import / cat-blob: $!";
109 $info =~ /\A[a-f0-9]{40} blob (\d+)\n\z/ or return;
115 $n = read($r, $buf, $left, $offset);
116 defined($n) or die "read cat-blob failed: $!";
117 $n == 0 and die 'fast-export (cat-blob) died';
121 $n = read($r, my $lf, 1);
122 defined($n) or die "read final byte of cat-blob failed: $!";
123 die "bad read on final byte: <$lf>" if $lf ne "\n";
125 # fixup some bugginess in old versions:
126 $buf =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
131 my ($self, $oid) = @_;
132 my ($r, $w) = $self->gfi_start;
133 _cat_blob($r, $w, $oid);
136 sub check_remove_v1 {
137 my ($r, $w, $tip, $path, $mime) = @_;
139 my $info = _check_path($r, $w, $tip, $path) or return ('MISSING',undef);
140 $info =~ m!\A100644 blob ([a-f0-9]{40})\t!s or die "not blob: $info";
142 my $msg = _cat_blob($r, $w, $oid) or die "BUG: cat-blob $1 failed";
143 my $cur = PublicInbox::MIME->new($msg);
144 my $cur_s = $cur->header('Subject');
145 $cur_s = '' unless defined $cur_s;
146 my $cur_m = $mime->header('Subject');
147 $cur_m = '' unless defined $cur_m;
148 if ($cur_s ne $cur_m || norm_body($cur) ne norm_body($mime)) {
149 return ('MISMATCH', $cur);
156 return unless $self->{pid};
157 print { $self->{out} } "checkpoint\n" or wfail;
162 my ($self, $msg) = @_;
163 return unless $self->{pid};
164 print { $self->{out} } "progress $msg\n" or wfail;
165 $self->{in}->getline eq "progress $msg\n" or die
166 "progress $msg not received\n";
170 sub _update_git_info ($$) {
171 my ($self, $do_gc) = @_;
172 # for compatibility with existing ssoma installations
173 # we can probably remove this entirely by 2020
174 my $git_dir = $self->{git}->{git_dir};
175 my @cmd = ('git', "--git-dir=$git_dir");
176 my $index = "$git_dir/ssoma.index";
177 if (-e $index && !$ENV{FAST}) {
178 my $env = { GIT_INDEX_FILE => $index };
179 run_die([@cmd, qw(read-tree -m -v -i), $self->{ref}], $env);
181 run_die([@cmd, 'update-server-info'], undef);
182 ($self->{path_type} eq '2/38') and eval {
183 require PublicInbox::SearchIdx;
184 my $ibx = $self->{-inbox} || $git_dir;
185 my $s = PublicInbox::SearchIdx->new($ibx);
186 $s->index_sync({ ref => $self->{ref} });
188 eval { run_die([@cmd, qw(gc --auto)], undef) } if $do_gc;
194 # For safety, we ensure git checkpoint is complete before because
195 # the data in git is still more important than what is in Xapian
196 # in v2. Performance may be gained by delaying the ->progress
197 # call but we lose safety
200 $self->progress('checkpoint');
201 _update_git_info($self, 0);
208 my ($self, $mark) = @_;
209 die "not active\n" unless $self->{pid};
210 my ($r, $w) = $self->gfi_start;
211 print $w "get-mark $mark\n" or wfail;
212 defined(my $oid = <$r>) or die "get-mark failed, need git 2.6.0+\n";
217 # returns undef on non-existent
218 # ('MISMATCH', Email::MIME) on mismatch
219 # (:MARK, Email::MIME) on success
221 # v2 callers should check with Xapian before calling this as
222 # it is not idempotent.
224 my ($self, $mime, $msg) = @_; # mime = Email::MIME
226 my $path_type = $self->{path_type};
227 my ($path, $err, $cur, $blob);
229 my ($r, $w) = $self->gfi_start;
230 my $tip = $self->{tip};
231 if ($path_type eq '2/38') {
232 $path = mid2path(v1_mid0($mime));
233 ($err, $cur) = check_remove_v1($r, $w, $tip, $path, $mime);
234 return ($err, $cur) if $err;
237 if (ref($mime) eq 'SCALAR') { # optimization used by V2Writable
239 } else { # XXX should not be necessary:
240 my $str = $mime->as_string;
243 my $len = length($$sref);
244 $blob = $self->{mark}++;
245 print $w "blob\nmark :$blob\ndata $len\n",
246 $$sref, "\n" or wfail;
249 my $ref = $self->{ref};
250 my $commit = $self->{mark}++;
251 my $parent = $tip =~ /\A:/ ? $tip : undef;
253 print $w "reset $ref\n" or wfail;
255 my $ident = $self->{ident};
258 my $len = length($msg) + 1;
259 print $w "commit $ref\nmark :$commit\n",
260 "author $ident $now\n",
261 "committer $ident $now\n",
262 "data $len\n$msg\n\n",
263 'from ', ($parent ? $parent : $tip), "\n" or wfail;
265 print $w "D $path\n\n" or wfail;
267 clean_tree_v2($self, $w, 'd');
268 print $w "M 100644 :$blob d\n\n" or wfail;
271 (($self->{tip} = ":$commit"), $cur);
275 my ($ts, $zone) = @_;
276 $ts = 0 if $ts < 0; # git uses unsigned times
280 sub extract_author_info ($) {
284 my $from = $mime->header('From');
286 my ($email) = PublicInbox::Address::emails($from);
287 my ($name) = PublicInbox::Address::names($from);
288 if (!defined($name) || !defined($email)) {
289 $sender = $mime->header('Sender');
291 if (!defined($name)) {
292 ($name) = PublicInbox::Address::names($sender);
294 if (!defined($email)) {
295 ($email) = PublicInbox::Address::emails($sender);
298 if (defined $email) {
299 # quiet down wide character warnings with utf8::encode
300 utf8::encode($email);
303 warn "no email in From: $from or Sender: $sender\n";
306 # git gets confused with:
307 # "'A U Thor <u@example.com>' via foo" <foo@example.com>
309 # <CAD0k6qSUYANxbjjbE4jTW4EeVwOYgBD=bXkSu=akiYC_CB7Ffw@mail.gmail.com>
315 warn "no name in From: $from or Sender: $sender\n";
320 # kill potentially confusing/misleading headers
321 sub drop_unwanted_headers ($) {
324 $mime->header_set($_) for qw(bytes lines content-length status);
325 $mime->header_set($_) for @PublicInbox::MDA::BAD_HEADERS;
328 # used by V2Writable, too
329 sub append_mid ($$) {
330 my ($hdr, $mid0) = @_;
331 # @cur is likely empty if we need to call this sub, but it could
332 # have random unparseable crap which we'll preserve, too.
333 my @cur = $hdr->header_raw('Message-ID');
334 $hdr->header_set('Message-ID', @cur, "<$mid0>");
339 my $hdr = $mime->header_obj;
340 my $mids = mids($hdr);
342 if (!scalar(@$mids)) { # spam often has no Message-Id
343 my $mid0 = digest2mid(content_digest($mime), $hdr);
344 append_mid($hdr, $mid0);
349 sub clean_tree_v2 ($$$) {
350 my ($self, $w, $keep) = @_;
351 my $tree = $self->{-tree} or return; #v2 only
352 delete $tree->{$keep};
353 foreach (keys %$tree) {
354 print $w "D $_\n" or wfail;
356 %$tree = ($keep => 1);
359 # returns undef on duplicate
360 # returns the :MARK of the most recent commit
362 my ($self, $mime, $check_cb) = @_; # mime = Email::MIME
364 my ($name, $email) = extract_author_info($mime);
365 my $hdr = $mime->header_obj;
366 my @at = msg_datestamp($hdr);
367 my @ct = msg_timestamp($hdr);
368 my $author_time_raw = git_timestamp(@at);
369 my $commit_time_raw = git_timestamp(@ct);
371 my $subject = $mime->header('Subject');
372 $subject = '(no subject)' unless defined $subject;
373 # Mime decoding can create nulls replace them with spaces to protect git
374 $subject =~ tr/\0/ /;
375 utf8::encode($subject);
377 my $path_type = $self->{path_type};
379 if ($path_type eq '2/38') {
380 $path = mid2path(v1_mid0($mime));
381 } else { # v2 layout, one file:
385 my ($r, $w) = $self->gfi_start;
386 my $tip = $self->{tip};
387 if ($path_type eq '2/38') {
388 _check_path($r, $w, $tip, $path) and return;
391 drop_unwanted_headers($mime);
395 $mime = $check_cb->($mime) or return;
398 my $blob = $self->{mark}++;
399 my $str = $mime->as_string;
400 my $n = length($str);
401 $self->{bytes_added} += $n;
402 print $w "blob\nmark :$blob\ndata ", $n, "\n" or wfail;
403 print $w $str, "\n" or wfail;
405 # v2: we need this for Xapian
406 if ($self->{want_object_info}) {
407 my $oid = $self->get_mark(":$blob");
408 $self->{last_object} = [ $oid, $n, \$str ];
410 my $ref = $self->{ref};
411 my $commit = $self->{mark}++;
412 my $parent = $tip =~ /\A:/ ? $tip : undef;
415 print $w "reset $ref\n" or wfail;
418 print $w "commit $ref\nmark :$commit\n",
419 "author $name <$email> $author_time_raw\n",
420 "committer $self->{ident} $commit_time_raw\n" or wfail;
421 print $w "data ", (length($subject) + 1), "\n",
422 $subject, "\n\n" or wfail;
424 print $w 'from ', ($parent ? $parent : $tip), "\n" or wfail;
426 clean_tree_v2($self, $w, $path);
427 print $w "M 100644 :$blob $path\n\n" or wfail;
429 $self->{tip} = ":$commit";
433 my ($cmd, $env, $rdr) = @_;
434 my $pid = spawn($cmd, $env, $rdr);
435 defined $pid or die "spawning ".join(' ', @$cmd)." failed: $!";
436 waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
437 $? == 0 or die join(' ', @$cmd) . " failed: $?\n";
442 my @cmd = (qw(git init --bare -q), $dir);
444 # set a reasonable default:
445 @cmd = (qw/git config/, "--file=$dir/config",
446 'repack.writeBitmaps', 'true');
452 my $w = delete $self->{out} or return;
453 my $r = delete $self->{in} or die 'BUG: missing {in} when done';
454 print $w "done\n" or wfail;
455 my $pid = delete $self->{pid} or die 'BUG: missing {pid} when done';
456 waitpid($pid, 0) == $pid or die 'fast-import did not finish';
457 $? == 0 or die "fast-import failed: $?";
459 _update_git_info($self, 1) if delete $self->{nchg};
463 $self->{git}->cleanup;
468 foreach my $f (qw(in out)) {
469 next unless defined($self->{$f});
470 close $self->{$f} or die "failed to close import[$f]: $!\n";
474 sub digest2mid ($$) {
475 my ($dig, $hdr) = @_;
476 my $b64 = $dig->clone->b64digest;
477 # Make our own URLs nicer:
478 # See "Base 64 Encoding with URL and Filename Safe Alphabet" in RFC4648
481 # Add a date prefix to prevent a leading '-' in case that trips
482 # up some tools (e.g. if a Message-ID were a expected as a
484 my $dt = msg_datestamp($hdr);
485 $dt = POSIX::strftime('%Y%m%d%H%M%S', gmtime($dt));
489 sub clean_purge_buffer {
490 my ($oids, $buf) = @_;
491 my $cmt_msg = 'purged '.join(' ',@$oids)."\n";
494 foreach my $i (0..$#$buf) {
496 if ($l =~ /^author .* (\d+ [\+-]?\d+)$/) {
497 $buf->[$i] = "author <> $1\n";
498 } elsif ($l =~ /^data (\d+)/) {
499 $buf->[$i++] = "data " . length($cmt_msg) . "\n";
500 $buf->[$i] = $cmt_msg;
507 my ($self, $purge) = @_;
508 my $tmp = "refs/heads/purge-".((keys %$purge)[0]);
509 my $old = $self->{'ref'};
510 my $git = $self->{git};
511 my @export = (qw(fast-export --no-data --use-done-feature), $old);
512 my $rd = $git->popen(@export);
513 my ($r, $w) = $self->gfi_start;
518 my $tree = $self->{-tree};
520 if (/^reset (?:.+)/) {
521 push @buf, "reset $tmp\n";
522 } elsif (/^commit (?:.+)/) {
524 $w->print(@buf) or wfail;
527 push @buf, "commit $tmp\n";
528 } elsif (/^data (\d+)/) {
529 # only commit message, so $len is small:
530 my $len = $1; # + 1 for trailing "\n"
532 my $n = read($rd, my $buf, $len) or die "read: $!";
533 $len == $n or die "short read ($n < $len)";
535 } elsif (/^M 100644 ([a-f0-9]+) (\w+)/) {
536 my ($oid, $path) = ($1, $2);
538 if ($purge->{$oid}) {
540 my $cmd = "M 100644 inline $path\ndata 0\n\n";
545 } elsif (/^D (\w+)/) {
547 push @buf, $_ if $tree->{$path};
548 } elsif ($_ eq "\n") {
550 my $out = join('', @buf);
552 warn "purge rewriting\n", $out, "\n";
553 clean_purge_buffer(\@oids, \@buf);
556 $w->print(@buf, "\n") or wfail;
558 } elsif ($_ eq "done\n") {
560 } elsif (/^mark :(\d+)$/) {
567 close $rd or die "close fast-export failed: $?";
569 $w->print(@buf) or wfail;
571 die 'done\n not seen from fast-export' unless $done;
572 chomp(my $cmt = $self->get_mark(":$mark")) if $npurge;
573 $self->{nchg} = 0; # prevent _update_git_info until update-ref:
575 my @git = ('git', "--git-dir=$git->{git_dir}");
577 run_die([@git, qw(update-ref), $old, $tmp]) if $npurge;
579 run_die([@git, qw(update-ref -d), $tmp]);
581 return if $npurge == 0;
583 run_die([@git, qw(-c gc.reflogExpire=now gc --prune=all)]);
585 foreach my $oid (keys %$purge) {
586 my @info = $git->check($oid);
588 warn "$oid not purged\n";
592 _update_git_info($self, 0);
593 die "Failed to purge $err object(s)\n" if $err;
603 PublicInbox::Import - message importer for public-inbox v1 inboxes
612 use PublicInbox::Git;
613 use PublicInbox::Import;
615 chomp(my $git_dir = `git rev-parse --git-dir`);
616 $git_dir or die "GIT_DIR= must be specified\n";
617 my $git = PublicInbox::Git->new($git_dir);
618 my @committer = ('inbox', 'inbox@example.org');
619 my $im = PublicInbox::Import->new($git, @committer);
622 my $message = "From: <u\@example.org>\n".
623 "Subject: test message \n" .
624 "Date: Thu, 01 Jan 1970 00:00:00 +0000\n" .
625 "Message-ID: <m\@example.org>\n".
627 my $parsed = Email::MIME->new($message);
628 my $ret = $im->add($parsed);
631 $parsed->header_obj->header_raw('Message-ID'), "\n";
633 print "imported at mark $ret\n";
637 # to remove a message
638 my $junk = Email::MIME->new($message);
639 my ($mark, $orig) = $im->remove($junk);
640 if ($mark eq 'MISSING') {
642 } elsif ($mark eq 'MISMATCH') {
643 print "Message exists but does not match\n\n",
644 $orig->as_string, "\n",;
646 print "removed at mark $mark\n\n",
647 $orig->as_string, "\n";
653 An importer and remover for public-inboxes which takes L<Email::MIME>
654 messages as input and stores them in a git repository as
655 documented in L<https://public-inbox.org/public-inbox-v1-format.txt>,
656 except it does not allow duplicate Message-IDs.
658 It requires L<git(1)> and L<git-fast-import(1)> to be installed.
666 my $im = PublicInbox::Import->new($git, @committer);
668 Initialize a new PublicInbox::Import object.
672 my $parsed = Email::MIME->new($message);
675 Adds a message to to the git repository. This will acquire
676 C<$GIT_DIR/ssoma.lock> and start L<git-fast-import(1)> if necessary.
678 Messages added will not be visible to other processes until L</done>
679 is called, but L</remove> may be called on them.
683 my $junk = Email::MIME->new($message);
684 my ($code, $orig) = $im->remove($junk);
686 Removes a message from the repository. On success, it returns
687 a ':'-prefixed numeric code representing the git-fast-import
688 mark and the original messages as an Email::MIME object.
689 If the message could not be found, the code is "MISSING"
690 and the original message is undef. If there is a mismatch where
691 the "Message-ID" is matched but the subject and body do not match,
692 the returned code is "MISMATCH" and the conflicting message
697 Finalizes the L<git-fast-import(1)> and unlocks the repository.
698 Calling this is required to finalize changes to a repository.
706 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
708 The mail archives are hosted at L<https://public-inbox.org/meta/>
712 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
714 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>