]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Import.pm
v2writable: support purging messages from git entirely
[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 msg_datestamp);
15 use PublicInbox::ContentId qw(content_digest);
16 use PublicInbox::MDA;
17
18 sub new {
19         my ($class, $git, $name, $email, $ibx) = @_;
20         my $ref = 'refs/heads/master';
21         if ($ibx) {
22                 $ref = $ibx->{ref_head} || 'refs/heads/master';
23                 $name ||= $ibx->{name};
24                 $email ||= $ibx->{-primary_address};
25         }
26         bless {
27                 git => $git,
28                 ident => "$name <$email>",
29                 mark => 1,
30                 ref => $ref,
31                 inbox => $ibx,
32                 path_type => '2/38', # or 'v2'
33                 lock_path => "$git->{git_dir}/ssoma.lock", # v2 changes this
34                 bytes_added => 0,
35         }, $class
36 }
37
38 # idempotent start function
39 sub gfi_start {
40         my ($self) = @_;
41
42         return ($self->{in}, $self->{out}) if $self->{pid};
43
44         my ($in_r, $in_w, $out_r, $out_w);
45         pipe($in_r, $in_w) or die "pipe failed: $!";
46         pipe($out_r, $out_w) or die "pipe failed: $!";
47         my $git = $self->{git};
48
49         $self->lock_acquire;
50
51         local $/ = "\n";
52         chomp($self->{tip} = $git->qx(qw(rev-parse --revs-only), $self->{ref}));
53
54         my $git_dir = $git->{git_dir};
55         my @cmd = ('git', "--git-dir=$git_dir", qw(fast-import
56                         --quiet --done --date-format=raw));
57         my $rdr = { 0 => fileno($out_r), 1 => fileno($in_w) };
58         my $pid = spawn(\@cmd, undef, $rdr);
59         die "spawn fast-import failed: $!" unless defined $pid;
60         $out_w->autoflush(1);
61         $self->{in} = $in_r;
62         $self->{out} = $out_w;
63         $self->{pid} = $pid;
64         $self->{nchg} = 0;
65         binmode $out_w, ':raw' or die "binmode :raw failed: $!";
66         binmode $in_r, ':raw' or die "binmode :raw failed: $!";
67         ($in_r, $out_w);
68 }
69
70 sub wfail () { die "write to fast-import failed: $!" }
71
72 sub now_raw () { time . ' +0000' }
73
74 sub norm_body ($) {
75         my ($mime) = @_;
76         my $b = $mime->body_raw;
77         $b =~ s/(\r?\n)+\z//s;
78         $b
79 }
80
81 # only used for v1 (ssoma) inboxes
82 sub _check_path ($$$$) {
83         my ($r, $w, $tip, $path) = @_;
84         return if $tip eq '';
85         print $w "ls $tip $path\n" or wfail;
86         local $/ = "\n";
87         defined(my $info = <$r>) or die "EOF from fast-import: $!";
88         $info =~ /\Amissing / ? undef : $info;
89 }
90
91 sub check_remove_v1 {
92         my ($r, $w, $tip, $path, $mime) = @_;
93
94         my $info = _check_path($r, $w, $tip, $path) or return ('MISSING',undef);
95         $info =~ m!\A100644 blob ([a-f0-9]{40})\t!s or die "not blob: $info";
96         my $blob = $1;
97
98         print $w "cat-blob $blob\n" or wfail;
99         local $/ = "\n";
100         $info = <$r>;
101         defined $info or die "EOF from fast-import / cat-blob: $!";
102         $info =~ /\A[a-f0-9]{40} blob (\d+)\n\z/ or
103                                 die "unexpected cat-blob response: $info";
104         my $left = $1;
105         my $offset = 0;
106         my $buf = '';
107         my $n;
108         while ($left > 0) {
109                 $n = read($r, $buf, $left, $offset);
110                 defined($n) or die "read cat-blob failed: $!";
111                 $n == 0 and die 'fast-export (cat-blob) died';
112                 $left -= $n;
113                 $offset += $n;
114         }
115         $n = read($r, my $lf, 1);
116         defined($n) or die "read final byte of cat-blob failed: $!";
117         die "bad read on final byte: <$lf>" if $lf ne "\n";
118         my $cur = PublicInbox::MIME->new(\$buf);
119         my $cur_s = $cur->header('Subject');
120         $cur_s = '' unless defined $cur_s;
121         my $cur_m = $mime->header('Subject');
122         $cur_m = '' unless defined $cur_m;
123         if ($cur_s ne $cur_m || norm_body($cur) ne norm_body($mime)) {
124                 return ('MISMATCH', $cur);
125         }
126         (undef, $cur);
127 }
128
129 sub checkpoint {
130         my ($self) = @_;
131         return unless $self->{pid};
132         print { $self->{out} } "checkpoint\n" or wfail;
133         undef;
134 }
135
136 sub progress {
137         my ($self, $msg) = @_;
138         return unless $self->{pid};
139         print { $self->{out} } "progress $msg\n" or wfail;
140         $self->{in}->getline eq "progress $msg\n" or die
141                 "progress $msg not received\n";
142         undef;
143 }
144
145 sub _update_git_info ($$) {
146         my ($self, $do_gc) = @_;
147         # for compatibility with existing ssoma installations
148         # we can probably remove this entirely by 2020
149         my $git_dir = $self->{git}->{git_dir};
150         my @cmd = ('git', "--git-dir=$git_dir");
151         my $index = "$git_dir/ssoma.index";
152         if (-e $index && !$ENV{FAST}) {
153                 my $env = { GIT_INDEX_FILE => $index };
154                 run_die([@cmd, qw(read-tree -m -v -i), $self->{ref}], $env);
155         }
156         run_die([@cmd, 'update-server-info'], undef);
157         ($self->{path_type} eq '2/38') and eval {
158                 require PublicInbox::SearchIdx;
159                 my $inbox = $self->{inbox} || $git_dir;
160                 my $s = PublicInbox::SearchIdx->new($inbox);
161                 $s->index_sync({ ref => $self->{ref} });
162         };
163         eval { run_die([@cmd, qw(gc --auto)], undef) } if $do_gc;
164 }
165
166 sub barrier {
167         my ($self) = @_;
168
169         # For safety, we ensure git checkpoint is complete before because
170         # the data in git is still more important than what is in Xapian
171         # in v2.  Performance may be gained by delaying the ->progress
172         # call but we lose safety
173         if ($self->{nchg}) {
174                 $self->checkpoint;
175                 $self->progress('checkpoint');
176                 _update_git_info($self, 0);
177                 $self->{nchg} = 0;
178         }
179 }
180
181 # used for v2
182 sub get_mark {
183         my ($self, $mark) = @_;
184         die "not active\n" unless $self->{pid};
185         my ($r, $w) = $self->gfi_start;
186         print $w "get-mark $mark\n" or wfail;
187         defined(my $oid = <$r>) or die "get-mark failed, need git 2.6.0+\n";
188         $oid;
189 }
190
191 # returns undef on non-existent
192 # ('MISMATCH', Email::MIME) on mismatch
193 # (:MARK, Email::MIME) on success
194 #
195 # v2 callers should check with Xapian before calling this as
196 # it is not idempotent.
197 sub remove {
198         my ($self, $mime, $msg) = @_; # mime = Email::MIME
199
200         my $path_type = $self->{path_type};
201         my ($path, $err, $cur, $blob);
202
203         my ($r, $w) = $self->gfi_start;
204         my $tip = $self->{tip};
205         if ($path_type eq '2/38') {
206                 $path = mid2path(v1_mid0($mime));
207                 ($err, $cur) = check_remove_v1($r, $w, $tip, $path, $mime);
208                 return ($err, $cur) if $err;
209         } else {
210                 my $sref;
211                 if (ref($mime) eq 'SCALAR') { # optimization used by V2Writable
212                         $sref = $mime;
213                 } else { # XXX should not be necessary:
214                         my $str = $mime->as_string;
215                         $sref = \$str;
216                 }
217                 my $len = length($$sref);
218                 $blob = $self->{mark}++;
219                 print $w "blob\nmark :$blob\ndata $len\n",
220                         $$sref, "\n" or wfail;
221         }
222
223         my $ref = $self->{ref};
224         my $commit = $self->{mark}++;
225         my $parent = $tip =~ /\A:/ ? $tip : undef;
226         unless ($parent) {
227                 print $w "reset $ref\n" or wfail;
228         }
229         my $ident = $self->{ident};
230         my $now = now_raw();
231         $msg ||= 'rm';
232         my $len = length($msg) + 1;
233         print $w "commit $ref\nmark :$commit\n",
234                 "author $ident $now\n",
235                 "committer $ident $now\n",
236                 "data $len\n$msg\n\n",
237                 'from ', ($parent ? $parent : $tip), "\n" or wfail;
238         if (defined $path) {
239                 print $w "D $path\n\n" or wfail;
240         } else {
241                 print $w "M 100644 :$blob _/D\n\n" or wfail;
242         }
243         $self->{nchg}++;
244         (($self->{tip} = ":$commit"), $cur);
245 }
246
247 sub git_timestamp {
248         my ($ts, $zone) = @_;
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 # kill potentially confusing/misleading headers
292 sub drop_unwanted_headers ($) {
293         my ($mime) = @_;
294
295         $mime->header_set($_) for qw(bytes lines content-length status);
296         $mime->header_set($_) for @PublicInbox::MDA::BAD_HEADERS;
297 }
298
299 # used by V2Writable, too
300 sub append_mid ($$) {
301         my ($hdr, $mid0) = @_;
302         # @cur is likely empty if we need to call this sub, but it could
303         # have random unparseable crap which we'll preserve, too.
304         my @cur = $hdr->header_raw('Message-ID');
305         $hdr->header_set('Message-ID', @cur, "<$mid0>");
306 }
307
308 sub v1_mid0 ($) {
309         my ($mime) = @_;
310         my $hdr = $mime->header_obj;
311         my $mids = mids($hdr);
312
313         if (!scalar(@$mids)) { # spam often has no Message-Id
314                 my $mid0 = digest2mid(content_digest($mime));
315                 append_mid($hdr, $mid0);
316                 return $mid0;
317         }
318         $mids->[0];
319 }
320
321 # returns undef on duplicate
322 # returns the :MARK of the most recent commit
323 sub add {
324         my ($self, $mime, $check_cb) = @_; # mime = Email::MIME
325
326         my ($name, $email) = extract_author_info($mime);
327         my $hdr = $mime->header_obj;
328         my @at = msg_datestamp($hdr);
329         my @ct = msg_timestamp($hdr);
330         my $author_time_raw = git_timestamp(@at);
331         my $commit_time_raw = git_timestamp(@ct);
332         my $subject = $mime->header('Subject');
333         $subject = '(no subject)' unless defined $subject;
334         my $path_type = $self->{path_type};
335
336         my $path;
337         if ($path_type eq '2/38') {
338                 $path = mid2path(v1_mid0($mime));
339         } else { # v2 layout, one file:
340                 $path = 'm';
341         }
342
343         my ($r, $w) = $self->gfi_start;
344         my $tip = $self->{tip};
345         if ($path_type eq '2/38') {
346                 _check_path($r, $w, $tip, $path) and return;
347         }
348
349         drop_unwanted_headers($mime);
350
351         # spam check:
352         if ($check_cb) {
353                 $mime = $check_cb->($mime) or return;
354         }
355
356         my $blob = $self->{mark}++;
357         my $str = $mime->as_string;
358         my $n = length($str);
359         $self->{bytes_added} += $n;
360         print $w "blob\nmark :$blob\ndata ", $n, "\n" or wfail;
361         print $w $str, "\n" or wfail;
362
363         # v2: we need this for Xapian
364         if ($self->{want_object_info}) {
365                 chomp(my $oid = $self->get_mark(":$blob"));
366                 $self->{last_object} = [ $oid, $n, \$str ];
367         }
368         my $ref = $self->{ref};
369         my $commit = $self->{mark}++;
370         my $parent = $tip =~ /\A:/ ? $tip : undef;
371
372         unless ($parent) {
373                 print $w "reset $ref\n" or wfail;
374         }
375
376         utf8::encode($subject);
377         print $w "commit $ref\nmark :$commit\n",
378                 "author $name <$email> $author_time_raw\n",
379                 "committer $self->{ident} $commit_time_raw\n" or wfail;
380         print $w "data ", (length($subject) + 1), "\n",
381                 $subject, "\n\n" or wfail;
382         if ($tip ne '') {
383                 print $w 'from ', ($parent ? $parent : $tip), "\n" or wfail;
384         }
385         print $w "M 100644 :$blob $path\n\n" or wfail;
386         $self->{nchg}++;
387         $self->{tip} = ":$commit";
388 }
389
390 sub run_die ($;$) {
391         my ($cmd, $env) = @_;
392         my $pid = spawn($cmd, $env, undef);
393         defined $pid or die "spawning ".join(' ', @$cmd)." failed: $!";
394         waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
395         $? == 0 or die join(' ', @$cmd) . " failed: $?\n";
396 }
397
398 sub done {
399         my ($self) = @_;
400         my $w = delete $self->{out} or return;
401         my $r = delete $self->{in} or die 'BUG: missing {in} when done';
402         print $w "done\n" or wfail;
403         my $pid = delete $self->{pid} or die 'BUG: missing {pid} when done';
404         waitpid($pid, 0) == $pid or die 'fast-import did not finish';
405         $? == 0 or die "fast-import failed: $?";
406
407         _update_git_info($self, 1) if delete $self->{nchg};
408
409         $self->lock_release;
410 }
411
412 sub atfork_child {
413         my ($self) = @_;
414         foreach my $f (qw(in out)) {
415                 close $self->{$f} or die "failed to close import[$f]: $!\n";
416         }
417 }
418
419 sub digest2mid ($) {
420         my ($dig) = @_;
421         my $b64 = $dig->clone->b64digest;
422         # Make our own URLs nicer:
423         # See "Base 64 Encoding with URL and Filename Safe Alphabet" in RFC4648
424         $b64 =~ tr!+/=!-_!d;
425
426         # We can make this more meaningful with a date prefix or other things,
427         # but this is only needed for crap that fails to generate a Message-ID
428         # or reuses one.  In other words, it's usually spammers who hit this
429         # so they don't deserve nice Message-IDs :P
430         $b64 . '@localhost';
431 }
432
433 sub clean_purge_buffer {
434         my ($oid, $buf) = @_;
435         my $cmt_msg = "purged $oid\n";
436
437         foreach my $i (0..$#$buf) {
438                 my $l = $buf->[$i];
439                 if ($l =~ /^author .* (\d+ [\+-]?\d+)$/) {
440                         $buf->[$i] = "author <> $1\n";
441                 } elsif ($l =~ /^data (\d+)/) {
442                         $buf->[$i++] = "data " . length($cmt_msg) . "\n";
443                         $buf->[$i] = $cmt_msg;
444                         last;
445                 }
446         }
447 }
448
449 sub purge_oids {
450         my ($self, $purge) = @_;
451         my $tmp = "refs/heads/purge-".((keys %$purge)[0]);
452         my $old = $self->{'ref'};
453         my $git = $self->{git};
454         my @export = (qw(fast-export --no-data --use-done-feature), $old);
455         my ($rd, $pid) = $git->popen(@export);
456         my ($r, $w) = $self->gfi_start;
457         my @buf;
458         my $npurge = 0;
459         while (<$rd>) {
460                 if (/^reset (?:.+)/) {
461                         push @buf, "reset $tmp\n";
462                 } elsif (/^commit (?:.+)/) {
463                         if (@buf) {
464                                 $w->print(@buf) or wfail;
465                                 @buf = ();
466                         }
467                         push @buf, "commit $tmp\n";
468                 } elsif (/^data (\d+)/) {
469                         # only commit message, so $len is small:
470                         my $len = $1; # + 1 for trailing "\n"
471                         push @buf, $_;
472                         my $n = read($rd, my $buf, $len) or die "read: $!";
473                         $len == $n or die "short read ($n < $len)";
474                         push @buf, $buf;
475                 } elsif (/^M 100644 ([a-f0-9]+) /) {
476                         my $oid = $1;
477                         if ($purge->{$oid}) {
478                                 my $lf = <$rd>;
479                                 if ($lf eq "\n") {
480                                         my $out = join('', @buf);
481                                         $out =~ s/^/# /sgm;
482                                         warn "purge rewriting\n", $out, "\n";
483                                         clean_purge_buffer($oid, \@buf);
484                                         $out = join('', @buf);
485                                         $w->print(@buf, "\n") or wfail;
486                                         @buf = ();
487                                         $npurge++;
488                                 } else {
489                                         die "expected LF: $lf\n";
490                                 }
491                         } else {
492                                 push @buf, $_;
493                         }
494                 } else {
495                         push @buf, $_;
496                 }
497         }
498         if (@buf) {
499                 $w->print(@buf) or wfail;
500         }
501         $w = $r = undef;
502         $self->done;
503         my @git = ('git', "--git-dir=$git->{git_dir}");
504
505         run_die([@git, qw(update-ref), $old, $tmp]) if $npurge;
506
507         run_die([@git, qw(update-ref -d), $tmp]);
508
509         return if $npurge == 0;
510
511         run_die([@git, qw(-c gc.reflogExpire=now gc --prune=all)]);
512         my $err = 0;
513         foreach my $oid (keys %$purge) {
514                 my @info = $git->check($oid);
515                 if (@info) {
516                         warn "$oid not purged\n";
517                         $err++;
518                 }
519         }
520         die "Failed to purge $err object(s)\n" if $err;
521 }
522
523 1;
524 __END__
525 =pod
526
527 =head1 NAME
528
529 PublicInbox::Import - message importer for public-inbox
530
531 =head1 VERSION
532
533 version 1.0
534
535 =head1 SYNOPSYS
536
537         use Email::MIME;
538         use PublicInbox::Git;
539         use PublicInbox::Import;
540
541         chomp(my $git_dir = `git rev-parse --git-dir`);
542         $git_dir or die "GIT_DIR= must be specified\n";
543         my $git = PublicInbox::Git->new($git_dir);
544         my @committer = ('inbox', 'inbox@example.org');
545         my $im = PublicInbox::Import->new($git, @committer);
546
547         # to add a message:
548         my $message = "From: <u\@example.org>\n".
549                 "Subject: test message \n" .
550                 "Date: Thu, 01 Jan 1970 00:00:00 +0000\n" .
551                 "Message-ID: <m\@example.org>\n".
552                 "\ntest message";
553         my $parsed = Email::MIME->new($message);
554         my $ret = $im->add($parsed);
555         if (!defined $ret) {
556                 warn "duplicate: ",
557                         $parsed->header_obj->header_raw('Message-ID'), "\n";
558         } else {
559                 print "imported at mark $ret\n";
560         }
561         $im->done;
562
563         # to remove a message
564         my $junk = Email::MIME->new($message);
565         my ($mark, $orig) = $im->remove($junk);
566         if ($mark eq 'MISSING') {
567                 print "not found\n";
568         } elsif ($mark eq 'MISMATCH') {
569                 print "Message exists but does not match\n\n",
570                         $orig->as_string, "\n",;
571         } else {
572                 print "removed at mark $mark\n\n",
573                         $orig->as_string, "\n";
574         }
575         $im->done;
576
577 =head1 DESCRIPTION
578
579 An importer and remover for public-inboxes which takes L<Email::MIME>
580 messages as input and stores them in a ssoma repository as
581 documented in L<https://ssoma.public-inbox.org/ssoma_repository.txt>,
582 except it does not allow duplicate Message-IDs.
583
584 It requires L<git(1)> and L<git-fast-import(1)> to be installed.
585
586 =head1 METHODS
587
588 =cut
589
590 =head2 new
591
592         my $im = PublicInbox::Import->new($git, @committer);
593
594 Initialize a new PublicInbox::Import object.
595
596 =head2 add
597
598         my $parsed = Email::MIME->new($message);
599         $im->add($parsed);
600
601 Adds a message to to the git repository.  This will acquire
602 C<$GIT_DIR/ssoma.lock> and start L<git-fast-import(1)> if necessary.
603
604 Messages added will not be visible to other processes until L</done>
605 is called, but L</remove> may be called on them.
606
607 =head2 remove
608
609         my $junk = Email::MIME->new($message);
610         my ($code, $orig) = $im->remove($junk);
611
612 Removes a message from the repository.  On success, it returns
613 a ':'-prefixed numeric code representing the git-fast-import
614 mark and the original messages as an Email::MIME object.
615 If the message could not be found, the code is "MISSING"
616 and the original message is undef.  If there is a mismatch where
617 the "Message-ID" is matched but the subject and body do not match,
618 the returned code is "MISMATCH" and the conflicting message
619 is returned as orig.
620
621 =head2 done
622
623 Finalizes the L<git-fast-import(1)> and unlocks the repository.
624 Calling this is required to finalize changes to a repository.
625
626 =head1 SEE ALSO
627
628 L<Email::MIME>
629
630 =head1 CONTACT
631
632 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
633
634 The mail archives are hosted at L<https://public-inbox.org/meta/>
635
636 =head1 COPYRIGHT
637
638 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
639
640 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>
641
642 =cut