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