1 # Copyright (C) 2016-2018 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 and public-inbox-learn,
6 # not the WWW or NNTP code which only requires read-only access.
7 package PublicInbox::Import;
10 use base qw(PublicInbox::Lock);
11 use PublicInbox::Spawn qw(spawn);
12 use PublicInbox::MID qw(mids mid_mime mid2path);
13 use PublicInbox::Address;
14 use PublicInbox::MsgTime qw(msg_timestamp msg_datestamp);
15 use PublicInbox::ContentId qw(content_digest);
17 use POSIX qw(strftime);
20 my ($class, $git, $name, $email, $ibx) = @_;
21 my $ref = 'refs/heads/master';
23 $ref = $ibx->{ref_head} || 'refs/heads/master';
24 $name ||= $ibx->{name};
25 $email ||= $ibx->{-primary_address};
29 ident => "$name <$email>",
33 path_type => '2/38', # or 'v2'
34 lock_path => "$git->{git_dir}/ssoma.lock", # v2 changes this
39 # idempotent start function
43 return ($self->{in}, $self->{out}) if $self->{pid};
45 my ($in_r, $in_w, $out_r, $out_w);
46 pipe($in_r, $in_w) or die "pipe failed: $!";
47 pipe($out_r, $out_w) or die "pipe failed: $!";
48 my $git = $self->{git};
53 my $ref = $self->{ref};
54 chomp($self->{tip} = $git->qx(qw(rev-parse --revs-only), $ref));
55 if ($self->{path_type} ne '2/38' && $self->{tip}) {
57 my @tree = $git->qx(qw(ls-tree -r -z --name-only), $ref);
59 $self->{-tree} = { map { $_ => 1 } @tree };
62 my $git_dir = $git->{git_dir};
63 my @cmd = ('git', "--git-dir=$git_dir", qw(fast-import
64 --quiet --done --date-format=raw));
65 my $rdr = { 0 => fileno($out_r), 1 => fileno($in_w) };
66 my $pid = spawn(\@cmd, undef, $rdr);
67 die "spawn fast-import failed: $!" unless defined $pid;
70 $self->{out} = $out_w;
73 binmode $out_w, ':raw' or die "binmode :raw failed: $!";
74 binmode $in_r, ':raw' or die "binmode :raw failed: $!";
78 sub wfail () { die "write to fast-import failed: $!" }
80 sub now_raw () { time . ' +0000' }
84 my $b = $mime->body_raw;
85 $b =~ s/(\r?\n)+\z//s;
89 # only used for v1 (ssoma) inboxes
90 sub _check_path ($$$$) {
91 my ($r, $w, $tip, $path) = @_;
93 print $w "ls $tip $path\n" or wfail;
95 defined(my $info = <$r>) or die "EOF from fast-import: $!";
96 $info =~ /\Amissing / ? undef : $info;
100 my ($r, $w, $oid) = @_;
101 print $w "cat-blob $oid\n" or wfail;
104 defined $info or die "EOF from fast-import / cat-blob: $!";
105 $info =~ /\A[a-f0-9]{40} blob (\d+)\n\z/ or return;
111 $n = read($r, $buf, $left, $offset);
112 defined($n) or die "read cat-blob failed: $!";
113 $n == 0 and die 'fast-export (cat-blob) died';
117 $n = read($r, my $lf, 1);
118 defined($n) or die "read final byte of cat-blob failed: $!";
119 die "bad read on final byte: <$lf>" if $lf ne "\n";
121 # fixup some bugginess in old versions:
122 $buf =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
127 my ($self, $oid) = @_;
128 my ($r, $w) = $self->gfi_start;
129 _cat_blob($r, $w, $oid);
132 sub check_remove_v1 {
133 my ($r, $w, $tip, $path, $mime) = @_;
135 my $info = _check_path($r, $w, $tip, $path) or return ('MISSING',undef);
136 $info =~ m!\A100644 blob ([a-f0-9]{40})\t!s or die "not blob: $info";
138 my $msg = _cat_blob($r, $w, $oid) or die "BUG: cat-blob $1 failed";
139 my $cur = PublicInbox::MIME->new($msg);
140 my $cur_s = $cur->header('Subject');
141 $cur_s = '' unless defined $cur_s;
142 my $cur_m = $mime->header('Subject');
143 $cur_m = '' unless defined $cur_m;
144 if ($cur_s ne $cur_m || norm_body($cur) ne norm_body($mime)) {
145 return ('MISMATCH', $cur);
152 return unless $self->{pid};
153 print { $self->{out} } "checkpoint\n" or wfail;
158 my ($self, $msg) = @_;
159 return unless $self->{pid};
160 print { $self->{out} } "progress $msg\n" or wfail;
161 $self->{in}->getline eq "progress $msg\n" or die
162 "progress $msg not received\n";
166 sub _update_git_info ($$) {
167 my ($self, $do_gc) = @_;
168 # for compatibility with existing ssoma installations
169 # we can probably remove this entirely by 2020
170 my $git_dir = $self->{git}->{git_dir};
171 my @cmd = ('git', "--git-dir=$git_dir");
172 my $index = "$git_dir/ssoma.index";
173 if (-e $index && !$ENV{FAST}) {
174 my $env = { GIT_INDEX_FILE => $index };
175 run_die([@cmd, qw(read-tree -m -v -i), $self->{ref}], $env);
177 run_die([@cmd, 'update-server-info'], undef);
178 ($self->{path_type} eq '2/38') and eval {
179 require PublicInbox::SearchIdx;
180 my $inbox = $self->{inbox} || $git_dir;
181 my $s = PublicInbox::SearchIdx->new($inbox);
182 $s->index_sync({ ref => $self->{ref} });
184 eval { run_die([@cmd, qw(gc --auto)], undef) } if $do_gc;
190 # For safety, we ensure git checkpoint is complete before because
191 # the data in git is still more important than what is in Xapian
192 # in v2. Performance may be gained by delaying the ->progress
193 # call but we lose safety
196 $self->progress('checkpoint');
197 _update_git_info($self, 0);
204 my ($self, $mark) = @_;
205 die "not active\n" unless $self->{pid};
206 my ($r, $w) = $self->gfi_start;
207 print $w "get-mark $mark\n" or wfail;
208 defined(my $oid = <$r>) or die "get-mark failed, need git 2.6.0+\n";
213 # returns undef on non-existent
214 # ('MISMATCH', Email::MIME) on mismatch
215 # (:MARK, Email::MIME) on success
217 # v2 callers should check with Xapian before calling this as
218 # it is not idempotent.
220 my ($self, $mime, $msg) = @_; # mime = Email::MIME
222 my $path_type = $self->{path_type};
223 my ($path, $err, $cur, $blob);
225 my ($r, $w) = $self->gfi_start;
226 my $tip = $self->{tip};
227 if ($path_type eq '2/38') {
228 $path = mid2path(v1_mid0($mime));
229 ($err, $cur) = check_remove_v1($r, $w, $tip, $path, $mime);
230 return ($err, $cur) if $err;
233 if (ref($mime) eq 'SCALAR') { # optimization used by V2Writable
235 } else { # XXX should not be necessary:
236 my $str = $mime->as_string;
239 my $len = length($$sref);
240 $blob = $self->{mark}++;
241 print $w "blob\nmark :$blob\ndata $len\n",
242 $$sref, "\n" or wfail;
245 my $ref = $self->{ref};
246 my $commit = $self->{mark}++;
247 my $parent = $tip =~ /\A:/ ? $tip : undef;
249 print $w "reset $ref\n" or wfail;
251 my $ident = $self->{ident};
254 my $len = length($msg) + 1;
255 print $w "commit $ref\nmark :$commit\n",
256 "author $ident $now\n",
257 "committer $ident $now\n",
258 "data $len\n$msg\n\n",
259 'from ', ($parent ? $parent : $tip), "\n" or wfail;
261 print $w "D $path\n\n" or wfail;
263 clean_tree_v2($self, $w, 'd');
264 print $w "M 100644 :$blob d\n\n" or wfail;
267 (($self->{tip} = ":$commit"), $cur);
271 my ($ts, $zone) = @_;
272 $ts = 0 if $ts < 0; # git uses unsigned times
276 sub extract_author_info ($) {
280 my $from = $mime->header('From');
281 my ($email) = PublicInbox::Address::emails($from);
282 my ($name) = PublicInbox::Address::names($from);
283 if (!defined($name) || !defined($email)) {
284 $sender = $mime->header('Sender');
285 if (!defined($name)) {
286 ($name) = PublicInbox::Address::names($sender);
288 if (!defined($email)) {
289 ($email) = PublicInbox::Address::emails($sender);
292 if (defined $email) {
293 # quiet down wide character warnings with utf8::encode
294 utf8::encode($email);
297 warn "no email in From: $from or Sender: $sender\n";
300 # git gets confused with:
301 # "'A U Thor <u@example.com>' via foo" <foo@example.com>
303 # <CAD0k6qSUYANxbjjbE4jTW4EeVwOYgBD=bXkSu=akiYC_CB7Ffw@mail.gmail.com>
309 warn "no name in From: $from or Sender: $sender\n";
314 # kill potentially confusing/misleading headers
315 sub drop_unwanted_headers ($) {
318 $mime->header_set($_) for qw(bytes lines content-length status);
319 $mime->header_set($_) for @PublicInbox::MDA::BAD_HEADERS;
322 # used by V2Writable, too
323 sub append_mid ($$) {
324 my ($hdr, $mid0) = @_;
325 # @cur is likely empty if we need to call this sub, but it could
326 # have random unparseable crap which we'll preserve, too.
327 my @cur = $hdr->header_raw('Message-ID');
328 $hdr->header_set('Message-ID', @cur, "<$mid0>");
333 my $hdr = $mime->header_obj;
334 my $mids = mids($hdr);
336 if (!scalar(@$mids)) { # spam often has no Message-Id
337 my $mid0 = digest2mid(content_digest($mime), $hdr);
338 append_mid($hdr, $mid0);
343 sub clean_tree_v2 ($$$) {
344 my ($self, $w, $keep) = @_;
345 my $tree = $self->{-tree} or return; #v2 only
346 delete $tree->{$keep};
347 foreach (keys %$tree) {
348 print $w "D $_\n" or wfail;
350 %$tree = ($keep => 1);
353 # returns undef on duplicate
354 # returns the :MARK of the most recent commit
356 my ($self, $mime, $check_cb) = @_; # mime = Email::MIME
358 my ($name, $email) = extract_author_info($mime);
359 my $hdr = $mime->header_obj;
360 my @at = msg_datestamp($hdr);
361 my @ct = msg_timestamp($hdr);
362 my $author_time_raw = git_timestamp(@at);
363 my $commit_time_raw = git_timestamp(@ct);
364 my $subject = $mime->header('Subject');
365 $subject = '(no subject)' unless defined $subject;
366 my $path_type = $self->{path_type};
369 if ($path_type eq '2/38') {
370 $path = mid2path(v1_mid0($mime));
371 } else { # v2 layout, one file:
375 my ($r, $w) = $self->gfi_start;
376 my $tip = $self->{tip};
377 if ($path_type eq '2/38') {
378 _check_path($r, $w, $tip, $path) and return;
381 drop_unwanted_headers($mime);
385 $mime = $check_cb->($mime) or return;
388 my $blob = $self->{mark}++;
389 my $str = $mime->as_string;
390 my $n = length($str);
391 $self->{bytes_added} += $n;
392 print $w "blob\nmark :$blob\ndata ", $n, "\n" or wfail;
393 print $w $str, "\n" or wfail;
395 # v2: we need this for Xapian
396 if ($self->{want_object_info}) {
397 my $oid = $self->get_mark(":$blob");
398 $self->{last_object} = [ $oid, $n, \$str ];
400 my $ref = $self->{ref};
401 my $commit = $self->{mark}++;
402 my $parent = $tip =~ /\A:/ ? $tip : undef;
405 print $w "reset $ref\n" or wfail;
408 utf8::encode($subject);
409 print $w "commit $ref\nmark :$commit\n",
410 "author $name <$email> $author_time_raw\n",
411 "committer $self->{ident} $commit_time_raw\n" or wfail;
412 print $w "data ", (length($subject) + 1), "\n",
413 $subject, "\n\n" or wfail;
415 print $w 'from ', ($parent ? $parent : $tip), "\n" or wfail;
417 clean_tree_v2($self, $w, $path);
418 print $w "M 100644 :$blob $path\n\n" or wfail;
420 $self->{tip} = ":$commit";
424 my ($cmd, $env, $rdr) = @_;
425 my $pid = spawn($cmd, $env, $rdr);
426 defined $pid or die "spawning ".join(' ', @$cmd)." failed: $!";
427 waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
428 $? == 0 or die join(' ', @$cmd) . " failed: $?\n";
433 my $w = delete $self->{out} or return;
434 my $r = delete $self->{in} or die 'BUG: missing {in} when done';
435 print $w "done\n" or wfail;
436 my $pid = delete $self->{pid} or die 'BUG: missing {pid} when done';
437 waitpid($pid, 0) == $pid or die 'fast-import did not finish';
438 $? == 0 or die "fast-import failed: $?";
440 _update_git_info($self, 1) if delete $self->{nchg};
444 $self->{git}->cleanup;
449 foreach my $f (qw(in out)) {
450 close $self->{$f} or die "failed to close import[$f]: $!\n";
454 sub digest2mid ($$) {
455 my ($dig, $hdr) = @_;
456 my $b64 = $dig->clone->b64digest;
457 # Make our own URLs nicer:
458 # See "Base 64 Encoding with URL and Filename Safe Alphabet" in RFC4648
461 # Add a date prefix to prevent a leading '-' in case that trips
462 # up some tools (e.g. if a Message-ID were a expected as a
464 my $dt = msg_datestamp($hdr);
465 $dt = POSIX::strftime('%Y%m%d%H%M%S', gmtime($dt));
469 sub clean_purge_buffer {
470 my ($oids, $buf) = @_;
471 my $cmt_msg = 'purged '.join(' ',@$oids)."\n";
474 foreach my $i (0..$#$buf) {
476 if ($l =~ /^author .* (\d+ [\+-]?\d+)$/) {
477 $buf->[$i] = "author <> $1\n";
478 } elsif ($l =~ /^data (\d+)/) {
479 $buf->[$i++] = "data " . length($cmt_msg) . "\n";
480 $buf->[$i] = $cmt_msg;
487 my ($self, $purge) = @_;
488 my $tmp = "refs/heads/purge-".((keys %$purge)[0]);
489 my $old = $self->{'ref'};
490 my $git = $self->{git};
491 my @export = (qw(fast-export --no-data --use-done-feature), $old);
492 my ($rd, $pid) = $git->popen(@export);
493 my ($r, $w) = $self->gfi_start;
498 my $tree = $self->{-tree};
500 if (/^reset (?:.+)/) {
501 push @buf, "reset $tmp\n";
502 } elsif (/^commit (?:.+)/) {
504 $w->print(@buf) or wfail;
507 push @buf, "commit $tmp\n";
508 } elsif (/^data (\d+)/) {
509 # only commit message, so $len is small:
510 my $len = $1; # + 1 for trailing "\n"
512 my $n = read($rd, my $buf, $len) or die "read: $!";
513 $len == $n or die "short read ($n < $len)";
515 } elsif (/^M 100644 ([a-f0-9]+) (\w+)/) {
516 my ($oid, $path) = ($1, $2);
517 if ($purge->{$oid}) {
519 delete $tree->{$path};
524 } elsif (/^D (\w+)/) {
526 push @buf, $_ if $tree->{$path};
527 } elsif ($_ eq "\n") {
529 my $out = join('', @buf);
531 warn "purge rewriting\n", $out, "\n";
532 clean_purge_buffer(\@oids, \@buf);
535 $w->print(@buf, "\n") or wfail;
537 } elsif ($_ eq "done\n") {
539 } elsif (/^mark :(\d+)$/) {
547 $w->print(@buf) or wfail;
549 die 'done\n not seen from fast-export' unless $done;
550 chomp(my $cmt = $self->get_mark(":$mark")) if $npurge;
551 $self->{nchg} = 0; # prevent _update_git_info until update-ref:
553 my @git = ('git', "--git-dir=$git->{git_dir}");
555 run_die([@git, qw(update-ref), $old, $tmp]) if $npurge;
557 run_die([@git, qw(update-ref -d), $tmp]);
559 return if $npurge == 0;
561 run_die([@git, qw(-c gc.reflogExpire=now gc --prune=all)]);
563 foreach my $oid (keys %$purge) {
564 my @info = $git->check($oid);
566 warn "$oid not purged\n";
570 _update_git_info($self, 0);
571 die "Failed to purge $err object(s)\n" if $err;
581 PublicInbox::Import - message importer for public-inbox
590 use PublicInbox::Git;
591 use PublicInbox::Import;
593 chomp(my $git_dir = `git rev-parse --git-dir`);
594 $git_dir or die "GIT_DIR= must be specified\n";
595 my $git = PublicInbox::Git->new($git_dir);
596 my @committer = ('inbox', 'inbox@example.org');
597 my $im = PublicInbox::Import->new($git, @committer);
600 my $message = "From: <u\@example.org>\n".
601 "Subject: test message \n" .
602 "Date: Thu, 01 Jan 1970 00:00:00 +0000\n" .
603 "Message-ID: <m\@example.org>\n".
605 my $parsed = Email::MIME->new($message);
606 my $ret = $im->add($parsed);
609 $parsed->header_obj->header_raw('Message-ID'), "\n";
611 print "imported at mark $ret\n";
615 # to remove a message
616 my $junk = Email::MIME->new($message);
617 my ($mark, $orig) = $im->remove($junk);
618 if ($mark eq 'MISSING') {
620 } elsif ($mark eq 'MISMATCH') {
621 print "Message exists but does not match\n\n",
622 $orig->as_string, "\n",;
624 print "removed at mark $mark\n\n",
625 $orig->as_string, "\n";
631 An importer and remover for public-inboxes which takes L<Email::MIME>
632 messages as input and stores them in a ssoma repository as
633 documented in L<https://ssoma.public-inbox.org/ssoma_repository.txt>,
634 except it does not allow duplicate Message-IDs.
636 It requires L<git(1)> and L<git-fast-import(1)> to be installed.
644 my $im = PublicInbox::Import->new($git, @committer);
646 Initialize a new PublicInbox::Import object.
650 my $parsed = Email::MIME->new($message);
653 Adds a message to to the git repository. This will acquire
654 C<$GIT_DIR/ssoma.lock> and start L<git-fast-import(1)> if necessary.
656 Messages added will not be visible to other processes until L</done>
657 is called, but L</remove> may be called on them.
661 my $junk = Email::MIME->new($message);
662 my ($code, $orig) = $im->remove($junk);
664 Removes a message from the repository. On success, it returns
665 a ':'-prefixed numeric code representing the git-fast-import
666 mark and the original messages as an Email::MIME object.
667 If the message could not be found, the code is "MISSING"
668 and the original message is undef. If there is a mismatch where
669 the "Message-ID" is matched but the subject and body do not match,
670 the returned code is "MISMATCH" and the conflicting message
675 Finalizes the L<git-fast-import(1)> and unlocks the repository.
676 Calling this is required to finalize changes to a repository.
684 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
686 The mail archives are hosted at L<https://public-inbox.org/meta/>
690 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
692 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>