1 # Copyright (C) 2015-2018 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <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, $ibx, $creat) = @_;
55 my $mainrepo = $ibx; # for "public-inbox-index" w/o entry in config
56 my $git_dir = $mainrepo;
60 $mainrepo = $ibx->{mainrepo};
61 $altid = $ibx->{altid};
62 $version = $ibx->{version} || 1;
64 require PublicInbox::AltId;
66 PublicInbox::AltId->new($ibx, $_);
71 $git = PublicInbox::Git->new($git_dir); # v1 only
73 require Search::Xapian::WritableDatabase;
75 mainrepo => $mainrepo,
80 my $perm = $self->_git_config_perm;
81 my $umask = _umask_for($perm);
82 $self->{umask} = $umask;
84 $self->{lock_path} = "$mainrepo/ssoma.lock";
85 } elsif ($version == 2) {
86 $self->{lock_path} = "$mainrepo/inbox.lock";
87 $self->{msgmap_path} = "$mainrepo/msgmap.sqlite3";
89 die "unsupported inbox version=$version\n";
91 $self->{creat} = ($creat || 0) == 1;
97 my $xdb = delete $self->{xdb} or croak 'not acquired';
99 _lock_release($self) if $self->{creat};
105 croak 'already acquired' if $self->{xdb};
106 my $dir = $self->xdir;
107 my $flag = Search::Xapian::DB_OPEN;
108 if ($self->{creat}) {
110 _lock_acquire($self);
111 File::Path::mkpath($dir);
112 $flag = Search::Xapian::DB_CREATE_OR_OPEN;
114 $self->{xdb} = Search::Xapian::WritableDatabase->new($dir, $flag);
117 # we only acquire the flock if creating or reindexing;
118 # PublicInbox::Import already has the lock on its own.
121 croak 'already locked' if $self->{lockfh};
122 sysopen(my $lockfh, $self->{lock_path}, O_WRONLY|O_CREAT) or
123 die "failed to open lock $self->{lock_path}: $!\n";
124 flock($lockfh, LOCK_EX) or die "lock failed: $!\n";
125 $self->{lockfh} = $lockfh;
130 my $lockfh = delete $self->{lockfh} or croak 'not locked';
131 flock($lockfh, LOCK_UN) or die "unlock failed: $!\n";
132 close $lockfh or die "close failed: $!\n";
136 my ($doc, $col, $num) = @_;
137 $num = Search::Xapian::sortable_serialise($num);
138 $doc->add_value($col, $num);
141 sub add_values ($$$) {
142 my ($smsg, $bytes, $num) = @_;
145 my $doc = $smsg->{doc};
146 add_val($doc, &PublicInbox::Search::TS, $ts);
148 defined($num) and add_val($doc, &PublicInbox::Search::NUM, $num);
150 defined($bytes) and add_val($doc, &PublicInbox::Search::BYTES, $bytes);
152 add_val($doc, &PublicInbox::Search::LINES,
153 $smsg->{mime}->body_raw =~ tr!\n!\n!);
155 my $yyyymmdd = strftime('%Y%m%d', gmtime($ts));
156 add_val($doc, PublicInbox::Search::YYYYMMDD, $yyyymmdd);
159 sub index_users ($$) {
160 my ($tg, $smsg) = @_;
162 my $from = $smsg->from;
166 $tg->index_text($from, 1, 'A'); # A - author
167 $tg->increase_termpos;
168 $tg->index_text($to, 1, 'XTO') if $to ne '';
169 $tg->increase_termpos;
170 $tg->index_text($cc, 1, 'XCC') if $cc ne '';
171 $tg->increase_termpos;
174 sub index_text_inc ($$$) {
175 my ($tg, $text, $pfx) = @_;
176 $tg->index_text($text, 1, $pfx);
177 $tg->increase_termpos;
180 sub index_old_diff_fn {
181 my ($tg, $seen, $fa, $fb) = @_;
183 # no renames or space support for traditional diffs,
184 # find the number of leading common paths to strip:
185 my @fa = split('/', $fa);
186 my @fb = split('/', $fb);
187 while (scalar(@fa) && scalar(@fb)) {
188 $fa = join('/', @fa);
189 $fb = join('/', @fb);
191 index_text_inc($tg, $fa,'XDFN') unless $seen->{$fa}++;
200 sub index_diff ($$$) {
201 my ($tg, $lines, $doc) = @_;
205 if ($in_diff && s/^ //) { # diff context
206 index_text_inc($tg, $_, 'XDFCTX');
207 } elsif (/^-- $/) { # email signature begins
209 } elsif (m!^diff --git ("?a/.+) ("?b/.+)\z!) {
210 my ($fa, $fb) = ($1, $2);
211 my $fn = (split('/', git_unquote($fa), 2))[1];
212 index_text_inc($tg, $fn, 'XDFN') unless $seen{$fn}++;
213 $fn = (split('/', git_unquote($fb), 2))[1];
214 index_text_inc($tg, $fn, 'XDFN') unless $seen{$fn}++;
217 } elsif (m/^diff -(.+) (\S+) (\S+)$/) {
218 my ($opt, $fa, $fb) = ($1, $2, $3);
219 # only support unified:
220 next unless $opt =~ /[uU]/;
221 $in_diff = index_old_diff_fn($tg, \%seen, $fa, $fb);
222 } elsif (m!^--- ("?a/.+)!) {
223 my $fn = (split('/', git_unquote($1), 2))[1];
224 index_text_inc($tg, $fn, 'XDFN') unless $seen{$fn}++;
226 } elsif (m!^\+\+\+ ("?b/.+)!) {
227 my $fn = (split('/', git_unquote($1), 2))[1];
228 index_text_inc($tg, $fn, 'XDFN') unless $seen{$fn}++;
230 } elsif (/^--- (\S+)/) {
232 } elsif (defined $in_diff && /^\+\+\+ (\S+)/) {
233 $in_diff = index_old_diff_fn($tg, \%seen, $in_diff, $1);
234 } elsif ($in_diff && s/^\+//) { # diff added
235 index_text_inc($tg, $_, 'XDFB');
236 } elsif ($in_diff && s/^-//) { # diff removed
237 index_text_inc($tg, $_, 'XDFA');
238 } elsif (m!^index ([a-f0-9]+)\.\.([a-f0-9]+)!) {
239 my ($ba, $bb) = ($1, $2);
240 index_git_blob_id($doc, 'XDFPRE', $ba);
241 index_git_blob_id($doc, 'XDFPOST', $bb);
243 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*$/) {
244 # traditional diff w/o -p
245 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*(\S+.*)$/) {
246 # hunk header context
247 index_text_inc($tg, $1, 'XDFHH');
248 # ignore the following lines:
249 } elsif (/^(?:dis)similarity index/) {
250 } elsif (/^(?:old|new) mode/) {
251 } elsif (/^(?:deleted|new) file mode/) {
252 } elsif (/^(?:copy|rename) (?:from|to) /) {
253 } elsif (/^(?:dis)?similarity index /) {
254 } elsif (/^\\ No newline at end of file/) {
255 } elsif (/^Binary files .* differ/) {
259 warn "non-diff line: $_\n" if DEBUG && $_ ne '';
265 sub index_body ($$$) {
266 my ($tg, $lines, $doc) = @_;
267 my $txt = join("\n", @$lines);
268 $tg->index_text($txt, !!$doc, $doc ? 'XNQ' : 'XQUOT');
269 $tg->increase_termpos;
270 # does it look like a diff?
271 if ($doc && $txt =~ /^(?:diff|---|\+\+\+) /ms) {
273 index_diff($tg, $lines, $doc);
279 my ($self, $mime, $bytes, $num, $blob) = @_; # mime = Email::MIME object
280 my $db = $self->{xdb};
282 my ($doc_id, $old_tid);
283 my $mid = mid_clean(mid_mime($mime));
286 die 'Message-ID too long' if length($mid) > MAX_MID_SIZE;
287 my $smsg = $self->lookup_message($mid);
289 # convert a ghost to a regular message
290 # it will also clobber any existing regular message
291 $doc_id = $smsg->{doc_id};
292 $old_tid = $smsg->thread_id;
294 $smsg = PublicInbox::SearchMsg->new($mime);
295 my $doc = $smsg->{doc};
296 $doc->add_term('XMID' . $mid);
298 my $subj = $smsg->subject;
300 my $path = $self->subject_path($subj);
301 $doc->add_term('XPATH' . id_compress($path));
304 add_values($smsg, $bytes, $num);
306 my $tg = $self->term_generator;
308 $tg->set_document($doc);
309 $tg->index_text($subj, 1, 'S') if $subj;
310 $tg->increase_termpos;
312 index_users($tg, $smsg);
314 msg_iter($mime, sub {
315 my ($part, $depth, @idx) = @{$_[0]};
316 my $ct = $part->content_type || 'text/plain';
317 my $fn = $part->filename;
318 if (defined $fn && $fn ne '') {
319 $tg->index_text($fn, 1, 'XFN');
322 return if $ct =~ m!\btext/x?html\b!i;
324 my $s = eval { $part->body_str };
326 if ($ct =~ m!\btext/plain\b!i) {
327 # Try to assume UTF-8 because Alpine
328 # seems to do wacky things and set
330 $part->charset_set('UTF-8');
331 $s = eval { $part->body_str };
332 $s = $part->body if $@;
335 defined $s or return;
338 my $body = $part->body;
339 my @lines = split(/\n/, $body);
340 while (defined(my $l = shift @lines)) {
342 index_body($tg, \@orig, $doc) if @orig;
345 index_body($tg, \@quot, 0) if @quot;
349 index_body($tg, \@quot, 0) if @quot;
350 index_body($tg, \@orig, $doc) if @orig;
353 link_message($self, $smsg, $old_tid);
354 $tg->index_text($mid, 1, 'XM');
355 $doc->set_data($smsg->to_doc_data($blob));
357 if (my $altid = $self->{-altid}) {
358 foreach my $alt (@$altid) {
359 my $id = $alt->mid2alt($mid);
360 next unless defined $id;
361 $doc->add_term($alt->{xprefix} . $id);
364 if (defined $doc_id) {
365 $db->replace_document($doc_id, $doc);
367 $doc_id = $db->add_document($doc);
372 warn "failed to index message <$mid>: $@\n";
378 # returns deleted doc_id on success, undef on missing
380 my ($self, $mid) = @_;
381 my $db = $self->{xdb};
383 $mid = mid_clean($mid);
386 my ($head, $tail) = $self->find_doc_ids('XMID' . $mid);
387 if ($head->equal($tail)) {
388 warn "cannot remove non-existent <$mid>\n";
390 for (; $head != $tail; $head->inc) {
391 my $docid = $head->get_docid;
392 $db->delete_document($docid);
397 warn "failed to remove message <$mid>: $@\n";
403 sub term_generator { # write-only
406 my $tg = $self->{term_generator};
409 $tg = Search::Xapian::TermGenerator->new;
410 $tg->set_stemmer($self->stemmer);
412 $self->{term_generator} = $tg;
415 # increments last_thread_id counter
416 # returns a 64-bit integer represented as a decimal string
419 my $db = $self->{xdb};
420 my $last_thread_id = int($db->get_metadata('last_thread_id') || 0);
422 $db->set_metadata('last_thread_id', ++$last_thread_id);
428 my ($self, $smsg, $old_tid) = @_;
429 my $doc = $smsg->{doc};
430 my $mid = $smsg->mid;
431 my $mime = $smsg->{mime};
432 my $hdr = $mime->header_obj;
434 # last References should be IRT, but some mail clients do things
435 # out of order, so trust IRT over References iff IRT exists
436 my @refs = (($hdr->header_raw('References') || '') =~ /<([^>]+)>/g);
437 push(@refs, (($hdr->header_raw('In-Reply-To') || '') =~ /<([^>]+)>/g));
441 my %uniq = ($mid => 1);
442 my @orig_refs = @refs;
445 # prevent circular references via References: here:
446 foreach my $ref (@orig_refs) {
447 if (length($ref) > MAX_MID_SIZE) {
448 warn "References: <$ref> too long, ignoring\n";
457 $smsg->{references} = '<'.join('> <', @refs).'>';
459 # first ref *should* be the thread root,
460 # but we can never trust clients to do the right thing
461 my $ref = shift @refs;
462 $tid = $self->_resolve_mid_to_tid($ref);
463 $self->merge_threads($tid, $old_tid) if defined $old_tid;
465 # the rest of the refs should point to this tid:
466 foreach $ref (@refs) {
467 my $ptid = $self->_resolve_mid_to_tid($ref);
468 merge_threads($self, $tid, $ptid);
471 $tid = defined $old_tid ? $old_tid : $self->next_thread_id;
473 $doc->add_term('G' . $tid);
477 my ($self, $mime, $bytes, $num, $blob) = @_;
478 $self->add_message($mime, $bytes, $num, $blob);
481 sub index_git_blob_id {
482 my ($doc, $pfx, $objid) = @_;
484 my $len = length($objid);
485 for (my $len = length($objid); $len >= 7; ) {
486 $doc->add_term($pfx.$objid);
487 $objid = substr($objid, 0, --$len);
492 my ($self, $mime) = @_;
493 my $mid = eval { mid_clean(mid_mime($mime)) };
494 $self->remove_message($mid) if defined $mid;
498 my ($self, $mime) = @_;
499 my $mid = mid_clean(mid_mime($mime));
500 my $mm = $self->{mm};
501 my $num = $mm->mid_insert($mid);
503 # fallback to num_for since filters like RubyLang set the number
504 defined $num ? $num : $mm->num_for($mid);
508 my ($self, $mime) = @_;
509 $self->{mm}->mid_delete(mid_clean(mid_mime($mime)));
513 my ($self, $mime, $bytes, $blob) = @_;
514 my $num = $self->{mm}->num_for(mid_clean(mid_mime($mime)));
515 index_blob($self, $mime, $bytes, $num, $blob);
519 my ($self, $mime) = @_;
520 $self->{mm}->mid_delete(mid_clean(mid_mime($mime)));
521 unindex_blob($self, $mime);
525 my ($self, $mime, $bytes, $blob) = @_;
526 my $num = index_mm($self, $mime);
527 index_blob($self, $mime, $bytes, $num, $blob);
531 my ($self, $mime) = @_;
532 unindex_blob($self, $mime);
533 unindex_mm($self, $mime);
537 my ($git, $blob, $sizeref) = @_;
539 my $str = $git->cat_file($blob, $sizeref);
540 # fixup bugs from import:
541 $$str =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
542 PublicInbox::MIME->new($str);
548 my ($self, $opts) = @_;
549 with_umask($self, sub { $self->_index_sync($opts) });
552 sub batch_adjust ($$$$) {
553 my ($max, $bytes, $batch_cb, $latest) = @_;
557 $batch_cb->($latest, 1);
563 my ($self, $log, $add_cb, $del_cb, $batch_cb) = @_;
564 my $hex = '[a-f0-9]';
565 my $h40 = $hex .'{40}';
566 my $addmsg = qr!^:000000 100644 \S+ ($h40) A\t${hex}{2}/${hex}{38}$!;
567 my $delmsg = qr!^:100644 000000 ($h40) \S+ D\t${hex}{2}/${hex}{38}$!;
568 my $git = $self->{git};
571 my $max = BATCH_BYTES;
574 while (defined($line = <$log>)) {
575 if ($line =~ /$addmsg/o) {
577 my $mime = do_cat_mail($git, $blob, \$bytes) or next;
578 batch_adjust(\$max, $bytes, $batch_cb, $latest);
579 $add_cb->($self, $mime, $bytes, $blob);
580 } elsif ($line =~ /$delmsg/o) {
582 my $mime = do_cat_mail($git, $blob, \$bytes) or next;
583 batch_adjust(\$max, $bytes, $batch_cb, $latest);
584 $del_cb->($self, $mime);
585 } elsif ($line =~ /^commit ($h40)/o) {
589 $batch_cb->($latest, 0);
594 $self->{mm} ||= eval {
595 require PublicInbox::Msgmap;
596 my $msgmap_path = $self->{msgmap_path};
597 if (defined $msgmap_path) { # v2
598 PublicInbox::Msgmap->new_file($msgmap_path, 1);
600 PublicInbox::Msgmap->new($self->{mainrepo}, 1);
606 my ($self, $range) = @_;
607 $self->{git}->popen(qw/log --reverse --no-notes --no-color
608 --raw -r --no-abbrev/, $range);
611 # indexes all unindexed messages
613 my ($self, $opts) = @_;
614 my $tip = $opts->{ref} || 'HEAD';
615 my $reindex = $opts->{reindex};
616 my ($mkey, $last_commit, $lx, $xlog);
617 $self->{git}->batch_prepare;
618 my $xdb = _xdb_acquire($self);
619 $xdb->begin_transaction;
622 $mkey = 'last_commit';
623 $last_commit = $xdb->get_metadata('last_commit');
627 $mkey = undef if $last_commit ne '';
629 $xdb->cancel_transaction;
630 $xdb = _xdb_release($self);
632 # ensure we leak no FDs to "git log"
633 my $range = $lx eq '' ? $tip : "$lx..$tip";
634 $xlog = _git_log($self, $range);
636 $xdb = _xdb_acquire($self);
637 $xdb->begin_transaction;
638 } while ($xdb->get_metadata('last_commit') ne $last_commit);
640 my $mm = _msgmap_init($self);
641 my $dbh = $mm->{dbh} if $mm;
644 my ($commit, $more) = @_;
646 $mm->last_commit($commit) if $commit;
650 $xdb->set_metadata($mkey, $commit) if $mkey && $commit;
651 $xdb->commit_transaction;
652 $xdb = _xdb_release($self);
654 # let another process do some work... <
657 $xdb = _xdb_acquire($self);
658 $xdb->begin_transaction;
660 $dbh->begin_work if $dbh;
666 my $lm = $mm->last_commit || '';
668 # Common case is the indexes are synced,
669 # we only need to run git-log once:
670 rlog($self, $xlog, *index_both, *unindex_both, $cb);
672 # Uncommon case, msgmap and xapian are out-of-sync
673 # do not care for performance (but git is fast :>)
674 # This happens if we have to reindex Xapian since
675 # msgmap is a frozen format and our Xapian format
677 my $r = $lm eq '' ? $tip : "$lm..$tip";
679 # first, ensure msgmap is up-to-date:
680 my $mkey_prev = $mkey;
681 $mkey = undef; # ignore xapian, for now
682 my $mlog = _git_log($self, $r);
684 rlog($self, $mlog, *index_mm, *unindex_mm, $cb);
685 $mm_only = $mlog = undef;
687 # now deal with Xapian
690 rlog($self, $xlog, *index_mm2, *unindex_mm2, $cb);
693 # user didn't install DBD::SQLite and DBI
694 rlog($self, $xlog, *index_blob, *unindex_blob, $cb);
698 # this will create a ghost as necessary
699 sub _resolve_mid_to_tid {
700 my ($self, $mid) = @_;
702 my $smsg = $self->lookup_message($mid) || $self->create_ghost($mid);
707 my ($self, $mid) = @_;
709 my $tid = $self->next_thread_id;
710 my $doc = Search::Xapian::Document->new;
711 $doc->add_term('XMID' . $mid);
712 $doc->add_term('G' . $tid);
713 $doc->add_term('T' . 'ghost');
715 my $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
716 $self->{xdb}->add_document($doc);
722 my ($self, $winner_tid, $loser_tid) = @_;
723 return if $winner_tid == $loser_tid;
724 my ($head, $tail) = $self->find_doc_ids('G' . $loser_tid);
725 my $db = $self->{xdb};
727 for (; $head != $tail; $head->inc) {
728 my $docid = $head->get_docid;
729 my $doc = $db->get_document($docid);
730 $doc->remove_term('G' . $loser_tid);
731 $doc->add_term('G' . $winner_tid);
732 $db->replace_document($docid, $doc);
736 sub _read_git_config_perm {
738 my @cmd = qw(config);
739 if ($self->{version} == 2) {
740 push @cmd, "--file=$self->{mainrepo}/inbox-config";
742 my $fh = $self->{git}->popen(@cmd, 'core.sharedRepository');
745 chomp $perm if defined $perm;
749 sub _git_config_perm {
751 my $perm = scalar @_ ? $_[0] : _read_git_config_perm($self);
752 return PERM_GROUP if (!defined($perm) || $perm eq '');
753 return PERM_UMASK if ($perm eq 'umask');
754 return PERM_GROUP if ($perm eq 'group');
755 if ($perm =~ /\A(?:all|world|everybody)\z/) {
756 return PERM_EVERYBODY;
758 return PERM_GROUP if ($perm =~ /\A(?:true|yes|on|1)\z/);
759 return PERM_UMASK if ($perm =~ /\A(?:false|no|off|0)\z/);
762 return PERM_UMASK if ($i == PERM_UMASK);
763 return PERM_GROUP if ($i == OLD_PERM_GROUP);
764 return PERM_EVERYBODY if ($i == OLD_PERM_EVERYBODY);
766 if (($i & 0600) != 0600) {
767 die "core.sharedRepository mode invalid: ".
768 sprintf('%.3o', $i) . "\nOwner must have permissions\n";
774 my ($perm) = @_; # _git_config_perm return value
776 return umask if $rv == 0;
778 # set +x bit if +r or +w were set
779 $rv |= 0100 if ($rv & 0600);
780 $rv |= 0010 if ($rv & 0060);
781 $rv |= 0001 if ($rv & 0006);
786 my ($self, $cb) = @_;
787 my $old = umask $self->{umask};
788 my $rv = eval { $cb->() };
796 # order matters for unlocking
797 $_[0]->{xdb} = undef;
798 $_[0]->{lockfh} = undef;