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);
17 my ($class, $git, $name, $email, $ibx) = @_;
18 my $ref = 'refs/heads/master';
20 $ref = $ibx->{ref_head} || 'refs/heads/master';
21 $name ||= $ibx->{name};
22 $email ||= $ibx->{-primary_address};
26 ident => "$name <$email>",
30 path_type => '2/38', # or 'v2'
31 ssoma_lock => 1, # disable for v2
35 # idempotent start function
39 return ($self->{in}, $self->{out}) if $self->{pid};
41 my ($in_r, $in_w, $out_r, $out_w);
42 pipe($in_r, $in_w) or die "pipe failed: $!";
43 pipe($out_r, $out_w) or die "pipe failed: $!";
44 my $git = $self->{git};
45 my $git_dir = $git->{git_dir};
48 if ($self->{ssoma_lock}) {
49 my $lockpath = "$git_dir/ssoma.lock";
50 sysopen($lockfh, $lockpath, O_WRONLY|O_CREAT) or
51 die "failed to open lock $lockpath: $!";
52 # wait for other processes to be done
53 flock($lockfh, LOCK_EX) or die "lock failed: $!\n";
57 chomp($self->{tip} = $git->qx(qw(rev-parse --revs-only), $self->{ref}));
59 my @cmd = ('git', "--git-dir=$git_dir", qw(fast-import
60 --quiet --done --date-format=rfc2822));
61 my $rdr = { 0 => fileno($out_r), 1 => fileno($in_w) };
62 my $pid = spawn(\@cmd, undef, $rdr);
63 die "spawn fast-import failed: $!" unless defined $pid;
66 $self->{out} = $out_w;
67 $self->{lockfh} = $lockfh;
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: $!" }
79 my $day = qw(Sun Mon Tue Wed Thu Fri Sat)[$t[6]];
80 my $mon = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)[$t[4]];
82 sprintf('%s, %2d %s %d %02d:%02d:%02d +0000',
83 $day, $t[3], $mon, $t[5] + 1900, $t[2], $t[1], $t[0]);
88 my $b = $mime->body_raw;
89 $b =~ s/(\r?\n)+\z//s;
93 # only used for v1 (ssoma) inboxes
94 sub _check_path ($$$$) {
95 my ($r, $w, $tip, $path) = @_;
97 print $w "ls $tip $path\n" or wfail;
99 defined(my $info = <$r>) or die "EOF from fast-import: $!";
100 $info =~ /\Amissing / ? undef : $info;
103 sub check_remove_v1 {
104 my ($r, $w, $tip, $path, $mime) = @_;
106 my $info = _check_path($r, $w, $tip, $path) or return ('MISSING',undef);
107 $info =~ m!\A100644 blob ([a-f0-9]{40})\t!s or die "not blob: $info";
110 print $w "cat-blob $blob\n" or wfail;
113 defined $info or die "EOF from fast-import / cat-blob: $!";
114 $info =~ /\A[a-f0-9]{40} blob (\d+)\n\z/ or
115 die "unexpected cat-blob response: $info";
121 $n = read($r, $buf, $left, $offset);
122 defined($n) or die "read cat-blob failed: $!";
123 $n == 0 and die 'fast-export (cat-blob) died';
127 $n = read($r, my $lf, 1);
128 defined($n) or die "read final byte of cat-blob failed: $!";
129 die "bad read on final byte: <$lf>" if $lf ne "\n";
130 my $cur = PublicInbox::MIME->new($buf);
131 my $cur_s = $cur->header('Subject');
132 $cur_s = '' unless defined $cur_s;
133 my $cur_m = $mime->header('Subject');
134 $cur_m = '' unless defined $cur_m;
135 if ($cur_s ne $cur_m || norm_body($cur) ne norm_body($mime)) {
136 return ('MISMATCH', $cur);
141 # used for v2 (maybe)
144 return unless $self->{pid};
145 print { $self->{out} } "checkpoint\n" or wfail;
151 my ($self, $mark) = @_;
152 die "not active\n" unless $self->{pid};
153 my ($r, $w) = $self->gfi_start;
154 print $w "get-mark $mark\n" or wfail;
155 defined(my $oid = <$r>) or die "get-mark failed, need git 2.6.0+\n";
159 # returns undef on non-existent
160 # ('MISMATCH', Email::MIME) on mismatch
161 # (:MARK, Email::MIME) on success
163 # For v2 inboxes, the content_id is returned instead of the msg
164 # v2 callers should check with Xapian before calling this as
165 # it is not idempotent.
167 my ($self, $mime, $msg) = @_; # mime = Email::MIME
169 my $path_type = $self->{path_type};
170 my ($path, $err, $cur, $blob);
172 my ($r, $w) = $self->gfi_start;
173 my $tip = $self->{tip};
174 if ($path_type eq '2/38') {
175 $path = mid2path(mid_mime($mime));
176 ($err, $cur) = check_remove_v1($r, $w, $tip, $path, $mime);
177 return ($err, $cur) if $err;
179 $cur = content_id($mime);
180 my $len = length($cur);
181 $blob = $self->{mark}++;
182 print $w "blob\nmark :$blob\ndata $len\n$cur\n" or wfail;
185 my $ref = $self->{ref};
186 my $commit = $self->{mark}++;
187 my $parent = $tip =~ /\A:/ ? $tip : undef;
189 print $w "reset $ref\n" or wfail;
191 my $ident = $self->{ident};
194 my $len = length($msg) + 1;
195 print $w "commit $ref\nmark :$commit\n",
196 "author $ident $now\n",
197 "committer $ident $now\n",
198 "data $len\n$msg\n\n",
199 'from ', ($parent ? $parent : $tip), "\n" or wfail;
201 print $w "D $path\n\n" or wfail;
203 print $w "M 100644 :$blob d\n\n" or wfail;
206 (($self->{tip} = ":$commit"), $cur);
209 # returns undef on duplicate
210 # returns the :MARK of the most recent commit
212 my ($self, $mime, $check_cb) = @_; # mime = Email::MIME
214 my $from = $mime->header('From');
215 my ($email) = PublicInbox::Address::emails($from);
216 my ($name) = PublicInbox::Address::names($from);
217 # git gets confused with:
218 # "'A U Thor <u@example.com>' via foo" <foo@example.com>
220 # <CAD0k6qSUYANxbjjbE4jTW4EeVwOYgBD=bXkSu=akiYC_CB7Ffw@mail.gmail.com>
223 my $date = $mime->header('Date');
224 my $subject = $mime->header('Subject');
225 $subject = '(no subject)' unless defined $subject;
226 my $path_type = $self->{path_type};
229 if ($path_type eq '2/38') {
230 $path = mid2path(mid_mime($mime));
231 } else { # v2 layout, one file:
235 my ($r, $w) = $self->gfi_start;
236 my $tip = $self->{tip};
237 if ($path_type eq '2/38') {
238 _check_path($r, $w, $tip, $path) and return;
241 # kill potentially confusing/misleading headers
242 $mime->header_set($_) for qw(bytes lines content-length status);
246 $mime = $check_cb->($mime) or return;
249 $mime = $mime->as_string;
250 my $blob = $self->{mark}++;
251 print $w "blob\nmark :$blob\ndata ", length($mime), "\n" or wfail;
252 print $w $mime, "\n" or wfail;
254 # v2: we need this for Xapian
255 if ($self->{want_object_id}) {
256 chomp($self->{last_object_id} = $self->get_mark(":$blob"));
259 my $ref = $self->{ref};
260 my $commit = $self->{mark}++;
261 my $parent = $tip =~ /\A:/ ? $tip : undef;
264 print $w "reset $ref\n" or wfail;
267 utf8::encode($email);
269 utf8::encode($subject);
270 # quiet down wide character warnings:
271 print $w "commit $ref\nmark :$commit\n",
272 "author $name <$email> $date\n",
273 "committer $self->{ident} ", now2822(), "\n" or wfail;
274 print $w "data ", (length($subject) + 1), "\n",
275 $subject, "\n\n" or wfail;
277 print $w 'from ', ($parent ? $parent : $tip), "\n" or wfail;
279 print $w "M 100644 :$blob $path\n\n" or wfail;
281 $self->{tip} = ":$commit";
285 my ($cmd, $env) = @_;
286 my $pid = spawn($cmd, $env, undef);
287 defined $pid or die "spawning ".join(' ', @$cmd)." failed: $!";
288 waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
289 $? == 0 or die join(' ', @$cmd) . " failed: $?\n";
294 my $w = delete $self->{out} or return;
295 my $r = delete $self->{in} or die 'BUG: missing {in} when done';
296 print $w "done\n" or wfail;
297 my $pid = delete $self->{pid} or die 'BUG: missing {pid} when done';
298 waitpid($pid, 0) == $pid or die 'fast-import did not finish';
299 $? == 0 or die "fast-import failed: $?";
300 my $nchg = delete $self->{nchg};
302 # for compatibility with existing ssoma installations
303 # we can probably remove this entirely by 2020
304 my $git_dir = $self->{git}->{git_dir};
305 my @cmd = ('git', "--git-dir=$git_dir");
306 my $index = "$git_dir/ssoma.index";
307 if ($nchg && -e $index && !$ENV{FAST}) {
308 my $env = { GIT_INDEX_FILE => $index };
309 run_die([@cmd, qw(read-tree -m -v -i), $self->{ref}], $env);
312 run_die([@cmd, 'update-server-info'], undef);
314 require PublicInbox::SearchIdx;
315 my $inbox = $self->{inbox} || $git_dir;
316 my $s = PublicInbox::SearchIdx->new($inbox);
317 $s->index_sync({ ref => $self->{ref} });
320 eval { run_die([@cmd, qw(gc --auto)], undef) };
323 $self->{ssoma_lock} or return;
324 my $lockfh = delete $self->{lockfh} or die "BUG: not locked: $!";
325 flock($lockfh, LOCK_UN) or die "unlock failed: $!";
326 close $lockfh or die "close lock failed: $!";
335 PublicInbox::Import - message importer for public-inbox
344 use PublicInbox::Git;
345 use PublicInbox::Import;
347 chomp(my $git_dir = `git rev-parse --git-dir`);
348 $git_dir or die "GIT_DIR= must be specified\n";
349 my $git = PublicInbox::Git->new($git_dir);
350 my @committer = ('inbox', 'inbox@example.org');
351 my $im = PublicInbox::Import->new($git, @committer);
354 my $message = "From: <u\@example.org>\n".
355 "Subject: test message \n" .
356 "Date: Thu, 01 Jan 1970 00:00:00 +0000\n" .
357 "Message-ID: <m\@example.org>\n".
359 my $parsed = Email::MIME->new($message);
360 my $ret = $im->add($parsed);
363 $parsed->header_obj->header_raw('Message-ID'), "\n";
365 print "imported at mark $ret\n";
369 # to remove a message
370 my $junk = Email::MIME->new($message);
371 my ($mark, $orig) = $im->remove($junk);
372 if ($mark eq 'MISSING') {
374 } elsif ($mark eq 'MISMATCH') {
375 print "Message exists but does not match\n\n",
376 $orig->as_string, "\n",;
378 print "removed at mark $mark\n\n",
379 $orig->as_string, "\n";
385 An importer and remover for public-inboxes which takes L<Email::MIME>
386 messages as input and stores them in a ssoma repository as
387 documented in L<https://ssoma.public-inbox.org/ssoma_repository.txt>,
388 except it does not allow duplicate Message-IDs.
390 It requires L<git(1)> and L<git-fast-import(1)> to be installed.
398 my $im = PublicInbox::Import->new($git, @committer);
400 Initialize a new PublicInbox::Import object.
404 my $parsed = Email::MIME->new($message);
407 Adds a message to to the git repository. This will acquire
408 C<$GIT_DIR/ssoma.lock> and start L<git-fast-import(1)> if necessary.
410 Messages added will not be visible to other processes until L</done>
411 is called, but L</remove> may be called on them.
415 my $junk = Email::MIME->new($message);
416 my ($code, $orig) = $im->remove($junk);
418 Removes a message from the repository. On success, it returns
419 a ':'-prefixed numeric code representing the git-fast-import
420 mark and the original messages as an Email::MIME object.
421 If the message could not be found, the code is "MISSING"
422 and the original message is undef. If there is a mismatch where
423 the "Message-ID" is matched but the subject and body do not match,
424 the returned code is "MISMATCH" and the conflicting message
429 Finalizes the L<git-fast-import(1)> and unlocks the repository.
430 Calling this is required to finalize changes to a repository.
438 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
440 The mail archives are hosted at L<https://public-inbox.org/meta/>
444 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
446 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>