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