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