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