339650a8f14e7a189679f884da1ce0c2e09016d4
[citadel.git] / citadel / msgbase.c
1 /*
2  * Implements the message store.
3  *
4  * Copyright (c) 1987-2018 by the citadel.org team
5  *
6  * This program is open source software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 3.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  */
14
15
16 #include <stdlib.h>
17 #include <unistd.h>
18 #include <stdio.h>
19 #include <regex.h>
20 #include <sys/stat.h>
21 #include <libcitadel.h>
22 #include "md5.h"
23 #include "ctdl_module.h"
24 #include "citserver.h"
25 #include "control.h"
26 #include "config.h"
27 #include "clientsocket.h"
28 #include "genstamp.h"
29 #include "room_ops.h"
30 #include "user_ops.h"
31 #include "internet_addressing.h"
32 #include "euidindex.h"
33 #include "msgbase.h"
34 #include "journaling.h"
35
36 struct addresses_to_be_filed *atbf = NULL;
37
38 /* This temp file holds the queue of operations for AdjRefCount() */
39 static FILE *arcfp = NULL;
40 void AdjRefCountList(long *msgnum, long nmsg, int incr);
41
42 /*
43  * These are the four-character field headers we use when outputting
44  * messages in Citadel format (as opposed to RFC822 format).
45  */
46 char *msgkeys[91] = {
47         NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 
48         NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 
49         NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 
50         NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 
51         NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 
52         NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 
53         NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 
54         NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 
55         NULL, 
56         "from", /* A -> eAuthor       */
57         NULL,   /* B -> eBig_message  */
58         NULL,   /* C -> eRemoteRoom   FIXME no more ignet */
59         NULL,   /* D -> eDestination  FIXME no more ignet */
60         "exti", /* E -> eXclusivID    */
61         "rfca", /* F -> erFc822Addr   */
62         NULL,   /* G */
63         "hnod", /* H -> eHumanNode    FIXME no more ignet */
64         "msgn", /* I -> emessageId    */
65         "jrnl", /* J -> eJournal      */
66         "rep2", /* K -> eReplyTo      */
67         "list", /* L -> eListID       */
68         "text", /* M -> eMesageText   */
69         "node", /* N -> eNodeName     FIXME no more ignet */
70         "room", /* O -> eOriginalRoom */
71         "path", /* P -> eMessagePath  */
72         NULL,   /* Q */
73         "rcpt", /* R -> eRecipient    */
74         "spec", /* S -> eSpecialField FIXME we might not be using this anymore */
75         "time", /* T -> eTimestamp    */
76         "subj", /* U -> eMsgSubject   */
77         "nvto", /* V -> eenVelopeTo   */
78         "wefw", /* W -> eWeferences   */
79         NULL,   /* X */
80         "cccc", /* Y -> eCarbonCopY   */
81         NULL   /* Z */
82
83 };
84 HashList *msgKeyLookup = NULL;
85
86 int GetFieldFromMnemonic(eMsgField *f, const char* c)
87 {
88         void *v = NULL;
89         if (GetHash(msgKeyLookup, c, 4, &v)) {
90                 *f = (eMsgField) v;
91                 return 1;
92         }
93         return 0;
94 }
95
96 void FillMsgKeyLookupTable(void)
97 {
98         long i;
99
100         msgKeyLookup = NewHash (1, FourHash);
101
102         for (i=0; i < 91; i++) {
103                 if (msgkeys[i] != NULL) {
104                         Put(msgKeyLookup, msgkeys[i], 4, (void*)i, reference_free_handler);
105                 }
106         }
107 }
108
109 eMsgField FieldOrder[]  = {
110 /* Important fields */
111         emessageId   ,
112         eMessagePath ,
113         eTimestamp   ,
114         eAuthor      ,
115         erFc822Addr  ,
116         eOriginalRoom,
117         eNodeName    ,
118         eHumanNode   ,
119         eRecipient   ,
120         eDestination ,
121 /* Semi-important fields */
122         eBig_message ,
123         eRemoteRoom  ,
124         eExclusiveID ,
125         eWeferences  ,
126         eJournal     ,
127 /* G is not used yet, may become virus signature*/
128         eReplyTo     ,
129         eListID      ,
130 /* Q is not used yet */
131         eSpecialField,
132         eenVelopeTo  ,
133 /* X is not used yet */
134 /* Z is not used yet */
135         eCarbonCopY  ,
136         eMsgSubject  ,
137 /* internal only */
138         eErrorMsg    ,
139         eSuppressIdx ,
140         eExtnotify   ,
141 /* Message text (MUST be last) */
142         eMesageText 
143 /* Not saved to disk: 
144         eVltMsgNum
145 */
146 };
147
148 static const long NDiskFields = sizeof(FieldOrder) / sizeof(eMsgField);
149
150
151 int CM_IsEmpty(struct CtdlMessage *Msg, eMsgField which)
152 {
153         return !((Msg->cm_fields[which] != NULL) && (Msg->cm_fields[which][0] != '\0'));
154 }
155
156
157 void CM_SetField(struct CtdlMessage *Msg, eMsgField which, const char *buf, long length)
158 {
159         if (Msg->cm_fields[which] != NULL) {
160                 free (Msg->cm_fields[which]);
161         }
162         Msg->cm_fields[which] = malloc(length + 1);
163         memcpy(Msg->cm_fields[which], buf, length);
164         Msg->cm_fields[which][length] = '\0';
165         Msg->cm_lengths[which] = length;
166 }
167
168
169 void CM_SetFieldLONG(struct CtdlMessage *Msg, eMsgField which, long lvalue)
170 {
171         char buf[128];
172         long len;
173         len = snprintf(buf, sizeof(buf), "%ld", lvalue);
174         CM_SetField(Msg, which, buf, len);
175 }
176
177
178 void CM_CutFieldAt(struct CtdlMessage *Msg, eMsgField WhichToCut, long maxlen)
179 {
180         if (Msg->cm_fields[WhichToCut] == NULL)
181                 return;
182
183         if (Msg->cm_lengths[WhichToCut] > maxlen)
184         {
185                 Msg->cm_fields[WhichToCut][maxlen] = '\0';
186                 Msg->cm_lengths[WhichToCut] = maxlen;
187         }
188 }
189
190
191 void CM_FlushField(struct CtdlMessage *Msg, eMsgField which)
192 {
193         if (Msg->cm_fields[which] != NULL)
194                 free (Msg->cm_fields[which]);
195         Msg->cm_fields[which] = NULL;
196         Msg->cm_lengths[which] = 0;
197 }
198
199
200 void CM_Flush(struct CtdlMessage *Msg)
201 {
202         int i;
203
204         if (CM_IsValidMsg(Msg) == 0) {
205                 return;
206         }
207
208         for (i = 0; i < 256; ++i) {
209                 CM_FlushField(Msg, i);
210         }
211 }
212
213
214 void CM_CopyField(struct CtdlMessage *Msg, eMsgField WhichToPutTo, eMsgField WhichtToCopy)
215 {
216         long len;
217         if (Msg->cm_fields[WhichToPutTo] != NULL) {
218                 free (Msg->cm_fields[WhichToPutTo]);
219         }
220
221         if (Msg->cm_fields[WhichtToCopy] != NULL) {
222                 len = Msg->cm_lengths[WhichtToCopy];
223                 Msg->cm_fields[WhichToPutTo] = malloc(len + 1);
224                 memcpy(Msg->cm_fields[WhichToPutTo], Msg->cm_fields[WhichtToCopy], len);
225                 Msg->cm_fields[WhichToPutTo][len] = '\0';
226                 Msg->cm_lengths[WhichToPutTo] = len;
227         }
228         else {
229                 Msg->cm_fields[WhichToPutTo] = NULL;
230                 Msg->cm_lengths[WhichToPutTo] = 0;
231         }
232 }
233
234
235 void CM_PrependToField(struct CtdlMessage *Msg, eMsgField which, const char *buf, long length)
236 {
237         if (Msg->cm_fields[which] != NULL) {
238                 long oldmsgsize;
239                 long newmsgsize;
240                 char *new;
241
242                 oldmsgsize = Msg->cm_lengths[which] + 1;
243                 newmsgsize = length + oldmsgsize;
244
245                 new = malloc(newmsgsize);
246                 memcpy(new, buf, length);
247                 memcpy(new + length, Msg->cm_fields[which], oldmsgsize);
248                 free(Msg->cm_fields[which]);
249                 Msg->cm_fields[which] = new;
250                 Msg->cm_lengths[which] = newmsgsize - 1;
251         }
252         else {
253                 Msg->cm_fields[which] = malloc(length + 1);
254                 memcpy(Msg->cm_fields[which], buf, length);
255                 Msg->cm_fields[which][length] = '\0';
256                 Msg->cm_lengths[which] = length;
257         }
258 }
259
260
261 void CM_SetAsField(struct CtdlMessage *Msg, eMsgField which, char **buf, long length)
262 {
263         if (Msg->cm_fields[which] != NULL) {
264                 free (Msg->cm_fields[which]);
265         }
266
267         Msg->cm_fields[which] = *buf;
268         *buf = NULL;
269         Msg->cm_lengths[which] = length;
270 }
271
272
273 void CM_SetAsFieldSB(struct CtdlMessage *Msg, eMsgField which, StrBuf **buf)
274 {
275         if (Msg->cm_fields[which] != NULL) {
276                 free (Msg->cm_fields[which]);
277         }
278
279         Msg->cm_lengths[which] = StrLength(*buf);
280         Msg->cm_fields[which] = SmashStrBuf(buf);
281 }
282
283
284 void CM_GetAsField(struct CtdlMessage *Msg, eMsgField which, char **ret, long *retlen)
285 {
286         if (Msg->cm_fields[which] != NULL) {
287                 *retlen = Msg->cm_lengths[which];
288                 *ret = Msg->cm_fields[which];
289                 Msg->cm_fields[which] = NULL;
290                 Msg->cm_lengths[which] = 0;
291         }
292         else {
293                 *ret = NULL;
294                 *retlen = 0;
295         }
296 }
297
298
299 /*
300  * Returns 1 if the supplied pointer points to a valid Citadel message.
301  * If the pointer is NULL or the magic number check fails, returns 0.
302  */
303 int CM_IsValidMsg(struct CtdlMessage *msg) {
304         if (msg == NULL) {
305                 return 0;
306         }
307         if ((msg->cm_magic) != CTDLMESSAGE_MAGIC) {
308                 syslog(LOG_WARNING, "msgbase: CM_IsValidMsg() self-check failed");
309                 return 0;
310         }
311         return 1;
312 }
313
314
315 void CM_FreeContents(struct CtdlMessage *msg)
316 {
317         int i;
318
319         for (i = 0; i < 256; ++i)
320                 if (msg->cm_fields[i] != NULL) {
321                         free(msg->cm_fields[i]);
322                         msg->cm_lengths[i] = 0;
323                 }
324
325         msg->cm_magic = 0;      /* just in case */
326 }
327
328
329 /*
330  * 'Destructor' for struct CtdlMessage
331  */
332 void CM_Free(struct CtdlMessage *msg)
333 {
334         if (CM_IsValidMsg(msg) == 0) {
335                 if (msg != NULL) free (msg);
336                 return;
337         }
338         CM_FreeContents(msg);
339         free(msg);
340 }
341
342
343 int CM_DupField(eMsgField i, struct CtdlMessage *OrgMsg, struct CtdlMessage *NewMsg)
344 {
345         long len;
346         len = OrgMsg->cm_lengths[i];
347         NewMsg->cm_fields[i] = malloc(len + 1);
348         if (NewMsg->cm_fields[i] == NULL) {
349                 return 0;
350         }
351         memcpy(NewMsg->cm_fields[i], OrgMsg->cm_fields[i], len);
352         NewMsg->cm_fields[i][len] = '\0';
353         NewMsg->cm_lengths[i] = len;
354         return 1;
355 }
356
357
358 struct CtdlMessage * CM_Duplicate(struct CtdlMessage *OrgMsg)
359 {
360         int i;
361         struct CtdlMessage *NewMsg;
362
363         if (CM_IsValidMsg(OrgMsg) == 0) {
364                 return NULL;
365         }
366         NewMsg = (struct CtdlMessage *)malloc(sizeof(struct CtdlMessage));
367         if (NewMsg == NULL) {
368                 return NULL;
369         }
370
371         memcpy(NewMsg, OrgMsg, sizeof(struct CtdlMessage));
372
373         memset(&NewMsg->cm_fields, 0, sizeof(char*) * 256);
374         
375         for (i = 0; i < 256; ++i) {
376                 if (OrgMsg->cm_fields[i] != NULL) {
377                         if (!CM_DupField(i, OrgMsg, NewMsg)) {
378                                 CM_Free(NewMsg);
379                                 return NULL;
380                         }
381                 }
382         }
383
384         return NewMsg;
385 }
386
387
388 /* Determine if a given message matches the fields in a message template.
389  * Return 0 for a successful match.
390  */
391 int CtdlMsgCmp(struct CtdlMessage *msg, struct CtdlMessage *template) {
392         int i;
393
394         /* If there aren't any fields in the template, all messages will
395          * match.
396          */
397         if (template == NULL) return(0);
398
399         /* Null messages are bogus. */
400         if (msg == NULL) return(1);
401
402         for (i='A'; i<='Z'; ++i) {
403                 if (template->cm_fields[i] != NULL) {
404                         if (msg->cm_fields[i] == NULL) {
405                                 /* Considered equal if temmplate is empty string */
406                                 if (IsEmptyStr(template->cm_fields[i])) continue;
407                                 return 1;
408                         }
409                         if ((template->cm_lengths[i] != msg->cm_lengths[i]) ||
410                             (strcasecmp(msg->cm_fields[i], template->cm_fields[i])))
411                                 return 1;
412                 }
413         }
414
415         /* All compares succeeded: we have a match! */
416         return 0;
417 }
418
419
420
421 /*
422  * Retrieve the "seen" message list for the current room.
423  */
424 void CtdlGetSeen(char *buf, int which_set) {
425         visit vbuf;
426
427         /* Learn about the user and room in question */
428         CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
429
430         if (which_set == ctdlsetseen_seen)
431                 safestrncpy(buf, vbuf.v_seen, SIZ);
432         if (which_set == ctdlsetseen_answered)
433                 safestrncpy(buf, vbuf.v_answered, SIZ);
434 }
435
436
437
438 /*
439  * Manipulate the "seen msgs" string (or other message set strings)
440  */
441 void CtdlSetSeen(long *target_msgnums, int num_target_msgnums,
442                 int target_setting, int which_set,
443                 struct ctdluser *which_user, struct ctdlroom *which_room) {
444         struct cdbdata *cdbfr;
445         int i, k;
446         int is_seen = 0;
447         int was_seen = 0;
448         long lo = (-1L);
449         long hi = (-1L); /// TODO: we just write here. y?
450         visit vbuf;
451         long *msglist;
452         int num_msgs = 0;
453         StrBuf *vset;
454         StrBuf *setstr;
455         StrBuf *lostr;
456         StrBuf *histr;
457         const char *pvset;
458         char *is_set;   /* actually an array of booleans */
459
460         /* Don't bother doing *anything* if we were passed a list of zero messages */
461         if (num_target_msgnums < 1) {
462                 return;
463         }
464
465         /* If no room was specified, we go with the current room. */
466         if (!which_room) {
467                 which_room = &CC->room;
468         }
469
470         /* If no user was specified, we go with the current user. */
471         if (!which_user) {
472                 which_user = &CC->user;
473         }
474
475         syslog(LOG_DEBUG, "msgbase: CtdlSetSeen(%d msgs starting with %ld, %s, %d) in <%s>",
476                    num_target_msgnums, target_msgnums[0],
477                    (target_setting ? "SET" : "CLEAR"),
478                    which_set,
479                    which_room->QRname);
480
481         /* Learn about the user and room in question */
482         CtdlGetRelationship(&vbuf, which_user, which_room);
483
484         /* Load the message list */
485         cdbfr = cdb_fetch(CDB_MSGLISTS, &which_room->QRnumber, sizeof(long));
486         if (cdbfr != NULL) {
487                 msglist = (long *) cdbfr->ptr;
488                 cdbfr->ptr = NULL;      /* CtdlSetSeen() now owns this memory */
489                 num_msgs = cdbfr->len / sizeof(long);
490                 cdb_free(cdbfr);
491         } else {
492                 return; /* No messages at all?  No further action. */
493         }
494
495         is_set = malloc(num_msgs * sizeof(char));
496         memset(is_set, 0, (num_msgs * sizeof(char)) );
497
498         /* Decide which message set we're manipulating */
499         switch(which_set) {
500         case ctdlsetseen_seen:
501                 vset = NewStrBufPlain(vbuf.v_seen, -1);
502                 break;
503         case ctdlsetseen_answered:
504                 vset = NewStrBufPlain(vbuf.v_answered, -1);
505                 break;
506         default:
507                 vset = NewStrBuf();
508         }
509
510
511 #if 0   /* This is a special diagnostic section.  Do not allow it to run during normal operation. */
512         syslog(LOG_DEBUG, "There are %d messages in the room.\n", num_msgs);
513         for (i=0; i<num_msgs; ++i) {
514                 if ((i > 0) && (msglist[i] <= msglist[i-1])) abort();
515         }
516         syslog(LOG_DEBUG, "We are twiddling %d of them.\n", num_target_msgnums);
517         for (k=0; k<num_target_msgnums; ++k) {
518                 if ((k > 0) && (target_msgnums[k] <= target_msgnums[k-1])) abort();
519         }
520 #endif
521
522         /* Translate the existing sequence set into an array of booleans */
523         setstr = NewStrBuf();
524         lostr = NewStrBuf();
525         histr = NewStrBuf();
526         pvset = NULL;
527         while (StrBufExtract_NextToken(setstr, vset, &pvset, ',') >= 0) {
528
529                 StrBufExtract_token(lostr, setstr, 0, ':');
530                 if (StrBufNum_tokens(setstr, ':') >= 2) {
531                         StrBufExtract_token(histr, setstr, 1, ':');
532                 }
533                 else {
534                         FlushStrBuf(histr);
535                         StrBufAppendBuf(histr, lostr, 0);
536                 }
537                 lo = StrTol(lostr);
538                 if (!strcmp(ChrPtr(histr), "*")) {
539                         hi = LONG_MAX;
540                 }
541                 else {
542                         hi = StrTol(histr);
543                 }
544
545                 for (i = 0; i < num_msgs; ++i) {
546                         if ((msglist[i] >= lo) && (msglist[i] <= hi)) {
547                                 is_set[i] = 1;
548                         }
549                 }
550         }
551         FreeStrBuf(&setstr);
552         FreeStrBuf(&lostr);
553         FreeStrBuf(&histr);
554
555
556         /* Now translate the array of booleans back into a sequence set */
557         FlushStrBuf(vset);
558         was_seen = 0;
559         lo = (-1);
560         hi = (-1);
561
562         for (i=0; i<num_msgs; ++i) {
563                 is_seen = is_set[i];
564
565                 /* Apply changes */
566                 for (k=0; k<num_target_msgnums; ++k) {
567                         if (msglist[i] == target_msgnums[k]) {
568                                 is_seen = target_setting;
569                         }
570                 }
571
572                 if ((was_seen == 0) && (is_seen == 1)) {
573                         lo = msglist[i];
574                 }
575                 else if ((was_seen == 1) && (is_seen == 0)) {
576                         hi = msglist[i-1];
577
578                         if (StrLength(vset) > 0) {
579                                 StrBufAppendBufPlain(vset, HKEY(","), 0);
580                         }
581                         if (lo == hi) {
582                                 StrBufAppendPrintf(vset, "%ld", hi);
583                         }
584                         else {
585                                 StrBufAppendPrintf(vset, "%ld:%ld", lo, hi);
586                         }
587                 }
588
589                 if ((is_seen) && (i == num_msgs - 1)) {
590                         if (StrLength(vset) > 0) {
591                                 StrBufAppendBufPlain(vset, HKEY(","), 0);
592                         }
593                         if ((i==0) || (was_seen == 0)) {
594                                 StrBufAppendPrintf(vset, "%ld", msglist[i]);
595                         }
596                         else {
597                                 StrBufAppendPrintf(vset, "%ld:%ld", lo, msglist[i]);
598                         }
599                 }
600
601                 was_seen = is_seen;
602         }
603
604         /*
605          * We will have to stuff this string back into a 4096 byte buffer, so if it's
606          * larger than that now, truncate it by removing tokens from the beginning.
607          * The limit of 100 iterations is there to prevent an infinite loop in case
608          * something unexpected happens.
609          */
610         int number_of_truncations = 0;
611         while ( (StrLength(vset) > SIZ) && (number_of_truncations < 100) ) {
612                 StrBufRemove_token(vset, 0, ',');
613                 ++number_of_truncations;
614         }
615
616         /*
617          * If we're truncating the sequence set of messages marked with the 'seen' flag,
618          * we want the earliest messages (the truncated ones) to be marked, not unmarked.
619          * Otherwise messages at the beginning will suddenly appear to be 'unseen'.
620          */
621         if ( (which_set == ctdlsetseen_seen) && (number_of_truncations > 0) ) {
622                 StrBuf *first_tok;
623                 first_tok = NewStrBuf();
624                 StrBufExtract_token(first_tok, vset, 0, ',');
625                 StrBufRemove_token(vset, 0, ',');
626
627                 if (StrBufNum_tokens(first_tok, ':') > 1) {
628                         StrBufRemove_token(first_tok, 0, ':');
629                 }
630                 
631                 StrBuf *new_set;
632                 new_set = NewStrBuf();
633                 StrBufAppendBufPlain(new_set, HKEY("1:"), 0);
634                 StrBufAppendBuf(new_set, first_tok, 0);
635                 StrBufAppendBufPlain(new_set, HKEY(":"), 0);
636                 StrBufAppendBuf(new_set, vset, 0);
637
638                 FreeStrBuf(&vset);
639                 FreeStrBuf(&first_tok);
640                 vset = new_set;
641         }
642
643         /* Decide which message set we're manipulating */
644         switch (which_set) {
645                 case ctdlsetseen_seen:
646                         safestrncpy(vbuf.v_seen, ChrPtr(vset), sizeof vbuf.v_seen);
647                         break;
648                 case ctdlsetseen_answered:
649                         safestrncpy(vbuf.v_answered, ChrPtr(vset), sizeof vbuf.v_answered);
650                         break;
651         }
652
653         free(is_set);
654         free(msglist);
655         CtdlSetRelationship(&vbuf, which_user, which_room);
656         FreeStrBuf(&vset);
657 }
658
659
660 /*
661  * API function to perform an operation for each qualifying message in the
662  * current room.  (Returns the number of messages processed.)
663  */
664 int CtdlForEachMessage(int mode, long ref, char *search_string,
665                         char *content_type,
666                         struct CtdlMessage *compare,
667                         ForEachMsgCallback CallBack,
668                         void *userdata)
669 {
670         int a, i, j;
671         visit vbuf;
672         struct cdbdata *cdbfr;
673         long *msglist = NULL;
674         int num_msgs = 0;
675         int num_processed = 0;
676         long thismsg;
677         struct MetaData smi;
678         struct CtdlMessage *msg = NULL;
679         int is_seen = 0;
680         long lastold = 0L;
681         int printed_lastold = 0;
682         int num_search_msgs = 0;
683         long *search_msgs = NULL;
684         regex_t re;
685         int need_to_free_re = 0;
686         regmatch_t pm;
687
688         if ((content_type) && (!IsEmptyStr(content_type))) {
689                 regcomp(&re, content_type, 0);
690                 need_to_free_re = 1;
691         }
692
693         /* Learn about the user and room in question */
694         if (server_shutting_down) {
695                 if (need_to_free_re) regfree(&re);
696                 return -1;
697         }
698         CtdlGetUser(&CC->user, CC->curr_user);
699
700         if (server_shutting_down) {
701                 if (need_to_free_re) regfree(&re);
702                 return -1;
703         }
704         CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
705
706         if (server_shutting_down) {
707                 if (need_to_free_re) regfree(&re);
708                 return -1;
709         }
710
711         /* Load the message list */
712         cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
713         if (cdbfr == NULL) {
714                 if (need_to_free_re) regfree(&re);
715                 return 0;       /* No messages at all?  No further action. */
716         }
717
718         msglist = (long *) cdbfr->ptr;
719         num_msgs = cdbfr->len / sizeof(long);
720
721         cdbfr->ptr = NULL;      /* clear this so that cdb_free() doesn't free it */
722         cdb_free(cdbfr);        /* we own this memory now */
723
724         /*
725          * Now begin the traversal.
726          */
727         if (num_msgs > 0) for (a = 0; a < num_msgs; ++a) {
728
729                 /* If the caller is looking for a specific MIME type, filter
730                  * out all messages which are not of the type requested.
731                  */
732                 if ((content_type != NULL) && (!IsEmptyStr(content_type))) {
733
734                         /* This call to GetMetaData() sits inside this loop
735                          * so that we only do the extra database read per msg
736                          * if we need to.  Doing the extra read all the time
737                          * really kills the server.  If we ever need to use
738                          * metadata for another search criterion, we need to
739                          * move the read somewhere else -- but still be smart
740                          * enough to only do the read if the caller has
741                          * specified something that will need it.
742                          */
743                         if (server_shutting_down) {
744                                 if (need_to_free_re) regfree(&re);
745                                 free(msglist);
746                                 return -1;
747                         }
748                         GetMetaData(&smi, msglist[a]);
749
750                         /* if (strcasecmp(smi.meta_content_type, content_type)) { old non-regex way */
751                         if (regexec(&re, smi.meta_content_type, 1, &pm, 0) != 0) {
752                                 msglist[a] = 0L;
753                         }
754                 }
755         }
756
757         num_msgs = sort_msglist(msglist, num_msgs);
758
759         /* If a template was supplied, filter out the messages which
760          * don't match.  (This could induce some delays!)
761          */
762         if (num_msgs > 0) {
763                 if (compare != NULL) {
764                         for (a = 0; a < num_msgs; ++a) {
765                                 if (server_shutting_down) {
766                                         if (need_to_free_re) regfree(&re);
767                                         free(msglist);
768                                         return -1;
769                                 }
770                                 msg = CtdlFetchMessage(msglist[a], 1, 1);
771                                 if (msg != NULL) {
772                                         if (CtdlMsgCmp(msg, compare)) {
773                                                 msglist[a] = 0L;
774                                         }
775                                         CM_Free(msg);
776                                 }
777                         }
778                 }
779         }
780
781         /* If a search string was specified, get a message list from
782          * the full text index and remove messages which aren't on both
783          * lists.
784          *
785          * How this works:
786          * Since the lists are sorted and strictly ascending, and the
787          * output list is guaranteed to be shorter than or equal to the
788          * input list, we overwrite the bottom of the input list.  This
789          * eliminates the need to memmove big chunks of the list over and
790          * over again.
791          */
792         if ( (num_msgs > 0) && (mode == MSGS_SEARCH) && (search_string) ) {
793
794                 /* Call search module via hook mechanism.
795                  * NULL means use any search function available.
796                  * otherwise replace with a char * to name of search routine
797                  */
798                 CtdlModuleDoSearch(&num_search_msgs, &search_msgs, search_string, "fulltext");
799
800                 if (num_search_msgs > 0) {
801         
802                         int orig_num_msgs;
803
804                         orig_num_msgs = num_msgs;
805                         num_msgs = 0;
806                         for (i=0; i<orig_num_msgs; ++i) {
807                                 for (j=0; j<num_search_msgs; ++j) {
808                                         if (msglist[i] == search_msgs[j]) {
809                                                 msglist[num_msgs++] = msglist[i];
810                                         }
811                                 }
812                         }
813                 }
814                 else {
815                         num_msgs = 0;   /* No messages qualify */
816                 }
817                 if (search_msgs != NULL) free(search_msgs);
818
819                 /* Now that we've purged messages which don't contain the search
820                  * string, treat a MSGS_SEARCH just like a MSGS_ALL from this
821                  * point on.
822                  */
823                 mode = MSGS_ALL;
824         }
825
826         /*
827          * Now iterate through the message list, according to the
828          * criteria supplied by the caller.
829          */
830         if (num_msgs > 0)
831                 for (a = 0; a < num_msgs; ++a) {
832                         if (server_shutting_down) {
833                                 if (need_to_free_re) regfree(&re);
834                                 free(msglist);
835                                 return num_processed;
836                         }
837                         thismsg = msglist[a];
838                         if (mode == MSGS_ALL) {
839                                 is_seen = 0;
840                         }
841                         else {
842                                 is_seen = is_msg_in_sequence_set(
843                                                         vbuf.v_seen, thismsg);
844                                 if (is_seen) lastold = thismsg;
845                         }
846                         if ((thismsg > 0L)
847                             && (
848
849                                        (mode == MSGS_ALL)
850                                        || ((mode == MSGS_OLD) && (is_seen))
851                                        || ((mode == MSGS_NEW) && (!is_seen))
852                                        || ((mode == MSGS_LAST) && (a >= (num_msgs - ref)))
853                                    || ((mode == MSGS_FIRST) && (a < ref))
854                                 || ((mode == MSGS_GT) && (thismsg > ref))
855                                 || ((mode == MSGS_LT) && (thismsg < ref))
856                                 || ((mode == MSGS_EQ) && (thismsg == ref))
857                             )
858                             ) {
859                                 if ((mode == MSGS_NEW) && (CC->user.flags & US_LASTOLD) && (lastold > 0L) && (printed_lastold == 0) && (!is_seen)) {
860                                         if (CallBack)
861                                                 CallBack(lastold, userdata);
862                                         printed_lastold = 1;
863                                         ++num_processed;
864                                 }
865                                 if (CallBack) CallBack(thismsg, userdata);
866                                 ++num_processed;
867                         }
868                 }
869         if (need_to_free_re) regfree(&re);
870
871         /*
872          * We cache the most recent msglist in order to do security checks later
873          */
874         if (CC->client_socket > 0) {
875                 if (CC->cached_msglist != NULL) {
876                         free(CC->cached_msglist);
877                 }
878                 CC->cached_msglist = msglist;
879                 CC->cached_num_msgs = num_msgs;
880         }
881         else {
882                 free(msglist);
883         }
884
885         return num_processed;
886 }
887
888
889
890 /*
891  * memfmout()  -  Citadel text formatter and paginator.
892  *           Although the original purpose of this routine was to format
893  *           text to the reader's screen width, all we're really using it
894  *           for here is to format text out to 80 columns before sending it
895  *           to the client.  The client software may reformat it again.
896  */
897 void memfmout(
898         char *mptr,             /* where are we going to get our text from? */
899         const char *nl          /* string to terminate lines with */
900 ) {
901         int column = 0;
902         unsigned char ch = 0;
903         char outbuf[1024];
904         int len = 0;
905         int nllen = 0;
906
907         if (!mptr) return;
908         nllen = strlen(nl);
909         while (ch=*(mptr++), ch != 0) {
910
911                 if (ch == '\n') {
912                         if (client_write(outbuf, len) == -1)
913                         {
914                                 syslog(LOG_ERR, "msgbase: memfmout() aborting due to write failure");
915                                 return;
916                         }
917                         len = 0;
918                         if (client_write(nl, nllen) == -1)
919                         {
920                                 syslog(LOG_ERR, "msgbase: memfmout() aborting due to write failure");
921                                 return;
922                         }
923                         column = 0;
924                 }
925                 else if (ch == '\r') {
926                         /* Ignore carriage returns.  Newlines are always LF or CRLF but never CR. */
927                 }
928                 else if (isspace(ch)) {
929                         if (column > 72) {              /* Beyond 72 columns, break on the next space */
930                                 if (client_write(outbuf, len) == -1)
931                                 {
932                                         syslog(LOG_ERR, "msgbase: memfmout() aborting due to write failure");
933                                         return;
934                                 }
935                                 len = 0;
936                                 if (client_write(nl, nllen) == -1)
937                                 {
938                                         syslog(LOG_ERR, "msgbase: memfmout() aborting due to write failure");
939                                         return;
940                                 }
941                                 column = 0;
942                         }
943                         else {
944                                 outbuf[len++] = ch;
945                                 ++column;
946                         }
947                 }
948                 else {
949                         outbuf[len++] = ch;
950                         ++column;
951                         if (column > 1000) {            /* Beyond 1000 columns, break anywhere */
952                                 if (client_write(outbuf, len) == -1)
953                                 {
954                                         syslog(LOG_ERR, "msgbase: memfmout() aborting due to write failure");
955                                         return;
956                                 }
957                                 len = 0;
958                                 if (client_write(nl, nllen) == -1)
959                                 {
960                                         syslog(LOG_ERR, "msgbase: memfmout(): aborting due to write failure");
961                                         return;
962                                 }
963                                 column = 0;
964                         }
965                 }
966         }
967         if (len) {
968                 if (client_write(outbuf, len) == -1)
969                 {
970                         syslog(LOG_ERR, "msgbase: memfmout() aborting due to write failure");
971                         return;
972                 }
973                 client_write(nl, nllen);
974                 column = 0;
975         }
976 }
977
978
979
980 /*
981  * Callback function for mime parser that simply lists the part
982  */
983 void list_this_part(char *name, char *filename, char *partnum, char *disp,
984                     void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
985                     char *cbid, void *cbuserdata)
986 {
987         struct ma_info *ma;
988         
989         ma = (struct ma_info *)cbuserdata;
990         if (ma->is_ma == 0) {
991                 cprintf("part=%s|%s|%s|%s|%s|%ld|%s|%s\n",
992                         name, 
993                         filename, 
994                         partnum, 
995                         disp, 
996                         cbtype, 
997                         (long)length, 
998                         cbid, 
999                         cbcharset);
1000         }
1001 }
1002
1003 /* 
1004  * Callback function for multipart prefix
1005  */
1006 void list_this_pref(char *name, char *filename, char *partnum, char *disp,
1007                     void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
1008                     char *cbid, void *cbuserdata)
1009 {
1010         struct ma_info *ma;
1011         
1012         ma = (struct ma_info *)cbuserdata;
1013         if (!strcasecmp(cbtype, "multipart/alternative")) {
1014                 ++ma->is_ma;
1015         }
1016
1017         if (ma->is_ma == 0) {
1018                 cprintf("pref=%s|%s\n", partnum, cbtype);
1019         }
1020 }
1021
1022 /* 
1023  * Callback function for multipart sufffix
1024  */
1025 void list_this_suff(char *name, char *filename, char *partnum, char *disp,
1026                     void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
1027                     char *cbid, void *cbuserdata)
1028 {
1029         struct ma_info *ma;
1030         
1031         ma = (struct ma_info *)cbuserdata;
1032         if (ma->is_ma == 0) {
1033                 cprintf("suff=%s|%s\n", partnum, cbtype);
1034         }
1035         if (!strcasecmp(cbtype, "multipart/alternative")) {
1036                 --ma->is_ma;
1037         }
1038 }
1039
1040
1041 /*
1042  * Callback function for mime parser that opens a section for downloading
1043  * we use serv_files function here: 
1044  */
1045 extern void OpenCmdResult(char *filename, const char *mime_type);
1046 void mime_download(char *name, char *filename, char *partnum, char *disp,
1047                    void *content, char *cbtype, char *cbcharset, size_t length,
1048                    char *encoding, char *cbid, void *cbuserdata)
1049 {
1050         int rv = 0;
1051
1052         /* Silently go away if there's already a download open. */
1053         if (CC->download_fp != NULL)
1054                 return;
1055
1056         if (
1057                 (!IsEmptyStr(partnum) && (!strcasecmp(CC->download_desired_section, partnum)))
1058         ||      (!IsEmptyStr(cbid) && (!strcasecmp(CC->download_desired_section, cbid)))
1059         ) {
1060                 CC->download_fp = tmpfile();
1061                 if (CC->download_fp == NULL) {
1062                         syslog(LOG_EMERG, "msgbase: mime_download() couldn't write: %m");
1063                         cprintf("%d cannot open temporary file: %s\n", ERROR + INTERNAL_ERROR, strerror(errno));
1064                         return;
1065                 }
1066         
1067                 rv = fwrite(content, length, 1, CC->download_fp);
1068                 if (rv <= 0) {
1069                         syslog(LOG_EMERG, "msgbase: mime_download() Couldn't write: %m");
1070                         cprintf("%d unable to write tempfile.\n", ERROR + TOO_BIG);
1071                         fclose(CC->download_fp);
1072                         CC->download_fp = NULL;
1073                         return;
1074                 }
1075                 fflush(CC->download_fp);
1076                 rewind(CC->download_fp);
1077         
1078                 OpenCmdResult(filename, cbtype);
1079         }
1080 }
1081
1082
1083
1084 /*
1085  * Callback function for mime parser that outputs a section all at once.
1086  * We can specify the desired section by part number *or* content-id.
1087  */
1088 void mime_spew_section(char *name, char *filename, char *partnum, char *disp,
1089                    void *content, char *cbtype, char *cbcharset, size_t length,
1090                    char *encoding, char *cbid, void *cbuserdata)
1091 {
1092         int *found_it = (int *)cbuserdata;
1093
1094         if (
1095                 (!IsEmptyStr(partnum) && (!strcasecmp(CC->download_desired_section, partnum)))
1096         ||      (!IsEmptyStr(cbid) && (!strcasecmp(CC->download_desired_section, cbid)))
1097         ) {
1098                 *found_it = 1;
1099                 cprintf("%d %d|-1|%s|%s|%s\n",
1100                         BINARY_FOLLOWS,
1101                         (int)length,
1102                         filename,
1103                         cbtype,
1104                         cbcharset
1105                 );
1106                 client_write(content, length);
1107         }
1108 }
1109
1110 struct CtdlMessage *CtdlDeserializeMessage(long msgnum, int with_body, const char *Buffer, long Length)
1111 {
1112         struct CtdlMessage *ret = NULL;
1113         const char *mptr;
1114         const char *upper_bound;
1115         cit_uint8_t ch;
1116         cit_uint8_t field_header;
1117         eMsgField which;
1118
1119         mptr = Buffer;
1120         upper_bound = Buffer + Length;
1121
1122         /* Parse the three bytes that begin EVERY message on disk.
1123          * The first is always 0xFF, the on-disk magic number.
1124          * The second is the anonymous/public type byte.
1125          * The third is the format type byte (vari, fixed, or MIME).
1126          */
1127         ch = *mptr++;
1128         if (ch != 255) {
1129                 syslog(LOG_ERR, "msgbase: message %ld appears to be corrupted", msgnum);
1130                 return NULL;
1131         }
1132         ret = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
1133         memset(ret, 0, sizeof(struct CtdlMessage));
1134
1135         ret->cm_magic = CTDLMESSAGE_MAGIC;
1136         ret->cm_anon_type = *mptr++;    /* Anon type byte */
1137         ret->cm_format_type = *mptr++;  /* Format type byte */
1138
1139         /*
1140          * The rest is zero or more arbitrary fields.  Load them in.
1141          * We're done when we encounter either a zero-length field or
1142          * have just processed the 'M' (message text) field.
1143          */
1144         do {
1145                 field_header = '\0';
1146                 long len;
1147
1148                 /* work around possibly buggy messages: */
1149                 while (field_header == '\0')
1150                 {
1151                         if (mptr >= upper_bound) {
1152                                 break;
1153                         }
1154                         field_header = *mptr++;
1155                 }
1156                 if (mptr >= upper_bound) {
1157                         break;
1158                 }
1159                 which = field_header;
1160                 len = strlen(mptr);
1161
1162                 CM_SetField(ret, which, mptr, len);
1163
1164                 mptr += len + 1;        /* advance to next field */
1165
1166         } while ((mptr < upper_bound) && (field_header != 'M'));
1167
1168         return (ret);
1169 }
1170
1171
1172 /*
1173  * Load a message from disk into memory.
1174  * This is used by CtdlOutputMsg() and other fetch functions.
1175  *
1176  * NOTE: Caller is responsible for freeing the returned CtdlMessage struct
1177  *       using the CM_Free(); function.
1178  */
1179 struct CtdlMessage *CtdlFetchMessage(long msgnum, int with_body, int run_msg_hooks)
1180 {
1181         struct cdbdata *dmsgtext;
1182         struct CtdlMessage *ret = NULL;
1183
1184         syslog(LOG_DEBUG, "msgbase: CtdlFetchMessage(%ld, %d)", msgnum, with_body);
1185         dmsgtext = cdb_fetch(CDB_MSGMAIN, &msgnum, sizeof(long));
1186         if (dmsgtext == NULL) {
1187                 syslog(LOG_ERR, "msgbase: CtdlFetchMessage(%ld, %d) Failed!", msgnum, with_body);
1188                 return NULL;
1189         }
1190
1191         if (dmsgtext->ptr[dmsgtext->len - 1] != '\0')
1192         {
1193                 syslog(LOG_ERR, "msgbase: CtdlFetchMessage(%ld, %d) Forcefully terminating message!!", msgnum, with_body);
1194                 dmsgtext->ptr[dmsgtext->len - 1] = '\0';
1195         }
1196
1197         ret = CtdlDeserializeMessage(msgnum, with_body, dmsgtext->ptr, dmsgtext->len);
1198
1199         cdb_free(dmsgtext);
1200
1201         if (ret == NULL) {
1202                 return NULL;
1203         }
1204
1205         /* Always make sure there's something in the msg text field.  If
1206          * it's NULL, the message text is most likely stored separately,
1207          * so go ahead and fetch that.  Failing that, just set a dummy
1208          * body so other code doesn't barf.
1209          */
1210         if ( (CM_IsEmpty(ret, eMesageText)) && (with_body) ) {
1211                 dmsgtext = cdb_fetch(CDB_BIGMSGS, &msgnum, sizeof(long));
1212                 if (dmsgtext != NULL) {
1213                         CM_SetAsField(ret, eMesageText, &dmsgtext->ptr, dmsgtext->len - 1);
1214                         cdb_free(dmsgtext);
1215                 }
1216         }
1217         if (CM_IsEmpty(ret, eMesageText)) {
1218                 CM_SetField(ret, eMesageText, HKEY("\r\n\r\n (no text)\r\n"));
1219         }
1220
1221         /* Perform "before read" hooks (aborting if any return nonzero) */
1222         if (run_msg_hooks && (PerformMessageHooks(ret, NULL, EVT_BEFOREREAD) > 0)) {
1223                 CM_Free(ret);
1224                 return NULL;
1225         }
1226
1227         return (ret);
1228 }
1229
1230
1231
1232 /*
1233  * Pre callback function for multipart/alternative
1234  *
1235  * NOTE: this differs from the standard behavior for a reason.  Normally when
1236  *       displaying multipart/alternative you want to show the _last_ usable
1237  *       format in the message.  Here we show the _first_ one, because it's
1238  *       usually text/plain.  Since this set of functions is designed for text
1239  *       output to non-MIME-aware clients, this is the desired behavior.
1240  *
1241  */
1242 void fixed_output_pre(char *name, char *filename, char *partnum, char *disp,
1243                 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
1244                 char *cbid, void *cbuserdata)
1245 {
1246         struct ma_info *ma;
1247         
1248         ma = (struct ma_info *)cbuserdata;
1249         syslog(LOG_DEBUG, "msgbase: fixed_output_pre() type=<%s>", cbtype);     
1250         if (!strcasecmp(cbtype, "multipart/alternative")) {
1251                 ++ma->is_ma;
1252                 ma->did_print = 0;
1253         }
1254         if (!strcasecmp(cbtype, "message/rfc822")) {
1255                 ++ma->freeze;
1256         }
1257 }
1258
1259 /*
1260  * Post callback function for multipart/alternative
1261  */
1262 void fixed_output_post(char *name, char *filename, char *partnum, char *disp,
1263                 void *content, char *cbtype, char *cbcharset, size_t length,
1264                 char *encoding, char *cbid, void *cbuserdata)
1265 {
1266         struct ma_info *ma;
1267         
1268         ma = (struct ma_info *)cbuserdata;
1269         syslog(LOG_DEBUG, "msgbase: fixed_output_post() type=<%s>", cbtype);    
1270         if (!strcasecmp(cbtype, "multipart/alternative")) {
1271                 --ma->is_ma;
1272                 ma->did_print = 0;
1273         }
1274         if (!strcasecmp(cbtype, "message/rfc822")) {
1275                 --ma->freeze;
1276         }
1277 }
1278
1279 /*
1280  * Inline callback function for mime parser that wants to display text
1281  */
1282 void fixed_output(char *name, char *filename, char *partnum, char *disp,
1283                 void *content, char *cbtype, char *cbcharset, size_t length,
1284                 char *encoding, char *cbid, void *cbuserdata)
1285 {
1286         char *ptr;
1287         char *wptr;
1288         size_t wlen;
1289         struct ma_info *ma;
1290
1291         ma = (struct ma_info *)cbuserdata;
1292
1293         syslog(LOG_DEBUG,
1294                 "msgbase: fixed_output() part %s: %s (%s) (%ld bytes)",
1295                 partnum, filename, cbtype, (long)length
1296         );
1297
1298         /*
1299          * If we're in the middle of a multipart/alternative scope and
1300          * we've already printed another section, skip this one.
1301          */     
1302         if ( (ma->is_ma) && (ma->did_print) ) {
1303                 syslog(LOG_DEBUG, "msgbase: skipping part %s (%s)", partnum, cbtype);
1304                 return;
1305         }
1306         ma->did_print = 1;
1307
1308         if ( (!strcasecmp(cbtype, "text/plain")) 
1309            || (IsEmptyStr(cbtype)) ) {
1310                 wptr = content;
1311                 if (length > 0) {
1312                         client_write(wptr, length);
1313                         if (wptr[length-1] != '\n') {
1314                                 cprintf("\n");
1315                         }
1316                 }
1317                 return;
1318         }
1319
1320         if (!strcasecmp(cbtype, "text/html")) {
1321                 ptr = html_to_ascii(content, length, 80, 0);
1322                 wlen = strlen(ptr);
1323                 client_write(ptr, wlen);
1324                 if ((wlen > 0) && (ptr[wlen-1] != '\n')) {
1325                         cprintf("\n");
1326                 }
1327                 free(ptr);
1328                 return;
1329         }
1330
1331         if (ma->use_fo_hooks) {
1332                 if (PerformFixedOutputHooks(cbtype, content, length)) {
1333                 /* above function returns nonzero if it handled the part */
1334                         return;
1335                 }
1336         }
1337
1338         if (strncasecmp(cbtype, "multipart/", 10)) {
1339                 cprintf("Part %s: %s (%s) (%ld bytes)\r\n",
1340                         partnum, filename, cbtype, (long)length);
1341                 return;
1342         }
1343 }
1344
1345 /*
1346  * The client is elegant and sophisticated and wants to be choosy about
1347  * MIME content types, so figure out which multipart/alternative part
1348  * we're going to send.
1349  *
1350  * We use a system of weights.  When we find a part that matches one of the
1351  * MIME types we've declared as preferential, we can store it in ma->chosen_part
1352  * and then set ma->chosen_pref to that MIME type's position in our preference
1353  * list.  If we then hit another match, we only replace the first match if
1354  * the preference value is lower.
1355  */
1356 void choose_preferred(char *name, char *filename, char *partnum, char *disp,
1357                 void *content, char *cbtype, char *cbcharset, size_t length,
1358                 char *encoding, char *cbid, void *cbuserdata)
1359 {
1360         char buf[1024];
1361         int i;
1362         struct ma_info *ma;
1363         
1364         ma = (struct ma_info *)cbuserdata;
1365
1366         // NOTE: REMOVING THIS CONDITIONAL FIXES BUG 220
1367         //       http://bugzilla.citadel.org/show_bug.cgi?id=220
1368         // I don't know if there are any side effects!  Please TEST TEST TEST
1369         //if (ma->is_ma > 0) {
1370
1371         for (i=0; i<num_tokens(CC->preferred_formats, '|'); ++i) {
1372                 extract_token(buf, CC->preferred_formats, i, '|', sizeof buf);
1373                 if ( (!strcasecmp(buf, cbtype)) && (!ma->freeze) ) {
1374                         if (i < ma->chosen_pref) {
1375                                 syslog(LOG_DEBUG, "msgbase: setting chosen part to <%s>", partnum);
1376                                 safestrncpy(ma->chosen_part, partnum, sizeof ma->chosen_part);
1377                                 ma->chosen_pref = i;
1378                         }
1379                 }
1380         }
1381 }
1382
1383 /*
1384  * Now that we've chosen our preferred part, output it.
1385  */
1386 void output_preferred(char *name, 
1387                       char *filename, 
1388                       char *partnum, 
1389                       char *disp,
1390                       void *content, 
1391                       char *cbtype, 
1392                       char *cbcharset, 
1393                       size_t length,
1394                       char *encoding, 
1395                       char *cbid, 
1396                       void *cbuserdata)
1397 {
1398         int i;
1399         char buf[128];
1400         int add_newline = 0;
1401         char *text_content;
1402         struct ma_info *ma;
1403         char *decoded = NULL;
1404         size_t bytes_decoded;
1405         int rc = 0;
1406
1407         ma = (struct ma_info *)cbuserdata;
1408
1409         /* This is not the MIME part you're looking for... */
1410         if (strcasecmp(partnum, ma->chosen_part)) return;
1411
1412         /* If the content-type of this part is in our preferred formats
1413          * list, we can simply output it verbatim.
1414          */
1415         for (i=0; i<num_tokens(CC->preferred_formats, '|'); ++i) {
1416                 extract_token(buf, CC->preferred_formats, i, '|', sizeof buf);
1417                 if (!strcasecmp(buf, cbtype)) {
1418                         /* Yeah!  Go!  W00t!! */
1419                         if (ma->dont_decode == 0) 
1420                                 rc = mime_decode_now (content, 
1421                                                       length,
1422                                                       encoding,
1423                                                       &decoded,
1424                                                       &bytes_decoded);
1425                         if (rc < 0)
1426                                 break; /* Give us the chance, maybe theres another one. */
1427
1428                         if (rc == 0) text_content = (char *)content;
1429                         else {
1430                                 text_content = decoded;
1431                                 length = bytes_decoded;
1432                         }
1433
1434                         if (text_content[length-1] != '\n') {
1435                                 ++add_newline;
1436                         }
1437                         cprintf("Content-type: %s", cbtype);
1438                         if (!IsEmptyStr(cbcharset)) {
1439                                 cprintf("; charset=%s", cbcharset);
1440                         }
1441                         cprintf("\nContent-length: %d\n",
1442                                 (int)(length + add_newline) );
1443                         if (!IsEmptyStr(encoding)) {
1444                                 cprintf("Content-transfer-encoding: %s\n", encoding);
1445                         }
1446                         else {
1447                                 cprintf("Content-transfer-encoding: 7bit\n");
1448                         }
1449                         cprintf("X-Citadel-MSG4-Partnum: %s\n", partnum);
1450                         cprintf("\n");
1451                         if (client_write(text_content, length) == -1)
1452                         {
1453                                 syslog(LOG_ERR, "msgbase: output_preferred() aborting due to write failure");
1454                                 return;
1455                         }
1456                         if (add_newline) cprintf("\n");
1457                         if (decoded != NULL) free(decoded);
1458                         return;
1459                 }
1460         }
1461
1462         /* No translations required or possible: output as text/plain */
1463         cprintf("Content-type: text/plain\n\n");
1464         rc = 0;
1465         if (ma->dont_decode == 0)
1466                 rc = mime_decode_now (content, 
1467                                       length,
1468                                       encoding,
1469                                       &decoded,
1470                                       &bytes_decoded);
1471         if (rc < 0)
1472                 return; /* Give us the chance, maybe theres another one. */
1473         
1474         if (rc == 0) text_content = (char *)content;
1475         else {
1476                 text_content = decoded;
1477                 length = bytes_decoded;
1478         }
1479
1480         fixed_output(name, filename, partnum, disp, text_content, cbtype, cbcharset,
1481                         length, encoding, cbid, cbuserdata);
1482         if (decoded != NULL) free(decoded);
1483 }
1484
1485
1486 struct encapmsg {
1487         char desired_section[64];
1488         char *msg;
1489         size_t msglen;
1490 };
1491
1492
1493 /*
1494  * Callback function for
1495  */
1496 void extract_encapsulated_message(char *name, char *filename, char *partnum, char *disp,
1497                    void *content, char *cbtype, char *cbcharset, size_t length,
1498                    char *encoding, char *cbid, void *cbuserdata)
1499 {
1500         struct encapmsg *encap;
1501
1502         encap = (struct encapmsg *)cbuserdata;
1503
1504         /* Only proceed if this is the desired section... */
1505         if (!strcasecmp(encap->desired_section, partnum)) {
1506                 encap->msglen = length;
1507                 encap->msg = malloc(length + 2);
1508                 memcpy(encap->msg, content, length);
1509                 return;
1510         }
1511 }
1512
1513
1514 /*
1515  * Determine whether the specified message exists in the cached_msglist
1516  * (This is a security check)
1517  */
1518 int check_cached_msglist(long msgnum) {
1519
1520         /* cases in which we skip the check */
1521         if (!CC) return om_ok;                                          /* not a session */
1522         if (CC->client_socket <= 0) return om_ok;                       /* not a client session */
1523         if (CC->cached_msglist == NULL) return om_access_denied;        /* no msglist fetched */
1524         if (CC->cached_num_msgs == 0) return om_access_denied;          /* nothing to check */
1525
1526
1527         /* Do a binary search within the cached_msglist for the requested msgnum */
1528         int min = 0;
1529         int max = (CC->cached_num_msgs - 1);
1530
1531         while (max >= min) {
1532                 int middle = min + (max-min) / 2 ;
1533                 if (msgnum == CC->cached_msglist[middle]) {
1534                         return om_ok;
1535                 }
1536                 if (msgnum > CC->cached_msglist[middle]) {
1537                         min = middle + 1;
1538                 }
1539                 else {
1540                         max = middle - 1;
1541                 }
1542         }
1543
1544         return om_access_denied;
1545 }
1546
1547
1548
1549 /*
1550  * Get a message off disk.  (returns om_* values found in msgbase.h)
1551  * 
1552  */
1553 int CtdlOutputMsg(long msg_num,         /* message number (local) to fetch */
1554                 int mode,               /* how would you like that message? */
1555                 int headers_only,       /* eschew the message body? */
1556                 int do_proto,           /* do Citadel protocol responses? */
1557                 int crlf,               /* Use CRLF newlines instead of LF? */
1558                 char *section,          /* NULL or a message/rfc822 section */
1559                 int flags,              /* various flags; see msgbase.h */
1560                 char **Author,
1561                 char **Address,
1562                 char **MessageID
1563 ) {
1564         struct CtdlMessage *TheMessage = NULL;
1565         int retcode = CIT_OK;
1566         struct encapmsg encap;
1567         int r;
1568
1569         syslog(LOG_DEBUG, "msgbase: CtdlOutputMsg(msgnum=%ld, mode=%d, section=%s)", 
1570                 msg_num, mode,
1571                 (section ? section : "<>")
1572         );
1573
1574         r = CtdlDoIHavePermissionToReadMessagesInThisRoom();
1575         if (r != om_ok) {
1576                 if (do_proto) {
1577                         if (r == om_not_logged_in) {
1578                                 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
1579                         }
1580                         else {
1581                                 cprintf("%d An unknown error has occurred.\n", ERROR);
1582                         }
1583                 }
1584                 return(r);
1585         }
1586
1587         /*
1588          * Check to make sure the message is actually IN this room
1589          */
1590         r = check_cached_msglist(msg_num);
1591         if (r == om_access_denied) {
1592                 /* Not in the cache?  We get ONE shot to check it again. */
1593                 CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL, NULL, NULL);
1594                 r = check_cached_msglist(msg_num);
1595         }
1596         if (r != om_ok) {
1597                 syslog(LOG_DEBUG, "msgbase: security check fail; message %ld is not in %s",
1598                            msg_num, CC->room.QRname
1599                 );
1600                 if (do_proto) {
1601                         if (r == om_access_denied) {
1602                                 cprintf("%d message %ld was not found in this room\n",
1603                                         ERROR + HIGHER_ACCESS_REQUIRED,
1604                                         msg_num
1605                                 );
1606                         }
1607                 }
1608                 return(r);
1609         }
1610
1611         /*
1612          * Fetch the message from disk.  If we're in HEADERS_FAST mode,
1613          * request that we don't even bother loading the body into memory.
1614          */
1615         if (headers_only == HEADERS_FAST) {
1616                 TheMessage = CtdlFetchMessage(msg_num, 0, 1);
1617         }
1618         else {
1619                 TheMessage = CtdlFetchMessage(msg_num, 1, 1);
1620         }
1621
1622         if (TheMessage == NULL) {
1623                 if (do_proto) cprintf("%d Can't locate msg %ld on disk\n",
1624                         ERROR + MESSAGE_NOT_FOUND, msg_num);
1625                 return(om_no_such_msg);
1626         }
1627
1628         /* Here is the weird form of this command, to process only an
1629          * encapsulated message/rfc822 section.
1630          */
1631         if (section) if (!IsEmptyStr(section)) if (strcmp(section, "0")) {
1632                 memset(&encap, 0, sizeof encap);
1633                 safestrncpy(encap.desired_section, section, sizeof encap.desired_section);
1634                 mime_parser(CM_RANGE(TheMessage, eMesageText),
1635                             *extract_encapsulated_message,
1636                             NULL, NULL, (void *)&encap, 0
1637                         );
1638
1639                 if ((Author != NULL) && (*Author == NULL))
1640                 {
1641                         long len;
1642                         CM_GetAsField(TheMessage, eAuthor, Author, &len);
1643                 }
1644                 if ((Address != NULL) && (*Address == NULL))
1645                 {       
1646                         long len;
1647                         CM_GetAsField(TheMessage, erFc822Addr, Address, &len);
1648                 }
1649                 if ((MessageID != NULL) && (*MessageID == NULL))
1650                 {       
1651                         long len;
1652                         CM_GetAsField(TheMessage, emessageId, MessageID, &len);
1653                 }
1654                 CM_Free(TheMessage);
1655                 TheMessage = NULL;
1656
1657                 if (encap.msg) {
1658                         encap.msg[encap.msglen] = 0;
1659                         TheMessage = convert_internet_message(encap.msg);
1660                         encap.msg = NULL;       /* no free() here, TheMessage owns it now */
1661
1662                         /* Now we let it fall through to the bottom of this
1663                          * function, because TheMessage now contains the
1664                          * encapsulated message instead of the top-level
1665                          * message.  Isn't that neat?
1666                          */
1667                 }
1668                 else {
1669                         if (do_proto) {
1670                                 cprintf("%d msg %ld has no part %s\n",
1671                                         ERROR + MESSAGE_NOT_FOUND,
1672                                         msg_num,
1673                                         section);
1674                         }
1675                         retcode = om_no_such_msg;
1676                 }
1677
1678         }
1679
1680         /* Ok, output the message now */
1681         if (retcode == CIT_OK)
1682                 retcode = CtdlOutputPreLoadedMsg(TheMessage, mode, headers_only, do_proto, crlf, flags);
1683         if ((Author != NULL) && (*Author == NULL))
1684         {
1685                 long len;
1686                 CM_GetAsField(TheMessage, eAuthor, Author, &len);
1687         }
1688         if ((Address != NULL) && (*Address == NULL))
1689         {       
1690                 long len;
1691                 CM_GetAsField(TheMessage, erFc822Addr, Address, &len);
1692         }
1693         if ((MessageID != NULL) && (*MessageID == NULL))
1694         {       
1695                 long len;
1696                 CM_GetAsField(TheMessage, emessageId, MessageID, &len);
1697         }
1698
1699         CM_Free(TheMessage);
1700
1701         return(retcode);
1702 }
1703
1704
1705
1706 void OutputCtdlMsgHeaders(
1707         struct CtdlMessage *TheMessage,
1708         int do_proto)           /* do Citadel protocol responses? */
1709 {
1710         int i;
1711         int suppress_f = 0;
1712         char buf[SIZ];
1713         char display_name[256];
1714
1715         /* begin header processing loop for Citadel message format */
1716         safestrncpy(display_name, "<unknown>", sizeof display_name);
1717         if (!CM_IsEmpty(TheMessage, eAuthor)) {
1718                 strcpy(buf, TheMessage->cm_fields[eAuthor]);
1719                 if (TheMessage->cm_anon_type == MES_ANONONLY) {
1720                         safestrncpy(display_name, "****", sizeof display_name);
1721                 }
1722                 else if (TheMessage->cm_anon_type == MES_ANONOPT) {
1723                         safestrncpy(display_name, "anonymous", sizeof display_name);
1724                 }
1725                 else {
1726                         safestrncpy(display_name, buf, sizeof display_name);
1727                 }
1728                 if ((is_room_aide())
1729                     && ((TheMessage->cm_anon_type == MES_ANONONLY)
1730                         || (TheMessage->cm_anon_type == MES_ANONOPT))) {
1731                         size_t tmp = strlen(display_name);
1732                         snprintf(&display_name[tmp],
1733                                  sizeof display_name - tmp,
1734                                  " [%s]", buf);
1735                 }
1736         }
1737
1738         /* Don't show Internet address for users on the
1739          * local Citadel network.
1740          */
1741         suppress_f = 0;
1742         if (!CM_IsEmpty(TheMessage, eNodeName) &&
1743             (haschar(TheMessage->cm_fields[eNodeName], '.') == 0))
1744         {
1745                 suppress_f = 1;
1746         }
1747
1748         /* Now spew the header fields in the order we like them. */
1749         for (i=0; i< NDiskFields; ++i) {
1750                 eMsgField Field;
1751                 Field = FieldOrder[i];
1752                 if (Field != eMesageText) {
1753                         if ( (!CM_IsEmpty(TheMessage, Field))
1754                              && (msgkeys[Field] != NULL) ) {
1755                                 if ((Field == eenVelopeTo) ||
1756                                     (Field == eRecipient) ||
1757                                     (Field == eCarbonCopY)) {
1758                                         sanitize_truncated_recipient(TheMessage->cm_fields[Field]);
1759                                 }
1760                                 if (Field == eAuthor) {
1761                                         if (do_proto) cprintf("%s=%s\n",
1762                                                               msgkeys[Field],
1763                                                               display_name);
1764                                 }
1765                                 else if ((Field == erFc822Addr) && (suppress_f)) {
1766                                         /* do nothing */
1767                                 }
1768                                 /* Masquerade display name if needed */
1769                                 else {
1770                                         if (do_proto) cprintf("%s=%s\n",
1771                                                               msgkeys[Field],
1772                                                               TheMessage->cm_fields[Field]
1773                                                 );
1774                                 }
1775                         }
1776                 }
1777         }
1778
1779 }
1780
1781 void OutputRFC822MsgHeaders(
1782         struct CtdlMessage *TheMessage,
1783         int flags,              /* should the bessage be exported clean */
1784         const char *nl, int nlen,
1785         char *mid, long sizeof_mid,
1786         char *suser, long sizeof_suser,
1787         char *luser, long sizeof_luser,
1788         char *fuser, long sizeof_fuser,
1789         char *snode, long sizeof_snode)
1790 {
1791         char datestamp[100];
1792         int subject_found = 0;
1793         char buf[SIZ];
1794         int i, j, k;
1795         char *mptr = NULL;
1796         char *mpptr = NULL;
1797         char *hptr;
1798
1799         for (i = 0; i < NDiskFields; ++i) {
1800                 if (TheMessage->cm_fields[FieldOrder[i]]) {
1801                         mptr = mpptr = TheMessage->cm_fields[FieldOrder[i]];
1802                         switch (FieldOrder[i]) {
1803                         case eAuthor:
1804                                 safestrncpy(luser, mptr, sizeof_luser);
1805                                 safestrncpy(suser, mptr, sizeof_suser);
1806                                 break;
1807                         case eCarbonCopY:
1808                                 if ((flags & QP_EADDR) != 0) {
1809                                         mptr = qp_encode_email_addrs(mptr);
1810                                 }
1811                                 sanitize_truncated_recipient(mptr);
1812                                 cprintf("CC: %s%s", mptr, nl);
1813                                 break;
1814                         case eMessagePath:
1815                                 cprintf("Return-Path: %s%s", mptr, nl);
1816                                 break;
1817                         case eListID:
1818                                 cprintf("List-ID: %s%s", mptr, nl);
1819                                 break;
1820                         case eenVelopeTo:
1821                                 if ((flags & QP_EADDR) != 0) 
1822                                         mptr = qp_encode_email_addrs(mptr);
1823                                 hptr = mptr;
1824                                 while ((*hptr != '\0') && isspace(*hptr))
1825                                         hptr ++;
1826                                 if (!IsEmptyStr(hptr))
1827                                         cprintf("Envelope-To: %s%s", hptr, nl);
1828                                 break;
1829                         case eMsgSubject:
1830                                 cprintf("Subject: %s%s", mptr, nl);
1831                                 subject_found = 1;
1832                                 break;
1833                         case emessageId:
1834                                 safestrncpy(mid, mptr, sizeof_mid); /// TODO: detect @ here and copy @nodename in if not found.
1835                                 break;
1836                         case erFc822Addr:
1837                                 safestrncpy(fuser, mptr, sizeof_fuser);
1838                         /* case eOriginalRoom:
1839                            cprintf("X-Citadel-Room: %s%s",
1840                            mptr, nl)
1841                            break;
1842                            ; */
1843                         case eNodeName:
1844                                 safestrncpy(snode, mptr, sizeof_snode);
1845                                 break;
1846                         case eRecipient:
1847                                 if (haschar(mptr, '@') == 0)
1848                                 {
1849                                         sanitize_truncated_recipient(mptr);
1850                                         cprintf("To: %s@%s", mptr, CtdlGetConfigStr("c_fqdn"));
1851                                         cprintf("%s", nl);
1852                                 }
1853                                 else
1854                                 {
1855                                         if ((flags & QP_EADDR) != 0) {
1856                                                 mptr = qp_encode_email_addrs(mptr);
1857                                         }
1858                                         sanitize_truncated_recipient(mptr);
1859                                         cprintf("To: %s", mptr);
1860                                         cprintf("%s", nl);
1861                                 }
1862                                 break;
1863                         case eTimestamp:
1864                                 datestring(datestamp, sizeof datestamp,
1865                                            atol(mptr), DATESTRING_RFC822);
1866                                 cprintf("Date: %s%s", datestamp, nl);
1867                                 break;
1868                         case eWeferences:
1869                                 cprintf("References: ");
1870                                 k = num_tokens(mptr, '|');
1871                                 for (j=0; j<k; ++j) {
1872                                         extract_token(buf, mptr, j, '|', sizeof buf);
1873                                         cprintf("<%s>", buf);
1874                                         if (j == (k-1)) {
1875                                                 cprintf("%s", nl);
1876                                         }
1877                                         else {
1878                                                 cprintf(" ");
1879                                         }
1880                                 }
1881                                 break;
1882                         case eReplyTo:
1883                                 hptr = mptr;
1884                                 while ((*hptr != '\0') && isspace(*hptr))
1885                                         hptr ++;
1886                                 if (!IsEmptyStr(hptr))
1887                                         cprintf("Reply-To: %s%s", mptr, nl);
1888                                 break;
1889
1890                         case eRemoteRoom:
1891                         case eDestination:
1892                         case eExclusiveID:
1893                         case eHumanNode:
1894                         case eJournal:
1895                         case eMesageText:
1896                         case eBig_message:
1897                         case eOriginalRoom:
1898                         case eSpecialField:
1899                         case eErrorMsg:
1900                         case eSuppressIdx:
1901                         case eExtnotify:
1902                         case eVltMsgNum:
1903                                 /* these don't map to mime message headers. */
1904                                 break;
1905
1906                         }
1907                         if (mptr != mpptr)
1908                                 free (mptr);
1909                 }
1910         }
1911         if (subject_found == 0) {
1912                 cprintf("Subject: (no subject)%s", nl);
1913         }
1914 }
1915
1916
1917 void Dump_RFC822HeadersBody(
1918         struct CtdlMessage *TheMessage,
1919         int headers_only,       /* eschew the message body? */
1920         int flags,              /* should the bessage be exported clean? */
1921
1922         const char *nl, int nlen)
1923 {
1924         cit_uint8_t prev_ch;
1925         int eoh = 0;
1926         const char *StartOfText = StrBufNOTNULL;
1927         char outbuf[1024];
1928         int outlen = 0;
1929         int nllen = strlen(nl);
1930         char *mptr;
1931         int lfSent = 0;
1932
1933         mptr = TheMessage->cm_fields[eMesageText];
1934
1935
1936         prev_ch = '\0';
1937         while (*mptr != '\0') {
1938                 if (*mptr == '\r') {
1939                         /* do nothing */
1940                 }
1941                 else {
1942                         if ((!eoh) &&
1943                             (*mptr == '\n'))
1944                         {
1945                                 eoh = (*(mptr+1) == '\r') && (*(mptr+2) == '\n');
1946                                 if (!eoh)
1947                                         eoh = *(mptr+1) == '\n';
1948                                 if (eoh)
1949                                 {
1950                                         StartOfText = mptr;
1951                                         StartOfText = strchr(StartOfText, '\n');
1952                                         StartOfText = strchr(StartOfText, '\n');
1953                                 }
1954                         }
1955                         if (((headers_only == HEADERS_NONE) && (mptr >= StartOfText)) ||
1956                             ((headers_only == HEADERS_ONLY) && (mptr < StartOfText)) ||
1957                             ((headers_only != HEADERS_NONE) && 
1958                              (headers_only != HEADERS_ONLY))
1959                                 ) {
1960                                 if (*mptr == '\n') {
1961                                         memcpy(&outbuf[outlen], nl, nllen);
1962                                         outlen += nllen;
1963                                         outbuf[outlen] = '\0';
1964                                 }
1965                                 else {
1966                                         outbuf[outlen++] = *mptr;
1967                                 }
1968                         }
1969                 }
1970                 if (flags & ESC_DOT)
1971                 {
1972                         if ((prev_ch == '\n') && 
1973                             (*mptr == '.') && 
1974                             ((*(mptr+1) == '\r') || (*(mptr+1) == '\n')))
1975                         {
1976                                 outbuf[outlen++] = '.';
1977                         }
1978                         prev_ch = *mptr;
1979                 }
1980                 ++mptr;
1981                 if (outlen > 1000) {
1982                         if (client_write(outbuf, outlen) == -1)
1983                         {
1984                                 syslog(LOG_ERR, "msgbase: Dump_RFC822HeadersBody() aborting due to write failure");
1985                                 return;
1986                         }
1987                         lfSent =  (outbuf[outlen - 1] == '\n');
1988                         outlen = 0;
1989                 }
1990         }
1991         if (outlen > 0) {
1992                 client_write(outbuf, outlen);
1993                 lfSent =  (outbuf[outlen - 1] == '\n');
1994         }
1995         if (!lfSent)
1996                 client_write(nl, nlen);
1997 }
1998
1999
2000
2001 /* If the format type on disk is 1 (fixed-format), then we want
2002  * everything to be output completely literally ... regardless of
2003  * what message transfer format is in use.
2004  */
2005 void DumpFormatFixed(
2006         struct CtdlMessage *TheMessage,
2007         int mode,               /* how would you like that message? */
2008         const char *nl, int nllen)
2009 {
2010         cit_uint8_t ch;
2011         char buf[SIZ];
2012         int buflen;
2013         int xlline = 0;
2014         char *mptr;
2015
2016         mptr = TheMessage->cm_fields[eMesageText];
2017         
2018         if (mode == MT_MIME) {
2019                 cprintf("Content-type: text/plain\n\n");
2020         }
2021         *buf = '\0';
2022         buflen = 0;
2023         while (ch = *mptr++, ch > 0) {
2024                 if (ch == '\n')
2025                         ch = '\r';
2026
2027                 if ((buflen > 250) && (!xlline)){
2028                         int tbuflen;
2029                         tbuflen = buflen;
2030
2031                         while ((buflen > 0) && 
2032                                (!isspace(buf[buflen])))
2033                                 buflen --;
2034                         if (buflen == 0) {
2035                                 xlline = 1;
2036                         }
2037                         else {
2038                                 mptr -= tbuflen - buflen;
2039                                 buf[buflen] = '\0';
2040                                 ch = '\r';
2041                         }
2042                 }
2043                 /* if we reach the outer bounds of our buffer, 
2044                    abort without respect what whe purge. */
2045                 if (xlline && 
2046                     ((isspace(ch)) || 
2047                      (buflen > SIZ - nllen - 2)))
2048                         ch = '\r';
2049
2050                 if (ch == '\r') {
2051                         memcpy (&buf[buflen], nl, nllen);
2052                         buflen += nllen;
2053                         buf[buflen] = '\0';
2054
2055                         if (client_write(buf, buflen) == -1)
2056                         {
2057                                 syslog(LOG_ERR, "msgbase: DumpFormatFixed() aborting due to write failure");
2058                                 return;
2059                         }
2060                         *buf = '\0';
2061                         buflen = 0;
2062                         xlline = 0;
2063                 } else {
2064                         buf[buflen] = ch;
2065                         buflen++;
2066                 }
2067         }
2068         buf[buflen] = '\0';
2069         if (!IsEmptyStr(buf))
2070                 cprintf("%s%s", buf, nl);
2071 }
2072
2073 /*
2074  * Get a message off disk.  (returns om_* values found in msgbase.h)
2075  */
2076 int CtdlOutputPreLoadedMsg(
2077                 struct CtdlMessage *TheMessage,
2078                 int mode,               /* how would you like that message? */
2079                 int headers_only,       /* eschew the message body? */
2080                 int do_proto,           /* do Citadel protocol responses? */
2081                 int crlf,               /* Use CRLF newlines instead of LF? */
2082                 int flags               /* should the bessage be exported clean? */
2083 ) {
2084         int i;
2085         const char *nl; /* newline string */
2086         int nlen;
2087         struct ma_info ma;
2088
2089         /* Buffers needed for RFC822 translation.  These are all filled
2090          * using functions that are bounds-checked, and therefore we can
2091          * make them substantially smaller than SIZ.
2092          */
2093         char suser[100];
2094         char luser[100];
2095         char fuser[100];
2096         char snode[100];
2097         char mid[100];
2098
2099         syslog(LOG_DEBUG, "msgbase: CtdlOutputPreLoadedMsg(TheMessage=%s, %d, %d, %d, %d",
2100                    ((TheMessage == NULL) ? "NULL" : "not null"),
2101                    mode, headers_only, do_proto, crlf
2102         );
2103
2104         strcpy(mid, "unknown");
2105         nl = (crlf ? "\r\n" : "\n");
2106         nlen = crlf ? 2 : 1;
2107
2108         if (!CM_IsValidMsg(TheMessage)) {
2109                 syslog(LOG_ERR, "msgbase: error; invalid preloaded message for output");
2110                 return(om_no_such_msg);
2111         }
2112
2113         /* Suppress envelope recipients if required to avoid disclosing BCC addresses.
2114          * Pad it with spaces in order to avoid changing the RFC822 length of the message.
2115          */
2116         if ( (flags & SUPPRESS_ENV_TO) && (!CM_IsEmpty(TheMessage, eenVelopeTo)) ) {
2117                 memset(TheMessage->cm_fields[eenVelopeTo], ' ', TheMessage->cm_lengths[eenVelopeTo]);
2118         }
2119                 
2120         /* Are we downloading a MIME component? */
2121         if (mode == MT_DOWNLOAD) {
2122                 if (TheMessage->cm_format_type != FMT_RFC822) {
2123                         if (do_proto)
2124                                 cprintf("%d This is not a MIME message.\n",
2125                                 ERROR + ILLEGAL_VALUE);
2126                 } else if (CC->download_fp != NULL) {
2127                         if (do_proto) cprintf(
2128                                 "%d You already have a download open.\n",
2129                                 ERROR + RESOURCE_BUSY);
2130                 } else {
2131                         /* Parse the message text component */
2132                         mime_parser(CM_RANGE(TheMessage, eMesageText),
2133                                     *mime_download, NULL, NULL, NULL, 0);
2134                         /* If there's no file open by this time, the requested
2135                          * section wasn't found, so print an error
2136                          */
2137                         if (CC->download_fp == NULL) {
2138                                 if (do_proto) cprintf(
2139                                         "%d Section %s not found.\n",
2140                                         ERROR + FILE_NOT_FOUND,
2141                                         CC->download_desired_section);
2142                         }
2143                 }
2144                 return((CC->download_fp != NULL) ? om_ok : om_mime_error);
2145         }
2146
2147         /* MT_SPEW_SECTION is like MT_DOWNLOAD except it outputs the whole MIME part
2148          * in a single server operation instead of opening a download file.
2149          */
2150         if (mode == MT_SPEW_SECTION) {
2151                 if (TheMessage->cm_format_type != FMT_RFC822) {
2152                         if (do_proto)
2153                                 cprintf("%d This is not a MIME message.\n",
2154                                 ERROR + ILLEGAL_VALUE);
2155                 } else {
2156                         /* Parse the message text component */
2157                         int found_it = 0;
2158
2159                         mime_parser(CM_RANGE(TheMessage, eMesageText),
2160                                     *mime_spew_section, NULL, NULL, (void *)&found_it, 0);
2161                         /* If section wasn't found, print an error
2162                          */
2163                         if (!found_it) {
2164                                 if (do_proto) cprintf(
2165                                         "%d Section %s not found.\n",
2166                                         ERROR + FILE_NOT_FOUND,
2167                                         CC->download_desired_section);
2168                         }
2169                 }
2170                 return((CC->download_fp != NULL) ? om_ok : om_mime_error);
2171         }
2172
2173         /* now for the user-mode message reading loops */
2174         if (do_proto) cprintf("%d msg:\n", LISTING_FOLLOWS);
2175
2176         /* Does the caller want to skip the headers? */
2177         if (headers_only == HEADERS_NONE) goto START_TEXT;
2178
2179         /* Tell the client which format type we're using. */
2180         if ( (mode == MT_CITADEL) && (do_proto) ) {
2181                 cprintf("type=%d\n", TheMessage->cm_format_type);
2182         }
2183
2184         /* nhdr=yes means that we're only displaying headers, no body */
2185         if ( (TheMessage->cm_anon_type == MES_ANONONLY)
2186            && ((mode == MT_CITADEL) || (mode == MT_MIME))
2187            && (do_proto)
2188            ) {
2189                 cprintf("nhdr=yes\n");
2190         }
2191
2192         if ((mode == MT_CITADEL) || (mode == MT_MIME)) 
2193                 OutputCtdlMsgHeaders(TheMessage, do_proto);
2194
2195
2196         /* begin header processing loop for RFC822 transfer format */
2197         strcpy(suser, "");
2198         strcpy(luser, "");
2199         strcpy(fuser, "");
2200         memcpy(snode, CtdlGetConfigStr("c_nodename"), strlen(CtdlGetConfigStr("c_nodename")) + 1);
2201         if (mode == MT_RFC822) 
2202                 OutputRFC822MsgHeaders(
2203                         TheMessage,
2204                         flags,
2205                         nl, nlen,
2206                         mid, sizeof(mid),
2207                         suser, sizeof(suser),
2208                         luser, sizeof(luser),
2209                         fuser, sizeof(fuser),
2210                         snode, sizeof(snode)
2211                         );
2212
2213
2214         for (i=0; !IsEmptyStr(&suser[i]); ++i) {
2215                 suser[i] = tolower(suser[i]);
2216                 if (!isalnum(suser[i])) suser[i]='_';
2217         }
2218
2219         if (mode == MT_RFC822) {
2220                 if (!strcasecmp(snode, NODENAME)) {
2221                         safestrncpy(snode, FQDN, sizeof snode);
2222                 }
2223
2224                 /* Construct a fun message id */
2225                 cprintf("Message-ID: <%s", mid);/// todo: this possibly breaks threadding mails.
2226                 if (strchr(mid, '@')==NULL) {
2227                         cprintf("@%s", snode);
2228                 }
2229                 cprintf(">%s", nl);
2230
2231                 if (!is_room_aide() && (TheMessage->cm_anon_type == MES_ANONONLY)) {
2232                         cprintf("From: \"----\" <x@x.org>%s", nl);
2233                 }
2234                 else if (!is_room_aide() && (TheMessage->cm_anon_type == MES_ANONOPT)) {
2235                         cprintf("From: \"anonymous\" <x@x.org>%s", nl);
2236                 }
2237                 else if (!IsEmptyStr(fuser)) {
2238                         cprintf("From: \"%s\" <%s>%s", luser, fuser, nl);
2239                 }
2240                 else {
2241                         cprintf("From: \"%s\" <%s@%s>%s", luser, suser, snode, nl);
2242                 }
2243
2244                 /* Blank line signifying RFC822 end-of-headers */
2245                 if (TheMessage->cm_format_type != FMT_RFC822) {
2246                         cprintf("%s", nl);
2247                 }
2248         }
2249
2250         /* end header processing loop ... at this point, we're in the text */
2251 START_TEXT:
2252         if (headers_only == HEADERS_FAST) goto DONE;
2253
2254         /* Tell the client about the MIME parts in this message */
2255         if (TheMessage->cm_format_type == FMT_RFC822) {
2256                 if ( (mode == MT_CITADEL) || (mode == MT_MIME) ) {
2257                         memset(&ma, 0, sizeof(struct ma_info));
2258                         mime_parser(CM_RANGE(TheMessage, eMesageText),
2259                                 (do_proto ? *list_this_part : NULL),
2260                                 (do_proto ? *list_this_pref : NULL),
2261                                 (do_proto ? *list_this_suff : NULL),
2262                                 (void *)&ma, 1);
2263                 }
2264                 else if (mode == MT_RFC822) {   /* unparsed RFC822 dump */
2265                         Dump_RFC822HeadersBody(
2266                                 TheMessage,
2267                                 headers_only,
2268                                 flags,
2269                                 nl, nlen);
2270                         goto DONE;
2271                 }
2272         }
2273
2274         if (headers_only == HEADERS_ONLY) {
2275                 goto DONE;
2276         }
2277
2278         /* signify start of msg text */
2279         if ( (mode == MT_CITADEL) || (mode == MT_MIME) ) {
2280                 if (do_proto) cprintf("text\n");
2281         }
2282
2283         if (TheMessage->cm_format_type == FMT_FIXED) 
2284                 DumpFormatFixed(
2285                         TheMessage,
2286                         mode,           /* how would you like that message? */
2287                         nl, nlen);
2288
2289         /* If the message on disk is format 0 (Citadel vari-format), we
2290          * output using the formatter at 80 columns.  This is the final output
2291          * form if the transfer format is RFC822, but if the transfer format
2292          * is Citadel proprietary, it'll still work, because the indentation
2293          * for new paragraphs is correct and the client will reformat the
2294          * message to the reader's screen width.
2295          */
2296         if (TheMessage->cm_format_type == FMT_CITADEL) {
2297                 if (mode == MT_MIME) {
2298                         cprintf("Content-type: text/x-citadel-variformat\n\n");
2299                 }
2300                 memfmout(TheMessage->cm_fields[eMesageText], nl);
2301         }
2302
2303         /* If the message on disk is format 4 (MIME), we've gotta hand it
2304          * off to the MIME parser.  The client has already been told that
2305          * this message is format 1 (fixed format), so the callback function
2306          * we use will display those parts as-is.
2307          */
2308         if (TheMessage->cm_format_type == FMT_RFC822) {
2309                 memset(&ma, 0, sizeof(struct ma_info));
2310
2311                 if (mode == MT_MIME) {
2312                         ma.use_fo_hooks = 0;
2313                         strcpy(ma.chosen_part, "1");
2314                         ma.chosen_pref = 9999;
2315                         ma.dont_decode = CC->msg4_dont_decode;
2316                         mime_parser(CM_RANGE(TheMessage, eMesageText),
2317                                     *choose_preferred, *fixed_output_pre,
2318                                     *fixed_output_post, (void *)&ma, 1);
2319                         mime_parser(CM_RANGE(TheMessage, eMesageText),
2320                                     *output_preferred, NULL, NULL, (void *)&ma, 1);
2321                 }
2322                 else {
2323                         ma.use_fo_hooks = 1;
2324                         mime_parser(CM_RANGE(TheMessage, eMesageText),
2325                                     *fixed_output, *fixed_output_pre,
2326                                     *fixed_output_post, (void *)&ma, 0);
2327                 }
2328
2329         }
2330
2331 DONE:   /* now we're done */
2332         if (do_proto) cprintf("000\n");
2333         return(om_ok);
2334 }
2335
2336 /*
2337  * Save one or more message pointers into a specified room
2338  * (Returns 0 for success, nonzero for failure)
2339  * roomname may be NULL to use the current room
2340  *
2341  * Note that the 'supplied_msg' field may be set to NULL, in which case
2342  * the message will be fetched from disk, by number, if we need to perform
2343  * replication checks.  This adds an additional database read, so if the
2344  * caller already has the message in memory then it should be supplied.  (Obviously
2345  * this mode of operation only works if we're saving a single message.)
2346  */
2347 int CtdlSaveMsgPointersInRoom(char *roomname, long newmsgidlist[], int num_newmsgs,
2348                         int do_repl_check, struct CtdlMessage *supplied_msg, int suppress_refcount_adj
2349 ) {
2350         int i, j, unique;
2351         char hold_rm[ROOMNAMELEN];
2352         struct cdbdata *cdbfr;
2353         int num_msgs;
2354         long *msglist;
2355         long highest_msg = 0L;
2356
2357         long msgid = 0;
2358         struct CtdlMessage *msg = NULL;
2359
2360         long *msgs_to_be_merged = NULL;
2361         int num_msgs_to_be_merged = 0;
2362
2363         syslog(LOG_DEBUG,
2364                 "msgbase: CtdlSaveMsgPointersInRoom(room=%s, num_msgs=%d, repl=%d, suppress_rca=%d)",
2365                 roomname, num_newmsgs, do_repl_check, suppress_refcount_adj
2366         );
2367
2368         strcpy(hold_rm, CC->room.QRname);
2369
2370         /* Sanity checks */
2371         if (newmsgidlist == NULL) return(ERROR + INTERNAL_ERROR);
2372         if (num_newmsgs < 1) return(ERROR + INTERNAL_ERROR);
2373         if (num_newmsgs > 1) supplied_msg = NULL;
2374
2375         /* Now the regular stuff */
2376         if (CtdlGetRoomLock(&CC->room,
2377            ((roomname != NULL) ? roomname : CC->room.QRname) )
2378            != 0) {
2379                 syslog(LOG_ERR, "msgbase: no such room <%s>", roomname);
2380                 return(ERROR + ROOM_NOT_FOUND);
2381         }
2382
2383
2384         msgs_to_be_merged = malloc(sizeof(long) * num_newmsgs);
2385         num_msgs_to_be_merged = 0;
2386
2387
2388         cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
2389         if (cdbfr == NULL) {
2390                 msglist = NULL;
2391                 num_msgs = 0;
2392         } else {
2393                 msglist = (long *) cdbfr->ptr;
2394                 cdbfr->ptr = NULL;      /* CtdlSaveMsgPointerInRoom() now owns this memory */
2395                 num_msgs = cdbfr->len / sizeof(long);
2396                 cdb_free(cdbfr);
2397         }
2398
2399
2400         /* Create a list of msgid's which were supplied by the caller, but do
2401          * not already exist in the target room.  It is absolutely taboo to
2402          * have more than one reference to the same message in a room.
2403          */
2404         for (i=0; i<num_newmsgs; ++i) {
2405                 unique = 1;
2406                 if (num_msgs > 0) for (j=0; j<num_msgs; ++j) {
2407                         if (msglist[j] == newmsgidlist[i]) {
2408                                 unique = 0;
2409                         }
2410                 }
2411                 if (unique) {
2412                         msgs_to_be_merged[num_msgs_to_be_merged++] = newmsgidlist[i];
2413                 }
2414         }
2415
2416         syslog(LOG_DEBUG, "msgbase: %d unique messages to be merged", num_msgs_to_be_merged);
2417
2418         /*
2419          * Now merge the new messages
2420          */
2421         msglist = realloc(msglist, (sizeof(long) * (num_msgs + num_msgs_to_be_merged)) );
2422         if (msglist == NULL) {
2423                 syslog(LOG_ALERT, "msgbase: ERROR; can't realloc message list!");
2424                 free(msgs_to_be_merged);
2425                 return (ERROR + INTERNAL_ERROR);
2426         }
2427         memcpy(&msglist[num_msgs], msgs_to_be_merged, (sizeof(long) * num_msgs_to_be_merged) );
2428         num_msgs += num_msgs_to_be_merged;
2429
2430         /* Sort the message list, so all the msgid's are in order */
2431         num_msgs = sort_msglist(msglist, num_msgs);
2432
2433         /* Determine the highest message number */
2434         highest_msg = msglist[num_msgs - 1];
2435
2436         /* Write it back to disk. */
2437         cdb_store(CDB_MSGLISTS, &CC->room.QRnumber, (int)sizeof(long),
2438                   msglist, (int)(num_msgs * sizeof(long)));
2439
2440         /* Free up the memory we used. */
2441         free(msglist);
2442
2443         /* Update the highest-message pointer and unlock the room. */
2444         CC->room.QRhighest = highest_msg;
2445         CtdlPutRoomLock(&CC->room);
2446
2447         /* Perform replication checks if necessary */
2448         if ( (DoesThisRoomNeedEuidIndexing(&CC->room)) && (do_repl_check) ) {
2449                 syslog(LOG_DEBUG, "msgbase: CtdlSaveMsgPointerInRoom() doing repl checks");
2450
2451                 for (i=0; i<num_msgs_to_be_merged; ++i) {
2452                         msgid = msgs_to_be_merged[i];
2453         
2454                         if (supplied_msg != NULL) {
2455                                 msg = supplied_msg;
2456                         }
2457                         else {
2458                                 msg = CtdlFetchMessage(msgid, 0, 1);
2459                         }
2460         
2461                         if (msg != NULL) {
2462                                 ReplicationChecks(msg);
2463                 
2464                                 /* If the message has an Exclusive ID, index that... */
2465                                 if (!CM_IsEmpty(msg, eExclusiveID)) {
2466                                         index_message_by_euid(msg->cm_fields[eExclusiveID], &CC->room, msgid);
2467                                 }
2468
2469                                 /* Free up the memory we may have allocated */
2470                                 if (msg != supplied_msg) {
2471                                         CM_Free(msg);
2472                                 }
2473                         }
2474         
2475                 }
2476         }
2477
2478         else {
2479                 syslog(LOG_DEBUG, "msgbase: CtdlSaveMsgPointerInRoom() skips repl checks");
2480         }
2481
2482         /* Submit this room for processing by hooks */
2483         PerformRoomHooks(&CC->room);
2484
2485         /* Go back to the room we were in before we wandered here... */
2486         CtdlGetRoom(&CC->room, hold_rm);
2487
2488         /* Bump the reference count for all messages which were merged */
2489         if (!suppress_refcount_adj) {
2490                 AdjRefCountList(msgs_to_be_merged, num_msgs_to_be_merged, +1);
2491         }
2492
2493         /* Free up memory... */
2494         if (msgs_to_be_merged != NULL) {
2495                 free(msgs_to_be_merged);
2496         }
2497
2498         /* Return success. */
2499         return (0);
2500 }
2501
2502
2503 /*
2504  * This is the same as CtdlSaveMsgPointersInRoom() but it only accepts
2505  * a single message.
2506  */
2507 int CtdlSaveMsgPointerInRoom(char *roomname, long msgid,
2508                              int do_repl_check, struct CtdlMessage *supplied_msg)
2509 {
2510         return CtdlSaveMsgPointersInRoom(roomname, &msgid, 1, do_repl_check, supplied_msg, 0);
2511 }
2512
2513
2514
2515
2516 /*
2517  * Message base operation to save a new message to the message store
2518  * (returns new message number)
2519  *
2520  * This is the back end for CtdlSubmitMsg() and should not be directly
2521  * called by server-side modules.
2522  *
2523  */
2524 long CtdlSaveThisMessage(struct CtdlMessage *msg, long msgid, int Reply) {
2525         long retval;
2526         struct ser_ret smr;
2527         int is_bigmsg = 0;
2528         char *holdM = NULL;
2529         long holdMLen = 0;
2530
2531         /*
2532          * If the message is big, set its body aside for storage elsewhere
2533          * and we hide the message body from the serializer
2534          */
2535         if (!CM_IsEmpty(msg, eMesageText) && msg->cm_lengths[eMesageText] > BIGMSG)
2536         {
2537                 is_bigmsg = 1;
2538                 holdM = msg->cm_fields[eMesageText];
2539                 msg->cm_fields[eMesageText] = NULL;
2540                 holdMLen = msg->cm_lengths[eMesageText];
2541                 msg->cm_lengths[eMesageText] = 0;
2542         }
2543
2544         /* Serialize our data structure for storage in the database */  
2545         CtdlSerializeMessage(&smr, msg);
2546
2547         if (is_bigmsg) {
2548                 /* put the message body back into the message */
2549                 msg->cm_fields[eMesageText] = holdM;
2550                 msg->cm_lengths[eMesageText] = holdMLen;
2551         }
2552
2553         if (smr.len == 0) {
2554                 if (Reply) {
2555                         cprintf("%d Unable to serialize message\n",
2556                                 ERROR + INTERNAL_ERROR);
2557                 }
2558                 else {
2559                         syslog(LOG_ERR, "msgbase: CtdlSaveMessage() unable to serialize message");
2560
2561                 }
2562                 return (-1L);
2563         }
2564
2565         /* Write our little bundle of joy into the message base */
2566         retval = cdb_store(CDB_MSGMAIN, &msgid, (int)sizeof(long),
2567                            smr.ser, smr.len);
2568         if (retval < 0) {
2569                 syslog(LOG_ERR, "msgbase: can't store message %ld: %ld", msgid, retval);
2570         }
2571         else {
2572                 if (is_bigmsg) {
2573                         retval = cdb_store(CDB_BIGMSGS,
2574                                            &msgid,
2575                                            (int)sizeof(long),
2576                                            holdM,
2577                                            (holdMLen + 1)
2578                                 );
2579                         if (retval < 0) {
2580                                 syslog(LOG_ERR, "msgbase: failed to store message body for msgid %ld: %ld", msgid, retval);
2581                         }
2582                 }
2583         }
2584
2585         /* Free the memory we used for the serialized message */
2586         free(smr.ser);
2587
2588         return(retval);
2589 }
2590
2591 long send_message(struct CtdlMessage *msg) {
2592         long newmsgid;
2593         long retval;
2594         char msgidbuf[256];
2595         long msgidbuflen;
2596
2597         /* Get a new message number */
2598         newmsgid = get_new_message_number();
2599
2600         /* Generate an ID if we don't have one already */
2601         if (CM_IsEmpty(msg, emessageId)) {
2602                 msgidbuflen = snprintf(msgidbuf, sizeof msgidbuf, "%08lX-%08lX@%s",
2603                                        (long unsigned int) time(NULL),
2604                                        (long unsigned int) newmsgid,
2605                                        CtdlGetConfigStr("c_fqdn")
2606                         );
2607
2608                 CM_SetField(msg, emessageId, msgidbuf, msgidbuflen);
2609         }
2610
2611         retval = CtdlSaveThisMessage(msg, newmsgid, 1);
2612
2613         if (retval == 0) {
2614                 retval = newmsgid;
2615         }
2616
2617         /* Return the *local* message ID to the caller
2618          * (even if we're storing an incoming network message)
2619          */
2620         return(retval);
2621 }
2622
2623
2624
2625 /*
2626  * Serialize a struct CtdlMessage into the format used on disk and network.
2627  * 
2628  * This function loads up a "struct ser_ret" (defined in server.h) which
2629  * contains the length of the serialized message and a pointer to the
2630  * serialized message in memory.  THE LATTER MUST BE FREED BY THE CALLER.
2631  */
2632 void CtdlSerializeMessage(struct ser_ret *ret,          /* return values */
2633                           struct CtdlMessage *msg)      /* unserialized msg */
2634 {
2635         size_t wlen;
2636         int i;
2637
2638         /*
2639          * Check for valid message format
2640          */
2641         if (CM_IsValidMsg(msg) == 0) {
2642                 syslog(LOG_ERR, "msgbase: CtdlSerializeMessage() aborting due to invalid message");
2643                 ret->len = 0;
2644                 ret->ser = NULL;
2645                 return;
2646         }
2647
2648         ret->len = 3;
2649         for (i=0; i < NDiskFields; ++i)
2650                 if (msg->cm_fields[FieldOrder[i]] != NULL)
2651                         ret->len += msg->cm_lengths[FieldOrder[i]] + 2;
2652
2653         ret->ser = malloc(ret->len);
2654         if (ret->ser == NULL) {
2655                 syslog(LOG_ERR, "msgbase: CtdlSerializeMessage() malloc(%ld) failed: %m", (long)ret->len);
2656                 ret->len = 0;
2657                 ret->ser = NULL;
2658                 return;
2659         }
2660
2661         ret->ser[0] = 0xFF;
2662         ret->ser[1] = msg->cm_anon_type;
2663         ret->ser[2] = msg->cm_format_type;
2664         wlen = 3;
2665
2666         for (i=0; i < NDiskFields; ++i)
2667                 if (msg->cm_fields[FieldOrder[i]] != NULL)
2668                 {
2669                         ret->ser[wlen++] = (char)FieldOrder[i];
2670
2671                         memcpy(&ret->ser[wlen],
2672                                msg->cm_fields[FieldOrder[i]],
2673                                msg->cm_lengths[FieldOrder[i]] + 1);
2674
2675                         wlen = wlen + msg->cm_lengths[FieldOrder[i]] + 1;
2676                 }
2677
2678         if (ret->len != wlen) {
2679                 syslog(LOG_ERR, "msgbase: ERROR; len=%ld wlen=%ld", (long)ret->len, (long)wlen);
2680         }
2681
2682         return;
2683 }
2684
2685
2686 /*
2687  * Check to see if any messages already exist in the current room which
2688  * carry the same Exclusive ID as this one.  If any are found, delete them.
2689  */
2690 void ReplicationChecks(struct CtdlMessage *msg) {
2691         long old_msgnum = (-1L);
2692
2693         if (DoesThisRoomNeedEuidIndexing(&CC->room) == 0) return;
2694
2695         syslog(LOG_DEBUG, "msgbase: performing replication checks in <%s>", CC->room.QRname);
2696
2697         /* No exclusive id?  Don't do anything. */
2698         if (msg == NULL) return;
2699         if (CM_IsEmpty(msg, eExclusiveID)) return;
2700
2701         /*syslog(LOG_DEBUG, "msgbase: exclusive ID: <%s> for room <%s>",
2702           msg->cm_fields[eExclusiveID], CC->room.QRname);*/
2703
2704         old_msgnum = CtdlLocateMessageByEuid(msg->cm_fields[eExclusiveID], &CC->room);
2705         if (old_msgnum > 0L) {
2706                 syslog(LOG_DEBUG, "msgbase: ReplicationChecks() replacing message %ld", old_msgnum);
2707                 CtdlDeleteMessages(CC->room.QRname, &old_msgnum, 1, "");
2708         }
2709 }
2710
2711
2712
2713 /*
2714  * Save a message to disk and submit it into the delivery system.
2715  */
2716 long CtdlSubmitMsg(struct CtdlMessage *msg,     /* message to save */
2717                    recptypes *recps,            /* recipients (if mail) */
2718                    const char *force,           /* force a particular room? */
2719                    int flags                    /* should the message be exported clean? */
2720         )
2721 {
2722         char hold_rm[ROOMNAMELEN];
2723         char actual_rm[ROOMNAMELEN];
2724         char force_room[ROOMNAMELEN];
2725         char content_type[SIZ];                 /* We have to learn this */
2726         char recipient[SIZ];
2727         char bounce_to[1024];
2728         const char *room;
2729         long newmsgid;
2730         const char *mptr = NULL;
2731         struct ctdluser userbuf;
2732         int a, i;
2733         struct MetaData smi;
2734         char *collected_addresses = NULL;
2735         struct addresses_to_be_filed *aptr = NULL;
2736         StrBuf *saved_rfc822_version = NULL;
2737         int qualified_for_journaling = 0;
2738
2739         syslog(LOG_DEBUG, "msgbase: CtdlSubmitMsg() called");
2740         if (CM_IsValidMsg(msg) == 0) return(-1);        /* self check */
2741
2742         /* If this message has no timestamp, we take the liberty of
2743          * giving it one, right now.
2744          */
2745         if (CM_IsEmpty(msg, eTimestamp)) {
2746                 CM_SetFieldLONG(msg, eTimestamp, time(NULL));
2747         }
2748
2749         /* If this message has no path, we generate one.
2750          */
2751         if (CM_IsEmpty(msg, eMessagePath)) {
2752                 if (!CM_IsEmpty(msg, eAuthor)) {
2753                         CM_CopyField(msg, eMessagePath, eAuthor);
2754                         for (a=0; !IsEmptyStr(&msg->cm_fields[eMessagePath][a]); ++a) {
2755                                 if (isspace(msg->cm_fields[eMessagePath][a])) {
2756                                         msg->cm_fields[eMessagePath][a] = ' ';
2757                                 }
2758                         }
2759                 }
2760                 else {
2761                         CM_SetField(msg, eMessagePath, HKEY("unknown"));
2762                 }
2763         }
2764
2765         if (force == NULL) {
2766                 force_room[0] = '\0';
2767         }
2768         else {
2769                 strcpy(force_room, force);
2770         }
2771
2772         /* Learn about what's inside, because it's what's inside that counts */
2773         if (CM_IsEmpty(msg, eMesageText)) {
2774                 syslog(LOG_ERR, "msgbase: ERROR; attempt to save message with NULL body");
2775                 return(-2);
2776         }
2777
2778         switch (msg->cm_format_type) {
2779         case 0:
2780                 strcpy(content_type, "text/x-citadel-variformat");
2781                 break;
2782         case 1:
2783                 strcpy(content_type, "text/plain");
2784                 break;
2785         case 4:
2786                 strcpy(content_type, "text/plain");
2787                 mptr = bmstrcasestr(msg->cm_fields[eMesageText], "Content-type:");
2788                 if (mptr != NULL) {
2789                         char *aptr;
2790                         safestrncpy(content_type, &mptr[13], sizeof content_type);
2791                         striplt(content_type);
2792                         aptr = content_type;
2793                         while (!IsEmptyStr(aptr)) {
2794                                 if ((*aptr == ';')
2795                                     || (*aptr == ' ')
2796                                     || (*aptr == 13)
2797                                     || (*aptr == 10)) {
2798                                         *aptr = 0;
2799                                 }
2800                                 else aptr++;
2801                         }
2802                 }
2803         }
2804
2805         /* Goto the correct room */
2806         room = (recps) ? CC->room.QRname : SENTITEMS;
2807         syslog(LOG_DEBUG, "msgbase: selected room %s", room);
2808         strcpy(hold_rm, CC->room.QRname);
2809         strcpy(actual_rm, CC->room.QRname);
2810         if (recps != NULL) {
2811                 strcpy(actual_rm, SENTITEMS);
2812         }
2813
2814         /* If the user is a twit, move to the twit room for posting */
2815         if (TWITDETECT) {
2816                 if (CC->user.axlevel == AxProbU) {
2817                         strcpy(hold_rm, actual_rm);
2818                         strcpy(actual_rm, CtdlGetConfigStr("c_twitroom"));
2819                         syslog(LOG_DEBUG, "msgbase: diverting to twit room");
2820                 }
2821         }
2822
2823         /* ...or if this message is destined for Aide> then go there. */
2824         if (!IsEmptyStr(force_room)) {
2825                 strcpy(actual_rm, force_room);
2826         }
2827
2828         syslog(LOG_DEBUG, "msgbase: final selection: %s (%s)", actual_rm, room);
2829         if (strcasecmp(actual_rm, CC->room.QRname)) {
2830                 /* CtdlGetRoom(&CC->room, actual_rm); */
2831                 CtdlUserGoto(actual_rm, 0, 1, NULL, NULL, NULL, NULL);
2832         }
2833
2834         /*
2835          * If this message has no O (room) field, generate one.
2836          */
2837         if (CM_IsEmpty(msg, eOriginalRoom) && !IsEmptyStr(CC->room.QRname)) {
2838                 CM_SetField(msg, eOriginalRoom, CC->room.QRname, strlen(CC->room.QRname));
2839         }
2840
2841         /* Perform "before save" hooks (aborting if any return nonzero) */
2842         syslog(LOG_DEBUG, "msgbase: performing before-save hooks");
2843         if (PerformMessageHooks(msg, recps, EVT_BEFORESAVE) > 0) return(-3);
2844
2845         /*
2846          * If this message has an Exclusive ID, and the room is replication
2847          * checking enabled, then do replication checks.
2848          */
2849         if (DoesThisRoomNeedEuidIndexing(&CC->room)) {
2850                 ReplicationChecks(msg);
2851         }
2852
2853         /* Save it to disk */
2854         syslog(LOG_DEBUG, "msgbase: saving to disk");
2855         newmsgid = send_message(msg);
2856         if (newmsgid <= 0L) return(-5);
2857
2858         /* Write a supplemental message info record.  This doesn't have to
2859          * be a critical section because nobody else knows about this message
2860          * yet.
2861          */
2862         syslog(LOG_DEBUG, "msgbase: creating metadata record");
2863         memset(&smi, 0, sizeof(struct MetaData));
2864         smi.meta_msgnum = newmsgid;
2865         smi.meta_refcount = 0;
2866         safestrncpy(smi.meta_content_type, content_type,
2867                     sizeof smi.meta_content_type);
2868
2869         /*
2870          * Measure how big this message will be when rendered as RFC822.
2871          * We do this for two reasons:
2872          * 1. We need the RFC822 length for the new metadata record, so the
2873          *    POP and IMAP services don't have to calculate message lengths
2874          *    while the user is waiting (multiplied by potentially hundreds
2875          *    or thousands of messages).
2876          * 2. If journaling is enabled, we will need an RFC822 version of the
2877          *    message to attach to the journalized copy.
2878          */
2879         if (CC->redirect_buffer != NULL) {
2880                 syslog(LOG_ALERT, "msgbase: CC->redirect_buffer is not NULL during message submission!");
2881                 abort();
2882         }
2883         CC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
2884         CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_ALL, 0, 1, QP_EADDR);
2885         smi.meta_rfc822_length = StrLength(CC->redirect_buffer);
2886         saved_rfc822_version = CC->redirect_buffer;
2887         CC->redirect_buffer = NULL;
2888
2889         PutMetaData(&smi);
2890
2891         /* Now figure out where to store the pointers */
2892         syslog(LOG_DEBUG, "msgbase: storing pointers");
2893
2894         /* If this is being done by the networker delivering a private
2895          * message, we want to BYPASS saving the sender's copy (because there
2896          * is no local sender; it would otherwise go to the Trashcan).
2897          */
2898         if ((!CC->internal_pgm) || (recps == NULL)) {
2899                 if (CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 1, msg) != 0) {
2900                         syslog(LOG_ERR, "msgbase: ERROR saving message pointer!");
2901                         CtdlSaveMsgPointerInRoom(CtdlGetConfigStr("c_aideroom"), newmsgid, 0, msg);
2902                 }
2903         }
2904
2905         /* For internet mail, drop a copy in the outbound queue room */
2906         if ((recps != NULL) && (recps->num_internet > 0)) {
2907                 CtdlSaveMsgPointerInRoom(SMTP_SPOOLOUT_ROOM, newmsgid, 0, msg);
2908         }
2909
2910         /* If other rooms are specified, drop them there too. */
2911         if ((recps != NULL) && (recps->num_room > 0))
2912                 for (i=0; i<num_tokens(recps->recp_room, '|'); ++i) {
2913                         extract_token(recipient, recps->recp_room, i,
2914                                       '|', sizeof recipient);
2915                         syslog(LOG_DEBUG, "msgbase: delivering to room <%s>", recipient);
2916                         CtdlSaveMsgPointerInRoom(recipient, newmsgid, 0, msg);
2917                 }
2918
2919         /* Bump this user's messages posted counter. */
2920         syslog(LOG_DEBUG, "msgbase: updating user");
2921         CtdlLockGetCurrentUser();
2922         CC->user.posted = CC->user.posted + 1;
2923         CtdlPutCurrentUserLock();
2924
2925         /* Decide where bounces need to be delivered */
2926         if ((recps != NULL) && (recps->bounce_to == NULL))
2927         {
2928                 if (CC->logged_in) {
2929                         snprintf(bounce_to, sizeof bounce_to, "%s@%s", CC->user.fullname, CtdlGetConfigStr("c_nodename"));
2930                 }
2931                 else {
2932                         snprintf(bounce_to, sizeof bounce_to, "%s@%s", msg->cm_fields[eAuthor], msg->cm_fields[eNodeName]);
2933                 }
2934                 recps->bounce_to = bounce_to;
2935         }
2936                 
2937         CM_SetFieldLONG(msg, eVltMsgNum, newmsgid);
2938
2939
2940         /* If this is private, local mail, make a copy in the
2941          * recipient's mailbox and bump the reference count.
2942          */
2943         if ((recps != NULL) && (recps->num_local > 0))
2944         {
2945                 char *pch;
2946                 int ntokens;
2947
2948                 pch = recps->recp_local;
2949                 recps->recp_local = recipient;
2950                 ntokens = num_tokens(pch, '|');
2951                 for (i=0; i<ntokens; ++i)
2952                 {
2953                         extract_token(recipient, pch, i, '|', sizeof recipient);
2954                         syslog(LOG_DEBUG, "msgbase: delivering private local mail to <%s>", recipient);
2955                         if (CtdlGetUser(&userbuf, recipient) == 0) {
2956                                 CtdlMailboxName(actual_rm, sizeof actual_rm, &userbuf, MAILROOM);
2957                                 CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 0, msg);
2958                                 CtdlBumpNewMailCounter(userbuf.usernum);
2959                                 PerformMessageHooks(msg, recps, EVT_AFTERUSRMBOXSAVE);
2960                         }
2961                         else {
2962                                 syslog(LOG_DEBUG, "msgbase: no user <%s>", recipient);
2963                                 CtdlSaveMsgPointerInRoom(CtdlGetConfigStr("c_aideroom"), newmsgid, 0, msg);
2964                         }
2965                 }
2966                 recps->recp_local = pch;
2967         }
2968
2969         /* Perform "after save" hooks */
2970         syslog(LOG_DEBUG, "msgbase: performing after-save hooks");
2971
2972         PerformMessageHooks(msg, recps, EVT_AFTERSAVE);
2973         CM_FlushField(msg, eVltMsgNum);
2974
2975         /* Go back to the room we started from */
2976         syslog(LOG_DEBUG, "msgbase: returning to original room %s", hold_rm);
2977         if (strcasecmp(hold_rm, CC->room.QRname))
2978                 CtdlUserGoto(hold_rm, 0, 1, NULL, NULL, NULL, NULL);
2979
2980         /*
2981          * Any addresses to harvest for someone's address book?
2982          */
2983         if ( (CC->logged_in) && (recps != NULL) ) {
2984                 collected_addresses = harvest_collected_addresses(msg);
2985         }
2986
2987         if (collected_addresses != NULL) {
2988                 aptr = (struct addresses_to_be_filed *)
2989                         malloc(sizeof(struct addresses_to_be_filed));
2990                 CtdlMailboxName(actual_rm, sizeof actual_rm,
2991                                 &CC->user, USERCONTACTSROOM);
2992                 aptr->roomname = strdup(actual_rm);
2993                 aptr->collected_addresses = collected_addresses;
2994                 begin_critical_section(S_ATBF);
2995                 aptr->next = atbf;
2996                 atbf = aptr;
2997                 end_critical_section(S_ATBF);
2998         }
2999
3000         /*
3001          * Determine whether this message qualifies for journaling.
3002          */
3003         if (!CM_IsEmpty(msg, eJournal)) {
3004                 qualified_for_journaling = 0;
3005         }
3006         else {
3007                 if (recps == NULL) {
3008                         qualified_for_journaling = CtdlGetConfigInt("c_journal_pubmsgs");
3009                 }
3010                 else if (recps->num_local + recps->num_ignet + recps->num_internet > 0) {
3011                         qualified_for_journaling = CtdlGetConfigInt("c_journal_email");
3012                 }
3013                 else {
3014                         qualified_for_journaling = CtdlGetConfigInt("c_journal_pubmsgs");
3015                 }
3016         }
3017
3018         /*
3019          * Do we have to perform journaling?  If so, hand off the saved
3020          * RFC822 version will be handed off to the journaler for background
3021          * submit.  Otherwise, we have to free the memory ourselves.
3022          */
3023         if (saved_rfc822_version != NULL) {
3024                 if (qualified_for_journaling) {
3025                         JournalBackgroundSubmit(msg, saved_rfc822_version, recps);
3026                 }
3027                 else {
3028                         FreeStrBuf(&saved_rfc822_version);
3029                 }
3030         }
3031
3032         if ((recps != NULL) && (recps->bounce_to == bounce_to))
3033                 recps->bounce_to = NULL;
3034
3035         /* Done. */
3036         return(newmsgid);
3037 }
3038
3039
3040 /*
3041  * Convenience function for generating small administrative messages.
3042  */
3043 long quickie_message(const char *from,
3044                      const char *fromaddr,
3045                      const char *to,
3046                      char *room,
3047                      const char *text, 
3048                      int format_type,
3049                      const char *subject)
3050 {
3051         struct CtdlMessage *msg;
3052         recptypes *recp = NULL;
3053
3054         msg = malloc(sizeof(struct CtdlMessage));
3055         memset(msg, 0, sizeof(struct CtdlMessage));
3056         msg->cm_magic = CTDLMESSAGE_MAGIC;
3057         msg->cm_anon_type = MES_NORMAL;
3058         msg->cm_format_type = format_type;
3059
3060         if (!IsEmptyStr(from)) {
3061                 CM_SetField(msg, eAuthor, from, strlen(from));
3062         }
3063         else if (!IsEmptyStr(fromaddr)) {
3064                 char *pAt;
3065                 CM_SetField(msg, eAuthor, fromaddr, strlen(fromaddr));
3066                 pAt = strchr(msg->cm_fields[eAuthor], '@');
3067                 if (pAt != NULL) {
3068                         CM_CutFieldAt(msg, eAuthor, pAt - msg->cm_fields[eAuthor]);
3069                 }
3070         }
3071         else {
3072                 msg->cm_fields[eAuthor] = strdup("Citadel");
3073         }
3074
3075         if (!IsEmptyStr(fromaddr)) CM_SetField(msg, erFc822Addr, fromaddr, strlen(fromaddr));
3076         if (!IsEmptyStr(room)) CM_SetField(msg, eOriginalRoom, room, strlen(room));
3077         CM_SetField(msg, eNodeName, CtdlGetConfigStr("c_nodename"), strlen(CtdlGetConfigStr("c_nodename")));
3078         if (!IsEmptyStr(to)) {
3079                 CM_SetField(msg, eRecipient, to, strlen(to));
3080                 recp = validate_recipients(to, NULL, 0);
3081         }
3082         if (!IsEmptyStr(subject)) {
3083                 CM_SetField(msg, eMsgSubject, subject, strlen(subject));
3084         }
3085         if (!IsEmptyStr(text)) {
3086                 CM_SetField(msg, eMesageText, text, strlen(text));
3087         }
3088
3089         long msgnum = CtdlSubmitMsg(msg, recp, room, 0);
3090         CM_Free(msg);
3091         if (recp != NULL) free_recipients(recp);
3092         return msgnum;
3093 }
3094
3095
3096 /*
3097  * Back end function used by CtdlMakeMessage() and similar functions
3098  */
3099 StrBuf *CtdlReadMessageBodyBuf(char *terminator,        /* token signalling EOT */
3100                                long tlen,
3101                                size_t maxlen,           /* maximum message length */
3102                                StrBuf *exist,           /* if non-null, append to it;
3103                                                            exist is ALWAYS freed  */
3104                                int crlf                 /* CRLF newlines instead of LF */
3105         ) 
3106 {
3107         StrBuf *Message;
3108         StrBuf *LineBuf;
3109         int flushing = 0;
3110         int finished = 0;
3111         int dotdot = 0;
3112
3113         LineBuf = NewStrBufPlain(NULL, SIZ);
3114         if (exist == NULL) {
3115                 Message = NewStrBufPlain(NULL, 4 * SIZ);
3116         }
3117         else {
3118                 Message = NewStrBufDup(exist);
3119         }
3120
3121         /* Do we need to change leading ".." to "." for SMTP escaping? */
3122         if ((tlen == 1) && (*terminator == '.')) {
3123                 dotdot = 1;
3124         }
3125
3126         /* read in the lines of message text one by one */
3127         do {
3128                 if (CtdlClientGetLine(LineBuf) < 0) {
3129                         finished = 1;
3130                 }
3131                 if ((StrLength(LineBuf) == tlen) && (!strcmp(ChrPtr(LineBuf), terminator))) {
3132                         finished = 1;
3133                 }
3134                 if ( (!flushing) && (!finished) ) {
3135                         if (crlf) {
3136                                 StrBufAppendBufPlain(LineBuf, HKEY("\r\n"), 0);
3137                         }
3138                         else {
3139                                 StrBufAppendBufPlain(LineBuf, HKEY("\n"), 0);
3140                         }
3141                         
3142                         /* Unescape SMTP-style input of two dots at the beginning of the line */
3143                         if ((dotdot) &&
3144                             (StrLength(LineBuf) == 2) && 
3145                             (!strcmp(ChrPtr(LineBuf), "..")))
3146                         {
3147                                 StrBufCutLeft(LineBuf, 1);
3148                         }
3149                         
3150                         StrBufAppendBuf(Message, LineBuf, 0);
3151                 }
3152
3153                 /* if we've hit the max msg length, flush the rest */
3154                 if (StrLength(Message) >= maxlen) flushing = 1;
3155
3156         } while (!finished);
3157         FreeStrBuf(&LineBuf);
3158         return Message;
3159 }
3160
3161
3162 /*
3163  * Back end function used by CtdlMakeMessage() and similar functions
3164  */
3165 char *CtdlReadMessageBody(char *terminator,     /* token signalling EOT */
3166                           long tlen,
3167                           size_t maxlen,                /* maximum message length */
3168                           StrBuf *exist,                /* if non-null, append to it;
3169                                                    exist is ALWAYS freed  */
3170                           int crlf              /* CRLF newlines instead of LF */
3171         ) 
3172 {
3173         StrBuf *Message;
3174
3175         Message = CtdlReadMessageBodyBuf(terminator,
3176                                          tlen,
3177                                          maxlen,
3178                                          exist,
3179                                          crlf
3180         );
3181         if (Message == NULL)
3182                 return NULL;
3183         else
3184                 return SmashStrBuf(&Message);
3185 }
3186
3187 struct CtdlMessage *CtdlMakeMessage(
3188         struct ctdluser *author,        /* author's user structure */
3189         char *recipient,                /* NULL if it's not mail */
3190         char *recp_cc,                  /* NULL if it's not mail */
3191         char *room,                     /* room where it's going */
3192         int type,                       /* see MES_ types in header file */
3193         int format_type,                /* variformat, plain text, MIME... */
3194         char *fake_name,                /* who we're masquerading as */
3195         char *my_email,                 /* which of my email addresses to use (empty is ok) */
3196         char *subject,                  /* Subject (optional) */
3197         char *supplied_euid,            /* ...or NULL if this is irrelevant */
3198         char *preformatted_text,        /* ...or NULL to read text from client */
3199         char *references                /* Thread references */
3200 )
3201 {
3202         return CtdlMakeMessageLen(
3203                 author, /* author's user structure */
3204                 recipient,              /* NULL if it's not mail */
3205                 (recipient)?strlen(recipient) : 0,
3206                 recp_cc,                        /* NULL if it's not mail */
3207                 (recp_cc)?strlen(recp_cc): 0,
3208                 room,                   /* room where it's going */
3209                 (room)?strlen(room): 0,
3210                 type,                   /* see MES_ types in header file */
3211                 format_type,            /* variformat, plain text, MIME... */
3212                 fake_name,              /* who we're masquerading as */
3213                 (fake_name)?strlen(fake_name): 0,
3214                 my_email,                       /* which of my email addresses to use (empty is ok) */
3215                 (my_email)?strlen(my_email): 0,
3216                 subject,                        /* Subject (optional) */
3217                 (subject)?strlen(subject): 0,
3218                 supplied_euid,          /* ...or NULL if this is irrelevant */
3219                 (supplied_euid)?strlen(supplied_euid):0,
3220                 preformatted_text,      /* ...or NULL to read text from client */
3221                 (preformatted_text)?strlen(preformatted_text) : 0,
3222                 references,             /* Thread references */
3223                 (references)?strlen(references):0);
3224
3225 }
3226
3227 /*
3228  * Build a binary message to be saved on disk.
3229  * (NOTE: if you supply 'preformatted_text', the buffer you give it
3230  * will become part of the message.  This means you are no longer
3231  * responsible for managing that memory -- it will be freed along with
3232  * the rest of the fields when CM_Free() is called.)
3233  */
3234
3235 struct CtdlMessage *CtdlMakeMessageLen(
3236         struct ctdluser *author,        /* author's user structure */
3237         char *recipient,                /* NULL if it's not mail */
3238         long rcplen,
3239         char *recp_cc,                  /* NULL if it's not mail */
3240         long cclen,
3241         char *room,                     /* room where it's going */
3242         long roomlen,
3243         int type,                       /* see MES_ types in header file */
3244         int format_type,                /* variformat, plain text, MIME... */
3245         char *fake_name,                /* who we're masquerading as */
3246         long fnlen,
3247         char *my_email,                 /* which of my email addresses to use (empty is ok) */
3248         long myelen,
3249         char *subject,                  /* Subject (optional) */
3250         long subjlen,
3251         char *supplied_euid,            /* ...or NULL if this is irrelevant */
3252         long euidlen,
3253         char *preformatted_text,        /* ...or NULL to read text from client */
3254         long textlen,
3255         char *references,               /* Thread references */
3256         long reflen
3257         )
3258 {
3259         /* Don't confuse the poor folks if it's not routed mail. * /
3260            char dest_node[256] = "";*/
3261         long blen;
3262         char buf[1024];
3263         struct CtdlMessage *msg;
3264         StrBuf *FakeAuthor;
3265         StrBuf *FakeEncAuthor = NULL;
3266
3267         msg = malloc(sizeof(struct CtdlMessage));
3268         memset(msg, 0, sizeof(struct CtdlMessage));
3269         msg->cm_magic = CTDLMESSAGE_MAGIC;
3270         msg->cm_anon_type = type;
3271         msg->cm_format_type = format_type;
3272
3273         if (recipient != NULL) rcplen = striplt(recipient);
3274         if (recp_cc != NULL) cclen = striplt(recp_cc);
3275
3276         /* Path or Return-Path */
3277         if (myelen > 0) {
3278                 CM_SetField(msg, eMessagePath, my_email, myelen);
3279         }
3280         else if (!IsEmptyStr(author->fullname)) {
3281                 CM_SetField(msg, eMessagePath, author->fullname, strlen(author->fullname));
3282         }
3283         convert_spaces_to_underscores(msg->cm_fields[eMessagePath]);
3284
3285         blen = snprintf(buf, sizeof buf, "%ld", (long)time(NULL));
3286         CM_SetField(msg, eTimestamp, buf, blen);
3287
3288         if (fnlen > 0) {
3289                 FakeAuthor = NewStrBufPlain (fake_name, fnlen);
3290         }
3291         else {
3292                 FakeAuthor = NewStrBufPlain (author->fullname, -1);
3293         }
3294         StrBufRFC2047encode(&FakeEncAuthor, FakeAuthor);
3295         CM_SetAsFieldSB(msg, eAuthor, &FakeEncAuthor);
3296         FreeStrBuf(&FakeAuthor);
3297
3298         if (!!IsEmptyStr(CC->room.QRname)) {
3299                 if (CC->room.QRflags & QR_MAILBOX) {            /* room */
3300                         CM_SetField(msg, eOriginalRoom, &CC->room.QRname[11], strlen(&CC->room.QRname[11]));
3301                 }
3302                 else {
3303                         CM_SetField(msg, eOriginalRoom, CC->room.QRname, strlen(CC->room.QRname));
3304                 }
3305         }
3306
3307         CM_SetField(msg, eNodeName, CtdlGetConfigStr("c_nodename"), strlen(CtdlGetConfigStr("c_nodename")));
3308         CM_SetField(msg, eHumanNode, CtdlGetConfigStr("c_humannode"), strlen(CtdlGetConfigStr("c_humannode")));
3309
3310         if (rcplen > 0) {
3311                 CM_SetField(msg, eRecipient, recipient, rcplen);
3312         }
3313         if (cclen > 0) {
3314                 CM_SetField(msg, eCarbonCopY, recp_cc, cclen);
3315         }
3316
3317         if (myelen > 0) {
3318                 CM_SetField(msg, erFc822Addr, my_email, myelen);
3319         }
3320         else if ( (author == &CC->user) && (!IsEmptyStr(CC->cs_inet_email)) ) {
3321                 CM_SetField(msg, erFc822Addr, CC->cs_inet_email, strlen(CC->cs_inet_email));
3322         }
3323
3324         if (subject != NULL) {
3325                 long length;
3326                 length = striplt(subject);
3327                 if (length > 0) {
3328                         long i;
3329                         long IsAscii;
3330                         IsAscii = -1;
3331                         i = 0;
3332                         while ((subject[i] != '\0') &&
3333                                (IsAscii = isascii(subject[i]) != 0 ))
3334                                 i++;
3335                         if (IsAscii != 0)
3336                                 CM_SetField(msg, eMsgSubject, subject, subjlen);
3337                         else /* ok, we've got utf8 in the string. */
3338                         {
3339                                 char *rfc2047Subj;
3340                                 rfc2047Subj = rfc2047encode(subject, length);
3341                                 CM_SetAsField(msg, eMsgSubject, &rfc2047Subj, strlen(rfc2047Subj));
3342                         }
3343
3344                 }
3345         }
3346
3347         if (euidlen > 0) {
3348                 CM_SetField(msg, eExclusiveID, supplied_euid, euidlen);
3349         }
3350
3351         if (reflen > 0) {
3352                 CM_SetField(msg, eWeferences, references, reflen);
3353         }
3354
3355         if (preformatted_text != NULL) {
3356                 CM_SetField(msg, eMesageText, preformatted_text, textlen);
3357         }
3358         else {
3359                 StrBuf *MsgBody;
3360                 MsgBody = CtdlReadMessageBodyBuf(HKEY("000"), CtdlGetConfigLong("c_maxmsglen"), NULL, 0);
3361                 if (MsgBody != NULL) {
3362                         CM_SetAsFieldSB(msg, eMesageText, &MsgBody);
3363                 }
3364         }
3365
3366         return(msg);
3367 }
3368
3369
3370
3371
3372 /*
3373  * API function to delete messages which match a set of criteria
3374  * (returns the actual number of messages deleted)
3375  */
3376 int CtdlDeleteMessages(const char *room_name,           /* which room */
3377                        long *dmsgnums,          /* array of msg numbers to be deleted */
3378                        int num_dmsgnums,        /* number of msgs to be deleted, or 0 for "any" */
3379                        char *content_type       /* or "" for any.  regular expressions expected. */
3380         )
3381 {
3382         struct ctdlroom qrbuf;
3383         struct cdbdata *cdbfr;
3384         long *msglist = NULL;
3385         long *dellist = NULL;
3386         int num_msgs = 0;
3387         int i, j;
3388         int num_deleted = 0;
3389         int delete_this;
3390         struct MetaData smi;
3391         regex_t re;
3392         regmatch_t pm;
3393         int need_to_free_re = 0;
3394
3395         if (content_type) if (!IsEmptyStr(content_type)) {
3396                         regcomp(&re, content_type, 0);
3397                         need_to_free_re = 1;
3398                 }
3399         syslog(LOG_DEBUG, "msgbase: CtdlDeleteMessages(%s, %d msgs, %s)", room_name, num_dmsgnums, content_type);
3400
3401         /* get room record, obtaining a lock... */
3402         if (CtdlGetRoomLock(&qrbuf, room_name) != 0) {
3403                 syslog(LOG_ERR, "msgbase: CtdlDeleteMessages(): Room <%s> not found", room_name);
3404                 if (need_to_free_re) regfree(&re);
3405                 return(0);      /* room not found */
3406         }
3407         cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf.QRnumber, sizeof(long));
3408
3409         if (cdbfr != NULL) {
3410                 dellist = malloc(cdbfr->len);
3411                 msglist = (long *) cdbfr->ptr;
3412                 cdbfr->ptr = NULL;      /* CtdlDeleteMessages() now owns this memory */
3413                 num_msgs = cdbfr->len / sizeof(long);
3414                 cdb_free(cdbfr);
3415         }
3416         if (num_msgs > 0) {
3417                 int have_contenttype = (content_type != NULL) && !IsEmptyStr(content_type);
3418                 int have_delmsgs = (num_dmsgnums == 0) || (dmsgnums == NULL);
3419                 int have_more_del = 1;
3420
3421                 num_msgs = sort_msglist(msglist, num_msgs);
3422                 if (num_dmsgnums > 1)
3423                         num_dmsgnums = sort_msglist(dmsgnums, num_dmsgnums);
3424 /*
3425                 {
3426                         StrBuf *dbg = NewStrBuf();
3427                         for (i = 0; i < num_dmsgnums; i++)
3428                                 StrBufAppendPrintf(dbg, ", %ld", dmsgnums[i]);
3429                         syslog(LOG_DEBUG, "msgbase: Deleting before: %s", ChrPtr(dbg));
3430                         FreeStrBuf(&dbg);
3431                 }
3432 */
3433                 i = 0; j = 0;
3434                 while ((i < num_msgs) && (have_more_del)) {
3435                         delete_this = 0x00;
3436
3437                         /* Set/clear a bit for each criterion */
3438
3439                         /* 0 messages in the list or a null list means that we are
3440                          * interested in deleting any messages which meet the other criteria.
3441                          */
3442                         if (have_delmsgs) {
3443                                 delete_this |= 0x01;
3444                         }
3445                         else {
3446                                 while ((i < num_msgs) && (msglist[i] < dmsgnums[j])) i++;
3447
3448                                 if (i >= num_msgs)
3449                                         continue;
3450
3451                                 if (msglist[i] == dmsgnums[j]) {
3452                                         delete_this |= 0x01;
3453                                 }
3454                                 j++;
3455                                 have_more_del = (j < num_dmsgnums);
3456                         }
3457
3458                         if (have_contenttype) {
3459                                 GetMetaData(&smi, msglist[i]);
3460                                 if (regexec(&re, smi.meta_content_type, 1, &pm, 0) == 0) {
3461                                         delete_this |= 0x02;
3462                                 }
3463                         } else {
3464                                 delete_this |= 0x02;
3465                         }
3466
3467                         /* Delete message only if all bits are set */
3468                         if (delete_this == 0x03) {
3469                                 dellist[num_deleted++] = msglist[i];
3470                                 msglist[i] = 0L;
3471                         }
3472                         i++;
3473                 }
3474 /*
3475                 {
3476                         StrBuf *dbg = NewStrBuf();
3477                         for (i = 0; i < num_deleted; i++)
3478                                 StrBufAppendPrintf(dbg, ", %ld", dellist[i]);
3479                         syslog(LOG_DEBUG, "msgbase: Deleting: %s", ChrPtr(dbg));
3480                         FreeStrBuf(&dbg);
3481                 }
3482 */
3483                 num_msgs = sort_msglist(msglist, num_msgs);
3484                 cdb_store(CDB_MSGLISTS, &qrbuf.QRnumber, (int)sizeof(long),
3485                           msglist, (int)(num_msgs * sizeof(long)));
3486
3487                 if (num_msgs > 0)
3488                         qrbuf.QRhighest = msglist[num_msgs - 1];
3489                 else
3490                         qrbuf.QRhighest = 0;
3491         }
3492         CtdlPutRoomLock(&qrbuf);
3493
3494         /* Go through the messages we pulled out of the index, and decrement
3495          * their reference counts by 1.  If this is the only room the message
3496          * was in, the reference count will reach zero and the message will
3497          * automatically be deleted from the database.  We do this in a
3498          * separate pass because there might be plug-in hooks getting called,
3499          * and we don't want that happening during an S_ROOMS critical
3500          * section.
3501          */
3502         if (num_deleted) {
3503                 for (i=0; i<num_deleted; ++i) {
3504                         PerformDeleteHooks(qrbuf.QRname, dellist[i]);
3505                 }
3506                 AdjRefCountList(dellist, num_deleted, -1);
3507         }
3508         /* Now free the memory we used, and go away. */
3509         if (msglist != NULL) free(msglist);
3510         if (dellist != NULL) free(dellist);
3511         syslog(LOG_DEBUG, "msgbase: %d message(s) deleted", num_deleted);
3512         if (need_to_free_re) regfree(&re);
3513         return (num_deleted);
3514 }
3515
3516
3517 /*
3518  * GetMetaData()  -  Get the supplementary record for a message
3519  */
3520 void GetMetaData(struct MetaData *smibuf, long msgnum)
3521 {
3522
3523         struct cdbdata *cdbsmi;
3524         long TheIndex;
3525
3526         memset(smibuf, 0, sizeof(struct MetaData));
3527         smibuf->meta_msgnum = msgnum;
3528         smibuf->meta_refcount = 1;      /* Default reference count is 1 */
3529
3530         /* Use the negative of the message number for its supp record index */
3531         TheIndex = (0L - msgnum);
3532
3533         cdbsmi = cdb_fetch(CDB_MSGMAIN, &TheIndex, sizeof(long));
3534         if (cdbsmi == NULL) {
3535                 return;         /* record not found; go with defaults */
3536         }
3537         memcpy(smibuf, cdbsmi->ptr,                                     // FIXME can we do this without a memcpy?
3538                ((cdbsmi->len > sizeof(struct MetaData)) ?
3539                 sizeof(struct MetaData) : cdbsmi->len));
3540         cdb_free(cdbsmi);
3541         return;
3542 }
3543
3544
3545 /*
3546  * PutMetaData()  -  (re)write supplementary record for a message
3547  */
3548 void PutMetaData(struct MetaData *smibuf)
3549 {
3550         long TheIndex;
3551
3552         /* Use the negative of the message number for the metadata db index */
3553         TheIndex = (0L - smibuf->meta_msgnum);
3554
3555         cdb_store(CDB_MSGMAIN,
3556                   &TheIndex, (int)sizeof(long),
3557                   smibuf, (int)sizeof(struct MetaData));
3558
3559 }
3560
3561 /*
3562  * AdjRefCount  -  submit an adjustment to the reference count for a message.
3563  *                 (These are just queued -- we actually process them later.)
3564  */
3565 void AdjRefCount(long msgnum, int incr)
3566 {
3567         struct arcq new_arcq;
3568         int rv = 0;
3569
3570         syslog(LOG_DEBUG, "msgbase: AdjRefCount() msg %ld ref count delta %+d", msgnum, incr);
3571
3572         begin_critical_section(S_SUPPMSGMAIN);
3573         if (arcfp == NULL) {
3574                 arcfp = fopen(file_arcq, "ab+");
3575                 chown(file_arcq, CTDLUID, (-1));
3576                 chmod(file_arcq, 0600);
3577         }
3578         end_critical_section(S_SUPPMSGMAIN);
3579
3580         /* msgnum < 0 means that we're trying to close the file */
3581         if (msgnum < 0) {
3582                 syslog(LOG_DEBUG, "msgbase: closing the AdjRefCount queue file");
3583                 begin_critical_section(S_SUPPMSGMAIN);
3584                 if (arcfp != NULL) {
3585                         fclose(arcfp);
3586                         arcfp = NULL;
3587                 }
3588                 end_critical_section(S_SUPPMSGMAIN);
3589                 return;
3590         }
3591
3592         /*
3593          * If we can't open the queue, perform the operation synchronously.
3594          */
3595         if (arcfp == NULL) {
3596                 TDAP_AdjRefCount(msgnum, incr);
3597                 return;
3598         }
3599
3600         new_arcq.arcq_msgnum = msgnum;
3601         new_arcq.arcq_delta = incr;
3602         rv = fwrite(&new_arcq, sizeof(struct arcq), 1, arcfp);
3603         if (rv == -1) {
3604                 syslog(LOG_EMERG, "%s: %m", file_arcq);
3605         }
3606         fflush(arcfp);
3607
3608         return;
3609 }
3610
3611 void AdjRefCountList(long *msgnum, long nmsg, int incr)
3612 {
3613         long i, the_size, offset;
3614         struct arcq *new_arcq;
3615         int rv = 0;
3616
3617         begin_critical_section(S_SUPPMSGMAIN);
3618         if (arcfp == NULL) {
3619                 arcfp = fopen(file_arcq, "ab+");
3620                 chown(file_arcq, CTDLUID, (-1));
3621                 chmod(file_arcq, 0600);
3622         }
3623         end_critical_section(S_SUPPMSGMAIN);
3624
3625         /*
3626          * If we can't open the queue, perform the operation synchronously.
3627          */
3628         if (arcfp == NULL) {
3629                 for (i = 0; i < nmsg; i++)
3630                         TDAP_AdjRefCount(msgnum[i], incr);
3631                 return;
3632         }
3633
3634         the_size = sizeof(struct arcq) * nmsg;
3635         new_arcq = malloc(the_size);
3636         for (i = 0; i < nmsg; i++) {
3637                 syslog(LOG_DEBUG, "msgbase: AdjRefCountList() msg %ld ref count delta %+d", msgnum[i], incr);
3638                 new_arcq[i].arcq_msgnum = msgnum[i];
3639                 new_arcq[i].arcq_delta = incr;
3640         }
3641         rv = 0;
3642         offset = 0;
3643         while ((rv >= 0) && (offset < the_size))
3644         {
3645                 rv = fwrite(new_arcq + offset, 1, the_size - offset, arcfp);
3646                 if (rv == -1) {
3647                         syslog(LOG_ERR, "%s: %m", file_arcq);
3648                 }
3649                 else {
3650                         offset += rv;
3651                 }
3652         }
3653         free(new_arcq);
3654         fflush(arcfp);
3655
3656         return;
3657 }
3658
3659
3660 /*
3661  * TDAP_ProcessAdjRefCountQueue()
3662  *
3663  * Process the queue of message count adjustments that was created by calls
3664  * to AdjRefCount() ... by reading the queue and calling TDAP_AdjRefCount()
3665  * for each one.  This should be an "off hours" operation.
3666  */
3667 int TDAP_ProcessAdjRefCountQueue(void)
3668 {
3669         char file_arcq_temp[PATH_MAX];
3670         int r;
3671         FILE *fp;
3672         struct arcq arcq_rec;
3673         int num_records_processed = 0;
3674
3675         snprintf(file_arcq_temp, sizeof file_arcq_temp, "%s.%04x", file_arcq, rand());
3676
3677         begin_critical_section(S_SUPPMSGMAIN);
3678         if (arcfp != NULL) {
3679                 fclose(arcfp);
3680                 arcfp = NULL;
3681         }
3682
3683         r = link(file_arcq, file_arcq_temp);
3684         if (r != 0) {
3685                 syslog(LOG_ERR, "%s: %m", file_arcq_temp);
3686                 end_critical_section(S_SUPPMSGMAIN);
3687                 return(num_records_processed);
3688         }
3689
3690         unlink(file_arcq);
3691         end_critical_section(S_SUPPMSGMAIN);
3692
3693         fp = fopen(file_arcq_temp, "rb");
3694         if (fp == NULL) {
3695                 syslog(LOG_ERR, "%s: %m", file_arcq_temp);
3696                 return(num_records_processed);
3697         }
3698
3699         while (fread(&arcq_rec, sizeof(struct arcq), 1, fp) == 1) {
3700                 TDAP_AdjRefCount(arcq_rec.arcq_msgnum, arcq_rec.arcq_delta);
3701                 ++num_records_processed;
3702         }
3703
3704         fclose(fp);
3705         r = unlink(file_arcq_temp);
3706         if (r != 0) {
3707                 syslog(LOG_ERR, "%s: %m", file_arcq_temp);
3708         }
3709
3710         return(num_records_processed);
3711 }
3712
3713
3714
3715 /*
3716  * TDAP_AdjRefCount  -  adjust the reference count for a message.
3717  *                      This one does it "for real" because it's called by
3718  *                      the autopurger function that processes the queue
3719  *                      created by AdjRefCount().   If a message's reference
3720  *                      count becomes zero, we also delete the message from
3721  *                      disk and de-index it.
3722  */
3723 void TDAP_AdjRefCount(long msgnum, int incr)
3724 {
3725
3726         struct MetaData smi;
3727         long delnum;
3728
3729         /* This is a *tight* critical section; please keep it that way, as
3730          * it may get called while nested in other critical sections.  
3731          * Complicating this any further will surely cause deadlock!
3732          */
3733         begin_critical_section(S_SUPPMSGMAIN);
3734         GetMetaData(&smi, msgnum);
3735         smi.meta_refcount += incr;
3736         PutMetaData(&smi);
3737         end_critical_section(S_SUPPMSGMAIN);
3738         syslog(LOG_DEBUG, "msgbase: TDAP_AdjRefCount() msg %ld ref count delta %+d, is now %d",
3739                    msgnum, incr, smi.meta_refcount
3740                 );
3741
3742         /* If the reference count is now zero, delete the message
3743          * (and its supplementary record as well).
3744          */
3745         if (smi.meta_refcount == 0) {
3746                 syslog(LOG_DEBUG, "msgbase: deleting message <%ld>", msgnum);
3747                 
3748                 /* Call delete hooks with NULL room to show it has gone altogether */
3749                 PerformDeleteHooks(NULL, msgnum);
3750
3751                 /* Remove from message base */
3752                 delnum = msgnum;
3753                 cdb_delete(CDB_MSGMAIN, &delnum, (int)sizeof(long));
3754                 cdb_delete(CDB_BIGMSGS, &delnum, (int)sizeof(long));
3755
3756                 /* Remove metadata record */
3757                 delnum = (0L - msgnum);
3758                 cdb_delete(CDB_MSGMAIN, &delnum, (int)sizeof(long));
3759         }
3760
3761 }
3762
3763 /*
3764  * Write a generic object to this room
3765  *
3766  * Note: this could be much more efficient.  Right now we use two temporary
3767  * files, and still pull the message into memory as with all others.
3768  */
3769 void CtdlWriteObject(char *req_room,                    /* Room to stuff it in */
3770                      char *content_type,                /* MIME type of this object */
3771                      char *raw_message,         /* Data to be written */
3772                      off_t raw_length,          /* Size of raw_message */
3773                      struct ctdluser *is_mailbox,       /* Mailbox room? */
3774                      int is_binary,                     /* Is encoding necessary? */
3775                      int is_unique,                     /* Del others of this type? */
3776                      unsigned int flags         /* Internal save flags */
3777         )
3778 {
3779         struct ctdlroom qrbuf;
3780         char roomname[ROOMNAMELEN];
3781         struct CtdlMessage *msg;
3782         StrBuf *encoded_message = NULL;
3783
3784         if (is_mailbox != NULL) {
3785                 CtdlMailboxName(roomname, sizeof roomname, is_mailbox, req_room);
3786         }
3787         else {
3788                 safestrncpy(roomname, req_room, sizeof(roomname));
3789         }
3790
3791         syslog(LOG_DEBUG, "msfbase: raw length is %ld", (long)raw_length);
3792
3793         if (is_binary) {
3794                 encoded_message = NewStrBufPlain(NULL, (size_t) (((raw_length * 134) / 100) + 4096 ) );
3795         }
3796         else {
3797                 encoded_message = NewStrBufPlain(NULL, (size_t)(raw_length + 4096));
3798         }
3799
3800         StrBufAppendBufPlain(encoded_message, HKEY("Content-type: "), 0);
3801         StrBufAppendBufPlain(encoded_message, content_type, -1, 0);
3802         StrBufAppendBufPlain(encoded_message, HKEY("\n"), 0);
3803
3804         if (is_binary) {
3805                 StrBufAppendBufPlain(encoded_message, HKEY("Content-transfer-encoding: base64\n\n"), 0);
3806         }
3807         else {
3808                 StrBufAppendBufPlain(encoded_message, HKEY("Content-transfer-encoding: 7bit\n\n"), 0);
3809         }
3810
3811         if (is_binary) {
3812                 StrBufBase64Append(encoded_message, NULL, raw_message, raw_length, 0);
3813         }
3814         else {
3815                 StrBufAppendBufPlain(encoded_message, raw_message, raw_length, 0);
3816         }
3817
3818         syslog(LOG_DEBUG, "msgbase: allocating");
3819         msg = malloc(sizeof(struct CtdlMessage));
3820         memset(msg, 0, sizeof(struct CtdlMessage));
3821         msg->cm_magic = CTDLMESSAGE_MAGIC;
3822         msg->cm_anon_type = MES_NORMAL;
3823         msg->cm_format_type = 4;
3824         CM_SetField(msg, eAuthor, CC->user.fullname, strlen(CC->user.fullname));
3825         CM_SetField(msg, eOriginalRoom, req_room, strlen(req_room));
3826         CM_SetField(msg, eNodeName, CtdlGetConfigStr("c_nodename"), strlen(CtdlGetConfigStr("c_nodename")));
3827         CM_SetField(msg, eHumanNode, CtdlGetConfigStr("c_humannode"), strlen(CtdlGetConfigStr("c_humannode")));
3828         msg->cm_flags = flags;
3829         
3830         CM_SetAsFieldSB(msg, eMesageText, &encoded_message);
3831
3832         /* Create the requested room if we have to. */
3833         if (CtdlGetRoom(&qrbuf, roomname) != 0) {
3834                 CtdlCreateRoom(roomname, 
3835                                ( (is_mailbox != NULL) ? 5 : 3 ),
3836                                "", 0, 1, 0, VIEW_BBS);
3837         }
3838         /* If the caller specified this object as unique, delete all
3839          * other objects of this type that are currently in the room.
3840          */
3841         if (is_unique) {
3842                 syslog(LOG_DEBUG, "msgbase: deleted %d other msgs of this type",
3843                            CtdlDeleteMessages(roomname, NULL, 0, content_type)
3844                         );
3845         }
3846         /* Now write the data */
3847         CtdlSubmitMsg(msg, NULL, roomname, 0);
3848         CM_Free(msg);
3849 }
3850
3851
3852
3853 /*****************************************************************************/
3854 /*                      MODULE INITIALIZATION STUFF                          */
3855 /*****************************************************************************/
3856
3857 CTDL_MODULE_INIT(msgbase)
3858 {
3859         if (!threading) {
3860                 FillMsgKeyLookupTable();
3861         }
3862
3863         /* return our Subversion id for the Log */
3864         return "msgbase";
3865 }