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