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 Date::Parse qw(str2time);
16 use Time::Zone qw(tz_offset);
19 my ($class, $git, $name, $email, $ibx) = @_;
20 my $ref = 'refs/heads/master';
22 $ref = $ibx->{ref_head} || 'refs/heads/master';
23 $name ||= $ibx->{name};
24 $email ||= $ibx->{-primary_address};
28 ident => "$name <$email>",
32 path_type => '2/38', # or 'v2'
33 ssoma_lock => 1, # disable for v2
38 # idempotent start function
42 return ($self->{in}, $self->{out}) if $self->{pid};
44 my ($in_r, $in_w, $out_r, $out_w);
45 pipe($in_r, $in_w) or die "pipe failed: $!";
46 pipe($out_r, $out_w) or die "pipe failed: $!";
47 my $git = $self->{git};
48 my $git_dir = $git->{git_dir};
51 if ($self->{ssoma_lock}) {
52 my $lockpath = "$git_dir/ssoma.lock";
53 sysopen($lockfh, $lockpath, O_WRONLY|O_CREAT) or
54 die "failed to open lock $lockpath: $!";
55 # wait for other processes to be done
56 flock($lockfh, LOCK_EX) or die "lock failed: $!\n";
60 chomp($self->{tip} = $git->qx(qw(rev-parse --revs-only), $self->{ref}));
62 my @cmd = ('git', "--git-dir=$git_dir", qw(fast-import
63 --quiet --done --date-format=raw));
64 my $rdr = { 0 => fileno($out_r), 1 => fileno($in_w) };
65 my $pid = spawn(\@cmd, undef, $rdr);
66 die "spawn fast-import failed: $!" unless defined $pid;
69 $self->{out} = $out_w;
70 $self->{lockfh} = $lockfh;
73 binmode $out_w, ':raw' or die "binmode :raw failed: $!";
74 binmode $in_r, ':raw' or die "binmode :raw failed: $!";
78 sub wfail () { die "write to fast-import failed: $!" }
80 sub now_raw () { time . ' +0000' }
84 my $b = $mime->body_raw;
85 $b =~ s/(\r?\n)+\z//s;
89 # only used for v1 (ssoma) inboxes
90 sub _check_path ($$$$) {
91 my ($r, $w, $tip, $path) = @_;
93 print $w "ls $tip $path\n" or wfail;
95 defined(my $info = <$r>) or die "EOF from fast-import: $!";
96 $info =~ /\Amissing / ? undef : $info;
100 my ($r, $w, $tip, $path, $mime) = @_;
102 my $info = _check_path($r, $w, $tip, $path) or return ('MISSING',undef);
103 $info =~ m!\A100644 blob ([a-f0-9]{40})\t!s or die "not blob: $info";
106 print $w "cat-blob $blob\n" or wfail;
109 defined $info or die "EOF from fast-import / cat-blob: $!";
110 $info =~ /\A[a-f0-9]{40} blob (\d+)\n\z/ or
111 die "unexpected cat-blob response: $info";
117 $n = read($r, $buf, $left, $offset);
118 defined($n) or die "read cat-blob failed: $!";
119 $n == 0 and die 'fast-export (cat-blob) died';
123 $n = read($r, my $lf, 1);
124 defined($n) or die "read final byte of cat-blob failed: $!";
125 die "bad read on final byte: <$lf>" if $lf ne "\n";
126 my $cur = PublicInbox::MIME->new($buf);
127 my $cur_s = $cur->header('Subject');
128 $cur_s = '' unless defined $cur_s;
129 my $cur_m = $mime->header('Subject');
130 $cur_m = '' unless defined $cur_m;
131 if ($cur_s ne $cur_m || norm_body($cur) ne norm_body($mime)) {
132 return ('MISMATCH', $cur);
137 # used for v2 (maybe)
140 return unless $self->{pid};
141 print { $self->{out} } "checkpoint\n" or wfail;
147 my ($self, $mark) = @_;
148 die "not active\n" unless $self->{pid};
149 my ($r, $w) = $self->gfi_start;
150 print $w "get-mark $mark\n" or wfail;
151 defined(my $oid = <$r>) or die "get-mark failed, need git 2.6.0+\n";
155 # returns undef on non-existent
156 # ('MISMATCH', Email::MIME) on mismatch
157 # (:MARK, Email::MIME) on success
159 # For v2 inboxes, the content_id is returned instead of the msg
160 # v2 callers should check with Xapian before calling this as
161 # it is not idempotent.
163 my ($self, $mime, $msg) = @_; # mime = Email::MIME
165 my $path_type = $self->{path_type};
166 my ($path, $err, $cur, $blob);
168 my ($r, $w) = $self->gfi_start;
169 my $tip = $self->{tip};
170 if ($path_type eq '2/38') {
171 $path = mid2path(mid_mime($mime));
172 ($err, $cur) = check_remove_v1($r, $w, $tip, $path, $mime);
173 return ($err, $cur) if $err;
175 $cur = content_id($mime);
176 my $len = length($cur);
177 $blob = $self->{mark}++;
178 print $w "blob\nmark :$blob\ndata $len\n$cur\n" or wfail;
181 my $ref = $self->{ref};
182 my $commit = $self->{mark}++;
183 my $parent = $tip =~ /\A:/ ? $tip : undef;
185 print $w "reset $ref\n" or wfail;
187 my $ident = $self->{ident};
190 my $len = length($msg) + 1;
191 print $w "commit $ref\nmark :$commit\n",
192 "author $ident $now\n",
193 "committer $ident $now\n",
194 "data $len\n$msg\n\n",
195 'from ', ($parent ? $parent : $tip), "\n" or wfail;
197 print $w "D $path\n\n" or wfail;
199 print $w "M 100644 :$blob d\n\n" or wfail;
202 (($self->{tip} = ":$commit"), $cur);
207 my $hdr = $mime->header_obj;
208 my $date = $hdr->header_raw('Date');
210 my $mid = $hdr->header_raw('Message-ID');
212 $ts = eval { str2time($date) };
214 warn "bad Date: $date in $mid: $@\n";
215 } elsif ($date =~ /\s+([\+\-]\d+)\s*\z/) {
220 my @recvd = $hdr->header_raw('Received');
221 foreach my $r (@recvd) {
223 $r =~ /\s*(\d+\s+[[:alpha:]]+\s+\d{2,4}\s+
224 \d+\D\d+(?:\D\d+)\s+([\+\-]\d+))/osx or next;
226 $ts = eval { str2time($1) } and last;
227 warn "no date in Received: $r\n";
231 # "-1200" is the furthest westermost zone offset,
232 # but git fast-import is liberal so we use "-1400"
233 if ($zone >= 1400 || $zone <= -1400) {
234 warn "bogus TZ offset: $zone, ignoring and assuming +0000\n";
237 $ts = time unless defined $ts;
238 $ts = 0 if $ts < 0; # git uses unsigned times
242 # returns undef on duplicate
243 # returns the :MARK of the most recent commit
245 my ($self, $mime, $check_cb) = @_; # mime = Email::MIME
247 my $from = $mime->header('From');
248 my ($email) = PublicInbox::Address::emails($from);
249 my ($name) = PublicInbox::Address::names($from);
251 my $date_raw = parse_date($mime);
252 my $subject = $mime->header('Subject');
253 $subject = '(no subject)' unless defined $subject;
254 my $path_type = $self->{path_type};
257 if ($path_type eq '2/38') {
258 $path = mid2path(mid_mime($mime));
259 } else { # v2 layout, one file:
263 my ($r, $w) = $self->gfi_start;
264 my $tip = $self->{tip};
265 if ($path_type eq '2/38') {
266 _check_path($r, $w, $tip, $path) and return;
269 # kill potentially confusing/misleading headers
270 $mime->header_set($_) for qw(bytes lines content-length status);
274 $mime = $check_cb->($mime) or return;
277 my $blob = $self->{mark}++;
278 my $str = $mime->as_string;
279 my $n = length($str);
280 $self->{bytes_added} += $n;
281 print $w "blob\nmark :$blob\ndata ", $n, "\n" or wfail;
282 print $w $str, "\n" or wfail;
284 # v2: we need this for Xapian
285 if ($self->{want_object_id}) {
286 chomp($self->{last_object_id} = $self->get_mark(":$blob"));
287 $self->{last_object} = [ $n, \$str ];
289 my $ref = $self->{ref};
290 my $commit = $self->{mark}++;
291 my $parent = $tip =~ /\A:/ ? $tip : undef;
294 print $w "reset $ref\n" or wfail;
297 # quiet down wide character warnings with utf8::encode
298 if (defined $email) {
299 utf8::encode($email);
302 warn "no email in From: $from\n";
305 # git gets confused with:
306 # "'A U Thor <u@example.com>' via foo" <foo@example.com>
308 # <CAD0k6qSUYANxbjjbE4jTW4EeVwOYgBD=bXkSu=akiYC_CB7Ffw@mail.gmail.com>
314 warn "no name in From: $from\n";
316 utf8::encode($subject);
317 print $w "commit $ref\nmark :$commit\n",
318 "author $name <$email> $date_raw\n",
319 "committer $self->{ident} ", now_raw(), "\n" or wfail;
320 print $w "data ", (length($subject) + 1), "\n",
321 $subject, "\n\n" or wfail;
323 print $w 'from ', ($parent ? $parent : $tip), "\n" or wfail;
325 print $w "M 100644 :$blob $path\n\n" or wfail;
327 $self->{tip} = ":$commit";
331 my ($cmd, $env) = @_;
332 my $pid = spawn($cmd, $env, undef);
333 defined $pid or die "spawning ".join(' ', @$cmd)." failed: $!";
334 waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
335 $? == 0 or die join(' ', @$cmd) . " failed: $?\n";
340 my $w = delete $self->{out} or return;
341 my $r = delete $self->{in} or die 'BUG: missing {in} when done';
342 print $w "done\n" or wfail;
343 my $pid = delete $self->{pid} or die 'BUG: missing {pid} when done';
344 waitpid($pid, 0) == $pid or die 'fast-import did not finish';
345 $? == 0 or die "fast-import failed: $?";
346 my $nchg = delete $self->{nchg};
348 # for compatibility with existing ssoma installations
349 # we can probably remove this entirely by 2020
350 my $git_dir = $self->{git}->{git_dir};
351 my @cmd = ('git', "--git-dir=$git_dir");
352 my $index = "$git_dir/ssoma.index";
353 if ($nchg && -e $index && !$ENV{FAST}) {
354 my $env = { GIT_INDEX_FILE => $index };
355 run_die([@cmd, qw(read-tree -m -v -i), $self->{ref}], $env);
358 run_die([@cmd, 'update-server-info'], undef);
359 ($self->{path_type} eq '2/38') and eval {
360 require PublicInbox::SearchIdx;
361 my $inbox = $self->{inbox} || $git_dir;
362 my $s = PublicInbox::SearchIdx->new($inbox);
363 $s->index_sync({ ref => $self->{ref} });
366 eval { run_die([@cmd, qw(gc --auto)], undef) };
369 $self->{ssoma_lock} or return;
370 my $lockfh = delete $self->{lockfh} or die "BUG: not locked: $!";
371 flock($lockfh, LOCK_UN) or die "unlock failed: $!";
372 close $lockfh or die "close lock failed: $!";
377 foreach my $f (qw(in out)) {
378 close $self->{$f} or die "failed to close import[$f]: $!\n";
388 PublicInbox::Import - message importer for public-inbox
397 use PublicInbox::Git;
398 use PublicInbox::Import;
400 chomp(my $git_dir = `git rev-parse --git-dir`);
401 $git_dir or die "GIT_DIR= must be specified\n";
402 my $git = PublicInbox::Git->new($git_dir);
403 my @committer = ('inbox', 'inbox@example.org');
404 my $im = PublicInbox::Import->new($git, @committer);
407 my $message = "From: <u\@example.org>\n".
408 "Subject: test message \n" .
409 "Date: Thu, 01 Jan 1970 00:00:00 +0000\n" .
410 "Message-ID: <m\@example.org>\n".
412 my $parsed = Email::MIME->new($message);
413 my $ret = $im->add($parsed);
416 $parsed->header_obj->header_raw('Message-ID'), "\n";
418 print "imported at mark $ret\n";
422 # to remove a message
423 my $junk = Email::MIME->new($message);
424 my ($mark, $orig) = $im->remove($junk);
425 if ($mark eq 'MISSING') {
427 } elsif ($mark eq 'MISMATCH') {
428 print "Message exists but does not match\n\n",
429 $orig->as_string, "\n",;
431 print "removed at mark $mark\n\n",
432 $orig->as_string, "\n";
438 An importer and remover for public-inboxes which takes L<Email::MIME>
439 messages as input and stores them in a ssoma repository as
440 documented in L<https://ssoma.public-inbox.org/ssoma_repository.txt>,
441 except it does not allow duplicate Message-IDs.
443 It requires L<git(1)> and L<git-fast-import(1)> to be installed.
451 my $im = PublicInbox::Import->new($git, @committer);
453 Initialize a new PublicInbox::Import object.
457 my $parsed = Email::MIME->new($message);
460 Adds a message to to the git repository. This will acquire
461 C<$GIT_DIR/ssoma.lock> and start L<git-fast-import(1)> if necessary.
463 Messages added will not be visible to other processes until L</done>
464 is called, but L</remove> may be called on them.
468 my $junk = Email::MIME->new($message);
469 my ($code, $orig) = $im->remove($junk);
471 Removes a message from the repository. On success, it returns
472 a ':'-prefixed numeric code representing the git-fast-import
473 mark and the original messages as an Email::MIME object.
474 If the message could not be found, the code is "MISSING"
475 and the original message is undef. If there is a mismatch where
476 the "Message-ID" is matched but the subject and body do not match,
477 the returned code is "MISMATCH" and the conflicting message
482 Finalizes the L<git-fast-import(1)> and unlocks the repository.
483 Calling this is required to finalize changes to a repository.
491 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
493 The mail archives are hosted at L<https://public-inbox.org/meta/>
497 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
499 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>