]> Sergey Matveev's repositories - public-inbox.git/blobdiff - lib/PublicInbox/Import.pm
watch: avoid unnecessary spawning on spam removals
[public-inbox.git] / lib / PublicInbox / Import.pm
index d279fea1a43f25a823cd168801cc82bc24034e13..ee5ca2ea11b4f383e514ecdf117ac1dabe2c14c1 100644 (file)
@@ -1,4 +1,4 @@
-# Copyright (C) 2016-2019 all contributors <meta@public-inbox.org>
+# Copyright (C) 2016-2020 all contributors <meta@public-inbox.org>
 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
 #
 # git fast-import-based ssoma-mda MDA replacement
@@ -7,14 +7,16 @@
 # requires read-only access.
 package PublicInbox::Import;
 use strict;
-use warnings;
-use base qw(PublicInbox::Lock);
+use parent qw(PublicInbox::Lock);
+use v5.10.1;
 use PublicInbox::Spawn qw(spawn popen_rd);
 use PublicInbox::MID qw(mids mid2path);
 use PublicInbox::Address;
-use PublicInbox::MsgTime qw(msg_timestamp msg_datestamp);
-use PublicInbox::ContentId qw(content_digest);
+use PublicInbox::Smsg;
+use PublicInbox::MsgTime qw(msg_datestamp);
+use PublicInbox::ContentHash qw(content_digest);
 use PublicInbox::MDA;
+use PublicInbox::Eml;
 use POSIX qw(strftime);
 
 sub new {
@@ -23,17 +25,17 @@ sub new {
        my ($class, $git, $name, $email, $ibx) = @_;
        my $ref = 'refs/heads/master';
        if ($ibx) {
-               $ref = $ibx->{ref_head} || 'refs/heads/master';
-               $name ||= $ibx->{name};
-               $email ||= $ibx->{-primary_address};
-               $git ||= $ibx->git;
+               $ref = $ibx->{ref_head} // 'refs/heads/master';
+               $name //= $ibx->{name};
+               $email //= $ibx->{-primary_address};
+               $git //= $ibx->git;
        }
        bless {
                git => $git,
                ident => "$name <$email>",
                mark => 1,
                ref => $ref,
-               -inbox => $ibx,
+               ibx => $ibx,
                path_type => '2/38', # or 'v2'
                lock_path => "$git->{git_dir}/ssoma.lock", # v2 changes this
                bytes_added => 0,
@@ -46,34 +48,35 @@ sub gfi_start {
 
        return ($self->{in}, $self->{out}) if $self->{pid};
 
-       my ($out_r, $out_w);
+       my (@ret, $out_r, $out_w);
        pipe($out_r, $out_w) or die "pipe failed: $!";
-       my $git = $self->{git};
 
        $self->lock_acquire;
-
-       local $/ = "\n";
-       my $ref = $self->{ref};
-       chomp($self->{tip} = $git->qx(qw(rev-parse --revs-only), $ref));
-       if ($self->{path_type} ne '2/38' && $self->{tip}) {
-               local $/ = "\0";
-               my @tree = $git->qx(qw(ls-tree -r -z --name-only), $ref);
-               chomp @tree;
-               $self->{-tree} = { map { $_ => 1 } @tree };
+       eval {
+               my ($git, $ref) = @$self{qw(git ref)};
+               local $/ = "\n";
+               chomp($self->{tip} = $git->qx(qw(rev-parse --revs-only), $ref));
+               if ($self->{path_type} ne '2/38' && $self->{tip}) {
+                       local $/ = "\0";
+                       my @t = $git->qx(qw(ls-tree -r -z --name-only), $ref);
+                       chomp @t;
+                       $self->{-tree} = { map { $_ => 1 } @t };
+               }
+               my @cmd = ('git', "--git-dir=$git->{git_dir}",
+                       qw(fast-import --quiet --done --date-format=raw));
+               my ($in_r, $pid) = popen_rd(\@cmd, undef, { 0 => $out_r });
+               $out_w->autoflush(1);
+               $self->{in} = $in_r;
+               $self->{out} = $out_w;
+               $self->{pid} = $pid;
+               $self->{nchg} = 0;
+               @ret = ($in_r, $out_w);
+       };
+       if ($@) {
+               $self->lock_release;
+               die $@;
        }
-
-       my $git_dir = $git->{git_dir};
-       my @cmd = ('git', "--git-dir=$git_dir", qw(fast-import
-                       --quiet --done --date-format=raw));
-       my ($in_r, $pid) = popen_rd(\@cmd, undef, { 0 => $out_r });
-       $out_w->autoflush(1);
-       $self->{in} = $in_r;
-       $self->{out} = $out_w;
-       $self->{pid} = $pid;
-       $self->{nchg} = 0;
-       binmode $out_w, ':raw' or die "binmode :raw failed: $!";
-       binmode $in_r, ':raw' or die "binmode :raw failed: $!";
-       ($in_r, $out_w);
+       @ret;
 }
 
 sub wfail () { die "write to fast-import failed: $!" }
@@ -137,7 +140,7 @@ sub check_remove_v1 {
        $info =~ m!\A100644 blob ([a-f0-9]{40})\t!s or die "not blob: $info";
        my $oid = $1;
        my $msg = _cat_blob($r, $w, $oid) or die "BUG: cat-blob $1 failed";
-       my $cur = PublicInbox::MIME->new($msg);
+       my $cur = PublicInbox::Eml->new($msg);
        my $cur_s = $cur->header('Subject');
        $cur_s = '' unless defined $cur_s;
        my $cur_m = $mime->header('Subject');
@@ -159,7 +162,7 @@ sub progress {
        my ($self, $msg) = @_;
        return unless $self->{pid};
        print { $self->{out} } "progress $msg\n" or wfail;
-       $self->{in}->getline eq "progress $msg\n" or die
+       readline($self->{in}) eq "progress $msg\n" or die
                "progress $msg not received\n";
        undef;
 }
@@ -175,13 +178,16 @@ sub _update_git_info ($$) {
                my $env = { GIT_INDEX_FILE => $index };
                run_die([@cmd, qw(read-tree -m -v -i), $self->{ref}], $env);
        }
-       run_die([@cmd, 'update-server-info']);
-       my $ibx = $self->{-inbox};
-       ($ibx && $self->{path_type} eq '2/38') and eval {
-               require PublicInbox::SearchIdx;
-               my $s = PublicInbox::SearchIdx->new($ibx);
-               $s->index_sync({ ref => $self->{ref} });
-       };
+       eval { run_die([@cmd, 'update-server-info']) };
+       my $ibx = $self->{ibx};
+       if ($ibx && $ibx->version == 1 && -d "$ibx->{inboxdir}/public-inbox" &&
+                               eval { require PublicInbox::SearchIdx }) {
+               eval {
+                       my $s = PublicInbox::SearchIdx->new($ibx);
+                       $s->index_sync({ ref => $self->{ref} });
+               };
+               warn "$ibx->{inboxdir} index failed: $@\n" if $@;
+       }
        eval { run_die([@cmd, qw(gc --auto)]) } if $do_gc;
 }
 
@@ -212,13 +218,13 @@ sub get_mark {
 }
 
 # returns undef on non-existent
-# ('MISMATCH', Email::MIME) on mismatch
-# (:MARK, Email::MIME) on success
+# ('MISMATCH', PublicInbox::Eml) on mismatch
+# (:MARK, PublicInbox::Eml) on success
 #
 # v2 callers should check with Xapian before calling this as
 # it is not idempotent.
 sub remove {
-       my ($self, $mime, $msg) = @_; # mime = Email::MIME
+       my ($self, $mime, $msg) = @_; # mime = PublicInbox::Eml or Email::MIME
 
        my $path_type = $self->{path_type};
        my ($path, $err, $cur, $blob);
@@ -251,7 +257,7 @@ sub remove {
        }
        my $ident = $self->{ident};
        my $now = now_raw();
-       $msg ||= 'rm';
+       $msg //= 'rm';
        my $len = length($msg) + 1;
        print $w "commit $ref\nmark :$commit\n",
                "author $ident $now\n",
@@ -268,31 +274,33 @@ sub remove {
        (($self->{tip} = ":$commit"), $cur);
 }
 
-sub git_timestamp {
-       my ($ts, $zone) = @_;
+sub git_timestamp ($) {
+       my ($ts, $zone) = @{$_[0]};
        $ts = 0 if $ts < 0; # git uses unsigned times
        "$ts $zone";
 }
 
-sub extract_cmt_info ($) {
-       my ($mime) = @_;
+sub extract_cmt_info ($;$) {
+       my ($mime, $smsg) = @_;
+       # $mime is PublicInbox::Eml, but remains Email::MIME-compatible
+       $smsg //= bless {}, 'PublicInbox::Smsg';
+
+       $smsg->populate($mime);
 
        my $sender = '';
-       my $from = $mime->header('From');
-       $from ||= '';
+       my $from = delete($smsg->{From}) // '';
        my ($email) = PublicInbox::Address::emails($from);
        my ($name) = PublicInbox::Address::names($from);
        if (!defined($name) || !defined($email)) {
-               $sender = $mime->header('Sender');
-               $sender ||= '';
-               if (!defined($name)) {
-                       ($name) = PublicInbox::Address::names($sender);
-               }
-               if (!defined($email)) {
-                       ($email) = PublicInbox::Address::emails($sender);
-               }
+               $sender = $mime->header('Sender') // '';
+               $name //= (PublicInbox::Address::names($sender))[0];
+               $email //= (PublicInbox::Address::emails($sender))[0];
        }
        if (defined $email) {
+               # Email::Address::XS may leave quoted '<' in addresses,
+               # which git-fast-import doesn't like
+               $email =~ tr/<>//d;
+
                # quiet down wide character warnings with utf8::encode
                utf8::encode($email);
        } else {
@@ -312,23 +320,18 @@ sub extract_cmt_info ($) {
                warn "no name in From: $from or Sender: $sender\n";
        }
 
-       my $hdr = $mime->header_obj;
-
-       my $subject = $hdr->header('Subject');
-       $subject = '(no subject)' unless defined $subject;
-       # Mime decoding can create nulls replace them with spaces to protect git
-       $subject =~ tr/\0/ /;
+       my $subject = delete($smsg->{Subject}) // '(no subject)';
        utf8::encode($subject);
-       my $at = git_timestamp(my @at = msg_datestamp($hdr));
-       my $ct = git_timestamp(my @ct = msg_timestamp($hdr));
-       ($name, $email, $at, $ct, $subject);
+       my $at = git_timestamp(delete $smsg->{-ds});
+       my $ct = git_timestamp(delete $smsg->{-ts});
+       ("$name <$email>", $at, $ct, $subject);
 }
 
 # kill potentially confusing/misleading headers
 sub drop_unwanted_headers ($) {
        my ($mime) = @_;
 
-       $mime->header_set($_) for qw(bytes lines content-length status);
+       $mime->header_set($_) for qw(Bytes Lines Content-Length Status);
        $mime->header_set($_) for @PublicInbox::MDA::BAD_HEADERS;
 }
 
@@ -342,13 +345,12 @@ sub append_mid ($$) {
 }
 
 sub v1_mid0 ($) {
-       my ($mime) = @_;
-       my $hdr = $mime->header_obj;
-       my $mids = mids($hdr);
+       my ($eml) = @_;
+       my $mids = mids($eml);
 
-       if (!scalar(@$mids)) { # spam often has no Message-Id
-               my $mid0 = digest2mid(content_digest($mime), $hdr);
-               append_mid($hdr, $mid0);
+       if (!scalar(@$mids)) { # spam often has no Message-ID
+               my $mid0 = digest2mid(content_digest($eml), $eml);
+               append_mid($eml, $mid0);
                return $mid0;
        }
        $mids->[0];
@@ -366,9 +368,9 @@ sub clean_tree_v2 ($$$) {
 # returns undef on duplicate
 # returns the :MARK of the most recent commit
 sub add {
-       my ($self, $mime, $check_cb) = @_; # mime = Email::MIME
+       my ($self, $mime, $check_cb, $smsg) = @_;
 
-       my ($name, $email, $at, $ct, $subject) = extract_cmt_info($mime);
+       my ($author, $at, $ct, $subject) = extract_cmt_info($mime, $smsg);
        my $path_type = $self->{path_type};
        my $path;
        if ($path_type eq '2/38') {
@@ -387,7 +389,7 @@ sub add {
 
        # spam check:
        if ($check_cb) {
-               $mime = $check_cb->($mime) or return;
+               $mime = $check_cb->($mime, $self->{ibx}) or return;
        }
 
        my $blob = $self->{mark}++;
@@ -398,9 +400,10 @@ sub add {
        print $w $raw_email, "\n" or wfail;
 
        # v2: we need this for Xapian
-       if ($self->{want_object_info}) {
-               my $oid = $self->get_mark(":$blob");
-               $self->{last_object} = [ $oid, $n, \$raw_email ];
+       if ($smsg) {
+               $smsg->{blob} = $self->get_mark(":$blob");
+               $smsg->{raw_bytes} = $n;
+               $smsg->{-raw_email} = \$raw_email;
        }
        my $ref = $self->{ref};
        my $commit = $self->{mark}++;
@@ -411,7 +414,7 @@ sub add {
        }
 
        print $w "commit $ref\nmark :$commit\n",
-               "author $name <$email> $at\n",
+               "author $author $at\n",
                "committer $self->{ident} $ct\n" or wfail;
        print $w "data ", (length($subject) + 1), "\n",
                $subject, "\n\n" or wfail;
@@ -431,30 +434,56 @@ sub run_die ($;$$) {
        $? == 0 or die join(' ', @$cmd) . " failed: $?\n";
 }
 
+my @INIT_FILES = ('HEAD' => "ref: refs/heads/master\n",
+               'description' => <<EOD,
+Unnamed repository; edit this file 'description' to name the repository.
+EOD
+               'config' => <<EOC);
+[core]
+       repositoryFormatVersion = 0
+       filemode = true
+       bare = true
+[repack]
+       writeBitmaps = true
+EOC
+
 sub init_bare {
-       my ($dir) = @_;
-       my @cmd = (qw(git init --bare -q), $dir);
-       run_die(\@cmd);
-       # set a reasonable default:
-       @cmd = (qw/git config/, "--file=$dir/config",
-               'repack.writeBitmaps', 'true');
-       run_die(\@cmd);
+       my ($dir) = @_; # or self
+       $dir = $dir->{git}->{git_dir} if ref($dir);
+       require File::Path;
+       File::Path::mkpath([ map { "$dir/$_" } qw(objects/info refs/heads) ]);
+       for (my $i = 0; $i < @INIT_FILES; $i++) {
+               my $f = $dir.'/'.$INIT_FILES[$i++];
+               next if -f $f;
+               open my $fh, '>', $f or die "open $f: $!";
+               print $fh $INIT_FILES[$i] or die "print $f: $!";
+               close $fh or die "close $f: $!";
+       }
 }
 
+# true if locked and active
+sub active { !!$_[0]->{out} }
+
 sub done {
        my ($self) = @_;
        my $w = delete $self->{out} or return;
-       my $r = delete $self->{in} or die 'BUG: missing {in} when done';
-       print $w "done\n" or wfail;
-       my $pid = delete $self->{pid} or die 'BUG: missing {pid} when done';
-       waitpid($pid, 0) == $pid or die 'fast-import did not finish';
-       $? == 0 or die "fast-import failed: $?";
-
-       _update_git_info($self, 1) if delete $self->{nchg};
-
-       $self->lock_release;
-
+       eval {
+               my $r = delete $self->{in} or die 'BUG: missing {in} when done';
+               print $w "done\n" or wfail;
+               my $pid = delete $self->{pid} or
+                               die 'BUG: missing {pid} when done';
+               waitpid($pid, 0) == $pid or die 'fast-import did not finish';
+               $? == 0 or die "fast-import failed: $?";
+       };
+       my $wait_err = $@;
+       my $nchg = delete $self->{nchg};
+       if ($nchg && !$wait_err) {
+               eval { _update_git_info($self, 1) };
+               warn "E: $self->{git}->{git_dir} update info: $@\n" if $@;
+       }
+       $self->lock_release(!!$nchg);
        $self->{git}->cleanup;
+       die $wait_err if $wait_err;
 }
 
 sub atfork_child {
@@ -482,11 +511,11 @@ sub digest2mid ($$) {
 
 sub rewrite_commit ($$$$) {
        my ($self, $oids, $buf, $mime) = @_;
-       my ($name, $email, $at, $ct, $subject);
+       my ($author, $at, $ct, $subject);
        if ($mime) {
-               ($name, $email, $at, $ct, $subject) = extract_cmt_info($mime);
+               ($author, $at, $ct, $subject) = extract_cmt_info($mime);
        } else {
-               $name = $email = '';
+               $author = '<>';
                $subject = 'purged '.join(' ', @$oids);
        }
        @$oids = ();
@@ -495,7 +524,7 @@ sub rewrite_commit ($$$$) {
                my $l = $buf->[$i];
                if ($l =~ /^author .* ([0-9]+ [\+-]?[0-9]+)$/) {
                        $at //= $1;
-                       $buf->[$i] = "author $name <$email> $at\n";
+                       $buf->[$i] = "author $author $at\n";
                } elsif ($l =~ /^committer .* ([0-9]+ [\+-]?[0-9]+)$/) {
                        $ct //= $1;
                        $buf->[$i] = "committer $self->{ident} $ct\n";
@@ -527,7 +556,7 @@ sub replace_oids {
                        push @buf, "reset $tmp\n";
                } elsif (/^commit (?:.+)/) {
                        if (@buf) {
-                               $w->print(@buf) or wfail;
+                               print $w @buf or wfail;
                                @buf = ();
                        }
                        push @buf, "commit $tmp\n";
@@ -564,7 +593,7 @@ sub replace_oids {
                                rewrite_commit($self, \@oids, \@buf, $mime);
                                $nreplace++;
                        }
-                       $w->print(@buf, "\n") or wfail;
+                       print $w @buf, "\n" or wfail;
                        @buf = ();
                } elsif ($_ eq "done\n") {
                        $done = 1;
@@ -577,7 +606,7 @@ sub replace_oids {
        }
        close $rd or die "close fast-export failed: $?";
        if (@buf) {
-               $w->print(@buf) or wfail;
+               print $w @buf or wfail;
        }
        die 'done\n not seen from fast-export' unless $done;
        chomp(my $cmt = $self->get_mark(":$mark")) if $nreplace;
@@ -621,7 +650,10 @@ version 1.0
 
 =head1 SYNOPSIS
 
-       use Email::MIME;
+       use PublicInbox::Eml;
+       # PublicInbox::Eml exists as of public-inbox 1.5.0,
+       # Email::MIME was used in older versions
+
        use PublicInbox::Git;
        use PublicInbox::Import;
 
@@ -637,18 +669,17 @@ version 1.0
                "Date: Thu, 01 Jan 1970 00:00:00 +0000\n" .
                "Message-ID: <m\@example.org>\n".
                "\ntest message";
-       my $parsed = Email::MIME->new($message);
+       my $parsed = PublicInbox::Eml->new($message);
        my $ret = $im->add($parsed);
        if (!defined $ret) {
-               warn "duplicate: ",
-                       $parsed->header_obj->header_raw('Message-ID'), "\n";
+               warn "duplicate: ", $parsed->header_raw('Message-ID'), "\n";
        } else {
                print "imported at mark $ret\n";
        }
        $im->done;
 
        # to remove a message
-       my $junk = Email::MIME->new($message);
+       my $junk = PublicInbox::Eml->new($message);
        my ($mark, $orig) = $im->remove($junk);
        if ($mark eq 'MISSING') {
                print "not found\n";
@@ -663,8 +694,8 @@ version 1.0
 
 =head1 DESCRIPTION
 
-An importer and remover for public-inboxes which takes L<Email::MIME>
-messages as input and stores them in a git repository as
+An importer and remover for public-inboxes which takes C<PublicInbox::Eml>
+or L<Email::MIME> messages as input and stores them in a git repository as
 documented in L<https://public-inbox.org/public-inbox-v1-format.txt>,
 except it does not allow duplicate Message-IDs.
 
@@ -682,7 +713,7 @@ Initialize a new PublicInbox::Import object.
 
 =head2 add
 
-       my $parsed = Email::MIME->new($message);
+       my $parsed = PublicInbox::Eml->new($message);
        $im->add($parsed);
 
 Adds a message to to the git repository.  This will acquire
@@ -693,12 +724,13 @@ is called, but L</remove> may be called on them.
 
 =head2 remove
 
-       my $junk = Email::MIME->new($message);
+       my $junk = PublicInbox::Eml->new($message);
        my ($code, $orig) = $im->remove($junk);
 
 Removes a message from the repository.  On success, it returns
 a ':'-prefixed numeric code representing the git-fast-import
-mark and the original messages as an Email::MIME object.
+mark and the original messages as a PublicInbox::Eml
+(or Email::MIME) object.
 If the message could not be found, the code is "MISSING"
 and the original message is undef.  If there is a mismatch where
 the "Message-ID" is matched but the subject and body do not match,
@@ -722,7 +754,7 @@ The mail archives are hosted at L<https://public-inbox.org/meta/>
 
 =head1 COPYRIGHT
 
-Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
+Copyright (C) 2016-2020 all contributors L<mailto:meta@public-inbox.org>
 
 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>