cleaned up some compiler warnings
[citadel.git] / citadel / modules / fulltext / serv_fulltext.c
1 /*
2  * This module handles fulltext indexing of the message base.
3  * Copyright (c) 2005-2018 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 /*
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                                 "fulltext: flushing index cache to disk (%d%% complete)",
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, "fulltext: flushed index cache to disk (100%% complete)");
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, 1);
125         if (msg == NULL) {
126                 syslog(LOG_ERR, "fulltext: ft_index_message() could not load msg %ld", msgnum);
127                 return;
128         }
129
130         if (!CM_IsEmpty(msg, eSuppressIdx)) {
131                 syslog(LOG_DEBUG, "fulltext: ft_index_message() excluded msg %ld", msgnum);
132                 CM_Free(msg);
133                 return;
134         }
135
136         syslog(LOG_DEBUG, "fulltext: ft_index_message() %s msg %ld", (op ? "adding" : "removing") , msgnum);
137
138         /* Output the message as text before indexing it, so we don't end up
139          * indexing a bunch of encoded base64, etc.
140          */
141         CC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
142         CtdlOutputPreLoadedMsg(msg, MT_CITADEL, HEADERS_ALL, 0, 1, 0);
143         CM_Free(msg);
144         msgtext = CC->redirect_buffer;
145         CC->redirect_buffer = NULL;
146         if (msgtext != NULL) {
147                 syslog(LOG_DEBUG, "fulltext: wordbreaking message %ld (%d bytes)", msgnum, StrLength(msgtext));
148         }
149         txt = SmashStrBuf(&msgtext);
150         wordbreaker(txt, &num_tokens, &tokens);
151         free(txt);
152
153         syslog(LOG_DEBUG, "fulltext: indexing message %ld [%d tokens]", 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, "fulltext: invalid token %d !!", tok);
200                         }
201                 }
202
203                 free(tokens);
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, (ft_num_alloc * sizeof(long)));
218                 }
219                 ft_newmsgs[ft_num_msgs - 1] = msgnum;
220         }
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_progress = 0L;
244         static int is_running = 0;
245         if (is_running) return;         /* Concurrency check - only one can run */
246         is_running = 1;
247
248         /*
249          * Don't do this if the site doesn't have it enabled.
250          */
251         if (!CtdlGetConfigInt("c_enable_fulltext")) {
252                 return;
253         }
254
255         /*
256          * If we've switched wordbreaker modules, burn the index and start over.
257          */
258         begin_critical_section(S_CONTROL);
259         if (CtdlGetConfigInt("MM_fulltext_wordbreaker") != FT_WORDBREAKER_ID) {
260                 syslog(LOG_DEBUG, "fulltext: wb ver on disk = %d, code ver = %d",
261                         CtdlGetConfigInt("MM_fulltext_wordbreaker"), FT_WORDBREAKER_ID
262                 );
263                 syslog(LOG_INFO, "fulltext: (re)initializing index");
264                 cdb_trunc(CDB_FULLTEXT);
265                 CtdlSetConfigLong("MMfulltext", 0);
266         }
267         end_critical_section(S_CONTROL);
268
269         /*
270          * Silently return if our fulltext index is up to date with new messages.
271          */
272         if ((CtdlGetConfigLong("MMfulltext") >= CtdlGetConfigLong("MMhighest"))) {
273                 return;         /* nothing to do! */
274         }
275
276         /*
277          * Now go through each room and find messages to index.
278          */
279         ft_newhighest = CtdlGetConfigLong("MMhighest");
280         CtdlForEachRoom(ft_index_room, NULL);   /* load all msg pointers */
281
282         if (ft_num_msgs > 0) {
283                 qsort(ft_newmsgs, ft_num_msgs, sizeof(long), longcmp);
284                 for (i=0; i<(ft_num_msgs-1); ++i) { /* purge dups */
285                         if (ft_newmsgs[i] == ft_newmsgs[i+1]) {
286                                 memmove(&ft_newmsgs[i], &ft_newmsgs[i+1],
287                                         ((ft_num_msgs - i - 1)*sizeof(long)));
288                                 --ft_num_msgs;
289                                 --i;
290                         }
291                 }
292
293                 /* Here it is ... do each message! */
294                 for (i=0; i<ft_num_msgs; ++i) {
295                         if (time(NULL) != last_progress) {
296                                 syslog(LOG_DEBUG,
297                                         "fulltext: indexed %d of %d messages (%d%%)",
298                                                 i, ft_num_msgs,
299                                                 ((i*100) / ft_num_msgs)
300                                 );
301                                 last_progress = time(NULL);
302                         }
303                         ft_index_message(ft_newmsgs[i], 1);
304
305                         /* Check to see if we need to quit early */
306                         if (server_shutting_down) {
307                                 syslog(LOG_DEBUG, "fulltext: indexer quitting early");
308                                 ft_newhighest = ft_newmsgs[i];
309                                 break;
310                         }
311
312                         /* Check to see if we have to maybe flush to disk */
313                         if (i >= FT_MAX_CACHE) {
314                                 syslog(LOG_DEBUG, "fulltext: time to flush.");
315                                 ft_newhighest = ft_newmsgs[i];
316                                 break;
317                         }
318
319                 }
320
321                 free(ft_newmsgs);
322                 ft_num_msgs = 0;
323                 ft_num_alloc = 0;
324                 ft_newmsgs = NULL;
325         }
326
327         if (server_shutting_down) {
328                 is_running = 0;
329                 return;
330         }
331         
332         /* Save our place so we don't have to do this again */
333         ft_flush_cache();
334         begin_critical_section(S_CONTROL);
335         CtdlSetConfigLong("MMfulltext", ft_newhighest);
336         CtdlSetConfigInt("MM_fulltext_wordbreaker", FT_WORDBREAKER_ID);
337         end_critical_section(S_CONTROL);
338
339         syslog(LOG_DEBUG, "fulltext: indexing finished");
340         is_running = 0;
341         return;
342 }
343
344
345 /*
346  * API call to perform searches.
347  * (This one does the "all of these words" search.)
348  * Caller is responsible for freeing the message list.
349  */
350 void ft_search(int *fts_num_msgs, long **fts_msgs, const char *search_string) {
351         int num_tokens = 0;
352         int *tokens = NULL;
353         int i, j;
354         struct cdbdata *cdb_bucket;
355         int num_all_msgs = 0;
356         long *all_msgs = NULL;
357         int num_ret_msgs = 0;
358         int num_ret_alloc = 0;
359         long *ret_msgs = NULL;
360         int tok;
361
362         wordbreaker(search_string, &num_tokens, &tokens);
363         if (num_tokens > 0) {
364                 for (i=0; i<num_tokens; ++i) {
365
366                         /* search for tokens[i] */
367                         tok = tokens[i];
368
369                         /* fetch the bucket, Liza */
370                         if (ftc_msgs[tok] == NULL) {
371                                 cdb_bucket = cdb_fetch(CDB_FULLTEXT, &tok, sizeof(int));
372                                 if (cdb_bucket != NULL) {
373                                         ftc_num_msgs[tok] = cdb_bucket->len / sizeof(long);
374                                         ftc_msgs[tok] = (long *)cdb_bucket->ptr;
375                                         cdb_bucket->ptr = NULL;
376                                         cdb_free(cdb_bucket);
377                                 }
378                                 else {
379                                         ftc_num_msgs[tok] = 0;
380                                         ftc_msgs[tok] = malloc(sizeof(long));
381                                 }
382                         }
383
384                         num_all_msgs += ftc_num_msgs[tok];
385                         if (num_all_msgs > 0) {
386                                 all_msgs = realloc(all_msgs, num_all_msgs*sizeof(long) );
387                                 memcpy(&all_msgs[num_all_msgs-ftc_num_msgs[tok]],
388                                         ftc_msgs[tok], ftc_num_msgs[tok]*sizeof(long) );
389                         }
390
391                 }
392                 free(tokens);
393                 if (all_msgs != NULL) {
394                         qsort(all_msgs, num_all_msgs, sizeof(long), longcmp);
395
396                         /*
397                          * At this point, if a message appears num_tokens times in the
398                          * list, then it contains all of the search tokens.
399                          */
400                         if (num_all_msgs >= num_tokens)
401                                 for (j=0; j<(num_all_msgs-num_tokens+1); ++j) {
402                                         if (all_msgs[j] == all_msgs[j+num_tokens-1]) {
403                                                 
404                                                 ++num_ret_msgs;
405                                                 if (num_ret_msgs > num_ret_alloc) {
406                                                         num_ret_alloc += 64;
407                                                         ret_msgs = realloc(ret_msgs,
408                                                                            (num_ret_alloc*sizeof(long)) );
409                                                 }
410                                                 ret_msgs[num_ret_msgs - 1] = all_msgs[j];
411                                                 
412                                         }
413                                 }
414                         free(all_msgs);
415                 }
416         }
417
418         *fts_num_msgs = num_ret_msgs;
419         *fts_msgs = ret_msgs;
420 }
421
422
423 /*
424  * This search command is for diagnostic purposes and may be removed or replaced.
425  */
426 void cmd_srch(char *argbuf) {
427         int num_msgs = 0;
428         long *msgs = NULL;
429         int i;
430         char search_string[256];
431
432         if (CtdlAccessCheck(ac_logged_in)) return;
433
434         if (!CtdlGetConfigInt("c_enable_fulltext")) {
435                 cprintf("%d Full text index is not enabled on this server.\n",
436                         ERROR + CMD_NOT_SUPPORTED);
437                 return;
438         }
439
440         extract_token(search_string, argbuf, 0, '|', sizeof search_string);
441         ft_search(&num_msgs, &msgs, search_string);
442
443         cprintf("%d %d msgs match all search words:\n",
444                 LISTING_FOLLOWS, num_msgs);
445         if (num_msgs > 0) {
446                 for (i=0; i<num_msgs; ++i) {
447                         cprintf("%ld\n", msgs[i]);
448                 }
449         }
450         if (msgs != NULL) free(msgs);
451         cprintf("000\n");
452 }
453
454
455 /*
456  * Zero out our index cache.
457  */
458 void initialize_ft_cache(void) {
459         memset(ftc_num_msgs, 0, (65536 * sizeof(int)));
460         memset(ftc_msgs, 0, (65536 * sizeof(long *)));
461 }
462
463
464 void ft_delete_remove(char *room, long msgnum)
465 {
466         if (room) return;
467         
468         /* Remove from fulltext index */
469         if (CtdlGetConfigInt("c_enable_fulltext")) {
470                 ft_index_message(msgnum, 0);
471         }
472 }
473
474
475 /*****************************************************************************/
476
477 CTDL_MODULE_INIT(fulltext)
478 {
479         if (!threading)
480         {
481                 initialize_ft_cache();
482                 initialize_noise_words();
483                 CtdlRegisterProtoHook(cmd_srch, "SRCH", "Full text search");
484                 CtdlRegisterDeleteHook(ft_delete_remove);
485                 CtdlRegisterSearchFuncHook(ft_search, "fulltext");
486                 CtdlRegisterCleanupHook(noise_word_cleanup);
487                 CtdlRegisterSessionHook(do_fulltext_indexing, EVT_TIMER, PRIO_CLEANUP + 300);
488         }
489         /* return our module name for the log */
490         return "fulltext";
491 }