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 my ($class, $git, $name, $email, $ibx) = @_;
22 my $ref = 'refs/heads/master';
24 $ref = $ibx->{ref_head} || 'refs/heads/master';
25 $name ||= $ibx->{name};
26 $email ||= $ibx->{-primary_address};
30 ident => "$name <$email>",
34 path_type => '2/38', # or 'v2'
35 lock_path => "$git->{git_dir}/ssoma.lock", # v2 changes this
40 # idempotent start function
44 return ($self->{in}, $self->{out}) if $self->{pid};
46 my ($in_r, $in_w, $out_r, $out_w);
47 pipe($in_r, $in_w) or die "pipe failed: $!";
48 pipe($out_r, $out_w) or die "pipe failed: $!";
49 my $git = $self->{git};
54 my $ref = $self->{ref};
55 chomp($self->{tip} = $git->qx(qw(rev-parse --revs-only), $ref));
56 if ($self->{path_type} ne '2/38' && $self->{tip}) {
58 my @tree = $git->qx(qw(ls-tree -r -z --name-only), $ref);
60 $self->{-tree} = { map { $_ => 1 } @tree };
63 my $git_dir = $git->{git_dir};
64 my @cmd = ('git', "--git-dir=$git_dir", qw(fast-import
65 --quiet --done --date-format=raw));
66 my $rdr = { 0 => fileno($out_r), 1 => fileno($in_w) };
67 my $pid = spawn(\@cmd, undef, $rdr);
68 die "spawn fast-import failed: $!" unless defined $pid;
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 (\d+)\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'], undef);
179 ($self->{path_type} eq '2/38') and eval {
180 require PublicInbox::SearchIdx;
181 my $inbox = $self->{inbox} || $git_dir;
182 my $s = PublicInbox::SearchIdx->new($inbox);
183 $s->index_sync({ ref => $self->{ref} });
185 eval { run_die([@cmd, qw(gc --auto)], undef) } 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_author_info ($) {
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 # quiet down wide character warnings with utf8::encode
297 utf8::encode($email);
300 warn "no email in From: $from or Sender: $sender\n";
303 # git gets confused with:
304 # "'A U Thor <u@example.com>' via foo" <foo@example.com>
306 # <CAD0k6qSUYANxbjjbE4jTW4EeVwOYgBD=bXkSu=akiYC_CB7Ffw@mail.gmail.com>
312 warn "no name in From: $from or Sender: $sender\n";
317 # kill potentially confusing/misleading headers
318 sub drop_unwanted_headers ($) {
321 $mime->header_set($_) for qw(bytes lines content-length status);
322 $mime->header_set($_) for @PublicInbox::MDA::BAD_HEADERS;
325 # used by V2Writable, too
326 sub append_mid ($$) {
327 my ($hdr, $mid0) = @_;
328 # @cur is likely empty if we need to call this sub, but it could
329 # have random unparseable crap which we'll preserve, too.
330 my @cur = $hdr->header_raw('Message-ID');
331 $hdr->header_set('Message-ID', @cur, "<$mid0>");
336 my $hdr = $mime->header_obj;
337 my $mids = mids($hdr);
339 if (!scalar(@$mids)) { # spam often has no Message-Id
340 my $mid0 = digest2mid(content_digest($mime), $hdr);
341 append_mid($hdr, $mid0);
346 sub clean_tree_v2 ($$$) {
347 my ($self, $w, $keep) = @_;
348 my $tree = $self->{-tree} or return; #v2 only
349 delete $tree->{$keep};
350 foreach (keys %$tree) {
351 print $w "D $_\n" or wfail;
353 %$tree = ($keep => 1);
356 # returns undef on duplicate
357 # returns the :MARK of the most recent commit
359 my ($self, $mime, $check_cb) = @_; # mime = Email::MIME
361 my ($name, $email) = extract_author_info($mime);
362 my $hdr = $mime->header_obj;
363 my @at = msg_datestamp($hdr);
364 my @ct = msg_timestamp($hdr);
365 my $author_time_raw = git_timestamp(@at);
366 my $commit_time_raw = git_timestamp(@ct);
367 my $subject = $mime->header('Subject');
368 $subject = '(no subject)' unless defined $subject;
369 my $path_type = $self->{path_type};
372 if ($path_type eq '2/38') {
373 $path = mid2path(v1_mid0($mime));
374 } else { # v2 layout, one file:
378 my ($r, $w) = $self->gfi_start;
379 my $tip = $self->{tip};
380 if ($path_type eq '2/38') {
381 _check_path($r, $w, $tip, $path) and return;
384 drop_unwanted_headers($mime);
388 $mime = $check_cb->($mime) or return;
391 my $blob = $self->{mark}++;
392 my $str = $mime->as_string;
393 my $n = length($str);
394 $self->{bytes_added} += $n;
395 print $w "blob\nmark :$blob\ndata ", $n, "\n" or wfail;
396 print $w $str, "\n" or wfail;
398 # v2: we need this for Xapian
399 if ($self->{want_object_info}) {
400 my $oid = $self->get_mark(":$blob");
401 $self->{last_object} = [ $oid, $n, \$str ];
403 my $ref = $self->{ref};
404 my $commit = $self->{mark}++;
405 my $parent = $tip =~ /\A:/ ? $tip : undef;
408 print $w "reset $ref\n" or wfail;
411 # Mime decoding can create nulls replace them with spaces to protect git
412 $subject =~ tr/\0/ /;
413 utf8::encode($subject);
414 print $w "commit $ref\nmark :$commit\n",
415 "author $name <$email> $author_time_raw\n",
416 "committer $self->{ident} $commit_time_raw\n" or wfail;
417 print $w "data ", (length($subject) + 1), "\n",
418 $subject, "\n\n" or wfail;
420 print $w 'from ', ($parent ? $parent : $tip), "\n" or wfail;
422 clean_tree_v2($self, $w, $path);
423 print $w "M 100644 :$blob $path\n\n" or wfail;
425 $self->{tip} = ":$commit";
429 my ($cmd, $env, $rdr) = @_;
430 my $pid = spawn($cmd, $env, $rdr);
431 defined $pid or die "spawning ".join(' ', @$cmd)." failed: $!";
432 waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
433 $? == 0 or die join(' ', @$cmd) . " failed: $?\n";
438 my $w = delete $self->{out} or return;
439 my $r = delete $self->{in} or die 'BUG: missing {in} when done';
440 print $w "done\n" or wfail;
441 my $pid = delete $self->{pid} or die 'BUG: missing {pid} when done';
442 waitpid($pid, 0) == $pid or die 'fast-import did not finish';
443 $? == 0 or die "fast-import failed: $?";
445 _update_git_info($self, 1) if delete $self->{nchg};
449 $self->{git}->cleanup;
454 foreach my $f (qw(in out)) {
455 next unless defined($self->{$f});
456 close $self->{$f} or die "failed to close import[$f]: $!\n";
460 sub digest2mid ($$) {
461 my ($dig, $hdr) = @_;
462 my $b64 = $dig->clone->b64digest;
463 # Make our own URLs nicer:
464 # See "Base 64 Encoding with URL and Filename Safe Alphabet" in RFC4648
467 # Add a date prefix to prevent a leading '-' in case that trips
468 # up some tools (e.g. if a Message-ID were a expected as a
470 my $dt = msg_datestamp($hdr);
471 $dt = POSIX::strftime('%Y%m%d%H%M%S', gmtime($dt));
475 sub clean_purge_buffer {
476 my ($oids, $buf) = @_;
477 my $cmt_msg = 'purged '.join(' ',@$oids)."\n";
480 foreach my $i (0..$#$buf) {
482 if ($l =~ /^author .* (\d+ [\+-]?\d+)$/) {
483 $buf->[$i] = "author <> $1\n";
484 } elsif ($l =~ /^data (\d+)/) {
485 $buf->[$i++] = "data " . length($cmt_msg) . "\n";
486 $buf->[$i] = $cmt_msg;
493 my ($self, $purge) = @_;
494 my $tmp = "refs/heads/purge-".((keys %$purge)[0]);
495 my $old = $self->{'ref'};
496 my $git = $self->{git};
497 my @export = (qw(fast-export --no-data --use-done-feature), $old);
498 my ($rd, $pid) = $git->popen(@export);
499 my ($r, $w) = $self->gfi_start;
504 my $tree = $self->{-tree};
506 if (/^reset (?:.+)/) {
507 push @buf, "reset $tmp\n";
508 } elsif (/^commit (?:.+)/) {
510 $w->print(@buf) or wfail;
513 push @buf, "commit $tmp\n";
514 } elsif (/^data (\d+)/) {
515 # only commit message, so $len is small:
516 my $len = $1; # + 1 for trailing "\n"
518 my $n = read($rd, my $buf, $len) or die "read: $!";
519 $len == $n or die "short read ($n < $len)";
521 } elsif (/^M 100644 ([a-f0-9]+) (\w+)/) {
522 my ($oid, $path) = ($1, $2);
524 if ($purge->{$oid}) {
526 my $cmd = "M 100644 inline $path\ndata 0\n\n";
531 } elsif (/^D (\w+)/) {
533 push @buf, $_ if $tree->{$path};
534 } elsif ($_ eq "\n") {
536 my $out = join('', @buf);
538 warn "purge rewriting\n", $out, "\n";
539 clean_purge_buffer(\@oids, \@buf);
542 $w->print(@buf, "\n") or wfail;
544 } elsif ($_ eq "done\n") {
546 } elsif (/^mark :(\d+)$/) {
554 $w->print(@buf) or wfail;
556 die 'done\n not seen from fast-export' unless $done;
557 chomp(my $cmt = $self->get_mark(":$mark")) if $npurge;
558 $self->{nchg} = 0; # prevent _update_git_info until update-ref:
560 my @git = ('git', "--git-dir=$git->{git_dir}");
562 run_die([@git, qw(update-ref), $old, $tmp]) if $npurge;
564 run_die([@git, qw(update-ref -d), $tmp]);
566 return if $npurge == 0;
568 run_die([@git, qw(-c gc.reflogExpire=now gc --prune=all)]);
570 foreach my $oid (keys %$purge) {
571 my @info = $git->check($oid);
573 warn "$oid not purged\n";
577 _update_git_info($self, 0);
578 die "Failed to purge $err object(s)\n" if $err;
588 PublicInbox::Import - message importer for public-inbox
597 use PublicInbox::Git;
598 use PublicInbox::Import;
600 chomp(my $git_dir = `git rev-parse --git-dir`);
601 $git_dir or die "GIT_DIR= must be specified\n";
602 my $git = PublicInbox::Git->new($git_dir);
603 my @committer = ('inbox', 'inbox@example.org');
604 my $im = PublicInbox::Import->new($git, @committer);
607 my $message = "From: <u\@example.org>\n".
608 "Subject: test message \n" .
609 "Date: Thu, 01 Jan 1970 00:00:00 +0000\n" .
610 "Message-ID: <m\@example.org>\n".
612 my $parsed = Email::MIME->new($message);
613 my $ret = $im->add($parsed);
616 $parsed->header_obj->header_raw('Message-ID'), "\n";
618 print "imported at mark $ret\n";
622 # to remove a message
623 my $junk = Email::MIME->new($message);
624 my ($mark, $orig) = $im->remove($junk);
625 if ($mark eq 'MISSING') {
627 } elsif ($mark eq 'MISMATCH') {
628 print "Message exists but does not match\n\n",
629 $orig->as_string, "\n",;
631 print "removed at mark $mark\n\n",
632 $orig->as_string, "\n";
638 An importer and remover for public-inboxes which takes L<Email::MIME>
639 messages as input and stores them in a git repository as
640 documented in L<https://public-inbox.org/public-inbox-v1-format.txt>,
641 except it does not allow duplicate Message-IDs.
643 It requires L<git(1)> and L<git-fast-import(1)> to be installed.
651 my $im = PublicInbox::Import->new($git, @committer);
653 Initialize a new PublicInbox::Import object.
657 my $parsed = Email::MIME->new($message);
660 Adds a message to to the git repository. This will acquire
661 C<$GIT_DIR/ssoma.lock> and start L<git-fast-import(1)> if necessary.
663 Messages added will not be visible to other processes until L</done>
664 is called, but L</remove> may be called on them.
668 my $junk = Email::MIME->new($message);
669 my ($code, $orig) = $im->remove($junk);
671 Removes a message from the repository. On success, it returns
672 a ':'-prefixed numeric code representing the git-fast-import
673 mark and the original messages as an Email::MIME object.
674 If the message could not be found, the code is "MISSING"
675 and the original message is undef. If there is a mismatch where
676 the "Message-ID" is matched but the subject and body do not match,
677 the returned code is "MISMATCH" and the conflicting message
682 Finalizes the L<git-fast-import(1)> and unlocks the repository.
683 Calling this is required to finalize changes to a repository.
691 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
693 The mail archives are hosted at L<https://public-inbox.org/meta/>
697 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
699 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>