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