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