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