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);
136 # used for v2 (maybe)
139 return unless $self->{pid};
140 print { $self->{out} } "checkpoint\n" or wfail;
146 my ($self, $mark) = @_;
147 die "not active\n" unless $self->{pid};
148 my ($r, $w) = $self->gfi_start;
149 print $w "get-mark $mark\n" or wfail;
150 defined(my $oid = <$r>) or die "get-mark failed, need git 2.6.0+\n";
154 # returns undef on non-existent
155 # ('MISMATCH', Email::MIME) on mismatch
156 # (:MARK, Email::MIME) on success
158 # For v2 inboxes, the content_id is returned instead of the msg
159 # v2 callers should check with Xapian before calling this as
160 # it is not idempotent.
162 my ($self, $mime, $msg) = @_; # mime = Email::MIME
164 my $path_type = $self->{path_type};
165 my ($path, $err, $cur, $blob);
167 my ($r, $w) = $self->gfi_start;
168 my $tip = $self->{tip};
169 if ($path_type eq '2/38') {
170 $path = mid2path(mid_mime($mime));
171 ($err, $cur) = check_remove_v1($r, $w, $tip, $path, $mime);
172 return ($err, $cur) if $err;
174 $cur = content_id($mime);
175 my $len = length($cur);
176 $blob = $self->{mark}++;
177 print $w "blob\nmark :$blob\ndata $len\n$cur\n" or wfail;
180 my $ref = $self->{ref};
181 my $commit = $self->{mark}++;
182 my $parent = $tip =~ /\A:/ ? $tip : undef;
184 print $w "reset $ref\n" or wfail;
186 my $ident = $self->{ident};
189 my $len = length($msg) + 1;
190 print $w "commit $ref\nmark :$commit\n",
191 "author $ident $now\n",
192 "committer $ident $now\n",
193 "data $len\n$msg\n\n",
194 'from ', ($parent ? $parent : $tip), "\n" or wfail;
196 print $w "D $path\n\n" or wfail;
198 print $w "M 100644 :$blob d\n\n" or wfail;
201 (($self->{tip} = ":$commit"), $cur);
206 my ($ts, $zone) = msg_timestamp($mime->header_obj);
207 $ts = 0 if $ts < 0; # git uses unsigned times
211 # returns undef on duplicate
212 # returns the :MARK of the most recent commit
214 my ($self, $mime, $check_cb) = @_; # mime = Email::MIME
216 my $from = $mime->header('From');
217 my ($email) = PublicInbox::Address::emails($from);
218 my ($name) = PublicInbox::Address::names($from);
220 my $date_raw = parse_date($mime);
221 my $subject = $mime->header('Subject');
222 $subject = '(no subject)' unless defined $subject;
223 my $path_type = $self->{path_type};
226 if ($path_type eq '2/38') {
227 $path = mid2path(mid_mime($mime));
228 } else { # v2 layout, one file:
232 my ($r, $w) = $self->gfi_start;
233 my $tip = $self->{tip};
234 if ($path_type eq '2/38') {
235 _check_path($r, $w, $tip, $path) and return;
238 # kill potentially confusing/misleading headers
239 $mime->header_set($_) for qw(bytes lines content-length status);
243 $mime = $check_cb->($mime) or return;
246 my $blob = $self->{mark}++;
247 my $str = $mime->as_string;
248 my $n = length($str);
249 $self->{bytes_added} += $n;
250 print $w "blob\nmark :$blob\ndata ", $n, "\n" or wfail;
251 print $w $str, "\n" or wfail;
253 # v2: we need this for Xapian
254 if ($self->{want_object_info}) {
255 chomp(my $oid = $self->get_mark(":$blob"));
256 $self->{last_object} = [ $oid, $n, \$str ];
258 my $ref = $self->{ref};
259 my $commit = $self->{mark}++;
260 my $parent = $tip =~ /\A:/ ? $tip : undef;
263 print $w "reset $ref\n" or wfail;
266 # quiet down wide character warnings with utf8::encode
267 if (defined $email) {
268 utf8::encode($email);
271 warn "no email in From: $from\n";
274 # git gets confused with:
275 # "'A U Thor <u@example.com>' via foo" <foo@example.com>
277 # <CAD0k6qSUYANxbjjbE4jTW4EeVwOYgBD=bXkSu=akiYC_CB7Ffw@mail.gmail.com>
283 warn "no name in From: $from\n";
285 utf8::encode($subject);
286 print $w "commit $ref\nmark :$commit\n",
287 "author $name <$email> $date_raw\n",
288 "committer $self->{ident} ", now_raw(), "\n" or wfail;
289 print $w "data ", (length($subject) + 1), "\n",
290 $subject, "\n\n" or wfail;
292 print $w 'from ', ($parent ? $parent : $tip), "\n" or wfail;
294 print $w "M 100644 :$blob $path\n\n" or wfail;
296 $self->{tip} = ":$commit";
300 my ($cmd, $env) = @_;
301 my $pid = spawn($cmd, $env, undef);
302 defined $pid or die "spawning ".join(' ', @$cmd)." failed: $!";
303 waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
304 $? == 0 or die join(' ', @$cmd) . " failed: $?\n";
309 my $w = delete $self->{out} or return;
310 my $r = delete $self->{in} or die 'BUG: missing {in} when done';
311 print $w "done\n" or wfail;
312 my $pid = delete $self->{pid} or die 'BUG: missing {pid} when done';
313 waitpid($pid, 0) == $pid or die 'fast-import did not finish';
314 $? == 0 or die "fast-import failed: $?";
315 my $nchg = delete $self->{nchg};
317 # for compatibility with existing ssoma installations
318 # we can probably remove this entirely by 2020
319 my $git_dir = $self->{git}->{git_dir};
320 my @cmd = ('git', "--git-dir=$git_dir");
321 my $index = "$git_dir/ssoma.index";
322 if ($nchg && -e $index && !$ENV{FAST}) {
323 my $env = { GIT_INDEX_FILE => $index };
324 run_die([@cmd, qw(read-tree -m -v -i), $self->{ref}], $env);
327 run_die([@cmd, 'update-server-info'], undef);
328 ($self->{path_type} eq '2/38') and eval {
329 require PublicInbox::SearchIdx;
330 my $inbox = $self->{inbox} || $git_dir;
331 my $s = PublicInbox::SearchIdx->new($inbox);
332 $s->index_sync({ ref => $self->{ref} });
335 eval { run_die([@cmd, qw(gc --auto)], undef) };
338 $self->{ssoma_lock} or return;
339 my $lockfh = delete $self->{lockfh} or die "BUG: not locked: $!";
340 flock($lockfh, LOCK_UN) or die "unlock failed: $!";
341 close $lockfh or die "close lock failed: $!";
346 foreach my $f (qw(in out)) {
347 close $self->{$f} or die "failed to close import[$f]: $!\n";
357 PublicInbox::Import - message importer for public-inbox
366 use PublicInbox::Git;
367 use PublicInbox::Import;
369 chomp(my $git_dir = `git rev-parse --git-dir`);
370 $git_dir or die "GIT_DIR= must be specified\n";
371 my $git = PublicInbox::Git->new($git_dir);
372 my @committer = ('inbox', 'inbox@example.org');
373 my $im = PublicInbox::Import->new($git, @committer);
376 my $message = "From: <u\@example.org>\n".
377 "Subject: test message \n" .
378 "Date: Thu, 01 Jan 1970 00:00:00 +0000\n" .
379 "Message-ID: <m\@example.org>\n".
381 my $parsed = Email::MIME->new($message);
382 my $ret = $im->add($parsed);
385 $parsed->header_obj->header_raw('Message-ID'), "\n";
387 print "imported at mark $ret\n";
391 # to remove a message
392 my $junk = Email::MIME->new($message);
393 my ($mark, $orig) = $im->remove($junk);
394 if ($mark eq 'MISSING') {
396 } elsif ($mark eq 'MISMATCH') {
397 print "Message exists but does not match\n\n",
398 $orig->as_string, "\n",;
400 print "removed at mark $mark\n\n",
401 $orig->as_string, "\n";
407 An importer and remover for public-inboxes which takes L<Email::MIME>
408 messages as input and stores them in a ssoma repository as
409 documented in L<https://ssoma.public-inbox.org/ssoma_repository.txt>,
410 except it does not allow duplicate Message-IDs.
412 It requires L<git(1)> and L<git-fast-import(1)> to be installed.
420 my $im = PublicInbox::Import->new($git, @committer);
422 Initialize a new PublicInbox::Import object.
426 my $parsed = Email::MIME->new($message);
429 Adds a message to to the git repository. This will acquire
430 C<$GIT_DIR/ssoma.lock> and start L<git-fast-import(1)> if necessary.
432 Messages added will not be visible to other processes until L</done>
433 is called, but L</remove> may be called on them.
437 my $junk = Email::MIME->new($message);
438 my ($code, $orig) = $im->remove($junk);
440 Removes a message from the repository. On success, it returns
441 a ':'-prefixed numeric code representing the git-fast-import
442 mark and the original messages as an Email::MIME object.
443 If the message could not be found, the code is "MISSING"
444 and the original message is undef. If there is a mismatch where
445 the "Message-ID" is matched but the subject and body do not match,
446 the returned code is "MISMATCH" and the conflicting message
451 Finalizes the L<git-fast-import(1)> and unlocks the repository.
452 Calling this is required to finalize changes to a repository.
460 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
462 The mail archives are hosted at L<https://public-inbox.org/meta/>
466 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
468 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>