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