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