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