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