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