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 # returns undef on non-existent
142 # ('MISMATCH', msg) on mismatch
143 # (:MARK, msg) on success
145 # For v2 inboxes, the content_id is returned instead of the msg
146 # v2 callers should check with Xapian before calling this as
147 # it is not idempotent.
149 my ($self, $mime, $msg) = @_; # mime = Email::MIME
151 my $path_type = $self->{path_type};
152 my ($path, $err, $cur, $blob);
154 my ($r, $w) = $self->gfi_start;
155 my $tip = $self->{tip};
156 if ($path_type eq '2/38') {
157 $path = mid2path(mid_mime($mime));
158 ($err, $cur) = check_remove_v1($r, $w, $tip, $path, $mime);
159 return ($err, $cur) if $err;
161 $cur = content_id($mime);
162 my $len = length($cur);
163 $blob = $self->{mark}++;
164 print $w "blob\nmark :$blob\ndata $len\n$cur\n" or wfail;
167 my $ref = $self->{ref};
168 my $commit = $self->{mark}++;
169 my $parent = $tip =~ /\A:/ ? $tip : undef;
171 print $w "reset $ref\n" or wfail;
173 my $ident = $self->{ident};
176 my $len = length($msg) + 1;
177 print $w "commit $ref\nmark :$commit\n",
178 "author $ident $now\n",
179 "committer $ident $now\n",
180 "data $len\n$msg\n\n",
181 'from ', ($parent ? $parent : $tip), "\n" or wfail;
183 print $w "D $path\n\n" or wfail;
185 print $w "M 100644 :$blob d\n\n" or wfail;
188 (($self->{tip} = ":$commit"), $cur);
191 # returns undef on duplicate
193 my ($self, $mime, $check_cb) = @_; # mime = Email::MIME
195 my $from = $mime->header('From');
196 my ($email) = PublicInbox::Address::emails($from);
197 my ($name) = PublicInbox::Address::names($from);
198 # git gets confused with:
199 # "'A U Thor <u@example.com>' via foo" <foo@example.com>
201 # <CAD0k6qSUYANxbjjbE4jTW4EeVwOYgBD=bXkSu=akiYC_CB7Ffw@mail.gmail.com>
204 my $date = $mime->header('Date');
205 my $subject = $mime->header('Subject');
206 $subject = '(no subject)' unless defined $subject;
207 my $path_type = $self->{path_type};
210 if ($path_type eq '2/38') {
211 $path = mid2path(mid_mime($mime));
212 } else { # v2 layout, one file:
216 my ($r, $w) = $self->gfi_start;
217 my $tip = $self->{tip};
218 if ($path_type eq '2/38') {
219 _check_path($r, $w, $tip, $path) and return;
222 # kill potentially confusing/misleading headers
223 $mime->header_set($_) for qw(bytes lines content-length status);
227 $mime = $check_cb->($mime) or return;
230 $mime = $mime->as_string;
231 my $blob = $self->{mark}++;
232 print $w "blob\nmark :$blob\ndata ", length($mime), "\n" or wfail;
233 print $w $mime, "\n" or wfail;
235 # v2: we need this for Xapian
236 if ($self->{want_object_id}) {
237 print $w "get-mark :$blob\n" or wfail;
238 defined(my $object_id = <$r>) or
239 die "get-mark failed, need git 2.6.0+\n";
240 chomp($self->{last_object_id} = $object_id);
243 my $ref = $self->{ref};
244 my $commit = $self->{mark}++;
245 my $parent = $tip =~ /\A:/ ? $tip : undef;
248 print $w "reset $ref\n" or wfail;
251 utf8::encode($email);
253 utf8::encode($subject);
254 # quiet down wide character warnings:
255 print $w "commit $ref\nmark :$commit\n",
256 "author $name <$email> $date\n",
257 "committer $self->{ident} ", now2822(), "\n" or wfail;
258 print $w "data ", (length($subject) + 1), "\n",
259 $subject, "\n\n" or wfail;
261 print $w 'from ', ($parent ? $parent : $tip), "\n" or wfail;
263 print $w "M 100644 :$blob $path\n\n" or wfail;
265 $self->{tip} = ":$commit";
269 my ($cmd, $env) = @_;
270 my $pid = spawn($cmd, $env, undef);
271 defined $pid or die "spawning ".join(' ', @$cmd)." failed: $!";
272 waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
273 $? == 0 or die join(' ', @$cmd) . " failed: $?\n";
278 my $w = delete $self->{out} or return;
279 my $r = delete $self->{in} or die 'BUG: missing {in} when done';
280 print $w "done\n" or wfail;
281 my $pid = delete $self->{pid} or die 'BUG: missing {pid} when done';
282 waitpid($pid, 0) == $pid or die 'fast-import did not finish';
283 $? == 0 or die "fast-import failed: $?";
284 my $nchg = delete $self->{nchg};
286 # for compatibility with existing ssoma installations
287 # we can probably remove this entirely by 2020
288 my $git_dir = $self->{git}->{git_dir};
289 my @cmd = ('git', "--git-dir=$git_dir");
290 my $index = "$git_dir/ssoma.index";
291 if ($nchg && -e $index && !$ENV{FAST}) {
292 my $env = { GIT_INDEX_FILE => $index };
293 run_die([@cmd, qw(read-tree -m -v -i), $self->{ref}], $env);
296 run_die([@cmd, 'update-server-info'], undef);
298 require PublicInbox::SearchIdx;
299 my $inbox = $self->{inbox} || $git_dir;
300 my $s = PublicInbox::SearchIdx->new($inbox);
301 $s->index_sync({ ref => $self->{ref} });
304 eval { run_die([@cmd, qw(gc --auto)], undef) };
307 $self->{ssoma_lock} or return;
308 my $lockfh = delete $self->{lockfh} or die "BUG: not locked: $!";
309 flock($lockfh, LOCK_UN) or die "unlock failed: $!";
310 close $lockfh or die "close lock failed: $!";
319 PublicInbox::Import - message importer for public-inbox
328 use PublicInbox::Git;
329 use PublicInbox::Import;
331 chomp(my $git_dir = `git rev-parse --git-dir`);
332 $git_dir or die "GIT_DIR= must be specified\n";
333 my $git = PublicInbox::Git->new($git_dir);
334 my @committer = ('inbox', 'inbox@example.org');
335 my $im = PublicInbox::Import->new($git, @committer);
338 my $message = "From: <u\@example.org>\n".
339 "Subject: test message \n" .
340 "Date: Thu, 01 Jan 1970 00:00:00 +0000\n" .
341 "Message-ID: <m\@example.org>\n".
343 my $parsed = Email::MIME->new($message);
344 my $ret = $im->add($parsed);
347 $parsed->header_obj->header_raw('Message-ID'), "\n";
349 print "imported at mark $ret\n";
353 # to remove a message
354 my $junk = Email::MIME->new($message);
355 my ($mark, $orig) = $im->remove($junk);
356 if ($mark eq 'MISSING') {
358 } elsif ($mark eq 'MISMATCH') {
359 print "Message exists but does not match\n\n",
360 $orig->as_string, "\n",;
362 print "removed at mark $mark\n\n",
363 $orig->as_string, "\n";
369 An importer and remover for public-inboxes which takes L<Email::MIME>
370 messages as input and stores them in a ssoma repository as
371 documented in L<https://ssoma.public-inbox.org/ssoma_repository.txt>,
372 except it does not allow duplicate Message-IDs.
374 It requires L<git(1)> and L<git-fast-import(1)> to be installed.
382 my $im = PublicInbox::Import->new($git, @committer);
384 Initialize a new PublicInbox::Import object.
388 my $parsed = Email::MIME->new($message);
391 Adds a message to to the git repository. This will acquire
392 C<$GIT_DIR/ssoma.lock> and start L<git-fast-import(1)> if necessary.
394 Messages added will not be visible to other processes until L</done>
395 is called, but L</remove> may be called on them.
399 my $junk = Email::MIME->new($message);
400 my ($code, $orig) = $im->remove($junk);
402 Removes a message from the repository. On success, it returns
403 a ':'-prefixed numeric code representing the git-fast-import
404 mark and the original messages as an Email::MIME object.
405 If the message could not be found, the code is "MISSING"
406 and the original message is undef. If there is a mismatch where
407 the "Message-ID" is matched but the subject and body do not match,
408 the returned code is "MISMATCH" and the conflicting message
413 Finalizes the L<git-fast-import(1)> and unlocks the repository.
414 Calling this is required to finalize changes to a repository.
422 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
424 The mail archives are hosted at L<https://public-inbox.org/meta/>
428 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
430 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>