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