2cd006d2e02b406648d90d11b399596d0e895d3a
[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                 client_write(nl, nllen);
945                 column = 0;
946         }
947 }
948
949
950
951 /*
952  * Callback function for mime parser that simply lists the part
953  */
954 void list_this_part(char *name, char *filename, char *partnum, char *disp,
955                     void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
956                     char *cbid, void *cbuserdata)
957 {
958         struct ma_info *ma;
959         
960         ma = (struct ma_info *)cbuserdata;
961         if (ma->is_ma == 0) {
962                 cprintf("part=%s|%s|%s|%s|%s|%ld|%s|%s\n",
963                         name, 
964                         filename, 
965                         partnum, 
966                         disp, 
967                         cbtype, 
968                         (long)length, 
969                         cbid, 
970                         cbcharset);
971         }
972 }
973
974 /* 
975  * Callback function for multipart prefix
976  */
977 void list_this_pref(char *name, char *filename, char *partnum, char *disp,
978                     void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
979                     char *cbid, void *cbuserdata)
980 {
981         struct ma_info *ma;
982         
983         ma = (struct ma_info *)cbuserdata;
984         if (!strcasecmp(cbtype, "multipart/alternative")) {
985                 ++ma->is_ma;
986         }
987
988         if (ma->is_ma == 0) {
989                 cprintf("pref=%s|%s\n", partnum, cbtype);
990         }
991 }
992
993 /* 
994  * Callback function for multipart sufffix
995  */
996 void list_this_suff(char *name, char *filename, char *partnum, char *disp,
997                     void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
998                     char *cbid, void *cbuserdata)
999 {
1000         struct ma_info *ma;
1001         
1002         ma = (struct ma_info *)cbuserdata;
1003         if (ma->is_ma == 0) {
1004                 cprintf("suff=%s|%s\n", partnum, cbtype);
1005         }
1006         if (!strcasecmp(cbtype, "multipart/alternative")) {
1007                 --ma->is_ma;
1008         }
1009 }
1010
1011
1012 /*
1013  * Callback function for mime parser that opens a section for downloading
1014  * we use serv_files function here: 
1015  */
1016 extern void OpenCmdResult(char *filename, const char *mime_type);
1017 void mime_download(char *name, char *filename, char *partnum, char *disp,
1018                    void *content, char *cbtype, char *cbcharset, size_t length,
1019                    char *encoding, char *cbid, void *cbuserdata)
1020 {
1021         int rv = 0;
1022         CitContext *CCC = MyContext();
1023
1024         /* Silently go away if there's already a download open. */
1025         if (CCC->download_fp != NULL)
1026                 return;
1027
1028         if (
1029                 (!IsEmptyStr(partnum) && (!strcasecmp(CCC->download_desired_section, partnum)))
1030         ||      (!IsEmptyStr(cbid) && (!strcasecmp(CCC->download_desired_section, cbid)))
1031         ) {
1032                 CCC->download_fp = tmpfile();
1033                 if (CCC->download_fp == NULL) {
1034                         MSG_syslog(LOG_EMERG, "mime_download(): Couldn't write: %s\n",
1035                                     strerror(errno));
1036                         cprintf("%d cannot open temporary file: %s\n",
1037                                 ERROR + INTERNAL_ERROR, strerror(errno));
1038                         return;
1039                 }
1040         
1041                 rv = fwrite(content, length, 1, CCC->download_fp);
1042                 if (rv <= 0) {
1043                         MSG_syslog(LOG_EMERG, "mime_download(): Couldn't write: %s\n",
1044                                    strerror(errno));
1045                         cprintf("%d unable to write tempfile.\n",
1046                                 ERROR + TOO_BIG);
1047                         fclose(CCC->download_fp);
1048                         CCC->download_fp = NULL;
1049                         return;
1050                 }
1051                 fflush(CCC->download_fp);
1052                 rewind(CCC->download_fp);
1053         
1054                 OpenCmdResult(filename, cbtype);
1055         }
1056 }
1057
1058
1059
1060 /*
1061  * Callback function for mime parser that outputs a section all at once.
1062  * We can specify the desired section by part number *or* content-id.
1063  */
1064 void mime_spew_section(char *name, char *filename, char *partnum, char *disp,
1065                    void *content, char *cbtype, char *cbcharset, size_t length,
1066                    char *encoding, char *cbid, void *cbuserdata)
1067 {
1068         int *found_it = (int *)cbuserdata;
1069
1070         if (
1071                 (!IsEmptyStr(partnum) && (!strcasecmp(CC->download_desired_section, partnum)))
1072         ||      (!IsEmptyStr(cbid) && (!strcasecmp(CC->download_desired_section, cbid)))
1073         ) {
1074                 *found_it = 1;
1075                 cprintf("%d %d|-1|%s|%s|%s\n",
1076                         BINARY_FOLLOWS,
1077                         (int)length,
1078                         filename,
1079                         cbtype,
1080                         cbcharset
1081                 );
1082                 client_write(content, length);
1083         }
1084 }
1085
1086
1087 /*
1088  * Load a message from disk into memory.
1089  * This is used by CtdlOutputMsg() and other fetch functions.
1090  *
1091  * NOTE: Caller is responsible for freeing the returned CtdlMessage struct
1092  *       using the CtdlMessageFree() function.
1093  */
1094 struct CtdlMessage *CtdlFetchMessage(long msgnum, int with_body)
1095 {
1096         struct CitContext *CCC = CC;
1097         struct cdbdata *dmsgtext;
1098         struct CtdlMessage *ret = NULL;
1099         char *mptr;
1100         char *upper_bound;
1101         cit_uint8_t ch;
1102         cit_uint8_t field_header;
1103         eMsgField which;
1104
1105         MSG_syslog(LOG_DEBUG, "CtdlFetchMessage(%ld, %d)\n", msgnum, with_body);
1106         dmsgtext = cdb_fetch(CDB_MSGMAIN, &msgnum, sizeof(long));
1107         if (dmsgtext == NULL) {
1108                 MSG_syslog(LOG_ERR, "CtdlFetchMessage(%ld, %d) Failed!\n", msgnum, with_body);
1109                 return NULL;
1110         }
1111         mptr = dmsgtext->ptr;
1112         upper_bound = mptr + dmsgtext->len;
1113
1114         /* Parse the three bytes that begin EVERY message on disk.
1115          * The first is always 0xFF, the on-disk magic number.
1116          * The second is the anonymous/public type byte.
1117          * The third is the format type byte (vari, fixed, or MIME).
1118          */
1119         ch = *mptr++;
1120         if (ch != 255) {
1121                 MSG_syslog(LOG_ERR, "Message %ld appears to be corrupted.\n", msgnum);
1122                 cdb_free(dmsgtext);
1123                 return NULL;
1124         }
1125         ret = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
1126         memset(ret, 0, sizeof(struct CtdlMessage));
1127
1128         ret->cm_magic = CTDLMESSAGE_MAGIC;
1129         ret->cm_anon_type = *mptr++;    /* Anon type byte */
1130         ret->cm_format_type = *mptr++;  /* Format type byte */
1131
1132
1133         if (dmsgtext->ptr[dmsgtext->len - 1] != '\0')
1134         {
1135                 MSG_syslog(LOG_ERR, "CtdlFetchMessage(%ld, %d) Forcefully terminating message!!\n", msgnum, with_body);
1136                 dmsgtext->ptr[dmsgtext->len - 1] = '\0';
1137         }
1138
1139         /*
1140          * The rest is zero or more arbitrary fields.  Load them in.
1141          * We're done when we encounter either a zero-length field or
1142          * have just processed the 'M' (message text) field.
1143          */
1144         do {
1145                 long len;
1146                 if (mptr >= upper_bound) {
1147                         break;
1148                 }
1149                 field_header = *mptr++;
1150                 which = field_header;
1151                 len = strlen(mptr);
1152                 CM_SetField(ret, which, mptr, len);
1153
1154                 mptr += len + 1;        /* advance to next field */
1155
1156         } while ((mptr < upper_bound) && (field_header != 'M'));
1157
1158         cdb_free(dmsgtext);
1159
1160         /* Always make sure there's something in the msg text field.  If
1161          * it's NULL, the message text is most likely stored separately,
1162          * so go ahead and fetch that.  Failing that, just set a dummy
1163          * body so other code doesn't barf.
1164          */
1165         if ( (CM_IsEmpty(ret, eMesageText)) && (with_body) ) {
1166                 dmsgtext = cdb_fetch(CDB_BIGMSGS, &msgnum, sizeof(long));
1167                 if (dmsgtext != NULL) {
1168                         CM_SetAsField(ret, eMesageText, &dmsgtext->ptr, dmsgtext->len);
1169                         cdb_free(dmsgtext);
1170                 }
1171         }
1172         if (CM_IsEmpty(ret, eMesageText)) {
1173                 CM_SetField(ret, eMesageText, HKEY("\r\n\r\n (no text)\r\n"));
1174         }
1175
1176         /* Perform "before read" hooks (aborting if any return nonzero) */
1177         if (PerformMessageHooks(ret, NULL, EVT_BEFOREREAD) > 0) {
1178                 CM_Free(ret);
1179                 return NULL;
1180         }
1181
1182         return (ret);
1183 }
1184
1185
1186
1187 /*
1188  * Pre callback function for multipart/alternative
1189  *
1190  * NOTE: this differs from the standard behavior for a reason.  Normally when
1191  *       displaying multipart/alternative you want to show the _last_ usable
1192  *       format in the message.  Here we show the _first_ one, because it's
1193  *       usually text/plain.  Since this set of functions is designed for text
1194  *       output to non-MIME-aware clients, this is the desired behavior.
1195  *
1196  */
1197 void fixed_output_pre(char *name, char *filename, char *partnum, char *disp,
1198                 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
1199                 char *cbid, void *cbuserdata)
1200 {
1201         struct CitContext *CCC = CC;
1202         struct ma_info *ma;
1203         
1204         ma = (struct ma_info *)cbuserdata;
1205         MSG_syslog(LOG_DEBUG, "fixed_output_pre() type=<%s>\n", cbtype);        
1206         if (!strcasecmp(cbtype, "multipart/alternative")) {
1207                 ++ma->is_ma;
1208                 ma->did_print = 0;
1209         }
1210         if (!strcasecmp(cbtype, "message/rfc822")) {
1211                 ++ma->freeze;
1212         }
1213 }
1214
1215 /*
1216  * Post callback function for multipart/alternative
1217  */
1218 void fixed_output_post(char *name, char *filename, char *partnum, char *disp,
1219                 void *content, char *cbtype, char *cbcharset, size_t length,
1220                 char *encoding, char *cbid, void *cbuserdata)
1221 {
1222         struct CitContext *CCC = CC;
1223         struct ma_info *ma;
1224         
1225         ma = (struct ma_info *)cbuserdata;
1226         MSG_syslog(LOG_DEBUG, "fixed_output_post() type=<%s>\n", cbtype);       
1227         if (!strcasecmp(cbtype, "multipart/alternative")) {
1228                 --ma->is_ma;
1229                 ma->did_print = 0;
1230         }
1231         if (!strcasecmp(cbtype, "message/rfc822")) {
1232                 --ma->freeze;
1233         }
1234 }
1235
1236 /*
1237  * Inline callback function for mime parser that wants to display text
1238  */
1239 void fixed_output(char *name, char *filename, char *partnum, char *disp,
1240                 void *content, char *cbtype, char *cbcharset, size_t length,
1241                 char *encoding, char *cbid, void *cbuserdata)
1242 {
1243         struct CitContext *CCC = CC;
1244         char *ptr;
1245         char *wptr;
1246         size_t wlen;
1247         struct ma_info *ma;
1248
1249         ma = (struct ma_info *)cbuserdata;
1250
1251         MSG_syslog(LOG_DEBUG,
1252                 "fixed_output() part %s: %s (%s) (%ld bytes)\n",
1253                 partnum, filename, cbtype, (long)length);
1254
1255         /*
1256          * If we're in the middle of a multipart/alternative scope and
1257          * we've already printed another section, skip this one.
1258          */     
1259         if ( (ma->is_ma) && (ma->did_print) ) {
1260                 MSG_syslog(LOG_DEBUG, "Skipping part %s (%s)\n", partnum, cbtype);
1261                 return;
1262         }
1263         ma->did_print = 1;
1264
1265         if ( (!strcasecmp(cbtype, "text/plain")) 
1266            || (IsEmptyStr(cbtype)) ) {
1267                 wptr = content;
1268                 if (length > 0) {
1269                         client_write(wptr, length);
1270                         if (wptr[length-1] != '\n') {
1271                                 cprintf("\n");
1272                         }
1273                 }
1274                 return;
1275         }
1276
1277         if (!strcasecmp(cbtype, "text/html")) {
1278                 ptr = html_to_ascii(content, length, 80, 0);
1279                 wlen = strlen(ptr);
1280                 client_write(ptr, wlen);
1281                 if ((wlen > 0) && (ptr[wlen-1] != '\n')) {
1282                         cprintf("\n");
1283                 }
1284                 free(ptr);
1285                 return;
1286         }
1287
1288         if (ma->use_fo_hooks) {
1289                 if (PerformFixedOutputHooks(cbtype, content, length)) {
1290                 /* above function returns nonzero if it handled the part */
1291                         return;
1292                 }
1293         }
1294
1295         if (strncasecmp(cbtype, "multipart/", 10)) {
1296                 cprintf("Part %s: %s (%s) (%ld bytes)\r\n",
1297                         partnum, filename, cbtype, (long)length);
1298                 return;
1299         }
1300 }
1301
1302 /*
1303  * The client is elegant and sophisticated and wants to be choosy about
1304  * MIME content types, so figure out which multipart/alternative part
1305  * we're going to send.
1306  *
1307  * We use a system of weights.  When we find a part that matches one of the
1308  * MIME types we've declared as preferential, we can store it in ma->chosen_part
1309  * and then set ma->chosen_pref to that MIME type's position in our preference
1310  * list.  If we then hit another match, we only replace the first match if
1311  * the preference value is lower.
1312  */
1313 void choose_preferred(char *name, char *filename, char *partnum, char *disp,
1314                 void *content, char *cbtype, char *cbcharset, size_t length,
1315                 char *encoding, char *cbid, void *cbuserdata)
1316 {
1317         struct CitContext *CCC = CC;
1318         char buf[1024];
1319         int i;
1320         struct ma_info *ma;
1321         
1322         ma = (struct ma_info *)cbuserdata;
1323
1324         // NOTE: REMOVING THIS CONDITIONAL FIXES BUG 220
1325         //       http://bugzilla.citadel.org/show_bug.cgi?id=220
1326         // I don't know if there are any side effects!  Please TEST TEST TEST
1327         //if (ma->is_ma > 0) {
1328
1329         for (i=0; i<num_tokens(CCC->preferred_formats, '|'); ++i) {
1330                 extract_token(buf, CCC->preferred_formats, i, '|', sizeof buf);
1331                 if ( (!strcasecmp(buf, cbtype)) && (!ma->freeze) ) {
1332                         if (i < ma->chosen_pref) {
1333                                 MSG_syslog(LOG_DEBUG, "Setting chosen part: <%s>\n", partnum);
1334                                 safestrncpy(ma->chosen_part, partnum, sizeof ma->chosen_part);
1335                                 ma->chosen_pref = i;
1336                         }
1337                 }
1338         }
1339 }
1340
1341 /*
1342  * Now that we've chosen our preferred part, output it.
1343  */
1344 void output_preferred(char *name, 
1345                       char *filename, 
1346                       char *partnum, 
1347                       char *disp,
1348                       void *content, 
1349                       char *cbtype, 
1350                       char *cbcharset, 
1351                       size_t length,
1352                       char *encoding, 
1353                       char *cbid, 
1354                       void *cbuserdata)
1355 {
1356         struct CitContext *CCC = CC;
1357         int i;
1358         char buf[128];
1359         int add_newline = 0;
1360         char *text_content;
1361         struct ma_info *ma;
1362         char *decoded = NULL;
1363         size_t bytes_decoded;
1364         int rc = 0;
1365
1366         ma = (struct ma_info *)cbuserdata;
1367
1368         /* This is not the MIME part you're looking for... */
1369         if (strcasecmp(partnum, ma->chosen_part)) return;
1370
1371         /* If the content-type of this part is in our preferred formats
1372          * list, we can simply output it verbatim.
1373          */
1374         for (i=0; i<num_tokens(CCC->preferred_formats, '|'); ++i) {
1375                 extract_token(buf, CCC->preferred_formats, i, '|', sizeof buf);
1376                 if (!strcasecmp(buf, cbtype)) {
1377                         /* Yeah!  Go!  W00t!! */
1378                         if (ma->dont_decode == 0) 
1379                                 rc = mime_decode_now (content, 
1380                                                       length,
1381                                                       encoding,
1382                                                       &decoded,
1383                                                       &bytes_decoded);
1384                         if (rc < 0)
1385                                 break; /* Give us the chance, maybe theres another one. */
1386
1387                         if (rc == 0) text_content = (char *)content;
1388                         else {
1389                                 text_content = decoded;
1390                                 length = bytes_decoded;
1391                         }
1392
1393                         if (text_content[length-1] != '\n') {
1394                                 ++add_newline;
1395                         }
1396                         cprintf("Content-type: %s", cbtype);
1397                         if (!IsEmptyStr(cbcharset)) {
1398                                 cprintf("; charset=%s", cbcharset);
1399                         }
1400                         cprintf("\nContent-length: %d\n",
1401                                 (int)(length + add_newline) );
1402                         if (!IsEmptyStr(encoding)) {
1403                                 cprintf("Content-transfer-encoding: %s\n", encoding);
1404                         }
1405                         else {
1406                                 cprintf("Content-transfer-encoding: 7bit\n");
1407                         }
1408                         cprintf("X-Citadel-MSG4-Partnum: %s\n", partnum);
1409                         cprintf("\n");
1410                         if (client_write(text_content, length) == -1)
1411                         {
1412                                 MSGM_syslog(LOG_ERR, "output_preferred(): aborting due to write failure.\n");
1413                                 return;
1414                         }
1415                         if (add_newline) cprintf("\n");
1416                         if (decoded != NULL) free(decoded);
1417                         return;
1418                 }
1419         }
1420
1421         /* No translations required or possible: output as text/plain */
1422         cprintf("Content-type: text/plain\n\n");
1423         rc = 0;
1424         if (ma->dont_decode == 0)
1425                 rc = mime_decode_now (content, 
1426                                       length,
1427                                       encoding,
1428                                       &decoded,
1429                                       &bytes_decoded);
1430         if (rc < 0)
1431                 return; /* Give us the chance, maybe theres another one. */
1432         
1433         if (rc == 0) text_content = (char *)content;
1434         else {
1435                 text_content = decoded;
1436                 length = bytes_decoded;
1437         }
1438
1439         fixed_output(name, filename, partnum, disp, text_content, cbtype, cbcharset,
1440                         length, encoding, cbid, cbuserdata);
1441         if (decoded != NULL) free(decoded);
1442 }
1443
1444
1445 struct encapmsg {
1446         char desired_section[64];
1447         char *msg;
1448         size_t msglen;
1449 };
1450
1451
1452 /*
1453  * Callback function for
1454  */
1455 void extract_encapsulated_message(char *name, char *filename, char *partnum, char *disp,
1456                    void *content, char *cbtype, char *cbcharset, size_t length,
1457                    char *encoding, char *cbid, void *cbuserdata)
1458 {
1459         struct encapmsg *encap;
1460
1461         encap = (struct encapmsg *)cbuserdata;
1462
1463         /* Only proceed if this is the desired section... */
1464         if (!strcasecmp(encap->desired_section, partnum)) {
1465                 encap->msglen = length;
1466                 encap->msg = malloc(length + 2);
1467                 memcpy(encap->msg, content, length);
1468                 return;
1469         }
1470 }
1471
1472
1473 /*
1474  * Determine whether the specified message exists in the cached_msglist
1475  * (This is a security check)
1476  */
1477 int check_cached_msglist(long msgnum) {
1478         struct CitContext *CCC = CC;
1479
1480         /* cases in which we skip the check */
1481         if (!CCC) return om_ok;                                         /* not a session */
1482         if (CCC->client_socket <= 0) return om_ok;                      /* not a client session */
1483         if (CCC->cached_msglist == NULL) return om_access_denied;       /* no msglist fetched */
1484         if (CCC->cached_num_msgs == 0) return om_access_denied;         /* nothing to check */
1485
1486
1487         /* Do a binary search within the cached_msglist for the requested msgnum */
1488         int min = 0;
1489         int max = (CC->cached_num_msgs - 1);
1490
1491         while (max >= min) {
1492                 int middle = min + (max-min) / 2 ;
1493                 if (msgnum == CCC->cached_msglist[middle]) {
1494                         return om_ok;
1495                 }
1496                 if (msgnum > CC->cached_msglist[middle]) {
1497                         min = middle + 1;
1498                 }
1499                 else {
1500                         max = middle - 1;
1501                 }
1502         }
1503
1504         return om_access_denied;
1505 }
1506
1507
1508
1509 /*
1510  * Get a message off disk.  (returns om_* values found in msgbase.h)
1511  * 
1512  */
1513 int CtdlOutputMsg(long msg_num,         /* message number (local) to fetch */
1514                   int mode,             /* how would you like that message? */
1515                   int headers_only,     /* eschew the message body? */
1516                   int do_proto,         /* do Citadel protocol responses? */
1517                   int crlf,             /* Use CRLF newlines instead of LF? */
1518                   char *section,        /* NULL or a message/rfc822 section */
1519                   int flags,            /* various flags; see msgbase.h */
1520                   char **Author,
1521                   char **Address
1522 ) {
1523         struct CitContext *CCC = CC;
1524         struct CtdlMessage *TheMessage = NULL;
1525         int retcode = CIT_OK;
1526         struct encapmsg encap;
1527         int r;
1528
1529         MSG_syslog(LOG_DEBUG, "CtdlOutputMsg(msgnum=%ld, mode=%d, section=%s)\n", 
1530                 msg_num, mode,
1531                 (section ? section : "<>")
1532         );
1533
1534         r = CtdlDoIHavePermissionToReadMessagesInThisRoom();
1535         if (r != om_ok) {
1536                 if (do_proto) {
1537                         if (r == om_not_logged_in) {
1538                                 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
1539                         }
1540                         else {
1541                                 cprintf("%d An unknown error has occurred.\n", ERROR);
1542                         }
1543                 }
1544                 return(r);
1545         }
1546
1547         /*
1548          * Check to make sure the message is actually IN this room
1549          */
1550         r = check_cached_msglist(msg_num);
1551         if (r == om_access_denied) {
1552                 /* Not in the cache?  We get ONE shot to check it again. */
1553                 CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL, NULL, NULL);
1554                 r = check_cached_msglist(msg_num);
1555         }
1556         if (r != om_ok) {
1557                 MSG_syslog(LOG_DEBUG, "Security check fail: message %ld is not in %s\n",
1558                            msg_num, CCC->room.QRname
1559                 );
1560                 if (do_proto) {
1561                         if (r == om_access_denied) {
1562                                 cprintf("%d message %ld was not found in this room\n",
1563                                         ERROR + HIGHER_ACCESS_REQUIRED,
1564                                         msg_num
1565                                 );
1566                         }
1567                 }
1568                 return(r);
1569         }
1570
1571         /*
1572          * Fetch the message from disk.  If we're in HEADERS_FAST mode,
1573          * request that we don't even bother loading the body into memory.
1574          */
1575         if (headers_only == HEADERS_FAST) {
1576                 TheMessage = CtdlFetchMessage(msg_num, 0);
1577         }
1578         else {
1579                 TheMessage = CtdlFetchMessage(msg_num, 1);
1580         }
1581
1582         if (TheMessage == NULL) {
1583                 if (do_proto) cprintf("%d Can't locate msg %ld on disk\n",
1584                         ERROR + MESSAGE_NOT_FOUND, msg_num);
1585                 return(om_no_such_msg);
1586         }
1587
1588         /* Here is the weird form of this command, to process only an
1589          * encapsulated message/rfc822 section.
1590          */
1591         if (section) if (!IsEmptyStr(section)) if (strcmp(section, "0")) {
1592                 memset(&encap, 0, sizeof encap);
1593                 safestrncpy(encap.desired_section, section, sizeof encap.desired_section);
1594                 mime_parser(CM_RANGE(TheMessage, eMesageText),
1595                             *extract_encapsulated_message,
1596                             NULL, NULL, (void *)&encap, 0
1597                         );
1598
1599                 if ((Author != NULL) && (*Author == NULL))
1600                 {
1601                         long len;
1602                         CM_GetAsField(TheMessage, eAuthor, Author, &len);
1603                 }
1604                 if ((Address != NULL) && (*Address == NULL))
1605                 {       
1606                         long len;
1607                         CM_GetAsField(TheMessage, erFc822Addr, Address, &len);
1608                 }
1609                 CM_Free(TheMessage);
1610                 TheMessage = NULL;
1611
1612                 if (encap.msg) {
1613                         encap.msg[encap.msglen] = 0;
1614                         TheMessage = convert_internet_message(encap.msg);
1615                         encap.msg = NULL;       /* no free() here, TheMessage owns it now */
1616
1617                         /* Now we let it fall through to the bottom of this
1618                          * function, because TheMessage now contains the
1619                          * encapsulated message instead of the top-level
1620                          * message.  Isn't that neat?
1621                          */
1622                 }
1623                 else {
1624                         if (do_proto) {
1625                                 cprintf("%d msg %ld has no part %s\n",
1626                                         ERROR + MESSAGE_NOT_FOUND,
1627                                         msg_num,
1628                                         section);
1629                         }
1630                         retcode = om_no_such_msg;
1631                 }
1632
1633         }
1634
1635         /* Ok, output the message now */
1636         if (retcode == CIT_OK)
1637                 retcode = CtdlOutputPreLoadedMsg(TheMessage, mode, headers_only, do_proto, crlf, flags);
1638         if ((Author != NULL) && (*Author == NULL))
1639         {
1640                 long len;
1641                 CM_GetAsField(TheMessage, eAuthor, Author, &len);
1642         }
1643         if ((Address != NULL) && (*Address == NULL))
1644         {       
1645                 long len;
1646                 CM_GetAsField(TheMessage, erFc822Addr, Address, &len);
1647         }
1648
1649         CM_Free(TheMessage);
1650
1651         return(retcode);
1652 }
1653
1654
1655
1656 void OutputCtdlMsgHeaders(
1657         struct CtdlMessage *TheMessage,
1658         int do_proto)           /* do Citadel protocol responses? */
1659 {
1660         int i;
1661         int suppress_f = 0;
1662         char buf[SIZ];
1663         char display_name[256];
1664
1665         /* begin header processing loop for Citadel message format */
1666         safestrncpy(display_name, "<unknown>", sizeof display_name);
1667         if (!CM_IsEmpty(TheMessage, eAuthor)) {
1668                 strcpy(buf, TheMessage->cm_fields[eAuthor]);
1669                 if (TheMessage->cm_anon_type == MES_ANONONLY) {
1670                         safestrncpy(display_name, "****", sizeof display_name);
1671                 }
1672                 else if (TheMessage->cm_anon_type == MES_ANONOPT) {
1673                         safestrncpy(display_name, "anonymous", sizeof display_name);
1674                 }
1675                 else {
1676                         safestrncpy(display_name, buf, sizeof display_name);
1677                 }
1678                 if ((is_room_aide())
1679                     && ((TheMessage->cm_anon_type == MES_ANONONLY)
1680                         || (TheMessage->cm_anon_type == MES_ANONOPT))) {
1681                         size_t tmp = strlen(display_name);
1682                         snprintf(&display_name[tmp],
1683                                  sizeof display_name - tmp,
1684                                  " [%s]", buf);
1685                 }
1686         }
1687
1688         /* Don't show Internet address for users on the
1689          * local Citadel network.
1690          */
1691         suppress_f = 0;
1692         if (!CM_IsEmpty(TheMessage, eNodeName) &&
1693             (haschar(TheMessage->cm_fields[eNodeName], '.') == 0))
1694         {
1695                 suppress_f = 1;
1696         }
1697
1698         /* Now spew the header fields in the order we like them. */
1699         for (i=0; i< NDiskFields; ++i) {
1700                 eMsgField Field;
1701                 Field = FieldOrder[i];
1702                 if (Field != eMesageText) {
1703                         if ( (!CM_IsEmpty(TheMessage, Field))
1704                              && (msgkeys[Field] != NULL) ) {
1705                                 if ((Field == eenVelopeTo) ||
1706                                     (Field == eRecipient) ||
1707                                     (Field == eCarbonCopY)) {
1708                                         sanitize_truncated_recipient(TheMessage->cm_fields[Field]);
1709                                 }
1710                                 if (Field == eAuthor) {
1711                                         if (do_proto) cprintf("%s=%s\n",
1712                                                               msgkeys[Field],
1713                                                               display_name);
1714                                 }
1715                                 else if ((Field == erFc822Addr) && (suppress_f)) {
1716                                         /* do nothing */
1717                                 }
1718                                 /* Masquerade display name if needed */
1719                                 else {
1720                                         if (do_proto) cprintf("%s=%s\n",
1721                                                               msgkeys[Field],
1722                                                               TheMessage->cm_fields[Field]
1723                                                 );
1724                                 }
1725                         }
1726                 }
1727         }
1728
1729 }
1730
1731 void OutputRFC822MsgHeaders(
1732         struct CtdlMessage *TheMessage,
1733         int flags,              /* should the bessage be exported clean */
1734         const char *nl,
1735         char *mid, long sizeof_mid,
1736         char *suser, long sizeof_suser,
1737         char *luser, long sizeof_luser,
1738         char *fuser, long sizeof_fuser,
1739         char *snode, long sizeof_snode)
1740 {
1741         char datestamp[100];
1742         int subject_found = 0;
1743         char buf[SIZ];
1744         int i, j, k;
1745         char *mptr = NULL;
1746         char *mpptr = NULL;
1747         char *hptr;
1748
1749         for (i = 0; i < 256; ++i) {
1750                 if (TheMessage->cm_fields[i]) {
1751                         mptr = mpptr = TheMessage->cm_fields[i];
1752                                 
1753                         if (i == eAuthor) {
1754                                 safestrncpy(luser, mptr, sizeof_luser);
1755                                 safestrncpy(suser, mptr, sizeof_suser);
1756                         }
1757                         else if (i == 'Y') {
1758                                 if ((flags & QP_EADDR) != 0) {
1759                                         mptr = qp_encode_email_addrs(mptr);
1760                                 }
1761                                 sanitize_truncated_recipient(mptr);
1762                                 cprintf("CC: %s%s", mptr, nl);
1763                         }
1764                         else if (i == 'P') {
1765                                 cprintf("Return-Path: %s%s", mptr, nl);
1766                         }
1767                         else if (i == eListID) {
1768                                 cprintf("List-ID: %s%s", mptr, nl);
1769                         }
1770                         else if (i == 'V') {
1771                                 if ((flags & QP_EADDR) != 0) 
1772                                         mptr = qp_encode_email_addrs(mptr);
1773                                 hptr = mptr;
1774                                 while ((*hptr != '\0') && isspace(*hptr))
1775                                         hptr ++;
1776                                 if (!IsEmptyStr(hptr))
1777                                         cprintf("Envelope-To: %s%s", hptr, nl);
1778                         }
1779                         else if (i == 'U') {
1780                                 cprintf("Subject: %s%s", mptr, nl);
1781                                 subject_found = 1;
1782                         }
1783                         else if (i == 'I')
1784                                 safestrncpy(mid, mptr, sizeof_mid); /// TODO: detect @ here and copy @nodename in if not found.
1785                         else if (i == erFc822Addr)
1786                                 safestrncpy(fuser, mptr, sizeof_fuser);
1787                         /* else if (i == 'O')
1788                            cprintf("X-Citadel-Room: %s%s",
1789                            mptr, nl); */
1790                         else if (i == 'N')
1791                                 safestrncpy(snode, mptr, sizeof_snode);
1792                         else if (i == 'R')
1793                         {
1794                                 if (haschar(mptr, '@') == 0)
1795                                 {
1796                                         sanitize_truncated_recipient(mptr);
1797                                         cprintf("To: %s@%s", mptr, config.c_fqdn);
1798                                         cprintf("%s", nl);
1799                                 }
1800                                 else
1801                                 {
1802                                         if ((flags & QP_EADDR) != 0) {
1803                                                 mptr = qp_encode_email_addrs(mptr);
1804                                         }
1805                                         sanitize_truncated_recipient(mptr);
1806                                         cprintf("To: %s", mptr);
1807                                         cprintf("%s", nl);
1808                                 }
1809                         }
1810                         else if (i == 'T') {
1811                                 datestring(datestamp, sizeof datestamp,
1812                                            atol(mptr), DATESTRING_RFC822);
1813                                 cprintf("Date: %s%s", datestamp, nl);
1814                         }
1815                         else if (i == 'W') {
1816                                 cprintf("References: ");
1817                                 k = num_tokens(mptr, '|');
1818                                 for (j=0; j<k; ++j) {
1819                                         extract_token(buf, mptr, j, '|', sizeof buf);
1820                                         cprintf("<%s>", buf);
1821                                         if (j == (k-1)) {
1822                                                 cprintf("%s", nl);
1823                                         }
1824                                         else {
1825                                                 cprintf(" ");
1826                                         }
1827                                 }
1828                         }
1829                         else if (i == eReplyTo) {
1830                                 hptr = mptr;
1831                                 while ((*hptr != '\0') && isspace(*hptr))
1832                                         hptr ++;
1833                                 if (!IsEmptyStr(hptr))
1834                                         cprintf("Reply-To: %s%s", mptr, nl);
1835                         }
1836                         if (mptr != mpptr)
1837                                 free (mptr);
1838                 }
1839         }
1840         if (subject_found == 0) {
1841                 cprintf("Subject: (no subject)%s", nl);
1842         }
1843 }
1844
1845
1846 void Dump_RFC822HeadersBody(
1847         struct CtdlMessage *TheMessage,
1848         int headers_only,       /* eschew the message body? */
1849         int flags,              /* should the bessage be exported clean? */
1850
1851         const char *nl)
1852 {
1853         cit_uint8_t prev_ch;
1854         int eoh = 0;
1855         const char *StartOfText = StrBufNOTNULL;
1856         char outbuf[1024];
1857         int outlen = 0;
1858         int nllen = strlen(nl);
1859         char *mptr;
1860
1861         mptr = TheMessage->cm_fields[eMesageText];
1862
1863
1864         prev_ch = '\0';
1865         while (*mptr != '\0') {
1866                 if (*mptr == '\r') {
1867                         /* do nothing */
1868                 }
1869                 else {
1870                         if ((!eoh) &&
1871                             (*mptr == '\n'))
1872                         {
1873                                 eoh = (*(mptr+1) == '\r') && (*(mptr+2) == '\n');
1874                                 if (!eoh)
1875                                         eoh = *(mptr+1) == '\n';
1876                                 if (eoh)
1877                                 {
1878                                         StartOfText = mptr;
1879                                         StartOfText = strchr(StartOfText, '\n');
1880                                         StartOfText = strchr(StartOfText, '\n');
1881                                 }
1882                         }
1883                         if (((headers_only == HEADERS_NONE) && (mptr >= StartOfText)) ||
1884                             ((headers_only == HEADERS_ONLY) && (mptr < StartOfText)) ||
1885                             ((headers_only != HEADERS_NONE) && 
1886                              (headers_only != HEADERS_ONLY))
1887                                 ) {
1888                                 if (*mptr == '\n') {
1889                                         memcpy(&outbuf[outlen], nl, nllen);
1890                                         outlen += nllen;
1891                                         outbuf[outlen] = '\0';
1892                                 }
1893                                 else {
1894                                         outbuf[outlen++] = *mptr;
1895                                 }
1896                         }
1897                 }
1898                 if (flags & ESC_DOT)
1899                 {
1900                         if ((prev_ch == '\n') && 
1901                             (*mptr == '.') && 
1902                             ((*(mptr+1) == '\r') || (*(mptr+1) == '\n')))
1903                         {
1904                                 outbuf[outlen++] = '.';
1905                         }
1906                         prev_ch = *mptr;
1907                 }
1908                 ++mptr;
1909                 if (outlen > 1000) {
1910                         if (client_write(outbuf, outlen) == -1)
1911                         {
1912                                 struct CitContext *CCC = CC;
1913                                 MSGM_syslog(LOG_ERR, "Dump_RFC822HeadersBody(): aborting due to write failure.\n");
1914                                 return;
1915                         }
1916                         outlen = 0;
1917                 }
1918         }
1919         if (outlen > 0) {
1920                 client_write(outbuf, outlen);
1921         }
1922 }
1923
1924
1925
1926 /* If the format type on disk is 1 (fixed-format), then we want
1927  * everything to be output completely literally ... regardless of
1928  * what message transfer format is in use.
1929  */
1930 void DumpFormatFixed(
1931         struct CtdlMessage *TheMessage,
1932         int mode,               /* how would you like that message? */
1933         const char *nl)
1934 {
1935         cit_uint8_t ch;
1936         char buf[SIZ];
1937         int buflen;
1938         int xlline = 0;
1939         int nllen = strlen (nl);
1940         char *mptr;
1941
1942         mptr = TheMessage->cm_fields[eMesageText];
1943         
1944         if (mode == MT_MIME) {
1945                 cprintf("Content-type: text/plain\n\n");
1946         }
1947         *buf = '\0';
1948         buflen = 0;
1949         while (ch = *mptr++, ch > 0) {
1950                 if (ch == '\n')
1951                         ch = '\r';
1952
1953                 if ((buflen > 250) && (!xlline)){
1954                         int tbuflen;
1955                         tbuflen = buflen;
1956
1957                         while ((buflen > 0) && 
1958                                (!isspace(buf[buflen])))
1959                                 buflen --;
1960                         if (buflen == 0) {
1961                                 xlline = 1;
1962                         }
1963                         else {
1964                                 mptr -= tbuflen - buflen;
1965                                 buf[buflen] = '\0';
1966                                 ch = '\r';
1967                         }
1968                 }
1969                 /* if we reach the outer bounds of our buffer, 
1970                    abort without respect what whe purge. */
1971                 if (xlline && 
1972                     ((isspace(ch)) || 
1973                      (buflen > SIZ - nllen - 2)))
1974                         ch = '\r';
1975
1976                 if (ch == '\r') {
1977                         memcpy (&buf[buflen], nl, nllen);
1978                         buflen += nllen;
1979                         buf[buflen] = '\0';
1980
1981                         if (client_write(buf, buflen) == -1)
1982                         {
1983                                 struct CitContext *CCC = CC;
1984                                 MSGM_syslog(LOG_ERR, "DumpFormatFixed(): aborting due to write failure.\n");
1985                                 return;
1986                         }
1987                         *buf = '\0';
1988                         buflen = 0;
1989                         xlline = 0;
1990                 } else {
1991                         buf[buflen] = ch;
1992                         buflen++;
1993                 }
1994         }
1995         buf[buflen] = '\0';
1996         if (!IsEmptyStr(buf))
1997                 cprintf("%s%s", buf, nl);
1998 }
1999
2000 /*
2001  * Get a message off disk.  (returns om_* values found in msgbase.h)
2002  */
2003 int CtdlOutputPreLoadedMsg(
2004                 struct CtdlMessage *TheMessage,
2005                 int mode,               /* how would you like that message? */
2006                 int headers_only,       /* eschew the message body? */
2007                 int do_proto,           /* do Citadel protocol responses? */
2008                 int crlf,               /* Use CRLF newlines instead of LF? */
2009                 int flags               /* should the bessage be exported clean? */
2010 ) {
2011         struct CitContext *CCC = CC;
2012         int i;
2013         const char *nl; /* newline string */
2014         struct ma_info ma;
2015
2016         /* Buffers needed for RFC822 translation.  These are all filled
2017          * using functions that are bounds-checked, and therefore we can
2018          * make them substantially smaller than SIZ.
2019          */
2020         char suser[100];
2021         char luser[100];
2022         char fuser[100];
2023         char snode[100];
2024         char mid[100];
2025
2026         MSG_syslog(LOG_DEBUG, "CtdlOutputPreLoadedMsg(TheMessage=%s, %d, %d, %d, %d\n",
2027                    ((TheMessage == NULL) ? "NULL" : "not null"),
2028                    mode, headers_only, do_proto, crlf);
2029
2030         strcpy(mid, "unknown");
2031         nl = (crlf ? "\r\n" : "\n");
2032
2033         if (!CM_IsValidMsg(TheMessage)) {
2034                 MSGM_syslog(LOG_ERR,
2035                             "ERROR: invalid preloaded message for output\n");
2036                 cit_backtrace ();
2037                 return(om_no_such_msg);
2038         }
2039
2040         /* Suppress envelope recipients if required to avoid disclosing BCC addresses.
2041          * Pad it with spaces in order to avoid changing the RFC822 length of the message.
2042          */
2043         if ( (flags & SUPPRESS_ENV_TO) && (!CM_IsEmpty(TheMessage, eenVelopeTo)) ) {
2044                 memset(TheMessage->cm_fields[eenVelopeTo], ' ', TheMessage->cm_lengths[eenVelopeTo]);
2045         }
2046                 
2047         /* Are we downloading a MIME component? */
2048         if (mode == MT_DOWNLOAD) {
2049                 if (TheMessage->cm_format_type != FMT_RFC822) {
2050                         if (do_proto)
2051                                 cprintf("%d This is not a MIME message.\n",
2052                                 ERROR + ILLEGAL_VALUE);
2053                 } else if (CCC->download_fp != NULL) {
2054                         if (do_proto) cprintf(
2055                                 "%d You already have a download open.\n",
2056                                 ERROR + RESOURCE_BUSY);
2057                 } else {
2058                         /* Parse the message text component */
2059                         mime_parser(CM_RANGE(TheMessage, eMesageText),
2060                                     *mime_download, NULL, NULL, NULL, 0);
2061                         /* If there's no file open by this time, the requested
2062                          * section wasn't found, so print an error
2063                          */
2064                         if (CCC->download_fp == NULL) {
2065                                 if (do_proto) cprintf(
2066                                         "%d Section %s not found.\n",
2067                                         ERROR + FILE_NOT_FOUND,
2068                                         CCC->download_desired_section);
2069                         }
2070                 }
2071                 return((CCC->download_fp != NULL) ? om_ok : om_mime_error);
2072         }
2073
2074         /* MT_SPEW_SECTION is like MT_DOWNLOAD except it outputs the whole MIME part
2075          * in a single server operation instead of opening a download file.
2076          */
2077         if (mode == MT_SPEW_SECTION) {
2078                 if (TheMessage->cm_format_type != FMT_RFC822) {
2079                         if (do_proto)
2080                                 cprintf("%d This is not a MIME message.\n",
2081                                 ERROR + ILLEGAL_VALUE);
2082                 } else {
2083                         /* Parse the message text component */
2084                         int found_it = 0;
2085
2086                         mime_parser(CM_RANGE(TheMessage, eMesageText),
2087                                     *mime_spew_section, NULL, NULL, (void *)&found_it, 0);
2088                         /* If section wasn't found, print an error
2089                          */
2090                         if (!found_it) {
2091                                 if (do_proto) cprintf(
2092                                         "%d Section %s not found.\n",
2093                                         ERROR + FILE_NOT_FOUND,
2094                                         CCC->download_desired_section);
2095                         }
2096                 }
2097                 return((CCC->download_fp != NULL) ? om_ok : om_mime_error);
2098         }
2099
2100         /* now for the user-mode message reading loops */
2101         if (do_proto) cprintf("%d msg:\n", LISTING_FOLLOWS);
2102
2103         /* Does the caller want to skip the headers? */
2104         if (headers_only == HEADERS_NONE) goto START_TEXT;
2105
2106         /* Tell the client which format type we're using. */
2107         if ( (mode == MT_CITADEL) && (do_proto) ) {
2108                 cprintf("type=%d\n", TheMessage->cm_format_type);
2109         }
2110
2111         /* nhdr=yes means that we're only displaying headers, no body */
2112         if ( (TheMessage->cm_anon_type == MES_ANONONLY)
2113            && ((mode == MT_CITADEL) || (mode == MT_MIME))
2114            && (do_proto)
2115            ) {
2116                 cprintf("nhdr=yes\n");
2117         }
2118
2119         if ((mode == MT_CITADEL) || (mode == MT_MIME)) 
2120                 OutputCtdlMsgHeaders(TheMessage, do_proto);
2121
2122
2123         /* begin header processing loop for RFC822 transfer format */
2124         strcpy(suser, "");
2125         strcpy(luser, "");
2126         strcpy(fuser, "");
2127         memcpy(snode, CFG_KEY(c_nodename) + 1);
2128         if (mode == MT_RFC822) 
2129                 OutputRFC822MsgHeaders(
2130                         TheMessage,
2131                         flags,
2132                         nl,
2133                         mid, sizeof(mid),
2134                         suser, sizeof(suser),
2135                         luser, sizeof(luser),
2136                         fuser, sizeof(fuser),
2137                         snode, sizeof(snode)
2138                         );
2139
2140
2141         for (i=0; !IsEmptyStr(&suser[i]); ++i) {
2142                 suser[i] = tolower(suser[i]);
2143                 if (!isalnum(suser[i])) suser[i]='_';
2144         }
2145
2146         if (mode == MT_RFC822) {
2147                 if (!strcasecmp(snode, NODENAME)) {
2148                         safestrncpy(snode, FQDN, sizeof snode);
2149                 }
2150
2151                 /* Construct a fun message id */
2152                 cprintf("Message-ID: <%s", mid);/// todo: this possibly breaks threadding mails.
2153                 if (strchr(mid, '@')==NULL) {
2154                         cprintf("@%s", snode);
2155                 }
2156                 cprintf(">%s", nl);
2157
2158                 if (!is_room_aide() && (TheMessage->cm_anon_type == MES_ANONONLY)) {
2159                         cprintf("From: \"----\" <x@x.org>%s", nl);
2160                 }
2161                 else if (!is_room_aide() && (TheMessage->cm_anon_type == MES_ANONOPT)) {
2162                         cprintf("From: \"anonymous\" <x@x.org>%s", nl);
2163                 }
2164                 else if (!IsEmptyStr(fuser)) {
2165                         cprintf("From: \"%s\" <%s>%s", luser, fuser, nl);
2166                 }
2167                 else {
2168                         cprintf("From: \"%s\" <%s@%s>%s", luser, suser, snode, nl);
2169                 }
2170
2171                 /* Blank line signifying RFC822 end-of-headers */
2172                 if (TheMessage->cm_format_type != FMT_RFC822) {
2173                         cprintf("%s", nl);
2174                 }
2175         }
2176
2177         /* end header processing loop ... at this point, we're in the text */
2178 START_TEXT:
2179         if (headers_only == HEADERS_FAST) goto DONE;
2180
2181         /* Tell the client about the MIME parts in this message */
2182         if (TheMessage->cm_format_type == FMT_RFC822) {
2183                 if ( (mode == MT_CITADEL) || (mode == MT_MIME) ) {
2184                         memset(&ma, 0, sizeof(struct ma_info));
2185                         mime_parser(CM_RANGE(TheMessage, eMesageText),
2186                                 (do_proto ? *list_this_part : NULL),
2187                                 (do_proto ? *list_this_pref : NULL),
2188                                 (do_proto ? *list_this_suff : NULL),
2189                                 (void *)&ma, 1);
2190                 }
2191                 else if (mode == MT_RFC822) {   /* unparsed RFC822 dump */
2192                         Dump_RFC822HeadersBody(
2193                                 TheMessage,
2194                                 headers_only,
2195                                 flags,
2196                                 nl);
2197                         goto DONE;
2198                 }
2199         }
2200
2201         if (headers_only == HEADERS_ONLY) {
2202                 goto DONE;
2203         }
2204
2205         /* signify start of msg text */
2206         if ( (mode == MT_CITADEL) || (mode == MT_MIME) ) {
2207                 if (do_proto) cprintf("text\n");
2208         }
2209
2210         if (TheMessage->cm_format_type == FMT_FIXED) 
2211                 DumpFormatFixed(
2212                         TheMessage,
2213                         mode,           /* how would you like that message? */
2214                         nl);
2215
2216         /* If the message on disk is format 0 (Citadel vari-format), we
2217          * output using the formatter at 80 columns.  This is the final output
2218          * form if the transfer format is RFC822, but if the transfer format
2219          * is Citadel proprietary, it'll still work, because the indentation
2220          * for new paragraphs is correct and the client will reformat the
2221          * message to the reader's screen width.
2222          */
2223         if (TheMessage->cm_format_type == FMT_CITADEL) {
2224                 if (mode == MT_MIME) {
2225                         cprintf("Content-type: text/x-citadel-variformat\n\n");
2226                 }
2227                 memfmout(TheMessage->cm_fields[eMesageText], nl);
2228         }
2229
2230         /* If the message on disk is format 4 (MIME), we've gotta hand it
2231          * off to the MIME parser.  The client has already been told that
2232          * this message is format 1 (fixed format), so the callback function
2233          * we use will display those parts as-is.
2234          */
2235         if (TheMessage->cm_format_type == FMT_RFC822) {
2236                 memset(&ma, 0, sizeof(struct ma_info));
2237
2238                 if (mode == MT_MIME) {
2239                         ma.use_fo_hooks = 0;
2240                         strcpy(ma.chosen_part, "1");
2241                         ma.chosen_pref = 9999;
2242                         ma.dont_decode = CCC->msg4_dont_decode;
2243                         mime_parser(CM_RANGE(TheMessage, eMesageText),
2244                                     *choose_preferred, *fixed_output_pre,
2245                                     *fixed_output_post, (void *)&ma, 1);
2246                         mime_parser(CM_RANGE(TheMessage, eMesageText),
2247                                     *output_preferred, NULL, NULL, (void *)&ma, 1);
2248                 }
2249                 else {
2250                         ma.use_fo_hooks = 1;
2251                         mime_parser(CM_RANGE(TheMessage, eMesageText),
2252                                     *fixed_output, *fixed_output_pre,
2253                                     *fixed_output_post, (void *)&ma, 0);
2254                 }
2255
2256         }
2257
2258 DONE:   /* now we're done */
2259         if (do_proto) cprintf("000\n");
2260         return(om_ok);
2261 }
2262
2263 /*
2264  * Save one or more message pointers into a specified room
2265  * (Returns 0 for success, nonzero for failure)
2266  * roomname may be NULL to use the current room
2267  *
2268  * Note that the 'supplied_msg' field may be set to NULL, in which case
2269  * the message will be fetched from disk, by number, if we need to perform
2270  * replication checks.  This adds an additional database read, so if the
2271  * caller already has the message in memory then it should be supplied.  (Obviously
2272  * this mode of operation only works if we're saving a single message.)
2273  */
2274 int CtdlSaveMsgPointersInRoom(char *roomname, long newmsgidlist[], int num_newmsgs,
2275                         int do_repl_check, struct CtdlMessage *supplied_msg, int suppress_refcount_adj
2276 ) {
2277         struct CitContext *CCC = CC;
2278         int i, j, unique;
2279         char hold_rm[ROOMNAMELEN];
2280         struct cdbdata *cdbfr;
2281         int num_msgs;
2282         long *msglist;
2283         long highest_msg = 0L;
2284
2285         long msgid = 0;
2286         struct CtdlMessage *msg = NULL;
2287
2288         long *msgs_to_be_merged = NULL;
2289         int num_msgs_to_be_merged = 0;
2290
2291         MSG_syslog(LOG_DEBUG,
2292                    "CtdlSaveMsgPointersInRoom(room=%s, num_msgs=%d, repl=%d, suppress_rca=%d)\n",
2293                    roomname, num_newmsgs, do_repl_check, suppress_refcount_adj
2294         );
2295
2296         strcpy(hold_rm, CCC->room.QRname);
2297
2298         /* Sanity checks */
2299         if (newmsgidlist == NULL) return(ERROR + INTERNAL_ERROR);
2300         if (num_newmsgs < 1) return(ERROR + INTERNAL_ERROR);
2301         if (num_newmsgs > 1) supplied_msg = NULL;
2302
2303         /* Now the regular stuff */
2304         if (CtdlGetRoomLock(&CCC->room,
2305            ((roomname != NULL) ? roomname : CCC->room.QRname) )
2306            != 0) {
2307                 MSG_syslog(LOG_ERR, "No such room <%s>\n", roomname);
2308                 return(ERROR + ROOM_NOT_FOUND);
2309         }
2310
2311
2312         msgs_to_be_merged = malloc(sizeof(long) * num_newmsgs);
2313         num_msgs_to_be_merged = 0;
2314
2315
2316         cdbfr = cdb_fetch(CDB_MSGLISTS, &CCC->room.QRnumber, sizeof(long));
2317         if (cdbfr == NULL) {
2318                 msglist = NULL;
2319                 num_msgs = 0;
2320         } else {
2321                 msglist = (long *) cdbfr->ptr;
2322                 cdbfr->ptr = NULL;      /* CtdlSaveMsgPointerInRoom() now owns this memory */
2323                 num_msgs = cdbfr->len / sizeof(long);
2324                 cdb_free(cdbfr);
2325         }
2326
2327
2328         /* Create a list of msgid's which were supplied by the caller, but do
2329          * not already exist in the target room.  It is absolutely taboo to
2330          * have more than one reference to the same message in a room.
2331          */
2332         for (i=0; i<num_newmsgs; ++i) {
2333                 unique = 1;
2334                 if (num_msgs > 0) for (j=0; j<num_msgs; ++j) {
2335                         if (msglist[j] == newmsgidlist[i]) {
2336                                 unique = 0;
2337                         }
2338                 }
2339                 if (unique) {
2340                         msgs_to_be_merged[num_msgs_to_be_merged++] = newmsgidlist[i];
2341                 }
2342         }
2343
2344         MSG_syslog(LOG_DEBUG, "%d unique messages to be merged\n", num_msgs_to_be_merged);
2345
2346         /*
2347          * Now merge the new messages
2348          */
2349         msglist = realloc(msglist, (sizeof(long) * (num_msgs + num_msgs_to_be_merged)) );
2350         if (msglist == NULL) {
2351                 MSGM_syslog(LOG_ALERT, "ERROR: can't realloc message list!\n");
2352                 free(msgs_to_be_merged);
2353                 return (ERROR + INTERNAL_ERROR);
2354         }
2355         memcpy(&msglist[num_msgs], msgs_to_be_merged, (sizeof(long) * num_msgs_to_be_merged) );
2356         num_msgs += num_msgs_to_be_merged;
2357
2358         /* Sort the message list, so all the msgid's are in order */
2359         num_msgs = sort_msglist(msglist, num_msgs);
2360
2361         /* Determine the highest message number */
2362         highest_msg = msglist[num_msgs - 1];
2363
2364         /* Write it back to disk. */
2365         cdb_store(CDB_MSGLISTS, &CCC->room.QRnumber, (int)sizeof(long),
2366                   msglist, (int)(num_msgs * sizeof(long)));
2367
2368         /* Free up the memory we used. */
2369         free(msglist);
2370
2371         /* Update the highest-message pointer and unlock the room. */
2372         CCC->room.QRhighest = highest_msg;
2373         CtdlPutRoomLock(&CCC->room);
2374
2375         /* Perform replication checks if necessary */
2376         if ( (DoesThisRoomNeedEuidIndexing(&CCC->room)) && (do_repl_check) ) {
2377                 MSGM_syslog(LOG_DEBUG, "CtdlSaveMsgPointerInRoom() doing repl checks\n");
2378
2379                 for (i=0; i<num_msgs_to_be_merged; ++i) {
2380                         msgid = msgs_to_be_merged[i];
2381         
2382                         if (supplied_msg != NULL) {
2383                                 msg = supplied_msg;
2384                         }
2385                         else {
2386                                 msg = CtdlFetchMessage(msgid, 0);
2387                         }
2388         
2389                         if (msg != NULL) {
2390                                 ReplicationChecks(msg);
2391                 
2392                                 /* If the message has an Exclusive ID, index that... */
2393                                 if (!CM_IsEmpty(msg, eExclusiveID)) {
2394                                         index_message_by_euid(msg->cm_fields[eExclusiveID], &CCC->room, msgid);
2395                                 }
2396
2397                                 /* Free up the memory we may have allocated */
2398                                 if (msg != supplied_msg) {
2399                                         CM_Free(msg);
2400                                 }
2401                         }
2402         
2403                 }
2404         }
2405
2406         else {
2407                 MSGM_syslog(LOG_DEBUG, "CtdlSaveMsgPointerInRoom() skips repl checks\n");
2408         }
2409
2410         /* Submit this room for processing by hooks */
2411         PerformRoomHooks(&CCC->room);
2412
2413         /* Go back to the room we were in before we wandered here... */
2414         CtdlGetRoom(&CCC->room, hold_rm);
2415
2416         /* Bump the reference count for all messages which were merged */
2417         if (!suppress_refcount_adj) {
2418                 AdjRefCountList(msgs_to_be_merged, num_msgs_to_be_merged, +1);
2419         }
2420
2421         /* Free up memory... */
2422         if (msgs_to_be_merged != NULL) {
2423                 free(msgs_to_be_merged);
2424         }
2425
2426         /* Return success. */
2427         return (0);
2428 }
2429
2430
2431 /*
2432  * This is the same as CtdlSaveMsgPointersInRoom() but it only accepts
2433  * a single message.
2434  */
2435 int CtdlSaveMsgPointerInRoom(char *roomname, long msgid,
2436                              int do_repl_check, struct CtdlMessage *supplied_msg)
2437 {
2438         return CtdlSaveMsgPointersInRoom(roomname, &msgid, 1, do_repl_check, supplied_msg, 0);
2439 }
2440
2441
2442
2443
2444 /*
2445  * Message base operation to save a new message to the message store
2446  * (returns new message number)
2447  *
2448  * This is the back end for CtdlSubmitMsg() and should not be directly
2449  * called by server-side modules.
2450  *
2451  */
2452 long send_message(struct CtdlMessage *msg) {
2453         struct CitContext *CCC = CC;
2454         long newmsgid;
2455         long retval;
2456         char msgidbuf[256];
2457         long msgidbuflen;
2458         struct ser_ret smr;
2459         int is_bigmsg = 0;
2460         char *holdM = NULL;
2461         long holdMLen = 0;
2462
2463         /* Get a new message number */
2464         newmsgid = get_new_message_number();
2465         msgidbuflen = snprintf(msgidbuf, sizeof msgidbuf, "%08lX-%08lX@%s",
2466                                (long unsigned int) time(NULL),
2467                                (long unsigned int) newmsgid,
2468                                config.c_fqdn
2469                 );
2470
2471         /* Generate an ID if we don't have one already */
2472         if (CM_IsEmpty(msg, emessageId)) {
2473                 CM_SetField(msg, emessageId, msgidbuf, msgidbuflen);
2474         }
2475
2476         /* If the message is big, set its body aside for storage elsewhere */
2477         if (!CM_IsEmpty(msg, eMesageText)) {
2478                 if (msg->cm_lengths[eMesageText] > BIGMSG) {
2479                         is_bigmsg = 1;
2480                         holdM = msg->cm_fields[eMesageText];
2481                         msg->cm_fields[eMesageText] = NULL;
2482                         holdMLen = msg->cm_lengths[eMesageText];
2483                         msg->cm_lengths[eMesageText] = 0;
2484                 }
2485         }
2486
2487         /* Serialize our data structure for storage in the database */  
2488         CtdlSerializeMessage(&smr, msg);
2489
2490         if (is_bigmsg) {
2491                 msg->cm_fields[eMesageText] = holdM;
2492                 msg->cm_lengths[eMesageText] = holdMLen;
2493         }
2494
2495         if (smr.len == 0) {
2496                 cprintf("%d Unable to serialize message\n",
2497                         ERROR + INTERNAL_ERROR);
2498                 return (-1L);
2499         }
2500
2501         /* Write our little bundle of joy into the message base */
2502         if (cdb_store(CDB_MSGMAIN, &newmsgid, (int)sizeof(long),
2503                       smr.ser, smr.len) < 0) {
2504                 MSGM_syslog(LOG_ERR, "Can't store message\n");
2505                 retval = 0L;
2506         } else {
2507                 if (is_bigmsg) {
2508                         cdb_store(CDB_BIGMSGS,
2509                                   &newmsgid,
2510                                   (int)sizeof(long),
2511                                   holdM,
2512                                   (holdMLen + 1)
2513                                 );
2514                 }
2515                 retval = newmsgid;
2516         }
2517
2518         /* Free the memory we used for the serialized message */
2519         free(smr.ser);
2520
2521         /* Return the *local* message ID to the caller
2522          * (even if we're storing an incoming network message)
2523          */
2524         return(retval);
2525 }
2526
2527
2528
2529 /*
2530  * Serialize a struct CtdlMessage into the format used on disk and network.
2531  * 
2532  * This function loads up a "struct ser_ret" (defined in server.h) which
2533  * contains the length of the serialized message and a pointer to the
2534  * serialized message in memory.  THE LATTER MUST BE FREED BY THE CALLER.
2535  */
2536 void CtdlSerializeMessage(struct ser_ret *ret,          /* return values */
2537                        struct CtdlMessage *msg) /* unserialized msg */
2538 {
2539         struct CitContext *CCC = CC;
2540         size_t wlen;
2541         int i;
2542
2543         /*
2544          * Check for valid message format
2545          */
2546         if (CM_IsValidMsg(msg) == 0) {
2547                 MSGM_syslog(LOG_ERR, "CtdlSerializeMessage() aborting due to invalid message\n");
2548                 ret->len = 0;
2549                 ret->ser = NULL;
2550                 return;
2551         }
2552
2553         ret->len = 3;
2554         for (i=0; i < NDiskFields; ++i)
2555                 if (msg->cm_fields[FieldOrder[i]] != NULL)
2556                         ret->len += msg->cm_lengths[FieldOrder[i]] + 2;
2557
2558         ret->ser = malloc(ret->len);
2559         if (ret->ser == NULL) {
2560                 MSG_syslog(LOG_ERR, "CtdlSerializeMessage() malloc(%ld) failed: %s\n",
2561                            (long)ret->len, strerror(errno));
2562                 ret->len = 0;
2563                 ret->ser = NULL;
2564                 return;
2565         }
2566
2567         ret->ser[0] = 0xFF;
2568         ret->ser[1] = msg->cm_anon_type;
2569         ret->ser[2] = msg->cm_format_type;
2570         wlen = 3;
2571
2572         for (i=0; i < NDiskFields; ++i)
2573                 if (msg->cm_fields[FieldOrder[i]] != NULL)
2574                 {
2575                         ret->ser[wlen++] = (char)FieldOrder[i];
2576
2577                         memcpy(&ret->ser[wlen],
2578                                msg->cm_fields[FieldOrder[i]],
2579                                msg->cm_lengths[FieldOrder[i]] + 1);
2580
2581                         wlen = wlen + msg->cm_lengths[FieldOrder[i]] + 1;
2582                 }
2583
2584         if (ret->len != wlen) {
2585                 MSG_syslog(LOG_ERR, "ERROR: len=%ld wlen=%ld\n",
2586                            (long)ret->len, (long)wlen);
2587         }
2588
2589         return;
2590 }
2591
2592
2593 /*
2594  * Check to see if any messages already exist in the current room which
2595  * carry the same Exclusive ID as this one.  If any are found, delete them.
2596  */
2597 void ReplicationChecks(struct CtdlMessage *msg) {
2598         struct CitContext *CCC = CC;
2599         long old_msgnum = (-1L);
2600
2601         if (DoesThisRoomNeedEuidIndexing(&CCC->room) == 0) return;
2602
2603         MSG_syslog(LOG_DEBUG, "Performing replication checks in <%s>\n",
2604                    CCC->room.QRname);
2605
2606         /* No exclusive id?  Don't do anything. */
2607         if (msg == NULL) return;
2608         if (CM_IsEmpty(msg, eExclusiveID)) return;
2609
2610         /*MSG_syslog(LOG_DEBUG, "Exclusive ID: <%s> for room <%s>\n",
2611           msg->cm_fields[eExclusiveID], CCC->room.QRname);*/
2612
2613         old_msgnum = CtdlLocateMessageByEuid(msg->cm_fields[eExclusiveID], &CCC->room);
2614         if (old_msgnum > 0L) {
2615                 MSG_syslog(LOG_DEBUG, "ReplicationChecks() replacing message %ld\n", old_msgnum);
2616                 CtdlDeleteMessages(CCC->room.QRname, &old_msgnum, 1, "");
2617         }
2618 }
2619
2620
2621
2622 /*
2623  * Save a message to disk and submit it into the delivery system.
2624  */
2625 long CtdlSubmitMsg(struct CtdlMessage *msg,     /* message to save */
2626                    recptypes *recps,            /* recipients (if mail) */
2627                    const char *force,           /* force a particular room? */
2628                    int flags                    /* should the message be exported clean? */
2629         )
2630 {
2631         char hold_rm[ROOMNAMELEN];
2632         char actual_rm[ROOMNAMELEN];
2633         char force_room[ROOMNAMELEN];
2634         char content_type[SIZ];                 /* We have to learn this */
2635         char recipient[SIZ];
2636         char bounce_to[1024];
2637         const char *room;
2638         long newmsgid;
2639         const char *mptr = NULL;
2640         struct ctdluser userbuf;
2641         int a, i;
2642         struct MetaData smi;
2643         char *collected_addresses = NULL;
2644         struct addresses_to_be_filed *aptr = NULL;
2645         StrBuf *saved_rfc822_version = NULL;
2646         int qualified_for_journaling = 0;
2647         CitContext *CCC = MyContext();
2648
2649         MSGM_syslog(LOG_DEBUG, "CtdlSubmitMsg() called\n");
2650         if (CM_IsValidMsg(msg) == 0) return(-1);        /* self check */
2651
2652         /* If this message has no timestamp, we take the liberty of
2653          * giving it one, right now.
2654          */
2655         if (CM_IsEmpty(msg, eTimestamp)) {
2656                 CM_SetFieldLONG(msg, eTimestamp, time(NULL));
2657         }
2658
2659         /* If this message has no path, we generate one.
2660          */
2661         if (CM_IsEmpty(msg, eMessagePath)) {
2662                 if (!CM_IsEmpty(msg, eAuthor)) {
2663                         CM_CopyField(msg, eMessagePath, eAuthor);
2664                         for (a=0; !IsEmptyStr(&msg->cm_fields[eMessagePath][a]); ++a) {
2665                                 if (isspace(msg->cm_fields[eMessagePath][a])) {
2666                                         msg->cm_fields[eMessagePath][a] = ' ';
2667                                 }
2668                         }
2669                 }
2670                 else {
2671                         CM_SetField(msg, eMessagePath, HKEY("unknown"));
2672                 }
2673         }
2674
2675         if (force == NULL) {
2676                 force_room[0] = '\0';
2677         }
2678         else {
2679                 strcpy(force_room, force);
2680         }
2681
2682         /* Learn about what's inside, because it's what's inside that counts */
2683         if (CM_IsEmpty(msg, eMesageText)) {
2684                 MSGM_syslog(LOG_ERR, "ERROR: attempt to save message with NULL body\n");
2685                 return(-2);
2686         }
2687
2688         switch (msg->cm_format_type) {
2689         case 0:
2690                 strcpy(content_type, "text/x-citadel-variformat");
2691                 break;
2692         case 1:
2693                 strcpy(content_type, "text/plain");
2694                 break;
2695         case 4:
2696                 strcpy(content_type, "text/plain");
2697                 mptr = bmstrcasestr(msg->cm_fields[eMesageText], "Content-type:");
2698                 if (mptr != NULL) {
2699                         char *aptr;
2700                         safestrncpy(content_type, &mptr[13], sizeof content_type);
2701                         striplt(content_type);
2702                         aptr = content_type;
2703                         while (!IsEmptyStr(aptr)) {
2704                                 if ((*aptr == ';')
2705                                     || (*aptr == ' ')
2706                                     || (*aptr == 13)
2707                                     || (*aptr == 10)) {
2708                                         *aptr = 0;
2709                                 }
2710                                 else aptr++;
2711                         }
2712                 }
2713         }
2714
2715         /* Goto the correct room */
2716         room = (recps) ? CCC->room.QRname : SENTITEMS;
2717         MSG_syslog(LOG_DEBUG, "Selected room %s\n", room);
2718         strcpy(hold_rm, CCC->room.QRname);
2719         strcpy(actual_rm, CCC->room.QRname);
2720         if (recps != NULL) {
2721                 strcpy(actual_rm, SENTITEMS);
2722         }
2723
2724         /* If the user is a twit, move to the twit room for posting */
2725         if (TWITDETECT) {
2726                 if (CCC->user.axlevel == AxProbU) {
2727                         strcpy(hold_rm, actual_rm);
2728                         strcpy(actual_rm, config.c_twitroom);
2729                         MSGM_syslog(LOG_DEBUG, "Diverting to twit room\n");
2730                 }
2731         }
2732
2733         /* ...or if this message is destined for Aide> then go there. */
2734         if (!IsEmptyStr(force_room)) {
2735                 strcpy(actual_rm, force_room);
2736         }
2737
2738         MSG_syslog(LOG_INFO, "Final selection: %s (%s)\n", actual_rm, room);
2739         if (strcasecmp(actual_rm, CCC->room.QRname)) {
2740                 /* CtdlGetRoom(&CCC->room, actual_rm); */
2741                 CtdlUserGoto(actual_rm, 0, 1, NULL, NULL);
2742         }
2743
2744         /*
2745          * If this message has no O (room) field, generate one.
2746          */
2747         if (CM_IsEmpty(msg, eOriginalRoom)) {
2748                 CM_SetField(msg, eOriginalRoom, CCC->room.QRname, strlen(CCC->room.QRname));
2749         }
2750
2751         /* Perform "before save" hooks (aborting if any return nonzero) */
2752         MSGM_syslog(LOG_DEBUG, "Performing before-save hooks\n");
2753         if (PerformMessageHooks(msg, recps, EVT_BEFORESAVE) > 0) return(-3);
2754
2755         /*
2756          * If this message has an Exclusive ID, and the room is replication
2757          * checking enabled, then do replication checks.
2758          */
2759         if (DoesThisRoomNeedEuidIndexing(&CCC->room)) {
2760                 ReplicationChecks(msg);
2761         }
2762
2763         /* Save it to disk */
2764         MSGM_syslog(LOG_DEBUG, "Saving to disk\n");
2765         newmsgid = send_message(msg);
2766         if (newmsgid <= 0L) return(-5);
2767
2768         /* Write a supplemental message info record.  This doesn't have to
2769          * be a critical section because nobody else knows about this message
2770          * yet.
2771          */
2772         MSGM_syslog(LOG_DEBUG, "Creating MetaData record\n");
2773         memset(&smi, 0, sizeof(struct MetaData));
2774         smi.meta_msgnum = newmsgid;
2775         smi.meta_refcount = 0;
2776         safestrncpy(smi.meta_content_type, content_type,
2777                     sizeof smi.meta_content_type);
2778
2779         /*
2780          * Measure how big this message will be when rendered as RFC822.
2781          * We do this for two reasons:
2782          * 1. We need the RFC822 length for the new metadata record, so the
2783          *    POP and IMAP services don't have to calculate message lengths
2784          *    while the user is waiting (multiplied by potentially hundreds
2785          *    or thousands of messages).
2786          * 2. If journaling is enabled, we will need an RFC822 version of the
2787          *    message to attach to the journalized copy.
2788          */
2789         if (CCC->redirect_buffer != NULL) {
2790                 MSGM_syslog(LOG_ALERT, "CCC->redirect_buffer is not NULL during message submission!\n");
2791                 abort();
2792         }
2793         CCC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
2794         CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_ALL, 0, 1, QP_EADDR);
2795         smi.meta_rfc822_length = StrLength(CCC->redirect_buffer);
2796         saved_rfc822_version = CCC->redirect_buffer;
2797         CCC->redirect_buffer = NULL;
2798
2799         PutMetaData(&smi);
2800
2801         /* Now figure out where to store the pointers */
2802         MSGM_syslog(LOG_DEBUG, "Storing pointers\n");
2803
2804         /* If this is being done by the networker delivering a private
2805          * message, we want to BYPASS saving the sender's copy (because there
2806          * is no local sender; it would otherwise go to the Trashcan).
2807          */
2808         if ((!CCC->internal_pgm) || (recps == NULL)) {
2809                 if (CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 1, msg) != 0) {
2810                         MSGM_syslog(LOG_ERR, "ERROR saving message pointer!\n");
2811                         CtdlSaveMsgPointerInRoom(config.c_aideroom, newmsgid, 0, msg);
2812                 }
2813         }
2814
2815         /* For internet mail, drop a copy in the outbound queue room */
2816         if ((recps != NULL) && (recps->num_internet > 0)) {
2817                 CtdlSaveMsgPointerInRoom(SMTP_SPOOLOUT_ROOM, newmsgid, 0, msg);
2818         }
2819
2820         /* If other rooms are specified, drop them there too. */
2821         if ((recps != NULL) && (recps->num_room > 0))
2822                 for (i=0; i<num_tokens(recps->recp_room, '|'); ++i) {
2823                         extract_token(recipient, recps->recp_room, i,
2824                                       '|', sizeof recipient);
2825                         MSG_syslog(LOG_DEBUG, "Delivering to room <%s>\n", recipient);///// xxxx
2826                         CtdlSaveMsgPointerInRoom(recipient, newmsgid, 0, msg);
2827                 }
2828
2829         /* Bump this user's messages posted counter. */
2830         MSGM_syslog(LOG_DEBUG, "Updating user\n");
2831         CtdlGetUserLock(&CCC->user, CCC->curr_user);
2832         CCC->user.posted = CCC->user.posted + 1;
2833         CtdlPutUserLock(&CCC->user);
2834
2835         /* Decide where bounces need to be delivered */
2836         if ((recps != NULL) && (recps->bounce_to == NULL))
2837         {
2838                 if (CCC->logged_in) 
2839                         snprintf(bounce_to, sizeof bounce_to, "%s@%s",
2840                                  CCC->user.fullname, config.c_nodename);
2841                 else 
2842                         snprintf(bounce_to, sizeof bounce_to, "%s@%s",
2843                                  msg->cm_fields[eAuthor], msg->cm_fields[eNodeName]);
2844                 recps->bounce_to = bounce_to;
2845         }
2846                 
2847         CM_SetFieldLONG(msg, eVltMsgNum, newmsgid);
2848
2849
2850         /* If this is private, local mail, make a copy in the
2851          * recipient's mailbox and bump the reference count.
2852          */
2853         if ((recps != NULL) && (recps->num_local > 0))
2854         {
2855                 char *pch;
2856                 int ntokens;
2857
2858                 pch = recps->recp_local;
2859                 recps->recp_local = recipient;
2860                 ntokens = num_tokens(pch, '|');
2861                 for (i=0; i<ntokens; ++i)
2862                 {
2863                         extract_token(recipient, pch, i, '|', sizeof recipient);
2864                         MSG_syslog(LOG_DEBUG, "Delivering private local mail to <%s>\n", recipient);
2865                         if (CtdlGetUser(&userbuf, recipient) == 0) {
2866                                 CtdlMailboxName(actual_rm, sizeof actual_rm, &userbuf, MAILROOM);
2867                                 CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 0, msg);
2868                                 CtdlBumpNewMailCounter(userbuf.usernum);
2869                                 PerformMessageHooks(msg, recps, EVT_AFTERUSRMBOXSAVE);
2870                         }
2871                         else {
2872                                 MSG_syslog(LOG_DEBUG, "No user <%s>\n", recipient);
2873                                 CtdlSaveMsgPointerInRoom(config.c_aideroom, newmsgid, 0, msg);
2874                         }
2875                 }
2876                 recps->recp_local = pch;
2877         }
2878
2879         /* Perform "after save" hooks */
2880         MSGM_syslog(LOG_DEBUG, "Performing after-save hooks\n");
2881
2882         PerformMessageHooks(msg, recps, EVT_AFTERSAVE);
2883         CM_FlushField(msg, eVltMsgNum);
2884
2885         /* Go back to the room we started from */
2886         MSG_syslog(LOG_DEBUG, "Returning to original room %s\n", hold_rm);
2887         if (strcasecmp(hold_rm, CCC->room.QRname))
2888                 CtdlUserGoto(hold_rm, 0, 1, NULL, NULL);
2889
2890         /*
2891          * Any addresses to harvest for someone's address book?
2892          */
2893         if ( (CCC->logged_in) && (recps != NULL) ) {
2894                 collected_addresses = harvest_collected_addresses(msg);
2895         }
2896
2897         if (collected_addresses != NULL) {
2898                 aptr = (struct addresses_to_be_filed *)
2899                         malloc(sizeof(struct addresses_to_be_filed));
2900                 CtdlMailboxName(actual_rm, sizeof actual_rm,
2901                                 &CCC->user, USERCONTACTSROOM);
2902                 aptr->roomname = strdup(actual_rm);
2903                 aptr->collected_addresses = collected_addresses;
2904                 begin_critical_section(S_ATBF);
2905                 aptr->next = atbf;
2906                 atbf = aptr;
2907                 end_critical_section(S_ATBF);
2908         }
2909
2910         /*
2911          * Determine whether this message qualifies for journaling.
2912          */
2913         if (!CM_IsEmpty(msg, eJournal)) {
2914                 qualified_for_journaling = 0;
2915         }
2916         else {
2917                 if (recps == NULL) {
2918                         qualified_for_journaling = config.c_journal_pubmsgs;
2919                 }
2920                 else if (recps->num_local + recps->num_ignet + recps->num_internet > 0) {
2921                         qualified_for_journaling = config.c_journal_email;
2922                 }
2923                 else {
2924                         qualified_for_journaling = config.c_journal_pubmsgs;
2925                 }
2926         }
2927
2928         /*
2929          * Do we have to perform journaling?  If so, hand off the saved
2930          * RFC822 version will be handed off to the journaler for background
2931          * submit.  Otherwise, we have to free the memory ourselves.
2932          */
2933         if (saved_rfc822_version != NULL) {
2934                 if (qualified_for_journaling) {
2935                         JournalBackgroundSubmit(msg, saved_rfc822_version, recps);
2936                 }
2937                 else {
2938                         FreeStrBuf(&saved_rfc822_version);
2939                 }
2940         }
2941
2942         if ((recps != NULL) && (recps->bounce_to == bounce_to))
2943                 recps->bounce_to = NULL;
2944
2945         /* Done. */
2946         return(newmsgid);
2947 }
2948
2949
2950 /*
2951  * Convenience function for generating small administrative messages.
2952  */
2953 void quickie_message(const char *from,
2954                      const char *fromaddr,
2955                      const char *to,
2956                      char *room,
2957                      const char *text, 
2958                      int format_type,
2959                      const char *subject)
2960 {
2961         struct CtdlMessage *msg;
2962         recptypes *recp = NULL;
2963
2964         msg = malloc(sizeof(struct CtdlMessage));
2965         memset(msg, 0, sizeof(struct CtdlMessage));
2966         msg->cm_magic = CTDLMESSAGE_MAGIC;
2967         msg->cm_anon_type = MES_NORMAL;
2968         msg->cm_format_type = format_type;
2969
2970         if (from != NULL) {
2971                 CM_SetField(msg, eAuthor, from, strlen(from));
2972         }
2973         else if (fromaddr != NULL) {
2974                 char *pAt;
2975                 CM_SetField(msg, eAuthor, fromaddr, strlen(fromaddr));
2976                 pAt = strchr(msg->cm_fields[eAuthor], '@');
2977                 if (pAt != NULL) {
2978                         CM_CutFieldAt(msg, eAuthor, pAt - msg->cm_fields[eAuthor]);
2979                 }
2980         }
2981         else {
2982                 msg->cm_fields[eAuthor] = strdup("Citadel");
2983         }
2984
2985         if (fromaddr != NULL) CM_SetField(msg, erFc822Addr, fromaddr, strlen(fromaddr));
2986         if (room != NULL) CM_SetField(msg, eOriginalRoom, room, strlen(room));
2987         CM_SetField(msg, eNodeName, CFG_KEY(c_nodename));
2988         if (to != NULL) {
2989                 CM_SetField(msg, eRecipient, to, strlen(to));
2990                 recp = validate_recipients(to, NULL, 0);
2991         }
2992         if (subject != NULL) {
2993                 CM_SetField(msg, eMsgSubject, subject, strlen(subject));
2994         }
2995         CM_SetField(msg, eMesageText, text, strlen(text));
2996
2997         CtdlSubmitMsg(msg, recp, room, 0);
2998         CM_Free(msg);
2999         if (recp != NULL) free_recipients(recp);
3000 }
3001
3002 void flood_protect_quickie_message(const char *from,
3003                                    const char *fromaddr,
3004                                    const char *to,
3005                                    char *room,
3006                                    const char *text, 
3007                                    int format_type,
3008                                    const char *subject,
3009                                    int nCriterions,
3010                                    const char **CritStr,
3011                                    long *CritStrLen,
3012                                    long ccid,
3013                                    long ioid,
3014                                    time_t NOW)
3015 {
3016         int i;
3017         u_char rawdigest[MD5_DIGEST_LEN];
3018         struct MD5Context md5context;
3019         StrBuf *guid;
3020         char timestamp[64];
3021         long tslen;
3022         time_t tsday = NOW / (8*60*60); /* just care for a day... */
3023
3024         tslen = snprintf(timestamp, sizeof(timestamp), "%ld", tsday);
3025         MD5Init(&md5context);
3026
3027         for (i = 0; i < nCriterions; i++)
3028                 MD5Update(&md5context,
3029                           (const unsigned char*)CritStr[i], CritStrLen[i]);
3030         MD5Update(&md5context,
3031                   (const unsigned char*)timestamp, tslen);
3032         MD5Final(rawdigest, &md5context);
3033
3034         guid = NewStrBufPlain(NULL,
3035                               MD5_DIGEST_LEN * 2 + 12);
3036         StrBufHexEscAppend(guid, NULL, rawdigest, MD5_DIGEST_LEN);
3037         StrBufAppendBufPlain(guid, HKEY("_fldpt"), 0);
3038         if (StrLength(guid) > 40)
3039                 StrBufCutAt(guid, 40, NULL);
3040
3041         if (CheckIfAlreadySeen("FPAideMessage",
3042                                guid,
3043                                NOW,
3044                                tsday,
3045                                eUpdate,
3046                                ccid,
3047                                ioid)!= 0)
3048         {
3049                 FreeStrBuf(&guid);
3050                 /* yes, we did. flood protection kicks in. */
3051                 syslog(LOG_DEBUG,
3052                        "not sending message again\n");
3053                 return;
3054         }
3055         FreeStrBuf(&guid);
3056         /* no, this message isn't sent recently; go ahead. */
3057         quickie_message(from,
3058                         fromaddr,
3059                         to,
3060                         room,
3061                         text, 
3062                         format_type,
3063                         subject);
3064 }
3065
3066
3067 /*
3068  * Back end function used by CtdlMakeMessage() and similar functions
3069  */
3070 StrBuf *CtdlReadMessageBodyBuf(char *terminator,        /* token signalling EOT */
3071                                long tlen,
3072                                size_t maxlen,           /* maximum message length */
3073                                StrBuf *exist,           /* if non-null, append to it;
3074                                                            exist is ALWAYS freed  */
3075                                int crlf,                /* CRLF newlines instead of LF */
3076                                int *sock                /* socket handle or 0 for this session's client socket */
3077         ) 
3078 {
3079         StrBuf *Message;
3080         StrBuf *LineBuf;
3081         int flushing = 0;
3082         int finished = 0;
3083         int dotdot = 0;
3084
3085         LineBuf = NewStrBufPlain(NULL, SIZ);
3086         if (exist == NULL) {
3087                 Message = NewStrBufPlain(NULL, 4 * SIZ);
3088         }
3089         else {
3090                 Message = NewStrBufDup(exist);
3091         }
3092
3093         /* Do we need to change leading ".." to "." for SMTP escaping? */
3094         if ((tlen == 1) && (*terminator == '.')) {
3095                 dotdot = 1;
3096         }
3097
3098         /* read in the lines of message text one by one */
3099         do {
3100                 if (sock != NULL) {
3101                         if ((CtdlSockGetLine(sock, LineBuf, 5) < 0) ||
3102                             (*sock == -1))
3103                                 finished = 1;
3104                 }
3105                 else {
3106                         if (CtdlClientGetLine(LineBuf) < 0) finished = 1;
3107                 }
3108                 if ((StrLength(LineBuf) == tlen) && 
3109                     (!strcmp(ChrPtr(LineBuf), terminator)))
3110                         finished = 1;
3111
3112                 if ( (!flushing) && (!finished) ) {
3113                         if (crlf) {
3114                                 StrBufAppendBufPlain(LineBuf, HKEY("\r\n"), 0);
3115                         }
3116                         else {
3117                                 StrBufAppendBufPlain(LineBuf, HKEY("\n"), 0);
3118                         }
3119                         
3120                         /* Unescape SMTP-style input of two dots at the beginning of the line */
3121                         if ((dotdot) &&
3122                             (StrLength(LineBuf) == 2) && 
3123                             (!strcmp(ChrPtr(LineBuf), "..")))
3124                         {
3125                                 StrBufCutLeft(LineBuf, 1);
3126                         }
3127                         
3128                         StrBufAppendBuf(Message, LineBuf, 0);
3129                 }
3130
3131                 /* if we've hit the max msg length, flush the rest */
3132                 if (StrLength(Message) >= maxlen) flushing = 1;
3133
3134         } while (!finished);
3135         FreeStrBuf(&LineBuf);
3136         return Message;
3137 }
3138
3139 void DeleteAsyncMsg(ReadAsyncMsg **Msg)
3140 {
3141         if (*Msg == NULL)
3142                 return;
3143         FreeStrBuf(&(*Msg)->MsgBuf);
3144
3145         free(*Msg);
3146         *Msg = NULL;
3147 }
3148
3149 ReadAsyncMsg *NewAsyncMsg(const char *terminator,       /* token signalling EOT */
3150                           long tlen,
3151                           size_t maxlen,                /* maximum message length */
3152                           size_t expectlen,             /* if we expect a message, how long should it be? */
3153                           StrBuf *exist,                /* if non-null, append to it;
3154                                                            exist is ALWAYS freed  */
3155                           long eLen,                    /* length of exist */
3156                           int crlf                      /* CRLF newlines instead of LF */
3157         )
3158 {
3159         ReadAsyncMsg *NewMsg;
3160
3161         NewMsg = (ReadAsyncMsg *)malloc(sizeof(ReadAsyncMsg));
3162         memset(NewMsg, 0, sizeof(ReadAsyncMsg));
3163
3164         if (exist == NULL) {
3165                 long len;
3166
3167                 if (expectlen == 0) {
3168                         len = 4 * SIZ;
3169                 }
3170                 else {
3171                         len = expectlen + 10;
3172                 }
3173                 NewMsg->MsgBuf = NewStrBufPlain(NULL, len);
3174         }
3175         else {
3176                 NewMsg->MsgBuf = NewStrBufDup(exist);
3177         }
3178         /* Do we need to change leading ".." to "." for SMTP escaping? */
3179         if ((tlen == 1) && (*terminator == '.')) {
3180                 NewMsg->dodot = 1;
3181         }
3182
3183         NewMsg->terminator = terminator;
3184         NewMsg->tlen = tlen;
3185
3186         NewMsg->maxlen = maxlen;
3187
3188         NewMsg->crlf = crlf;
3189
3190         return NewMsg;
3191 }
3192
3193 /*
3194  * Back end function used by CtdlMakeMessage() and similar functions
3195  */
3196 eReadState CtdlReadMessageBodyAsync(AsyncIO *IO)
3197 {
3198         ReadAsyncMsg *ReadMsg;
3199         int MsgFinished = 0;
3200         eReadState Finished = eMustReadMore;
3201
3202 #ifdef BIGBAD_IODBG
3203         char fn [SIZ];
3204         FILE *fd;
3205         const char *pch = ChrPtr(IO->SendBuf.Buf);
3206         const char *pchh = IO->SendBuf.ReadWritePointer;
3207         long nbytes;
3208         
3209         if (pchh == NULL)
3210                 pchh = pch;
3211         
3212         nbytes = StrLength(IO->SendBuf.Buf) - (pchh - pch);
3213         snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
3214                  ((CitContext*)(IO->CitContext))->ServiceName,
3215                  IO->SendBuf.fd);
3216         
3217         fd = fopen(fn, "a+");
3218 #endif
3219
3220         ReadMsg = IO->ReadMsg;
3221
3222         /* read in the lines of message text one by one */
3223         do {
3224                 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
3225                 
3226                 switch (Finished) {
3227                 case eMustReadMore: /// read new from socket... 
3228 #ifdef BIGBAD_IODBG
3229                         if (IO->RecvBuf.ReadWritePointer != NULL) {
3230                                 nbytes = StrLength(IO->RecvBuf.Buf) - (IO->RecvBuf.ReadWritePointer - ChrPtr(IO->RecvBuf.Buf));
3231                                 fprintf(fd, "Read; Line unfinished: %ld Bytes still in buffer [", nbytes);
3232                                 
3233                                 fwrite(IO->RecvBuf.ReadWritePointer, nbytes, 1, fd);
3234                         
3235                                 fprintf(fd, "]\n");
3236                         } else {
3237                                 fprintf(fd, "BufferEmpty! \n");
3238                         }
3239                         fclose(fd);
3240 #endif
3241                         return Finished;
3242                     break;
3243                 case eBufferNotEmpty: /* shouldn't happen... */
3244                 case eReadSuccess: /// done for now...
3245                     break;
3246                 case eReadFail: /// WHUT?
3247                     ///todo: shut down! 
3248                         break;
3249                 }
3250             
3251
3252                 if ((StrLength(IO->IOBuf) == ReadMsg->tlen) && 
3253                     (!strcmp(ChrPtr(IO->IOBuf), ReadMsg->terminator))) {
3254                         MsgFinished = 1;
3255 #ifdef BIGBAD_IODBG
3256                         fprintf(fd, "found Terminator; Message Size: %d\n", StrLength(ReadMsg->MsgBuf));
3257 #endif
3258                 }
3259                 else if (!ReadMsg->flushing) {
3260
3261 #ifdef BIGBAD_IODBG
3262                         fprintf(fd, "Read Line: [%d][%s]\n", StrLength(IO->IOBuf), ChrPtr(IO->IOBuf));
3263 #endif
3264
3265                         /* Unescape SMTP-style input of two dots at the beginning of the line */
3266                         if ((ReadMsg->dodot) &&
3267                             (StrLength(IO->IOBuf) == 2) &&  /* TODO: do we just unescape lines with two dots or any line? */
3268                             (!strcmp(ChrPtr(IO->IOBuf), "..")))
3269                         {
3270 #ifdef BIGBAD_IODBG
3271                                 fprintf(fd, "UnEscaped!\n");
3272 #endif
3273                                 StrBufCutLeft(IO->IOBuf, 1);
3274                         }
3275
3276                         if (ReadMsg->crlf) {
3277                                 StrBufAppendBufPlain(IO->IOBuf, HKEY("\r\n"), 0);
3278                         }
3279                         else {
3280                                 StrBufAppendBufPlain(IO->IOBuf, HKEY("\n"), 0);
3281                         }
3282
3283                         StrBufAppendBuf(ReadMsg->MsgBuf, IO->IOBuf, 0);
3284                 }
3285
3286                 /* if we've hit the max msg length, flush the rest */
3287                 if (StrLength(ReadMsg->MsgBuf) >= ReadMsg->maxlen) ReadMsg->flushing = 1;
3288
3289         } while (!MsgFinished);
3290
3291 #ifdef BIGBAD_IODBG
3292         fprintf(fd, "Done with reading; %s.\n, ",
3293                 (MsgFinished)?"Message Finished": "FAILED");
3294         fclose(fd);
3295 #endif
3296         if (MsgFinished)
3297                 return eReadSuccess;
3298         else 
3299                 return eAbort;
3300 }
3301
3302
3303 /*
3304  * Back end function used by CtdlMakeMessage() and similar functions
3305  */
3306 char *CtdlReadMessageBody(char *terminator,     /* token signalling EOT */
3307                           long tlen,
3308                           size_t maxlen,                /* maximum message length */
3309                           StrBuf *exist,                /* if non-null, append to it;
3310                                                    exist is ALWAYS freed  */
3311                           int crlf,             /* CRLF newlines instead of LF */
3312                           int *sock             /* socket handle or 0 for this session's client socket */
3313         ) 
3314 {
3315         StrBuf *Message;
3316
3317         Message = CtdlReadMessageBodyBuf(terminator,
3318                                          tlen,
3319                                          maxlen,
3320                                          exist,
3321                                          crlf,
3322                                          sock);
3323         if (Message == NULL)
3324                 return NULL;
3325         else
3326                 return SmashStrBuf(&Message);
3327 }
3328
3329 struct CtdlMessage *CtdlMakeMessage(
3330         struct ctdluser *author,        /* author's user structure */
3331         char *recipient,                /* NULL if it's not mail */
3332         char *recp_cc,                  /* NULL if it's not mail */
3333         char *room,                     /* room where it's going */
3334         int type,                       /* see MES_ types in header file */
3335         int format_type,                /* variformat, plain text, MIME... */
3336         char *fake_name,                /* who we're masquerading as */
3337         char *my_email,                 /* which of my email addresses to use (empty is ok) */
3338         char *subject,                  /* Subject (optional) */
3339         char *supplied_euid,            /* ...or NULL if this is irrelevant */
3340         char *preformatted_text,        /* ...or NULL to read text from client */
3341         char *references                /* Thread references */
3342 )
3343 {
3344         return CtdlMakeMessageLen(
3345                 author, /* author's user structure */
3346                 recipient,              /* NULL if it's not mail */
3347                 (recipient)?strlen(recipient) : 0,
3348                 recp_cc,                        /* NULL if it's not mail */
3349                 (recp_cc)?strlen(recp_cc): 0,
3350                 room,                   /* room where it's going */
3351                 (room)?strlen(room): 0,
3352                 type,                   /* see MES_ types in header file */
3353                 format_type,            /* variformat, plain text, MIME... */
3354                 fake_name,              /* who we're masquerading as */
3355                 (fake_name)?strlen(fake_name): 0,
3356                 my_email,                       /* which of my email addresses to use (empty is ok) */
3357                 (my_email)?strlen(my_email): 0,
3358                 subject,                        /* Subject (optional) */
3359                 (subject)?strlen(subject): 0,
3360                 supplied_euid,          /* ...or NULL if this is irrelevant */
3361                 (supplied_euid)?strlen(supplied_euid):0,
3362                 preformatted_text,      /* ...or NULL to read text from client */
3363                 (preformatted_text)?strlen(preformatted_text) : 0,
3364                 references,             /* Thread references */
3365                 (references)?strlen(references):0);
3366
3367 }
3368
3369 /*
3370  * Build a binary message to be saved on disk.
3371  * (NOTE: if you supply 'preformatted_text', the buffer you give it
3372  * will become part of the message.  This means you are no longer
3373  * responsible for managing that memory -- it will be freed along with
3374  * the rest of the fields when CM_Free() is called.)
3375  */
3376
3377 struct CtdlMessage *CtdlMakeMessageLen(
3378         struct ctdluser *author,        /* author's user structure */
3379         char *recipient,                /* NULL if it's not mail */
3380         long rcplen,
3381         char *recp_cc,                  /* NULL if it's not mail */
3382         long cclen,
3383         char *room,                     /* room where it's going */
3384         long roomlen,
3385         int type,                       /* see MES_ types in header file */
3386         int format_type,                /* variformat, plain text, MIME... */
3387         char *fake_name,                /* who we're masquerading as */
3388         long fnlen,
3389         char *my_email,                 /* which of my email addresses to use (empty is ok) */
3390         long myelen,
3391         char *subject,                  /* Subject (optional) */
3392         long subjlen,
3393         char *supplied_euid,            /* ...or NULL if this is irrelevant */
3394         long euidlen,
3395         char *preformatted_text,        /* ...or NULL to read text from client */
3396         long textlen,
3397         char *references,               /* Thread references */
3398         long reflen
3399         )
3400 {
3401         struct CitContext *CCC = CC;
3402         /* Don't confuse the poor folks if it's not routed mail. * /
3403            char dest_node[256] = "";*/
3404         long blen;
3405         char buf[1024];
3406         struct CtdlMessage *msg;
3407         StrBuf *FakeAuthor;
3408         StrBuf *FakeEncAuthor = NULL;
3409
3410         msg = malloc(sizeof(struct CtdlMessage));
3411         memset(msg, 0, sizeof(struct CtdlMessage));
3412         msg->cm_magic = CTDLMESSAGE_MAGIC;
3413         msg->cm_anon_type = type;
3414         msg->cm_format_type = format_type;
3415
3416         if (recipient != NULL) rcplen = striplt(recipient);
3417         if (recp_cc != NULL) cclen = striplt(recp_cc);
3418
3419         /* Path or Return-Path */
3420         if (myelen > 0) {
3421                 CM_SetField(msg, eMessagePath, my_email, myelen);
3422         }
3423         else {
3424                 CM_SetField(msg, eMessagePath, author->fullname, strlen(author->fullname));
3425         }
3426         convert_spaces_to_underscores(msg->cm_fields[eMessagePath]);
3427
3428         blen = snprintf(buf, sizeof buf, "%ld", (long)time(NULL));
3429         CM_SetField(msg, eTimestamp, buf, blen);
3430
3431         if (fnlen > 0) {
3432                 FakeAuthor = NewStrBufPlain (fake_name, fnlen);
3433         }
3434         else {
3435                 FakeAuthor = NewStrBufPlain (author->fullname, -1);
3436         }
3437         StrBufRFC2047encode(&FakeEncAuthor, FakeAuthor);
3438         CM_SetAsFieldSB(msg, eAuthor, &FakeEncAuthor);
3439         FreeStrBuf(&FakeAuthor);
3440
3441         if (CCC->room.QRflags & QR_MAILBOX) {           /* room */
3442                 CM_SetField(msg, eOriginalRoom, &CCC->room.QRname[11], strlen(&CCC->room.QRname[11]));
3443         }
3444         else {
3445                 CM_SetField(msg, eOriginalRoom, CCC->room.QRname, strlen(CCC->room.QRname));
3446         }
3447
3448         CM_SetField(msg, eNodeName, CFG_KEY(c_nodename));
3449         CM_SetField(msg, eHumanNode, CFG_KEY(c_humannode));
3450
3451         if (rcplen > 0) {
3452                 CM_SetField(msg, eRecipient, recipient, rcplen);
3453         }
3454         if (cclen > 0) {
3455                 CM_SetField(msg, eCarbonCopY, recp_cc, cclen);
3456         }
3457
3458         if (myelen > 0) {
3459                 CM_SetField(msg, erFc822Addr, my_email, myelen);
3460         }
3461         else if ( (author == &CCC->user) && (!IsEmptyStr(CCC->cs_inet_email)) ) {
3462                 CM_SetField(msg, erFc822Addr, CCC->cs_inet_email, strlen(CCC->cs_inet_email));
3463         }
3464
3465         if (subject != NULL) {
3466                 long length;
3467                 length = striplt(subject);
3468                 if (length > 0) {
3469                         long i;
3470                         long IsAscii;
3471                         IsAscii = -1;
3472                         i = 0;
3473                         while ((subject[i] != '\0') &&
3474                                (IsAscii = isascii(subject[i]) != 0 ))
3475                                 i++;
3476                         if (IsAscii != 0)
3477                                 CM_SetField(msg, eMsgSubject, subject, subjlen);
3478                         else /* ok, we've got utf8 in the string. */
3479                         {
3480                                 char *rfc2047Subj;
3481                                 rfc2047Subj = rfc2047encode(subject, length);
3482                                 CM_SetAsField(msg, eMsgSubject, &rfc2047Subj, strlen(rfc2047Subj));
3483                         }
3484
3485                 }
3486         }
3487
3488         if (euidlen > 0) {
3489                 CM_SetField(msg, eExclusiveID, supplied_euid, euidlen);
3490         }
3491
3492         if (reflen > 0) {
3493                 CM_SetField(msg, eWeferences, references, reflen);
3494         }
3495
3496         if (preformatted_text != NULL) {
3497                 CM_SetField(msg, eMesageText, preformatted_text, textlen);
3498         }
3499         else {
3500                 StrBuf *MsgBody;
3501                 MsgBody = CtdlReadMessageBodyBuf(HKEY("000"), config.c_maxmsglen, NULL, 0, 0);
3502                 if (MsgBody != NULL) {
3503                         CM_SetAsFieldSB(msg, eMesageText, &MsgBody);
3504                 }
3505         }
3506
3507         return(msg);
3508 }
3509
3510
3511
3512
3513 /*
3514  * API function to delete messages which match a set of criteria
3515  * (returns the actual number of messages deleted)
3516  */
3517 int CtdlDeleteMessages(char *room_name,         /* which room */
3518                        long *dmsgnums,          /* array of msg numbers to be deleted */
3519                        int num_dmsgnums,        /* number of msgs to be deleted, or 0 for "any" */
3520                        char *content_type       /* or "" for any.  regular expressions expected. */
3521         )
3522 {
3523         struct CitContext *CCC = CC;
3524         struct ctdlroom qrbuf;
3525         struct cdbdata *cdbfr;
3526         long *msglist = NULL;
3527         long *dellist = NULL;
3528         int num_msgs = 0;
3529         int i, j;
3530         int num_deleted = 0;
3531         int delete_this;
3532         struct MetaData smi;
3533         regex_t re;
3534         regmatch_t pm;
3535         int need_to_free_re = 0;
3536
3537         if (content_type) if (!IsEmptyStr(content_type)) {
3538                         regcomp(&re, content_type, 0);
3539                         need_to_free_re = 1;
3540                 }
3541         MSG_syslog(LOG_DEBUG, " CtdlDeleteMessages(%s, %d msgs, %s)\n",
3542                    room_name, num_dmsgnums, content_type);
3543
3544         /* get room record, obtaining a lock... */
3545         if (CtdlGetRoomLock(&qrbuf, room_name) != 0) {
3546                 MSG_syslog(LOG_ERR, " CtdlDeleteMessages(): Room <%s> not found\n",
3547                            room_name);
3548                 if (need_to_free_re) regfree(&re);
3549                 return (0);     /* room not found */
3550         }
3551         cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf.QRnumber, sizeof(long));
3552
3553         if (cdbfr != NULL) {
3554                 dellist = malloc(cdbfr->len);
3555                 msglist = (long *) cdbfr->ptr;
3556                 cdbfr->ptr = NULL;      /* CtdlDeleteMessages() now owns this memory */
3557                 num_msgs = cdbfr->len / sizeof(long);
3558                 cdb_free(cdbfr);
3559         }
3560         if (num_msgs > 0) {
3561                 int have_contenttype = (content_type != NULL) && !IsEmptyStr(content_type);
3562                 int have_delmsgs = (num_dmsgnums == 0) || (dmsgnums == NULL);
3563                 int have_more_del = 1;
3564
3565                 num_msgs = sort_msglist(msglist, num_msgs);
3566                 if (num_dmsgnums > 1)
3567                         num_dmsgnums = sort_msglist(dmsgnums, num_dmsgnums);
3568 /*
3569                 {
3570                         StrBuf *dbg = NewStrBuf();
3571                         for (i = 0; i < num_dmsgnums; i++)
3572                                 StrBufAppendPrintf(dbg, ", %ld", dmsgnums[i]);
3573                         MSG_syslog(LOG_DEBUG, " Deleting before: %s", ChrPtr(dbg));
3574                         FreeStrBuf(&dbg);
3575                 }
3576 */
3577                 i = 0; j = 0;
3578                 while ((i < num_msgs) && (have_more_del)) {
3579                         delete_this = 0x00;
3580
3581                         /* Set/clear a bit for each criterion */
3582
3583                         /* 0 messages in the list or a null list means that we are
3584                          * interested in deleting any messages which meet the other criteria.
3585                          */
3586                         if (have_delmsgs) {
3587                                 delete_this |= 0x01;
3588                         }
3589                         else {
3590                                 while ((i < num_msgs) && (msglist[i] < dmsgnums[j])) i++;
3591
3592                                 if (i >= num_msgs)
3593                                         continue;
3594
3595                                 if (msglist[i] == dmsgnums[j]) {
3596                                         delete_this |= 0x01;
3597                                 }
3598                                 j++;
3599                                 have_more_del = (j < num_dmsgnums);
3600                         }
3601
3602                         if (have_contenttype) {
3603                                 GetMetaData(&smi, msglist[i]);
3604                                 if (regexec(&re, smi.meta_content_type, 1, &pm, 0) == 0) {
3605                                         delete_this |= 0x02;
3606                                 }
3607                         } else {
3608                                 delete_this |= 0x02;
3609                         }
3610
3611                         /* Delete message only if all bits are set */
3612                         if (delete_this == 0x03) {
3613                                 dellist[num_deleted++] = msglist[i];
3614                                 msglist[i] = 0L;
3615                         }
3616                         i++;
3617                 }
3618 /*
3619                 {
3620                         StrBuf *dbg = NewStrBuf();
3621                         for (i = 0; i < num_deleted; i++)
3622                                 StrBufAppendPrintf(dbg, ", %ld", dellist[i]);
3623                         MSG_syslog(LOG_DEBUG, " Deleting: %s", ChrPtr(dbg));
3624                         FreeStrBuf(&dbg);
3625                 }
3626 */
3627                 num_msgs = sort_msglist(msglist, num_msgs);
3628                 cdb_store(CDB_MSGLISTS, &qrbuf.QRnumber, (int)sizeof(long),
3629                           msglist, (int)(num_msgs * sizeof(long)));
3630
3631                 if (num_msgs > 0)
3632                         qrbuf.QRhighest = msglist[num_msgs - 1];
3633                 else
3634                         qrbuf.QRhighest = 0;
3635         }
3636         CtdlPutRoomLock(&qrbuf);
3637
3638         /* Go through the messages we pulled out of the index, and decrement
3639          * their reference counts by 1.  If this is the only room the message
3640          * was in, the reference count will reach zero and the message will
3641          * automatically be deleted from the database.  We do this in a
3642          * separate pass because there might be plug-in hooks getting called,
3643          * and we don't want that happening during an S_ROOMS critical
3644          * section.
3645          */
3646         if (num_deleted) {
3647                 for (i=0; i<num_deleted; ++i) {
3648                         PerformDeleteHooks(qrbuf.QRname, dellist[i]);
3649                 }
3650                 AdjRefCountList(dellist, num_deleted, -1);
3651         }
3652         /* Now free the memory we used, and go away. */
3653         if (msglist != NULL) free(msglist);
3654         if (dellist != NULL) free(dellist);
3655         MSG_syslog(LOG_DEBUG, " %d message(s) deleted.\n", num_deleted);
3656         if (need_to_free_re) regfree(&re);
3657         return (num_deleted);
3658 }
3659
3660
3661
3662
3663 /*
3664  * GetMetaData()  -  Get the supplementary record for a message
3665  */
3666 void GetMetaData(struct MetaData *smibuf, long msgnum)
3667 {
3668
3669         struct cdbdata *cdbsmi;
3670         long TheIndex;
3671
3672         memset(smibuf, 0, sizeof(struct MetaData));
3673         smibuf->meta_msgnum = msgnum;
3674         smibuf->meta_refcount = 1;      /* Default reference count is 1 */
3675
3676         /* Use the negative of the message number for its supp record index */
3677         TheIndex = (0L - msgnum);
3678
3679         cdbsmi = cdb_fetch(CDB_MSGMAIN, &TheIndex, sizeof(long));
3680         if (cdbsmi == NULL) {
3681                 return;         /* record not found; go with defaults */
3682         }
3683         memcpy(smibuf, cdbsmi->ptr,
3684                ((cdbsmi->len > sizeof(struct MetaData)) ?
3685                 sizeof(struct MetaData) : cdbsmi->len));
3686         cdb_free(cdbsmi);
3687         return;
3688 }
3689
3690
3691 /*
3692  * PutMetaData()  -  (re)write supplementary record for a message
3693  */
3694 void PutMetaData(struct MetaData *smibuf)
3695 {
3696         long TheIndex;
3697
3698         /* Use the negative of the message number for the metadata db index */
3699         TheIndex = (0L - smibuf->meta_msgnum);
3700
3701         cdb_store(CDB_MSGMAIN,
3702                   &TheIndex, (int)sizeof(long),
3703                   smibuf, (int)sizeof(struct MetaData));
3704
3705 }
3706
3707 /*
3708  * AdjRefCount  -  submit an adjustment to the reference count for a message.
3709  *                 (These are just queued -- we actually process them later.)
3710  */
3711 void AdjRefCount(long msgnum, int incr)
3712 {
3713         struct CitContext *CCC = CC;
3714         struct arcq new_arcq;
3715         int rv = 0;
3716
3717         MSG_syslog(LOG_DEBUG, "AdjRefCount() msg %ld ref count delta %+d\n", msgnum, incr);
3718
3719         begin_critical_section(S_SUPPMSGMAIN);
3720         if (arcfp == NULL) {
3721                 arcfp = fopen(file_arcq, "ab+");
3722                 chown(file_arcq, CTDLUID, (-1));
3723                 chmod(file_arcq, 0600);
3724         }
3725         end_critical_section(S_SUPPMSGMAIN);
3726
3727         /* msgnum < 0 means that we're trying to close the file */
3728         if (msgnum < 0) {
3729                 MSGM_syslog(LOG_DEBUG, "Closing the AdjRefCount queue file\n");
3730                 begin_critical_section(S_SUPPMSGMAIN);
3731                 if (arcfp != NULL) {
3732                         fclose(arcfp);
3733                         arcfp = NULL;
3734                 }
3735                 end_critical_section(S_SUPPMSGMAIN);
3736                 return;
3737         }
3738
3739         /*
3740          * If we can't open the queue, perform the operation synchronously.
3741          */
3742         if (arcfp == NULL) {
3743                 TDAP_AdjRefCount(msgnum, incr);
3744                 return;
3745         }
3746
3747         new_arcq.arcq_msgnum = msgnum;
3748         new_arcq.arcq_delta = incr;
3749         rv = fwrite(&new_arcq, sizeof(struct arcq), 1, arcfp);
3750         if (rv == -1) {
3751                 MSG_syslog(LOG_EMERG, "Couldn't write Refcount Queue File %s: %s\n",
3752                            file_arcq,
3753                            strerror(errno));
3754         }
3755         fflush(arcfp);
3756
3757         return;
3758 }
3759
3760 void AdjRefCountList(long *msgnum, long nmsg, int incr)
3761 {
3762         struct CitContext *CCC = CC;
3763         long i, the_size, offset;
3764         struct arcq *new_arcq;
3765         int rv = 0;
3766
3767         MSG_syslog(LOG_DEBUG, "AdjRefCountList() msg %ld ref count delta %+d\n", nmsg, incr);
3768
3769         begin_critical_section(S_SUPPMSGMAIN);
3770         if (arcfp == NULL) {
3771                 arcfp = fopen(file_arcq, "ab+");
3772                 chown(file_arcq, CTDLUID, (-1));
3773                 chmod(file_arcq, 0600);
3774         }
3775         end_critical_section(S_SUPPMSGMAIN);
3776
3777         /*
3778          * If we can't open the queue, perform the operation synchronously.
3779          */
3780         if (arcfp == NULL) {
3781                 for (i = 0; i < nmsg; i++)
3782                         TDAP_AdjRefCount(msgnum[i], incr);
3783                 return;
3784         }
3785
3786         the_size = sizeof(struct arcq) * nmsg;
3787         new_arcq = malloc(the_size);
3788         for (i = 0; i < nmsg; i++) {
3789                 new_arcq[i].arcq_msgnum = msgnum[i];
3790                 new_arcq[i].arcq_delta = incr;
3791         }
3792         rv = 0;
3793         offset = 0;
3794         while ((rv >= 0) && (offset < the_size))
3795         {
3796                 rv = fwrite(new_arcq + offset, 1, the_size - offset, arcfp);
3797                 if (rv == -1) {
3798                         MSG_syslog(LOG_EMERG, "Couldn't write Refcount Queue File %s: %s\n",
3799                                    file_arcq,
3800                                    strerror(errno));
3801                 }
3802                 else {
3803                         offset += rv;
3804                 }
3805         }
3806         free(new_arcq);
3807         fflush(arcfp);
3808
3809         return;
3810 }
3811
3812
3813 /*
3814  * TDAP_ProcessAdjRefCountQueue()
3815  *
3816  * Process the queue of message count adjustments that was created by calls
3817  * to AdjRefCount() ... by reading the queue and calling TDAP_AdjRefCount()
3818  * for each one.  This should be an "off hours" operation.
3819  */
3820 int TDAP_ProcessAdjRefCountQueue(void)
3821 {
3822         struct CitContext *CCC = CC;
3823         char file_arcq_temp[PATH_MAX];
3824         int r;
3825         FILE *fp;
3826         struct arcq arcq_rec;
3827         int num_records_processed = 0;
3828
3829         snprintf(file_arcq_temp, sizeof file_arcq_temp, "%s.%04x", file_arcq, rand());
3830
3831         begin_critical_section(S_SUPPMSGMAIN);
3832         if (arcfp != NULL) {
3833                 fclose(arcfp);
3834                 arcfp = NULL;
3835         }
3836
3837         r = link(file_arcq, file_arcq_temp);
3838         if (r != 0) {
3839                 MSG_syslog(LOG_CRIT, "%s: %s\n", file_arcq_temp, strerror(errno));
3840                 end_critical_section(S_SUPPMSGMAIN);
3841                 return(num_records_processed);
3842         }
3843
3844         unlink(file_arcq);
3845         end_critical_section(S_SUPPMSGMAIN);
3846
3847         fp = fopen(file_arcq_temp, "rb");
3848         if (fp == NULL) {
3849                 MSG_syslog(LOG_CRIT, "%s: %s\n", file_arcq_temp, strerror(errno));
3850                 return(num_records_processed);
3851         }
3852
3853         while (fread(&arcq_rec, sizeof(struct arcq), 1, fp) == 1) {
3854                 TDAP_AdjRefCount(arcq_rec.arcq_msgnum, arcq_rec.arcq_delta);
3855                 ++num_records_processed;
3856         }
3857
3858         fclose(fp);
3859         r = unlink(file_arcq_temp);
3860         if (r != 0) {
3861                 MSG_syslog(LOG_CRIT, "%s: %s\n", file_arcq_temp, strerror(errno));
3862         }
3863
3864         return(num_records_processed);
3865 }
3866
3867
3868
3869 /*
3870  * TDAP_AdjRefCount  -  adjust the reference count for a message.
3871  *                      This one does it "for real" because it's called by
3872  *                      the autopurger function that processes the queue
3873  *                      created by AdjRefCount().   If a message's reference
3874  *                      count becomes zero, we also delete the message from
3875  *                      disk and de-index it.
3876  */
3877 void TDAP_AdjRefCount(long msgnum, int incr)
3878 {
3879         struct CitContext *CCC = CC;
3880
3881         struct MetaData smi;
3882         long delnum;
3883
3884         /* This is a *tight* critical section; please keep it that way, as
3885          * it may get called while nested in other critical sections.  
3886          * Complicating this any further will surely cause deadlock!
3887          */
3888         begin_critical_section(S_SUPPMSGMAIN);
3889         GetMetaData(&smi, msgnum);
3890         smi.meta_refcount += incr;
3891         PutMetaData(&smi);
3892         end_critical_section(S_SUPPMSGMAIN);
3893         MSG_syslog(LOG_DEBUG, "TDAP_AdjRefCount() msg %ld ref count delta %+d, is now %d\n",
3894                    msgnum, incr, smi.meta_refcount
3895                 );
3896
3897         /* If the reference count is now zero, delete the message
3898          * (and its supplementary record as well).
3899          */
3900         if (smi.meta_refcount == 0) {
3901                 MSG_syslog(LOG_DEBUG, "Deleting message <%ld>\n", msgnum);
3902                 
3903                 /* Call delete hooks with NULL room to show it has gone altogether */
3904                 PerformDeleteHooks(NULL, msgnum);
3905
3906                 /* Remove from message base */
3907                 delnum = msgnum;
3908                 cdb_delete(CDB_MSGMAIN, &delnum, (int)sizeof(long));
3909                 cdb_delete(CDB_BIGMSGS, &delnum, (int)sizeof(long));
3910
3911                 /* Remove metadata record */
3912                 delnum = (0L - msgnum);
3913                 cdb_delete(CDB_MSGMAIN, &delnum, (int)sizeof(long));
3914         }
3915
3916 }
3917
3918 /*
3919  * Write a generic object to this room
3920  *
3921  * Note: this could be much more efficient.  Right now we use two temporary
3922  * files, and still pull the message into memory as with all others.
3923  */
3924 void CtdlWriteObject(char *req_room,                    /* Room to stuff it in */
3925                      char *content_type,                /* MIME type of this object */
3926                      char *raw_message,         /* Data to be written */
3927                      off_t raw_length,          /* Size of raw_message */
3928                      struct ctdluser *is_mailbox,       /* Mailbox room? */
3929                      int is_binary,                     /* Is encoding necessary? */
3930                      int is_unique,                     /* Del others of this type? */
3931                      unsigned int flags         /* Internal save flags */
3932         )
3933 {
3934         struct CitContext *CCC = CC;
3935         struct ctdlroom qrbuf;
3936         char roomname[ROOMNAMELEN];
3937         struct CtdlMessage *msg;
3938         StrBuf *encoded_message = NULL;
3939
3940         if (is_mailbox != NULL) {
3941                 CtdlMailboxName(roomname, sizeof roomname, is_mailbox, req_room);
3942         }
3943         else {
3944                 safestrncpy(roomname, req_room, sizeof(roomname));
3945         }
3946
3947         MSG_syslog(LOG_DEBUG, "Raw length is %ld\n", (long)raw_length);
3948
3949         if (is_binary) {
3950                 encoded_message = NewStrBufPlain(NULL, (size_t) (((raw_length * 134) / 100) + 4096 ) );
3951         }
3952         else {
3953                 encoded_message = NewStrBufPlain(NULL, (size_t)(raw_length + 4096));
3954         }
3955
3956         StrBufAppendBufPlain(encoded_message, HKEY("Content-type: "), 0);
3957         StrBufAppendBufPlain(encoded_message, content_type, -1, 0);
3958         StrBufAppendBufPlain(encoded_message, HKEY("\n"), 0);
3959
3960         if (is_binary) {
3961                 StrBufAppendBufPlain(encoded_message, HKEY("Content-transfer-encoding: base64\n\n"), 0);
3962         }
3963         else {
3964                 StrBufAppendBufPlain(encoded_message, HKEY("Content-transfer-encoding: 7bit\n\n"), 0);
3965         }
3966
3967         if (is_binary) {
3968                 StrBufBase64Append(encoded_message, NULL, raw_message, raw_length, 0);
3969         }
3970         else {
3971                 StrBufAppendBufPlain(encoded_message, raw_message, raw_length, 0);
3972         }
3973
3974         MSGM_syslog(LOG_DEBUG, "Allocating\n");
3975         msg = malloc(sizeof(struct CtdlMessage));
3976         memset(msg, 0, sizeof(struct CtdlMessage));
3977         msg->cm_magic = CTDLMESSAGE_MAGIC;
3978         msg->cm_anon_type = MES_NORMAL;
3979         msg->cm_format_type = 4;
3980         CM_SetField(msg, eAuthor, CCC->user.fullname, strlen(CCC->user.fullname));
3981         CM_SetField(msg, eOriginalRoom, req_room, strlen(req_room));
3982         CM_SetField(msg, eNodeName, CFG_KEY(c_nodename));
3983         CM_SetField(msg, eHumanNode, CFG_KEY(c_humannode));
3984         msg->cm_flags = flags;
3985         
3986         CM_SetAsFieldSB(msg, eMesageText, &encoded_message);
3987
3988         /* Create the requested room if we have to. */
3989         if (CtdlGetRoom(&qrbuf, roomname) != 0) {
3990                 CtdlCreateRoom(roomname, 
3991                                ( (is_mailbox != NULL) ? 5 : 3 ),
3992                                "", 0, 1, 0, VIEW_BBS);
3993         }
3994         /* If the caller specified this object as unique, delete all
3995          * other objects of this type that are currently in the room.
3996          */
3997         if (is_unique) {
3998                 MSG_syslog(LOG_DEBUG, "Deleted %d other msgs of this type\n",
3999                            CtdlDeleteMessages(roomname, NULL, 0, content_type)
4000                         );
4001         }
4002         /* Now write the data */
4003         CtdlSubmitMsg(msg, NULL, roomname, 0);
4004         CM_Free(msg);
4005 }
4006
4007
4008
4009 /*****************************************************************************/
4010 /*                      MODULE INITIALIZATION STUFF                          */
4011 /*****************************************************************************/
4012 void SetMessageDebugEnabled(const int n)
4013 {
4014         MessageDebugEnabled = n;
4015 }
4016 CTDL_MODULE_INIT(msgbase)
4017 {
4018         if (!threading) {
4019                 CtdlRegisterDebugFlagHook(HKEY("messages"), SetMessageDebugEnabled, &MessageDebugEnabled);
4020         }
4021
4022         /* return our Subversion id for the Log */
4023         return "msgbase";
4024 }