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