]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Import.pm
import: pass "raw" dates to git-fast-import(1)
[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         # git gets confused with:
250         #  "'A U Thor <u@example.com>' via foo" <foo@example.com>
251         # ref:
252         # <CAD0k6qSUYANxbjjbE4jTW4EeVwOYgBD=bXkSu=akiYC_CB7Ffw@mail.gmail.com>
253         $name =~ tr/<>//d;
254
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         print $w "blob\nmark :$blob\ndata ", length($str), "\n" or wfail;
284         print $w $str, "\n" or wfail;
285         $str = undef;
286
287         # v2: we need this for Xapian
288         if ($self->{want_object_id}) {
289                 chomp($self->{last_object_id} = $self->get_mark(":$blob"));
290         }
291
292         my $ref = $self->{ref};
293         my $commit = $self->{mark}++;
294         my $parent = $tip =~ /\A:/ ? $tip : undef;
295
296         unless ($parent) {
297                 print $w "reset $ref\n" or wfail;
298         }
299
300         utf8::encode($email);
301         utf8::encode($name);
302         utf8::encode($subject);
303         # quiet down wide character warnings:
304         print $w "commit $ref\nmark :$commit\n",
305                 "author $name <$email> $date_raw\n",
306                 "committer $self->{ident} ", now_raw(), "\n" or wfail;
307         print $w "data ", (length($subject) + 1), "\n",
308                 $subject, "\n\n" or wfail;
309         if ($tip ne '') {
310                 print $w 'from ', ($parent ? $parent : $tip), "\n" or wfail;
311         }
312         print $w "M 100644 :$blob $path\n\n" or wfail;
313         $self->{nchg}++;
314         $self->{tip} = ":$commit";
315 }
316
317 sub run_die ($$) {
318         my ($cmd, $env) = @_;
319         my $pid = spawn($cmd, $env, undef);
320         defined $pid or die "spawning ".join(' ', @$cmd)." failed: $!";
321         waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
322         $? == 0 or die join(' ', @$cmd) . " failed: $?\n";
323 }
324
325 sub done {
326         my ($self) = @_;
327         my $w = delete $self->{out} or return;
328         my $r = delete $self->{in} or die 'BUG: missing {in} when done';
329         print $w "done\n" or wfail;
330         my $pid = delete $self->{pid} or die 'BUG: missing {pid} when done';
331         waitpid($pid, 0) == $pid or die 'fast-import did not finish';
332         $? == 0 or die "fast-import failed: $?";
333         my $nchg = delete $self->{nchg};
334
335         # for compatibility with existing ssoma installations
336         # we can probably remove this entirely by 2020
337         my $git_dir = $self->{git}->{git_dir};
338         my @cmd = ('git', "--git-dir=$git_dir");
339         my $index = "$git_dir/ssoma.index";
340         if ($nchg && -e $index && !$ENV{FAST}) {
341                 my $env = { GIT_INDEX_FILE => $index };
342                 run_die([@cmd, qw(read-tree -m -v -i), $self->{ref}], $env);
343         }
344         if ($nchg) {
345                 run_die([@cmd, 'update-server-info'], undef);
346                 eval {
347                         require PublicInbox::SearchIdx;
348                         my $inbox = $self->{inbox} || $git_dir;
349                         my $s = PublicInbox::SearchIdx->new($inbox);
350                         $s->index_sync({ ref => $self->{ref} });
351                 };
352
353                 eval { run_die([@cmd, qw(gc --auto)], undef) };
354         }
355
356         $self->{ssoma_lock} or return;
357         my $lockfh = delete $self->{lockfh} or die "BUG: not locked: $!";
358         flock($lockfh, LOCK_UN) or die "unlock failed: $!";
359         close $lockfh or die "close lock failed: $!";
360 }
361
362 1;
363 __END__
364 =pod
365
366 =head1 NAME
367
368 PublicInbox::Import - message importer for public-inbox
369
370 =head1 VERSION
371
372 version 1.0
373
374 =head1 SYNOPSYS
375
376         use Email::MIME;
377         use PublicInbox::Git;
378         use PublicInbox::Import;
379
380         chomp(my $git_dir = `git rev-parse --git-dir`);
381         $git_dir or die "GIT_DIR= must be specified\n";
382         my $git = PublicInbox::Git->new($git_dir);
383         my @committer = ('inbox', 'inbox@example.org');
384         my $im = PublicInbox::Import->new($git, @committer);
385
386         # to add a message:
387         my $message = "From: <u\@example.org>\n".
388                 "Subject: test message \n" .
389                 "Date: Thu, 01 Jan 1970 00:00:00 +0000\n" .
390                 "Message-ID: <m\@example.org>\n".
391                 "\ntest message";
392         my $parsed = Email::MIME->new($message);
393         my $ret = $im->add($parsed);
394         if (!defined $ret) {
395                 warn "duplicate: ",
396                         $parsed->header_obj->header_raw('Message-ID'), "\n";
397         } else {
398                 print "imported at mark $ret\n";
399         }
400         $im->done;
401
402         # to remove a message
403         my $junk = Email::MIME->new($message);
404         my ($mark, $orig) = $im->remove($junk);
405         if ($mark eq 'MISSING') {
406                 print "not found\n";
407         } elsif ($mark eq 'MISMATCH') {
408                 print "Message exists but does not match\n\n",
409                         $orig->as_string, "\n",;
410         } else {
411                 print "removed at mark $mark\n\n",
412                         $orig->as_string, "\n";
413         }
414         $im->done;
415
416 =head1 DESCRIPTION
417
418 An importer and remover for public-inboxes which takes L<Email::MIME>
419 messages as input and stores them in a ssoma repository as
420 documented in L<https://ssoma.public-inbox.org/ssoma_repository.txt>,
421 except it does not allow duplicate Message-IDs.
422
423 It requires L<git(1)> and L<git-fast-import(1)> to be installed.
424
425 =head1 METHODS
426
427 =cut
428
429 =head2 new
430
431         my $im = PublicInbox::Import->new($git, @committer);
432
433 Initialize a new PublicInbox::Import object.
434
435 =head2 add
436
437         my $parsed = Email::MIME->new($message);
438         $im->add($parsed);
439
440 Adds a message to to the git repository.  This will acquire
441 C<$GIT_DIR/ssoma.lock> and start L<git-fast-import(1)> if necessary.
442
443 Messages added will not be visible to other processes until L</done>
444 is called, but L</remove> may be called on them.
445
446 =head2 remove
447
448         my $junk = Email::MIME->new($message);
449         my ($code, $orig) = $im->remove($junk);
450
451 Removes a message from the repository.  On success, it returns
452 a ':'-prefixed numeric code representing the git-fast-import
453 mark and the original messages as an Email::MIME object.
454 If the message could not be found, the code is "MISSING"
455 and the original message is undef.  If there is a mismatch where
456 the "Message-ID" is matched but the subject and body do not match,
457 the returned code is "MISMATCH" and the conflicting message
458 is returned as orig.
459
460 =head2 done
461
462 Finalizes the L<git-fast-import(1)> and unlocks the repository.
463 Calling this is required to finalize changes to a repository.
464
465 =head1 SEE ALSO
466
467 L<Email::MIME>
468
469 =head1 CONTACT
470
471 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
472
473 The mail archives are hosted at L<https://public-inbox.org/meta/>
474
475 =head1 COPYRIGHT
476
477 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
478
479 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>
480
481 =cut