]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Import.pm
remove Email::Address dependency
[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 PublicInbox::Spawn qw(spawn);
12 use PublicInbox::MID qw(mid_mime mid2path);
13
14 sub new {
15         my ($class, $git, $name, $email) = @_;
16         bless {
17                 git => $git,
18                 ident => "$name <$email>",
19                 mark => 1,
20                 ref => 'refs/heads/master',
21         }, $class
22 }
23
24 # idempotent start function
25 sub gfi_start {
26         my ($self) = @_;
27
28         return ($self->{in}, $self->{out}) if $self->{pid};
29
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: $!";
38
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}));
42
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;
48         $out_w->autoflush(1);
49         $self->{in} = $in_r;
50         $self->{out} = $out_w;
51         $self->{lockfh} = $lockfh;
52         $self->{pid} = $pid;
53         $self->{nchg} = 0;
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->{nchg}++;
135         (($self->{tip} = ":$commit"), $cur);
136 }
137
138 # returns undef on duplicate
139 sub add {
140         my ($self, $mime) = @_; # mime = Email::MIME
141
142         my $from = $mime->header('From');
143         my ($email) = ($from =~ /([^<\s]+\@[^>\s]+)/g);
144         my $name = $from;
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>
148         # ref:
149         # <CAD0k6qSUYANxbjjbE4jTW4EeVwOYgBD=bXkSu=akiYC_CB7Ffw@mail.gmail.com>
150         $name =~ tr/<>// and $name = $email;
151
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);
157
158         my ($r, $w) = $self->gfi_start;
159         my $tip = $self->{tip};
160         if ($tip ne '') {
161                 print $w "ls $tip $path\n" or wfail;
162                 local $/ = "\n";
163                 my $check = <$r>;
164                 defined $check or die "EOF from fast-import: $!";
165                 return unless $check =~ /\Amissing /;
166         }
167
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;
177
178         unless ($parent) {
179                 print $w "reset $ref\n" or wfail;
180         }
181
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: $!";
190
191         if ($tip ne '') {
192                 print $w 'from ', ($parent ? $parent : $tip), "\n" or wfail;
193         }
194         print $w "M 100644 :$blob $path\n\n" or wfail;
195         $self->{nchg}++;
196         $self->{tip} = ":$commit";
197 }
198
199 sub done {
200         my ($self) = @_;
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};
208
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";
222         }
223         if ($nchg) {
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";
229         }
230
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: $!";
234 }
235
236 1;
237 __END__
238 =pod
239
240 =head1 NAME
241
242 PublicInbox::Import - message importer for public-inbox
243
244 =head1 VERSION
245
246 version 1.0
247
248 =head1 SYNOPSYS
249
250         use Email::MIME;
251         use PublicInbox::Git;
252         use PublicInbox::Import;
253
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);
259
260         # to add a message:
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".
265                 "\ntest message";
266         my $parsed = Email::MIME->new($message);
267         my $ret = $im->add($parsed);
268         if (!defined $ret) {
269                 warn "duplicate: ",
270                         $parsed->header_obj->header_raw('Message-ID'), "\n";
271         } else {
272                 print "imported at mark $ret\n";
273         }
274         $im->done;
275
276         # to remove a message
277         my $junk = Email::MIME->new($message);
278         my ($mark, $orig) = $im->remove($junk);
279         if ($mark eq 'MISSING') {
280                 print "not found\n";
281         } elsif ($mark eq 'MISMATCH') {
282                 print "Message exists but does not match\n\n",
283                         $orig->as_string, "\n",;
284         } else {
285                 print "removed at mark $mark\n\n",
286                         $orig->as_string, "\n";
287         }
288         $im->done;
289
290 =head1 DESCRIPTION
291
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.
296
297 It requires L<git(1)> and L<git-fast-import(1)> to be installed.
298
299 =head1 METHODS
300
301 =cut
302
303 =head2 new
304
305         my $im = PublicInbox::Import->new($git, @committer);
306
307 Initialize a new PublicInbox::Import object.
308
309 =head2 add
310
311         my $parsed = Email::MIME->new($message);
312         $im->add($parsed);
313
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.
316
317 Messages added will not be visible to other processes until L</done>
318 is called, but L</remove> may be called on them.
319
320 =head2 remove
321
322         my $junk = Email::MIME->new($message);
323         my ($code, $orig) = $im->remove($junk);
324
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
332 is returned as orig.
333
334 =head2 done
335
336 Finalizes the L<git-fast-import(1)> and unlocks the repository.
337 Calling this is required to finalize changes to a repository.
338
339 =head1 SEE ALSO
340
341 L<Email::MIME>
342
343 =head1 CONTACT
344
345 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
346
347 The mail archives are hosted at L<https://public-inbox.org/meta/>
348
349 =head1 COPYRIGHT
350
351 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
352
353 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>
354
355 =cut