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 Fcntl qw(:flock :DEFAULT);
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};
47 my $git_dir = $git->{git_dir};
49 if (my $lock_path = $self->{lock_path}) {
50 sysopen(my $lockfh, $lock_path, O_WRONLY|O_CREAT) or
51 die "failed to open lock $lock_path: $!";
52 # wait for other processes to be done
53 flock($lockfh, LOCK_EX) or die "lock failed: $!\n";
54 $self->{lockfh} = $lockfh;
58 chomp($self->{tip} = $git->qx(qw(rev-parse --revs-only), $self->{ref}));
60 my @cmd = ('git', "--git-dir=$git_dir", qw(fast-import
61 --quiet --done --date-format=raw));
62 my $rdr = { 0 => fileno($out_r), 1 => fileno($in_w) };
63 my $pid = spawn(\@cmd, undef, $rdr);
64 die "spawn fast-import failed: $!" unless defined $pid;
67 $self->{out} = $out_w;
70 binmode $out_w, ':raw' or die "binmode :raw failed: $!";
71 binmode $in_r, ':raw' or die "binmode :raw failed: $!";
75 sub wfail () { die "write to fast-import failed: $!" }
77 sub now_raw () { time . ' +0000' }
81 my $b = $mime->body_raw;
82 $b =~ s/(\r?\n)+\z//s;
86 # only used for v1 (ssoma) inboxes
87 sub _check_path ($$$$) {
88 my ($r, $w, $tip, $path) = @_;
90 print $w "ls $tip $path\n" or wfail;
92 defined(my $info = <$r>) or die "EOF from fast-import: $!";
93 $info =~ /\Amissing / ? undef : $info;
97 my ($r, $w, $tip, $path, $mime) = @_;
99 my $info = _check_path($r, $w, $tip, $path) or return ('MISSING',undef);
100 $info =~ m!\A100644 blob ([a-f0-9]{40})\t!s or die "not blob: $info";
103 print $w "cat-blob $blob\n" or wfail;
106 defined $info or die "EOF from fast-import / cat-blob: $!";
107 $info =~ /\A[a-f0-9]{40} blob (\d+)\n\z/ or
108 die "unexpected cat-blob response: $info";
114 $n = read($r, $buf, $left, $offset);
115 defined($n) or die "read cat-blob failed: $!";
116 $n == 0 and die 'fast-export (cat-blob) died';
120 $n = read($r, my $lf, 1);
121 defined($n) or die "read final byte of cat-blob failed: $!";
122 die "bad read on final byte: <$lf>" if $lf ne "\n";
123 my $cur = PublicInbox::MIME->new(\$buf);
124 my $cur_s = $cur->header('Subject');
125 $cur_s = '' unless defined $cur_s;
126 my $cur_m = $mime->header('Subject');
127 $cur_m = '' unless defined $cur_m;
128 if ($cur_s ne $cur_m || norm_body($cur) ne norm_body($mime)) {
129 return ('MISMATCH', $cur);
136 return unless $self->{pid};
137 print { $self->{out} } "checkpoint\n" or wfail;
142 my ($self, $msg) = @_;
143 return unless $self->{pid};
144 print { $self->{out} } "progress $msg\n" or wfail;
145 $self->{in}->getline eq "progress $msg\n" or die
146 "progress $msg not received\n";
150 sub _update_git_info ($$) {
151 my ($self, $do_gc) = @_;
152 # for compatibility with existing ssoma installations
153 # we can probably remove this entirely by 2020
154 my $git_dir = $self->{git}->{git_dir};
155 my @cmd = ('git', "--git-dir=$git_dir");
156 my $index = "$git_dir/ssoma.index";
157 if (-e $index && !$ENV{FAST}) {
158 my $env = { GIT_INDEX_FILE => $index };
159 run_die([@cmd, qw(read-tree -m -v -i), $self->{ref}], $env);
161 run_die([@cmd, 'update-server-info'], undef);
162 ($self->{path_type} eq '2/38') and eval {
163 require PublicInbox::SearchIdx;
164 my $inbox = $self->{inbox} || $git_dir;
165 my $s = PublicInbox::SearchIdx->new($inbox);
166 $s->index_sync({ ref => $self->{ref} });
168 eval { run_die([@cmd, qw(gc --auto)], undef) } if $do_gc;
174 # For safety, we ensure git checkpoint is complete before because
175 # the data in git is still more important than what is in Xapian
176 # in v2. Performance may be gained by delaying the ->progress
177 # call but we lose safety
180 $self->progress('checkpoint');
181 _update_git_info($self, 0);
188 my ($self, $mark) = @_;
189 die "not active\n" unless $self->{pid};
190 my ($r, $w) = $self->gfi_start;
191 print $w "get-mark $mark\n" or wfail;
192 defined(my $oid = <$r>) or die "get-mark failed, need git 2.6.0+\n";
196 # returns undef on non-existent
197 # ('MISMATCH', Email::MIME) on mismatch
198 # (:MARK, Email::MIME) on success
200 # v2 callers should check with Xapian before calling this as
201 # it is not idempotent.
203 my ($self, $mime, $msg) = @_; # mime = Email::MIME
205 my $path_type = $self->{path_type};
206 my ($path, $err, $cur, $blob);
208 my ($r, $w) = $self->gfi_start;
209 my $tip = $self->{tip};
210 if ($path_type eq '2/38') {
211 $path = mid2path(mid_mime($mime));
212 ($err, $cur) = check_remove_v1($r, $w, $tip, $path, $mime);
213 return ($err, $cur) if $err;
216 if (ref($mime) eq 'SCALAR') { # optimization used by V2Writable
218 } else { # XXX should not be necessary:
219 my $str = $mime->as_string;
222 my $len = length($$sref);
223 $blob = $self->{mark}++;
224 print $w "blob\nmark :$blob\ndata $len\n",
225 $$sref, "\n" or wfail;
228 my $ref = $self->{ref};
229 my $commit = $self->{mark}++;
230 my $parent = $tip =~ /\A:/ ? $tip : undef;
232 print $w "reset $ref\n" or wfail;
234 my $ident = $self->{ident};
237 my $len = length($msg) + 1;
238 print $w "commit $ref\nmark :$commit\n",
239 "author $ident $now\n",
240 "committer $ident $now\n",
241 "data $len\n$msg\n\n",
242 'from ', ($parent ? $parent : $tip), "\n" or wfail;
244 print $w "D $path\n\n" or wfail;
246 print $w "M 100644 :$blob _/D\n\n" or wfail;
249 (($self->{tip} = ":$commit"), $cur);
254 my ($ts, $zone) = msg_timestamp($mime->header_obj);
255 $ts = 0 if $ts < 0; # git uses unsigned times
259 sub extract_author_info ($) {
263 my $from = $mime->header('From');
264 my ($email) = PublicInbox::Address::emails($from);
265 my ($name) = PublicInbox::Address::names($from);
266 if (!defined($name) || !defined($email)) {
267 $sender = $mime->header('Sender');
268 if (!defined($name)) {
269 ($name) = PublicInbox::Address::names($sender);
271 if (!defined($email)) {
272 ($email) = PublicInbox::Address::emails($sender);
275 if (defined $email) {
276 # quiet down wide character warnings with utf8::encode
277 utf8::encode($email);
280 warn "no email in From: $from or Sender: $sender\n";
283 # git gets confused with:
284 # "'A U Thor <u@example.com>' via foo" <foo@example.com>
286 # <CAD0k6qSUYANxbjjbE4jTW4EeVwOYgBD=bXkSu=akiYC_CB7Ffw@mail.gmail.com>
292 warn "no name in From: $from or Sender: $sender\n";
297 # returns undef on duplicate
298 # returns the :MARK of the most recent commit
300 my ($self, $mime, $check_cb) = @_; # mime = Email::MIME
302 my ($name, $email) = extract_author_info($mime);
303 my $date_raw = parse_date($mime);
304 my $subject = $mime->header('Subject');
305 $subject = '(no subject)' unless defined $subject;
306 my $path_type = $self->{path_type};
309 if ($path_type eq '2/38') {
310 my $mids = mids($mime->header_obj);
311 if (!scalar(@$mids)) {
312 my $dig = content_digest($mime);
313 @$mids = (digest2mid($dig));
315 $path = mid2path($mids->[0]);
316 } else { # v2 layout, one file:
320 my ($r, $w) = $self->gfi_start;
321 my $tip = $self->{tip};
322 if ($path_type eq '2/38') {
323 _check_path($r, $w, $tip, $path) and return;
326 # kill potentially confusing/misleading headers
327 $mime->header_set($_) for qw(bytes lines content-length status);
331 $mime = $check_cb->($mime) or return;
334 my $blob = $self->{mark}++;
335 my $str = $mime->as_string;
336 my $n = length($str);
337 $self->{bytes_added} += $n;
338 print $w "blob\nmark :$blob\ndata ", $n, "\n" or wfail;
339 print $w $str, "\n" or wfail;
341 # v2: we need this for Xapian
342 if ($self->{want_object_info}) {
343 chomp(my $oid = $self->get_mark(":$blob"));
344 $self->{last_object} = [ $oid, $n, \$str ];
346 my $ref = $self->{ref};
347 my $commit = $self->{mark}++;
348 my $parent = $tip =~ /\A:/ ? $tip : undef;
351 print $w "reset $ref\n" or wfail;
354 utf8::encode($subject);
355 print $w "commit $ref\nmark :$commit\n",
356 "author $name <$email> $date_raw\n",
357 "committer $self->{ident} ", now_raw(), "\n" or wfail;
358 print $w "data ", (length($subject) + 1), "\n",
359 $subject, "\n\n" or wfail;
361 print $w 'from ', ($parent ? $parent : $tip), "\n" or wfail;
363 print $w "M 100644 :$blob $path\n\n" or wfail;
365 $self->{tip} = ":$commit";
369 my ($cmd, $env) = @_;
370 my $pid = spawn($cmd, $env, undef);
371 defined $pid or die "spawning ".join(' ', @$cmd)." failed: $!";
372 waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
373 $? == 0 or die join(' ', @$cmd) . " failed: $?\n";
378 my $w = delete $self->{out} or return;
379 my $r = delete $self->{in} or die 'BUG: missing {in} when done';
380 print $w "done\n" or wfail;
381 my $pid = delete $self->{pid} or die 'BUG: missing {pid} when done';
382 waitpid($pid, 0) == $pid or die 'fast-import did not finish';
383 $? == 0 or die "fast-import failed: $?";
385 _update_git_info($self, 1) if delete $self->{nchg};
387 $self->{lock_path} or return;
388 my $lockfh = delete $self->{lockfh} or die "BUG: not locked: $!";
389 flock($lockfh, LOCK_UN) or die "unlock failed: $!";
390 close $lockfh or die "close lock failed: $!";
395 foreach my $f (qw(in out)) {
396 close $self->{$f} or die "failed to close import[$f]: $!\n";
402 my $b64 = $dig->clone->b64digest;
403 # Make our own URLs nicer:
404 # See "Base 64 Encoding with URL and Filename Safe Alphabet" in RFC4648
407 # We can make this more meaningful with a date prefix or other things,
408 # but this is only needed for crap that fails to generate a Message-ID
409 # or reuses one. In other words, it's usually spammers who hit this
410 # so they don't deserve nice Message-IDs :P
420 PublicInbox::Import - message importer for public-inbox
429 use PublicInbox::Git;
430 use PublicInbox::Import;
432 chomp(my $git_dir = `git rev-parse --git-dir`);
433 $git_dir or die "GIT_DIR= must be specified\n";
434 my $git = PublicInbox::Git->new($git_dir);
435 my @committer = ('inbox', 'inbox@example.org');
436 my $im = PublicInbox::Import->new($git, @committer);
439 my $message = "From: <u\@example.org>\n".
440 "Subject: test message \n" .
441 "Date: Thu, 01 Jan 1970 00:00:00 +0000\n" .
442 "Message-ID: <m\@example.org>\n".
444 my $parsed = Email::MIME->new($message);
445 my $ret = $im->add($parsed);
448 $parsed->header_obj->header_raw('Message-ID'), "\n";
450 print "imported at mark $ret\n";
454 # to remove a message
455 my $junk = Email::MIME->new($message);
456 my ($mark, $orig) = $im->remove($junk);
457 if ($mark eq 'MISSING') {
459 } elsif ($mark eq 'MISMATCH') {
460 print "Message exists but does not match\n\n",
461 $orig->as_string, "\n",;
463 print "removed at mark $mark\n\n",
464 $orig->as_string, "\n";
470 An importer and remover for public-inboxes which takes L<Email::MIME>
471 messages as input and stores them in a ssoma repository as
472 documented in L<https://ssoma.public-inbox.org/ssoma_repository.txt>,
473 except it does not allow duplicate Message-IDs.
475 It requires L<git(1)> and L<git-fast-import(1)> to be installed.
483 my $im = PublicInbox::Import->new($git, @committer);
485 Initialize a new PublicInbox::Import object.
489 my $parsed = Email::MIME->new($message);
492 Adds a message to to the git repository. This will acquire
493 C<$GIT_DIR/ssoma.lock> and start L<git-fast-import(1)> if necessary.
495 Messages added will not be visible to other processes until L</done>
496 is called, but L</remove> may be called on them.
500 my $junk = Email::MIME->new($message);
501 my ($code, $orig) = $im->remove($junk);
503 Removes a message from the repository. On success, it returns
504 a ':'-prefixed numeric code representing the git-fast-import
505 mark and the original messages as an Email::MIME object.
506 If the message could not be found, the code is "MISSING"
507 and the original message is undef. If there is a mismatch where
508 the "Message-ID" is matched but the subject and body do not match,
509 the returned code is "MISMATCH" and the conflicting message
514 Finalizes the L<git-fast-import(1)> and unlocks the repository.
515 Calling this is required to finalize changes to a repository.
523 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
525 The mail archives are hosted at L<https://public-inbox.org/meta/>
529 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
531 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>