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);
18 my ($class, $git, $name, $email, $ibx) = @_;
19 my $ref = 'refs/heads/master';
21 $ref = $ibx->{ref_head} || 'refs/heads/master';
22 $name ||= $ibx->{name};
23 $email ||= $ibx->{-primary_address};
27 ident => "$name <$email>",
31 path_type => '2/38', # or 'v2'
32 lock_path => "$git->{git_dir}/ssoma.lock", # v2 changes this
37 # idempotent start function
41 return ($self->{in}, $self->{out}) if $self->{pid};
43 my ($in_r, $in_w, $out_r, $out_w);
44 pipe($in_r, $in_w) or die "pipe failed: $!";
45 pipe($out_r, $out_w) or die "pipe failed: $!";
46 my $git = $self->{git};
51 chomp($self->{tip} = $git->qx(qw(rev-parse --revs-only), $self->{ref}));
53 my $git_dir = $git->{git_dir};
54 my @cmd = ('git', "--git-dir=$git_dir", qw(fast-import
55 --quiet --done --date-format=raw));
56 my $rdr = { 0 => fileno($out_r), 1 => fileno($in_w) };
57 my $pid = spawn(\@cmd, undef, $rdr);
58 die "spawn fast-import failed: $!" unless defined $pid;
61 $self->{out} = $out_w;
64 binmode $out_w, ':raw' or die "binmode :raw failed: $!";
65 binmode $in_r, ':raw' or die "binmode :raw failed: $!";
69 sub wfail () { die "write to fast-import failed: $!" }
71 sub now_raw () { time . ' +0000' }
75 my $b = $mime->body_raw;
76 $b =~ s/(\r?\n)+\z//s;
80 # only used for v1 (ssoma) inboxes
81 sub _check_path ($$$$) {
82 my ($r, $w, $tip, $path) = @_;
84 print $w "ls $tip $path\n" or wfail;
86 defined(my $info = <$r>) or die "EOF from fast-import: $!";
87 $info =~ /\Amissing / ? undef : $info;
91 my ($r, $w, $tip, $path, $mime) = @_;
93 my $info = _check_path($r, $w, $tip, $path) or return ('MISSING',undef);
94 $info =~ m!\A100644 blob ([a-f0-9]{40})\t!s or die "not blob: $info";
97 print $w "cat-blob $blob\n" or wfail;
100 defined $info or die "EOF from fast-import / cat-blob: $!";
101 $info =~ /\A[a-f0-9]{40} blob (\d+)\n\z/ or
102 die "unexpected cat-blob response: $info";
108 $n = read($r, $buf, $left, $offset);
109 defined($n) or die "read cat-blob failed: $!";
110 $n == 0 and die 'fast-export (cat-blob) died';
114 $n = read($r, my $lf, 1);
115 defined($n) or die "read final byte of cat-blob failed: $!";
116 die "bad read on final byte: <$lf>" if $lf ne "\n";
117 my $cur = PublicInbox::MIME->new(\$buf);
118 my $cur_s = $cur->header('Subject');
119 $cur_s = '' unless defined $cur_s;
120 my $cur_m = $mime->header('Subject');
121 $cur_m = '' unless defined $cur_m;
122 if ($cur_s ne $cur_m || norm_body($cur) ne norm_body($mime)) {
123 return ('MISMATCH', $cur);
130 return unless $self->{pid};
131 print { $self->{out} } "checkpoint\n" or wfail;
136 my ($self, $msg) = @_;
137 return unless $self->{pid};
138 print { $self->{out} } "progress $msg\n" or wfail;
139 $self->{in}->getline eq "progress $msg\n" or die
140 "progress $msg not received\n";
144 sub _update_git_info ($$) {
145 my ($self, $do_gc) = @_;
146 # for compatibility with existing ssoma installations
147 # we can probably remove this entirely by 2020
148 my $git_dir = $self->{git}->{git_dir};
149 my @cmd = ('git', "--git-dir=$git_dir");
150 my $index = "$git_dir/ssoma.index";
151 if (-e $index && !$ENV{FAST}) {
152 my $env = { GIT_INDEX_FILE => $index };
153 run_die([@cmd, qw(read-tree -m -v -i), $self->{ref}], $env);
155 run_die([@cmd, 'update-server-info'], undef);
156 ($self->{path_type} eq '2/38') and eval {
157 require PublicInbox::SearchIdx;
158 my $inbox = $self->{inbox} || $git_dir;
159 my $s = PublicInbox::SearchIdx->new($inbox);
160 $s->index_sync({ ref => $self->{ref} });
162 eval { run_die([@cmd, qw(gc --auto)], undef) } if $do_gc;
168 # For safety, we ensure git checkpoint is complete before because
169 # the data in git is still more important than what is in Xapian
170 # in v2. Performance may be gained by delaying the ->progress
171 # call but we lose safety
174 $self->progress('checkpoint');
175 _update_git_info($self, 0);
182 my ($self, $mark) = @_;
183 die "not active\n" unless $self->{pid};
184 my ($r, $w) = $self->gfi_start;
185 print $w "get-mark $mark\n" or wfail;
186 defined(my $oid = <$r>) or die "get-mark failed, need git 2.6.0+\n";
190 # returns undef on non-existent
191 # ('MISMATCH', Email::MIME) on mismatch
192 # (:MARK, Email::MIME) on success
194 # v2 callers should check with Xapian before calling this as
195 # it is not idempotent.
197 my ($self, $mime, $msg) = @_; # mime = Email::MIME
199 my $path_type = $self->{path_type};
200 my ($path, $err, $cur, $blob);
202 my ($r, $w) = $self->gfi_start;
203 my $tip = $self->{tip};
204 if ($path_type eq '2/38') {
205 $path = mid2path(mid_mime($mime));
206 ($err, $cur) = check_remove_v1($r, $w, $tip, $path, $mime);
207 return ($err, $cur) if $err;
210 if (ref($mime) eq 'SCALAR') { # optimization used by V2Writable
212 } else { # XXX should not be necessary:
213 my $str = $mime->as_string;
216 my $len = length($$sref);
217 $blob = $self->{mark}++;
218 print $w "blob\nmark :$blob\ndata $len\n",
219 $$sref, "\n" or wfail;
222 my $ref = $self->{ref};
223 my $commit = $self->{mark}++;
224 my $parent = $tip =~ /\A:/ ? $tip : undef;
226 print $w "reset $ref\n" or wfail;
228 my $ident = $self->{ident};
231 my $len = length($msg) + 1;
232 print $w "commit $ref\nmark :$commit\n",
233 "author $ident $now\n",
234 "committer $ident $now\n",
235 "data $len\n$msg\n\n",
236 'from ', ($parent ? $parent : $tip), "\n" or wfail;
238 print $w "D $path\n\n" or wfail;
240 print $w "M 100644 :$blob _/D\n\n" or wfail;
243 (($self->{tip} = ":$commit"), $cur);
248 my ($ts, $zone) = msg_timestamp($mime->header_obj);
249 $ts = 0 if $ts < 0; # git uses unsigned times
253 sub extract_author_info ($) {
257 my $from = $mime->header('From');
258 my ($email) = PublicInbox::Address::emails($from);
259 my ($name) = PublicInbox::Address::names($from);
260 if (!defined($name) || !defined($email)) {
261 $sender = $mime->header('Sender');
262 if (!defined($name)) {
263 ($name) = PublicInbox::Address::names($sender);
265 if (!defined($email)) {
266 ($email) = PublicInbox::Address::emails($sender);
269 if (defined $email) {
270 # quiet down wide character warnings with utf8::encode
271 utf8::encode($email);
274 warn "no email in From: $from or Sender: $sender\n";
277 # git gets confused with:
278 # "'A U Thor <u@example.com>' via foo" <foo@example.com>
280 # <CAD0k6qSUYANxbjjbE4jTW4EeVwOYgBD=bXkSu=akiYC_CB7Ffw@mail.gmail.com>
286 warn "no name in From: $from or Sender: $sender\n";
291 # returns undef on duplicate
292 # returns the :MARK of the most recent commit
294 my ($self, $mime, $check_cb) = @_; # mime = Email::MIME
296 my ($name, $email) = extract_author_info($mime);
297 my $date_raw = parse_date($mime);
298 my $subject = $mime->header('Subject');
299 $subject = '(no subject)' unless defined $subject;
300 my $path_type = $self->{path_type};
303 if ($path_type eq '2/38') {
304 my $mids = mids($mime->header_obj);
305 if (!scalar(@$mids)) {
306 my $dig = content_digest($mime);
307 @$mids = (digest2mid($dig));
309 $path = mid2path($mids->[0]);
310 } else { # v2 layout, one file:
314 my ($r, $w) = $self->gfi_start;
315 my $tip = $self->{tip};
316 if ($path_type eq '2/38') {
317 _check_path($r, $w, $tip, $path) and return;
320 # kill potentially confusing/misleading headers
321 $mime->header_set($_) for qw(bytes lines content-length status);
325 $mime = $check_cb->($mime) or return;
328 my $blob = $self->{mark}++;
329 my $str = $mime->as_string;
330 my $n = length($str);
331 $self->{bytes_added} += $n;
332 print $w "blob\nmark :$blob\ndata ", $n, "\n" or wfail;
333 print $w $str, "\n" or wfail;
335 # v2: we need this for Xapian
336 if ($self->{want_object_info}) {
337 chomp(my $oid = $self->get_mark(":$blob"));
338 $self->{last_object} = [ $oid, $n, \$str ];
340 my $ref = $self->{ref};
341 my $commit = $self->{mark}++;
342 my $parent = $tip =~ /\A:/ ? $tip : undef;
345 print $w "reset $ref\n" or wfail;
348 utf8::encode($subject);
349 print $w "commit $ref\nmark :$commit\n",
350 "author $name <$email> $date_raw\n",
351 "committer $self->{ident} ", now_raw(), "\n" or wfail;
352 print $w "data ", (length($subject) + 1), "\n",
353 $subject, "\n\n" or wfail;
355 print $w 'from ', ($parent ? $parent : $tip), "\n" or wfail;
357 print $w "M 100644 :$blob $path\n\n" or wfail;
359 $self->{tip} = ":$commit";
363 my ($cmd, $env) = @_;
364 my $pid = spawn($cmd, $env, undef);
365 defined $pid or die "spawning ".join(' ', @$cmd)." failed: $!";
366 waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
367 $? == 0 or die join(' ', @$cmd) . " failed: $?\n";
372 my $w = delete $self->{out} or return;
373 my $r = delete $self->{in} or die 'BUG: missing {in} when done';
374 print $w "done\n" or wfail;
375 my $pid = delete $self->{pid} or die 'BUG: missing {pid} when done';
376 waitpid($pid, 0) == $pid or die 'fast-import did not finish';
377 $? == 0 or die "fast-import failed: $?";
379 _update_git_info($self, 1) if delete $self->{nchg};
386 foreach my $f (qw(in out)) {
387 close $self->{$f} or die "failed to close import[$f]: $!\n";
393 my $b64 = $dig->clone->b64digest;
394 # Make our own URLs nicer:
395 # See "Base 64 Encoding with URL and Filename Safe Alphabet" in RFC4648
398 # We can make this more meaningful with a date prefix or other things,
399 # but this is only needed for crap that fails to generate a Message-ID
400 # or reuses one. In other words, it's usually spammers who hit this
401 # so they don't deserve nice Message-IDs :P
411 PublicInbox::Import - message importer for public-inbox
420 use PublicInbox::Git;
421 use PublicInbox::Import;
423 chomp(my $git_dir = `git rev-parse --git-dir`);
424 $git_dir or die "GIT_DIR= must be specified\n";
425 my $git = PublicInbox::Git->new($git_dir);
426 my @committer = ('inbox', 'inbox@example.org');
427 my $im = PublicInbox::Import->new($git, @committer);
430 my $message = "From: <u\@example.org>\n".
431 "Subject: test message \n" .
432 "Date: Thu, 01 Jan 1970 00:00:00 +0000\n" .
433 "Message-ID: <m\@example.org>\n".
435 my $parsed = Email::MIME->new($message);
436 my $ret = $im->add($parsed);
439 $parsed->header_obj->header_raw('Message-ID'), "\n";
441 print "imported at mark $ret\n";
445 # to remove a message
446 my $junk = Email::MIME->new($message);
447 my ($mark, $orig) = $im->remove($junk);
448 if ($mark eq 'MISSING') {
450 } elsif ($mark eq 'MISMATCH') {
451 print "Message exists but does not match\n\n",
452 $orig->as_string, "\n",;
454 print "removed at mark $mark\n\n",
455 $orig->as_string, "\n";
461 An importer and remover for public-inboxes which takes L<Email::MIME>
462 messages as input and stores them in a ssoma repository as
463 documented in L<https://ssoma.public-inbox.org/ssoma_repository.txt>,
464 except it does not allow duplicate Message-IDs.
466 It requires L<git(1)> and L<git-fast-import(1)> to be installed.
474 my $im = PublicInbox::Import->new($git, @committer);
476 Initialize a new PublicInbox::Import object.
480 my $parsed = Email::MIME->new($message);
483 Adds a message to to the git repository. This will acquire
484 C<$GIT_DIR/ssoma.lock> and start L<git-fast-import(1)> if necessary.
486 Messages added will not be visible to other processes until L</done>
487 is called, but L</remove> may be called on them.
491 my $junk = Email::MIME->new($message);
492 my ($code, $orig) = $im->remove($junk);
494 Removes a message from the repository. On success, it returns
495 a ':'-prefixed numeric code representing the git-fast-import
496 mark and the original messages as an Email::MIME object.
497 If the message could not be found, the code is "MISSING"
498 and the original message is undef. If there is a mismatch where
499 the "Message-ID" is matched but the subject and body do not match,
500 the returned code is "MISMATCH" and the conflicting message
505 Finalizes the L<git-fast-import(1)> and unlocks the repository.
506 Calling this is required to finalize changes to a repository.
514 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
516 The mail archives are hosted at L<https://public-inbox.org/meta/>
520 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
522 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>