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