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