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