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, $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('XMID' . $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, 'XM');
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 my ($head, $tail) = $self->find_doc_ids('XMID' . $mid);
370 if ($head->equal($tail)) {
371 warn "cannot remove non-existent <$mid>\n";
373 for (; $head != $tail; $head->inc) {
374 my $docid = $head->get_docid;
375 $db->delete_document($docid);
380 warn "failed to remove message <$mid>: $@\n";
386 sub term_generator { # write-only
389 my $tg = $self->{term_generator};
392 $tg = Search::Xapian::TermGenerator->new;
393 $tg->set_stemmer($self->stemmer);
395 $self->{term_generator} = $tg;
398 # increments last_thread_id counter
399 # returns a 64-bit integer represented as a decimal string
402 my $db = $self->{xdb};
403 my $last_thread_id = int($db->get_metadata('last_thread_id') || 0);
405 $db->set_metadata('last_thread_id', ++$last_thread_id);
411 my ($self, $smsg, $old_tid) = @_;
412 my $doc = $smsg->{doc};
413 my $mid = $smsg->mid;
414 my $mime = $smsg->{mime};
415 my $hdr = $mime->header_obj;
417 # last References should be IRT, but some mail clients do things
418 # out of order, so trust IRT over References iff IRT exists
419 my @refs = (($hdr->header_raw('References') || '') =~ /<([^>]+)>/g);
420 push(@refs, (($hdr->header_raw('In-Reply-To') || '') =~ /<([^>]+)>/g));
424 my %uniq = ($mid => 1);
425 my @orig_refs = @refs;
428 # prevent circular references via References: here:
429 foreach my $ref (@orig_refs) {
430 if (length($ref) > MAX_MID_SIZE) {
431 warn "References: <$ref> too long, ignoring\n";
440 $smsg->{references} = '<'.join('> <', @refs).'>';
442 # first ref *should* be the thread root,
443 # but we can never trust clients to do the right thing
444 my $ref = shift @refs;
445 $tid = $self->_resolve_mid_to_tid($ref);
446 $self->merge_threads($tid, $old_tid) if defined $old_tid;
448 # the rest of the refs should point to this tid:
449 foreach $ref (@refs) {
450 my $ptid = $self->_resolve_mid_to_tid($ref);
451 merge_threads($self, $tid, $ptid);
454 $tid = defined $old_tid ? $old_tid : $self->next_thread_id;
456 $doc->add_term('G' . $tid);
460 my ($self, $mime, $bytes, $num, $blob) = @_;
461 $self->add_message($mime, $bytes, $num, $blob);
464 sub index_git_blob_id {
465 my ($doc, $pfx, $objid) = @_;
467 my $len = length($objid);
468 for (my $len = length($objid); $len >= 7; ) {
469 $doc->add_term($pfx.$objid);
470 $objid = substr($objid, 0, --$len);
475 my ($self, $mime) = @_;
476 my $mid = eval { mid_clean(mid_mime($mime)) };
477 $self->remove_message($mid) if defined $mid;
481 my ($self, $mime) = @_;
482 my $mid = mid_clean(mid_mime($mime));
483 my $mm = $self->{mm};
484 my $num = $mm->mid_insert($mid);
486 # fallback to num_for since filters like RubyLang set the number
487 defined $num ? $num : $mm->num_for($mid);
491 my ($self, $mime) = @_;
492 $self->{mm}->mid_delete(mid_clean(mid_mime($mime)));
496 my ($self, $mime, $bytes, $blob) = @_;
497 my $num = $self->{mm}->num_for(mid_clean(mid_mime($mime)));
498 index_blob($self, $mime, $bytes, $num, $blob);
502 my ($self, $mime) = @_;
503 $self->{mm}->mid_delete(mid_clean(mid_mime($mime)));
504 unindex_blob($self, $mime);
508 my ($self, $mime, $bytes, $blob) = @_;
509 my $num = index_mm($self, $mime);
510 index_blob($self, $mime, $bytes, $num, $blob);
514 my ($self, $mime) = @_;
515 unindex_blob($self, $mime);
516 unindex_mm($self, $mime);
520 my ($git, $blob, $sizeref) = @_;
522 my $str = $git->cat_file($blob, $sizeref);
523 # fixup bugs from import:
524 $$str =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
525 PublicInbox::MIME->new($str);
531 my ($self, $opts) = @_;
532 with_umask($self, sub { $self->_index_sync($opts) });
535 sub batch_adjust ($$$$) {
536 my ($max, $bytes, $batch_cb, $latest) = @_;
540 $batch_cb->($latest, 1);
545 my ($self, $log, $add_cb, $del_cb, $batch_cb) = @_;
546 my $hex = '[a-f0-9]';
547 my $h40 = $hex .'{40}';
548 my $addmsg = qr!^:000000 100644 \S+ ($h40) A\t${hex}{2}/${hex}{38}$!;
549 my $delmsg = qr!^:100644 000000 ($h40) \S+ D\t${hex}{2}/${hex}{38}$!;
550 my $git = $self->{git};
553 my $max = BATCH_BYTES;
556 while (defined($line = <$log>)) {
557 if ($line =~ /$addmsg/o) {
559 my $mime = do_cat_mail($git, $blob, \$bytes) or next;
560 batch_adjust(\$max, $bytes, $batch_cb, $latest);
561 $add_cb->($self, $mime, $bytes, $blob);
562 } elsif ($line =~ /$delmsg/o) {
564 my $mime = do_cat_mail($git, $blob, \$bytes) or next;
565 batch_adjust(\$max, $bytes, $batch_cb, $latest);
566 $del_cb->($self, $mime);
567 } elsif ($line =~ /^commit ($h40)/o) {
571 $batch_cb->($latest, 0);
577 require PublicInbox::Msgmap;
578 PublicInbox::Msgmap->new($self->{git_dir}, 1);
583 my ($self, $range) = @_;
584 $self->{git}->popen(qw/log --reverse --no-notes --no-color
585 --raw -r --no-abbrev/, $range);
588 # indexes all unindexed messages
590 my ($self, $opts) = @_;
591 my $tip = $opts->{ref} || 'HEAD';
592 my $reindex = $opts->{reindex};
593 my ($mkey, $last_commit, $lx, $xlog);
594 $self->{git}->batch_prepare;
595 my $xdb = _xdb_acquire($self);
596 $xdb->begin_transaction;
599 $mkey = 'last_commit';
600 $last_commit = $xdb->get_metadata('last_commit');
604 $mkey = undef if $last_commit ne '';
606 $xdb->cancel_transaction;
607 $xdb = _xdb_release($self);
609 # ensure we leak no FDs to "git log"
610 my $range = $lx eq '' ? $tip : "$lx..$tip";
611 $xlog = _git_log($self, $range);
613 $xdb = _xdb_acquire($self);
614 $xdb->begin_transaction;
615 } while ($xdb->get_metadata('last_commit') ne $last_commit);
617 my $mm = _msgmap_init($self);
618 my $dbh = $mm->{dbh} if $mm;
621 my ($commit, $more) = @_;
623 $mm->last_commit($commit) if $commit;
627 $xdb->set_metadata($mkey, $commit) if $mkey && $commit;
628 $xdb->commit_transaction;
629 $xdb = _xdb_release($self);
631 # let another process do some work... <
634 $xdb = _xdb_acquire($self);
635 $xdb->begin_transaction;
637 $dbh->begin_work if $dbh;
643 my $lm = $mm->last_commit || '';
645 # Common case is the indexes are synced,
646 # we only need to run git-log once:
647 rlog($self, $xlog, *index_both, *unindex_both, $cb);
649 # Uncommon case, msgmap and xapian are out-of-sync
650 # do not care for performance (but git is fast :>)
651 # This happens if we have to reindex Xapian since
652 # msgmap is a frozen format and our Xapian format
654 my $r = $lm eq '' ? $tip : "$lm..$tip";
656 # first, ensure msgmap is up-to-date:
657 my $mkey_prev = $mkey;
658 $mkey = undef; # ignore xapian, for now
659 my $mlog = _git_log($self, $r);
661 rlog($self, $mlog, *index_mm, *unindex_mm, $cb);
662 $mm_only = $mlog = undef;
664 # now deal with Xapian
667 rlog($self, $xlog, *index_mm2, *unindex_mm2, $cb);
670 # user didn't install DBD::SQLite and DBI
671 rlog($self, $xlog, *index_blob, *unindex_blob, $cb);
675 # this will create a ghost as necessary
676 sub _resolve_mid_to_tid {
677 my ($self, $mid) = @_;
679 my $smsg = $self->lookup_message($mid) || $self->create_ghost($mid);
684 my ($self, $mid) = @_;
686 my $tid = $self->next_thread_id;
687 my $doc = Search::Xapian::Document->new;
688 $doc->add_term('XMID' . $mid);
689 $doc->add_term('G' . $tid);
690 $doc->add_term('T' . 'ghost');
692 my $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
693 $self->{xdb}->add_document($doc);
699 my ($self, $winner_tid, $loser_tid) = @_;
700 return if $winner_tid == $loser_tid;
701 my ($head, $tail) = $self->find_doc_ids('G' . $loser_tid);
702 my $db = $self->{xdb};
704 for (; $head != $tail; $head->inc) {
705 my $docid = $head->get_docid;
706 my $doc = $db->get_document($docid);
707 $doc->remove_term('G' . $loser_tid);
708 $doc->add_term('G' . $winner_tid);
709 $db->replace_document($docid, $doc);
713 sub _read_git_config_perm {
715 my @cmd = qw(config core.sharedRepository);
716 my $fh = PublicInbox::Git->new($self->{git_dir})->popen(@cmd);
719 chomp $perm if defined $perm;
723 sub _git_config_perm {
725 my $perm = scalar @_ ? $_[0] : _read_git_config_perm($self);
726 return PERM_GROUP if (!defined($perm) || $perm eq '');
727 return PERM_UMASK if ($perm eq 'umask');
728 return PERM_GROUP if ($perm eq 'group');
729 if ($perm =~ /\A(?:all|world|everybody)\z/) {
730 return PERM_EVERYBODY;
732 return PERM_GROUP if ($perm =~ /\A(?:true|yes|on|1)\z/);
733 return PERM_UMASK if ($perm =~ /\A(?:false|no|off|0)\z/);
736 return PERM_UMASK if ($i == PERM_UMASK);
737 return PERM_GROUP if ($i == OLD_PERM_GROUP);
738 return PERM_EVERYBODY if ($i == OLD_PERM_EVERYBODY);
740 if (($i & 0600) != 0600) {
741 die "core.sharedRepository mode invalid: ".
742 sprintf('%.3o', $i) . "\nOwner must have permissions\n";
748 my ($perm) = @_; # _git_config_perm return value
750 return umask if $rv == 0;
752 # set +x bit if +r or +w were set
753 $rv |= 0100 if ($rv & 0600);
754 $rv |= 0010 if ($rv & 0060);
755 $rv |= 0001 if ($rv & 0006);
760 my ($self, $cb) = @_;
761 my $old = umask $self->{umask};
762 my $rv = eval { $cb->() };
770 # order matters for unlocking
771 $_[0]->{xdb} = undef;
772 $_[0]->{lockfh} = undef;