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