3709ef6319398c3515143af9871a7e473e9fcdfc
[citadel.git] / citadel / modules / fulltext / serv_fulltext.c
1 /*
2  * This module handles fulltext indexing of the message base.
3  * Copyright (c) 2005-2015 by the citadel.org team
4  *
5  * This program is open source software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License as published
7  * by the Free Software Foundation; either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18  */
19
20 #include "sysdep.h"
21 #include <stdlib.h>
22 #include <unistd.h>
23 #include <stdio.h>
24 #include <fcntl.h>
25 #include <signal.h>
26 #include <pwd.h>
27 #include <errno.h>
28 #include <sys/types.h>
29
30 #if TIME_WITH_SYS_TIME
31 # include <sys/time.h>
32 # include <time.h>
33 #else
34 # if HAVE_SYS_TIME_H
35 #  include <sys/time.h>
36 # else
37 #  include <time.h>
38 # endif
39 #endif
40
41 #include <sys/wait.h>
42 #include <string.h>
43 #include <limits.h>
44 #include <libcitadel.h>
45 #include "citadel.h"
46 #include "server.h"
47 #include "citserver.h"
48 #include "support.h"
49 #include "config.h"
50 #include "database.h"
51 #include "msgbase.h"
52 #include "control.h"
53 #include "serv_fulltext.h"
54 #include "ft_wordbreaker.h"
55 #include "threads.h"
56 #include "context.h"
57
58 #include "ctdl_module.h"
59
60 long ft_newhighest = 0L;
61 long *ft_newmsgs = NULL;
62 int ft_num_msgs = 0;
63 int ft_num_alloc = 0;
64
65 int ftc_num_msgs[65536];
66 long *ftc_msgs[65536];
67
68
69 /*
70  * Compare function
71  */
72 int longcmp(const void *rec1, const void *rec2) {
73         long i1, i2;
74
75         i1 = *(const long *)rec1;
76         i2 = *(const long *)rec2;
77
78         if (i1 > i2) return(1);
79         if (i1 < i2) return(-1);
80         return(0);
81 }
82
83 /*
84  * Flush our index cache out to disk.
85  */
86 void ft_flush_cache(void) {
87         int i;
88         time_t last_update = 0;
89
90         for (i=0; i<65536; ++i) {
91                 if ((time(NULL) - last_update) >= 10) {
92                         syslog(LOG_INFO,
93                                 "Flushing index cache to disk (%d%% complete)",
94                                 (i * 100 / 65536)
95                         );
96                         last_update = time(NULL);
97                 }
98                 if (ftc_msgs[i] != NULL) {
99                         cdb_store(CDB_FULLTEXT, &i, sizeof(int), ftc_msgs[i],
100                                 (ftc_num_msgs[i] * sizeof(long)));
101                         ftc_num_msgs[i] = 0;
102                         free(ftc_msgs[i]);
103                         ftc_msgs[i] = NULL;
104                 }
105         }
106         syslog(LOG_INFO, "Flushed index cache to disk (100%% complete)");
107 }
108
109
110 /*
111  * Index or de-index a message.  (op == 1 to index, 0 to de-index)
112  */
113 void ft_index_message(long msgnum, int op) {
114         int num_tokens = 0;
115         int *tokens = NULL;
116         int i, j;
117         struct cdbdata *cdb_bucket;
118         StrBuf *msgtext;
119         char *txt;
120         int tok;
121         struct CtdlMessage *msg = NULL;
122
123         msg = CtdlFetchMessage(msgnum, 1, 1);
124         if (msg == NULL) {
125                 syslog(LOG_ERR, "ft_index_message() could not load msg %ld", msgnum);
126                 return;
127         }
128
129         if (!CM_IsEmpty(msg, eSuppressIdx)) {
130                 syslog(LOG_DEBUG, "ft_index_message() excluded msg %ld", msgnum);
131                 CM_Free(msg);
132                 return;
133         }
134
135         syslog(LOG_DEBUG, "ft_index_message() %s msg %ld", (op ? "adding" : "removing") , msgnum);
136
137         /* Output the message as text before indexing it, so we don't end up
138          * indexing a bunch of encoded base64, etc.
139          */
140         CC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
141         CtdlOutputPreLoadedMsg(msg, MT_CITADEL, HEADERS_ALL, 0, 1, 0);
142         CM_Free(msg);
143         msgtext = CC->redirect_buffer;
144         CC->redirect_buffer = NULL;
145         if (msgtext != NULL) {
146                 syslog(LOG_DEBUG, "Wordbreaking message %ld (%d bytes)", msgnum, StrLength(msgtext));
147         }
148         txt = SmashStrBuf(&msgtext);
149         wordbreaker(txt, &num_tokens, &tokens);
150         free(txt);
151
152         syslog(LOG_DEBUG, "Indexing message %ld [%d tokens]", msgnum, num_tokens);
153         if (num_tokens > 0) {
154                 for (i=0; i<num_tokens; ++i) {
155
156                         /* Add the message to the relevant token bucket */
157
158                         /* search for tokens[i] */
159                         tok = tokens[i];
160
161                         if ( (tok >= 0) && (tok <= 65535) ) {
162                                 /* fetch the bucket, Liza */
163                                 if (ftc_msgs[tok] == NULL) {
164                                         cdb_bucket = cdb_fetch(CDB_FULLTEXT, &tok, sizeof(int));
165                                         if (cdb_bucket != NULL) {
166                                                 ftc_num_msgs[tok] = cdb_bucket->len / sizeof(long);
167                                                 ftc_msgs[tok] = (long *)cdb_bucket->ptr;
168                                                 cdb_bucket->ptr = NULL;
169                                                 cdb_free(cdb_bucket);
170                                         }
171                                         else {
172                                                 ftc_num_msgs[tok] = 0;
173                                                 ftc_msgs[tok] = malloc(sizeof(long));
174                                         }
175                                 }
176         
177         
178                                 if (op == 1) {  /* add to index */
179                                         ++ftc_num_msgs[tok];
180                                         ftc_msgs[tok] = realloc(ftc_msgs[tok],
181                                                                 ftc_num_msgs[tok]*sizeof(long));
182                                         ftc_msgs[tok][ftc_num_msgs[tok] - 1] = msgnum;
183                                 }
184         
185                                 if (op == 0) {  /* remove from index */
186                                         if (ftc_num_msgs[tok] >= 1) {
187                                                 for (j=0; j<ftc_num_msgs[tok]; ++j) {
188                                                         if (ftc_msgs[tok][j] == msgnum) {
189                                                                 memmove(&ftc_msgs[tok][j], &ftc_msgs[tok][j+1], ((ftc_num_msgs[tok] - j - 1)*sizeof(long)));
190                                                                 --ftc_num_msgs[tok];
191                                                                 --j;
192                                                         }
193                                                 }
194                                         }
195                                 }
196                         }
197                         else {
198                                 syslog(LOG_ALERT, "Invalid token %d !!", tok);
199                         }
200                 }
201
202                 free(tokens);
203         }
204 }
205
206
207
208 /*
209  * Add a message to the list of those to be indexed.
210  */
211 void ft_index_msg(long msgnum, void *userdata) {
212
213         if ((msgnum > CtdlGetConfigLong("MMfulltext")) && (msgnum <= ft_newhighest)) {
214                 ++ft_num_msgs;
215                 if (ft_num_msgs > ft_num_alloc) {
216                         ft_num_alloc += 1024;
217                         ft_newmsgs = realloc(ft_newmsgs,
218                                 (ft_num_alloc * sizeof(long)));
219                 }
220                 ft_newmsgs[ft_num_msgs - 1] = msgnum;
221         }
222
223 }
224
225 /*
226  * Scan a room for messages to index.
227  */
228 void ft_index_room(struct ctdlroom *qrbuf, void *data)
229 {
230         if (server_shutting_down)
231                 return;
232                 
233         CtdlGetRoom(&CC->room, qrbuf->QRname);
234         CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL, ft_index_msg, NULL);
235 }
236
237
238 /*
239  * Begin the fulltext indexing process.
240  */
241 void do_fulltext_indexing(void) {
242         int i;
243         static time_t last_index = 0L;
244         static time_t last_progress = 0L;
245         time_t run_time = 0L;
246         time_t end_time = 0L;
247         static int is_running = 0;
248         if (is_running) return;         /* Concurrency check - only one can run */
249         is_running = 1;
250         
251         /*
252          * Don't do this if the site doesn't have it enabled.
253          */
254         if (!CtdlGetConfigInt("c_enable_fulltext")) {
255                 return;
256         }
257
258         /*
259          * Make sure we don't run the indexer too frequently.
260          * FIXME move the setting into config
261          */
262  
263         if ( (time(NULL) - last_index) < 300L) {
264                 return;
265         }
266
267         /*
268          * Check to see whether the fulltext index is up to date; if there
269          * are no messages to index, don't waste any more time trying.
270          */
271         if (
272                 (CtdlGetConfigLong("MMfulltext") >= CtdlGetConfigLong("MMhighest"))
273                 && (CtdlGetConfigInt("MM_fulltext_wordbreaker") == FT_WORDBREAKER_ID)
274         ) {
275                 return;         /* nothing to do! */
276         }
277         
278         run_time = time(NULL);
279         syslog(LOG_DEBUG, "do_fulltext_indexing() started (%ld)", run_time);
280         
281         /*
282          * If we've switched wordbreaker modules, burn the index and start
283          * over.
284          */
285         begin_critical_section(S_CONTROL);
286         if (CtdlGetConfigInt("MM_fulltext_wordbreaker") != FT_WORDBREAKER_ID) {
287                 syslog(LOG_DEBUG, "wb ver on disk = %d, code ver = %d",
288                         CtdlGetConfigInt("MM_fulltext_wordbreaker"), FT_WORDBREAKER_ID
289                 );
290                 syslog(LOG_INFO, "(re)initializing full text index");
291                 cdb_trunc(CDB_FULLTEXT);
292                 CtdlSetConfigLong("MMfulltext", 0);
293         }
294         end_critical_section(S_CONTROL);
295
296         /*
297          * Now go through each room and find messages to index.
298          */
299         ft_newhighest = CtdlGetConfigLong("MMhighest");
300         CtdlForEachRoom(ft_index_room, NULL);   /* load all msg pointers */
301
302         if (ft_num_msgs > 0) {
303                 qsort(ft_newmsgs, ft_num_msgs, sizeof(long), longcmp);
304                 for (i=0; i<(ft_num_msgs-1); ++i) { /* purge dups */
305                         if (ft_newmsgs[i] == ft_newmsgs[i+1]) {
306                                 memmove(&ft_newmsgs[i], &ft_newmsgs[i+1],
307                                         ((ft_num_msgs - i - 1)*sizeof(long)));
308                                 --ft_num_msgs;
309                                 --i;
310                         }
311                 }
312
313                 /* Here it is ... do each message! */
314                 for (i=0; i<ft_num_msgs; ++i) {
315                         if (time(NULL) != last_progress) {
316                                 syslog(LOG_DEBUG,
317                                         "Indexed %d of %d messages (%d%%)",
318                                                 i, ft_num_msgs,
319                                                 ((i*100) / ft_num_msgs)
320                                 );
321                                 last_progress = time(NULL);
322                         }
323                         ft_index_message(ft_newmsgs[i], 1);
324
325                         /* Check to see if we need to quit early */
326                         if (server_shutting_down) {
327                                 syslog(LOG_DEBUG, "Indexer quitting early");
328                                 ft_newhighest = ft_newmsgs[i];
329                                 break;
330                         }
331
332                         /* Check to see if we have to maybe flush to disk */
333                         if (i >= FT_MAX_CACHE) {
334                                 syslog(LOG_DEBUG, "Time to flush.");
335                                 ft_newhighest = ft_newmsgs[i];
336                                 break;
337                         }
338
339                 }
340
341                 free(ft_newmsgs);
342                 ft_num_msgs = 0;
343                 ft_num_alloc = 0;
344                 ft_newmsgs = NULL;
345         }
346         end_time = time(NULL);
347
348         if (server_shutting_down) {
349                 is_running = 0;
350                 return;
351         }
352         
353         syslog(LOG_DEBUG, "do_fulltext_indexing() duration (%ld)", end_time - run_time);
354                 
355         /* Save our place so we don't have to do this again */
356         ft_flush_cache();
357         begin_critical_section(S_CONTROL);
358         CtdlSetConfigLong("MMfulltext", ft_newhighest);
359         CtdlSetConfigInt("MM_fulltext_wordbreaker", FT_WORDBREAKER_ID);
360         end_critical_section(S_CONTROL);
361         last_index = time(NULL);
362
363         syslog(LOG_DEBUG, "do_fulltext_indexing() finished");
364         is_running = 0;
365         return;
366 }
367
368
369
370 /*
371  * API call to perform searches.
372  * (This one does the "all of these words" search.)
373  * Caller is responsible for freeing the message list.
374  */
375 void ft_search(int *fts_num_msgs, long **fts_msgs, const char *search_string) {
376         int num_tokens = 0;
377         int *tokens = NULL;
378         int i, j;
379         struct cdbdata *cdb_bucket;
380         int num_all_msgs = 0;
381         long *all_msgs = NULL;
382         int num_ret_msgs = 0;
383         int num_ret_alloc = 0;
384         long *ret_msgs = NULL;
385         int tok;
386
387         wordbreaker(search_string, &num_tokens, &tokens);
388         if (num_tokens > 0) {
389                 for (i=0; i<num_tokens; ++i) {
390
391                         /* search for tokens[i] */
392                         tok = tokens[i];
393
394                         /* fetch the bucket, Liza */
395                         if (ftc_msgs[tok] == NULL) {
396                                 cdb_bucket = cdb_fetch(CDB_FULLTEXT, &tok, sizeof(int));
397                                 if (cdb_bucket != NULL) {
398                                         ftc_num_msgs[tok] = cdb_bucket->len / sizeof(long);
399                                         ftc_msgs[tok] = (long *)cdb_bucket->ptr;
400                                         cdb_bucket->ptr = NULL;
401                                         cdb_free(cdb_bucket);
402                                 }
403                                 else {
404                                         ftc_num_msgs[tok] = 0;
405                                         ftc_msgs[tok] = malloc(sizeof(long));
406                                 }
407                         }
408
409                         num_all_msgs += ftc_num_msgs[tok];
410                         if (num_all_msgs > 0) {
411                                 all_msgs = realloc(all_msgs, num_all_msgs*sizeof(long) );
412                                 memcpy(&all_msgs[num_all_msgs-ftc_num_msgs[tok]],
413                                         ftc_msgs[tok], ftc_num_msgs[tok]*sizeof(long) );
414                         }
415
416                 }
417                 free(tokens);
418                 if (all_msgs != NULL) {
419                         qsort(all_msgs, num_all_msgs, sizeof(long), longcmp);
420
421                         /*
422                          * At this point, if a message appears num_tokens times in the
423                          * list, then it contains all of the search tokens.
424                          */
425                         if (num_all_msgs >= num_tokens)
426                                 for (j=0; j<(num_all_msgs-num_tokens+1); ++j) {
427                                         if (all_msgs[j] == all_msgs[j+num_tokens-1]) {
428                                                 
429                                                 ++num_ret_msgs;
430                                                 if (num_ret_msgs > num_ret_alloc) {
431                                                         num_ret_alloc += 64;
432                                                         ret_msgs = realloc(ret_msgs,
433                                                                            (num_ret_alloc*sizeof(long)) );
434                                                 }
435                                                 ret_msgs[num_ret_msgs - 1] = all_msgs[j];
436                                                 
437                                         }
438                                 }
439                         free(all_msgs);
440                 }
441         }
442
443         *fts_num_msgs = num_ret_msgs;
444         *fts_msgs = ret_msgs;
445 }
446
447
448 /*
449  * This search command is for diagnostic purposes and may be removed or replaced.
450  */
451 void cmd_srch(char *argbuf) {
452         int num_msgs = 0;
453         long *msgs = NULL;
454         int i;
455         char search_string[256];
456
457         if (CtdlAccessCheck(ac_logged_in)) return;
458
459         if (!CtdlGetConfigInt("c_enable_fulltext")) {
460                 cprintf("%d Full text index is not enabled on this server.\n",
461                         ERROR + CMD_NOT_SUPPORTED);
462                 return;
463         }
464
465         extract_token(search_string, argbuf, 0, '|', sizeof search_string);
466         ft_search(&num_msgs, &msgs, search_string);
467
468         cprintf("%d %d msgs match all search words:\n",
469                 LISTING_FOLLOWS, num_msgs);
470         if (num_msgs > 0) {
471                 for (i=0; i<num_msgs; ++i) {
472                         cprintf("%ld\n", msgs[i]);
473                 }
474         }
475         if (msgs != NULL) free(msgs);
476         cprintf("000\n");
477 }
478
479 /*
480  * Zero out our index cache.
481  */
482 void initialize_ft_cache(void) {
483         memset(ftc_num_msgs, 0, (65536 * sizeof(int)));
484         memset(ftc_msgs, 0, (65536 * sizeof(long *)));
485 }
486
487
488 void ft_delete_remove(char *room, long msgnum)
489 {
490         if (room) return;
491         
492         /* Remove from fulltext index */
493         if (CtdlGetConfigInt("c_enable_fulltext")) {
494                 ft_index_message(msgnum, 0);
495         }
496 }
497
498 /*****************************************************************************/
499
500 CTDL_MODULE_INIT(fulltext)
501 {
502         if (!threading)
503         {
504                 initialize_ft_cache();
505                 initialize_noise_words();
506                 CtdlRegisterProtoHook(cmd_srch, "SRCH", "Full text search");
507                 CtdlRegisterDeleteHook(ft_delete_remove);
508                 CtdlRegisterSearchFuncHook(ft_search, "fulltext");
509                 CtdlRegisterCleanupHook(noise_word_cleanup);
510                 CtdlRegisterSessionHook(do_fulltext_indexing, EVT_TIMER, PRIO_CLEANUP + 300);
511         }
512         /* return our module name for the log */
513         return "fulltext";
514 }