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(mid_mime mid2path);
13 use PublicInbox::Address;
14 use PublicInbox::ContentId qw(content_id);
15 use PublicInbox::MsgTime qw(msg_timestamp);
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 ssoma_lock => 1, # disable for v2
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};
50 if ($self->{ssoma_lock}) {
51 my $lockpath = "$git_dir/ssoma.lock";
52 sysopen($lockfh, $lockpath, O_WRONLY|O_CREAT) or
53 die "failed to open lock $lockpath: $!";
54 # wait for other processes to be done
55 flock($lockfh, LOCK_EX) or die "lock failed: $!\n";
59 chomp($self->{tip} = $git->qx(qw(rev-parse --revs-only), $self->{ref}));
61 my @cmd = ('git', "--git-dir=$git_dir", qw(fast-import
62 --quiet --done --date-format=raw));
63 my $rdr = { 0 => fileno($out_r), 1 => fileno($in_w) };
64 my $pid = spawn(\@cmd, undef, $rdr);
65 die "spawn fast-import failed: $!" unless defined $pid;
68 $self->{out} = $out_w;
69 $self->{lockfh} = $lockfh;
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";
154 my ($self, $mark) = @_;
155 die "not active\n" unless $self->{pid};
156 my ($r, $w) = $self->gfi_start;
157 print $w "get-mark $mark\n" or wfail;
158 defined(my $oid = <$r>) or die "get-mark failed, need git 2.6.0+\n";
162 # returns undef on non-existent
163 # ('MISMATCH', Email::MIME) on mismatch
164 # (:MARK, Email::MIME) on success
166 # For v2 inboxes, the content_id is returned instead of the msg
167 # v2 callers should check with Xapian before calling this as
168 # it is not idempotent.
170 my ($self, $mime, $msg) = @_; # mime = Email::MIME
172 my $path_type = $self->{path_type};
173 my ($path, $err, $cur, $blob);
175 my ($r, $w) = $self->gfi_start;
176 my $tip = $self->{tip};
177 if ($path_type eq '2/38') {
178 $path = mid2path(mid_mime($mime));
179 ($err, $cur) = check_remove_v1($r, $w, $tip, $path, $mime);
180 return ($err, $cur) if $err;
182 $cur = content_id($mime);
183 my $len = length($cur);
184 $blob = $self->{mark}++;
185 print $w "blob\nmark :$blob\ndata $len\n$cur\n" or wfail;
188 my $ref = $self->{ref};
189 my $commit = $self->{mark}++;
190 my $parent = $tip =~ /\A:/ ? $tip : undef;
192 print $w "reset $ref\n" or wfail;
194 my $ident = $self->{ident};
197 my $len = length($msg) + 1;
198 print $w "commit $ref\nmark :$commit\n",
199 "author $ident $now\n",
200 "committer $ident $now\n",
201 "data $len\n$msg\n\n",
202 'from ', ($parent ? $parent : $tip), "\n" or wfail;
204 print $w "D $path\n\n" or wfail;
206 print $w "M 100644 :$blob d\n\n" or wfail;
209 (($self->{tip} = ":$commit"), $cur);
214 my ($ts, $zone) = msg_timestamp($mime->header_obj);
215 $ts = 0 if $ts < 0; # git uses unsigned times
219 sub extract_author_info ($) {
223 my $from = $mime->header('From');
224 my ($email) = PublicInbox::Address::emails($from);
225 my ($name) = PublicInbox::Address::names($from);
226 if (!defined($name) || !defined($email)) {
227 $sender = $mime->header('Sender');
228 if (!defined($name)) {
229 ($name) = PublicInbox::Address::names($sender);
231 if (!defined($email)) {
232 ($email) = PublicInbox::Address::emails($sender);
235 if (defined $email) {
236 # quiet down wide character warnings with utf8::encode
237 utf8::encode($email);
240 warn "no email in From: $from or Sender: $sender\n";
243 # git gets confused with:
244 # "'A U Thor <u@example.com>' via foo" <foo@example.com>
246 # <CAD0k6qSUYANxbjjbE4jTW4EeVwOYgBD=bXkSu=akiYC_CB7Ffw@mail.gmail.com>
252 warn "no name in From: $from or Sender: $sender\n";
257 # returns undef on duplicate
258 # returns the :MARK of the most recent commit
260 my ($self, $mime, $check_cb) = @_; # mime = Email::MIME
262 my ($name, $email) = extract_author_info($mime);
263 my $date_raw = parse_date($mime);
264 my $subject = $mime->header('Subject');
265 $subject = '(no subject)' unless defined $subject;
266 my $path_type = $self->{path_type};
269 if ($path_type eq '2/38') {
270 $path = mid2path(mid_mime($mime));
271 } else { # v2 layout, one file:
275 my ($r, $w) = $self->gfi_start;
276 my $tip = $self->{tip};
277 if ($path_type eq '2/38') {
278 _check_path($r, $w, $tip, $path) and return;
281 # kill potentially confusing/misleading headers
282 $mime->header_set($_) for qw(bytes lines content-length status);
286 $mime = $check_cb->($mime) or return;
289 my $blob = $self->{mark}++;
290 my $str = $mime->as_string;
291 my $n = length($str);
292 $self->{bytes_added} += $n;
293 print $w "blob\nmark :$blob\ndata ", $n, "\n" or wfail;
294 print $w $str, "\n" or wfail;
296 # v2: we need this for Xapian
297 if ($self->{want_object_info}) {
298 chomp(my $oid = $self->get_mark(":$blob"));
299 $self->{last_object} = [ $oid, $n, \$str ];
301 my $ref = $self->{ref};
302 my $commit = $self->{mark}++;
303 my $parent = $tip =~ /\A:/ ? $tip : undef;
306 print $w "reset $ref\n" or wfail;
309 utf8::encode($subject);
310 print $w "commit $ref\nmark :$commit\n",
311 "author $name <$email> $date_raw\n",
312 "committer $self->{ident} ", now_raw(), "\n" or wfail;
313 print $w "data ", (length($subject) + 1), "\n",
314 $subject, "\n\n" or wfail;
316 print $w 'from ', ($parent ? $parent : $tip), "\n" or wfail;
318 print $w "M 100644 :$blob $path\n\n" or wfail;
320 $self->{tip} = ":$commit";
324 my ($cmd, $env) = @_;
325 my $pid = spawn($cmd, $env, undef);
326 defined $pid or die "spawning ".join(' ', @$cmd)." failed: $!";
327 waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
328 $? == 0 or die join(' ', @$cmd) . " failed: $?\n";
333 my $w = delete $self->{out} or return;
334 my $r = delete $self->{in} or die 'BUG: missing {in} when done';
335 print $w "done\n" or wfail;
336 my $pid = delete $self->{pid} or die 'BUG: missing {pid} when done';
337 waitpid($pid, 0) == $pid or die 'fast-import did not finish';
338 $? == 0 or die "fast-import failed: $?";
339 my $nchg = delete $self->{nchg};
341 # for compatibility with existing ssoma installations
342 # we can probably remove this entirely by 2020
343 my $git_dir = $self->{git}->{git_dir};
344 my @cmd = ('git', "--git-dir=$git_dir");
345 my $index = "$git_dir/ssoma.index";
346 if ($nchg && -e $index && !$ENV{FAST}) {
347 my $env = { GIT_INDEX_FILE => $index };
348 run_die([@cmd, qw(read-tree -m -v -i), $self->{ref}], $env);
351 run_die([@cmd, 'update-server-info'], undef);
352 ($self->{path_type} eq '2/38') and eval {
353 require PublicInbox::SearchIdx;
354 my $inbox = $self->{inbox} || $git_dir;
355 my $s = PublicInbox::SearchIdx->new($inbox);
356 $s->index_sync({ ref => $self->{ref} });
359 eval { run_die([@cmd, qw(gc --auto)], undef) };
362 $self->{ssoma_lock} or return;
363 my $lockfh = delete $self->{lockfh} or die "BUG: not locked: $!";
364 flock($lockfh, LOCK_UN) or die "unlock failed: $!";
365 close $lockfh or die "close lock failed: $!";
370 foreach my $f (qw(in out)) {
371 close $self->{$f} or die "failed to close import[$f]: $!\n";
381 PublicInbox::Import - message importer for public-inbox
390 use PublicInbox::Git;
391 use PublicInbox::Import;
393 chomp(my $git_dir = `git rev-parse --git-dir`);
394 $git_dir or die "GIT_DIR= must be specified\n";
395 my $git = PublicInbox::Git->new($git_dir);
396 my @committer = ('inbox', 'inbox@example.org');
397 my $im = PublicInbox::Import->new($git, @committer);
400 my $message = "From: <u\@example.org>\n".
401 "Subject: test message \n" .
402 "Date: Thu, 01 Jan 1970 00:00:00 +0000\n" .
403 "Message-ID: <m\@example.org>\n".
405 my $parsed = Email::MIME->new($message);
406 my $ret = $im->add($parsed);
409 $parsed->header_obj->header_raw('Message-ID'), "\n";
411 print "imported at mark $ret\n";
415 # to remove a message
416 my $junk = Email::MIME->new($message);
417 my ($mark, $orig) = $im->remove($junk);
418 if ($mark eq 'MISSING') {
420 } elsif ($mark eq 'MISMATCH') {
421 print "Message exists but does not match\n\n",
422 $orig->as_string, "\n",;
424 print "removed at mark $mark\n\n",
425 $orig->as_string, "\n";
431 An importer and remover for public-inboxes which takes L<Email::MIME>
432 messages as input and stores them in a ssoma repository as
433 documented in L<https://ssoma.public-inbox.org/ssoma_repository.txt>,
434 except it does not allow duplicate Message-IDs.
436 It requires L<git(1)> and L<git-fast-import(1)> to be installed.
444 my $im = PublicInbox::Import->new($git, @committer);
446 Initialize a new PublicInbox::Import object.
450 my $parsed = Email::MIME->new($message);
453 Adds a message to to the git repository. This will acquire
454 C<$GIT_DIR/ssoma.lock> and start L<git-fast-import(1)> if necessary.
456 Messages added will not be visible to other processes until L</done>
457 is called, but L</remove> may be called on them.
461 my $junk = Email::MIME->new($message);
462 my ($code, $orig) = $im->remove($junk);
464 Removes a message from the repository. On success, it returns
465 a ':'-prefixed numeric code representing the git-fast-import
466 mark and the original messages as an Email::MIME object.
467 If the message could not be found, the code is "MISSING"
468 and the original message is undef. If there is a mismatch where
469 the "Message-ID" is matched but the subject and body do not match,
470 the returned code is "MISMATCH" and the conflicting message
475 Finalizes the L<git-fast-import(1)> and unlocks the repository.
476 Calling this is required to finalize changes to a repository.
484 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
486 The mail archives are hosted at L<https://public-inbox.org/meta/>
490 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
492 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>