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";
41 chomp($self->{tip} = $git->qx(qw(rev-parse --revs-only), $self->{ref}));
43 my @cmd = ('git', "--git-dir=$git_dir", qw(fast-import
44 --quiet --done --date-format=rfc2822));
45 my $rdr = { 0 => fileno($out_r), 1 => fileno($in_w) };
46 my $pid = spawn(\@cmd, undef, $rdr);
47 die "spawn fast-import failed: $!" unless defined $pid;
50 $self->{out} = $out_w;
51 $self->{lockfh} = $lockfh;
57 sub wfail () { die "write to fast-import failed: $!" }
61 my $day = qw(Sun Mon Tue Wed Thu Fri Sat)[$t[6]];
62 my $mon = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)[$t[4]];
64 sprintf('%s, %2d %s %d %02d:%02d:%02d +0000',
65 $day, $t[3], $mon, $t[5] + 1900, $t[2], $t[1], $t[0]);
70 my $b = $mime->body_raw;
71 $b =~ s/(\r?\n)+\z//s;
75 # returns undef on non-existent
76 # ('MISMATCH', msg) on mismatch
77 # (:MARK, msg) on success
79 my ($self, $mime) = @_; # mime = Email::MIME
81 my $mid = mid_mime($mime);
82 my $path = mid2path($mid);
84 my ($r, $w) = $self->gfi_start;
85 my $tip = $self->{tip};
86 return ('MISSING', undef) if $tip eq '';
88 print $w "ls $tip $path\n" or wfail;
91 defined $check or die "EOF from fast-import / ls: $!";
92 return ('MISSING', undef) if $check =~ /\Amissing /;
93 $check =~ m!\A100644 blob ([a-f0-9]{40})\t!s or die "not blob: $check";
95 print $w "cat-blob $blob\n" or wfail;
97 defined $check or die "EOF from fast-import / cat-blob: $!";
98 $check =~ /\A[a-f0-9]{40} blob (\d+)\n\z/ or
99 die "unexpected cat-blob response: $check";
105 $n = read($r, $buf, $left, $offset);
106 defined($n) or die "read cat-blob failed: $!";
107 $n == 0 and die 'fast-export (cat-blob) died';
111 $n = read($r, my $lf, 1);
112 defined($n) or die "read final byte of cat-blob failed: $!";
113 die "bad read on final byte: <$lf>" if $lf ne "\n";
114 my $cur = Email::MIME->new($buf);
115 if ($cur->header('Subject') ne $mime->header('Subject') ||
116 norm_body($cur) ne norm_body($mime)) {
117 return ('MISMATCH', $cur);
120 my $ref = $self->{ref};
121 my $commit = $self->{mark}++;
122 my $parent = $tip =~ /\A:/ ? $tip : undef;
124 print $w "reset $ref\n" or wfail;
126 my $ident = $self->{ident};
128 print $w "commit $ref\nmark :$commit\n",
129 "author $ident $now\n",
130 "committer $ident $now\n",
132 'from ', ($parent ? $parent : $tip), "\n" or wfail;
133 print $w "D $path\n\n" or wfail;
135 (($self->{tip} = ":$commit"), $cur);
138 # returns undef on duplicate
140 my ($self, $mime) = @_; # mime = Email::MIME
142 my $from = $mime->header('From');
143 my ($email) = ($from =~ /([^<\s]+\@[^>\s]+)/g);
145 $name =~ s/\s*\S+\@\S+\s*\z//;
146 # git gets confused with:
147 # "'A U Thor <u@example.com>' via foo" <foo@example.com>
149 # <CAD0k6qSUYANxbjjbE4jTW4EeVwOYgBD=bXkSu=akiYC_CB7Ffw@mail.gmail.com>
150 $name =~ tr/<>// and $name = $email;
152 my $date = $mime->header('Date');
153 my $subject = $mime->header('Subject');
154 $subject = '(no subject)' unless defined $subject;
155 my $mid = mid_mime($mime);
156 my $path = mid2path($mid);
158 my ($r, $w) = $self->gfi_start;
159 my $tip = $self->{tip};
161 print $w "ls $tip $path\n" or wfail;
164 defined $check or die "EOF from fast-import: $!";
165 return unless $check =~ /\Amissing /;
168 # kill potentially confusing/misleading headers
169 $mime->header_set($_) for qw(bytes lines content-length status);
170 $mime = $mime->as_string;
171 my $blob = $self->{mark}++;
172 print $w "blob\nmark :$blob\ndata ", length($mime), "\n" or wfail;
173 print $w $mime, "\n" or wfail;
174 my $ref = $self->{ref};
175 my $commit = $self->{mark}++;
176 my $parent = $tip =~ /\A:/ ? $tip : undef;
179 print $w "reset $ref\n" or wfail;
182 # quiet down wide character warnings:
183 binmode $w, ':utf8' or die "binmode :utf8 failed: $!";
184 print $w "commit $ref\nmark :$commit\n",
185 "author $name <$email> $date\n",
186 "committer $self->{ident} ", now2822(), "\n",
187 "data ", (bytes::length($subject) + 1), "\n",
188 $subject, "\n\n" or wfail;
189 binmode $w, ':raw' or die "binmode :raw failed: $!";
192 print $w 'from ', ($parent ? $parent : $tip), "\n" or wfail;
194 print $w "M 100644 :$blob $path\n\n" or wfail;
196 $self->{tip} = ":$commit";
201 my $w = delete $self->{out} or return;
202 my $r = delete $self->{in} or die 'BUG: missing {in} when done';
203 print $w "done\n" or wfail;
204 my $pid = delete $self->{pid} or die 'BUG: missing {pid} when done';
205 waitpid($pid, 0) == $pid or die 'fast-import did not finish';
206 $? == 0 or die "fast-import failed: $?";
207 my $nchg = delete $self->{nchg};
209 # for compatibility with existing ssoma installations
210 # we can probably remove this entirely by 2020
211 my $git_dir = $self->{git}->{git_dir};
212 # XXX: change the following scope to: if (-e $index) # in 2018 or so..
213 my @cmd = ('git', "--git-dir=$git_dir");
214 if ($nchg && !$ENV{FAST}) {
215 my $index = "$git_dir/ssoma.index";
216 my $env = { GIT_INDEX_FILE => $index };
217 my @rt = (@cmd, qw(read-tree -m -v -i), $self->{ref});
218 $pid = spawn(\@rt, $env, undef);
219 defined $pid or die "spawn read-tree failed: $!";
220 waitpid($pid, 0) == $pid or die 'read-tree did not finish';
221 $? == 0 or die "failed to update $git_dir/ssoma.index: $?\n";
224 $pid = spawn([@cmd, 'update-server-info'], undef, undef);
225 defined $pid or die "spawn update-server-info failed: $!\n";
226 waitpid($pid, 0) == $pid or
227 die 'update-server-info did not finish';
228 $? == 0 or die "failed to update-server-info: $?\n";
231 my $lockfh = delete $self->{lockfh} or die "BUG: not locked: $!";
232 flock($lockfh, LOCK_UN) or die "unlock failed: $!";
233 close $lockfh or die "close lock failed: $!";
242 PublicInbox::Import - message importer for public-inbox
251 use PublicInbox::Git;
252 use PublicInbox::Import;
254 chomp(my $git_dir = `git rev-parse --git-dir`);
255 $git_dir or die "GIT_DIR= must be specified\n";
256 my $git = PublicInbox::Git->new($git_dir);
257 my @committer = ('inbox', 'inbox@example.org');
258 my $im = PublicInbox::Import->new($git, @committer);
261 my $message = "From: <u\@example.org>\n".
262 "Subject: test message \n" .
263 "Date: Thu, 01 Jan 1970 00:00:00 +0000\n" .
264 "Message-ID: <m\@example.org>\n".
266 my $parsed = Email::MIME->new($message);
267 my $ret = $im->add($parsed);
270 $parsed->header_obj->header_raw('Message-ID'), "\n";
272 print "imported at mark $ret\n";
276 # to remove a message
277 my $junk = Email::MIME->new($message);
278 my ($mark, $orig) = $im->remove($junk);
279 if ($mark eq 'MISSING') {
281 } elsif ($mark eq 'MISMATCH') {
282 print "Message exists but does not match\n\n",
283 $orig->as_string, "\n",;
285 print "removed at mark $mark\n\n",
286 $orig->as_string, "\n";
292 An importer and remover for public-inboxes which takes L<Email::MIME>
293 messages as input and stores them in a ssoma repository as
294 documented in L<https://ssoma.public-inbox.org/ssoma_repository.txt>,
295 except it does not allow duplicate Message-IDs.
297 It requires L<git(1)> and L<git-fast-import(1)> to be installed.
305 my $im = PublicInbox::Import->new($git, @committer);
307 Initialize a new PublicInbox::Import object.
311 my $parsed = Email::MIME->new($message);
314 Adds a message to to the git repository. This will acquire
315 C<$GIT_DIR/ssoma.lock> and start L<git-fast-import(1)> if necessary.
317 Messages added will not be visible to other processes until L</done>
318 is called, but L</remove> may be called on them.
322 my $junk = Email::MIME->new($message);
323 my ($code, $orig) = $im->remove($junk);
325 Removes a message from the repository. On success, it returns
326 a ':'-prefixed numeric code representing the git-fast-import
327 mark and the original messages as an Email::MIME object.
328 If the message could not be found, the code is "MISSING"
329 and the original message is undef. If there is a mismatch where
330 the "Message-ID" is matched but the subject and body do not match,
331 the returned code is "MISMATCH" and the conflicting message
336 Finalizes the L<git-fast-import(1)> and unlocks the repository.
337 Calling this is required to finalize changes to a repository.
345 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
347 The mail archives are hosted at L<https://public-inbox.org/meta/>
351 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
353 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>