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