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