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