959e32637e6d14faa4d2b56b9738036dc160650a
[citadel.git] / citadel / server / modules / fulltext / serv_fulltext.c
1 // This module handles fulltext indexing of the message base.
2 //
3 // Copyright (c) 2005-2023 by the citadel.org team
4 //
5 // This program is open source software.  Use, duplication, or disclosure
6 // is subject to the terms of the GNU General Public License, version 3.
7
8 #include "../../sysdep.h"
9 #include <stdlib.h>
10 #include <unistd.h>
11 #include <stdio.h>
12 #include <fcntl.h>
13 #include <signal.h>
14 #include <pwd.h>
15 #include <errno.h>
16 #include <sys/types.h>
17 #include <time.h>
18 #include <sys/wait.h>
19 #include <string.h>
20 #include <limits.h>
21 #include <libcitadel.h>
22 #include "../../citadel_defs.h"
23 #include "../../server.h"
24 #include "../../citserver.h"
25 #include "../../support.h"
26 #include "../../config.h"
27 #include "../../room_ops.h"
28 #include "../../database.h"
29 #include "../../msgbase.h"
30 #include "../../control.h"
31 #include "serv_fulltext.h"
32 #include "ft_wordbreaker.h"
33 #include "../../threads.h"
34 #include "../../context.h"
35 #include "../../ctdl_module.h"
36
37 // These can be global variables because only one indexer runs at a time.
38 Array *messages_to_be_indexed = NULL;
39 long highest_msg_already_indexed = 0;
40 long highest_msg_to_be_indexed = 0;
41
42
43 // Compare function
44 int longcmp(const void *rec1, const void *rec2) {
45         long i1, i2;
46
47         i1 = *(const long *)rec1;
48         i2 = *(const long *)rec2;
49
50         if (i1 > i2) return(1);
51         if (i1 < i2) return(-1);
52         return(0);
53 }
54
55
56 // Index or de-index a message.  (op == 1 to index, 0 to de-index)
57 void ft_index_message(long msgnum, int op) {
58         int i, j;
59         Array *tokens_in_this_message = NULL;
60         struct cdbdata cdb_bucket;
61         StrBuf *msgtext;
62         char *txt;
63         int tok;
64         struct CtdlMessage *msg = NULL;
65
66         if (msgnum == 0) return;
67
68         msg = CtdlFetchMessage(msgnum, 1);
69         if (msg == NULL) {
70                 // This is not necessarily an error condition; it could simply mean that the message was
71                 // deleted before it could be indexed.  This happens often when the load tester is running.
72                 syslog(LOG_ERR, "fulltext: ft_index_message() could not load msg %ld", msgnum);
73                 return;
74         }
75
76         if (!CM_IsEmpty(msg, eSuppressIdx)) {
77                 syslog(LOG_DEBUG, "fulltext: ft_index_message() excluded msg %ld", msgnum);
78                 CM_Free(msg);
79                 return;
80         }
81
82         syslog(LOG_DEBUG, "fulltext: ft_index_message() %s msg %ld", (op ? "adding" : "removing") , msgnum);
83
84         // Output the message as text before indexing it, so we don't end up indexing a bunch of encoded base64, etc.
85         CC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
86         CtdlOutputPreLoadedMsg(msg, MT_CITADEL, HEADERS_ALL, 0, 1, 0);
87         CM_Free(msg);
88         msgtext = CC->redirect_buffer;
89         CC->redirect_buffer = NULL;
90         if (msgtext != NULL) {
91                 syslog(LOG_DEBUG, "fulltext: wordbreaking message %ld (%d bytes)", msgnum, StrLength(msgtext));
92         }
93         txt = SmashStrBuf(&msgtext);
94         tokens_in_this_message = wordbreaker(txt);
95         free(txt);
96
97         syslog(LOG_DEBUG, "fulltext: %sindexing message %ld [%d tokens]",
98                 (op ? "" : "de"),
99                 msgnum,
100                 array_len(tokens_in_this_message)
101         );
102
103         if (tokens_in_this_message == NULL) {
104                 return;
105         }
106
107         if (array_len(tokens_in_this_message) > 0) {
108                 begin_critical_section(S_INDEXER);
109                 cdb_begin_transaction();
110                 for (i=0; i<array_len(tokens_in_this_message); ++i) {
111
112                         // Identify the bucket which we will be modifying
113                         memcpy(&tok, array_get_element_at(tokens_in_this_message, i), sizeof(int));
114         
115                         // fetch the bucket
116                         cdb_bucket = cdb_fetch(CDB_FULLTEXT, &tok, sizeof(int));
117                         long *newbucket = malloc(cdb_bucket.len + sizeof(long));
118                         int nmsgs = cdb_bucket.len / sizeof(long);
119
120                         if (op == 1) {                                          // indexing, add this message to the bucket
121                                 memcpy(&newbucket[0], cdb_bucket.ptr, cdb_bucket.len);
122                                 int already_there = 0;
123                                 for (j=0; j<nmsgs; ++j) {
124                                         if (newbucket[j] == msgnum) {
125                                                 already_there = 1;
126                                         }
127                                 }
128                                 if (already_there == 0) {
129                                         memcpy(&newbucket[nmsgs++], &msgnum, sizeof(long));
130                                 }
131                         }
132
133                         else if (op == 0) {                                     // deindexing, remove this message from the bucket
134                                 memcpy(newbucket, cdb_bucket.ptr, cdb_bucket.len);
135                                 for (j=0; j<nmsgs; ++j) {
136                                         if ((newbucket[j] == msgnum) || (newbucket[j] == 0)) {
137                                                 memcpy(&newbucket[j], &newbucket[j+1], ((nmsgs-j)*sizeof(long)));
138                                                 --j;
139                                                 --nmsgs;
140                                         }
141                                 }
142                         }
143
144                         // Then write it back to disk
145                         cdb_store(CDB_FULLTEXT, &tok, sizeof(int), newbucket, (nmsgs*sizeof(long)));
146                         free(newbucket);
147
148                         if (server_shutting_down) break;
149                 }
150                 cdb_end_transaction();
151                 end_critical_section(S_INDEXER);
152                 CtdlSetConfigLong("MMfulltext", msgnum);
153         }
154         array_free(tokens_in_this_message);
155 }
156
157
158 // Scan a room for messages to index.
159 void ft_index_room(struct ctdlroom *qrbuf, void *data) {
160         if (server_shutting_down) {
161                 return;
162         }
163
164         int num_msgs = 0;
165         long *msglist;
166         int i;
167
168         // 2023aug30 ajc - old code did another CtdlGetRoom() here.  Not only is that redundant,
169         // but for some reason it also made Berkeley DB deadlock after a while.  I don't know why.
170
171         // qrbuf is already populated.  fetch the list of messages in this room.
172         num_msgs = CtdlFetchMsgList(qrbuf->QRnumber, &msglist);
173
174         // Identify messages which have NOT yet been seen by the indexer.
175         if (msglist != NULL) {
176                 for (i=0; i<num_msgs; ++i) {
177                         if (
178                                 (msglist[i] > 0)
179                                 && (msglist[i] > highest_msg_already_indexed)
180                                 && (msglist[i] <= highest_msg_to_be_indexed)
181                            ) {
182                                 array_append(messages_to_be_indexed, &msglist[i]);
183                         }
184                 }
185                 free(msglist);
186         }
187 }
188
189
190 // Begin the fulltext indexing process.
191 void do_fulltext_indexing(void) {
192         int i;
193         static time_t last_progress = 0L;
194         static int is_running = 0;
195
196         if (is_running) return;         // Concurrency check - only one can run 
197         is_running = 1;
198
199         // Don't do this if the site doesn't have it enabled.
200         if (!CtdlGetConfigInt("c_enable_fulltext")) {
201                 is_running = 0;
202                 return;
203         }
204         // If we've switched wordbreaker modules, burn the index and start over.
205         begin_critical_section(S_CONTROL);
206         if (CtdlGetConfigInt("MM_fulltext_wordbreaker") != FT_WORDBREAKER_ID) {
207                 syslog(LOG_DEBUG, "fulltext: wb ver on disk = %d, code ver = %d",
208                         CtdlGetConfigInt("MM_fulltext_wordbreaker"), FT_WORDBREAKER_ID
209                 );
210                 syslog(LOG_INFO, "fulltext: (re)initializing index");
211                 cdb_trunc(CDB_FULLTEXT);
212                 CtdlSetConfigLong("MMfulltext", 0);
213         }
214         end_critical_section(S_CONTROL);
215
216         // Silently return if our fulltext index is up to date with new messages.
217         if ((CtdlGetConfigLong("MMfulltext") >= CtdlGetConfigLong("MMhighest"))) {
218                 is_running = 0;
219                 return;         // nothing to do!
220         }
221
222         highest_msg_already_indexed = CtdlGetConfigLong("MMfulltext");
223         highest_msg_to_be_indexed = CtdlGetConfigLong("MMhighest");
224         syslog(LOG_DEBUG, "fulltext: indexing started. msgs %ld--%ld", highest_msg_already_indexed, highest_msg_to_be_indexed);
225
226         messages_to_be_indexed = array_new(sizeof(long));
227
228         // Now go through each room and find messages to index.
229         CtdlForEachRoom(ft_index_room, NULL);                           // load all msg pointers
230         array_sort(messages_to_be_indexed, longcmp);                    // sort them
231
232         // Here it is ... do each message!
233         long msgnum = 0;
234         long prev_msgnum = 0;
235         time_t started_indexing_at = time(NULL);
236         int yielded = 0;
237         for (i=0; ((i<array_len(messages_to_be_indexed)) && (yielded == 0)); ++i) {
238                 memcpy(&msgnum, array_get_element_at(messages_to_be_indexed, i), sizeof(long));
239
240                 if (msgnum != prev_msgnum) {                            // careful to avoid dupes
241                         ft_index_message(msgnum, 1);
242                 }
243                 prev_msgnum = msgnum;
244                 
245                 // If we run too long, yield the thread so the server can do other things.  We'll be back.
246                 if (time(NULL) - started_indexing_at >= MAXIMUM_INDEXER_RUN_TIME) {
247                         yielded = 1;
248                 }
249         }
250
251         array_free(messages_to_be_indexed);
252         CtdlSetConfigInt("MM_fulltext_wordbreaker", FT_WORDBREAKER_ID);
253         syslog(LOG_DEBUG, "fulltext: indexer has run for %ld seconds; yielded=%d", time(NULL) - started_indexing_at, yielded);
254
255         // This keeps the indexer from starting up over and over if the highest message in the list was deleted
256         // before we had a chance to index it.
257         if (!yielded) {
258                 CtdlSetConfigLong("MMfulltext", highest_msg_to_be_indexed);
259         }
260
261         is_running = 0;
262         return;
263 }
264
265
266 // API call to perform searches.
267 // (This one does the "all of these words" search.)
268 // Caller is responsible for freeing the message list.
269 Array *CtdlFullTextSearch(const char *search_string) {
270         int i, j, tok;
271         struct cdbdata cdb_bucket;
272         long msgnum, smsgnum;
273         int count;
274
275         Array *r = array_new(sizeof(long));
276         if (!r) return(NULL);
277         Array *t = wordbreaker(search_string);
278
279         if ((t != NULL) && (array_len(t) > 0)) {
280                 for (i=0; i<array_len(t); ++i) {
281                         memcpy(&tok, array_get_element_at(t, i), sizeof(int));
282                         cdb_bucket = cdb_fetch(CDB_FULLTEXT, &tok, sizeof(int));
283                         if (cdb_bucket.ptr != NULL) {
284                                 for (j=0; j<(cdb_bucket.len / sizeof(long)); ++j) {
285                                         memcpy(&msgnum, cdb_bucket.ptr + (j*sizeof(long)), sizeof(long));
286                                         array_append(r, &msgnum);
287                                 }
288                         }
289                 }
290         }
291
292         // We need to return any message containing ALL of the tokens.
293         // If a message number appears in the array `n` times, where `n` is the number of search words,
294         // that means it matched all search words.
295         array_sort(r, longcmp);
296         for (i=0; i<array_len(r); ++i) {
297                 memcpy(&msgnum, array_get_element_at(r, i), sizeof(long));
298                 count = 1;
299                 for (j=i+1; j<array_len(r); ++j) {
300                         memcpy(&smsgnum, array_get_element_at(r, j), sizeof(long));
301                         if (msgnum == smsgnum) {
302                                 ++count;
303                                 array_delete_element_at(r, j);
304                                 --j;
305                         }
306                 }
307                 if (count != array_len(t)) {
308                         array_delete_element_at(r, i);
309                         --i;
310                 }
311         }
312
313         array_free(t);
314         return(r);
315 }
316
317
318 // This search command is for diagnostic purposes and may be removed or replaced.
319 void cmd_srch(char *argbuf) {
320         int i;
321         char search_string[SIZ];
322         Array *matches = NULL;
323         long msgnum;
324
325         if (CtdlAccessCheck(ac_logged_in)) return;
326
327         if (!CtdlGetConfigInt("c_enable_fulltext")) {
328                 cprintf("%d Full text index is not enabled on this server.\n", ERROR + CMD_NOT_SUPPORTED);
329                 return;
330         }
331
332         extract_token(search_string, argbuf, 0, '|', sizeof search_string);
333         matches = CtdlFullTextSearch(search_string);
334
335         cprintf("%d %d msgs match all search words:\n", LISTING_FOLLOWS, array_len(matches));
336         if ((matches != NULL) && (array_len(matches) > 0)) {
337                 for (i=0; i<array_len(matches); ++i) {
338                         memcpy(&msgnum, array_get_element_at(matches, i), sizeof(long));
339                         cprintf("%ld\n", msgnum);
340                 }
341         }
342         if (matches != NULL) {
343                 array_free(matches);
344         }
345         cprintf("000\n");
346 }
347
348
349 void ft_delete_remove(char *room, long msgnum) {
350         if (room) return;
351         
352         // Remove from fulltext index
353         if (CtdlGetConfigInt("c_enable_fulltext")) {
354                 ft_index_message(msgnum, 0);
355         }
356 }
357
358
359 // Initialization function, called from modules_init.c
360 char *ctdl_module_init_fulltext(void) {
361         if (!threading) {
362                 CtdlRegisterProtoHook(cmd_srch, "SRCH", "Full text search");
363                 CtdlRegisterDeleteHook(ft_delete_remove);
364                 CtdlRegisterSessionHook(do_fulltext_indexing, EVT_HOUSE, PRIO_CLEANUP + 300);
365         }
366         // return our module name for the log
367         return "fulltext";
368 }