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