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