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);
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 chomp($self->{tip} = $git->qx(qw(rev-parse --revs-only), $self->{ref}));
54 my $git_dir = $git->{git_dir};
55 my @cmd = ('git', "--git-dir=$git_dir", qw(fast-import
56 --quiet --done --date-format=raw));
57 my $rdr = { 0 => fileno($out_r), 1 => fileno($in_w) };
58 my $pid = spawn(\@cmd, undef, $rdr);
59 die "spawn fast-import failed: $!" unless defined $pid;
62 $self->{out} = $out_w;
65 binmode $out_w, ':raw' or die "binmode :raw failed: $!";
66 binmode $in_r, ':raw' or die "binmode :raw failed: $!";
70 sub wfail () { die "write to fast-import failed: $!" }
72 sub now_raw () { time . ' +0000' }
76 my $b = $mime->body_raw;
77 $b =~ s/(\r?\n)+\z//s;
81 # only used for v1 (ssoma) inboxes
82 sub _check_path ($$$$) {
83 my ($r, $w, $tip, $path) = @_;
85 print $w "ls $tip $path\n" or wfail;
87 defined(my $info = <$r>) or die "EOF from fast-import: $!";
88 $info =~ /\Amissing / ? undef : $info;
92 my ($r, $w, $tip, $path, $mime) = @_;
94 my $info = _check_path($r, $w, $tip, $path) or return ('MISSING',undef);
95 $info =~ m!\A100644 blob ([a-f0-9]{40})\t!s or die "not blob: $info";
98 print $w "cat-blob $blob\n" or wfail;
101 defined $info or die "EOF from fast-import / cat-blob: $!";
102 $info =~ /\A[a-f0-9]{40} blob (\d+)\n\z/ or
103 die "unexpected cat-blob response: $info";
109 $n = read($r, $buf, $left, $offset);
110 defined($n) or die "read cat-blob failed: $!";
111 $n == 0 and die 'fast-export (cat-blob) died';
115 $n = read($r, my $lf, 1);
116 defined($n) or die "read final byte of cat-blob failed: $!";
117 die "bad read on final byte: <$lf>" if $lf ne "\n";
118 my $cur = PublicInbox::MIME->new(\$buf);
119 my $cur_s = $cur->header('Subject');
120 $cur_s = '' unless defined $cur_s;
121 my $cur_m = $mime->header('Subject');
122 $cur_m = '' unless defined $cur_m;
123 if ($cur_s ne $cur_m || norm_body($cur) ne norm_body($mime)) {
124 return ('MISMATCH', $cur);
131 return unless $self->{pid};
132 print { $self->{out} } "checkpoint\n" or wfail;
137 my ($self, $msg) = @_;
138 return unless $self->{pid};
139 print { $self->{out} } "progress $msg\n" or wfail;
140 $self->{in}->getline eq "progress $msg\n" or die
141 "progress $msg not received\n";
145 sub _update_git_info ($$) {
146 my ($self, $do_gc) = @_;
147 # for compatibility with existing ssoma installations
148 # we can probably remove this entirely by 2020
149 my $git_dir = $self->{git}->{git_dir};
150 my @cmd = ('git', "--git-dir=$git_dir");
151 my $index = "$git_dir/ssoma.index";
152 if (-e $index && !$ENV{FAST}) {
153 my $env = { GIT_INDEX_FILE => $index };
154 run_die([@cmd, qw(read-tree -m -v -i), $self->{ref}], $env);
156 run_die([@cmd, 'update-server-info'], undef);
157 ($self->{path_type} eq '2/38') and eval {
158 require PublicInbox::SearchIdx;
159 my $inbox = $self->{inbox} || $git_dir;
160 my $s = PublicInbox::SearchIdx->new($inbox);
161 $s->index_sync({ ref => $self->{ref} });
163 eval { run_die([@cmd, qw(gc --auto)], undef) } if $do_gc;
169 # For safety, we ensure git checkpoint is complete before because
170 # the data in git is still more important than what is in Xapian
171 # in v2. Performance may be gained by delaying the ->progress
172 # call but we lose safety
175 $self->progress('checkpoint');
176 _update_git_info($self, 0);
183 my ($self, $mark) = @_;
184 die "not active\n" unless $self->{pid};
185 my ($r, $w) = $self->gfi_start;
186 print $w "get-mark $mark\n" or wfail;
187 defined(my $oid = <$r>) or die "get-mark failed, need git 2.6.0+\n";
191 # returns undef on non-existent
192 # ('MISMATCH', Email::MIME) on mismatch
193 # (:MARK, Email::MIME) on success
195 # v2 callers should check with Xapian before calling this as
196 # it is not idempotent.
198 my ($self, $mime, $msg) = @_; # mime = Email::MIME
200 my $path_type = $self->{path_type};
201 my ($path, $err, $cur, $blob);
203 my ($r, $w) = $self->gfi_start;
204 my $tip = $self->{tip};
205 if ($path_type eq '2/38') {
206 $path = mid2path(mid_mime($mime));
207 ($err, $cur) = check_remove_v1($r, $w, $tip, $path, $mime);
208 return ($err, $cur) if $err;
211 if (ref($mime) eq 'SCALAR') { # optimization used by V2Writable
213 } else { # XXX should not be necessary:
214 my $str = $mime->as_string;
217 my $len = length($$sref);
218 $blob = $self->{mark}++;
219 print $w "blob\nmark :$blob\ndata $len\n",
220 $$sref, "\n" or wfail;
223 my $ref = $self->{ref};
224 my $commit = $self->{mark}++;
225 my $parent = $tip =~ /\A:/ ? $tip : undef;
227 print $w "reset $ref\n" or wfail;
229 my $ident = $self->{ident};
232 my $len = length($msg) + 1;
233 print $w "commit $ref\nmark :$commit\n",
234 "author $ident $now\n",
235 "committer $ident $now\n",
236 "data $len\n$msg\n\n",
237 'from ', ($parent ? $parent : $tip), "\n" or wfail;
239 print $w "D $path\n\n" or wfail;
241 print $w "M 100644 :$blob _/D\n\n" or wfail;
244 (($self->{tip} = ":$commit"), $cur);
249 my ($ts, $zone) = msg_timestamp($mime->header_obj);
250 $ts = 0 if $ts < 0; # git uses unsigned times
254 sub extract_author_info ($) {
258 my $from = $mime->header('From');
259 my ($email) = PublicInbox::Address::emails($from);
260 my ($name) = PublicInbox::Address::names($from);
261 if (!defined($name) || !defined($email)) {
262 $sender = $mime->header('Sender');
263 if (!defined($name)) {
264 ($name) = PublicInbox::Address::names($sender);
266 if (!defined($email)) {
267 ($email) = PublicInbox::Address::emails($sender);
270 if (defined $email) {
271 # quiet down wide character warnings with utf8::encode
272 utf8::encode($email);
275 warn "no email in From: $from or Sender: $sender\n";
278 # git gets confused with:
279 # "'A U Thor <u@example.com>' via foo" <foo@example.com>
281 # <CAD0k6qSUYANxbjjbE4jTW4EeVwOYgBD=bXkSu=akiYC_CB7Ffw@mail.gmail.com>
287 warn "no name in From: $from or Sender: $sender\n";
292 # returns undef on duplicate
293 # returns the :MARK of the most recent commit
295 my ($self, $mime, $check_cb) = @_; # mime = Email::MIME
297 my ($name, $email) = extract_author_info($mime);
298 my $date_raw = parse_date($mime);
299 my $subject = $mime->header('Subject');
300 $subject = '(no subject)' unless defined $subject;
301 my $path_type = $self->{path_type};
304 if ($path_type eq '2/38') {
305 my $mids = mids($mime->header_obj);
306 if (!scalar(@$mids)) {
307 my $dig = content_digest($mime);
308 @$mids = (digest2mid($dig));
310 $path = mid2path($mids->[0]);
311 } else { # v2 layout, one file:
315 my ($r, $w) = $self->gfi_start;
316 my $tip = $self->{tip};
317 if ($path_type eq '2/38') {
318 _check_path($r, $w, $tip, $path) and return;
321 # kill potentially confusing/misleading headers
322 $mime->header_set($_) for qw(bytes lines content-length status);
323 $mime->header_set($_) for @PublicInbox::MDA::BAD_HEADERS;
327 $mime = $check_cb->($mime) or return;
330 my $blob = $self->{mark}++;
331 my $str = $mime->as_string;
332 my $n = length($str);
333 $self->{bytes_added} += $n;
334 print $w "blob\nmark :$blob\ndata ", $n, "\n" or wfail;
335 print $w $str, "\n" or wfail;
337 # v2: we need this for Xapian
338 if ($self->{want_object_info}) {
339 chomp(my $oid = $self->get_mark(":$blob"));
340 $self->{last_object} = [ $oid, $n, \$str ];
342 my $ref = $self->{ref};
343 my $commit = $self->{mark}++;
344 my $parent = $tip =~ /\A:/ ? $tip : undef;
347 print $w "reset $ref\n" or wfail;
350 utf8::encode($subject);
351 print $w "commit $ref\nmark :$commit\n",
352 "author $name <$email> $date_raw\n",
353 "committer $self->{ident} ", now_raw(), "\n" or wfail;
354 print $w "data ", (length($subject) + 1), "\n",
355 $subject, "\n\n" or wfail;
357 print $w 'from ', ($parent ? $parent : $tip), "\n" or wfail;
359 print $w "M 100644 :$blob $path\n\n" or wfail;
361 $self->{tip} = ":$commit";
365 my ($cmd, $env) = @_;
366 my $pid = spawn($cmd, $env, undef);
367 defined $pid or die "spawning ".join(' ', @$cmd)." failed: $!";
368 waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
369 $? == 0 or die join(' ', @$cmd) . " failed: $?\n";
374 my $w = delete $self->{out} or return;
375 my $r = delete $self->{in} or die 'BUG: missing {in} when done';
376 print $w "done\n" or wfail;
377 my $pid = delete $self->{pid} or die 'BUG: missing {pid} when done';
378 waitpid($pid, 0) == $pid or die 'fast-import did not finish';
379 $? == 0 or die "fast-import failed: $?";
381 _update_git_info($self, 1) if delete $self->{nchg};
388 foreach my $f (qw(in out)) {
389 close $self->{$f} or die "failed to close import[$f]: $!\n";
395 my $b64 = $dig->clone->b64digest;
396 # Make our own URLs nicer:
397 # See "Base 64 Encoding with URL and Filename Safe Alphabet" in RFC4648
400 # We can make this more meaningful with a date prefix or other things,
401 # but this is only needed for crap that fails to generate a Message-ID
402 # or reuses one. In other words, it's usually spammers who hit this
403 # so they don't deserve nice Message-IDs :P
413 PublicInbox::Import - message importer for public-inbox
422 use PublicInbox::Git;
423 use PublicInbox::Import;
425 chomp(my $git_dir = `git rev-parse --git-dir`);
426 $git_dir or die "GIT_DIR= must be specified\n";
427 my $git = PublicInbox::Git->new($git_dir);
428 my @committer = ('inbox', 'inbox@example.org');
429 my $im = PublicInbox::Import->new($git, @committer);
432 my $message = "From: <u\@example.org>\n".
433 "Subject: test message \n" .
434 "Date: Thu, 01 Jan 1970 00:00:00 +0000\n" .
435 "Message-ID: <m\@example.org>\n".
437 my $parsed = Email::MIME->new($message);
438 my $ret = $im->add($parsed);
441 $parsed->header_obj->header_raw('Message-ID'), "\n";
443 print "imported at mark $ret\n";
447 # to remove a message
448 my $junk = Email::MIME->new($message);
449 my ($mark, $orig) = $im->remove($junk);
450 if ($mark eq 'MISSING') {
452 } elsif ($mark eq 'MISMATCH') {
453 print "Message exists but does not match\n\n",
454 $orig->as_string, "\n",;
456 print "removed at mark $mark\n\n",
457 $orig->as_string, "\n";
463 An importer and remover for public-inboxes which takes L<Email::MIME>
464 messages as input and stores them in a ssoma repository as
465 documented in L<https://ssoma.public-inbox.org/ssoma_repository.txt>,
466 except it does not allow duplicate Message-IDs.
468 It requires L<git(1)> and L<git-fast-import(1)> to be installed.
476 my $im = PublicInbox::Import->new($git, @committer);
478 Initialize a new PublicInbox::Import object.
482 my $parsed = Email::MIME->new($message);
485 Adds a message to to the git repository. This will acquire
486 C<$GIT_DIR/ssoma.lock> and start L<git-fast-import(1)> if necessary.
488 Messages added will not be visible to other processes until L</done>
489 is called, but L</remove> may be called on them.
493 my $junk = Email::MIME->new($message);
494 my ($code, $orig) = $im->remove($junk);
496 Removes a message from the repository. On success, it returns
497 a ':'-prefixed numeric code representing the git-fast-import
498 mark and the original messages as an Email::MIME object.
499 If the message could not be found, the code is "MISSING"
500 and the original message is undef. If there is a mismatch where
501 the "Message-ID" is matched but the subject and body do not match,
502 the returned code is "MISMATCH" and the conflicting message
507 Finalizes the L<git-fast-import(1)> and unlocks the repository.
508 Calling this is required to finalize changes to a repository.
516 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
518 The mail archives are hosted at L<https://public-inbox.org/meta/>
522 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
524 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>