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