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 base qw(PublicInbox::Search);
15 use PublicInbox::MID qw/mid_clean id_compress mid_mime mids references/;
16 use PublicInbox::MsgIter;
18 use POSIX qw(strftime);
19 require PublicInbox::Git;
22 MAX_MID_SIZE => 244, # max term size - 1 in Xapian
25 OLD_PERM_EVERYBODY => 2,
27 PERM_EVERYBODY => 0664,
28 BATCH_BYTES => 1_000_000,
29 DEBUG => !!$ENV{DEBUG},
44 return $s unless ($s =~ /\A"(.*)"\z/);
46 $s =~ s/\\([abfnrtv])/$GIT_ESC{$1}/g;
47 $s =~ s/\\([0-7]{1,3})/chr(oct($1))/ge;
52 my ($class, $ibx, $creat, $part) = @_;
53 my $mainrepo = $ibx; # for "public-inbox-index" w/o entry in config
54 my $git_dir = $mainrepo;
58 $mainrepo = $ibx->{mainrepo};
59 $altid = $ibx->{altid};
60 $version = $ibx->{version} || 1;
62 require PublicInbox::AltId;
64 PublicInbox::AltId->new($ibx, $_);
69 $git = PublicInbox::Git->new($git_dir); # v1 only
71 require Search::Xapian::WritableDatabase;
73 mainrepo => $mainrepo,
78 my $perm = $self->_git_config_perm;
79 my $umask = _umask_for($perm);
80 $self->{umask} = $umask;
82 $self->{lock_path} = "$mainrepo/ssoma.lock";
83 } elsif ($version == 2) {
84 defined $part or die "partition is required for v2\n";
85 # partition is a number or "all"
86 $self->{partition} = $part;
87 $self->{lock_path} = undef;
88 $self->{msgmap_path} = "$mainrepo/msgmap.sqlite3";
90 die "unsupported inbox version=$version\n";
92 $self->{creat} = ($creat || 0) == 1;
98 my $xdb = delete $self->{xdb} or croak 'not acquired';
100 _lock_release($self) if $self->{creat};
106 croak 'already acquired' if $self->{xdb};
107 my $dir = $self->xdir;
108 my $flag = Search::Xapian::DB_OPEN;
109 if ($self->{creat}) {
111 _lock_acquire($self);
112 File::Path::mkpath($dir);
113 $flag = Search::Xapian::DB_CREATE_OR_OPEN;
115 $self->{xdb} = Search::Xapian::WritableDatabase->new($dir, $flag);
118 # we only acquire the flock if creating or reindexing;
119 # PublicInbox::Import already has the lock on its own.
122 croak 'already locked' if $self->{lockfh};
123 my $lock_path = $self->{lock_path} or return;
124 sysopen(my $lockfh, $lock_path, O_WRONLY|O_CREAT) or
125 die "failed to open lock $lock_path: $!\n";
126 flock($lockfh, LOCK_EX) or die "lock failed: $!\n";
127 $self->{lockfh} = $lockfh;
132 return unless $self->{lock_path};
133 my $lockfh = delete $self->{lockfh} or croak 'not locked';
134 flock($lockfh, LOCK_UN) or die "unlock failed: $!\n";
135 close $lockfh or die "close failed: $!\n";
139 my ($doc, $col, $num) = @_;
140 $num = Search::Xapian::sortable_serialise($num);
141 $doc->add_value($col, $num);
144 sub add_values ($$) {
145 my ($doc, $values) = @_;
147 my $ts = $values->[PublicInbox::Search::TS];
148 add_val($doc, PublicInbox::Search::TS, $ts);
150 my $num = $values->[PublicInbox::Search::NUM];
151 defined($num) and add_val($doc, PublicInbox::Search::NUM, $num);
153 my $bytes = $values->[PublicInbox::Search::BYTES];
154 defined($bytes) and add_val($doc, PublicInbox::Search::BYTES, $bytes);
156 my $lines = $values->[PublicInbox::Search::LINES];
157 add_val($doc, PublicInbox::Search::LINES, $lines);
159 my $yyyymmdd = strftime('%Y%m%d', gmtime($ts));
160 add_val($doc, PublicInbox::Search::YYYYMMDD, $yyyymmdd);
163 sub index_users ($$) {
164 my ($tg, $smsg) = @_;
166 my $from = $smsg->from;
170 $tg->index_text($from, 1, 'A'); # A - author
171 $tg->increase_termpos;
172 $tg->index_text($to, 1, 'XTO') if $to ne '';
173 $tg->increase_termpos;
174 $tg->index_text($cc, 1, 'XCC') if $cc ne '';
175 $tg->increase_termpos;
178 sub index_text_inc ($$$) {
179 my ($tg, $text, $pfx) = @_;
180 $tg->index_text($text, 1, $pfx);
181 $tg->increase_termpos;
184 sub index_old_diff_fn {
185 my ($tg, $seen, $fa, $fb) = @_;
187 # no renames or space support for traditional diffs,
188 # find the number of leading common paths to strip:
189 my @fa = split('/', $fa);
190 my @fb = split('/', $fb);
191 while (scalar(@fa) && scalar(@fb)) {
192 $fa = join('/', @fa);
193 $fb = join('/', @fb);
195 index_text_inc($tg, $fa,'XDFN') unless $seen->{$fa}++;
204 sub index_diff ($$$) {
205 my ($tg, $lines, $doc) = @_;
209 if ($in_diff && s/^ //) { # diff context
210 index_text_inc($tg, $_, 'XDFCTX');
211 } elsif (/^-- $/) { # email signature begins
213 } elsif (m!^diff --git ("?a/.+) ("?b/.+)\z!) {
214 my ($fa, $fb) = ($1, $2);
215 my $fn = (split('/', git_unquote($fa), 2))[1];
216 index_text_inc($tg, $fn, 'XDFN') unless $seen{$fn}++;
217 $fn = (split('/', git_unquote($fb), 2))[1];
218 index_text_inc($tg, $fn, 'XDFN') unless $seen{$fn}++;
221 } elsif (m/^diff -(.+) (\S+) (\S+)$/) {
222 my ($opt, $fa, $fb) = ($1, $2, $3);
223 # only support unified:
224 next unless $opt =~ /[uU]/;
225 $in_diff = index_old_diff_fn($tg, \%seen, $fa, $fb);
226 } elsif (m!^--- ("?a/.+)!) {
227 my $fn = (split('/', git_unquote($1), 2))[1];
228 index_text_inc($tg, $fn, 'XDFN') unless $seen{$fn}++;
230 } elsif (m!^\+\+\+ ("?b/.+)!) {
231 my $fn = (split('/', git_unquote($1), 2))[1];
232 index_text_inc($tg, $fn, 'XDFN') unless $seen{$fn}++;
234 } elsif (/^--- (\S+)/) {
236 } elsif (defined $in_diff && /^\+\+\+ (\S+)/) {
237 $in_diff = index_old_diff_fn($tg, \%seen, $in_diff, $1);
238 } elsif ($in_diff && s/^\+//) { # diff added
239 index_text_inc($tg, $_, 'XDFB');
240 } elsif ($in_diff && s/^-//) { # diff removed
241 index_text_inc($tg, $_, 'XDFA');
242 } elsif (m!^index ([a-f0-9]+)\.\.([a-f0-9]+)!) {
243 my ($ba, $bb) = ($1, $2);
244 index_git_blob_id($doc, 'XDFPRE', $ba);
245 index_git_blob_id($doc, 'XDFPOST', $bb);
247 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*$/) {
248 # traditional diff w/o -p
249 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*(\S+.*)$/) {
250 # hunk header context
251 index_text_inc($tg, $1, 'XDFHH');
252 # ignore the following lines:
253 } elsif (/^(?:dis)similarity index/) {
254 } elsif (/^(?:old|new) mode/) {
255 } elsif (/^(?:deleted|new) file mode/) {
256 } elsif (/^(?:copy|rename) (?:from|to) /) {
257 } elsif (/^(?:dis)?similarity index /) {
258 } elsif (/^\\ No newline at end of file/) {
259 } elsif (/^Binary files .* differ/) {
263 warn "non-diff line: $_\n" if DEBUG && $_ ne '';
269 sub index_body ($$$) {
270 my ($tg, $lines, $doc) = @_;
271 my $txt = join("\n", @$lines);
272 $tg->index_text($txt, !!$doc, $doc ? 'XNQ' : 'XQUOT');
273 $tg->increase_termpos;
274 # does it look like a diff?
275 if ($doc && $txt =~ /^(?:diff|---|\+\+\+) /ms) {
277 index_diff($tg, $lines, $doc);
283 my ($self, $mime, $bytes, $num, $blob) = @_; # mime = Email::MIME object
284 my $db = $self->{xdb};
286 my ($doc_id, $old_tid);
287 my @mids = mid_mime($mime);
289 warn "Multi-MID: ( ",join(' | ', @mids)," )\n";
291 my $mid = mid_clean($mids[0]);
292 my $skel = $self->{skeleton};
295 die 'Message-ID too long' if length($mid) > MAX_MID_SIZE;
296 my $smsg = $self->lookup_message($mid);
298 # convert a ghost to a regular message
299 # it will also clobber any existing regular message
300 $doc_id = $smsg->{doc_id};
301 $old_tid = $smsg->thread_id unless $skel;
303 $smsg = PublicInbox::SearchMsg->new($mime);
304 my $doc = $smsg->{doc};
305 $doc->add_term('XMID' . $mid);
307 my $subj = $smsg->subject;
310 $xpath = $self->subject_path($subj);
311 $xpath = id_compress($xpath);
312 $doc->add_term('XPATH' . $xpath);
315 my $lines = $mime->body_raw =~ tr!\n!\n!;
316 my @values = ($smsg->ts, $num, $bytes, $lines);
317 add_values($doc, \@values);
319 my $tg = $self->term_generator;
321 $tg->set_document($doc);
322 $tg->index_text($subj, 1, 'S') if $subj;
323 $tg->increase_termpos;
325 index_users($tg, $smsg);
327 msg_iter($mime, sub {
328 my ($part, $depth, @idx) = @{$_[0]};
329 my $ct = $part->content_type || 'text/plain';
330 my $fn = $part->filename;
331 if (defined $fn && $fn ne '') {
332 $tg->index_text($fn, 1, 'XFN');
335 return if $ct =~ m!\btext/x?html\b!i;
337 my $s = eval { $part->body_str };
339 if ($ct =~ m!\btext/plain\b!i) {
340 # Try to assume UTF-8 because Alpine
341 # seems to do wacky things and set
343 $part->charset_set('UTF-8');
344 $s = eval { $part->body_str };
345 $s = $part->body if $@;
348 defined $s or return;
351 my $body = $part->body;
352 my @lines = split(/\n/, $body);
353 while (defined(my $l = shift @lines)) {
355 index_body($tg, \@orig, $doc) if @orig;
358 index_body($tg, \@quot, 0) if @quot;
362 index_body($tg, \@quot, 0) if @quot;
363 index_body($tg, \@orig, $doc) if @orig;
366 # populates smsg->references for smsg->to_doc_data
367 my $refs = parse_references($smsg);
368 my $data = $smsg->to_doc_data($blob);
370 push @values, $mid, $xpath, $data;
371 $skel->index_skeleton(\@values);
373 link_message($self, $smsg, $refs, $old_tid);
375 $tg->index_text($mid, 1, 'XM');
376 $doc->set_data($data);
378 if (my $altid = $self->{-altid}) {
379 foreach my $alt (@$altid) {
380 my $id = $alt->mid2alt($mid);
381 next unless defined $id;
382 $doc->add_term($alt->{xprefix} . $id);
385 if (defined $doc_id) {
386 $db->replace_document($doc_id, $doc);
388 $doc_id = $db->add_document($doc);
393 warn "failed to index message <$mid>: $@\n";
399 # returns deleted doc_id on success, undef on missing
401 my ($self, $mid) = @_;
402 my $db = $self->{xdb};
404 $mid = mid_clean($mid);
407 my ($head, $tail) = $self->find_doc_ids('XMID' . $mid);
408 if ($head->equal($tail)) {
409 warn "cannot remove non-existent <$mid>\n";
411 for (; $head != $tail; $head->inc) {
412 my $docid = $head->get_docid;
413 $db->delete_document($docid);
418 warn "failed to remove message <$mid>: $@\n";
424 sub term_generator { # write-only
427 my $tg = $self->{term_generator};
430 $tg = Search::Xapian::TermGenerator->new;
431 $tg->set_stemmer($self->stemmer);
433 $self->{term_generator} = $tg;
436 # increments last_thread_id counter
437 # returns a 64-bit integer represented as a decimal string
440 my $db = $self->{xdb};
441 my $last_thread_id = int($db->get_metadata('last_thread_id') || 0);
443 $db->set_metadata('last_thread_id', ++$last_thread_id);
448 sub parse_references ($) {
450 my $mime = $smsg->{mime};
451 my $hdr = $mime->header_obj;
452 my $refs = references($hdr);
453 return $refs if scalar(@$refs) == 0;
455 # prevent circular references via References here:
456 my %mids = map { $_ => 1 } @{mids($hdr)};
458 foreach my $ref (@$refs) {
459 # FIXME: this is an archive-prevention vector like X-No-Archive
460 if (length($ref) > MAX_MID_SIZE) {
461 warn "References: <$ref> too long, ignoring\n";
466 $smsg->{references} = '<'.join('> <', @keep).'>' if @keep;
471 my ($self, $smsg, $refs, $old_tid) = @_;
476 # first ref *should* be the thread root,
477 # but we can never trust clients to do the right thing
478 my $ref = shift @$refs;
479 $tid = $self->_resolve_mid_to_tid($ref);
480 $self->merge_threads($tid, $old_tid) if defined $old_tid;
482 # the rest of the refs should point to this tid:
483 foreach $ref (@$refs) {
484 my $ptid = $self->_resolve_mid_to_tid($ref);
485 merge_threads($self, $tid, $ptid);
488 $tid = defined $old_tid ? $old_tid : $self->next_thread_id;
490 $smsg->{doc}->add_term('G' . $tid);
493 sub index_git_blob_id {
494 my ($doc, $pfx, $objid) = @_;
496 my $len = length($objid);
497 for (my $len = length($objid); $len >= 7; ) {
498 $doc->add_term($pfx.$objid);
499 $objid = substr($objid, 0, --$len);
504 my ($self, $mime) = @_;
505 my $mid = eval { mid_clean(mid_mime($mime)) };
506 $self->remove_message($mid) if defined $mid;
510 my ($self, $mime) = @_;
511 my $mid = mid_clean(mid_mime($mime));
512 my $mm = $self->{mm};
513 my $num = $mm->mid_insert($mid);
514 return $num if defined $num;
516 # fallback to num_for since filters like RubyLang set the number
521 my ($self, $mime) = @_;
522 $self->{mm}->mid_delete(mid_clean(mid_mime($mime)));
526 my ($self, $mime, $bytes, $blob) = @_;
527 my $num = $self->{mm}->num_for(mid_clean(mid_mime($mime)));
528 add_message($self, $mime, $bytes, $num, $blob);
532 my ($self, $mime) = @_;
533 $self->{mm}->mid_delete(mid_clean(mid_mime($mime)));
534 unindex_blob($self, $mime);
538 my ($self, $mime, $bytes, $blob) = @_;
539 my $num = index_mm($self, $mime);
540 add_message($self, $mime, $bytes, $num, $blob);
544 my ($self, $mime) = @_;
545 unindex_blob($self, $mime);
546 unindex_mm($self, $mime);
550 my ($git, $blob, $sizeref) = @_;
552 my $str = $git->cat_file($blob, $sizeref);
553 # fixup bugs from import:
554 $$str =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
555 PublicInbox::MIME->new($str);
561 my ($self, $opts) = @_;
562 with_umask($self, sub { $self->_index_sync($opts) });
565 sub batch_adjust ($$$$) {
566 my ($max, $bytes, $batch_cb, $latest) = @_;
570 $batch_cb->($latest, 1);
576 my ($self, $log, $add_cb, $del_cb, $batch_cb) = @_;
577 my $hex = '[a-f0-9]';
578 my $h40 = $hex .'{40}';
579 my $addmsg = qr!^:000000 100644 \S+ ($h40) A\t${hex}{2}/${hex}{38}$!;
580 my $delmsg = qr!^:100644 000000 ($h40) \S+ D\t${hex}{2}/${hex}{38}$!;
581 my $git = $self->{git};
584 my $max = BATCH_BYTES;
587 while (defined($line = <$log>)) {
588 if ($line =~ /$addmsg/o) {
590 my $mime = do_cat_mail($git, $blob, \$bytes) or next;
591 batch_adjust(\$max, $bytes, $batch_cb, $latest);
592 $add_cb->($self, $mime, $bytes, $blob);
593 } elsif ($line =~ /$delmsg/o) {
595 my $mime = do_cat_mail($git, $blob, \$bytes) or next;
596 batch_adjust(\$max, $bytes, $batch_cb, $latest);
597 $del_cb->($self, $mime);
598 } elsif ($line =~ /^commit ($h40)/o) {
602 $batch_cb->($latest, 0);
607 $self->{mm} ||= eval {
608 require PublicInbox::Msgmap;
609 my $msgmap_path = $self->{msgmap_path};
610 if (defined $msgmap_path) { # v2
611 PublicInbox::Msgmap->new_file($msgmap_path, 1);
613 PublicInbox::Msgmap->new($self->{mainrepo}, 1);
619 my ($self, $range) = @_;
620 $self->{git}->popen(qw/log --reverse --no-notes --no-color
621 --raw -r --no-abbrev/, $range);
624 # indexes all unindexed messages
626 my ($self, $opts) = @_;
627 my $tip = $opts->{ref} || 'HEAD';
628 my $reindex = $opts->{reindex};
629 my ($mkey, $last_commit, $lx, $xlog);
630 $self->{git}->batch_prepare;
631 my $xdb = _xdb_acquire($self);
632 $xdb->begin_transaction;
635 $mkey = 'last_commit';
636 $last_commit = $xdb->get_metadata('last_commit');
640 $mkey = undef if $last_commit ne '';
642 $xdb->cancel_transaction;
643 $xdb = _xdb_release($self);
645 # ensure we leak no FDs to "git log"
646 my $range = $lx eq '' ? $tip : "$lx..$tip";
647 $xlog = _git_log($self, $range);
649 $xdb = _xdb_acquire($self);
650 $xdb->begin_transaction;
651 } while ($xdb->get_metadata('last_commit') ne $last_commit);
653 my $mm = _msgmap_init($self);
654 my $dbh = $mm->{dbh} if $mm;
657 my ($commit, $more) = @_;
659 $mm->last_commit($commit) if $commit;
663 $xdb->set_metadata($mkey, $commit) if $mkey && $commit;
664 $xdb->commit_transaction;
665 $xdb = _xdb_release($self);
667 # let another process do some work... <
670 $xdb = _xdb_acquire($self);
671 $xdb->begin_transaction;
673 $dbh->begin_work if $dbh;
679 my $lm = $mm->last_commit || '';
681 # Common case is the indexes are synced,
682 # we only need to run git-log once:
683 rlog($self, $xlog, *index_both, *unindex_both, $cb);
685 # Uncommon case, msgmap and xapian are out-of-sync
686 # do not care for performance (but git is fast :>)
687 # This happens if we have to reindex Xapian since
688 # msgmap is a frozen format and our Xapian format
690 my $r = $lm eq '' ? $tip : "$lm..$tip";
692 # first, ensure msgmap is up-to-date:
693 my $mkey_prev = $mkey;
694 $mkey = undef; # ignore xapian, for now
695 my $mlog = _git_log($self, $r);
697 rlog($self, $mlog, *index_mm, *unindex_mm, $cb);
698 $mm_only = $mlog = undef;
700 # now deal with Xapian
703 rlog($self, $xlog, *index_mm2, *unindex_mm2, $cb);
706 # user didn't install DBD::SQLite and DBI
707 rlog($self, $xlog, *add_message, *unindex_blob, $cb);
711 # this will create a ghost as necessary
712 sub _resolve_mid_to_tid {
713 my ($self, $mid) = @_;
715 my $smsg = $self->lookup_message($mid) || $self->create_ghost($mid);
720 my ($self, $mid) = @_;
722 my $tid = $self->next_thread_id;
723 my $doc = Search::Xapian::Document->new;
724 $doc->add_term('XMID' . $mid);
725 $doc->add_term('G' . $tid);
726 $doc->add_term('T' . 'ghost');
728 my $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
729 $self->{xdb}->add_document($doc);
735 my ($self, $winner_tid, $loser_tid) = @_;
736 return if $winner_tid == $loser_tid;
737 my $db = $self->{xdb};
739 my $batch_size = 1000; # don't let @ids grow too large to avoid OOM
741 my ($head, $tail) = $self->find_doc_ids('G' . $loser_tid);
742 return if $head == $tail;
744 for (; $head != $tail && @ids < $batch_size; $head->inc) {
745 push @ids, $head->get_docid;
747 foreach my $docid (@ids) {
748 my $doc = $db->get_document($docid);
749 $doc->remove_term('G' . $loser_tid);
750 $doc->add_term('G' . $winner_tid);
751 $db->replace_document($docid, $doc);
756 sub _read_git_config_perm {
758 my @cmd = qw(config);
759 if ($self->{version} == 2) {
760 push @cmd, "--file=$self->{mainrepo}/inbox-config";
762 my $fh = $self->{git}->popen(@cmd, 'core.sharedRepository');
765 chomp $perm if defined $perm;
769 sub _git_config_perm {
771 my $perm = scalar @_ ? $_[0] : _read_git_config_perm($self);
772 return PERM_GROUP if (!defined($perm) || $perm eq '');
773 return PERM_UMASK if ($perm eq 'umask');
774 return PERM_GROUP if ($perm eq 'group');
775 if ($perm =~ /\A(?:all|world|everybody)\z/) {
776 return PERM_EVERYBODY;
778 return PERM_GROUP if ($perm =~ /\A(?:true|yes|on|1)\z/);
779 return PERM_UMASK if ($perm =~ /\A(?:false|no|off|0)\z/);
782 return PERM_UMASK if ($i == PERM_UMASK);
783 return PERM_GROUP if ($i == OLD_PERM_GROUP);
784 return PERM_EVERYBODY if ($i == OLD_PERM_EVERYBODY);
786 if (($i & 0600) != 0600) {
787 die "core.sharedRepository mode invalid: ".
788 sprintf('%.3o', $i) . "\nOwner must have permissions\n";
794 my ($perm) = @_; # _git_config_perm return value
796 return umask if $rv == 0;
798 # set +x bit if +r or +w were set
799 $rv |= 0100 if ($rv & 0600);
800 $rv |= 0010 if ($rv & 0060);
801 $rv |= 0001 if ($rv & 0006);
806 my ($self, $cb) = @_;
807 my $old = umask $self->{umask};
808 my $rv = eval { $cb->() };
816 # order matters for unlocking
817 $_[0]->{xdb} = undef;
818 $_[0]->{lockfh} = undef;
821 # remote_* subs are only used by SearchIdxPart and SearchIdxSkeleton
824 print { $self->{w} } "commit\n" or die "failed to write commit: $!";
829 my $pid = delete $self->{pid} or die "no process to wait on\n";
830 my $w = delete $self->{w} or die "no pipe to write to\n";
831 print $w "close\n" or die "failed to write to pid:$pid: $!\n";
832 close $w or die "failed to close pipe for pid:$pid: $!\n";
833 waitpid($pid, 0) == $pid or die "remote process did not finish";
834 $? == 0 or die ref($self)." pid:$pid exited with: $?";