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;
22 *xpfx = *PublicInbox::Search::xpfx;
24 use constant MAX_MID_SIZE => 244; # max term size - 1 in Xapian
28 OLD_PERM_EVERYBODY => 2,
30 PERM_EVERYBODY => 0664,
34 my ($class, $inbox, $creat) = @_;
38 $git_dir = $inbox->{mainrepo};
39 $altid = $inbox->{altid};
41 require PublicInbox::AltId;
43 PublicInbox::AltId->new($inbox, $_);
47 require Search::Xapian::WritableDatabase;
48 my $self = bless { git_dir => $git_dir, -altid => $altid }, $class;
49 my $perm = $self->_git_config_perm;
50 my $umask = _umask_for($perm);
51 $self->{umask} = $umask;
52 $self->{lock_path} = "$git_dir/ssoma.lock";
53 $self->{git} = PublicInbox::Git->new($git_dir);
54 $self->{creat} = ($creat || 0) == 1;
60 my $xdb = delete $self->{xdb} or croak 'not acquired';
62 _lock_release($self) if $self->{creat};
68 croak 'already acquired' if $self->{xdb};
69 my $dir = PublicInbox::Search->xdir($self->{git_dir});
70 my $flag = Search::Xapian::DB_OPEN;
74 File::Path::mkpath($dir);
75 $self->{batch_size} = 100;
76 $flag = Search::Xapian::DB_CREATE_OR_OPEN;
78 $self->{xdb} = Search::Xapian::WritableDatabase->new($dir, $flag);
81 # we only acquire the flock if creating or reindexing;
82 # PublicInbox::Import already has the lock on its own.
85 croak 'already locked' if $self->{lockfh};
86 sysopen(my $lockfh, $self->{lock_path}, O_WRONLY|O_CREAT) or
87 die "failed to open lock $self->{lock_path}: $!\n";
88 flock($lockfh, LOCK_EX) or die "lock failed: $!\n";
89 $self->{lockfh} = $lockfh;
94 my $lockfh = delete $self->{lockfh} or croak 'not locked';
95 flock($lockfh, LOCK_UN) or die "unlock failed: $!\n";
96 close $lockfh or die "close failed: $!\n";
100 my ($doc, $col, $num) = @_;
101 $num = Search::Xapian::sortable_serialise($num);
102 $doc->add_value($col, $num);
105 sub add_values ($$$) {
106 my ($smsg, $bytes, $num) = @_;
109 my $doc = $smsg->{doc};
110 add_val($doc, &PublicInbox::Search::TS, $ts);
112 defined($num) and add_val($doc, &PublicInbox::Search::NUM, $num);
114 defined($bytes) and add_val($doc, &PublicInbox::Search::BYTES, $bytes);
116 add_val($doc, &PublicInbox::Search::LINES,
117 $smsg->{mime}->body_raw =~ tr!\n!\n!);
119 my $yyyymmdd = strftime('%Y%m%d', gmtime($ts));
120 add_val($doc, PublicInbox::Search::YYYYMMDD, $yyyymmdd);
123 sub index_users ($$) {
124 my ($tg, $smsg) = @_;
126 my $from = $smsg->from;
130 $tg->index_text($from, 1, 'A'); # A - author
131 $tg->increase_termpos;
132 $tg->index_text($to, 1, 'XTO') if $to ne '';
133 $tg->increase_termpos;
134 $tg->index_text($cc, 1, 'XCC') if $cc ne '';
135 $tg->increase_termpos;
138 sub index_body ($$$) {
139 my ($tg, $lines, $inc) = @_;
140 $tg->index_text(join("\n", @$lines), $inc, $inc ? 'XNQ' : 'XQUOT');
142 $tg->increase_termpos;
146 my ($self, $mime, $bytes, $num, $blob) = @_; # mime = Email::MIME object
147 my $db = $self->{xdb};
149 my ($doc_id, $old_tid);
150 my $mid = mid_clean(mid_mime($mime));
153 die 'Message-ID too long' if length($mid) > MAX_MID_SIZE;
154 my $smsg = $self->lookup_message($mid);
156 # convert a ghost to a regular message
157 # it will also clobber any existing regular message
158 $doc_id = $smsg->{doc_id};
159 $old_tid = $smsg->thread_id;
161 # no need to remove_term for old_tid, we use a new
162 # doc to replace the old one when reindexing:
163 $old_tid = undef if $self->{reindex};
165 $smsg = PublicInbox::SearchMsg->new($mime);
166 my $doc = $smsg->{doc};
167 $doc->add_term(xpfx('mid') . $mid);
169 my $subj = $smsg->subject;
171 my $path = $self->subject_path($subj);
172 $doc->add_term(xpfx('path') . id_compress($path));
175 add_values($smsg, $bytes, $num);
177 my $tg = $self->term_generator;
179 $tg->set_document($doc);
180 $tg->index_text($subj, 1, 'S') if $subj;
181 $tg->increase_termpos;
183 index_users($tg, $smsg);
185 msg_iter($mime, sub {
186 my ($part, $depth, @idx) = @{$_[0]};
187 my $ct = $part->content_type || 'text/plain';
188 my $fn = $part->filename;
189 if (defined $fn && $fn ne '') {
190 $tg->index_text($fn, 1, 'XFN');
193 return if $ct =~ m!\btext/x?html\b!i;
195 my $s = eval { $part->body_str };
197 if ($ct =~ m!\btext/plain\b!i) {
198 # Try to assume UTF-8 because Alpine
199 # seems to do wacky things and set
201 $part->charset_set('UTF-8');
202 $s = eval { $part->body_str };
203 $s = $part->body if $@;
206 defined $s or return;
209 my $body = $part->body;
210 my @lines = split(/\n/, $body);
211 while (defined(my $l = shift @lines)) {
213 index_body($tg, \@orig, 1) if @orig;
216 index_body($tg, \@quot, 0) if @quot;
220 index_body($tg, \@quot, 0) if @quot;
221 index_body($tg, \@orig, 1) if @orig;
224 link_message($self, $smsg, $old_tid);
225 $tg->index_text($mid, 1, 'XMID');
226 $doc->set_data($smsg->to_doc_data($blob));
228 if (my $altid = $self->{-altid}) {
229 foreach my $alt (@$altid) {
230 my $id = $alt->mid2alt($mid);
231 next unless defined $id;
232 $doc->add_term($alt->{xprefix} . $id);
235 if (defined $doc_id) {
236 $db->replace_document($doc_id, $doc);
238 $doc_id = $db->add_document($doc);
243 warn "failed to index message <$mid>: $@\n";
249 # returns deleted doc_id on success, undef on missing
251 my ($self, $mid) = @_;
252 my $db = $self->{xdb};
254 $mid = mid_clean($mid);
257 $doc_id = $self->find_unique_doc_id('mid', $mid);
258 $db->delete_document($doc_id) if defined $doc_id;
262 warn "failed to remove message <$mid>: $@\n";
268 sub term_generator { # write-only
271 my $tg = $self->{term_generator};
274 $tg = Search::Xapian::TermGenerator->new;
275 $tg->set_stemmer($self->stemmer);
277 $self->{term_generator} = $tg;
280 # increments last_thread_id counter
281 # returns a 64-bit integer represented as a hex string
284 my $db = $self->{xdb};
285 my $last_thread_id = int($db->get_metadata('last_thread_id') || 0);
287 $db->set_metadata('last_thread_id', ++$last_thread_id);
293 my ($self, $smsg, $old_tid) = @_;
294 my $doc = $smsg->{doc};
295 my $mid = $smsg->mid;
296 my $mime = $smsg->{mime};
297 my $hdr = $mime->header_obj;
298 my $refs = $hdr->header_raw('References');
299 my @refs = defined $refs ? ($refs =~ /<([^>]+)>/g) : ();
300 my $irt = $hdr->header_raw('In-Reply-To');
305 $irt = mid_clean($irt);
306 $irt = undef if $mid eq $irt;
312 my %uniq = ($mid => 1);
313 my @orig_refs = @refs;
317 # to check MAX_MID_SIZE
318 push @orig_refs, $irt;
320 # below, we will ensure IRT (if specified)
321 # is the last References
325 # prevent circular references via References: here:
326 foreach my $ref (@orig_refs) {
327 if (length($ref) > MAX_MID_SIZE) {
328 warn "References: <$ref> too long, ignoring\n";
336 # last References should be IRT, but some mail clients do things
337 # out of order, so trust IRT over References iff IRT exists
338 push @refs, $irt if defined $irt;
341 $smsg->{references} = '<'.join('> <', @refs).'>';
343 # first ref *should* be the thread root,
344 # but we can never trust clients to do the right thing
345 my $ref = shift @refs;
346 $tid = $self->_resolve_mid_to_tid($ref);
347 $self->merge_threads($tid, $old_tid) if defined $old_tid;
349 # the rest of the refs should point to this tid:
350 foreach $ref (@refs) {
351 my $ptid = $self->_resolve_mid_to_tid($ref);
352 merge_threads($self, $tid, $ptid);
355 $tid = $self->next_thread_id;
357 $doc->add_term(xpfx('thread') . $tid);
361 my ($self, $mime, $bytes, $num, $blob) = @_;
362 $self->add_message($mime, $bytes, $num, $blob);
366 my ($self, $mime) = @_;
367 my $mid = eval { mid_clean(mid_mime($mime)) };
368 $self->remove_message($mid) if defined $mid;
372 my ($self, $mime) = @_;
373 $self->{mm}->mid_insert(mid_clean(mid_mime($mime)));
377 my ($self, $mime) = @_;
378 $self->{mm}->mid_delete(mid_clean(mid_mime($mime)));
382 my ($self, $mime, $bytes, $blob) = @_;
383 my $num = $self->{mm}->num_for(mid_clean(mid_mime($mime)));
384 index_blob($self, $mime, $bytes, $num, $blob);
388 my ($self, $mime) = @_;
389 $self->{mm}->mid_delete(mid_clean(mid_mime($mime)));
390 unindex_blob($self, $mime);
394 my ($self, $mime, $bytes, $blob) = @_;
395 my $num = index_mm($self, $mime);
396 index_blob($self, $mime, $bytes, $num, $blob);
400 my ($self, $mime) = @_;
401 unindex_blob($self, $mime);
402 unindex_mm($self, $mime);
406 my ($git, $blob, $sizeref) = @_;
408 my $str = $git->cat_file($blob, $sizeref);
409 # fixup bugs from import:
410 $$str =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
411 PublicInbox::MIME->new($str);
417 my ($self, $opts) = @_;
418 with_umask($self, sub { $self->_index_sync($opts) });
422 my ($self, $log, $add_cb, $del_cb, $batch_cb) = @_;
423 my $hex = '[a-f0-9]';
424 my $h40 = $hex .'{40}';
425 my $addmsg = qr!^:000000 100644 \S+ ($h40) A\t${hex}{2}/${hex}{38}$!;
426 my $delmsg = qr!^:100644 000000 ($h40) \S+ D\t${hex}{2}/${hex}{38}$!;
427 my $git = $self->{git};
430 my $max = $self->{batch_size}; # may be undef
433 while (defined($line = <$log>)) {
434 if ($line =~ /$addmsg/o) {
436 my $mime = do_cat_mail($git, $blob, \$bytes) or next;
437 $add_cb->($self, $mime, $bytes, $blob);
438 } elsif ($line =~ /$delmsg/o) {
440 my $mime = do_cat_mail($git, $blob) or next;
441 $del_cb->($self, $mime);
442 } elsif ($line =~ /^commit ($h40)/o) {
443 if (defined $max && --$max <= 0) {
444 $max = $self->{batch_size};
445 $batch_cb->($latest, 1);
450 $batch_cb->($latest, 0);
456 require PublicInbox::Msgmap;
457 PublicInbox::Msgmap->new($self->{git_dir}, 1);
462 my ($self, $range) = @_;
463 $self->{git}->popen(qw/log --reverse --no-notes --no-color
464 --raw -r --no-abbrev/, $range);
467 # indexes all unindexed messages
469 my ($self, $opts) = @_;
470 my $tip = $opts->{ref} || 'HEAD';
471 $self->{reindex} = $opts->{reindex};
472 my ($mkey, $last_commit, $lx, $xlog);
473 $self->{git}->batch_prepare;
474 my $xdb = _xdb_acquire($self);
475 $xdb->begin_transaction;
478 $mkey = 'last_commit';
479 $last_commit = $xdb->get_metadata('last_commit');
481 if ($self->{reindex}) {
483 $mkey = undef if $last_commit ne '';
485 $xdb->cancel_transaction;
486 $xdb = _xdb_release($self);
488 # ensure we leak no FDs to "git log"
489 my $range = $lx eq '' ? $tip : "$lx..$tip";
490 $xlog = _git_log($self, $range);
492 $xdb = _xdb_acquire($self);
493 $xdb->begin_transaction;
494 } while ($xdb->get_metadata('last_commit') ne $last_commit);
496 my $mm = _msgmap_init($self);
497 my $dbh = $mm->{dbh} if $mm;
500 my ($commit, $more) = @_;
502 $mm->last_commit($commit) if $commit;
506 $xdb->set_metadata($mkey, $commit) if $mkey && $commit;
507 $xdb->commit_transaction;
508 $xdb = _xdb_release($self);
510 # let another process do some work... <
513 $xdb = _xdb_acquire($self);
514 $xdb->begin_transaction;
516 $dbh->begin_work if $dbh;
522 my $lm = $mm->last_commit || '';
524 # Common case is the indexes are synced,
525 # we only need to run git-log once:
526 rlog($self, $xlog, *index_both, *unindex_both, $cb);
528 # Uncommon case, msgmap and xapian are out-of-sync
529 # do not care for performance (but git is fast :>)
530 # This happens if we have to reindex Xapian since
531 # msgmap is a frozen format and our Xapian format
533 my $r = $lm eq '' ? $tip : "$lm..$tip";
535 # first, ensure msgmap is up-to-date:
536 my $mkey_prev = $mkey;
537 $mkey = undef; # ignore xapian, for now
538 my $mlog = _git_log($self, $r);
540 rlog($self, $mlog, *index_mm, *unindex_mm, $cb);
541 $mm_only = $mlog = undef;
543 # now deal with Xapian
546 rlog($self, $xlog, *index_mm2, *unindex_mm2, $cb);
549 # user didn't install DBD::SQLite and DBI
550 rlog($self, $xlog, *index_blob, *unindex_blob, $cb);
554 # this will create a ghost as necessary
555 sub _resolve_mid_to_tid {
556 my ($self, $mid) = @_;
558 my $smsg = $self->lookup_message($mid) || $self->create_ghost($mid);
563 my ($self, $mid) = @_;
565 my $tid = $self->next_thread_id;
566 my $doc = Search::Xapian::Document->new;
567 $doc->add_term(xpfx('mid') . $mid);
568 $doc->add_term(xpfx('thread') . $tid);
569 $doc->add_term(xpfx('type') . 'ghost');
571 my $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
572 $self->{xdb}->add_document($doc);
578 my ($self, $winner_tid, $loser_tid) = @_;
579 return if $winner_tid == $loser_tid;
580 my ($head, $tail) = $self->find_doc_ids('thread', $loser_tid);
581 my $thread_pfx = xpfx('thread');
582 my $db = $self->{xdb};
584 for (; $head != $tail; $head->inc) {
585 my $docid = $head->get_docid;
586 my $doc = $db->get_document($docid);
587 $doc->remove_term($thread_pfx . $loser_tid);
588 $doc->add_term($thread_pfx . $winner_tid);
589 $db->replace_document($docid, $doc);
593 sub _read_git_config_perm {
595 my @cmd = qw(config core.sharedRepository);
596 my $fh = PublicInbox::Git->new($self->{git_dir})->popen(@cmd);
599 chomp $perm if defined $perm;
603 sub _git_config_perm {
605 my $perm = scalar @_ ? $_[0] : _read_git_config_perm($self);
606 return PERM_GROUP if (!defined($perm) || $perm eq '');
607 return PERM_UMASK if ($perm eq 'umask');
608 return PERM_GROUP if ($perm eq 'group');
609 if ($perm =~ /\A(?:all|world|everybody)\z/) {
610 return PERM_EVERYBODY;
612 return PERM_GROUP if ($perm =~ /\A(?:true|yes|on|1)\z/);
613 return PERM_UMASK if ($perm =~ /\A(?:false|no|off|0)\z/);
616 return PERM_UMASK if ($i == PERM_UMASK);
617 return PERM_GROUP if ($i == OLD_PERM_GROUP);
618 return PERM_EVERYBODY if ($i == OLD_PERM_EVERYBODY);
620 if (($i & 0600) != 0600) {
621 die "core.sharedRepository mode invalid: ".
622 sprintf('%.3o', $i) . "\nOwner must have permissions\n";
628 my ($perm) = @_; # _git_config_perm return value
630 return umask if $rv == 0;
632 # set +x bit if +r or +w were set
633 $rv |= 0100 if ($rv & 0600);
634 $rv |= 0010 if ($rv & 0060);
635 $rv |= 0001 if ($rv & 0006);
640 my ($self, $cb) = @_;
641 my $old = umask $self->{umask};
642 my $rv = eval { $cb->() };
650 # order matters for unlocking
651 $_[0]->{xdb} = undef;
652 $_[0]->{lockfh} = undef;