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);
19 my ($class, $git, $name, $email, $ibx) = @_;
20 my $ref = 'refs/heads/master';
22 $ref = $ibx->{ref_head} || 'refs/heads/master';
23 $name ||= $ibx->{name};
24 $email ||= $ibx->{-primary_address};
28 ident => "$name <$email>",
32 path_type => '2/38', # or 'v2'
33 lock_path => "$git->{git_dir}/ssoma.lock", # v2 changes this
38 # idempotent start function
42 return ($self->{in}, $self->{out}) if $self->{pid};
44 my ($in_r, $in_w, $out_r, $out_w);
45 pipe($in_r, $in_w) or die "pipe failed: $!";
46 pipe($out_r, $out_w) or die "pipe failed: $!";
47 my $git = $self->{git};
52 my $ref = $self->{ref};
53 chomp($self->{tip} = $git->qx(qw(rev-parse --revs-only), $ref));
54 if ($self->{path_type} ne '2/38' && $self->{tip}) {
56 my @tree = $git->qx(qw(ls-tree -r -z --name-only), $ref);
58 $self->{-tree} = { map { $_ => 1 } @tree };
61 my $git_dir = $git->{git_dir};
62 my @cmd = ('git', "--git-dir=$git_dir", qw(fast-import
63 --quiet --done --date-format=raw));
64 my $rdr = { 0 => fileno($out_r), 1 => fileno($in_w) };
65 my $pid = spawn(\@cmd, undef, $rdr);
66 die "spawn fast-import failed: $!" unless defined $pid;
69 $self->{out} = $out_w;
72 binmode $out_w, ':raw' or die "binmode :raw failed: $!";
73 binmode $in_r, ':raw' or die "binmode :raw failed: $!";
77 sub wfail () { die "write to fast-import failed: $!" }
79 sub now_raw () { time . ' +0000' }
83 my $b = $mime->body_raw;
84 $b =~ s/(\r?\n)+\z//s;
88 # only used for v1 (ssoma) inboxes
89 sub _check_path ($$$$) {
90 my ($r, $w, $tip, $path) = @_;
92 print $w "ls $tip $path\n" or wfail;
94 defined(my $info = <$r>) or die "EOF from fast-import: $!";
95 $info =~ /\Amissing / ? undef : $info;
99 my ($r, $w, $tip, $path, $mime) = @_;
101 my $info = _check_path($r, $w, $tip, $path) or return ('MISSING',undef);
102 $info =~ m!\A100644 blob ([a-f0-9]{40})\t!s or die "not blob: $info";
105 print $w "cat-blob $blob\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
110 die "unexpected cat-blob response: $info";
116 $n = read($r, $buf, $left, $offset);
117 defined($n) or die "read cat-blob failed: $!";
118 $n == 0 and die 'fast-export (cat-blob) died';
122 $n = read($r, my $lf, 1);
123 defined($n) or die "read final byte of cat-blob failed: $!";
124 die "bad read on final byte: <$lf>" if $lf ne "\n";
125 my $cur = PublicInbox::MIME->new(\$buf);
126 my $cur_s = $cur->header('Subject');
127 $cur_s = '' unless defined $cur_s;
128 my $cur_m = $mime->header('Subject');
129 $cur_m = '' unless defined $cur_m;
130 if ($cur_s ne $cur_m || norm_body($cur) ne norm_body($mime)) {
131 return ('MISMATCH', $cur);
138 return unless $self->{pid};
139 print { $self->{out} } "checkpoint\n" or wfail;
144 my ($self, $msg) = @_;
145 return unless $self->{pid};
146 print { $self->{out} } "progress $msg\n" or wfail;
147 $self->{in}->getline eq "progress $msg\n" or die
148 "progress $msg not received\n";
152 sub _update_git_info ($$) {
153 my ($self, $do_gc) = @_;
154 # for compatibility with existing ssoma installations
155 # we can probably remove this entirely by 2020
156 my $git_dir = $self->{git}->{git_dir};
157 my @cmd = ('git', "--git-dir=$git_dir");
158 my $index = "$git_dir/ssoma.index";
159 if (-e $index && !$ENV{FAST}) {
160 my $env = { GIT_INDEX_FILE => $index };
161 run_die([@cmd, qw(read-tree -m -v -i), $self->{ref}], $env);
163 run_die([@cmd, 'update-server-info'], undef);
164 ($self->{path_type} eq '2/38') and eval {
165 require PublicInbox::SearchIdx;
166 my $inbox = $self->{inbox} || $git_dir;
167 my $s = PublicInbox::SearchIdx->new($inbox);
168 $s->index_sync({ ref => $self->{ref} });
170 eval { run_die([@cmd, qw(gc --auto)], undef) } if $do_gc;
176 # For safety, we ensure git checkpoint is complete before because
177 # the data in git is still more important than what is in Xapian
178 # in v2. Performance may be gained by delaying the ->progress
179 # call but we lose safety
182 $self->progress('checkpoint');
183 _update_git_info($self, 0);
190 my ($self, $mark) = @_;
191 die "not active\n" unless $self->{pid};
192 my ($r, $w) = $self->gfi_start;
193 print $w "get-mark $mark\n" or wfail;
194 defined(my $oid = <$r>) or die "get-mark failed, need git 2.6.0+\n";
199 # returns undef on non-existent
200 # ('MISMATCH', Email::MIME) on mismatch
201 # (:MARK, Email::MIME) on success
203 # v2 callers should check with Xapian before calling this as
204 # it is not idempotent.
206 my ($self, $mime, $msg) = @_; # mime = Email::MIME
208 my $path_type = $self->{path_type};
209 my ($path, $err, $cur, $blob);
211 my ($r, $w) = $self->gfi_start;
212 my $tip = $self->{tip};
213 if ($path_type eq '2/38') {
214 $path = mid2path(v1_mid0($mime));
215 ($err, $cur) = check_remove_v1($r, $w, $tip, $path, $mime);
216 return ($err, $cur) if $err;
219 if (ref($mime) eq 'SCALAR') { # optimization used by V2Writable
221 } else { # XXX should not be necessary:
222 my $str = $mime->as_string;
225 my $len = length($$sref);
226 $blob = $self->{mark}++;
227 print $w "blob\nmark :$blob\ndata $len\n",
228 $$sref, "\n" or wfail;
231 my $ref = $self->{ref};
232 my $commit = $self->{mark}++;
233 my $parent = $tip =~ /\A:/ ? $tip : undef;
235 print $w "reset $ref\n" or wfail;
237 my $ident = $self->{ident};
240 my $len = length($msg) + 1;
241 print $w "commit $ref\nmark :$commit\n",
242 "author $ident $now\n",
243 "committer $ident $now\n",
244 "data $len\n$msg\n\n",
245 'from ', ($parent ? $parent : $tip), "\n" or wfail;
247 print $w "D $path\n\n" or wfail;
249 clean_tree_v2($self, $w, 'd');
250 print $w "M 100644 :$blob d\n\n" or wfail;
253 (($self->{tip} = ":$commit"), $cur);
257 my ($ts, $zone) = @_;
258 $ts = 0 if $ts < 0; # git uses unsigned times
262 sub extract_author_info ($) {
266 my $from = $mime->header('From');
267 my ($email) = PublicInbox::Address::emails($from);
268 my ($name) = PublicInbox::Address::names($from);
269 if (!defined($name) || !defined($email)) {
270 $sender = $mime->header('Sender');
271 if (!defined($name)) {
272 ($name) = PublicInbox::Address::names($sender);
274 if (!defined($email)) {
275 ($email) = PublicInbox::Address::emails($sender);
278 if (defined $email) {
279 # quiet down wide character warnings with utf8::encode
280 utf8::encode($email);
283 warn "no email in From: $from or Sender: $sender\n";
286 # git gets confused with:
287 # "'A U Thor <u@example.com>' via foo" <foo@example.com>
289 # <CAD0k6qSUYANxbjjbE4jTW4EeVwOYgBD=bXkSu=akiYC_CB7Ffw@mail.gmail.com>
295 warn "no name in From: $from or Sender: $sender\n";
300 # kill potentially confusing/misleading headers
301 sub drop_unwanted_headers ($) {
304 $mime->header_set($_) for qw(bytes lines content-length status);
305 $mime->header_set($_) for @PublicInbox::MDA::BAD_HEADERS;
308 # used by V2Writable, too
309 sub append_mid ($$) {
310 my ($hdr, $mid0) = @_;
311 # @cur is likely empty if we need to call this sub, but it could
312 # have random unparseable crap which we'll preserve, too.
313 my @cur = $hdr->header_raw('Message-ID');
314 $hdr->header_set('Message-ID', @cur, "<$mid0>");
319 my $hdr = $mime->header_obj;
320 my $mids = mids($hdr);
322 if (!scalar(@$mids)) { # spam often has no Message-Id
323 my $mid0 = digest2mid(content_digest($mime));
324 append_mid($hdr, $mid0);
329 sub clean_tree_v2 ($$$) {
330 my ($self, $w, $keep) = @_;
331 my $tree = $self->{-tree} or return; #v2 only
332 delete $tree->{$keep};
333 foreach (keys %$tree) {
334 print $w "D $_\n" or wfail;
336 %$tree = ($keep => 1);
339 # returns undef on duplicate
340 # returns the :MARK of the most recent commit
342 my ($self, $mime, $check_cb) = @_; # mime = Email::MIME
344 my ($name, $email) = extract_author_info($mime);
345 my $hdr = $mime->header_obj;
346 my @at = msg_datestamp($hdr);
347 my @ct = msg_timestamp($hdr);
348 my $author_time_raw = git_timestamp(@at);
349 my $commit_time_raw = git_timestamp(@ct);
350 my $subject = $mime->header('Subject');
351 $subject = '(no subject)' unless defined $subject;
352 my $path_type = $self->{path_type};
355 if ($path_type eq '2/38') {
356 $path = mid2path(v1_mid0($mime));
357 } else { # v2 layout, one file:
361 my ($r, $w) = $self->gfi_start;
362 my $tip = $self->{tip};
363 if ($path_type eq '2/38') {
364 _check_path($r, $w, $tip, $path) and return;
367 drop_unwanted_headers($mime);
371 $mime = $check_cb->($mime) or return;
374 my $blob = $self->{mark}++;
375 my $str = $mime->as_string;
376 my $n = length($str);
377 $self->{bytes_added} += $n;
378 print $w "blob\nmark :$blob\ndata ", $n, "\n" or wfail;
379 print $w $str, "\n" or wfail;
381 # v2: we need this for Xapian
382 if ($self->{want_object_info}) {
383 my $oid = $self->get_mark(":$blob");
384 $self->{last_object} = [ $oid, $n, \$str ];
386 my $ref = $self->{ref};
387 my $commit = $self->{mark}++;
388 my $parent = $tip =~ /\A:/ ? $tip : undef;
391 print $w "reset $ref\n" or wfail;
394 utf8::encode($subject);
395 print $w "commit $ref\nmark :$commit\n",
396 "author $name <$email> $author_time_raw\n",
397 "committer $self->{ident} $commit_time_raw\n" or wfail;
398 print $w "data ", (length($subject) + 1), "\n",
399 $subject, "\n\n" or wfail;
401 print $w 'from ', ($parent ? $parent : $tip), "\n" or wfail;
403 clean_tree_v2($self, $w, $path);
404 print $w "M 100644 :$blob $path\n\n" or wfail;
406 $self->{tip} = ":$commit";
410 my ($cmd, $env, $rdr) = @_;
411 my $pid = spawn($cmd, $env, $rdr);
412 defined $pid or die "spawning ".join(' ', @$cmd)." failed: $!";
413 waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
414 $? == 0 or die join(' ', @$cmd) . " failed: $?\n";
419 my $w = delete $self->{out} or return;
420 my $r = delete $self->{in} or die 'BUG: missing {in} when done';
421 print $w "done\n" or wfail;
422 my $pid = delete $self->{pid} or die 'BUG: missing {pid} when done';
423 waitpid($pid, 0) == $pid or die 'fast-import did not finish';
424 $? == 0 or die "fast-import failed: $?";
426 _update_git_info($self, 1) if delete $self->{nchg};
433 foreach my $f (qw(in out)) {
434 close $self->{$f} or die "failed to close import[$f]: $!\n";
440 my $b64 = $dig->clone->b64digest;
441 # Make our own URLs nicer:
442 # See "Base 64 Encoding with URL and Filename Safe Alphabet" in RFC4648
445 # We can make this more meaningful with a date prefix or other things,
446 # but this is only needed for crap that fails to generate a Message-ID
447 # or reuses one. In other words, it's usually spammers who hit this
448 # so they don't deserve nice Message-IDs :P
452 sub clean_purge_buffer {
453 my ($oids, $buf) = @_;
454 my $cmt_msg = 'purged '.join(' ',@$oids)."\n";
457 foreach my $i (0..$#$buf) {
459 if ($l =~ /^author .* (\d+ [\+-]?\d+)$/) {
460 $buf->[$i] = "author <> $1\n";
461 } elsif ($l =~ /^data (\d+)/) {
462 $buf->[$i++] = "data " . length($cmt_msg) . "\n";
463 $buf->[$i] = $cmt_msg;
470 my ($self, $purge) = @_;
471 my $tmp = "refs/heads/purge-".((keys %$purge)[0]);
472 my $old = $self->{'ref'};
473 my $git = $self->{git};
474 my @export = (qw(fast-export --no-data --use-done-feature), $old);
475 my ($rd, $pid) = $git->popen(@export);
476 my ($r, $w) = $self->gfi_start;
481 my $tree = $self->{-tree};
483 if (/^reset (?:.+)/) {
484 push @buf, "reset $tmp\n";
485 } elsif (/^commit (?:.+)/) {
487 $w->print(@buf) or wfail;
490 push @buf, "commit $tmp\n";
491 } elsif (/^data (\d+)/) {
492 # only commit message, so $len is small:
493 my $len = $1; # + 1 for trailing "\n"
495 my $n = read($rd, my $buf, $len) or die "read: $!";
496 $len == $n or die "short read ($n < $len)";
498 } elsif (/^M 100644 ([a-f0-9]+) (\w+)/) {
499 my ($oid, $path) = ($1, $2);
500 if ($purge->{$oid}) {
502 delete $tree->{$path};
507 } elsif (/^D (\w+)/) {
509 push @buf, $_ if $tree->{$path};
510 } elsif ($_ eq "\n") {
512 my $out = join('', @buf);
514 warn "purge rewriting\n", $out, "\n";
515 clean_purge_buffer(\@oids, \@buf);
518 $w->print(@buf, "\n") or wfail;
520 } elsif ($_ eq "done\n") {
522 } elsif (/^mark :(\d+)$/) {
530 $w->print(@buf) or wfail;
532 die 'done\n not seen from fast-export' unless $done;
533 chomp(my $cmt = $self->get_mark(":$mark")) if $npurge;
534 $self->{nchg} = 0; # prevent _update_git_info until update-ref:
536 my @git = ('git', "--git-dir=$git->{git_dir}");
538 run_die([@git, qw(update-ref), $old, $tmp]) if $npurge;
540 run_die([@git, qw(update-ref -d), $tmp]);
542 return if $npurge == 0;
544 run_die([@git, qw(-c gc.reflogExpire=now gc --prune=all)]);
546 foreach my $oid (keys %$purge) {
547 my @info = $git->check($oid);
549 warn "$oid not purged\n";
553 _update_git_info($self, 0);
554 die "Failed to purge $err object(s)\n" if $err;
564 PublicInbox::Import - message importer for public-inbox
573 use PublicInbox::Git;
574 use PublicInbox::Import;
576 chomp(my $git_dir = `git rev-parse --git-dir`);
577 $git_dir or die "GIT_DIR= must be specified\n";
578 my $git = PublicInbox::Git->new($git_dir);
579 my @committer = ('inbox', 'inbox@example.org');
580 my $im = PublicInbox::Import->new($git, @committer);
583 my $message = "From: <u\@example.org>\n".
584 "Subject: test message \n" .
585 "Date: Thu, 01 Jan 1970 00:00:00 +0000\n" .
586 "Message-ID: <m\@example.org>\n".
588 my $parsed = Email::MIME->new($message);
589 my $ret = $im->add($parsed);
592 $parsed->header_obj->header_raw('Message-ID'), "\n";
594 print "imported at mark $ret\n";
598 # to remove a message
599 my $junk = Email::MIME->new($message);
600 my ($mark, $orig) = $im->remove($junk);
601 if ($mark eq 'MISSING') {
603 } elsif ($mark eq 'MISMATCH') {
604 print "Message exists but does not match\n\n",
605 $orig->as_string, "\n",;
607 print "removed at mark $mark\n\n",
608 $orig->as_string, "\n";
614 An importer and remover for public-inboxes which takes L<Email::MIME>
615 messages as input and stores them in a ssoma repository as
616 documented in L<https://ssoma.public-inbox.org/ssoma_repository.txt>,
617 except it does not allow duplicate Message-IDs.
619 It requires L<git(1)> and L<git-fast-import(1)> to be installed.
627 my $im = PublicInbox::Import->new($git, @committer);
629 Initialize a new PublicInbox::Import object.
633 my $parsed = Email::MIME->new($message);
636 Adds a message to to the git repository. This will acquire
637 C<$GIT_DIR/ssoma.lock> and start L<git-fast-import(1)> if necessary.
639 Messages added will not be visible to other processes until L</done>
640 is called, but L</remove> may be called on them.
644 my $junk = Email::MIME->new($message);
645 my ($code, $orig) = $im->remove($junk);
647 Removes a message from the repository. On success, it returns
648 a ':'-prefixed numeric code representing the git-fast-import
649 mark and the original messages as an Email::MIME object.
650 If the message could not be found, the code is "MISSING"
651 and the original message is undef. If there is a mismatch where
652 the "Message-ID" is matched but the subject and body do not match,
653 the returned code is "MISMATCH" and the conflicting message
658 Finalizes the L<git-fast-import(1)> and unlocks the repository.
659 Calling this is required to finalize changes to a repository.
667 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
669 The mail archives are hosted at L<https://public-inbox.org/meta/>
673 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
675 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>