]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/SearchIdx.pm
threading: deal with improperly-terminated References headers
[public-inbox.git] / lib / PublicInbox / SearchIdx.pm
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
4 #
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;
10 use strict;
11 use warnings;
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;
19 use Carp qw(croak);
20 use POSIX qw(strftime);
21 require PublicInbox::Git;
22
23 use constant {
24         MAX_MID_SIZE => 244, # max term size - 1 in Xapian
25         PERM_UMASK => 0,
26         OLD_PERM_GROUP => 1,
27         OLD_PERM_EVERYBODY => 2,
28         PERM_GROUP => 0660,
29         PERM_EVERYBODY => 0664,
30         BATCH_BYTES => 1_000_000,
31         DEBUG => !!$ENV{DEBUG},
32 };
33
34 my %GIT_ESC = (
35         a => "\a",
36         b => "\b",
37         f => "\f",
38         n => "\n",
39         r => "\r",
40         t => "\t",
41         v => "\013",
42 );
43
44 sub git_unquote ($) {
45         my ($s) = @_;
46         return $s unless ($s =~ /\A"(.*)"\z/);
47         $s = $1;
48         $s =~ s/\\([abfnrtv])/$GIT_ESC{$1}/g;
49         $s =~ s/\\([0-7]{1,3})/chr(oct($1))/ge;
50         $s;
51 }
52
53 sub new {
54         my ($class, $inbox, $creat) = @_;
55         my $git_dir = $inbox;
56         my $altid;
57         if (ref $inbox) {
58                 $git_dir = $inbox->{mainrepo};
59                 $altid = $inbox->{altid};
60                 if ($altid) {
61                         require PublicInbox::AltId;
62                         $altid = [ map {
63                                 PublicInbox::AltId->new($inbox, $_);
64                         } @$altid ];
65                 }
66         }
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;
75         $self;
76 }
77
78 sub _xdb_release {
79         my ($self) = @_;
80         my $xdb = delete $self->{xdb} or croak 'not acquired';
81         $xdb->close;
82         _lock_release($self) if $self->{creat};
83         undef;
84 }
85
86 sub _xdb_acquire {
87         my ($self) = @_;
88         croak 'already acquired' if $self->{xdb};
89         my $dir = PublicInbox::Search->xdir($self->{git_dir});
90         my $flag = Search::Xapian::DB_OPEN;
91         if ($self->{creat}) {
92                 require File::Path;
93                 _lock_acquire($self);
94                 File::Path::mkpath($dir);
95                 $flag = Search::Xapian::DB_CREATE_OR_OPEN;
96         }
97         $self->{xdb} = Search::Xapian::WritableDatabase->new($dir, $flag);
98 }
99
100 # we only acquire the flock if creating or reindexing;
101 # PublicInbox::Import already has the lock on its own.
102 sub _lock_acquire {
103         my ($self) = @_;
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;
109 }
110
111 sub _lock_release {
112         my ($self) = @_;
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";
116 }
117
118 sub add_val ($$$) {
119         my ($doc, $col, $num) = @_;
120         $num = Search::Xapian::sortable_serialise($num);
121         $doc->add_value($col, $num);
122 }
123
124 sub add_values ($$$) {
125         my ($smsg, $bytes, $num) = @_;
126
127         my $ts = $smsg->ts;
128         my $doc = $smsg->{doc};
129         add_val($doc, &PublicInbox::Search::TS, $ts);
130
131         defined($num) and add_val($doc, &PublicInbox::Search::NUM, $num);
132
133         defined($bytes) and add_val($doc, &PublicInbox::Search::BYTES, $bytes);
134
135         add_val($doc, &PublicInbox::Search::LINES,
136                         $smsg->{mime}->body_raw =~ tr!\n!\n!);
137
138         my $yyyymmdd = strftime('%Y%m%d', gmtime($ts));
139         add_val($doc, PublicInbox::Search::YYYYMMDD, $yyyymmdd);
140 }
141
142 sub index_users ($$) {
143         my ($tg, $smsg) = @_;
144
145         my $from = $smsg->from;
146         my $to = $smsg->to;
147         my $cc = $smsg->cc;
148
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;
155 }
156
157 sub index_text_inc ($$$) {
158         my ($tg, $text, $pfx) = @_;
159         $tg->index_text($text, 1, $pfx);
160         $tg->increase_termpos;
161 }
162
163 sub index_old_diff_fn {
164         my ($tg, $seen, $fa, $fb) = @_;
165
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);
173                 if ($fa eq $fb) {
174                         index_text_inc($tg, $fa,'XDFN') unless $seen->{$fa}++;
175                         return 1;
176                 }
177                 shift @fa;
178                 shift @fb;
179         }
180         0;
181 }
182
183 sub index_diff ($$$) {
184         my ($tg, $lines, $doc) = @_;
185         my %seen;
186         my $in_diff;
187         foreach (@$lines) {
188                 if ($in_diff && s/^ //) { # diff context
189                         index_text_inc($tg, $_, 'XDFCTX');
190                 } elsif (/^-- $/) { # email signature begins
191                         $in_diff = undef;
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}++;
198                         $in_diff = 1;
199                 # traditional diff:
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}++;
208                         $in_diff = 1;
209                 } elsif (m!^\+\+\+ ("?b/.+)!)  {
210                         my $fn = (split('/', git_unquote($1), 2))[1];
211                         index_text_inc($tg, $fn, 'XDFN') unless $seen{$fn}++;
212                         $in_diff = 1;
213                 } elsif (/^--- (\S+)/) {
214                         $in_diff = $1;
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);
225                         $in_diff = 1;
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/) {
239                 } elsif ($_ eq '') {
240                         $in_diff = undef;
241                 } else {
242                         warn "non-diff line: $_\n" if DEBUG && $_ ne '';
243                         $in_diff = undef;
244                 }
245         }
246 }
247
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) {
255                 $txt = undef;
256                 index_diff($tg, $lines, $doc);
257         }
258         @$lines = ();
259 }
260
261 sub add_message {
262         my ($self, $mime, $bytes, $num, $blob) = @_; # mime = Email::MIME object
263         my $db = $self->{xdb};
264
265         my ($doc_id, $old_tid);
266         my $mid = mid_clean(mid_mime($mime));
267
268         eval {
269                 die 'Message-ID too long' if length($mid) > MAX_MID_SIZE;
270                 my $smsg = $self->lookup_message($mid);
271                 if ($smsg) {
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;
276                 }
277                 $smsg = PublicInbox::SearchMsg->new($mime);
278                 my $doc = $smsg->{doc};
279                 $doc->add_term('Q' . $mid);
280
281                 my $subj = $smsg->subject;
282                 if ($subj ne '') {
283                         my $path = $self->subject_path($subj);
284                         $doc->add_term('XPATH' . id_compress($path));
285                 }
286
287                 add_values($smsg, $bytes, $num);
288
289                 my $tg = $self->term_generator;
290
291                 $tg->set_document($doc);
292                 $tg->index_text($subj, 1, 'S') if $subj;
293                 $tg->increase_termpos;
294
295                 index_users($tg, $smsg);
296
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');
303                         }
304
305                         return if $ct =~ m!\btext/x?html\b!i;
306
307                         my $s = eval { $part->body_str };
308                         if ($@) {
309                                 if ($ct =~ m!\btext/plain\b!i) {
310                                         # Try to assume UTF-8 because Alpine
311                                         # seems to do wacky things and set
312                                         # charset=X-UNKNOWN
313                                         $part->charset_set('UTF-8');
314                                         $s = eval { $part->body_str };
315                                         $s = $part->body if $@;
316                                 }
317                         }
318                         defined $s or return;
319
320                         my (@orig, @quot);
321                         my $body = $part->body;
322                         my @lines = split(/\n/, $body);
323                         while (defined(my $l = shift @lines)) {
324                                 if ($l =~ /^>/) {
325                                         index_body($tg, \@orig, $doc) if @orig;
326                                         push @quot, $l;
327                                 } else {
328                                         index_body($tg, \@quot, 0) if @quot;
329                                         push @orig, $l;
330                                 }
331                         }
332                         index_body($tg, \@quot, 0) if @quot;
333                         index_body($tg, \@orig, $doc) if @orig;
334                 });
335
336                 link_message($self, $smsg, $old_tid);
337                 $tg->index_text($mid, 1, 'XMID');
338                 $doc->set_data($smsg->to_doc_data($blob));
339
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);
345                         }
346                 }
347                 if (defined $doc_id) {
348                         $db->replace_document($doc_id, $doc);
349                 } else {
350                         $doc_id = $db->add_document($doc);
351                 }
352         };
353
354         if ($@) {
355                 warn "failed to index message <$mid>: $@\n";
356                 return undef;
357         }
358         $doc_id;
359 }
360
361 # returns deleted doc_id on success, undef on missing
362 sub remove_message {
363         my ($self, $mid) = @_;
364         my $db = $self->{xdb};
365         my $doc_id;
366         $mid = mid_clean($mid);
367
368         eval {
369                 $doc_id = $self->find_unique_doc_id('Q' . $mid);
370                 if (defined $doc_id) {
371                         $db->delete_document($doc_id);
372                 } else {
373                         warn "cannot remove non-existent <$mid>\n";
374                 }
375         };
376
377         if ($@) {
378                 warn "failed to remove message <$mid>: $@\n";
379                 return undef;
380         }
381         $doc_id;
382 }
383
384 sub term_generator { # write-only
385         my ($self) = @_;
386
387         my $tg = $self->{term_generator};
388         return $tg if $tg;
389
390         $tg = Search::Xapian::TermGenerator->new;
391         $tg->set_stemmer($self->stemmer);
392
393         $self->{term_generator} = $tg;
394 }
395
396 # increments last_thread_id counter
397 # returns a 64-bit integer represented as a hex string
398 sub next_thread_id {
399         my ($self) = @_;
400         my $db = $self->{xdb};
401         my $last_thread_id = int($db->get_metadata('last_thread_id') || 0);
402
403         $db->set_metadata('last_thread_id', ++$last_thread_id);
404
405         $last_thread_id;
406 }
407
408 sub link_message {
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;
414
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') || '') =~ /<([^>]+)>/g);
418         push(@refs, (($hdr->header_raw('In-Reply-To') || '') =~ /<([^>]+)>/g));
419
420         my $tid;
421         if (@refs) {
422                 my %uniq = ($mid => 1);
423                 my @orig_refs = @refs;
424                 @refs = ();
425
426                 # prevent circular references via References: here:
427                 foreach my $ref (@orig_refs) {
428                         if (length($ref) > MAX_MID_SIZE) {
429                                 warn "References: <$ref> too long, ignoring\n";
430                         }
431                         next if $uniq{$ref};
432                         $uniq{$ref} = 1;
433                         push @refs, $ref;
434                 }
435         }
436
437         if (@refs) {
438                 $smsg->{references} = '<'.join('> <', @refs).'>';
439
440                 # first ref *should* be the thread root,
441                 # but we can never trust clients to do the right thing
442                 my $ref = shift @refs;
443                 $tid = $self->_resolve_mid_to_tid($ref);
444                 $self->merge_threads($tid, $old_tid) if defined $old_tid;
445
446                 # the rest of the refs should point to this tid:
447                 foreach $ref (@refs) {
448                         my $ptid = $self->_resolve_mid_to_tid($ref);
449                         merge_threads($self, $tid, $ptid);
450                 }
451         } else {
452                 $tid = defined $old_tid ? $old_tid : $self->next_thread_id;
453         }
454         $doc->add_term('G' . $tid);
455 }
456
457 sub index_blob {
458         my ($self, $mime, $bytes, $num, $blob) = @_;
459         $self->add_message($mime, $bytes, $num, $blob);
460 }
461
462 sub index_git_blob_id {
463         my ($doc, $pfx, $objid) = @_;
464
465         my $len = length($objid);
466         for (my $len = length($objid); $len >= 7; ) {
467                 $doc->add_term($pfx.$objid);
468                 $objid = substr($objid, 0, --$len);
469         }
470 }
471
472 sub unindex_blob {
473         my ($self, $mime) = @_;
474         my $mid = eval { mid_clean(mid_mime($mime)) };
475         $self->remove_message($mid) if defined $mid;
476 }
477
478 sub index_mm {
479         my ($self, $mime) = @_;
480         my $mid = mid_clean(mid_mime($mime));
481         my $mm = $self->{mm};
482         my $num = $mm->mid_insert($mid);
483
484         # fallback to num_for since filters like RubyLang set the number
485         defined $num ? $num : $mm->num_for($mid);
486 }
487
488 sub unindex_mm {
489         my ($self, $mime) = @_;
490         $self->{mm}->mid_delete(mid_clean(mid_mime($mime)));
491 }
492
493 sub index_mm2 {
494         my ($self, $mime, $bytes, $blob) = @_;
495         my $num = $self->{mm}->num_for(mid_clean(mid_mime($mime)));
496         index_blob($self, $mime, $bytes, $num, $blob);
497 }
498
499 sub unindex_mm2 {
500         my ($self, $mime) = @_;
501         $self->{mm}->mid_delete(mid_clean(mid_mime($mime)));
502         unindex_blob($self, $mime);
503 }
504
505 sub index_both {
506         my ($self, $mime, $bytes, $blob) = @_;
507         my $num = index_mm($self, $mime);
508         index_blob($self, $mime, $bytes, $num, $blob);
509 }
510
511 sub unindex_both {
512         my ($self, $mime) = @_;
513         unindex_blob($self, $mime);
514         unindex_mm($self, $mime);
515 }
516
517 sub do_cat_mail {
518         my ($git, $blob, $sizeref) = @_;
519         my $mime = eval {
520                 my $str = $git->cat_file($blob, $sizeref);
521                 # fixup bugs from import:
522                 $$str =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
523                 PublicInbox::MIME->new($str);
524         };
525         $@ ? undef : $mime;
526 }
527
528 sub index_sync {
529         my ($self, $opts) = @_;
530         with_umask($self, sub { $self->_index_sync($opts) });
531 }
532
533 sub batch_adjust ($$$$) {
534         my ($max, $bytes, $batch_cb, $latest) = @_;
535         $$max -= $bytes;
536         if ($$max <= 0) {
537                 $$max = BATCH_BYTES;
538                 $batch_cb->($latest, 1);
539         }
540 }
541
542 sub rlog {
543         my ($self, $log, $add_cb, $del_cb, $batch_cb) = @_;
544         my $hex = '[a-f0-9]';
545         my $h40 = $hex .'{40}';
546         my $addmsg = qr!^:000000 100644 \S+ ($h40) A\t${hex}{2}/${hex}{38}$!;
547         my $delmsg = qr!^:100644 000000 ($h40) \S+ D\t${hex}{2}/${hex}{38}$!;
548         my $git = $self->{git};
549         my $latest;
550         my $bytes;
551         my $max = BATCH_BYTES;
552         local $/ = "\n";
553         my $line;
554         while (defined($line = <$log>)) {
555                 if ($line =~ /$addmsg/o) {
556                         my $blob = $1;
557                         my $mime = do_cat_mail($git, $blob, \$bytes) or next;
558                         batch_adjust(\$max, $bytes, $batch_cb, $latest);
559                         $add_cb->($self, $mime, $bytes, $blob);
560                 } elsif ($line =~ /$delmsg/o) {
561                         my $blob = $1;
562                         my $mime = do_cat_mail($git, $blob, \$bytes) or next;
563                         batch_adjust(\$max, $bytes, $batch_cb, $latest);
564                         $del_cb->($self, $mime);
565                 } elsif ($line =~ /^commit ($h40)/o) {
566                         $latest = $1;
567                 }
568         }
569         $batch_cb->($latest, 0);
570 }
571
572 sub _msgmap_init {
573         my ($self) = @_;
574         $self->{mm} = eval {
575                 require PublicInbox::Msgmap;
576                 PublicInbox::Msgmap->new($self->{git_dir}, 1);
577         };
578 }
579
580 sub _git_log {
581         my ($self, $range) = @_;
582         $self->{git}->popen(qw/log --reverse --no-notes --no-color
583                                 --raw -r --no-abbrev/, $range);
584 }
585
586 # indexes all unindexed messages
587 sub _index_sync {
588         my ($self, $opts) = @_;
589         my $tip = $opts->{ref} || 'HEAD';
590         my $reindex = $opts->{reindex};
591         my ($mkey, $last_commit, $lx, $xlog);
592         $self->{git}->batch_prepare;
593         my $xdb = _xdb_acquire($self);
594         $xdb->begin_transaction;
595         do {
596                 $xlog = undef;
597                 $mkey = 'last_commit';
598                 $last_commit = $xdb->get_metadata('last_commit');
599                 $lx = $last_commit;
600                 if ($reindex) {
601                         $lx = '';
602                         $mkey = undef if $last_commit ne '';
603                 }
604                 $xdb->cancel_transaction;
605                 $xdb = _xdb_release($self);
606
607                 # ensure we leak no FDs to "git log"
608                 my $range = $lx eq '' ? $tip : "$lx..$tip";
609                 $xlog = _git_log($self, $range);
610
611                 $xdb = _xdb_acquire($self);
612                 $xdb->begin_transaction;
613         } while ($xdb->get_metadata('last_commit') ne $last_commit);
614
615         my $mm = _msgmap_init($self);
616         my $dbh = $mm->{dbh} if $mm;
617         my $mm_only;
618         my $cb = sub {
619                 my ($commit, $more) = @_;
620                 if ($dbh) {
621                         $mm->last_commit($commit) if $commit;
622                         $dbh->commit;
623                 }
624                 if (!$mm_only) {
625                         $xdb->set_metadata($mkey, $commit) if $mkey && $commit;
626                         $xdb->commit_transaction;
627                         $xdb = _xdb_release($self);
628                 }
629                 # let another process do some work... <
630                 if ($more) {
631                         if (!$mm_only) {
632                                 $xdb = _xdb_acquire($self);
633                                 $xdb->begin_transaction;
634                         }
635                         $dbh->begin_work if $dbh;
636                 }
637         };
638
639         if ($mm) {
640                 $dbh->begin_work;
641                 my $lm = $mm->last_commit || '';
642                 if ($lm eq $lx) {
643                         # Common case is the indexes are synced,
644                         # we only need to run git-log once:
645                         rlog($self, $xlog, *index_both, *unindex_both, $cb);
646                 } else {
647                         # Uncommon case, msgmap and xapian are out-of-sync
648                         # do not care for performance (but git is fast :>)
649                         # This happens if we have to reindex Xapian since
650                         # msgmap is a frozen format and our Xapian format
651                         # is evolving.
652                         my $r = $lm eq '' ? $tip : "$lm..$tip";
653
654                         # first, ensure msgmap is up-to-date:
655                         my $mkey_prev = $mkey;
656                         $mkey = undef; # ignore xapian, for now
657                         my $mlog = _git_log($self, $r);
658                         $mm_only = 1;
659                         rlog($self, $mlog, *index_mm, *unindex_mm, $cb);
660                         $mm_only = $mlog = undef;
661
662                         # now deal with Xapian
663                         $mkey = $mkey_prev;
664                         $dbh = undef;
665                         rlog($self, $xlog, *index_mm2, *unindex_mm2, $cb);
666                 }
667         } else {
668                 # user didn't install DBD::SQLite and DBI
669                 rlog($self, $xlog, *index_blob, *unindex_blob, $cb);
670         }
671 }
672
673 # this will create a ghost as necessary
674 sub _resolve_mid_to_tid {
675         my ($self, $mid) = @_;
676
677         my $smsg = $self->lookup_message($mid) || $self->create_ghost($mid);
678         $smsg->thread_id;
679 }
680
681 sub create_ghost {
682         my ($self, $mid) = @_;
683
684         my $tid = $self->next_thread_id;
685         my $doc = Search::Xapian::Document->new;
686         $doc->add_term('Q' . $mid);
687         $doc->add_term('G' . $tid);
688         $doc->add_term('T' . 'ghost');
689
690         my $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
691         $self->{xdb}->add_document($doc);
692
693         $smsg;
694 }
695
696 sub merge_threads {
697         my ($self, $winner_tid, $loser_tid) = @_;
698         return if $winner_tid == $loser_tid;
699         my ($head, $tail) = $self->find_doc_ids('G' . $loser_tid);
700         my $db = $self->{xdb};
701
702         for (; $head != $tail; $head->inc) {
703                 my $docid = $head->get_docid;
704                 my $doc = $db->get_document($docid);
705                 $doc->remove_term('G' . $loser_tid);
706                 $doc->add_term('G' . $winner_tid);
707                 $db->replace_document($docid, $doc);
708         }
709 }
710
711 sub _read_git_config_perm {
712         my ($self) = @_;
713         my @cmd = qw(config core.sharedRepository);
714         my $fh = PublicInbox::Git->new($self->{git_dir})->popen(@cmd);
715         local $/ = "\n";
716         my $perm = <$fh>;
717         chomp $perm if defined $perm;
718         $perm;
719 }
720
721 sub _git_config_perm {
722         my $self = shift;
723         my $perm = scalar @_ ? $_[0] : _read_git_config_perm($self);
724         return PERM_GROUP if (!defined($perm) || $perm eq '');
725         return PERM_UMASK if ($perm eq 'umask');
726         return PERM_GROUP if ($perm eq 'group');
727         if ($perm =~ /\A(?:all|world|everybody)\z/) {
728                 return PERM_EVERYBODY;
729         }
730         return PERM_GROUP if ($perm =~ /\A(?:true|yes|on|1)\z/);
731         return PERM_UMASK if ($perm =~ /\A(?:false|no|off|0)\z/);
732
733         my $i = oct($perm);
734         return PERM_UMASK if ($i == PERM_UMASK);
735         return PERM_GROUP if ($i == OLD_PERM_GROUP);
736         return PERM_EVERYBODY if ($i == OLD_PERM_EVERYBODY);
737
738         if (($i & 0600) != 0600) {
739                 die "core.sharedRepository mode invalid: ".
740                     sprintf('%.3o', $i) . "\nOwner must have permissions\n";
741         }
742         ($i & 0666);
743 }
744
745 sub _umask_for {
746         my ($perm) = @_; # _git_config_perm return value
747         my $rv = $perm;
748         return umask if $rv == 0;
749
750         # set +x bit if +r or +w were set
751         $rv |= 0100 if ($rv & 0600);
752         $rv |= 0010 if ($rv & 0060);
753         $rv |= 0001 if ($rv & 0006);
754         (~$rv & 0777);
755 }
756
757 sub with_umask {
758         my ($self, $cb) = @_;
759         my $old = umask $self->{umask};
760         my $rv = eval { $cb->() };
761         my $err = $@;
762         umask $old;
763         die $err if $err;
764         $rv;
765 }
766
767 sub DESTROY {
768         # order matters for unlocking
769         $_[0]->{xdb} = undef;
770         $_[0]->{lockfh} = undef;
771 }
772
773 1;