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