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