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