1 # Copyright (C) 2015 all contributors <meta@public-inbox.org>
2 # License: AGPLv3 or later (https://www.gnu.org/licenses/agpl-3.0.txt)
3 # based on notmuch, but with no concept of folders, files or flags
5 # Indexes mail with Xapian and our (SQLite-based) ::Msgmap for use
6 # with the web and NNTP interfaces. This index maintains thread
7 # relationships for use by PublicInbox::SearchThread.
8 # This writes to the search index.
9 package PublicInbox::SearchIdx;
12 use Fcntl qw(:flock :DEFAULT);
13 use PublicInbox::MIME;
14 use Email::MIME::ContentType;
15 $Email::MIME::ContentType::STRICT_PARAMS = 0;
16 use base qw(PublicInbox::Search);
17 use PublicInbox::MID qw/mid_clean id_compress mid_mime/;
18 use PublicInbox::MsgIter;
20 use POSIX qw(strftime);
21 require PublicInbox::Git;
24 MAX_MID_SIZE => 244, # max term size - 1 in Xapian
27 OLD_PERM_EVERYBODY => 2,
29 PERM_EVERYBODY => 0664,
30 BATCH_BYTES => 1_000_000,
31 DEBUG => !!$ENV{DEBUG},
46 return $s unless ($s =~ /\A"(.*)"\z/);
48 $s =~ s/\\([abfnrtv])/$GIT_ESC{$1}/g;
49 $s =~ s/\\([0-7]{1,3})/chr(oct($1))/ge;
54 my ($class, $inbox, $creat) = @_;
58 $git_dir = $inbox->{mainrepo};
59 $altid = $inbox->{altid};
61 require PublicInbox::AltId;
63 PublicInbox::AltId->new($inbox, $_);
67 require Search::Xapian::WritableDatabase;
68 my $self = bless { git_dir => $git_dir, -altid => $altid }, $class;
69 my $perm = $self->_git_config_perm;
70 my $umask = _umask_for($perm);
71 $self->{umask} = $umask;
72 $self->{lock_path} = "$git_dir/ssoma.lock";
73 $self->{git} = PublicInbox::Git->new($git_dir);
74 $self->{creat} = ($creat || 0) == 1;
80 my $xdb = delete $self->{xdb} or croak 'not acquired';
82 _lock_release($self) if $self->{creat};
88 croak 'already acquired' if $self->{xdb};
89 my $dir = PublicInbox::Search->xdir($self->{git_dir});
90 my $flag = Search::Xapian::DB_OPEN;
94 File::Path::mkpath($dir);
95 $flag = Search::Xapian::DB_CREATE_OR_OPEN;
97 $self->{xdb} = Search::Xapian::WritableDatabase->new($dir, $flag);
100 # we only acquire the flock if creating or reindexing;
101 # PublicInbox::Import already has the lock on its own.
104 croak 'already locked' if $self->{lockfh};
105 sysopen(my $lockfh, $self->{lock_path}, O_WRONLY|O_CREAT) or
106 die "failed to open lock $self->{lock_path}: $!\n";
107 flock($lockfh, LOCK_EX) or die "lock failed: $!\n";
108 $self->{lockfh} = $lockfh;
113 my $lockfh = delete $self->{lockfh} or croak 'not locked';
114 flock($lockfh, LOCK_UN) or die "unlock failed: $!\n";
115 close $lockfh or die "close failed: $!\n";
119 my ($doc, $col, $num) = @_;
120 $num = Search::Xapian::sortable_serialise($num);
121 $doc->add_value($col, $num);
124 sub add_values ($$$) {
125 my ($smsg, $bytes, $num) = @_;
128 my $doc = $smsg->{doc};
129 add_val($doc, &PublicInbox::Search::TS, $ts);
131 defined($num) and add_val($doc, &PublicInbox::Search::NUM, $num);
133 defined($bytes) and add_val($doc, &PublicInbox::Search::BYTES, $bytes);
135 add_val($doc, &PublicInbox::Search::LINES,
136 $smsg->{mime}->body_raw =~ tr!\n!\n!);
138 my $yyyymmdd = strftime('%Y%m%d', gmtime($ts));
139 add_val($doc, PublicInbox::Search::YYYYMMDD, $yyyymmdd);
142 sub index_users ($$) {
143 my ($tg, $smsg) = @_;
145 my $from = $smsg->from;
149 $tg->index_text($from, 1, 'A'); # A - author
150 $tg->increase_termpos;
151 $tg->index_text($to, 1, 'XTO') if $to ne '';
152 $tg->increase_termpos;
153 $tg->index_text($cc, 1, 'XCC') if $cc ne '';
154 $tg->increase_termpos;
157 sub index_text_inc ($$$) {
158 my ($tg, $text, $pfx) = @_;
159 $tg->index_text($text, 1, $pfx);
160 $tg->increase_termpos;
163 sub index_old_diff_fn {
164 my ($tg, $seen, $fa, $fb) = @_;
166 # no renames or space support for traditional diffs,
167 # find the number of leading common paths to strip:
168 my @fa = split('/', $fa);
169 my @fb = split('/', $fb);
170 while (scalar(@fa) && scalar(@fb)) {
171 $fa = join('/', @fa);
172 $fb = join('/', @fb);
174 index_text_inc($tg, $fa,'XDFN') unless $seen->{$fa}++;
183 sub index_diff ($$$) {
184 my ($tg, $lines, $doc) = @_;
188 if ($in_diff && s/^ //) { # diff context
189 index_text_inc($tg, $_, 'XDFCTX');
190 } elsif (/^-- $/) { # email signature begins
192 } elsif (m!^diff --git ("?a/.+) ("?b/.+)\z!) {
193 my ($fa, $fb) = ($1, $2);
194 my $fn = (split('/', git_unquote($fa), 2))[1];
195 index_text_inc($tg, $fn, 'XDFN') unless $seen{$fn}++;
196 $fn = (split('/', git_unquote($fb), 2))[1];
197 index_text_inc($tg, $fn, 'XDFN') unless $seen{$fn}++;
200 } elsif (m/^diff -(.+) (\S+) (\S+)$/) {
201 my ($opt, $fa, $fb) = ($1, $2, $3);
202 # only support unified:
203 next unless $opt =~ /[uU]/;
204 $in_diff = index_old_diff_fn($tg, \%seen, $fa, $fb);
205 } elsif (m!^--- ("?a/.+)!) {
206 my $fn = (split('/', git_unquote($1), 2))[1];
207 index_text_inc($tg, $fn, 'XDFN') unless $seen{$fn}++;
209 } elsif (m!^\+\+\+ ("?b/.+)!) {
210 my $fn = (split('/', git_unquote($1), 2))[1];
211 index_text_inc($tg, $fn, 'XDFN') unless $seen{$fn}++;
213 } elsif (/^--- (\S+)/) {
215 } elsif (defined $in_diff && /^\+\+\+ (\S+)/) {
216 $in_diff = index_old_diff_fn($tg, \%seen, $in_diff, $1);
217 } elsif ($in_diff && s/^\+//) { # diff added
218 index_text_inc($tg, $_, 'XDFB');
219 } elsif ($in_diff && s/^-//) { # diff removed
220 index_text_inc($tg, $_, 'XDFA');
221 } elsif (m!^index ([a-f0-9]+)\.\.([a-f0-9]+)!) {
222 my ($ba, $bb) = ($1, $2);
223 index_git_blob_id($doc, 'XDFPRE', $ba);
224 index_git_blob_id($doc, 'XDFPOST', $bb);
226 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*$/) {
227 # traditional diff w/o -p
228 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*(\S+.*)$/) {
229 # hunk header context
230 index_text_inc($tg, $1, 'XDFHH');
231 # ignore the following lines:
232 } elsif (/^(?:dis)similarity index/) {
233 } elsif (/^(?:old|new) mode/) {
234 } elsif (/^(?:deleted|new) file mode/) {
235 } elsif (/^(?:copy|rename) (?:from|to) /) {
236 } elsif (/^(?:dis)?similarity index /) {
237 } elsif (/^\\ No newline at end of file/) {
238 } elsif (/^Binary files .* differ/) {
242 warn "non-diff line: $_\n" if DEBUG && $_ ne '';
248 sub index_body ($$$) {
249 my ($tg, $lines, $doc) = @_;
250 my $txt = join("\n", @$lines);
251 $tg->index_text($txt, !!$doc, $doc ? 'XNQ' : 'XQUOT');
252 $tg->increase_termpos;
253 # does it look like a diff?
254 if ($doc && $txt =~ /^(?:diff|---|\+\+\+) /ms) {
256 index_diff($tg, $lines, $doc);
262 my ($self, $mime, $bytes, $num, $blob) = @_; # mime = Email::MIME object
263 my $db = $self->{xdb};
265 my ($doc_id, $old_tid);
266 my $mid = mid_clean(mid_mime($mime));
269 die 'Message-ID too long' if length($mid) > MAX_MID_SIZE;
270 my $smsg = $self->lookup_message($mid);
272 # convert a ghost to a regular message
273 # it will also clobber any existing regular message
274 $doc_id = $smsg->{doc_id};
275 $old_tid = $smsg->thread_id;
277 $smsg = PublicInbox::SearchMsg->new($mime);
278 my $doc = $smsg->{doc};
279 $doc->add_term('Q' . $mid);
281 my $subj = $smsg->subject;
283 my $path = $self->subject_path($subj);
284 $doc->add_term('XPATH' . id_compress($path));
287 add_values($smsg, $bytes, $num);
289 my $tg = $self->term_generator;
291 $tg->set_document($doc);
292 $tg->index_text($subj, 1, 'S') if $subj;
293 $tg->increase_termpos;
295 index_users($tg, $smsg);
297 msg_iter($mime, sub {
298 my ($part, $depth, @idx) = @{$_[0]};
299 my $ct = $part->content_type || 'text/plain';
300 my $fn = $part->filename;
301 if (defined $fn && $fn ne '') {
302 $tg->index_text($fn, 1, 'XFN');
305 return if $ct =~ m!\btext/x?html\b!i;
307 my $s = eval { $part->body_str };
309 if ($ct =~ m!\btext/plain\b!i) {
310 # Try to assume UTF-8 because Alpine
311 # seems to do wacky things and set
313 $part->charset_set('UTF-8');
314 $s = eval { $part->body_str };
315 $s = $part->body if $@;
318 defined $s or return;
321 my $body = $part->body;
322 my @lines = split(/\n/, $body);
323 while (defined(my $l = shift @lines)) {
325 index_body($tg, \@orig, $doc) if @orig;
328 index_body($tg, \@quot, 0) if @quot;
332 index_body($tg, \@quot, 0) if @quot;
333 index_body($tg, \@orig, $doc) if @orig;
336 link_message($self, $smsg, $old_tid);
337 $tg->index_text($mid, 1, 'XMID');
338 $doc->set_data($smsg->to_doc_data($blob));
340 if (my $altid = $self->{-altid}) {
341 foreach my $alt (@$altid) {
342 my $id = $alt->mid2alt($mid);
343 next unless defined $id;
344 $doc->add_term($alt->{xprefix} . $id);
347 if (defined $doc_id) {
348 $db->replace_document($doc_id, $doc);
350 $doc_id = $db->add_document($doc);
355 warn "failed to index message <$mid>: $@\n";
361 # returns deleted doc_id on success, undef on missing
363 my ($self, $mid) = @_;
364 my $db = $self->{xdb};
366 $mid = mid_clean($mid);
369 $doc_id = $self->find_unique_doc_id('Q' . $mid);
370 if (defined $doc_id) {
371 $db->delete_document($doc_id);
373 warn "cannot remove non-existent <$mid>\n";
378 warn "failed to remove message <$mid>: $@\n";
384 sub term_generator { # write-only
387 my $tg = $self->{term_generator};
390 $tg = Search::Xapian::TermGenerator->new;
391 $tg->set_stemmer($self->stemmer);
393 $self->{term_generator} = $tg;
396 # increments last_thread_id counter
397 # returns a 64-bit integer represented as a hex string
400 my $db = $self->{xdb};
401 my $last_thread_id = int($db->get_metadata('last_thread_id') || 0);
403 $db->set_metadata('last_thread_id', ++$last_thread_id);
409 my ($self, $smsg, $old_tid) = @_;
410 my $doc = $smsg->{doc};
411 my $mid = $smsg->mid;
412 my $mime = $smsg->{mime};
413 my $hdr = $mime->header_obj;
415 # last References should be IRT, but some mail clients do things
416 # out of order, so trust IRT over References iff IRT exists
417 my @refs = ($hdr->header_raw('References'),
418 $hdr->header_raw('In-Reply-To'));
419 @refs = ((join(' ', @refs)) =~ /<([^>]+)>/g);
423 my %uniq = ($mid => 1);
424 my @orig_refs = @refs;
427 # prevent circular references via References: here:
428 foreach my $ref (@orig_refs) {
429 if (length($ref) > MAX_MID_SIZE) {
430 warn "References: <$ref> too long, ignoring\n";
439 $smsg->{references} = '<'.join('> <', @refs).'>';
441 # first ref *should* be the thread root,
442 # but we can never trust clients to do the right thing
443 my $ref = shift @refs;
444 $tid = $self->_resolve_mid_to_tid($ref);
445 $self->merge_threads($tid, $old_tid) if defined $old_tid;
447 # the rest of the refs should point to this tid:
448 foreach $ref (@refs) {
449 my $ptid = $self->_resolve_mid_to_tid($ref);
450 merge_threads($self, $tid, $ptid);
453 $tid = defined $old_tid ? $old_tid : $self->next_thread_id;
455 $doc->add_term('G' . $tid);
459 my ($self, $mime, $bytes, $num, $blob) = @_;
460 $self->add_message($mime, $bytes, $num, $blob);
463 sub index_git_blob_id {
464 my ($doc, $pfx, $objid) = @_;
466 my $len = length($objid);
467 for (my $len = length($objid); $len >= 7; ) {
468 $doc->add_term($pfx.$objid);
469 $objid = substr($objid, 0, --$len);
474 my ($self, $mime) = @_;
475 my $mid = eval { mid_clean(mid_mime($mime)) };
476 $self->remove_message($mid) if defined $mid;
480 my ($self, $mime) = @_;
481 my $mid = mid_clean(mid_mime($mime));
482 my $mm = $self->{mm};
483 my $num = $mm->mid_insert($mid);
485 # fallback to num_for since filters like RubyLang set the number
486 defined $num ? $num : $mm->num_for($mid);
490 my ($self, $mime) = @_;
491 $self->{mm}->mid_delete(mid_clean(mid_mime($mime)));
495 my ($self, $mime, $bytes, $blob) = @_;
496 my $num = $self->{mm}->num_for(mid_clean(mid_mime($mime)));
497 index_blob($self, $mime, $bytes, $num, $blob);
501 my ($self, $mime) = @_;
502 $self->{mm}->mid_delete(mid_clean(mid_mime($mime)));
503 unindex_blob($self, $mime);
507 my ($self, $mime, $bytes, $blob) = @_;
508 my $num = index_mm($self, $mime);
509 index_blob($self, $mime, $bytes, $num, $blob);
513 my ($self, $mime) = @_;
514 unindex_blob($self, $mime);
515 unindex_mm($self, $mime);
519 my ($git, $blob, $sizeref) = @_;
521 my $str = $git->cat_file($blob, $sizeref);
522 # fixup bugs from import:
523 $$str =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
524 PublicInbox::MIME->new($str);
530 my ($self, $opts) = @_;
531 with_umask($self, sub { $self->_index_sync($opts) });
534 sub batch_adjust ($$$$) {
535 my ($max, $bytes, $batch_cb, $latest) = @_;
539 $batch_cb->($latest, 1);
544 my ($self, $log, $add_cb, $del_cb, $batch_cb) = @_;
545 my $hex = '[a-f0-9]';
546 my $h40 = $hex .'{40}';
547 my $addmsg = qr!^:000000 100644 \S+ ($h40) A\t${hex}{2}/${hex}{38}$!;
548 my $delmsg = qr!^:100644 000000 ($h40) \S+ D\t${hex}{2}/${hex}{38}$!;
549 my $git = $self->{git};
552 my $max = BATCH_BYTES;
555 while (defined($line = <$log>)) {
556 if ($line =~ /$addmsg/o) {
558 my $mime = do_cat_mail($git, $blob, \$bytes) or next;
559 batch_adjust(\$max, $bytes, $batch_cb, $latest);
560 $add_cb->($self, $mime, $bytes, $blob);
561 } elsif ($line =~ /$delmsg/o) {
563 my $mime = do_cat_mail($git, $blob, \$bytes) or next;
564 batch_adjust(\$max, $bytes, $batch_cb, $latest);
565 $del_cb->($self, $mime);
566 } elsif ($line =~ /^commit ($h40)/o) {
570 $batch_cb->($latest, 0);
576 require PublicInbox::Msgmap;
577 PublicInbox::Msgmap->new($self->{git_dir}, 1);
582 my ($self, $range) = @_;
583 $self->{git}->popen(qw/log --reverse --no-notes --no-color
584 --raw -r --no-abbrev/, $range);
587 # indexes all unindexed messages
589 my ($self, $opts) = @_;
590 my $tip = $opts->{ref} || 'HEAD';
591 my $reindex = $opts->{reindex};
592 my ($mkey, $last_commit, $lx, $xlog);
593 $self->{git}->batch_prepare;
594 my $xdb = _xdb_acquire($self);
595 $xdb->begin_transaction;
598 $mkey = 'last_commit';
599 $last_commit = $xdb->get_metadata('last_commit');
603 $mkey = undef if $last_commit ne '';
605 $xdb->cancel_transaction;
606 $xdb = _xdb_release($self);
608 # ensure we leak no FDs to "git log"
609 my $range = $lx eq '' ? $tip : "$lx..$tip";
610 $xlog = _git_log($self, $range);
612 $xdb = _xdb_acquire($self);
613 $xdb->begin_transaction;
614 } while ($xdb->get_metadata('last_commit') ne $last_commit);
616 my $mm = _msgmap_init($self);
617 my $dbh = $mm->{dbh} if $mm;
620 my ($commit, $more) = @_;
622 $mm->last_commit($commit) if $commit;
626 $xdb->set_metadata($mkey, $commit) if $mkey && $commit;
627 $xdb->commit_transaction;
628 $xdb = _xdb_release($self);
630 # let another process do some work... <
633 $xdb = _xdb_acquire($self);
634 $xdb->begin_transaction;
636 $dbh->begin_work if $dbh;
642 my $lm = $mm->last_commit || '';
644 # Common case is the indexes are synced,
645 # we only need to run git-log once:
646 rlog($self, $xlog, *index_both, *unindex_both, $cb);
648 # Uncommon case, msgmap and xapian are out-of-sync
649 # do not care for performance (but git is fast :>)
650 # This happens if we have to reindex Xapian since
651 # msgmap is a frozen format and our Xapian format
653 my $r = $lm eq '' ? $tip : "$lm..$tip";
655 # first, ensure msgmap is up-to-date:
656 my $mkey_prev = $mkey;
657 $mkey = undef; # ignore xapian, for now
658 my $mlog = _git_log($self, $r);
660 rlog($self, $mlog, *index_mm, *unindex_mm, $cb);
661 $mm_only = $mlog = undef;
663 # now deal with Xapian
666 rlog($self, $xlog, *index_mm2, *unindex_mm2, $cb);
669 # user didn't install DBD::SQLite and DBI
670 rlog($self, $xlog, *index_blob, *unindex_blob, $cb);
674 # this will create a ghost as necessary
675 sub _resolve_mid_to_tid {
676 my ($self, $mid) = @_;
678 my $smsg = $self->lookup_message($mid) || $self->create_ghost($mid);
683 my ($self, $mid) = @_;
685 my $tid = $self->next_thread_id;
686 my $doc = Search::Xapian::Document->new;
687 $doc->add_term('Q' . $mid);
688 $doc->add_term('G' . $tid);
689 $doc->add_term('T' . 'ghost');
691 my $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
692 $self->{xdb}->add_document($doc);
698 my ($self, $winner_tid, $loser_tid) = @_;
699 return if $winner_tid == $loser_tid;
700 my ($head, $tail) = $self->find_doc_ids('G' . $loser_tid);
701 my $db = $self->{xdb};
703 for (; $head != $tail; $head->inc) {
704 my $docid = $head->get_docid;
705 my $doc = $db->get_document($docid);
706 $doc->remove_term('G' . $loser_tid);
707 $doc->add_term('G' . $winner_tid);
708 $db->replace_document($docid, $doc);
712 sub _read_git_config_perm {
714 my @cmd = qw(config core.sharedRepository);
715 my $fh = PublicInbox::Git->new($self->{git_dir})->popen(@cmd);
718 chomp $perm if defined $perm;
722 sub _git_config_perm {
724 my $perm = scalar @_ ? $_[0] : _read_git_config_perm($self);
725 return PERM_GROUP if (!defined($perm) || $perm eq '');
726 return PERM_UMASK if ($perm eq 'umask');
727 return PERM_GROUP if ($perm eq 'group');
728 if ($perm =~ /\A(?:all|world|everybody)\z/) {
729 return PERM_EVERYBODY;
731 return PERM_GROUP if ($perm =~ /\A(?:true|yes|on|1)\z/);
732 return PERM_UMASK if ($perm =~ /\A(?:false|no|off|0)\z/);
735 return PERM_UMASK if ($i == PERM_UMASK);
736 return PERM_GROUP if ($i == OLD_PERM_GROUP);
737 return PERM_EVERYBODY if ($i == OLD_PERM_EVERYBODY);
739 if (($i & 0600) != 0600) {
740 die "core.sharedRepository mode invalid: ".
741 sprintf('%.3o', $i) . "\nOwner must have permissions\n";
747 my ($perm) = @_; # _git_config_perm return value
749 return umask if $rv == 0;
751 # set +x bit if +r or +w were set
752 $rv |= 0100 if ($rv & 0600);
753 $rv |= 0010 if ($rv & 0060);
754 $rv |= 0001 if ($rv & 0006);
759 my ($self, $cb) = @_;
760 my $old = umask $self->{umask};
761 my $rv = eval { $cb->() };
769 # order matters for unlocking
770 $_[0]->{xdb} = undef;
771 $_[0]->{lockfh} = undef;