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