1 # Copyright (C) 2016 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);
15 my ($class, $git, $name, $email) = @_;
18 ident => "$name <$email>",
20 ref => 'refs/heads/master',
24 # idempotent start function
28 return ($self->{in}, $self->{out}) if $self->{pid};
30 my ($in_r, $in_w, $out_r, $out_w);
31 pipe($in_r, $in_w) or die "pipe failed: $!";
32 pipe($out_r, $out_w) or die "pipe failed: $!";
33 my $git = $self->{git};
34 my $git_dir = $git->{git_dir};
35 my $lockpath = "$git_dir/ssoma.lock";
36 sysopen(my $lockfh, $lockpath, O_WRONLY|O_CREAT) or
37 die "failed to open lock $lockpath: $!";
39 # wait for other processes to be done
40 flock($lockfh, LOCK_EX) or die "lock failed: $!\n";
42 chomp($self->{tip} = $git->qx(qw(rev-parse --revs-only), $self->{ref}));
44 my @cmd = ('git', "--git-dir=$git_dir", qw(fast-import
45 --quiet --done --date-format=rfc2822));
46 my $rdr = { 0 => fileno($out_r), 1 => fileno($in_w) };
47 my $pid = spawn(\@cmd, undef, $rdr);
48 die "spawn fast-import failed: $!" unless defined $pid;
51 $self->{out} = $out_w;
52 $self->{lockfh} = $lockfh;
58 sub wfail () { die "write to fast-import failed: $!" }
62 my $day = qw(Sun Mon Tue Wed Thu Fri Sat)[$t[6]];
63 my $mon = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)[$t[4]];
65 sprintf('%s, %2d %s %d %02d:%02d:%02d +0000',
66 $day, $t[3], $mon, $t[5] + 1900, $t[2], $t[1], $t[0]);
71 my $b = $mime->body_raw;
72 $b =~ s/(\r?\n)+\z//s;
76 # returns undef on non-existent
77 # ('MISMATCH', msg) on mismatch
78 # (:MARK, msg) on success
80 my ($self, $mime) = @_; # mime = Email::MIME
82 my $mid = mid_mime($mime);
83 my $path = mid2path($mid);
85 my ($r, $w) = $self->gfi_start;
86 my $tip = $self->{tip};
87 return ('MISSING', undef) if $tip eq '';
89 print $w "ls $tip $path\n" or wfail;
92 defined $check or die "EOF from fast-import / ls: $!";
93 return ('MISSING', undef) if $check =~ /\Amissing /;
94 $check =~ m!\A100644 blob ([a-f0-9]{40})\t!s or die "not blob: $check";
96 print $w "cat-blob $blob\n" or wfail;
98 defined $check or die "EOF from fast-import / cat-blob: $!";
99 $check =~ /\A[a-f0-9]{40} blob (\d+)\n\z/ or
100 die "unexpected cat-blob response: $check";
106 $n = read($r, $buf, $left, $offset);
107 defined($n) or die "read cat-blob failed: $!";
108 $n == 0 and die 'fast-export (cat-blob) died';
112 $n = read($r, my $lf, 1);
113 defined($n) or die "read final byte of cat-blob failed: $!";
114 die "bad read on final byte: <$lf>" if $lf ne "\n";
115 my $cur = Email::MIME->new($buf);
116 my $cur_s = $cur->header('Subject');
117 $cur_s = '' unless defined $cur_s;
118 my $cur_m = $mime->header('Subject');
119 $cur_m = '' unless defined $cur_m;
120 if ($cur_s ne $cur_m || norm_body($cur) ne norm_body($mime)) {
121 return ('MISMATCH', $cur);
124 my $ref = $self->{ref};
125 my $commit = $self->{mark}++;
126 my $parent = $tip =~ /\A:/ ? $tip : undef;
128 print $w "reset $ref\n" or wfail;
130 my $ident = $self->{ident};
132 print $w "commit $ref\nmark :$commit\n",
133 "author $ident $now\n",
134 "committer $ident $now\n",
136 'from ', ($parent ? $parent : $tip), "\n" or wfail;
137 print $w "D $path\n\n" or wfail;
139 (($self->{tip} = ":$commit"), $cur);
142 # returns undef on duplicate
144 my ($self, $mime, $check_cb) = @_; # mime = Email::MIME
146 my $from = $mime->header('From');
147 my ($email) = ($from =~ /([^<\s]+\@[^>\s]+)/g);
149 $name =~ s/\s*\S+\@\S+\s*\z//;
150 # git gets confused with:
151 # "'A U Thor <u@example.com>' via foo" <foo@example.com>
153 # <CAD0k6qSUYANxbjjbE4jTW4EeVwOYgBD=bXkSu=akiYC_CB7Ffw@mail.gmail.com>
154 $name =~ tr/<>// and $name = $email;
156 my $date = $mime->header('Date');
157 my $subject = $mime->header('Subject');
158 $subject = '(no subject)' unless defined $subject;
159 my $mid = mid_mime($mime);
160 my $path = mid2path($mid);
162 my ($r, $w) = $self->gfi_start;
163 my $tip = $self->{tip};
165 print $w "ls $tip $path\n" or wfail;
168 defined $check or die "EOF from fast-import: $!";
169 return unless $check =~ /\Amissing /;
172 # kill potentially confusing/misleading headers
173 $mime->header_set($_) for qw(bytes lines content-length status);
175 $mime = $check_cb->($mime) or return;
178 $mime = $mime->as_string;
179 my $blob = $self->{mark}++;
180 print $w "blob\nmark :$blob\ndata ", length($mime), "\n" or wfail;
181 print $w $mime, "\n" or wfail;
182 my $ref = $self->{ref};
183 my $commit = $self->{mark}++;
184 my $parent = $tip =~ /\A:/ ? $tip : undef;
187 print $w "reset $ref\n" or wfail;
190 # quiet down wide character warnings:
191 binmode $w, ':utf8' or die "binmode :utf8 failed: $!";
192 print $w "commit $ref\nmark :$commit\n",
193 "author $name <$email> $date\n",
194 "committer $self->{ident} ", now2822(), "\n",
195 "data ", (bytes::length($subject) + 1), "\n",
196 $subject, "\n\n" or wfail;
197 binmode $w, ':raw' or die "binmode :raw failed: $!";
200 print $w 'from ', ($parent ? $parent : $tip), "\n" or wfail;
202 print $w "M 100644 :$blob $path\n\n" or wfail;
204 $self->{tip} = ":$commit";
209 my $w = delete $self->{out} or return;
210 my $r = delete $self->{in} or die 'BUG: missing {in} when done';
211 print $w "done\n" or wfail;
212 my $pid = delete $self->{pid} or die 'BUG: missing {pid} when done';
213 waitpid($pid, 0) == $pid or die 'fast-import did not finish';
214 $? == 0 or die "fast-import failed: $?";
215 my $nchg = delete $self->{nchg};
217 # for compatibility with existing ssoma installations
218 # we can probably remove this entirely by 2020
219 my $git_dir = $self->{git}->{git_dir};
220 # XXX: change the following scope to: if (-e $index) # in 2018 or so..
221 my @cmd = ('git', "--git-dir=$git_dir");
222 if ($nchg && !$ENV{FAST}) {
223 my $index = "$git_dir/ssoma.index";
224 my $env = { GIT_INDEX_FILE => $index };
225 my @rt = (@cmd, qw(read-tree -m -v -i), $self->{ref});
226 $pid = spawn(\@rt, $env, undef);
227 defined $pid or die "spawn read-tree failed: $!";
228 waitpid($pid, 0) == $pid or die 'read-tree did not finish';
229 $? == 0 or die "failed to update $git_dir/ssoma.index: $?\n";
232 $pid = spawn([@cmd, 'update-server-info'], undef, undef);
233 defined $pid or die "spawn update-server-info failed: $!\n";
234 waitpid($pid, 0) == $pid or
235 die 'update-server-info did not finish';
236 $? == 0 or die "failed to update-server-info: $?\n";
239 require PublicInbox::SearchIdx;
240 PublicInbox::SearchIdx->new($git_dir, 2)->index_sync;
244 my $lockfh = delete $self->{lockfh} or die "BUG: not locked: $!";
245 flock($lockfh, LOCK_UN) or die "unlock failed: $!";
246 close $lockfh or die "close lock failed: $!";
255 PublicInbox::Import - message importer for public-inbox
264 use PublicInbox::Git;
265 use PublicInbox::Import;
267 chomp(my $git_dir = `git rev-parse --git-dir`);
268 $git_dir or die "GIT_DIR= must be specified\n";
269 my $git = PublicInbox::Git->new($git_dir);
270 my @committer = ('inbox', 'inbox@example.org');
271 my $im = PublicInbox::Import->new($git, @committer);
274 my $message = "From: <u\@example.org>\n".
275 "Subject: test message \n" .
276 "Date: Thu, 01 Jan 1970 00:00:00 +0000\n" .
277 "Message-ID: <m\@example.org>\n".
279 my $parsed = Email::MIME->new($message);
280 my $ret = $im->add($parsed);
283 $parsed->header_obj->header_raw('Message-ID'), "\n";
285 print "imported at mark $ret\n";
289 # to remove a message
290 my $junk = Email::MIME->new($message);
291 my ($mark, $orig) = $im->remove($junk);
292 if ($mark eq 'MISSING') {
294 } elsif ($mark eq 'MISMATCH') {
295 print "Message exists but does not match\n\n",
296 $orig->as_string, "\n",;
298 print "removed at mark $mark\n\n",
299 $orig->as_string, "\n";
305 An importer and remover for public-inboxes which takes L<Email::MIME>
306 messages as input and stores them in a ssoma repository as
307 documented in L<https://ssoma.public-inbox.org/ssoma_repository.txt>,
308 except it does not allow duplicate Message-IDs.
310 It requires L<git(1)> and L<git-fast-import(1)> to be installed.
318 my $im = PublicInbox::Import->new($git, @committer);
320 Initialize a new PublicInbox::Import object.
324 my $parsed = Email::MIME->new($message);
327 Adds a message to to the git repository. This will acquire
328 C<$GIT_DIR/ssoma.lock> and start L<git-fast-import(1)> if necessary.
330 Messages added will not be visible to other processes until L</done>
331 is called, but L</remove> may be called on them.
335 my $junk = Email::MIME->new($message);
336 my ($code, $orig) = $im->remove($junk);
338 Removes a message from the repository. On success, it returns
339 a ':'-prefixed numeric code representing the git-fast-import
340 mark and the original messages as an Email::MIME object.
341 If the message could not be found, the code is "MISSING"
342 and the original message is undef. If there is a mismatch where
343 the "Message-ID" is matched but the subject and body do not match,
344 the returned code is "MISMATCH" and the conflicting message
349 Finalizes the L<git-fast-import(1)> and unlocks the repository.
350 Calling this is required to finalize changes to a repository.
358 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
360 The mail archives are hosted at L<https://public-inbox.org/meta/>
364 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
366 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>