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