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