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