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