]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Import.pm
1db2a0b858701051f0c03e2e01b19e05b1518da5
[public-inbox.git] / lib / PublicInbox / Import.pm
1 # Copyright (C) 2016 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 #
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;
8 use strict;
9 use warnings;
10 use Fcntl qw(:flock :DEFAULT);
11 use Email::Address;
12 use PublicInbox::Spawn qw(spawn);
13 use PublicInbox::MID qw(mid_mime mid2path);
14
15 sub new {
16         my ($class, $git, $name, $email) = @_;
17         bless {
18                 git => $git,
19                 ident => "$name <$email>",
20                 mark => 1,
21                 ref => 'refs/heads/master',
22         }, $class
23 }
24
25 # idempotent start function
26 sub gfi_start {
27         my ($self) = @_;
28
29         return ($self->{in}, $self->{out}) if $self->{pid};
30
31         my ($in_r, $in_w, $out_r, $out_w);
32         pipe($in_r, $in_w) or die "pipe failed: $!";
33         pipe($out_r, $out_w) or die "pipe failed: $!";
34         my $git = $self->{git};
35         my $git_dir = $git->{git_dir};
36         my $lockpath = "$git_dir/ssoma.lock";
37         sysopen(my $lockfh, $lockpath, O_WRONLY|O_CREAT) or
38                 die "failed to open lock $lockpath: $!";
39
40         # wait for other processes to be done
41         flock($lockfh, LOCK_EX) or die "lock failed: $!\n";
42         chomp($self->{tip} = $git->qx(qw(rev-parse --revs-only), $self->{ref}));
43
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;
49         $out_w->autoflush(1);
50         $self->{in} = $in_r;
51         $self->{out} = $out_w;
52         $self->{lockfh} = $lockfh;
53         $self->{pid} = $pid;
54         ($in_r, $out_w);
55 }
56
57 sub wfail () { die "write to fast-import failed: $!" }
58
59 sub now2822 () {
60         my @t = gmtime(time);
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]];
63
64         sprintf('%s, %2d %s %d %02d:%02d:%02d +0000',
65                 $day, $t[3], $mon, $t[5] + 1900, $t[2], $t[1], $t[0]);
66 }
67
68 sub norm_body ($) {
69         my ($mime) = @_;
70         my $b = $mime->body_raw;
71         $b =~ s/(\r?\n)+\z//s;
72         $b
73 }
74
75 # returns undef on non-existent
76 # ('MISMATCH', msg) on mismatch
77 # (:MARK, msg) on success
78 sub remove {
79         my ($self, $mime) = @_; # mime = Email::MIME
80
81         my $mid = mid_mime($mime);
82         my $path = mid2path($mid);
83
84         my ($r, $w) = $self->gfi_start;
85         my $tip = $self->{tip};
86         return ('MISSING', undef) if $tip eq '';
87
88         print $w "ls $tip $path\n" or wfail;
89         local $/ = "\n";
90         my $check = <$r>;
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";
94         my $blob = $1;
95         print $w "cat-blob $blob\n" or wfail;
96         $check = <$r>;
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";
100         my $left = $1;
101         my $offset = 0;
102         my $buf = '';
103         my $n;
104         while ($left > 0) {
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';
108                 $left -= $n;
109                 $offset += $n;
110         }
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);
118         }
119
120         my $ref = $self->{ref};
121         my $commit = $self->{mark}++;
122         my $parent = $tip =~ /\A:/ ? $tip : undef;
123         unless ($parent) {
124                 print $w "reset $ref\n" or wfail;
125         }
126         my $ident = $self->{ident};
127         my $now = now2822();
128         print $w "commit $ref\nmark :$commit\n",
129                 "author $ident $now\n",
130                 "committer $ident $now\n",
131                 "data 3\nrm\n\n",
132                 'from ', ($parent ? $parent : $tip), "\n" or wfail;
133         print $w "D $path\n\n" or wfail;
134         (($self->{tip} = ":$commit"), $cur);
135 }
136
137 # returns undef on duplicate
138 sub add {
139         my ($self, $mime) = @_; # mime = Email::MIME
140
141         my $from = $mime->header('From');
142         my @from = Email::Address->parse($from);
143         my $name = $from[0]->name;
144         my $email = $from[0]->address;
145         my $date = $mime->header('Date');
146         my $subject = $mime->header('Subject');
147         $subject = '(no subject)' unless defined $subject;
148         my $mid = mid_mime($mime);
149         my $path = mid2path($mid);
150
151         # git gets confused with:
152         #  "'A U Thor <u@example.com>' via foo" <foo@example.com>
153         # ref:
154         # <CAD0k6qSUYANxbjjbE4jTW4EeVwOYgBD=bXkSu=akiYC_CB7Ffw@mail.gmail.com>
155         $name =~ tr/<>// and $name = $email;
156
157         my ($r, $w) = $self->gfi_start;
158         my $tip = $self->{tip};
159         if ($tip ne '') {
160                 print $w "ls $tip $path\n" or wfail;
161                 local $/ = "\n";
162                 my $check = <$r>;
163                 defined $check or die "EOF from fast-import: $!";
164                 return unless $check =~ /\Amissing /;
165         }
166
167         # kill potentially confusing/misleading headers
168         $mime->header_set($_) for qw(bytes lines content-length status);
169         $mime = $mime->as_string;
170         my $blob = $self->{mark}++;
171         print $w "blob\nmark :$blob\ndata ", length($mime), "\n" or wfail;
172         print $w $mime, "\n" or wfail;
173         my $ref = $self->{ref};
174         my $commit = $self->{mark}++;
175         my $parent = $tip =~ /\A:/ ? $tip : undef;
176
177         unless ($parent) {
178                 print $w "reset $ref\n" or wfail;
179         }
180
181         # quiet down wide character warnings:
182         binmode $w, ':utf8' or die "binmode :utf8 failed: $!";
183         print $w "commit $ref\nmark :$commit\n",
184                 "author $name <$email> $date\n",
185                 "committer $self->{ident} ", now2822(), "\n",
186                 "data ", (bytes::length($subject) + 1), "\n",
187                 $subject, "\n\n" or wfail;
188         binmode $w, ':raw' or die "binmode :raw failed: $!";
189
190         if ($tip ne '') {
191                 print $w 'from ', ($parent ? $parent : $tip), "\n" or wfail;
192         }
193         print $w "M 100644 :$blob $path\n\n" or wfail;
194         $self->{tip} = ":$commit";
195 }
196
197 sub done {
198         my ($self) = @_;
199         my $w = delete $self->{out} or return;
200         my $r = delete $self->{in} or die 'BUG: missing {in} when done';
201         print $w "done\n" or wfail;
202         my $pid = delete $self->{pid} or die 'BUG: missing {pid} when done';
203         waitpid($pid, 0) == $pid or die 'fast-import did not finish';
204         $? == 0 or die "fast-import failed: $?";
205
206         # for compatibility with existing ssoma installations
207         # we can probably remove this entirely by 2020
208         my $git_dir = $self->{git}->{git_dir};
209         my $index = "$git_dir/ssoma.index";
210         # XXX: change the following scope to: if (-e $index) # in 2018 or so..
211         my @cmd = ('git', "--git-dir=$git_dir");
212         unless ($ENV{FAST}) {
213                 my $env = { GIT_INDEX_FILE => $index };
214                 my @rt = (@cmd, qw(read-tree -m -v -i), $self->{ref});
215                 $pid = spawn(\@rt, $env, undef);
216                 defined $pid or die "spawn read-tree failed: $!";
217                 waitpid($pid, 0) == $pid or die 'read-tree did not finish';
218                 $? == 0 or die "failed to update $git_dir/ssoma.index: $?\n";
219         }
220
221         $pid = spawn([@cmd, 'update-server-info'], undef, undef);
222         defined $pid or die "spawn update-server-info failed: $!\n";
223         waitpid($pid, 0) == $pid or die 'update-server-info did not finish';
224         $? == 0 or die "failed to update-server-info: $?\n";
225
226         my $lockfh = delete $self->{lockfh} or die "BUG: not locked: $!";
227         flock($lockfh, LOCK_UN) or die "unlock failed: $!";
228         close $lockfh or die "close lock failed: $!";
229 }
230
231 1;
232 __END__
233 =pod
234
235 =head1 NAME
236
237 PublicInbox::Import - message importer for public-inbox
238
239 =head1 VERSION
240
241 version 1.0
242
243 =head1 SYNOPSYS
244
245         use Email::MIME;
246         use PublicInbox::Git;
247         use PublicInbox::Import;
248
249         chomp(my $git_dir = `git rev-parse --git-dir`);
250         $git_dir or die "GIT_DIR= must be specified\n";
251         my $git = PublicInbox::Git->new($git_dir);
252         my @committer = ('inbox', 'inbox@example.org');
253         my $im = PublicInbox::Import->new($git, @committer);
254
255         # to add a message:
256         my $message = "From: <u\@example.org>\n".
257                 "Subject: test message \n" .
258                 "Date: Thu, 01 Jan 1970 00:00:00 +0000\n" .
259                 "Message-ID: <m\@example.org>\n".
260                 "\ntest message";
261         my $parsed = Email::MIME->new($message);
262         my $ret = $im->add($parsed);
263         if (!defined $ret) {
264                 warn "duplicate: ",
265                         $parsed->header_obj->header_raw('Message-ID'), "\n";
266         } else {
267                 print "imported at mark $ret\n";
268         }
269         $im->done;
270
271         # to remove a message
272         my $junk = Email::MIME->new($message);
273         my ($mark, $orig) = $im->remove($junk);
274         if ($mark eq 'MISSING') {
275                 print "not found\n";
276         } elsif ($mark eq 'MISMATCH') {
277                 print "Message exists but does not match\n\n",
278                         $orig->as_string, "\n",;
279         } else {
280                 print "removed at mark $mark\n\n",
281                         $orig->as_string, "\n";
282         }
283         $im->done;
284
285 =head1 DESCRIPTION
286
287 An importer and remover for public-inboxes which takes L<Email::MIME>
288 messages as input and stores them in a ssoma repository as
289 documented in L<https://ssoma.public-inbox.org/ssoma_repository.txt>,
290 except it does not allow duplicate Message-IDs.
291
292 It requires L<git(1)> and L<git-fast-import(1)> to be installed.
293
294 =head1 METHODS
295
296 =cut
297
298 =head2 new
299
300         my $im = PublicInbox::Import->new($git, @committer);
301
302 Initialize a new PublicInbox::Import object.
303
304 =head2 add
305
306         my $parsed = Email::MIME->new($message);
307         $im->add($parsed);
308
309 Adds a message to to the git repository.  This will acquire
310 C<$GIT_DIR/ssoma.lock> and start L<git-fast-import(1)> if necessary.
311
312 Messages added will not be visible to other processes until L</done>
313 is called, but L</remove> may be called on them.
314
315 =head2 remove
316
317         my $junk = Email::MIME->new($message);
318         my ($code, $orig) = $im->remove($junk);
319
320 Removes a message from the repository.  On success, it returns
321 a ':'-prefixed numeric code representing the git-fast-import
322 mark and the original messages as an Email::MIME object.
323 If the message could not be found, the code is "MISSING"
324 and the original message is undef.  If there is a mismatch where
325 the "Message-ID" is matched but the subject and body do not match,
326 the returned code is "MISMATCH" and the conflicting message
327 is returned as orig.
328
329 =head2 done
330
331 Finalizes the L<git-fast-import(1)> and unlocks the repository.
332 Calling this is required to finalize changes to a repository.
333
334 =head1 SEE ALSO
335
336 L<Email::MIME>
337
338 =head1 CONTACT
339
340 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
341
342 The mail archives are hosted at L<https://public-inbox.org/meta/>
343
344 =head1 COPYRIGHT
345
346 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
347
348 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>
349
350 =cut