/
lucene-wrapper.cc
1639 lines (1403 loc) · 40.8 KB
/
lucene-wrapper.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright (c) 2006-2016 Dovecot authors, see the included COPYING file */
extern "C" {
#include "lib.h"
#include "array.h"
#include "unichar.h"
#include "hash.h"
#include "hex-binary.h"
#include "ioloop.h"
#include "unlink-directory.h"
#include "ioloop.h"
#include "mail-index.h"
#include "mail-search.h"
#include "mail-namespace.h"
#include "mailbox-list-private.h"
#include "mail-storage.h"
#include "fts-expunge-log.h"
#include "fts-lucene-plugin.h"
#include "lucene-wrapper.h"
#include <sys/stat.h>
#ifdef HAVE_LIBEXTTEXTCAT_TEXTCAT_H
# include <libexttextcat/textcat.h>
#elif defined (HAVE_LIBTEXTCAT_TEXTCAT_H)
# include <libtextcat/textcat.h>
#elif defined (HAVE_FTS_TEXTCAT)
# include <textcat.h>
#endif
};
#include <CLucene.h>
#include <CLucene/util/CLStreams.h>
#include <CLucene/search/MultiPhraseQuery.h>
#include "SnowballAnalyzer.h"
/* Lucene's default is 10000. Use it here also.. */
#define MAX_TERMS_PER_DOCUMENT 10000
#define FTS_LUCENE_MAX_SEARCH_TERMS 1000
#define LUCENE_LOCK_OVERRIDE_SECS 60
#define LUCENE_INDEX_CLOSE_TIMEOUT_MSECS (120*1000)
using namespace lucene::document;
using namespace lucene::index;
using namespace lucene::search;
using namespace lucene::queryParser;
using namespace lucene::analysis;
using namespace lucene::analysis;
using namespace lucene::util;
struct lucene_query {
Query *query;
BooleanClause::Occur occur;
};
ARRAY_DEFINE_TYPE(lucene_query, struct lucene_query);
struct lucene_analyzer {
char *lang;
Analyzer *analyzer;
};
struct lucene_index {
char *path;
struct mailbox_list *list;
struct fts_lucene_settings set;
normalizer_func_t *normalizer;
wchar_t mailbox_guid[MAILBOX_GUID_HEX_LENGTH + 1];
IndexReader *reader;
IndexWriter *writer;
IndexSearcher *searcher;
struct timeout *to_close;
buffer_t *normalizer_buf;
Analyzer *default_analyzer, *cur_analyzer;
ARRAY(struct lucene_analyzer) analyzers;
Document *doc;
uint32_t prev_uid, prev_part_idx;
bool no_analyzer;
};
struct rescan_context {
struct lucene_index *index;
struct mailbox *box;
guid_128_t box_guid;
int box_ret;
pool_t pool;
HASH_TABLE(uint8_t *, uint8_t *) seen_mailbox_guids;
ARRAY_TYPE(seq_range) uids;
struct seq_range_iter uids_iter;
unsigned int uids_iter_n;
uint32_t last_existing_uid;
bool warned;
};
static void *textcat = NULL;
#ifdef HAVE_FTS_TEXTCAT
static bool textcat_broken = FALSE;
#endif
static int textcat_refcount = 0;
static void lucene_handle_error(struct lucene_index *index, CLuceneError &err,
const char *msg);
static void rescan_clear_unseen_mailboxes(struct lucene_index *index,
struct rescan_context *rescan_ctx);
struct lucene_index *lucene_index_init(const char *path,
struct mailbox_list *list,
const struct fts_lucene_settings *set)
{
struct lucene_index *index;
index = i_new(struct lucene_index, 1);
index->path = i_strdup(path);
index->list = list;
if (set != NULL) {
index->set = *set;
index->normalizer = !set->normalize ? NULL :
mailbox_list_get_namespace(list)->user->default_normalizer;
} else {
/* this is valid only for doveadm dump, so it doesn't matter */
index->set.default_language = "";
}
if (index->set.use_libfts) {
index->default_analyzer = _CLNEW KeywordAnalyzer();
} else
#ifdef HAVE_FTS_STEMMER
if (set == NULL || !set->no_snowball) {
index->default_analyzer =
_CLNEW snowball::SnowballAnalyzer(index->normalizer,
index->set.default_language);
} else
#endif
{
index->default_analyzer = _CLNEW standard::StandardAnalyzer();
if (index->normalizer != NULL) {
index->normalizer_buf =
buffer_create_dynamic(default_pool, 1024);
}
}
i_array_init(&index->analyzers, 32);
textcat_refcount++;
return index;
}
void lucene_index_close(struct lucene_index *index)
{
if (index->to_close != NULL)
timeout_remove(&index->to_close);
_CLDELETE(index->searcher);
if (index->writer != NULL) {
try {
index->writer->close();
} catch (CLuceneError &err) {
lucene_handle_error(index, err, "IndexWriter::close");
}
_CLDELETE(index->writer);
}
if (index->reader != NULL) {
try {
index->reader->close();
} catch (CLuceneError &err) {
lucene_handle_error(index, err, "IndexReader::close");
}
_CLDELETE(index->reader);
}
}
void lucene_index_deinit(struct lucene_index *index)
{
struct lucene_analyzer *a;
lucene_index_close(index);
array_foreach_modifiable(&index->analyzers, a) {
i_free(a->lang);
_CLDELETE(a->analyzer);
}
array_free(&index->analyzers);
if (--textcat_refcount == 0 && textcat != NULL) {
#ifdef HAVE_FTS_TEXTCAT
textcat_Done(textcat);
#endif
textcat = NULL;
}
_CLDELETE(index->default_analyzer);
if (index->normalizer_buf != NULL)
buffer_free(&index->normalizer_buf);
i_free(index->path);
i_free(index);
}
static void lucene_data_translate(struct lucene_index *index,
wchar_t *data, unsigned int len)
{
const char *whitespace_chars = index->set.whitespace_chars;
unsigned int i;
if (*whitespace_chars == '\0' || index->set.use_libfts)
return;
for (i = 0; i < len; i++) {
if (strchr(whitespace_chars, data[i]) != NULL)
data[i] = ' ';
}
}
void lucene_utf8_n_to_tchar(const unsigned char *src, size_t srcsize,
wchar_t *dest, size_t destsize)
{
ARRAY_TYPE(unichars) dest_arr;
buffer_t buf = { 0, 0, { 0, 0, 0, 0, 0 } };
i_assert(sizeof(wchar_t) == sizeof(unichar_t));
buffer_create_from_data(&buf, dest, sizeof(wchar_t) * destsize);
array_create_from_buffer(&dest_arr, &buf, sizeof(wchar_t));
if (uni_utf8_to_ucs4_n(src, srcsize, &dest_arr) < 0)
i_unreached();
i_assert(array_count(&dest_arr)+1 == destsize);
dest[destsize-1] = 0;
}
static const wchar_t *
t_lucene_utf8_to_tchar(struct lucene_index *index, const char *str)
{
ARRAY_TYPE(unichars) dest_arr;
const unichar_t *chars;
wchar_t *ret;
unsigned int len;
i_assert(sizeof(wchar_t) == sizeof(unichar_t));
t_array_init(&dest_arr, strlen(str) + 1);
if (uni_utf8_to_ucs4(str, &dest_arr) < 0)
i_unreached();
(void)array_append_space(&dest_arr);
chars = array_get_modifiable(&dest_arr, &len);
ret = (wchar_t *)chars;
lucene_data_translate(index, ret, len - 1);
return ret;
}
void lucene_index_select_mailbox(struct lucene_index *index,
const wchar_t guid[MAILBOX_GUID_HEX_LENGTH])
{
memcpy(index->mailbox_guid, guid,
MAILBOX_GUID_HEX_LENGTH * sizeof(wchar_t));
index->mailbox_guid[MAILBOX_GUID_HEX_LENGTH] = '\0';
}
void lucene_index_unselect_mailbox(struct lucene_index *index)
{
memset(index->mailbox_guid, 0, sizeof(index->mailbox_guid));
}
static void lucene_handle_error(struct lucene_index *index, CLuceneError &err,
const char *msg)
{
const char *error, *what = err.what();
i_error("lucene index %s: %s failed (#%d): %s",
index->path, msg, err.number(), what);
if (index->list != NULL &&
(err.number() == CL_ERR_CorruptIndex ||
err.number() == CL_ERR_IO)) {
/* delete corrupted index. most IO errors are also about
missing files and other such corruption.. */
if (unlink_directory(index->path, (enum unlink_directory_flags)0, &error) < 0 &&
errno != ENOENT)
i_error("unlink_directory(%s) failed: %s", index->path, error);
rescan_clear_unseen_mailboxes(index, NULL);
}
}
static int lucene_index_open(struct lucene_index *index)
{
if (index->reader != NULL) {
i_assert(index->to_close != NULL);
timeout_reset(index->to_close);
return 1;
}
if (!IndexReader::indexExists(index->path))
return 0;
try {
index->reader = IndexReader::open(index->path);
} catch (CLuceneError &err) {
lucene_handle_error(index, err, "IndexReader::open()");
return -1;
}
i_assert(index->to_close == NULL);
index->to_close = timeout_add(LUCENE_INDEX_CLOSE_TIMEOUT_MSECS,
lucene_index_close, index);
return 1;
}
static int lucene_index_open_search(struct lucene_index *index)
{
int ret;
if (index->searcher != NULL)
return 1;
if ((ret = lucene_index_open(index)) <= 0)
return ret;
index->searcher = _CLNEW IndexSearcher(index->reader);
return 1;
}
static int
lucene_doc_get_uid(struct lucene_index *index, Document *doc, uint32_t *uid_r)
{
Field *field = doc->getField(_T("uid"));
const TCHAR *uid = field == NULL ? NULL : field->stringValue();
if (uid == NULL) {
i_error("lucene: Corrupted FTS index %s: No UID for document",
index->path);
return -1;
}
uint32_t num = 0;
while (*uid != 0) {
num = num*10 + (*uid - '0');
uid++;
}
*uid_r = num;
return 0;
}
static uint32_t
lucene_doc_get_part(struct lucene_index *index, Document *doc)
{
Field *field = doc->getField(_T("part"));
const TCHAR *part = field == NULL ? NULL : field->stringValue();
if (part == NULL)
return 0;
uint32_t num = 0;
while (*part != 0) {
num = num*10 + (*part - '0');
part++;
}
return num;
}
int lucene_index_get_last_uid(struct lucene_index *index, uint32_t *last_uid_r)
{
int ret = 0;
*last_uid_r = 0;
if ((ret = lucene_index_open_search(index)) <= 0)
return ret;
Term mailbox_term(_T("box"), index->mailbox_guid);
TermQuery query(&mailbox_term);
uint32_t last_uid = 0;
try {
Hits *hits = index->searcher->search(&query);
for (size_t i = 0; i < hits->length(); i++) {
uint32_t uid;
if (lucene_doc_get_uid(index, &hits->doc(i),
&uid) < 0) {
ret = -1;
break;
}
if (uid > last_uid)
last_uid = uid;
}
_CLDELETE(hits);
} catch (CLuceneError &err) {
lucene_handle_error(index, err, "last_uid search");
ret = -1;
}
*last_uid_r = last_uid;
return ret;
}
int lucene_index_get_doc_count(struct lucene_index *index, uint32_t *count_r)
{
int ret;
if (index->reader == NULL) {
lucene_index_close(index);
if ((ret = lucene_index_open(index)) < 0)
return -1;
if (ret == 0) {
*count_r = 0;
return 0;
}
}
*count_r = index->reader->numDocs();
return 0;
}
static int lucene_settings_check(struct lucene_index *index)
{
uint32_t set_checksum;
const char *error;
int ret = 0;
set_checksum = fts_lucene_settings_checksum(&index->set);
ret = fts_index_have_compatible_settings(index->list, set_checksum);
if (ret != 0)
return ret;
i_warning("fts-lucene: Settings have changed, rebuilding index for mailbox");
/* settings changed, rebuild index */
if (unlink_directory(index->path, (enum unlink_directory_flags)0, &error) < 0) {
i_error("unlink_directory(%s) failed: %s", index->path, error);
ret = -1;
} else {
rescan_clear_unseen_mailboxes(index, NULL);
}
return ret;
}
int lucene_index_build_init(struct lucene_index *index)
{
const char *lock_path;
struct stat st;
lucene_index_close(index);
lock_path = t_strdup_printf("%s/write.lock", index->path);
if (stat(lock_path, &st) == 0 &&
st.st_mtime < time(NULL) - LUCENE_LOCK_OVERRIDE_SECS) {
if (unlink(lock_path) < 0)
i_error("unlink(%s) failed: %m", lock_path);
}
if (lucene_settings_check(index) < 0)
return -1;
bool exists = IndexReader::indexExists(index->path);
try {
index->writer = _CLNEW IndexWriter(index->path,
index->default_analyzer,
!exists);
} catch (CLuceneError &err) {
lucene_handle_error(index, err, "IndexWriter()");
return -1;
}
index->writer->setMaxFieldLength(MAX_TERMS_PER_DOCUMENT);
return 0;
}
#ifdef HAVE_FTS_TEXTCAT
static Analyzer *get_analyzer(struct lucene_index *index, const char *lang)
{
normalizer_func_t *normalizer = index->normalizer;
const struct lucene_analyzer *a;
struct lucene_analyzer new_analyzer;
Analyzer *analyzer;
array_foreach(&index->analyzers, a) {
if (strcmp(a->lang, lang) == 0)
return a->analyzer;
}
memset(&new_analyzer, 0, sizeof(new_analyzer));
new_analyzer.lang = i_strdup(lang);
new_analyzer.analyzer =
_CLNEW snowball::SnowballAnalyzer(normalizer, lang);
array_append_i(&index->analyzers.arr, &new_analyzer, 1);
return new_analyzer.analyzer;
}
static void *textcat_init(struct lucene_index *index)
{
const char *textcat_dir = index->set.textcat_dir;
unsigned int len;
if (textcat_dir == NULL)
return NULL;
/* textcat really wants the '/' suffix */
len = strlen(textcat_dir);
if (len > 0 && textcat_dir[len-1] != '/')
textcat_dir = t_strconcat(textcat_dir, "/", NULL);
return special_textcat_Init(index->set.textcat_conf, textcat_dir);
}
static Analyzer *
guess_analyzer(struct lucene_index *index, const void *data, size_t size)
{
const char *lang;
if (textcat_broken)
return NULL;
if (textcat == NULL) {
textcat = textcat_init(index);
if (textcat == NULL) {
textcat_broken = TRUE;
return NULL;
}
}
/* try to guess the language */
lang = textcat_Classify(textcat, (const char *)data,
I_MIN(size, 500));
const char *p = strchr(lang, ']');
if (lang[0] != '[' || p == NULL)
return NULL;
lang = t_strdup_until(lang+1, p);
if (strcmp(lang, index->set.default_language) == 0)
return index->default_analyzer;
return get_analyzer(index, lang);
}
#else
static Analyzer *
guess_analyzer(struct lucene_index *index ATTR_UNUSED,
const void *data ATTR_UNUSED, size_t size ATTR_UNUSED)
{
return NULL;
}
#endif
static int lucene_index_build_flush(struct lucene_index *index)
{
int ret = 0;
if (index->doc == NULL)
return 0;
try {
CL_NS(analysis)::Analyzer *analyzer = NULL;
if (!index->set.use_libfts) {
analyzer = index->cur_analyzer != NULL ?
index->cur_analyzer : index->default_analyzer;
}
index->writer->addDocument(index->doc, analyzer);
} catch (CLuceneError &err) {
lucene_handle_error(index, err, "IndexWriter::addDocument()");
ret = -1;
}
_CLDELETE(index->doc);
index->doc = NULL;
index->cur_analyzer = NULL;
return ret;
}
int lucene_index_build_more(struct lucene_index *index, uint32_t uid,
uint32_t part_idx, const unsigned char *data,
size_t size, const char *hdr_name)
{
wchar_t id[MAX_INT_STRLEN];
size_t namesize, datasize;
if (uid != index->prev_uid || part_idx != index->prev_part_idx) {
if (lucene_index_build_flush(index) < 0)
return -1;
index->prev_uid = uid;
index->prev_part_idx = part_idx;
index->doc = _CLNEW Document();
swprintf(id, N_ELEMENTS(id), L"%u", uid);
index->doc->add(*_CLNEW Field(_T("uid"), id, Field::STORE_YES | Field::INDEX_UNTOKENIZED));
if (part_idx != 0) {
swprintf(id, N_ELEMENTS(id), L"%u", part_idx);
index->doc->add(*_CLNEW Field(_T("part"), id, Field::STORE_YES | Field::INDEX_UNTOKENIZED));
}
index->doc->add(*_CLNEW Field(_T("box"), index->mailbox_guid, Field::STORE_YES | Field::INDEX_UNTOKENIZED));
}
if (index->normalizer_buf != NULL && !index->set.use_libfts) {
buffer_set_used_size(index->normalizer_buf, 0);
index->normalizer(data, size, index->normalizer_buf);
data = (const unsigned char *)index->normalizer_buf->data;
size = index->normalizer_buf->used;
}
datasize = uni_utf8_strlen_n(data, size) + 1;
wchar_t *dest, *dest_free = NULL;
if (datasize < 4096)
dest = t_new(wchar_t, datasize);
else
dest = dest_free = i_new(wchar_t, datasize);
lucene_utf8_n_to_tchar(data, size, dest, datasize);
lucene_data_translate(index, dest, datasize-1);
int token_flag = index->set.use_libfts ?
Field::INDEX_UNTOKENIZED : Field::INDEX_TOKENIZED;
if (hdr_name != NULL) {
/* hdr_name should be ASCII, but don't break in case it isn't */
hdr_name = t_str_lcase(hdr_name);
namesize = uni_utf8_strlen(hdr_name) + 1;
wchar_t wname[namesize];
lucene_utf8_n_to_tchar((const unsigned char *)hdr_name,
strlen(hdr_name), wname, namesize);
if (!index->set.use_libfts)
index->doc->add(*_CLNEW Field(_T("hdr"), wname, Field::STORE_NO | token_flag));
index->doc->add(*_CLNEW Field(_T("hdr"), dest, Field::STORE_NO | token_flag));
if (fts_header_want_indexed(hdr_name))
index->doc->add(*_CLNEW Field(wname, dest, Field::STORE_NO | token_flag));
} else if (size > 0) {
if (index->cur_analyzer == NULL && !index->set.use_libfts)
index->cur_analyzer = guess_analyzer(index, data, size);
index->doc->add(*_CLNEW Field(_T("body"), dest, Field::STORE_NO | token_flag));
}
i_free(dest_free);
return 0;
}
int lucene_index_build_deinit(struct lucene_index *index)
{
int ret = 0;
if (index->prev_uid == 0) {
/* no changes. */
return 0;
}
index->prev_uid = 0;
index->prev_part_idx = 0;
if (index->writer == NULL) {
lucene_index_close(index);
return -1;
}
if (lucene_index_build_flush(index) < 0)
ret = -1;
try {
index->writer->close();
} catch (CLuceneError &err) {
lucene_handle_error(index, err, "IndexWriter::close()");
ret = -1;
}
lucene_index_close(index);
return ret;
}
static int
wcharguid_to_guid(guid_128_t dest, const wchar_t *src)
{
buffer_t buf = { 0, 0, { 0, 0, 0, 0, 0 } };
char src_chars[GUID_128_SIZE*2 + 1];
unsigned int i;
for (i = 0; i < sizeof(src_chars)-1; i++) {
if ((src[i] >= '0' && src[i] <= '9') ||
(src[i] >= 'a' && src[i] <= 'f'))
src_chars[i] = src[i];
else
return -1;
}
if (src[i] != '\0')
return -1;
src_chars[i] = '\0';
buffer_create_from_data(&buf, dest, GUID_128_SIZE);
return hex_to_binary(src_chars, &buf);
}
static int
rescan_get_uids(struct mailbox *box, ARRAY_TYPE(seq_range) *uids)
{
struct mailbox_status status;
if (mailbox_get_status(box, STATUS_MESSAGES, &status) < 0)
return -1;
if (status.messages > 0) T_BEGIN {
ARRAY_TYPE(seq_range) seqs;
t_array_init(&seqs, 2);
seq_range_array_add_range(&seqs, 1, status.messages);
mailbox_get_uid_range(box, &seqs, uids);
} T_END;
return 0;
}
static int rescan_finish(struct rescan_context *ctx)
{
int ret;
ret = fts_index_set_last_uid(ctx->box, ctx->last_existing_uid);
mailbox_free(&ctx->box);
return ret;
}
static int
fts_lucene_get_mailbox_guid(struct lucene_index *index, Document *doc,
guid_128_t guid_r)
{
Field *field = doc->getField(_T("box"));
const TCHAR *box_guid = field == NULL ? NULL : field->stringValue();
if (box_guid == NULL) {
i_error("lucene: Corrupted FTS index %s: No mailbox for document",
index->path);
return -1;
}
if (wcharguid_to_guid(guid_r, box_guid) < 0) {
i_error("lucene: Corrupted FTS index %s: "
"box field not in expected format", index->path);
return -1;
}
return 0;
}
static int
rescan_open_mailbox(struct rescan_context *ctx, Document *doc)
{
guid_128_t guid, *guidp;
int ret;
if (fts_lucene_get_mailbox_guid(ctx->index, doc, guid) < 0)
return 0;
if (memcmp(guid, ctx->box_guid, sizeof(guid)) == 0) {
/* same as last one */
return ctx->box_ret;
}
memcpy(ctx->box_guid, guid, sizeof(ctx->box_guid));
guidp = p_new(ctx->pool, guid_128_t, 1);
memcpy(guidp, guid, sizeof(*guidp));
hash_table_insert(ctx->seen_mailbox_guids, guidp, guidp);
if (ctx->box != NULL)
rescan_finish(ctx);
ctx->box = mailbox_alloc_guid(ctx->index->list, guid,
(enum mailbox_flags)0);
if (mailbox_open(ctx->box) < 0) {
enum mail_error error;
const char *errstr;
errstr = mailbox_get_last_error(ctx->box, &error);
if (error == MAIL_ERROR_NOTFOUND)
ret = 0;
else {
i_error("lucene: Couldn't open mailbox %s: %s",
mailbox_get_vname(ctx->box), errstr);
ret = -1;
}
mailbox_free(&ctx->box);
ctx->box_ret = ret;
return ret;
}
if (mailbox_sync(ctx->box, (enum mailbox_sync_flags)0) < 0) {
i_error("lucene: Failed to sync mailbox %s: %s",
mailbox_get_vname(ctx->box),
mailbox_get_last_error(ctx->box, NULL));
mailbox_free(&ctx->box);
ctx->box_ret = -1;
return -1;
}
array_clear(&ctx->uids);
rescan_get_uids(ctx->box, &ctx->uids);
ctx->warned = FALSE;
ctx->last_existing_uid = 0;
ctx->uids_iter_n = 0;
seq_range_array_iter_init(&ctx->uids_iter, &ctx->uids);
ctx->box_ret = 1;
return 1;
}
static int
rescan_next(struct rescan_context *ctx, Document *doc)
{
uint32_t lucene_uid, idx_uid;
if (lucene_doc_get_uid(ctx->index, doc, &lucene_uid) < 0)
return 0;
if (seq_range_array_iter_nth(&ctx->uids_iter, ctx->uids_iter_n,
&idx_uid)) {
if (idx_uid == lucene_uid) {
ctx->uids_iter_n++;
ctx->last_existing_uid = idx_uid;
return 1;
}
if (idx_uid < lucene_uid) {
/* lucene is missing an UID from the middle. delete
the rest of the messages from this mailbox and
reindex. */
if (!ctx->warned) {
i_warning("lucene: Mailbox %s "
"missing UIDs in the middle",
mailbox_get_vname(ctx->box));
ctx->warned = TRUE;
}
} else {
/* UID has been expunged from index. delete from
lucene as well. */
}
return 0;
} else {
/* the rest of the messages have been expunged from index */
return 0;
}
}
static void
rescan_clear_unseen_mailbox(struct lucene_index *index,
struct rescan_context *rescan_ctx,
const char *vname,
const struct fts_index_header *hdr)
{
struct mailbox *box;
struct mailbox_metadata metadata;
box = mailbox_alloc(index->list, vname,
(enum mailbox_flags)0);
if (mailbox_open(box) == 0 &&
mailbox_get_metadata(box, MAILBOX_METADATA_GUID,
&metadata) == 0 &&
(rescan_ctx == NULL ||
hash_table_lookup(rescan_ctx->seen_mailbox_guids,
metadata.guid) == NULL)) {
/* this mailbox had no records in lucene index.
make sure its last indexed uid is 0 */
(void)fts_index_set_header(box, hdr);
}
mailbox_free(&box);
}
static void rescan_clear_unseen_mailboxes(struct lucene_index *index,
struct rescan_context *rescan_ctx)
{
const enum mailbox_list_iter_flags iter_flags =
(enum mailbox_list_iter_flags)
(MAILBOX_LIST_ITER_NO_AUTO_BOXES |
MAILBOX_LIST_ITER_RETURN_NO_FLAGS);
struct mailbox_list_iterate_context *iter;
const struct mailbox_info *info;
struct fts_index_header hdr;
struct mail_namespace *ns = index->list->ns;
const char *vname;
memset(&hdr, 0, sizeof(hdr));
hdr.settings_checksum = fts_lucene_settings_checksum(&index->set);
iter = mailbox_list_iter_init(index->list, "*", iter_flags);
while ((info = mailbox_list_iter_next(iter)) != NULL)
rescan_clear_unseen_mailbox(index, rescan_ctx, info->vname, &hdr);
(void)mailbox_list_iter_deinit(&iter);
if (ns->prefix_len > 0 &&
ns->prefix[ns->prefix_len-1] == mail_namespace_get_sep(ns)) {
/* namespace prefix itself isn't returned by the listing */
vname = t_strndup(index->list->ns->prefix,
index->list->ns->prefix_len-1);
rescan_clear_unseen_mailbox(index, rescan_ctx, vname, &hdr);
}
}
int lucene_index_rescan(struct lucene_index *index)
{
static const TCHAR *sort_fields[] = { _T("box"), _T("uid"), NULL };
struct rescan_context ctx;
bool failed = false;
int ret;
i_assert(index->list != NULL);
if ((ret = lucene_index_open_search(index)) < 0)
return ret;
Term term(_T("box"), _T("*"));
WildcardQuery query(&term);
Sort sort(sort_fields);
memset(&ctx, 0, sizeof(ctx));
ctx.index = index;
ctx.pool = pool_alloconly_create("guids", 1024);
hash_table_create(&ctx.seen_mailbox_guids, ctx.pool, 0,
guid_128_hash, guid_128_cmp);
i_array_init(&ctx.uids, 128);
if (ret > 0) try {
Hits *hits = index->searcher->search(&query, &sort);
for (size_t i = 0; i < hits->length(); i++) {
ret = rescan_open_mailbox(&ctx, &hits->doc(i));
if (ret > 0)
ret = rescan_next(&ctx, &hits->doc(i));
if (ret < 0)
failed = true;
else if (ret == 0)
index->reader->deleteDocument(hits->id(i));
}
_CLDELETE(hits);
} catch (CLuceneError &err) {
lucene_handle_error(index, err, "rescan search");
failed = true;
}
lucene_index_close(index);
if (ctx.box != NULL)
rescan_finish(&ctx);
array_free(&ctx.uids);
rescan_clear_unseen_mailboxes(index, &ctx);
hash_table_destroy(&ctx.seen_mailbox_guids);
pool_unref(&ctx.pool);
return failed ? -1 : 0;
}
static void guid128_to_wguid(const guid_128_t guid,
wchar_t wguid_hex[MAILBOX_GUID_HEX_LENGTH + 1])
{
buffer_t buf = { 0, 0, { 0, 0, 0, 0, 0 } };
unsigned char guid_hex[MAILBOX_GUID_HEX_LENGTH];
unsigned int i;
buffer_create_from_data(&buf, guid_hex, MAILBOX_GUID_HEX_LENGTH);
binary_to_hex_append(&buf, guid, GUID_128_SIZE);
for (i = 0; i < MAILBOX_GUID_HEX_LENGTH; i++)
wguid_hex[i] = guid_hex[i];
wguid_hex[i] = '\0';
}
static bool
lucene_index_add_uid_filter(BooleanQuery *query,
const struct fts_expunge_log_read_record *rec)
{
struct seq_range_iter iter;
wchar_t wuid[MAX_INT_STRLEN];
unsigned int n;
uint32_t uid;
/* RangeQuery and WildcardQuery work by enumerating through all terms
that match them, and then adding TermQueries for them. So we can
simply do the same directly, and if it looks like there are too
many terms just go through everything. */
if (seq_range_count(&rec->uids) > FTS_LUCENE_MAX_SEARCH_TERMS)
return false;
seq_range_array_iter_init(&iter, &rec->uids); n = 0;
while (seq_range_array_iter_nth(&iter, n++, &uid)) {
swprintf(wuid, N_ELEMENTS(wuid), L"%u", uid);
Term *term = _CLNEW Term(_T("uid"), wuid);
query->add(_CLNEW TermQuery(term), true, BooleanClause::SHOULD);
_CLDECDELETE(term);
}
return true;
}
static int
lucene_index_expunge_record(struct lucene_index *index,
const struct fts_expunge_log_read_record *rec)
{
int ret;
if ((ret = lucene_index_open_search(index)) <= 0)
return ret;
BooleanQuery query;
BooleanQuery uids_query;
if (lucene_index_add_uid_filter(&uids_query, rec))
query.add(&uids_query, BooleanClause::MUST);
wchar_t wguid[MAILBOX_GUID_HEX_LENGTH + 1];
guid128_to_wguid(rec->mailbox_guid, wguid);
Term term(_T("box"), wguid);
TermQuery mailbox_query(&term);
query.add(&mailbox_query, BooleanClause::MUST);
try {
Hits *hits = index->searcher->search(&query);
for (size_t i = 0; i < hits->length(); i++) {
uint32_t uid;
if (lucene_doc_get_uid(index, &hits->doc(i),
&uid) < 0 ||
seq_range_exists(&rec->uids, uid))
index->reader->deleteDocument(hits->id(i));