405790cb43ded6e5b56871264ae5f2931eec99be
[citadel.git] / 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
160 int CM_IsEmpty(struct CtdlMessage *Msg, eMsgField which)
161 {
162         return !((Msg->cm_fields[which] != NULL) &&
163                  (Msg->cm_fields[which][0] != '\0'));
164 }
165
166 void CM_SetField(struct CtdlMessage *Msg, eMsgField which, const char *buf, long length)
167 {
168         if (Msg->cm_fields[which] != NULL)
169                 free (Msg->cm_fields[which]);
170         Msg->cm_fields[which] = malloc(length + 1);
171         memcpy(Msg->cm_fields[which], buf, length);
172         Msg->cm_fields[which][length] = '\0';
173 }
174
175 void CM_SetFieldLONG(struct CtdlMessage *Msg, eMsgField which, long lvalue)
176 {
177         char buf[128];
178         long len;
179         len = snprintf(buf, sizeof(buf), "%ld", lvalue);
180         CM_SetField(Msg, which, buf, len);
181 }
182 void CM_CutFieldAt(struct CtdlMessage *Msg, eMsgField WhichToCut, long maxlen)
183 {
184         if (Msg->cm_fields[WhichToCut] == NULL)
185                 return;
186
187         if (strlen(Msg->cm_fields[WhichToCut]) > maxlen)
188                 Msg->cm_fields[WhichToCut][maxlen] = '\0';
189 }
190
191 void CM_FlushField(struct CtdlMessage *Msg, eMsgField which)
192 {
193         if (Msg->cm_fields[which] != NULL)
194                 free (Msg->cm_fields[which]);
195         Msg->cm_fields[which] = NULL;
196 }
197
198 void CM_CopyField(struct CtdlMessage *Msg, eMsgField WhichToPutTo, eMsgField WhichtToCopy)
199 {
200         long len;
201         if (Msg->cm_fields[WhichToPutTo] != NULL)
202                 free (Msg->cm_fields[WhichToPutTo]);
203
204         if (Msg->cm_fields[WhichtToCopy] != NULL)
205         {
206                 len = strlen(Msg->cm_fields[WhichtToCopy]);
207                 Msg->cm_fields[WhichToPutTo] = malloc(len + 1);
208                 memcpy(Msg->cm_fields[WhichToPutTo], Msg->cm_fields[WhichToPutTo], len);
209                 Msg->cm_fields[WhichToPutTo][len] = '\0';
210         }
211         else
212                 Msg->cm_fields[WhichToPutTo] = NULL;
213 }
214
215
216 void CM_PrependToField(struct CtdlMessage *Msg, eMsgField which, const char *buf, long length)
217 {
218         if (Msg->cm_fields[which] != NULL) {
219                 long oldmsgsize;
220                 long newmsgsize;
221                 char *new;
222
223                 oldmsgsize = strlen(Msg->cm_fields[which]) + 1;
224                 newmsgsize = length + oldmsgsize;
225
226                 new = malloc(newmsgsize);
227                 memcpy(new, buf, length);
228                 memcpy(new + length, Msg->cm_fields[which], oldmsgsize);
229                 free(Msg->cm_fields[which]);
230                 Msg->cm_fields[which] = new;
231         }
232         else {
233                 Msg->cm_fields[which] = malloc(length + 1);
234                 memcpy(Msg->cm_fields[which], buf, length);
235                 Msg->cm_fields[which][length] = '\0';
236         }
237 }
238
239 void CM_SetAsField(struct CtdlMessage *Msg, eMsgField which, char **buf, long length)
240 {
241         if (Msg->cm_fields[which] != NULL)
242                 free (Msg->cm_fields[which]);
243
244         Msg->cm_fields[which] = *buf;
245         *buf = NULL;
246 }
247
248 void CM_SetAsFieldSB(struct CtdlMessage *Msg, eMsgField which, StrBuf **buf)
249 {
250         if (Msg->cm_fields[which] != NULL)
251                 free (Msg->cm_fields[which]);
252
253         Msg->cm_fields[which] = SmashStrBuf(buf);
254 }
255
256 void CM_GetAsField(struct CtdlMessage *Msg, eMsgField which, char **ret, long *retlen)
257 {
258         if (Msg->cm_fields[which] != NULL)
259         {
260                 *retlen = strlen(Msg->cm_fields[which]);
261                 *ret = Msg->cm_fields[which];
262                 Msg->cm_fields[which] = NULL;
263         }
264         else
265         {
266                 *ret = NULL;
267                 *retlen = 0;
268         }
269 }
270
271 /*
272  * Returns 1 if the supplied pointer points to a valid Citadel message.
273  * If the pointer is NULL or the magic number check fails, returns 0.
274  */
275 int CM_IsValidMsg(struct CtdlMessage *msg) {
276         if (msg == NULL)
277                 return 0;
278         if ((msg->cm_magic) != CTDLMESSAGE_MAGIC) {
279                 struct CitContext *CCC = CC;
280                 MSGM_syslog(LOG_WARNING, "CM_IsValidMsg() -- self-check failed\n");
281                 return 0;
282         }
283         return 1;
284 }
285
286 void CM_FreeContents(struct CtdlMessage *msg)
287 {
288         int i;
289
290         for (i = 0; i < 256; ++i)
291                 if (msg->cm_fields[i] != NULL) {
292                         free(msg->cm_fields[i]);
293                 }
294
295         msg->cm_magic = 0;      /* just in case */
296 }
297 /*
298  * 'Destructor' for struct CtdlMessage
299  */
300 void CM_Free(struct CtdlMessage *msg)
301 {
302         if (CM_IsValidMsg(msg) == 0) 
303         {
304                 if (msg != NULL) free (msg);
305                 return;
306         }
307         CM_FreeContents(msg);
308         free(msg);
309 }
310
311 int CM_DupField(eMsgField i, struct CtdlMessage *OrgMsg, struct CtdlMessage *NewMsg)
312 {
313         long len;
314         len = strlen(OrgMsg->cm_fields[i]);
315         NewMsg->cm_fields[i] = malloc(len + 1);
316         if (NewMsg->cm_fields[i] == NULL)
317                 return 0;
318         memcpy(NewMsg->cm_fields[i], OrgMsg->cm_fields[i], len);
319         NewMsg->cm_fields[i][len] = '\0';
320         return 1;
321 }
322
323 struct CtdlMessage * CM_Duplicate(struct CtdlMessage *OrgMsg)
324 {
325         int i;
326         struct CtdlMessage *NewMsg;
327
328         if (CM_IsValidMsg(OrgMsg) == 0) 
329                 return NULL;
330         NewMsg = (struct CtdlMessage *)malloc(sizeof(struct CtdlMessage));
331         if (NewMsg == NULL)
332                 return NULL;
333
334         memcpy(NewMsg, OrgMsg, sizeof(struct CtdlMessage));
335
336         memset(&NewMsg->cm_fields, 0, sizeof(char*) * 256);
337         
338         for (i = 0; i < 256; ++i)
339         {
340                 if (OrgMsg->cm_fields[i] != NULL)
341                 {
342                         if (!CM_DupField(i, OrgMsg, NewMsg))
343                         {
344                                 CM_Free(NewMsg);
345                                 return NULL;
346                         }
347                 }
348         }
349
350         return NewMsg;
351 }
352
353
354
355 /*
356  * This function is self explanatory.
357  * (What can I say, I'm in a weird mood today...)
358  */
359 void remove_any_whitespace_to_the_left_or_right_of_at_symbol(char *name)
360 {
361         int i;
362
363         for (i = 0; i < strlen(name); ++i) {
364                 if (name[i] == '@') {
365                         while (isspace(name[i - 1]) && i > 0) {
366                                 strcpy(&name[i - 1], &name[i]);
367                                 --i;
368                         }
369                         while (isspace(name[i + 1])) {
370                                 strcpy(&name[i + 1], &name[i + 2]);
371                         }
372                 }
373         }
374 }
375
376
377 /*
378  * Aliasing for network mail.
379  * (Error messages have been commented out, because this is a server.)
380  */
381 int alias(char *name)
382 {                               /* process alias and routing info for mail */
383         struct CitContext *CCC = CC;
384         FILE *fp;
385         int a, i;
386         char aaa[SIZ], bbb[SIZ];
387         char *ignetcfg = NULL;
388         char *ignetmap = NULL;
389         int at = 0;
390         char node[64];
391         char testnode[64];
392         char buf[SIZ];
393
394         char original_name[256];
395         safestrncpy(original_name, name, sizeof original_name);
396
397         striplt(name);
398         remove_any_whitespace_to_the_left_or_right_of_at_symbol(name);
399         stripallbut(name, '<', '>');
400
401         fp = fopen(file_mail_aliases, "r");
402         if (fp == NULL) {
403                 fp = fopen("/dev/null", "r");
404         }
405         if (fp == NULL) {
406                 return (MES_ERROR);
407         }
408         strcpy(aaa, "");
409         strcpy(bbb, "");
410         while (fgets(aaa, sizeof aaa, fp) != NULL) {
411                 while (isspace(name[0]))
412                         strcpy(name, &name[1]);
413                 aaa[strlen(aaa) - 1] = 0;
414                 strcpy(bbb, "");
415                 for (a = 0; a < strlen(aaa); ++a) {
416                         if (aaa[a] == ',') {
417                                 strcpy(bbb, &aaa[a + 1]);
418                                 aaa[a] = 0;
419                         }
420                 }
421                 if (!strcasecmp(name, aaa))
422                         strcpy(name, bbb);
423         }
424         fclose(fp);
425
426         /* Hit the Global Address Book */
427         if (CtdlDirectoryLookup(aaa, name, sizeof aaa) == 0) {
428                 strcpy(name, aaa);
429         }
430
431         if (strcasecmp(original_name, name)) {
432                 MSG_syslog(LOG_INFO, "%s is being forwarded to %s\n", original_name, name);
433         }
434
435         /* Change "user @ xxx" to "user" if xxx is an alias for this host */
436         for (a=0; a<strlen(name); ++a) {
437                 if (name[a] == '@') {
438                         if (CtdlHostAlias(&name[a+1]) == hostalias_localhost) {
439                                 name[a] = 0;
440                                 MSG_syslog(LOG_INFO, "Changed to <%s>\n", name);
441                         }
442                 }
443         }
444
445         /* determine local or remote type, see citadel.h */
446         at = haschar(name, '@');
447         if (at == 0) return(MES_LOCAL);         /* no @'s - local address */
448         if (at > 1) return(MES_ERROR);          /* >1 @'s - invalid address */
449         remove_any_whitespace_to_the_left_or_right_of_at_symbol(name);
450
451         /* figure out the delivery mode */
452         extract_token(node, name, 1, '@', sizeof node);
453
454         /* If there are one or more dots in the nodename, we assume that it
455          * is an FQDN and will attempt SMTP delivery to the Internet.
456          */
457         if (haschar(node, '.') > 0) {
458                 return(MES_INTERNET);
459         }
460
461         /* Otherwise we look in the IGnet maps for a valid Citadel node.
462          * Try directly-connected nodes first...
463          */
464         ignetcfg = CtdlGetSysConfig(IGNETCFG);
465         for (i=0; i<num_tokens(ignetcfg, '\n'); ++i) {
466                 extract_token(buf, ignetcfg, i, '\n', sizeof buf);
467                 extract_token(testnode, buf, 0, '|', sizeof testnode);
468                 if (!strcasecmp(node, testnode)) {
469                         free(ignetcfg);
470                         return(MES_IGNET);
471                 }
472         }
473         free(ignetcfg);
474
475         /*
476          * Then try nodes that are two or more hops away.
477          */
478         ignetmap = CtdlGetSysConfig(IGNETMAP);
479         for (i=0; i<num_tokens(ignetmap, '\n'); ++i) {
480                 extract_token(buf, ignetmap, i, '\n', sizeof buf);
481                 extract_token(testnode, buf, 0, '|', sizeof testnode);
482                 if (!strcasecmp(node, testnode)) {
483                         free(ignetmap);
484                         return(MES_IGNET);
485                 }
486         }
487         free(ignetmap);
488
489         /* If we get to this point it's an invalid node name */
490         return (MES_ERROR);
491 }
492
493
494 /*
495  * Back end for the MSGS command: output message number only.
496  */
497 void simple_listing(long msgnum, void *userdata)
498 {
499         cprintf("%ld\n", msgnum);
500 }
501
502
503
504 /*
505  * Back end for the MSGS command: output header summary.
506  */
507 void headers_listing(long msgnum, void *userdata)
508 {
509         struct CtdlMessage *msg;
510
511         msg = CtdlFetchMessage(msgnum, 0);
512         if (msg == NULL) {
513                 cprintf("%ld|0|||||\n", msgnum);
514                 return;
515         }
516
517         cprintf("%ld|%s|%s|%s|%s|%s|\n",
518                 msgnum,
519                 (!CM_IsEmpty(msg, eTimestamp) ? msg->cm_fields[eTimestamp] : "0"),
520                 (!CM_IsEmpty(msg, eAuthor) ? msg->cm_fields[eAuthor] : ""),
521                 (!CM_IsEmpty(msg, eNodeName) ? msg->cm_fields[eNodeName] : ""),
522                 (!CM_IsEmpty(msg, erFc822Addr) ? msg->cm_fields[erFc822Addr] : ""),
523                 (!CM_IsEmpty(msg, eMsgSubject) ? msg->cm_fields[eMsgSubject] : "")
524         );
525         CM_Free(msg);
526 }
527
528 /*
529  * Back end for the MSGS command: output EUID header.
530  */
531 void headers_euid(long msgnum, void *userdata)
532 {
533         struct CtdlMessage *msg;
534
535         msg = CtdlFetchMessage(msgnum, 0);
536         if (msg == NULL) {
537                 cprintf("%ld||\n", msgnum);
538                 return;
539         }
540
541         cprintf("%ld|%s|%s\n", 
542                 msgnum, 
543                 (!CM_IsEmpty(msg, eExclusiveID) ? msg->cm_fields[eExclusiveID] : ""),
544                 (!CM_IsEmpty(msg, eTimestamp) ? msg->cm_fields[eTimestamp] : "0"));
545         CM_Free(msg);
546 }
547
548
549
550
551
552 /* Determine if a given message matches the fields in a message template.
553  * Return 0 for a successful match.
554  */
555 int CtdlMsgCmp(struct CtdlMessage *msg, struct CtdlMessage *template) {
556         int i;
557
558         /* If there aren't any fields in the template, all messages will
559          * match.
560          */
561         if (template == NULL) return(0);
562
563         /* Null messages are bogus. */
564         if (msg == NULL) return(1);
565
566         for (i='A'; i<='Z'; ++i) {
567                 if (template->cm_fields[i] != NULL) {
568                         if (msg->cm_fields[i] == NULL) {
569                                 /* Considered equal if temmplate is empty string */
570                                 if (IsEmptyStr(template->cm_fields[i])) continue;
571                                 return 1;
572                         }
573                         if (strcasecmp(msg->cm_fields[i],
574                                 template->cm_fields[i])) return 1;
575                 }
576         }
577
578         /* All compares succeeded: we have a match! */
579         return 0;
580 }
581
582
583
584 /*
585  * Retrieve the "seen" message list for the current room.
586  */
587 void CtdlGetSeen(char *buf, int which_set) {
588         struct CitContext *CCC = CC;
589         visit vbuf;
590
591         /* Learn about the user and room in question */
592         CtdlGetRelationship(&vbuf, &CCC->user, &CCC->room);
593
594         if (which_set == ctdlsetseen_seen)
595                 safestrncpy(buf, vbuf.v_seen, SIZ);
596         if (which_set == ctdlsetseen_answered)
597                 safestrncpy(buf, vbuf.v_answered, SIZ);
598 }
599
600
601
602 /*
603  * Manipulate the "seen msgs" string (or other message set strings)
604  */
605 void CtdlSetSeen(long *target_msgnums, int num_target_msgnums,
606                 int target_setting, int which_set,
607                 struct ctdluser *which_user, struct ctdlroom *which_room) {
608         struct CitContext *CCC = CC;
609         struct cdbdata *cdbfr;
610         int i, k;
611         int is_seen = 0;
612         int was_seen = 0;
613         long lo = (-1L);
614         long hi = (-1L); /// TODO: we just write here. y?
615         visit vbuf;
616         long *msglist;
617         int num_msgs = 0;
618         StrBuf *vset;
619         StrBuf *setstr;
620         StrBuf *lostr;
621         StrBuf *histr;
622         const char *pvset;
623         char *is_set;   /* actually an array of booleans */
624
625         /* Don't bother doing *anything* if we were passed a list of zero messages */
626         if (num_target_msgnums < 1) {
627                 return;
628         }
629
630         /* If no room was specified, we go with the current room. */
631         if (!which_room) {
632                 which_room = &CCC->room;
633         }
634
635         /* If no user was specified, we go with the current user. */
636         if (!which_user) {
637                 which_user = &CCC->user;
638         }
639
640         MSG_syslog(LOG_DEBUG, "CtdlSetSeen(%d msgs starting with %ld, %s, %d) in <%s>\n",
641                    num_target_msgnums, target_msgnums[0],
642                    (target_setting ? "SET" : "CLEAR"),
643                    which_set,
644                    which_room->QRname);
645
646         /* Learn about the user and room in question */
647         CtdlGetRelationship(&vbuf, which_user, which_room);
648
649         /* Load the message list */
650         cdbfr = cdb_fetch(CDB_MSGLISTS, &which_room->QRnumber, sizeof(long));
651         if (cdbfr != NULL) {
652                 msglist = (long *) cdbfr->ptr;
653                 cdbfr->ptr = NULL;      /* CtdlSetSeen() now owns this memory */
654                 num_msgs = cdbfr->len / sizeof(long);
655                 cdb_free(cdbfr);
656         } else {
657                 return; /* No messages at all?  No further action. */
658         }
659
660         is_set = malloc(num_msgs * sizeof(char));
661         memset(is_set, 0, (num_msgs * sizeof(char)) );
662
663         /* Decide which message set we're manipulating */
664         switch(which_set) {
665         case ctdlsetseen_seen:
666                 vset = NewStrBufPlain(vbuf.v_seen, -1);
667                 break;
668         case ctdlsetseen_answered:
669                 vset = NewStrBufPlain(vbuf.v_answered, -1);
670                 break;
671         default:
672                 vset = NewStrBuf();
673         }
674
675
676 #if 0   /* This is a special diagnostic section.  Do not allow it to run during normal operation. */
677         MSG_syslog(LOG_DEBUG, "There are %d messages in the room.\n", num_msgs);
678         for (i=0; i<num_msgs; ++i) {
679                 if ((i > 0) && (msglist[i] <= msglist[i-1])) abort();
680         }
681         MSG_syslog(LOG_DEBUG, "We are twiddling %d of them.\n", num_target_msgnums);
682         for (k=0; k<num_target_msgnums; ++k) {
683                 if ((k > 0) && (target_msgnums[k] <= target_msgnums[k-1])) abort();
684         }
685 #endif
686
687         MSG_syslog(LOG_DEBUG, "before update: %s\n", ChrPtr(vset));
688
689         /* Translate the existing sequence set into an array of booleans */
690         setstr = NewStrBuf();
691         lostr = NewStrBuf();
692         histr = NewStrBuf();
693         pvset = NULL;
694         while (StrBufExtract_NextToken(setstr, vset, &pvset, ',') >= 0) {
695
696                 StrBufExtract_token(lostr, setstr, 0, ':');
697                 if (StrBufNum_tokens(setstr, ':') >= 2) {
698                         StrBufExtract_token(histr, setstr, 1, ':');
699                 }
700                 else {
701                         FlushStrBuf(histr);
702                         StrBufAppendBuf(histr, lostr, 0);
703                 }
704                 lo = StrTol(lostr);
705                 if (!strcmp(ChrPtr(histr), "*")) {
706                         hi = LONG_MAX;
707                 }
708                 else {
709                         hi = StrTol(histr);
710                 }
711
712                 for (i = 0; i < num_msgs; ++i) {
713                         if ((msglist[i] >= lo) && (msglist[i] <= hi)) {
714                                 is_set[i] = 1;
715                         }
716                 }
717         }
718         FreeStrBuf(&setstr);
719         FreeStrBuf(&lostr);
720         FreeStrBuf(&histr);
721
722
723         /* Now translate the array of booleans back into a sequence set */
724         FlushStrBuf(vset);
725         was_seen = 0;
726         lo = (-1);
727         hi = (-1);
728
729         for (i=0; i<num_msgs; ++i) {
730                 is_seen = is_set[i];
731
732                 /* Apply changes */
733                 for (k=0; k<num_target_msgnums; ++k) {
734                         if (msglist[i] == target_msgnums[k]) {
735                                 is_seen = target_setting;
736                         }
737                 }
738
739                 if ((was_seen == 0) && (is_seen == 1)) {
740                         lo = msglist[i];
741                 }
742                 else if ((was_seen == 1) && (is_seen == 0)) {
743                         hi = msglist[i-1];
744
745                         if (StrLength(vset) > 0) {
746                                 StrBufAppendBufPlain(vset, HKEY(","), 0);
747                         }
748                         if (lo == hi) {
749                                 StrBufAppendPrintf(vset, "%ld", hi);
750                         }
751                         else {
752                                 StrBufAppendPrintf(vset, "%ld:%ld", lo, hi);
753                         }
754                 }
755
756                 if ((is_seen) && (i == num_msgs - 1)) {
757                         if (StrLength(vset) > 0) {
758                                 StrBufAppendBufPlain(vset, HKEY(","), 0);
759                         }
760                         if ((i==0) || (was_seen == 0)) {
761                                 StrBufAppendPrintf(vset, "%ld", msglist[i]);
762                         }
763                         else {
764                                 StrBufAppendPrintf(vset, "%ld:%ld", lo, msglist[i]);
765                         }
766                 }
767
768                 was_seen = is_seen;
769         }
770
771         /*
772          * We will have to stuff this string back into a 4096 byte buffer, so if it's
773          * larger than that now, truncate it by removing tokens from the beginning.
774          * The limit of 100 iterations is there to prevent an infinite loop in case
775          * something unexpected happens.
776          */
777         int number_of_truncations = 0;
778         while ( (StrLength(vset) > SIZ) && (number_of_truncations < 100) ) {
779                 StrBufRemove_token(vset, 0, ',');
780                 ++number_of_truncations;
781         }
782
783         /*
784          * If we're truncating the sequence set of messages marked with the 'seen' flag,
785          * we want the earliest messages (the truncated ones) to be marked, not unmarked.
786          * Otherwise messages at the beginning will suddenly appear to be 'unseen'.
787          */
788         if ( (which_set == ctdlsetseen_seen) && (number_of_truncations > 0) ) {
789                 StrBuf *first_tok;
790                 first_tok = NewStrBuf();
791                 StrBufExtract_token(first_tok, vset, 0, ',');
792                 StrBufRemove_token(vset, 0, ',');
793
794                 if (StrBufNum_tokens(first_tok, ':') > 1) {
795                         StrBufRemove_token(first_tok, 0, ':');
796                 }
797                 
798                 StrBuf *new_set;
799                 new_set = NewStrBuf();
800                 StrBufAppendBufPlain(new_set, HKEY("1:"), 0);
801                 StrBufAppendBuf(new_set, first_tok, 0);
802                 StrBufAppendBufPlain(new_set, HKEY(":"), 0);
803                 StrBufAppendBuf(new_set, vset, 0);
804
805                 FreeStrBuf(&vset);
806                 FreeStrBuf(&first_tok);
807                 vset = new_set;
808         }
809
810         MSG_syslog(LOG_DEBUG, " after update: %s\n", ChrPtr(vset));
811
812         /* Decide which message set we're manipulating */
813         switch (which_set) {
814                 case ctdlsetseen_seen:
815                         safestrncpy(vbuf.v_seen, ChrPtr(vset), sizeof vbuf.v_seen);
816                         break;
817                 case ctdlsetseen_answered:
818                         safestrncpy(vbuf.v_answered, ChrPtr(vset), sizeof vbuf.v_answered);
819                         break;
820         }
821
822         free(is_set);
823         free(msglist);
824         CtdlSetRelationship(&vbuf, which_user, which_room);
825         FreeStrBuf(&vset);
826 }
827
828
829 /*
830  * API function to perform an operation for each qualifying message in the
831  * current room.  (Returns the number of messages processed.)
832  */
833 int CtdlForEachMessage(int mode, long ref, char *search_string,
834                         char *content_type,
835                         struct CtdlMessage *compare,
836                         ForEachMsgCallback CallBack,
837                         void *userdata)
838 {
839         struct CitContext *CCC = CC;
840         int a, i, j;
841         visit vbuf;
842         struct cdbdata *cdbfr;
843         long *msglist = NULL;
844         int num_msgs = 0;
845         int num_processed = 0;
846         long thismsg;
847         struct MetaData smi;
848         struct CtdlMessage *msg = NULL;
849         int is_seen = 0;
850         long lastold = 0L;
851         int printed_lastold = 0;
852         int num_search_msgs = 0;
853         long *search_msgs = NULL;
854         regex_t re;
855         int need_to_free_re = 0;
856         regmatch_t pm;
857
858         if ((content_type) && (!IsEmptyStr(content_type))) {
859                 regcomp(&re, content_type, 0);
860                 need_to_free_re = 1;
861         }
862
863         /* Learn about the user and room in question */
864         if (server_shutting_down) {
865                 if (need_to_free_re) regfree(&re);
866                 return -1;
867         }
868         CtdlGetUser(&CCC->user, CCC->curr_user);
869
870         if (server_shutting_down) {
871                 if (need_to_free_re) regfree(&re);
872                 return -1;
873         }
874         CtdlGetRelationship(&vbuf, &CCC->user, &CCC->room);
875
876         if (server_shutting_down) {
877                 if (need_to_free_re) regfree(&re);
878                 return -1;
879         }
880
881         /* Load the message list */
882         cdbfr = cdb_fetch(CDB_MSGLISTS, &CCC->room.QRnumber, sizeof(long));
883         if (cdbfr == NULL) {
884                 if (need_to_free_re) regfree(&re);
885                 return 0;       /* No messages at all?  No further action. */
886         }
887
888         msglist = (long *) cdbfr->ptr;
889         num_msgs = cdbfr->len / sizeof(long);
890
891         cdbfr->ptr = NULL;      /* clear this so that cdb_free() doesn't free it */
892         cdb_free(cdbfr);        /* we own this memory now */
893
894         /*
895          * Now begin the traversal.
896          */
897         if (num_msgs > 0) for (a = 0; a < num_msgs; ++a) {
898
899                 /* If the caller is looking for a specific MIME type, filter
900                  * out all messages which are not of the type requested.
901                  */
902                 if ((content_type != NULL) && (!IsEmptyStr(content_type))) {
903
904                         /* This call to GetMetaData() sits inside this loop
905                          * so that we only do the extra database read per msg
906                          * if we need to.  Doing the extra read all the time
907                          * really kills the server.  If we ever need to use
908                          * metadata for another search criterion, we need to
909                          * move the read somewhere else -- but still be smart
910                          * enough to only do the read if the caller has
911                          * specified something that will need it.
912                          */
913                         if (server_shutting_down) {
914                                 if (need_to_free_re) regfree(&re);
915                                 free(msglist);
916                                 return -1;
917                         }
918                         GetMetaData(&smi, msglist[a]);
919
920                         /* if (strcasecmp(smi.meta_content_type, content_type)) { old non-regex way */
921                         if (regexec(&re, smi.meta_content_type, 1, &pm, 0) != 0) {
922                                 msglist[a] = 0L;
923                         }
924                 }
925         }
926
927         num_msgs = sort_msglist(msglist, num_msgs);
928
929         /* If a template was supplied, filter out the messages which
930          * don't match.  (This could induce some delays!)
931          */
932         if (num_msgs > 0) {
933                 if (compare != NULL) {
934                         for (a = 0; a < num_msgs; ++a) {
935                                 if (server_shutting_down) {
936                                         if (need_to_free_re) regfree(&re);
937                                         free(msglist);
938                                         return -1;
939                                 }
940                                 msg = CtdlFetchMessage(msglist[a], 1);
941                                 if (msg != NULL) {
942                                         if (CtdlMsgCmp(msg, compare)) {
943                                                 msglist[a] = 0L;
944                                         }
945                                         CM_Free(msg);
946                                 }
947                         }
948                 }
949         }
950
951         /* If a search string was specified, get a message list from
952          * the full text index and remove messages which aren't on both
953          * lists.
954          *
955          * How this works:
956          * Since the lists are sorted and strictly ascending, and the
957          * output list is guaranteed to be shorter than or equal to the
958          * input list, we overwrite the bottom of the input list.  This
959          * eliminates the need to memmove big chunks of the list over and
960          * over again.
961          */
962         if ( (num_msgs > 0) && (mode == MSGS_SEARCH) && (search_string) ) {
963
964                 /* Call search module via hook mechanism.
965                  * NULL means use any search function available.
966                  * otherwise replace with a char * to name of search routine
967                  */
968                 CtdlModuleDoSearch(&num_search_msgs, &search_msgs, search_string, "fulltext");
969
970                 if (num_search_msgs > 0) {
971         
972                         int orig_num_msgs;
973
974                         orig_num_msgs = num_msgs;
975                         num_msgs = 0;
976                         for (i=0; i<orig_num_msgs; ++i) {
977                                 for (j=0; j<num_search_msgs; ++j) {
978                                         if (msglist[i] == search_msgs[j]) {
979                                                 msglist[num_msgs++] = msglist[i];
980                                         }
981                                 }
982                         }
983                 }
984                 else {
985                         num_msgs = 0;   /* No messages qualify */
986                 }
987                 if (search_msgs != NULL) free(search_msgs);
988
989                 /* Now that we've purged messages which don't contain the search
990                  * string, treat a MSGS_SEARCH just like a MSGS_ALL from this
991                  * point on.
992                  */
993                 mode = MSGS_ALL;
994         }
995
996         /*
997          * Now iterate through the message list, according to the
998          * criteria supplied by the caller.
999          */
1000         if (num_msgs > 0)
1001                 for (a = 0; a < num_msgs; ++a) {
1002                         if (server_shutting_down) {
1003                                 if (need_to_free_re) regfree(&re);
1004                                 free(msglist);
1005                                 return num_processed;
1006                         }
1007                         thismsg = msglist[a];
1008                         if (mode == MSGS_ALL) {
1009                                 is_seen = 0;
1010                         }
1011                         else {
1012                                 is_seen = is_msg_in_sequence_set(
1013                                                         vbuf.v_seen, thismsg);
1014                                 if (is_seen) lastold = thismsg;
1015                         }
1016                         if ((thismsg > 0L)
1017                             && (
1018
1019                                        (mode == MSGS_ALL)
1020                                        || ((mode == MSGS_OLD) && (is_seen))
1021                                        || ((mode == MSGS_NEW) && (!is_seen))
1022                                        || ((mode == MSGS_LAST) && (a >= (num_msgs - ref)))
1023                                    || ((mode == MSGS_FIRST) && (a < ref))
1024                                 || ((mode == MSGS_GT) && (thismsg > ref))
1025                                 || ((mode == MSGS_LT) && (thismsg < ref))
1026                                 || ((mode == MSGS_EQ) && (thismsg == ref))
1027                             )
1028                             ) {
1029                                 if ((mode == MSGS_NEW) && (CCC->user.flags & US_LASTOLD) && (lastold > 0L) && (printed_lastold == 0) && (!is_seen)) {
1030                                         if (CallBack)
1031                                                 CallBack(lastold, userdata);
1032                                         printed_lastold = 1;
1033                                         ++num_processed;
1034                                 }
1035                                 if (CallBack) CallBack(thismsg, userdata);
1036                                 ++num_processed;
1037                         }
1038                 }
1039         if (need_to_free_re) regfree(&re);
1040
1041         /*
1042          * We cache the most recent msglist in order to do security checks later
1043          */
1044         if (CCC->client_socket > 0) {
1045                 if (CCC->cached_msglist != NULL) {
1046                         free(CCC->cached_msglist);
1047                 }
1048                 CCC->cached_msglist = msglist;
1049                 CCC->cached_num_msgs = num_msgs;
1050         }
1051         else {
1052                 free(msglist);
1053         }
1054
1055         return num_processed;
1056 }
1057
1058
1059
1060 /*
1061  * cmd_msgs()  -  get list of message #'s in this room
1062  *              implements the MSGS server command using CtdlForEachMessage()
1063  */
1064 void cmd_msgs(char *cmdbuf)
1065 {
1066         int mode = 0;
1067         char which[16];
1068         char buf[256];
1069         char tfield[256];
1070         char tvalue[256];
1071         int cm_ref = 0;
1072         int i;
1073         int with_template = 0;
1074         struct CtdlMessage *template = NULL;
1075         char search_string[1024];
1076         ForEachMsgCallback CallBack;
1077
1078         if (CtdlAccessCheck(ac_logged_in_or_guest)) return;
1079
1080         extract_token(which, cmdbuf, 0, '|', sizeof which);
1081         cm_ref = extract_int(cmdbuf, 1);
1082         extract_token(search_string, cmdbuf, 1, '|', sizeof search_string);
1083         with_template = extract_int(cmdbuf, 2);
1084         switch (extract_int(cmdbuf, 3))
1085         {
1086         default:
1087         case MSG_HDRS_BRIEF:
1088                 CallBack = simple_listing;
1089                 break;
1090         case MSG_HDRS_ALL:
1091                 CallBack = headers_listing;
1092                 break;
1093         case MSG_HDRS_EUID:
1094                 CallBack = headers_euid;
1095                 break;
1096         }
1097
1098         strcat(which, "   ");
1099         if (!strncasecmp(which, "OLD", 3))
1100                 mode = MSGS_OLD;
1101         else if (!strncasecmp(which, "NEW", 3))
1102                 mode = MSGS_NEW;
1103         else if (!strncasecmp(which, "FIRST", 5))
1104                 mode = MSGS_FIRST;
1105         else if (!strncasecmp(which, "LAST", 4))
1106                 mode = MSGS_LAST;
1107         else if (!strncasecmp(which, "GT", 2))
1108                 mode = MSGS_GT;
1109         else if (!strncasecmp(which, "LT", 2))
1110                 mode = MSGS_LT;
1111         else if (!strncasecmp(which, "SEARCH", 6))
1112                 mode = MSGS_SEARCH;
1113         else
1114                 mode = MSGS_ALL;
1115
1116         if ( (mode == MSGS_SEARCH) && (!config.c_enable_fulltext) ) {
1117                 cprintf("%d Full text index is not enabled on this server.\n",
1118                         ERROR + CMD_NOT_SUPPORTED);
1119                 return;
1120         }
1121
1122         if (with_template) {
1123                 unbuffer_output();
1124                 cprintf("%d Send template then receive message list\n",
1125                         START_CHAT_MODE);
1126                 template = (struct CtdlMessage *)
1127                         malloc(sizeof(struct CtdlMessage));
1128                 memset(template, 0, sizeof(struct CtdlMessage));
1129                 template->cm_magic = CTDLMESSAGE_MAGIC;
1130                 template->cm_anon_type = MES_NORMAL;
1131
1132                 while(client_getln(buf, sizeof buf) >= 0 && strcmp(buf,"000")) {
1133                         long tValueLen;
1134                         extract_token(tfield, buf, 0, '|', sizeof tfield);
1135                         tValueLen = extract_token(tvalue, buf, 1, '|', sizeof tvalue);
1136                         for (i='A'; i<='Z'; ++i) if (msgkeys[i]!=NULL) {
1137                                 if (!strcasecmp(tfield, msgkeys[i])) {
1138                                         CM_SetField(template, i, tvalue, tValueLen);
1139                                 }
1140                         }
1141                 }
1142                 buffer_output();
1143         }
1144         else {
1145                 cprintf("%d  \n", LISTING_FOLLOWS);
1146         }
1147
1148         CtdlForEachMessage(mode,
1149                            ( (mode == MSGS_SEARCH) ? 0 : cm_ref ),
1150                            ( (mode == MSGS_SEARCH) ? search_string : NULL ),
1151                            NULL,
1152                            template,
1153                            CallBack,
1154                            NULL);
1155         if (template != NULL) CM_Free(template);
1156         cprintf("000\n");
1157 }
1158
1159
1160 /*
1161  * memfmout()  -  Citadel text formatter and paginator.
1162  *           Although the original purpose of this routine was to format
1163  *           text to the reader's screen width, all we're really using it
1164  *           for here is to format text out to 80 columns before sending it
1165  *           to the client.  The client software may reformat it again.
1166  */
1167 void memfmout(
1168         char *mptr,             /* where are we going to get our text from? */
1169         const char *nl          /* string to terminate lines with */
1170 ) {
1171         struct CitContext *CCC = CC;
1172         int column = 0;
1173         unsigned char ch = 0;
1174         char outbuf[1024];
1175         int len = 0;
1176         int nllen = 0;
1177
1178         if (!mptr) return;
1179         nllen = strlen(nl);
1180         while (ch=*(mptr++), ch != 0) {
1181
1182                 if (ch == '\n') {
1183                         if (client_write(outbuf, len) == -1)
1184                         {
1185                                 MSGM_syslog(LOG_ERR, "memfmout(): aborting due to write failure.\n");
1186                                 return;
1187                         }
1188                         len = 0;
1189                         if (client_write(nl, nllen) == -1)
1190                         {
1191                                 MSGM_syslog(LOG_ERR, "memfmout(): aborting due to write failure.\n");
1192                                 return;
1193                         }
1194                         column = 0;
1195                 }
1196                 else if (ch == '\r') {
1197                         /* Ignore carriage returns.  Newlines are always LF or CRLF but never CR. */
1198                 }
1199                 else if (isspace(ch)) {
1200                         if (column > 72) {              /* Beyond 72 columns, break on the next space */
1201                                 if (client_write(outbuf, len) == -1)
1202                                 {
1203                                         MSGM_syslog(LOG_ERR, "memfmout(): aborting due to write failure.\n");
1204                                         return;
1205                                 }
1206                                 len = 0;
1207                                 if (client_write(nl, nllen) == -1)
1208                                 {
1209                                         MSGM_syslog(LOG_ERR, "memfmout(): aborting due to write failure.\n");
1210                                         return;
1211                                 }
1212                                 column = 0;
1213                         }
1214                         else {
1215                                 outbuf[len++] = ch;
1216                                 ++column;
1217                         }
1218                 }
1219                 else {
1220                         outbuf[len++] = ch;
1221                         ++column;
1222                         if (column > 1000) {            /* Beyond 1000 columns, break anywhere */
1223                                 if (client_write(outbuf, len) == -1)
1224                                 {
1225                                         MSGM_syslog(LOG_ERR, "memfmout(): aborting due to write failure.\n");
1226                                         return;
1227                                 }
1228                                 len = 0;
1229                                 if (client_write(nl, nllen) == -1)
1230                                 {
1231                                         MSGM_syslog(LOG_ERR, "memfmout(): aborting due to write failure.\n");
1232                                         return;
1233                                 }
1234                                 column = 0;
1235                         }
1236                 }
1237         }
1238         if (len) {
1239                 if (client_write(outbuf, len) == -1)
1240                 {
1241                         MSGM_syslog(LOG_ERR, "memfmout(): aborting due to write failure.\n");
1242                         return;
1243                 }
1244                 len = 0;
1245                 client_write(nl, nllen);
1246                 column = 0;
1247         }
1248 }
1249
1250
1251
1252 /*
1253  * Callback function for mime parser that simply lists the part
1254  */
1255 void list_this_part(char *name, char *filename, char *partnum, char *disp,
1256                     void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
1257                     char *cbid, void *cbuserdata)
1258 {
1259         struct ma_info *ma;
1260         
1261         ma = (struct ma_info *)cbuserdata;
1262         if (ma->is_ma == 0) {
1263                 cprintf("part=%s|%s|%s|%s|%s|%ld|%s|%s\n",
1264                         name, 
1265                         filename, 
1266                         partnum, 
1267                         disp, 
1268                         cbtype, 
1269                         (long)length, 
1270                         cbid, 
1271                         cbcharset);
1272         }
1273 }
1274
1275 /* 
1276  * Callback function for multipart prefix
1277  */
1278 void list_this_pref(char *name, char *filename, char *partnum, char *disp,
1279                     void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
1280                     char *cbid, void *cbuserdata)
1281 {
1282         struct ma_info *ma;
1283         
1284         ma = (struct ma_info *)cbuserdata;
1285         if (!strcasecmp(cbtype, "multipart/alternative")) {
1286                 ++ma->is_ma;
1287         }
1288
1289         if (ma->is_ma == 0) {
1290                 cprintf("pref=%s|%s\n", partnum, cbtype);
1291         }
1292 }
1293
1294 /* 
1295  * Callback function for multipart sufffix
1296  */
1297 void list_this_suff(char *name, char *filename, char *partnum, char *disp,
1298                     void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
1299                     char *cbid, void *cbuserdata)
1300 {
1301         struct ma_info *ma;
1302         
1303         ma = (struct ma_info *)cbuserdata;
1304         if (ma->is_ma == 0) {
1305                 cprintf("suff=%s|%s\n", partnum, cbtype);
1306         }
1307         if (!strcasecmp(cbtype, "multipart/alternative")) {
1308                 --ma->is_ma;
1309         }
1310 }
1311
1312
1313 /*
1314  * Callback function for mime parser that opens a section for downloading
1315  */
1316 void mime_download(char *name, char *filename, char *partnum, char *disp,
1317                    void *content, char *cbtype, char *cbcharset, size_t length,
1318                    char *encoding, char *cbid, void *cbuserdata)
1319 {
1320         int rv = 0;
1321         CitContext *CCC = MyContext();
1322
1323         /* Silently go away if there's already a download open. */
1324         if (CCC->download_fp != NULL)
1325                 return;
1326
1327         if (
1328                 (!IsEmptyStr(partnum) && (!strcasecmp(CCC->download_desired_section, partnum)))
1329         ||      (!IsEmptyStr(cbid) && (!strcasecmp(CCC->download_desired_section, cbid)))
1330         ) {
1331                 CCC->download_fp = tmpfile();
1332                 if (CCC->download_fp == NULL) {
1333                         MSG_syslog(LOG_EMERG, "mime_download(): Couldn't write: %s\n",
1334                                     strerror(errno));
1335                         cprintf("%d cannot open temporary file: %s\n",
1336                                 ERROR + INTERNAL_ERROR, strerror(errno));
1337                         return;
1338                 }
1339         
1340                 rv = fwrite(content, length, 1, CCC->download_fp);
1341                 if (rv <= 0) {
1342                         MSG_syslog(LOG_EMERG, "mime_download(): Couldn't write: %s\n",
1343                                    strerror(errno));
1344                         cprintf("%d unable to write tempfile.\n",
1345                                 ERROR + TOO_BIG);
1346                         fclose(CCC->download_fp);
1347                         CCC->download_fp = NULL;
1348                         return;
1349                 }
1350                 fflush(CCC->download_fp);
1351                 rewind(CCC->download_fp);
1352         
1353                 OpenCmdResult(filename, cbtype);
1354         }
1355 }
1356
1357
1358
1359 /*
1360  * Callback function for mime parser that outputs a section all at once.
1361  * We can specify the desired section by part number *or* content-id.
1362  */
1363 void mime_spew_section(char *name, char *filename, char *partnum, char *disp,
1364                    void *content, char *cbtype, char *cbcharset, size_t length,
1365                    char *encoding, char *cbid, void *cbuserdata)
1366 {
1367         int *found_it = (int *)cbuserdata;
1368
1369         if (
1370                 (!IsEmptyStr(partnum) && (!strcasecmp(CC->download_desired_section, partnum)))
1371         ||      (!IsEmptyStr(cbid) && (!strcasecmp(CC->download_desired_section, cbid)))
1372         ) {
1373                 *found_it = 1;
1374                 cprintf("%d %d|-1|%s|%s|%s\n",
1375                         BINARY_FOLLOWS,
1376                         (int)length,
1377                         filename,
1378                         cbtype,
1379                         cbcharset
1380                 );
1381                 client_write(content, length);
1382         }
1383 }
1384
1385
1386 /*
1387  * Load a message from disk into memory.
1388  * This is used by CtdlOutputMsg() and other fetch functions.
1389  *
1390  * NOTE: Caller is responsible for freeing the returned CtdlMessage struct
1391  *       using the CtdlMessageFree() function.
1392  */
1393 struct CtdlMessage *CtdlFetchMessage(long msgnum, int with_body)
1394 {
1395         struct CitContext *CCC = CC;
1396         struct cdbdata *dmsgtext;
1397         struct CtdlMessage *ret = NULL;
1398         char *mptr;
1399         char *upper_bound;
1400         cit_uint8_t ch;
1401         cit_uint8_t field_header;
1402
1403         MSG_syslog(LOG_DEBUG, "CtdlFetchMessage(%ld, %d)\n", msgnum, with_body);
1404         dmsgtext = cdb_fetch(CDB_MSGMAIN, &msgnum, sizeof(long));
1405         if (dmsgtext == NULL) {
1406                 MSG_syslog(LOG_ERR, "CtdlFetchMessage(%ld, %d) Failed!\n", msgnum, with_body);
1407                 return NULL;
1408         }
1409         mptr = dmsgtext->ptr;
1410         upper_bound = mptr + dmsgtext->len;
1411
1412         /* Parse the three bytes that begin EVERY message on disk.
1413          * The first is always 0xFF, the on-disk magic number.
1414          * The second is the anonymous/public type byte.
1415          * The third is the format type byte (vari, fixed, or MIME).
1416          */
1417         ch = *mptr++;
1418         if (ch != 255) {
1419                 MSG_syslog(LOG_ERR, "Message %ld appears to be corrupted.\n", msgnum);
1420                 cdb_free(dmsgtext);
1421                 return NULL;
1422         }
1423         ret = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
1424         memset(ret, 0, sizeof(struct CtdlMessage));
1425
1426         ret->cm_magic = CTDLMESSAGE_MAGIC;
1427         ret->cm_anon_type = *mptr++;    /* Anon type byte */
1428         ret->cm_format_type = *mptr++;  /* Format type byte */
1429
1430         /*
1431          * The rest is zero or more arbitrary fields.  Load them in.
1432          * We're done when we encounter either a zero-length field or
1433          * have just processed the 'M' (message text) field.
1434          */
1435         do {
1436                 long len;
1437                 if (mptr >= upper_bound) {
1438                         break;
1439                 }
1440                 field_header = *mptr++;
1441                 len = strlen(mptr);
1442                 CM_SetField(ret, field_header, mptr, len);
1443
1444                 mptr += len + 1;        /* advance to next field */
1445
1446         } while ((mptr < upper_bound) && (field_header != 'M'));
1447
1448         cdb_free(dmsgtext);
1449
1450         /* Always make sure there's something in the msg text field.  If
1451          * it's NULL, the message text is most likely stored separately,
1452          * so go ahead and fetch that.  Failing that, just set a dummy
1453          * body so other code doesn't barf.
1454          */
1455         if ( (CM_IsEmpty(ret, eMesageText)) && (with_body) ) {
1456                 dmsgtext = cdb_fetch(CDB_BIGMSGS, &msgnum, sizeof(long));
1457                 if (dmsgtext != NULL) {
1458                         CM_SetAsField(ret, eMesageText, &dmsgtext->ptr, dmsgtext->len);
1459                         cdb_free(dmsgtext);
1460                 }
1461         }
1462         if (CM_IsEmpty(ret, eMesageText)) {
1463                 CM_SetField(ret, eMesageText, HKEY("\r\n\r\n (no text)\r\n"));
1464         }
1465
1466         /* Perform "before read" hooks (aborting if any return nonzero) */
1467         if (PerformMessageHooks(ret, EVT_BEFOREREAD) > 0) {
1468                 CM_Free(ret);
1469                 return NULL;
1470         }
1471
1472         return (ret);
1473 }
1474
1475
1476
1477 /*
1478  * Pre callback function for multipart/alternative
1479  *
1480  * NOTE: this differs from the standard behavior for a reason.  Normally when
1481  *       displaying multipart/alternative you want to show the _last_ usable
1482  *       format in the message.  Here we show the _first_ one, because it's
1483  *       usually text/plain.  Since this set of functions is designed for text
1484  *       output to non-MIME-aware clients, this is the desired behavior.
1485  *
1486  */
1487 void fixed_output_pre(char *name, char *filename, char *partnum, char *disp,
1488                 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
1489                 char *cbid, void *cbuserdata)
1490 {
1491         struct CitContext *CCC = CC;
1492         struct ma_info *ma;
1493         
1494         ma = (struct ma_info *)cbuserdata;
1495         MSG_syslog(LOG_DEBUG, "fixed_output_pre() type=<%s>\n", cbtype);        
1496         if (!strcasecmp(cbtype, "multipart/alternative")) {
1497                 ++ma->is_ma;
1498                 ma->did_print = 0;
1499         }
1500         if (!strcasecmp(cbtype, "message/rfc822")) {
1501                 ++ma->freeze;
1502         }
1503 }
1504
1505 /*
1506  * Post callback function for multipart/alternative
1507  */
1508 void fixed_output_post(char *name, char *filename, char *partnum, char *disp,
1509                 void *content, char *cbtype, char *cbcharset, size_t length,
1510                 char *encoding, char *cbid, void *cbuserdata)
1511 {
1512         struct CitContext *CCC = CC;
1513         struct ma_info *ma;
1514         
1515         ma = (struct ma_info *)cbuserdata;
1516         MSG_syslog(LOG_DEBUG, "fixed_output_post() type=<%s>\n", cbtype);       
1517         if (!strcasecmp(cbtype, "multipart/alternative")) {
1518                 --ma->is_ma;
1519                 ma->did_print = 0;
1520         }
1521         if (!strcasecmp(cbtype, "message/rfc822")) {
1522                 --ma->freeze;
1523         }
1524 }
1525
1526 /*
1527  * Inline callback function for mime parser that wants to display text
1528  */
1529 void fixed_output(char *name, char *filename, char *partnum, char *disp,
1530                 void *content, char *cbtype, char *cbcharset, size_t length,
1531                 char *encoding, char *cbid, void *cbuserdata)
1532 {
1533         struct CitContext *CCC = CC;
1534         char *ptr;
1535         char *wptr;
1536         size_t wlen;
1537         struct ma_info *ma;
1538
1539         ma = (struct ma_info *)cbuserdata;
1540
1541         MSG_syslog(LOG_DEBUG,
1542                 "fixed_output() part %s: %s (%s) (%ld bytes)\n",
1543                 partnum, filename, cbtype, (long)length);
1544
1545         /*
1546          * If we're in the middle of a multipart/alternative scope and
1547          * we've already printed another section, skip this one.
1548          */     
1549         if ( (ma->is_ma) && (ma->did_print) ) {
1550                 MSG_syslog(LOG_DEBUG, "Skipping part %s (%s)\n", partnum, cbtype);
1551                 return;
1552         }
1553         ma->did_print = 1;
1554
1555         if ( (!strcasecmp(cbtype, "text/plain")) 
1556            || (IsEmptyStr(cbtype)) ) {
1557                 wptr = content;
1558                 if (length > 0) {
1559                         client_write(wptr, length);
1560                         if (wptr[length-1] != '\n') {
1561                                 cprintf("\n");
1562                         }
1563                 }
1564                 return;
1565         }
1566
1567         if (!strcasecmp(cbtype, "text/html")) {
1568                 ptr = html_to_ascii(content, length, 80, 0);
1569                 wlen = strlen(ptr);
1570                 client_write(ptr, wlen);
1571                 if ((wlen > 0) && (ptr[wlen-1] != '\n')) {
1572                         cprintf("\n");
1573                 }
1574                 free(ptr);
1575                 return;
1576         }
1577
1578         if (ma->use_fo_hooks) {
1579                 if (PerformFixedOutputHooks(cbtype, content, length)) {
1580                 /* above function returns nonzero if it handled the part */
1581                         return;
1582                 }
1583         }
1584
1585         if (strncasecmp(cbtype, "multipart/", 10)) {
1586                 cprintf("Part %s: %s (%s) (%ld bytes)\r\n",
1587                         partnum, filename, cbtype, (long)length);
1588                 return;
1589         }
1590 }
1591
1592 /*
1593  * The client is elegant and sophisticated and wants to be choosy about
1594  * MIME content types, so figure out which multipart/alternative part
1595  * we're going to send.
1596  *
1597  * We use a system of weights.  When we find a part that matches one of the
1598  * MIME types we've declared as preferential, we can store it in ma->chosen_part
1599  * and then set ma->chosen_pref to that MIME type's position in our preference
1600  * list.  If we then hit another match, we only replace the first match if
1601  * the preference value is lower.
1602  */
1603 void choose_preferred(char *name, char *filename, char *partnum, char *disp,
1604                 void *content, char *cbtype, char *cbcharset, size_t length,
1605                 char *encoding, char *cbid, void *cbuserdata)
1606 {
1607         struct CitContext *CCC = CC;
1608         char buf[1024];
1609         int i;
1610         struct ma_info *ma;
1611         
1612         ma = (struct ma_info *)cbuserdata;
1613
1614         // NOTE: REMOVING THIS CONDITIONAL FIXES BUG 220
1615         //       http://bugzilla.citadel.org/show_bug.cgi?id=220
1616         // I don't know if there are any side effects!  Please TEST TEST TEST
1617         //if (ma->is_ma > 0) {
1618
1619         for (i=0; i<num_tokens(CCC->preferred_formats, '|'); ++i) {
1620                 extract_token(buf, CCC->preferred_formats, i, '|', sizeof buf);
1621                 if ( (!strcasecmp(buf, cbtype)) && (!ma->freeze) ) {
1622                         if (i < ma->chosen_pref) {
1623                                 MSG_syslog(LOG_DEBUG, "Setting chosen part: <%s>\n", partnum);
1624                                 safestrncpy(ma->chosen_part, partnum, sizeof ma->chosen_part);
1625                                 ma->chosen_pref = i;
1626                         }
1627                 }
1628         }
1629 }
1630
1631 /*
1632  * Now that we've chosen our preferred part, output it.
1633  */
1634 void output_preferred(char *name, 
1635                       char *filename, 
1636                       char *partnum, 
1637                       char *disp,
1638                       void *content, 
1639                       char *cbtype, 
1640                       char *cbcharset, 
1641                       size_t length,
1642                       char *encoding, 
1643                       char *cbid, 
1644                       void *cbuserdata)
1645 {
1646         struct CitContext *CCC = CC;
1647         int i;
1648         char buf[128];
1649         int add_newline = 0;
1650         char *text_content;
1651         struct ma_info *ma;
1652         char *decoded = NULL;
1653         size_t bytes_decoded;
1654         int rc = 0;
1655
1656         ma = (struct ma_info *)cbuserdata;
1657
1658         /* This is not the MIME part you're looking for... */
1659         if (strcasecmp(partnum, ma->chosen_part)) return;
1660
1661         /* If the content-type of this part is in our preferred formats
1662          * list, we can simply output it verbatim.
1663          */
1664         for (i=0; i<num_tokens(CCC->preferred_formats, '|'); ++i) {
1665                 extract_token(buf, CCC->preferred_formats, i, '|', sizeof buf);
1666                 if (!strcasecmp(buf, cbtype)) {
1667                         /* Yeah!  Go!  W00t!! */
1668                         if (ma->dont_decode == 0) 
1669                                 rc = mime_decode_now (content, 
1670                                                       length,
1671                                                       encoding,
1672                                                       &decoded,
1673                                                       &bytes_decoded);
1674                         if (rc < 0)
1675                                 break; /* Give us the chance, maybe theres another one. */
1676
1677                         if (rc == 0) text_content = (char *)content;
1678                         else {
1679                                 text_content = decoded;
1680                                 length = bytes_decoded;
1681                         }
1682
1683                         if (text_content[length-1] != '\n') {
1684                                 ++add_newline;
1685                         }
1686                         cprintf("Content-type: %s", cbtype);
1687                         if (!IsEmptyStr(cbcharset)) {
1688                                 cprintf("; charset=%s", cbcharset);
1689                         }
1690                         cprintf("\nContent-length: %d\n",
1691                                 (int)(length + add_newline) );
1692                         if (!IsEmptyStr(encoding)) {
1693                                 cprintf("Content-transfer-encoding: %s\n", encoding);
1694                         }
1695                         else {
1696                                 cprintf("Content-transfer-encoding: 7bit\n");
1697                         }
1698                         cprintf("X-Citadel-MSG4-Partnum: %s\n", partnum);
1699                         cprintf("\n");
1700                         if (client_write(text_content, length) == -1)
1701                         {
1702                                 MSGM_syslog(LOG_ERR, "output_preferred(): aborting due to write failure.\n");
1703                                 return;
1704                         }
1705                         if (add_newline) cprintf("\n");
1706                         if (decoded != NULL) free(decoded);
1707                         return;
1708                 }
1709         }
1710
1711         /* No translations required or possible: output as text/plain */
1712         cprintf("Content-type: text/plain\n\n");
1713         rc = 0;
1714         if (ma->dont_decode == 0)
1715                 rc = mime_decode_now (content, 
1716                                       length,
1717                                       encoding,
1718                                       &decoded,
1719                                       &bytes_decoded);
1720         if (rc < 0)
1721                 return; /* Give us the chance, maybe theres another one. */
1722         
1723         if (rc == 0) text_content = (char *)content;
1724         else {
1725                 text_content = decoded;
1726                 length = bytes_decoded;
1727         }
1728
1729         fixed_output(name, filename, partnum, disp, text_content, cbtype, cbcharset,
1730                         length, encoding, cbid, cbuserdata);
1731         if (decoded != NULL) free(decoded);
1732 }
1733
1734
1735 struct encapmsg {
1736         char desired_section[64];
1737         char *msg;
1738         size_t msglen;
1739 };
1740
1741
1742 /*
1743  * Callback function for
1744  */
1745 void extract_encapsulated_message(char *name, char *filename, char *partnum, char *disp,
1746                    void *content, char *cbtype, char *cbcharset, size_t length,
1747                    char *encoding, char *cbid, void *cbuserdata)
1748 {
1749         struct encapmsg *encap;
1750
1751         encap = (struct encapmsg *)cbuserdata;
1752
1753         /* Only proceed if this is the desired section... */
1754         if (!strcasecmp(encap->desired_section, partnum)) {
1755                 encap->msglen = length;
1756                 encap->msg = malloc(length + 2);
1757                 memcpy(encap->msg, content, length);
1758                 return;
1759         }
1760 }
1761
1762
1763 /*
1764  * Determine whether the specified message exists in the cached_msglist
1765  * (This is a security check)
1766  */
1767 int check_cached_msglist(long msgnum) {
1768         struct CitContext *CCC = CC;
1769
1770         /* cases in which we skip the check */
1771         if (!CCC) return om_ok;                                         /* not a session */
1772         if (CCC->client_socket <= 0) return om_ok;                      /* not a client session */
1773         if (CCC->cached_msglist == NULL) return om_access_denied;       /* no msglist fetched */
1774         if (CCC->cached_num_msgs == 0) return om_access_denied;         /* nothing to check */
1775
1776
1777         /* Do a binary search within the cached_msglist for the requested msgnum */
1778         int min = 0;
1779         int max = (CC->cached_num_msgs - 1);
1780
1781         while (max >= min) {
1782                 int middle = min + (max-min) / 2 ;
1783                 if (msgnum == CCC->cached_msglist[middle]) {
1784                         return om_ok;
1785                 }
1786                 if (msgnum > CC->cached_msglist[middle]) {
1787                         min = middle + 1;
1788                 }
1789                 else {
1790                         max = middle - 1;
1791                 }
1792         }
1793
1794         return om_access_denied;
1795 }
1796
1797
1798 /* 
1799  * Determine whether the currently logged in session has permission to read
1800  * messages in the current room.
1801  */
1802 int CtdlDoIHavePermissionToReadMessagesInThisRoom(void) {
1803         if (    (!(CC->logged_in))
1804                 && (!(CC->internal_pgm))
1805                 && (!config.c_guest_logins)
1806         ) {
1807                 return(om_not_logged_in);
1808         }
1809         return(om_ok);
1810 }
1811
1812
1813 /*
1814  * Get a message off disk.  (returns om_* values found in msgbase.h)
1815  * 
1816  */
1817 int CtdlOutputMsg(long msg_num,         /* message number (local) to fetch */
1818                   int mode,             /* how would you like that message? */
1819                   int headers_only,     /* eschew the message body? */
1820                   int do_proto,         /* do Citadel protocol responses? */
1821                   int crlf,             /* Use CRLF newlines instead of LF? */
1822                   char *section,        /* NULL or a message/rfc822 section */
1823                   int flags,            /* various flags; see msgbase.h */
1824                   char **Author,
1825                   char **Address
1826 ) {
1827         struct CitContext *CCC = CC;
1828         struct CtdlMessage *TheMessage = NULL;
1829         int retcode = CIT_OK;
1830         struct encapmsg encap;
1831         int r;
1832
1833         MSG_syslog(LOG_DEBUG, "CtdlOutputMsg(msgnum=%ld, mode=%d, section=%s)\n", 
1834                 msg_num, mode,
1835                 (section ? section : "<>")
1836         );
1837
1838         r = CtdlDoIHavePermissionToReadMessagesInThisRoom();
1839         if (r != om_ok) {
1840                 if (do_proto) {
1841                         if (r == om_not_logged_in) {
1842                                 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
1843                         }
1844                         else {
1845                                 cprintf("%d An unknown error has occurred.\n", ERROR);
1846                         }
1847                 }
1848                 return(r);
1849         }
1850
1851         /*
1852          * Check to make sure the message is actually IN this room
1853          */
1854         r = check_cached_msglist(msg_num);
1855         if (r == om_access_denied) {
1856                 /* Not in the cache?  We get ONE shot to check it again. */
1857                 CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL, NULL, NULL);
1858                 r = check_cached_msglist(msg_num);
1859         }
1860         if (r != om_ok) {
1861                 MSG_syslog(LOG_DEBUG, "Security check fail: message %ld is not in %s\n",
1862                            msg_num, CCC->room.QRname
1863                 );
1864                 if (do_proto) {
1865                         if (r == om_access_denied) {
1866                                 cprintf("%d message %ld was not found in this room\n",
1867                                         ERROR + HIGHER_ACCESS_REQUIRED,
1868                                         msg_num
1869                                 );
1870                         }
1871                 }
1872                 return(r);
1873         }
1874
1875         /*
1876          * Fetch the message from disk.  If we're in HEADERS_FAST mode,
1877          * request that we don't even bother loading the body into memory.
1878          */
1879         if (headers_only == HEADERS_FAST) {
1880                 TheMessage = CtdlFetchMessage(msg_num, 0);
1881         }
1882         else {
1883                 TheMessage = CtdlFetchMessage(msg_num, 1);
1884         }
1885
1886         if (TheMessage == NULL) {
1887                 if (do_proto) cprintf("%d Can't locate msg %ld on disk\n",
1888                         ERROR + MESSAGE_NOT_FOUND, msg_num);
1889                 return(om_no_such_msg);
1890         }
1891
1892         /* Here is the weird form of this command, to process only an
1893          * encapsulated message/rfc822 section.
1894          */
1895         if (section) if (!IsEmptyStr(section)) if (strcmp(section, "0")) {
1896                 memset(&encap, 0, sizeof encap);
1897                 safestrncpy(encap.desired_section, section, sizeof encap.desired_section);
1898                 mime_parser(TheMessage->cm_fields[eMesageText],
1899                         NULL,
1900                         *extract_encapsulated_message,
1901                         NULL, NULL, (void *)&encap, 0
1902                 );
1903
1904                 if ((Author != NULL) && (*Author == NULL))
1905                 {
1906                         *Author = TheMessage->cm_fields[eAuthor];
1907                         TheMessage->cm_fields[eAuthor] = NULL;
1908                 }
1909                 if ((Address != NULL) && (*Address == NULL))
1910                 {       
1911                         *Address = TheMessage->cm_fields[erFc822Addr];
1912                         TheMessage->cm_fields[erFc822Addr] = NULL;
1913                 }
1914                 CM_Free(TheMessage);
1915                 TheMessage = NULL;
1916
1917                 if (encap.msg) {
1918                         encap.msg[encap.msglen] = 0;
1919                         TheMessage = convert_internet_message(encap.msg);
1920                         encap.msg = NULL;       /* no free() here, TheMessage owns it now */
1921
1922                         /* Now we let it fall through to the bottom of this
1923                          * function, because TheMessage now contains the
1924                          * encapsulated message instead of the top-level
1925                          * message.  Isn't that neat?
1926                          */
1927                 }
1928                 else {
1929                         if (do_proto) {
1930                                 cprintf("%d msg %ld has no part %s\n",
1931                                         ERROR + MESSAGE_NOT_FOUND,
1932                                         msg_num,
1933                                         section);
1934                         }
1935                         retcode = om_no_such_msg;
1936                 }
1937
1938         }
1939
1940         /* Ok, output the message now */
1941         if (retcode == CIT_OK)
1942                 retcode = CtdlOutputPreLoadedMsg(TheMessage, mode, headers_only, do_proto, crlf, flags);
1943         if ((Author != NULL) && (*Author == NULL))
1944         {
1945                 *Author = TheMessage->cm_fields[eAuthor];
1946                 TheMessage->cm_fields[eAuthor] = NULL;
1947         }
1948         if ((Address != NULL) && (*Address == NULL))
1949         {       
1950                 *Address = TheMessage->cm_fields[erFc822Addr];
1951                 TheMessage->cm_fields[erFc822Addr] = NULL;
1952         }
1953
1954         CM_Free(TheMessage);
1955
1956         return(retcode);
1957 }
1958
1959
1960 char *qp_encode_email_addrs(char *source)
1961 {
1962         struct CitContext *CCC = CC;
1963         char *user, *node, *name;
1964         const char headerStr[] = "=?UTF-8?Q?";
1965         char *Encoded;
1966         char *EncodedName;
1967         char *nPtr;
1968         int need_to_encode = 0;
1969         long SourceLen;
1970         long EncodedMaxLen;
1971         long nColons = 0;
1972         long *AddrPtr;
1973         long *AddrUtf8;
1974         long nAddrPtrMax = 50;
1975         long nmax;
1976         int InQuotes = 0;
1977         int i, n;
1978
1979         if (source == NULL) return source;
1980         if (IsEmptyStr(source)) return source;
1981         if (MessageDebugEnabled != 0) cit_backtrace();
1982         MSG_syslog(LOG_DEBUG, "qp_encode_email_addrs: [%s]\n", source);
1983
1984         AddrPtr = malloc (sizeof (long) * nAddrPtrMax);
1985         AddrUtf8 = malloc (sizeof (long) * nAddrPtrMax);
1986         memset(AddrUtf8, 0, sizeof (long) * nAddrPtrMax);
1987         *AddrPtr = 0;
1988         i = 0;
1989         while (!IsEmptyStr (&source[i])) {
1990                 if (nColons >= nAddrPtrMax){
1991                         long *ptr;
1992
1993                         ptr = (long *) malloc(sizeof (long) * nAddrPtrMax * 2);
1994                         memcpy (ptr, AddrPtr, sizeof (long) * nAddrPtrMax);
1995                         free (AddrPtr), AddrPtr = ptr;
1996
1997                         ptr = (long *) malloc(sizeof (long) * nAddrPtrMax * 2);
1998                         memset(&ptr[nAddrPtrMax], 0, 
1999                                sizeof (long) * nAddrPtrMax);
2000
2001                         memcpy (ptr, AddrUtf8, sizeof (long) * nAddrPtrMax);
2002                         free (AddrUtf8), AddrUtf8 = ptr;
2003                         nAddrPtrMax *= 2;                               
2004                 }
2005                 if (((unsigned char) source[i] < 32) || 
2006                     ((unsigned char) source[i] > 126)) {
2007                         need_to_encode = 1;
2008                         AddrUtf8[nColons] = 1;
2009                 }
2010                 if (source[i] == '"')
2011                         InQuotes = !InQuotes;
2012                 if (!InQuotes && source[i] == ',') {
2013                         AddrPtr[nColons] = i;
2014                         nColons++;
2015                 }
2016                 i++;
2017         }
2018         if (need_to_encode == 0) {
2019                 free(AddrPtr);
2020                 free(AddrUtf8);
2021                 return source;
2022         }
2023
2024         SourceLen = i;
2025         EncodedMaxLen = nColons * (sizeof(headerStr) + 3) + SourceLen * 3;
2026         Encoded = (char*) malloc (EncodedMaxLen);
2027
2028         for (i = 0; i < nColons; i++)
2029                 source[AddrPtr[i]++] = '\0';
2030         /* TODO: if libidn, this might get larger*/
2031         user = malloc(SourceLen + 1);
2032         node = malloc(SourceLen + 1);
2033         name = malloc(SourceLen + 1);
2034
2035         nPtr = Encoded;
2036         *nPtr = '\0';
2037         for (i = 0; i < nColons && nPtr != NULL; i++) {
2038                 nmax = EncodedMaxLen - (nPtr - Encoded);
2039                 if (AddrUtf8[i]) {
2040                         process_rfc822_addr(&source[AddrPtr[i]], 
2041                                             user,
2042                                             node,
2043                                             name);
2044                         /* TODO: libIDN here ! */
2045                         if (IsEmptyStr(name)) {
2046                                 n = snprintf(nPtr, nmax, 
2047                                              (i==0)?"%s@%s" : ",%s@%s",
2048                                              user, node);
2049                         }
2050                         else {
2051                                 EncodedName = rfc2047encode(name, strlen(name));                        
2052                                 n = snprintf(nPtr, nmax, 
2053                                              (i==0)?"%s <%s@%s>" : ",%s <%s@%s>",
2054                                              EncodedName, user, node);
2055                                 free(EncodedName);
2056                         }
2057                 }
2058                 else { 
2059                         n = snprintf(nPtr, nmax, 
2060                                      (i==0)?"%s" : ",%s",
2061                                      &source[AddrPtr[i]]);
2062                 }
2063                 if (n > 0 )
2064                         nPtr += n;
2065                 else { 
2066                         char *ptr, *nnPtr;
2067                         ptr = (char*) malloc(EncodedMaxLen * 2);
2068                         memcpy(ptr, Encoded, EncodedMaxLen);
2069                         nnPtr = ptr + (nPtr - Encoded), nPtr = nnPtr;
2070                         free(Encoded), Encoded = ptr;
2071                         EncodedMaxLen *= 2;
2072                         i--; /* do it once more with properly lengthened buffer */
2073                 }
2074         }
2075         for (i = 0; i < nColons; i++)
2076                 source[--AddrPtr[i]] = ',';
2077
2078         free(user);
2079         free(node);
2080         free(name);
2081         free(AddrUtf8);
2082         free(AddrPtr);
2083         return Encoded;
2084 }
2085
2086
2087 /* If the last item in a list of recipients was truncated to a partial address,
2088  * remove it completely in order to avoid choking libSieve
2089  */
2090 void sanitize_truncated_recipient(char *str)
2091 {
2092         if (!str) return;
2093         if (num_tokens(str, ',') < 2) return;
2094
2095         int len = strlen(str);
2096         if (len < 900) return;
2097         if (len > 998) str[998] = 0;
2098
2099         char *cptr = strrchr(str, ',');
2100         if (!cptr) return;
2101
2102         char *lptr = strchr(cptr, '<');
2103         char *rptr = strchr(cptr, '>');
2104
2105         if ( (lptr) && (rptr) && (rptr > lptr) ) return;
2106
2107         *cptr = 0;
2108 }
2109
2110
2111 void OutputCtdlMsgHeaders(
2112         struct CtdlMessage *TheMessage,
2113         int do_proto)           /* do Citadel protocol responses? */
2114 {
2115         int i;
2116         int suppress_f = 0;
2117         char buf[SIZ];
2118         char display_name[256];
2119
2120         /* begin header processing loop for Citadel message format */
2121         safestrncpy(display_name, "<unknown>", sizeof display_name);
2122         if (!CM_IsEmpty(TheMessage, eAuthor)) {
2123                 strcpy(buf, TheMessage->cm_fields[eAuthor]);
2124                 if (TheMessage->cm_anon_type == MES_ANONONLY) {
2125                         safestrncpy(display_name, "****", sizeof display_name);
2126                 }
2127                 else if (TheMessage->cm_anon_type == MES_ANONOPT) {
2128                         safestrncpy(display_name, "anonymous", sizeof display_name);
2129                 }
2130                 else {
2131                         safestrncpy(display_name, buf, sizeof display_name);
2132                 }
2133                 if ((is_room_aide())
2134                     && ((TheMessage->cm_anon_type == MES_ANONONLY)
2135                         || (TheMessage->cm_anon_type == MES_ANONOPT))) {
2136                         size_t tmp = strlen(display_name);
2137                         snprintf(&display_name[tmp],
2138                                  sizeof display_name - tmp,
2139                                  " [%s]", buf);
2140                 }
2141         }
2142
2143         /* Don't show Internet address for users on the
2144          * local Citadel network.
2145          */
2146         suppress_f = 0;
2147         if (!CM_IsEmpty(TheMessage, eNodeName) &&
2148             (haschar(TheMessage->cm_fields[eNodeName], '.') == 0))
2149         {
2150                 suppress_f = 1;
2151         }
2152
2153         /* Now spew the header fields in the order we like them. */
2154         for (i=0; i< NDiskFields; ++i) {
2155                 eMsgField Field;
2156                 Field = FieldOrder[i];
2157                 if (Field != eMesageText) {
2158                         if ( (!CM_IsEmpty(TheMessage, Field))
2159                              && (msgkeys[Field] != NULL) ) {
2160                                 if ((Field == eenVelopeTo) ||
2161                                     (Field == eRecipient) ||
2162                                     (Field == eCarbonCopY)) {
2163                                         sanitize_truncated_recipient(TheMessage->cm_fields[Field]);
2164                                 }
2165                                 if (Field == eAuthor) {
2166                                         if (do_proto) cprintf("%s=%s\n",
2167                                                               msgkeys[Field],
2168                                                               display_name);
2169                                 }
2170                                 else if ((Field == erFc822Addr) && (suppress_f)) {
2171                                         /* do nothing */
2172                                 }
2173                                 /* Masquerade display name if needed */
2174                                 else {
2175                                         if (do_proto) cprintf("%s=%s\n",
2176                                                               msgkeys[Field],
2177                                                               TheMessage->cm_fields[Field]
2178                                                 );
2179                                 }
2180                         }
2181                 }
2182         }
2183
2184 }
2185
2186 void OutputRFC822MsgHeaders(
2187         struct CtdlMessage *TheMessage,
2188         int flags,              /* should the bessage be exported clean */
2189         const char *nl,
2190         char *mid, long sizeof_mid,
2191         char *suser, long sizeof_suser,
2192         char *luser, long sizeof_luser,
2193         char *fuser, long sizeof_fuser,
2194         char *snode, long sizeof_snode)
2195 {
2196         char datestamp[100];
2197         int subject_found = 0;
2198         char buf[SIZ];
2199         int i, j, k;
2200         char *mptr = NULL;
2201         char *mpptr = NULL;
2202         char *hptr;
2203
2204         for (i = 0; i < 256; ++i) {
2205                 if (TheMessage->cm_fields[i]) {
2206                         mptr = mpptr = TheMessage->cm_fields[i];
2207                                 
2208                         if (i == eAuthor) {
2209                                 safestrncpy(luser, mptr, sizeof_luser);
2210                                 safestrncpy(suser, mptr, sizeof_suser);
2211                         }
2212                         else if (i == 'Y') {
2213                                 if ((flags & QP_EADDR) != 0) {
2214                                         mptr = qp_encode_email_addrs(mptr);
2215                                 }
2216                                 sanitize_truncated_recipient(mptr);
2217                                 cprintf("CC: %s%s", mptr, nl);
2218                         }
2219                         else if (i == 'P') {
2220                                 cprintf("Return-Path: %s%s", mptr, nl);
2221                         }
2222                         else if (i == eListID) {
2223                                 cprintf("List-ID: %s%s", mptr, nl);
2224                         }
2225                         else if (i == 'V') {
2226                                 if ((flags & QP_EADDR) != 0) 
2227                                         mptr = qp_encode_email_addrs(mptr);
2228                                 hptr = mptr;
2229                                 while ((*hptr != '\0') && isspace(*hptr))
2230                                         hptr ++;
2231                                 if (!IsEmptyStr(hptr))
2232                                         cprintf("Envelope-To: %s%s", hptr, nl);
2233                         }
2234                         else if (i == 'U') {
2235                                 cprintf("Subject: %s%s", mptr, nl);
2236                                 subject_found = 1;
2237                         }
2238                         else if (i == 'I')
2239                                 safestrncpy(mid, mptr, sizeof_mid); /// TODO: detect @ here and copy @nodename in if not found.
2240                         else if (i == erFc822Addr)
2241                                 safestrncpy(fuser, mptr, sizeof_fuser);
2242                         /* else if (i == 'O')
2243                            cprintf("X-Citadel-Room: %s%s",
2244                            mptr, nl); */
2245                         else if (i == 'N')
2246                                 safestrncpy(snode, mptr, sizeof_snode);
2247                         else if (i == 'R')
2248                         {
2249                                 if (haschar(mptr, '@') == 0)
2250                                 {
2251                                         sanitize_truncated_recipient(mptr);
2252                                         cprintf("To: %s@%s", mptr, config.c_fqdn);
2253                                         cprintf("%s", nl);
2254                                 }
2255                                 else
2256                                 {
2257                                         if ((flags & QP_EADDR) != 0) {
2258                                                 mptr = qp_encode_email_addrs(mptr);
2259                                         }
2260                                         sanitize_truncated_recipient(mptr);
2261                                         cprintf("To: %s", mptr);
2262                                         cprintf("%s", nl);
2263                                 }
2264                         }
2265                         else if (i == 'T') {
2266                                 datestring(datestamp, sizeof datestamp,
2267                                            atol(mptr), DATESTRING_RFC822);
2268                                 cprintf("Date: %s%s", datestamp, nl);
2269                         }
2270                         else if (i == 'W') {
2271                                 cprintf("References: ");
2272                                 k = num_tokens(mptr, '|');
2273                                 for (j=0; j<k; ++j) {
2274                                         extract_token(buf, mptr, j, '|', sizeof buf);
2275                                         cprintf("<%s>", buf);
2276                                         if (j == (k-1)) {
2277                                                 cprintf("%s", nl);
2278                                         }
2279                                         else {
2280                                                 cprintf(" ");
2281                                         }
2282                                 }
2283                         }
2284                         else if (i == eReplyTo) {
2285                                 hptr = mptr;
2286                                 while ((*hptr != '\0') && isspace(*hptr))
2287                                         hptr ++;
2288                                 if (!IsEmptyStr(hptr))
2289                                         cprintf("Reply-To: %s%s", mptr, nl);
2290                         }
2291                         if (mptr != mpptr)
2292                                 free (mptr);
2293                 }
2294         }
2295         if (subject_found == 0) {
2296                 cprintf("Subject: (no subject)%s", nl);
2297         }
2298 }
2299
2300
2301 void Dump_RFC822HeadersBody(
2302         struct CtdlMessage *TheMessage,
2303         int headers_only,       /* eschew the message body? */
2304         int flags,              /* should the bessage be exported clean? */
2305
2306         const char *nl)
2307 {
2308         cit_uint8_t prev_ch;
2309         int eoh = 0;
2310         const char *StartOfText = StrBufNOTNULL;
2311         char outbuf[1024];
2312         int outlen = 0;
2313         int nllen = strlen(nl);
2314         char *mptr;
2315
2316         mptr = TheMessage->cm_fields[eMesageText];
2317
2318
2319         prev_ch = '\0';
2320         while (*mptr != '\0') {
2321                 if (*mptr == '\r') {
2322                         /* do nothing */
2323                 }
2324                 else {
2325                         if ((!eoh) &&
2326                             (*mptr == '\n'))
2327                         {
2328                                 eoh = (*(mptr+1) == '\r') && (*(mptr+2) == '\n');
2329                                 if (!eoh)
2330                                         eoh = *(mptr+1) == '\n';
2331                                 if (eoh)
2332                                 {
2333                                         StartOfText = mptr;
2334                                         StartOfText = strchr(StartOfText, '\n');
2335                                         StartOfText = strchr(StartOfText, '\n');
2336                                 }
2337                         }
2338                         if (((headers_only == HEADERS_NONE) && (mptr >= StartOfText)) ||
2339                             ((headers_only == HEADERS_ONLY) && (mptr < StartOfText)) ||
2340                             ((headers_only != HEADERS_NONE) && 
2341                              (headers_only != HEADERS_ONLY))
2342                                 ) {
2343                                 if (*mptr == '\n') {
2344                                         memcpy(&outbuf[outlen], nl, nllen);
2345                                         outlen += nllen;
2346                                         outbuf[outlen] = '\0';
2347                                 }
2348                                 else {
2349                                         outbuf[outlen++] = *mptr;
2350                                 }
2351                         }
2352                 }
2353                 if (flags & ESC_DOT)
2354                 {
2355                         if ((prev_ch == '\n') && 
2356                             (*mptr == '.') && 
2357                             ((*(mptr+1) == '\r') || (*(mptr+1) == '\n')))
2358                         {
2359                                 outbuf[outlen++] = '.';
2360                         }
2361                         prev_ch = *mptr;
2362                 }
2363                 ++mptr;
2364                 if (outlen > 1000) {
2365                         if (client_write(outbuf, outlen) == -1)
2366                         {
2367                                 struct CitContext *CCC = CC;
2368                                 MSGM_syslog(LOG_ERR, "Dump_RFC822HeadersBody(): aborting due to write failure.\n");
2369                                 return;
2370                         }
2371                         outlen = 0;
2372                 }
2373         }
2374         if (outlen > 0) {
2375                 client_write(outbuf, outlen);
2376         }
2377 }
2378
2379
2380
2381 /* If the format type on disk is 1 (fixed-format), then we want
2382  * everything to be output completely literally ... regardless of
2383  * what message transfer format is in use.
2384  */
2385 void DumpFormatFixed(
2386         struct CtdlMessage *TheMessage,
2387         int mode,               /* how would you like that message? */
2388         const char *nl)
2389 {
2390         cit_uint8_t ch;
2391         char buf[SIZ];
2392         int buflen;
2393         int xlline = 0;
2394         int nllen = strlen (nl);
2395         char *mptr;
2396
2397         mptr = TheMessage->cm_fields[eMesageText];
2398         
2399         if (mode == MT_MIME) {
2400                 cprintf("Content-type: text/plain\n\n");
2401         }
2402         *buf = '\0';
2403         buflen = 0;
2404         while (ch = *mptr++, ch > 0) {
2405                 if (ch == '\n')
2406                         ch = '\r';
2407
2408                 if ((buflen > 250) && (!xlline)){
2409                         int tbuflen;
2410                         tbuflen = buflen;
2411
2412                         while ((buflen > 0) && 
2413                                (!isspace(buf[buflen])))
2414                                 buflen --;
2415                         if (buflen == 0) {
2416                                 xlline = 1;
2417                         }
2418                         else {
2419                                 mptr -= tbuflen - buflen;
2420                                 buf[buflen] = '\0';
2421                                 ch = '\r';
2422                         }
2423                 }
2424                 /* if we reach the outer bounds of our buffer, 
2425                    abort without respect what whe purge. */
2426                 if (xlline && 
2427                     ((isspace(ch)) || 
2428                      (buflen > SIZ - nllen - 2)))
2429                         ch = '\r';
2430
2431                 if (ch == '\r') {
2432                         memcpy (&buf[buflen], nl, nllen);
2433                         buflen += nllen;
2434                         buf[buflen] = '\0';
2435
2436                         if (client_write(buf, buflen) == -1)
2437                         {
2438                                 struct CitContext *CCC = CC;
2439                                 MSGM_syslog(LOG_ERR, "DumpFormatFixed(): aborting due to write failure.\n");
2440                                 return;
2441                         }
2442                         *buf = '\0';
2443                         buflen = 0;
2444                         xlline = 0;
2445                 } else {
2446                         buf[buflen] = ch;
2447                         buflen++;
2448                 }
2449         }
2450         buf[buflen] = '\0';
2451         if (!IsEmptyStr(buf))
2452                 cprintf("%s%s", buf, nl);
2453 }
2454
2455 /*
2456  * Get a message off disk.  (returns om_* values found in msgbase.h)
2457  */
2458 int CtdlOutputPreLoadedMsg(
2459                 struct CtdlMessage *TheMessage,
2460                 int mode,               /* how would you like that message? */
2461                 int headers_only,       /* eschew the message body? */
2462                 int do_proto,           /* do Citadel protocol responses? */
2463                 int crlf,               /* Use CRLF newlines instead of LF? */
2464                 int flags               /* should the bessage be exported clean? */
2465 ) {
2466         struct CitContext *CCC = CC;
2467         int i;
2468         char *mptr = NULL;
2469         const char *nl; /* newline string */
2470         struct ma_info ma;
2471
2472         /* Buffers needed for RFC822 translation.  These are all filled
2473          * using functions that are bounds-checked, and therefore we can
2474          * make them substantially smaller than SIZ.
2475          */
2476         char suser[100];
2477         char luser[100];
2478         char fuser[100];
2479         char snode[100];
2480         char mid[100];
2481
2482         MSG_syslog(LOG_DEBUG, "CtdlOutputPreLoadedMsg(TheMessage=%s, %d, %d, %d, %d\n",
2483                    ((TheMessage == NULL) ? "NULL" : "not null"),
2484                    mode, headers_only, do_proto, crlf);
2485
2486         strcpy(mid, "unknown");
2487         nl = (crlf ? "\r\n" : "\n");
2488
2489         if (!CM_IsValidMsg(TheMessage)) {
2490                 MSGM_syslog(LOG_ERR,
2491                             "ERROR: invalid preloaded message for output\n");
2492                 cit_backtrace ();
2493                 return(om_no_such_msg);
2494         }
2495
2496         /* Suppress envelope recipients if required to avoid disclosing BCC addresses.
2497          * Pad it with spaces in order to avoid changing the RFC822 length of the message.
2498          */
2499         if ( (flags & SUPPRESS_ENV_TO) && (!CM_IsEmpty(TheMessage, eenVelopeTo)) ) {
2500                 memset(TheMessage->cm_fields[eenVelopeTo], ' ', strlen(TheMessage->cm_fields[eenVelopeTo]));
2501         }
2502                 
2503         /* Are we downloading a MIME component? */
2504         if (mode == MT_DOWNLOAD) {
2505                 if (TheMessage->cm_format_type != FMT_RFC822) {
2506                         if (do_proto)
2507                                 cprintf("%d This is not a MIME message.\n",
2508                                 ERROR + ILLEGAL_VALUE);
2509                 } else if (CCC->download_fp != NULL) {
2510                         if (do_proto) cprintf(
2511                                 "%d You already have a download open.\n",
2512                                 ERROR + RESOURCE_BUSY);
2513                 } else {
2514                         /* Parse the message text component */
2515                         mptr = TheMessage->cm_fields[eMesageText];
2516                         mime_parser(mptr, NULL, *mime_download, NULL, NULL, NULL, 0);
2517                         /* If there's no file open by this time, the requested
2518                          * section wasn't found, so print an error
2519                          */
2520                         if (CCC->download_fp == NULL) {
2521                                 if (do_proto) cprintf(
2522                                         "%d Section %s not found.\n",
2523                                         ERROR + FILE_NOT_FOUND,
2524                                         CCC->download_desired_section);
2525                         }
2526                 }
2527                 return((CCC->download_fp != NULL) ? om_ok : om_mime_error);
2528         }
2529
2530         /* MT_SPEW_SECTION is like MT_DOWNLOAD except it outputs the whole MIME part
2531          * in a single server operation instead of opening a download file.
2532          */
2533         if (mode == MT_SPEW_SECTION) {
2534                 if (TheMessage->cm_format_type != FMT_RFC822) {
2535                         if (do_proto)
2536                                 cprintf("%d This is not a MIME message.\n",
2537                                 ERROR + ILLEGAL_VALUE);
2538                 } else {
2539                         /* Parse the message text component */
2540                         int found_it = 0;
2541
2542                         mptr = TheMessage->cm_fields[eMesageText];
2543                         mime_parser(mptr, NULL, *mime_spew_section, NULL, NULL, (void *)&found_it, 0);
2544                         /* If section wasn't found, print an error
2545                          */
2546                         if (!found_it) {
2547                                 if (do_proto) cprintf(
2548                                         "%d Section %s not found.\n",
2549                                         ERROR + FILE_NOT_FOUND,
2550                                         CCC->download_desired_section);
2551                         }
2552                 }
2553                 return((CCC->download_fp != NULL) ? om_ok : om_mime_error);
2554         }
2555
2556         /* now for the user-mode message reading loops */
2557         if (do_proto) cprintf("%d msg:\n", LISTING_FOLLOWS);
2558
2559         /* Does the caller want to skip the headers? */
2560         if (headers_only == HEADERS_NONE) goto START_TEXT;
2561
2562         /* Tell the client which format type we're using. */
2563         if ( (mode == MT_CITADEL) && (do_proto) ) {
2564                 cprintf("type=%d\n", TheMessage->cm_format_type);
2565         }
2566
2567         /* nhdr=yes means that we're only displaying headers, no body */
2568         if ( (TheMessage->cm_anon_type == MES_ANONONLY)
2569            && ((mode == MT_CITADEL) || (mode == MT_MIME))
2570            && (do_proto)
2571            ) {
2572                 cprintf("nhdr=yes\n");
2573         }
2574
2575         if ((mode == MT_CITADEL) || (mode == MT_MIME)) 
2576                 OutputCtdlMsgHeaders(TheMessage, do_proto);
2577
2578
2579         /* begin header processing loop for RFC822 transfer format */
2580         strcpy(suser, "");
2581         strcpy(luser, "");
2582         strcpy(fuser, "");
2583         strcpy(snode, NODENAME);
2584         if (mode == MT_RFC822) 
2585                 OutputRFC822MsgHeaders(
2586                         TheMessage,
2587                         flags,
2588                         nl,
2589                         mid, sizeof(mid),
2590                         suser, sizeof(suser),
2591                         luser, sizeof(luser),
2592                         fuser, sizeof(fuser),
2593                         snode, sizeof(snode)
2594                         );
2595
2596
2597         for (i=0; !IsEmptyStr(&suser[i]); ++i) {
2598                 suser[i] = tolower(suser[i]);
2599                 if (!isalnum(suser[i])) suser[i]='_';
2600         }
2601
2602         if (mode == MT_RFC822) {
2603                 if (!strcasecmp(snode, NODENAME)) {
2604                         safestrncpy(snode, FQDN, sizeof snode);
2605                 }
2606
2607                 /* Construct a fun message id */
2608                 cprintf("Message-ID: <%s", mid);/// todo: this possibly breaks threadding mails.
2609                 if (strchr(mid, '@')==NULL) {
2610                         cprintf("@%s", snode);
2611                 }
2612                 cprintf(">%s", nl);
2613
2614                 if (!is_room_aide() && (TheMessage->cm_anon_type == MES_ANONONLY)) {
2615                         cprintf("From: \"----\" <x@x.org>%s", nl);
2616                 }
2617                 else if (!is_room_aide() && (TheMessage->cm_anon_type == MES_ANONOPT)) {
2618                         cprintf("From: \"anonymous\" <x@x.org>%s", nl);
2619                 }
2620                 else if (!IsEmptyStr(fuser)) {
2621                         cprintf("From: \"%s\" <%s>%s", luser, fuser, nl);
2622                 }
2623                 else {
2624                         cprintf("From: \"%s\" <%s@%s>%s", luser, suser, snode, nl);
2625                 }
2626
2627                 /* Blank line signifying RFC822 end-of-headers */
2628                 if (TheMessage->cm_format_type != FMT_RFC822) {
2629                         cprintf("%s", nl);
2630                 }
2631         }
2632
2633         /* end header processing loop ... at this point, we're in the text */
2634 START_TEXT:
2635         if (headers_only == HEADERS_FAST) goto DONE;
2636
2637         /* Tell the client about the MIME parts in this message */
2638         if (TheMessage->cm_format_type == FMT_RFC822) {
2639                 if ( (mode == MT_CITADEL) || (mode == MT_MIME) ) {
2640                         mptr = TheMessage->cm_fields[eMesageText];
2641                         memset(&ma, 0, sizeof(struct ma_info));
2642                         mime_parser(mptr, NULL,
2643                                 (do_proto ? *list_this_part : NULL),
2644                                 (do_proto ? *list_this_pref : NULL),
2645                                 (do_proto ? *list_this_suff : NULL),
2646                                 (void *)&ma, 1);
2647                 }
2648                 else if (mode == MT_RFC822) {   /* unparsed RFC822 dump */
2649                         Dump_RFC822HeadersBody(
2650                                 TheMessage,
2651                                 headers_only,
2652                                 flags,
2653                                 nl);
2654                         goto DONE;
2655                 }
2656         }
2657
2658         if (headers_only == HEADERS_ONLY) {
2659                 goto DONE;
2660         }
2661
2662         /* signify start of msg text */
2663         if ( (mode == MT_CITADEL) || (mode == MT_MIME) ) {
2664                 if (do_proto) cprintf("text\n");
2665         }
2666
2667         if (TheMessage->cm_format_type == FMT_FIXED) 
2668                 DumpFormatFixed(
2669                         TheMessage,
2670                         mode,           /* how would you like that message? */
2671                         nl);
2672
2673         /* If the message on disk is format 0 (Citadel vari-format), we
2674          * output using the formatter at 80 columns.  This is the final output
2675          * form if the transfer format is RFC822, but if the transfer format
2676          * is Citadel proprietary, it'll still work, because the indentation
2677          * for new paragraphs is correct and the client will reformat the
2678          * message to the reader's screen width.
2679          */
2680         if (TheMessage->cm_format_type == FMT_CITADEL) {
2681                 mptr = TheMessage->cm_fields[eMesageText];
2682
2683                 if (mode == MT_MIME) {
2684                         cprintf("Content-type: text/x-citadel-variformat\n\n");
2685                 }
2686                 memfmout(mptr, nl);
2687         }
2688
2689         /* If the message on disk is format 4 (MIME), we've gotta hand it
2690          * off to the MIME parser.  The client has already been told that
2691          * this message is format 1 (fixed format), so the callback function
2692          * we use will display those parts as-is.
2693          */
2694         if (TheMessage->cm_format_type == FMT_RFC822) {
2695                 memset(&ma, 0, sizeof(struct ma_info));
2696
2697                 if (mode == MT_MIME) {
2698                         ma.use_fo_hooks = 0;
2699                         strcpy(ma.chosen_part, "1");
2700                         ma.chosen_pref = 9999;
2701                         ma.dont_decode = CCC->msg4_dont_decode;
2702                         mime_parser(mptr, NULL,
2703                                 *choose_preferred, *fixed_output_pre,
2704                                 *fixed_output_post, (void *)&ma, 1);
2705                         mime_parser(mptr, NULL,
2706                                 *output_preferred, NULL, NULL, (void *)&ma, 1);
2707                 }
2708                 else {
2709                         ma.use_fo_hooks = 1;
2710                         mime_parser(mptr, NULL,
2711                                 *fixed_output, *fixed_output_pre,
2712                                 *fixed_output_post, (void *)&ma, 0);
2713                 }
2714
2715         }
2716
2717 DONE:   /* now we're done */
2718         if (do_proto) cprintf("000\n");
2719         return(om_ok);
2720 }
2721
2722
2723 /*
2724  * display a message (mode 0 - Citadel proprietary)
2725  */
2726 void cmd_msg0(char *cmdbuf)
2727 {
2728         long msgid;
2729         int headers_only = HEADERS_ALL;
2730
2731         msgid = extract_long(cmdbuf, 0);
2732         headers_only = extract_int(cmdbuf, 1);
2733
2734         CtdlOutputMsg(msgid, MT_CITADEL, headers_only, 1, 0, NULL, 0, NULL, NULL);
2735         return;
2736 }
2737
2738
2739 /*
2740  * display a message (mode 2 - RFC822)
2741  */
2742 void cmd_msg2(char *cmdbuf)
2743 {
2744         long msgid;
2745         int headers_only = HEADERS_ALL;
2746
2747         msgid = extract_long(cmdbuf, 0);
2748         headers_only = extract_int(cmdbuf, 1);
2749
2750         CtdlOutputMsg(msgid, MT_RFC822, headers_only, 1, 1, NULL, 0, NULL, NULL);
2751 }
2752
2753
2754
2755 /* 
2756  * display a message (mode 3 - IGnet raw format - internal programs only)
2757  */
2758 void cmd_msg3(char *cmdbuf)
2759 {
2760         long msgnum;
2761         struct CtdlMessage *msg = NULL;
2762         struct ser_ret smr;
2763
2764         if (CC->internal_pgm == 0) {
2765                 cprintf("%d This command is for internal programs only.\n",
2766                         ERROR + HIGHER_ACCESS_REQUIRED);
2767                 return;
2768         }
2769
2770         msgnum = extract_long(cmdbuf, 0);
2771         msg = CtdlFetchMessage(msgnum, 1);
2772         if (msg == NULL) {
2773                 cprintf("%d Message %ld not found.\n", 
2774                         ERROR + MESSAGE_NOT_FOUND, msgnum);
2775                 return;
2776         }
2777
2778         serialize_message(&smr, msg);
2779         CM_Free(msg);
2780
2781         if (smr.len == 0) {
2782                 cprintf("%d Unable to serialize message\n",
2783                         ERROR + INTERNAL_ERROR);
2784                 return;
2785         }
2786
2787         cprintf("%d %ld\n", BINARY_FOLLOWS, (long)smr.len);
2788         client_write((char *)smr.ser, (int)smr.len);
2789         free(smr.ser);
2790 }
2791
2792
2793
2794 /* 
2795  * Display a message using MIME content types
2796  */
2797 void cmd_msg4(char *cmdbuf)
2798 {
2799         long msgid;
2800         char section[64];
2801
2802         msgid = extract_long(cmdbuf, 0);
2803         extract_token(section, cmdbuf, 1, '|', sizeof section);
2804         CtdlOutputMsg(msgid, MT_MIME, 0, 1, 0, (section[0] ? section : NULL) , 0, NULL, NULL);
2805 }
2806
2807
2808
2809 /* 
2810  * Client tells us its preferred message format(s)
2811  */
2812 void cmd_msgp(char *cmdbuf)
2813 {
2814         if (!strcasecmp(cmdbuf, "dont_decode")) {
2815                 CC->msg4_dont_decode = 1;
2816                 cprintf("%d MSG4 will not pre-decode messages.\n", CIT_OK);
2817         }
2818         else {
2819                 safestrncpy(CC->preferred_formats, cmdbuf, sizeof(CC->preferred_formats));
2820                 cprintf("%d Preferred MIME formats have been set.\n", CIT_OK);
2821         }
2822 }
2823
2824
2825 /*
2826  * Open a component of a MIME message as a download file 
2827  */
2828 void cmd_opna(char *cmdbuf)
2829 {
2830         long msgid;
2831         char desired_section[128];
2832
2833         msgid = extract_long(cmdbuf, 0);
2834         extract_token(desired_section, cmdbuf, 1, '|', sizeof desired_section);
2835         safestrncpy(CC->download_desired_section, desired_section,
2836                 sizeof CC->download_desired_section);
2837         CtdlOutputMsg(msgid, MT_DOWNLOAD, 0, 1, 1, NULL, 0, NULL, NULL);
2838 }                       
2839
2840
2841 /*
2842  * Open a component of a MIME message and transmit it all at once
2843  */
2844 void cmd_dlat(char *cmdbuf)
2845 {
2846         long msgid;
2847         char desired_section[128];
2848
2849         msgid = extract_long(cmdbuf, 0);
2850         extract_token(desired_section, cmdbuf, 1, '|', sizeof desired_section);
2851         safestrncpy(CC->download_desired_section, desired_section,
2852                 sizeof CC->download_desired_section);
2853         CtdlOutputMsg(msgid, MT_SPEW_SECTION, 0, 1, 1, NULL, 0, NULL, NULL);
2854 }
2855
2856
2857 /*
2858  * Save one or more message pointers into a specified room
2859  * (Returns 0 for success, nonzero for failure)
2860  * roomname may be NULL to use the current room
2861  *
2862  * Note that the 'supplied_msg' field may be set to NULL, in which case
2863  * the message will be fetched from disk, by number, if we need to perform
2864  * replication checks.  This adds an additional database read, so if the
2865  * caller already has the message in memory then it should be supplied.  (Obviously
2866  * this mode of operation only works if we're saving a single message.)
2867  */
2868 int CtdlSaveMsgPointersInRoom(char *roomname, long newmsgidlist[], int num_newmsgs,
2869                         int do_repl_check, struct CtdlMessage *supplied_msg, int suppress_refcount_adj
2870 ) {
2871         struct CitContext *CCC = CC;
2872         int i, j, unique;
2873         char hold_rm[ROOMNAMELEN];
2874         struct cdbdata *cdbfr;
2875         int num_msgs;
2876         long *msglist;
2877         long highest_msg = 0L;
2878
2879         long msgid = 0;
2880         struct CtdlMessage *msg = NULL;
2881
2882         long *msgs_to_be_merged = NULL;
2883         int num_msgs_to_be_merged = 0;
2884
2885         MSG_syslog(LOG_DEBUG,
2886                    "CtdlSaveMsgPointersInRoom(room=%s, num_msgs=%d, repl=%d, suppress_rca=%d)\n",
2887                    roomname, num_newmsgs, do_repl_check, suppress_refcount_adj
2888         );
2889
2890         strcpy(hold_rm, CCC->room.QRname);
2891
2892         /* Sanity checks */
2893         if (newmsgidlist == NULL) return(ERROR + INTERNAL_ERROR);
2894         if (num_newmsgs < 1) return(ERROR + INTERNAL_ERROR);
2895         if (num_newmsgs > 1) supplied_msg = NULL;
2896
2897         /* Now the regular stuff */
2898         if (CtdlGetRoomLock(&CCC->room,
2899            ((roomname != NULL) ? roomname : CCC->room.QRname) )
2900            != 0) {
2901                 MSG_syslog(LOG_ERR, "No such room <%s>\n", roomname);
2902                 return(ERROR + ROOM_NOT_FOUND);
2903         }
2904
2905
2906         msgs_to_be_merged = malloc(sizeof(long) * num_newmsgs);
2907         num_msgs_to_be_merged = 0;
2908
2909
2910         cdbfr = cdb_fetch(CDB_MSGLISTS, &CCC->room.QRnumber, sizeof(long));
2911         if (cdbfr == NULL) {
2912                 msglist = NULL;
2913                 num_msgs = 0;
2914         } else {
2915                 msglist = (long *) cdbfr->ptr;
2916                 cdbfr->ptr = NULL;      /* CtdlSaveMsgPointerInRoom() now owns this memory */
2917                 num_msgs = cdbfr->len / sizeof(long);
2918                 cdb_free(cdbfr);
2919         }
2920
2921
2922         /* Create a list of msgid's which were supplied by the caller, but do
2923          * not already exist in the target room.  It is absolutely taboo to
2924          * have more than one reference to the same message in a room.
2925          */
2926         for (i=0; i<num_newmsgs; ++i) {
2927                 unique = 1;
2928                 if (num_msgs > 0) for (j=0; j<num_msgs; ++j) {
2929                         if (msglist[j] == newmsgidlist[i]) {
2930                                 unique = 0;
2931                         }
2932                 }
2933                 if (unique) {
2934                         msgs_to_be_merged[num_msgs_to_be_merged++] = newmsgidlist[i];
2935                 }
2936         }
2937
2938         MSG_syslog(LOG_DEBUG, "%d unique messages to be merged\n", num_msgs_to_be_merged);
2939
2940         /*
2941          * Now merge the new messages
2942          */
2943         msglist = realloc(msglist, (sizeof(long) * (num_msgs + num_msgs_to_be_merged)) );
2944         if (msglist == NULL) {
2945                 MSGM_syslog(LOG_ALERT, "ERROR: can't realloc message list!\n");
2946                 free(msgs_to_be_merged);
2947                 return (ERROR + INTERNAL_ERROR);
2948         }
2949         memcpy(&msglist[num_msgs], msgs_to_be_merged, (sizeof(long) * num_msgs_to_be_merged) );
2950         num_msgs += num_msgs_to_be_merged;
2951
2952         /* Sort the message list, so all the msgid's are in order */
2953         num_msgs = sort_msglist(msglist, num_msgs);
2954
2955         /* Determine the highest message number */
2956         highest_msg = msglist[num_msgs - 1];
2957
2958         /* Write it back to disk. */
2959         cdb_store(CDB_MSGLISTS, &CCC->room.QRnumber, (int)sizeof(long),
2960                   msglist, (int)(num_msgs * sizeof(long)));
2961
2962         /* Free up the memory we used. */
2963         free(msglist);
2964
2965         /* Update the highest-message pointer and unlock the room. */
2966         CCC->room.QRhighest = highest_msg;
2967         CtdlPutRoomLock(&CCC->room);
2968
2969         /* Perform replication checks if necessary */
2970         if ( (DoesThisRoomNeedEuidIndexing(&CCC->room)) && (do_repl_check) ) {
2971                 MSGM_syslog(LOG_DEBUG, "CtdlSaveMsgPointerInRoom() doing repl checks\n");
2972
2973                 for (i=0; i<num_msgs_to_be_merged; ++i) {
2974                         msgid = msgs_to_be_merged[i];
2975         
2976                         if (supplied_msg != NULL) {
2977                                 msg = supplied_msg;
2978                         }
2979                         else {
2980                                 msg = CtdlFetchMessage(msgid, 0);
2981                         }
2982         
2983                         if (msg != NULL) {
2984                                 ReplicationChecks(msg);
2985                 
2986                                 /* If the message has an Exclusive ID, index that... */
2987                                 if (!CM_IsEmpty(msg, eExclusiveID)) {
2988                                         index_message_by_euid(msg->cm_fields[eExclusiveID], &CCC->room, msgid);
2989                                 }
2990
2991                                 /* Free up the memory we may have allocated */
2992                                 if (msg != supplied_msg) {
2993                                         CM_Free(msg);
2994                                 }
2995                         }
2996         
2997                 }
2998         }
2999
3000         else {
3001                 MSGM_syslog(LOG_DEBUG, "CtdlSaveMsgPointerInRoom() skips repl checks\n");
3002         }
3003
3004         /* Submit this room for processing by hooks */
3005         PerformRoomHooks(&CCC->room);
3006
3007         /* Go back to the room we were in before we wandered here... */
3008         CtdlGetRoom(&CCC->room, hold_rm);
3009
3010         /* Bump the reference count for all messages which were merged */
3011         if (!suppress_refcount_adj) {
3012                 AdjRefCountList(msgs_to_be_merged, num_msgs_to_be_merged, +1);
3013         }
3014
3015         /* Free up memory... */
3016         if (msgs_to_be_merged != NULL) {
3017                 free(msgs_to_be_merged);
3018         }
3019
3020         /* Return success. */
3021         return (0);
3022 }
3023
3024
3025 /*
3026  * This is the same as CtdlSaveMsgPointersInRoom() but it only accepts
3027  * a single message.
3028  */
3029 int CtdlSaveMsgPointerInRoom(char *roomname, long msgid,
3030                              int do_repl_check, struct CtdlMessage *supplied_msg)
3031 {
3032         return CtdlSaveMsgPointersInRoom(roomname, &msgid, 1, do_repl_check, supplied_msg, 0);
3033 }
3034
3035
3036
3037
3038 /*
3039  * Message base operation to save a new message to the message store
3040  * (returns new message number)
3041  *
3042  * This is the back end for CtdlSubmitMsg() and should not be directly
3043  * called by server-side modules.
3044  *
3045  */
3046 long send_message(struct CtdlMessage *msg) {
3047         struct CitContext *CCC = CC;
3048         long newmsgid;
3049         long retval;
3050         char msgidbuf[256];
3051         long msgidbuflen;
3052         struct ser_ret smr;
3053         int is_bigmsg = 0;
3054         char *holdM = NULL;
3055
3056         /* Get a new message number */
3057         newmsgid = get_new_message_number();
3058         msgidbuflen = snprintf(msgidbuf, sizeof msgidbuf, "%08lX-%08lX@%s",
3059                                (long unsigned int) time(NULL),
3060                                (long unsigned int) newmsgid,
3061                                config.c_fqdn
3062                 );
3063
3064         /* Generate an ID if we don't have one already */
3065         if (CM_IsEmpty(msg, emessageId)) {
3066                 CM_SetField(msg, emessageId, msgidbuf, msgidbuflen);
3067         }
3068
3069         /* If the message is big, set its body aside for storage elsewhere */
3070         if (!CM_IsEmpty(msg, eMesageText)) {
3071                 if (strlen(msg->cm_fields[eMesageText]) > BIGMSG) {
3072                         is_bigmsg = 1;
3073                         holdM = msg->cm_fields[eMesageText];
3074                         msg->cm_fields[eMesageText] = NULL;
3075                 }
3076         }
3077
3078         /* Serialize our data structure for storage in the database */  
3079         serialize_message(&smr, msg);
3080
3081         if (is_bigmsg) {
3082                 msg->cm_fields[eMesageText] = holdM;
3083         }
3084
3085         if (smr.len == 0) {
3086                 cprintf("%d Unable to serialize message\n",
3087                         ERROR + INTERNAL_ERROR);
3088                 return (-1L);
3089         }
3090
3091         /* Write our little bundle of joy into the message base */
3092         if (cdb_store(CDB_MSGMAIN, &newmsgid, (int)sizeof(long),
3093                       smr.ser, smr.len) < 0) {
3094                 MSGM_syslog(LOG_ERR, "Can't store message\n");
3095                 retval = 0L;
3096         } else {
3097                 if (is_bigmsg) {
3098                         cdb_store(CDB_BIGMSGS,
3099                                   &newmsgid,
3100                                   (int)sizeof(long),
3101                                   holdM,
3102                                   (strlen(holdM) + 1)
3103                                 );
3104                 }
3105                 retval = newmsgid;
3106         }
3107
3108         /* Free the memory we used for the serialized message */
3109         free(smr.ser);
3110
3111         /* Return the *local* message ID to the caller
3112          * (even if we're storing an incoming network message)
3113          */
3114         return(retval);
3115 }
3116
3117
3118
3119 /*
3120  * Serialize a struct CtdlMessage into the format used on disk and network.
3121  * 
3122  * This function loads up a "struct ser_ret" (defined in server.h) which
3123  * contains the length of the serialized message and a pointer to the
3124  * serialized message in memory.  THE LATTER MUST BE FREED BY THE CALLER.
3125  */
3126 void serialize_message(struct ser_ret *ret,             /* return values */
3127                        struct CtdlMessage *msg) /* unserialized msg */
3128 {
3129         struct CitContext *CCC = CC;
3130         size_t wlen, fieldlen;
3131         int i;
3132         long lengths[NDiskFields];
3133         
3134         memset(lengths, 0, sizeof(lengths));
3135
3136         /*
3137          * Check for valid message format
3138          */
3139         if (CM_IsValidMsg(msg) == 0) {
3140                 MSGM_syslog(LOG_ERR, "serialize_message() aborting due to invalid message\n");
3141                 ret->len = 0;
3142                 ret->ser = NULL;
3143                 return;
3144         }
3145
3146         ret->len = 3;
3147         for (i=0; i < NDiskFields; ++i)
3148                 if (msg->cm_fields[FieldOrder[i]] != NULL)
3149                 {
3150                         lengths[i] = strlen(msg->cm_fields[FieldOrder[i]]);
3151                         ret->len += lengths[i] + 2;
3152                 }
3153
3154         ret->ser = malloc(ret->len);
3155         if (ret->ser == NULL) {
3156                 MSG_syslog(LOG_ERR, "serialize_message() malloc(%ld) failed: %s\n",
3157                            (long)ret->len, strerror(errno));
3158                 ret->len = 0;
3159                 ret->ser = NULL;
3160                 return;
3161         }
3162
3163         ret->ser[0] = 0xFF;
3164         ret->ser[1] = msg->cm_anon_type;
3165         ret->ser[2] = msg->cm_format_type;
3166         wlen = 3;
3167
3168         for (i=0; i < NDiskFields; ++i)
3169                 if (msg->cm_fields[FieldOrder[i]] != NULL)
3170                 {
3171                         fieldlen = lengths[i];
3172                         ret->ser[wlen++] = (char)FieldOrder[i];
3173
3174                         memcpy(&ret->ser[wlen],
3175                                msg->cm_fields[FieldOrder[i]],
3176                                fieldlen+1);
3177
3178                         wlen = wlen + fieldlen + 1;
3179                 }
3180
3181         if (ret->len != wlen) {
3182                 MSG_syslog(LOG_ERR, "ERROR: len=%ld wlen=%ld\n",
3183                            (long)ret->len, (long)wlen);
3184         }
3185
3186         return;
3187 }
3188
3189
3190 /*
3191  * Check to see if any messages already exist in the current room which
3192  * carry the same Exclusive ID as this one.  If any are found, delete them.
3193  */
3194 void ReplicationChecks(struct CtdlMessage *msg) {
3195         struct CitContext *CCC = CC;
3196         long old_msgnum = (-1L);
3197
3198         if (DoesThisRoomNeedEuidIndexing(&CCC->room) == 0) return;
3199
3200         MSG_syslog(LOG_DEBUG, "Performing replication checks in <%s>\n",
3201                    CCC->room.QRname);
3202
3203         /* No exclusive id?  Don't do anything. */
3204         if (msg == NULL) return;
3205         if (CM_IsEmpty(msg, eExclusiveID)) return;
3206
3207         /*MSG_syslog(LOG_DEBUG, "Exclusive ID: <%s> for room <%s>\n",
3208           msg->cm_fields[eExclusiveID], CCC->room.QRname);*/
3209
3210         old_msgnum = CtdlLocateMessageByEuid(msg->cm_fields[eExclusiveID], &CCC->room);
3211         if (old_msgnum > 0L) {
3212                 MSG_syslog(LOG_DEBUG, "ReplicationChecks() replacing message %ld\n", old_msgnum);
3213                 CtdlDeleteMessages(CCC->room.QRname, &old_msgnum, 1, "");
3214         }
3215 }
3216
3217
3218
3219 /*
3220  * Save a message to disk and submit it into the delivery system.
3221  */
3222 long CtdlSubmitMsg(struct CtdlMessage *msg,     /* message to save */
3223                    struct recptypes *recps,     /* recipients (if mail) */
3224                    const char *force,           /* force a particular room? */
3225                    int flags                    /* should the message be exported clean? */
3226         )
3227 {
3228         char submit_filename[128];
3229         char hold_rm[ROOMNAMELEN];
3230         char actual_rm[ROOMNAMELEN];
3231         char force_room[ROOMNAMELEN];
3232         char content_type[SIZ];                 /* We have to learn this */
3233         char recipient[SIZ];
3234         const char *room;
3235         long newmsgid;
3236         const char *mptr = NULL;
3237         struct ctdluser userbuf;
3238         int a, i;
3239         struct MetaData smi;
3240         FILE *network_fp = NULL;
3241         static int seqnum = 1;
3242         struct CtdlMessage *imsg = NULL;
3243         char *instr = NULL;
3244         size_t instr_alloc = 0;
3245         struct ser_ret smr;
3246         char *hold_R, *hold_D;
3247         char *collected_addresses = NULL;
3248         struct addresses_to_be_filed *aptr = NULL;
3249         StrBuf *saved_rfc822_version = NULL;
3250         int qualified_for_journaling = 0;
3251         CitContext *CCC = MyContext();
3252         char bounce_to[1024] = "";
3253         int rv = 0;
3254
3255         MSGM_syslog(LOG_DEBUG, "CtdlSubmitMsg() called\n");
3256         if (CM_IsValidMsg(msg) == 0) return(-1);        /* self check */
3257
3258         /* If this message has no timestamp, we take the liberty of
3259          * giving it one, right now.
3260          */
3261         if (CM_IsEmpty(msg, eTimestamp)) {
3262                 CM_SetFieldLONG(msg, eTimestamp, time(NULL));
3263         }
3264
3265         /* If this message has no path, we generate one.
3266          */
3267         if (CM_IsEmpty(msg, eMessagePath)) {
3268                 if (!CM_IsEmpty(msg, eAuthor)) {
3269                         CM_CopyField(msg, eMessagePath, eAuthor);
3270                         for (a=0; !IsEmptyStr(&msg->cm_fields[eMessagePath][a]); ++a) {
3271                                 if (isspace(msg->cm_fields[eMessagePath][a])) {
3272                                         msg->cm_fields[eMessagePath][a] = ' ';
3273                                 }
3274                         }
3275                 }
3276                 else {
3277                         CM_SetField(msg, eMessagePath, HKEY("unknown"));
3278                 }
3279         }
3280
3281         if (force == NULL) {
3282                 force_room[0] = '\0';
3283         }
3284         else {
3285                 strcpy(force_room, force);
3286         }
3287
3288         /* Learn about what's inside, because it's what's inside that counts */
3289         if (CM_IsEmpty(msg, eMesageText)) {
3290                 MSGM_syslog(LOG_ERR, "ERROR: attempt to save message with NULL body\n");
3291                 return(-2);
3292         }
3293
3294         switch (msg->cm_format_type) {
3295         case 0:
3296                 strcpy(content_type, "text/x-citadel-variformat");
3297                 break;
3298         case 1:
3299                 strcpy(content_type, "text/plain");
3300                 break;
3301         case 4:
3302                 strcpy(content_type, "text/plain");
3303                 mptr = bmstrcasestr(msg->cm_fields[eMesageText], "Content-type:");
3304                 if (mptr != NULL) {
3305                         char *aptr;
3306                         safestrncpy(content_type, &mptr[13], sizeof content_type);
3307                         striplt(content_type);
3308                         aptr = content_type;
3309                         while (!IsEmptyStr(aptr)) {
3310                                 if ((*aptr == ';')
3311                                     || (*aptr == ' ')
3312                                     || (*aptr == 13)
3313                                     || (*aptr == 10)) {
3314                                         *aptr = 0;
3315                                 }
3316                                 else aptr++;
3317                         }
3318                 }
3319         }
3320
3321         /* Goto the correct room */
3322         room = (recps) ? CCC->room.QRname : SENTITEMS;
3323         MSG_syslog(LOG_DEBUG, "Selected room %s\n", room);
3324         strcpy(hold_rm, CCC->room.QRname);
3325         strcpy(actual_rm, CCC->room.QRname);
3326         if (recps != NULL) {
3327                 strcpy(actual_rm, SENTITEMS);
3328         }
3329
3330         /* If the user is a twit, move to the twit room for posting */
3331         if (TWITDETECT) {
3332                 if (CCC->user.axlevel == AxProbU) {
3333                         strcpy(hold_rm, actual_rm);
3334                         strcpy(actual_rm, config.c_twitroom);
3335                         MSGM_syslog(LOG_DEBUG, "Diverting to twit room\n");
3336                 }
3337         }
3338
3339         /* ...or if this message is destined for Aide> then go there. */
3340         if (!IsEmptyStr(force_room)) {
3341                 strcpy(actual_rm, force_room);
3342         }
3343
3344         MSG_syslog(LOG_INFO, "Final selection: %s (%s)\n", actual_rm, room);
3345         if (strcasecmp(actual_rm, CCC->room.QRname)) {
3346                 /* CtdlGetRoom(&CCC->room, actual_rm); */
3347                 CtdlUserGoto(actual_rm, 0, 1, NULL, NULL);
3348         }
3349
3350         /*
3351          * If this message has no O (room) field, generate one.
3352          */
3353         if (CM_IsEmpty(msg, eOriginalRoom)) {
3354                 CM_SetField(msg, eOriginalRoom, CCC->room.QRname, strlen(CCC->room.QRname));
3355         }
3356
3357         /* Perform "before save" hooks (aborting if any return nonzero) */
3358         MSGM_syslog(LOG_DEBUG, "Performing before-save hooks\n");
3359         if (PerformMessageHooks(msg, EVT_BEFORESAVE) > 0) return(-3);
3360
3361         /*
3362          * If this message has an Exclusive ID, and the room is replication
3363          * checking enabled, then do replication checks.
3364          */
3365         if (DoesThisRoomNeedEuidIndexing(&CCC->room)) {
3366                 ReplicationChecks(msg);
3367         }
3368
3369         /* Save it to disk */
3370         MSGM_syslog(LOG_DEBUG, "Saving to disk\n");
3371         newmsgid = send_message(msg);
3372         if (newmsgid <= 0L) return(-5);
3373
3374         /* Write a supplemental message info record.  This doesn't have to
3375          * be a critical section because nobody else knows about this message
3376          * yet.
3377          */
3378         MSGM_syslog(LOG_DEBUG, "Creating MetaData record\n");
3379         memset(&smi, 0, sizeof(struct MetaData));
3380         smi.meta_msgnum = newmsgid;
3381         smi.meta_refcount = 0;
3382         safestrncpy(smi.meta_content_type, content_type,
3383                     sizeof smi.meta_content_type);
3384
3385         /*
3386          * Measure how big this message will be when rendered as RFC822.
3387          * We do this for two reasons:
3388          * 1. We need the RFC822 length for the new metadata record, so the
3389          *    POP and IMAP services don't have to calculate message lengths
3390          *    while the user is waiting (multiplied by potentially hundreds
3391          *    or thousands of messages).
3392          * 2. If journaling is enabled, we will need an RFC822 version of the
3393          *    message to attach to the journalized copy.
3394          */
3395         if (CCC->redirect_buffer != NULL) {
3396                 MSGM_syslog(LOG_ALERT, "CCC->redirect_buffer is not NULL during message submission!\n");
3397                 abort();
3398         }
3399         CCC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
3400         CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_ALL, 0, 1, QP_EADDR);
3401         smi.meta_rfc822_length = StrLength(CCC->redirect_buffer);
3402         saved_rfc822_version = CCC->redirect_buffer;
3403         CCC->redirect_buffer = NULL;
3404
3405         PutMetaData(&smi);
3406
3407         /* Now figure out where to store the pointers */
3408         MSGM_syslog(LOG_DEBUG, "Storing pointers\n");
3409
3410         /* If this is being done by the networker delivering a private
3411          * message, we want to BYPASS saving the sender's copy (because there
3412          * is no local sender; it would otherwise go to the Trashcan).
3413          */
3414         if ((!CCC->internal_pgm) || (recps == NULL)) {
3415                 if (CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 1, msg) != 0) {
3416                         MSGM_syslog(LOG_ERR, "ERROR saving message pointer!\n");
3417                         CtdlSaveMsgPointerInRoom(config.c_aideroom, newmsgid, 0, msg);
3418                 }
3419         }
3420
3421         /* For internet mail, drop a copy in the outbound queue room */
3422         if ((recps != NULL) && (recps->num_internet > 0)) {
3423                 CtdlSaveMsgPointerInRoom(SMTP_SPOOLOUT_ROOM, newmsgid, 0, msg);
3424         }
3425
3426         /* If other rooms are specified, drop them there too. */
3427         if ((recps != NULL) && (recps->num_room > 0))
3428                 for (i=0; i<num_tokens(recps->recp_room, '|'); ++i) {
3429                         extract_token(recipient, recps->recp_room, i,
3430                                       '|', sizeof recipient);
3431                         MSG_syslog(LOG_DEBUG, "Delivering to room <%s>\n", recipient);///// xxxx
3432                         CtdlSaveMsgPointerInRoom(recipient, newmsgid, 0, msg);
3433                 }
3434
3435         /* Bump this user's messages posted counter. */
3436         MSGM_syslog(LOG_DEBUG, "Updating user\n");
3437         CtdlGetUserLock(&CCC->user, CCC->curr_user);
3438         CCC->user.posted = CCC->user.posted + 1;
3439         CtdlPutUserLock(&CCC->user);
3440
3441         /* Decide where bounces need to be delivered */
3442         if ((recps != NULL) && (recps->bounce_to != NULL)) {
3443                 safestrncpy(bounce_to, recps->bounce_to, sizeof bounce_to);
3444         }
3445         else if (CCC->logged_in) {
3446                 snprintf(bounce_to, sizeof bounce_to, "%s@%s", CCC->user.fullname, config.c_nodename);
3447         }
3448         else {
3449                 snprintf(bounce_to, sizeof bounce_to, "%s@%s", msg->cm_fields[eAuthor], msg->cm_fields[eNodeName]);
3450         }
3451
3452         /* If this is private, local mail, make a copy in the
3453          * recipient's mailbox and bump the reference count.
3454          */
3455         if ((recps != NULL) && (recps->num_local > 0))
3456                 for (i=0; i<num_tokens(recps->recp_local, '|'); ++i) {
3457                         long recipientlen;
3458                         recipientlen = extract_token(recipient,
3459                                                      recps->recp_local, i,
3460                                                      '|', sizeof recipient);
3461                         MSG_syslog(LOG_DEBUG, "Delivering private local mail to <%s>\n",
3462                                recipient);
3463                         if (CtdlGetUser(&userbuf, recipient) == 0) {
3464                                 CtdlMailboxName(actual_rm, sizeof actual_rm, &userbuf, MAILROOM);
3465                                 CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 0, msg);
3466                                 CtdlBumpNewMailCounter(userbuf.usernum);
3467                                 if (!IsEmptyStr(config.c_funambol_host) || !IsEmptyStr(config.c_pager_program)) {
3468                                         /* Generate a instruction message for the Funambol notification
3469                                          * server, in the same style as the SMTP queue
3470                                          */
3471                                         long instrlen;
3472                                         instr_alloc = 1024;
3473                                         instr = malloc(instr_alloc);
3474                                         instrlen = snprintf(
3475                                                 instr, instr_alloc,
3476                                                 "Content-type: %s\n\nmsgid|%ld\nsubmitted|%ld\n"
3477                                                 "bounceto|%s\n",
3478                                                 SPOOLMIME,
3479                                                 newmsgid,
3480                                                 (long)time(NULL), //todo: time() is expensive!
3481                                                 bounce_to
3482                                                 );
3483                                 
3484                                         imsg = malloc(sizeof(struct CtdlMessage));
3485                                         memset(imsg, 0, sizeof(struct CtdlMessage));
3486                                         imsg->cm_magic = CTDLMESSAGE_MAGIC;
3487                                         imsg->cm_anon_type = MES_NORMAL;
3488                                         imsg->cm_format_type = FMT_RFC822;
3489                                         CM_SetField(imsg, eMsgSubject, HKEY("QMSG"));
3490                                         CM_SetField(imsg, eAuthor, HKEY("Citadel"));
3491                                         CM_SetField(imsg, eJournal, HKEY("do not journal"));
3492                                         CM_SetAsField(imsg, eMesageText, &instr, instrlen);
3493                                         CM_SetField(imsg, eExtnotify, recipient, recipientlen);
3494                                         CtdlSubmitMsg(imsg, NULL, FNBL_QUEUE_ROOM, 0);
3495                                         CM_Free(imsg);
3496                                 }
3497                         }
3498                         else {
3499                                 MSG_syslog(LOG_DEBUG, "No user <%s>\n", recipient);
3500                                 CtdlSaveMsgPointerInRoom(config.c_aideroom, newmsgid, 0, msg);
3501                         }
3502                 }
3503
3504         /* Perform "after save" hooks */
3505         MSGM_syslog(LOG_DEBUG, "Performing after-save hooks\n");
3506
3507         CM_SetFieldLONG(msg, eVltMsgNum, newmsgid);
3508         PerformMessageHooks(msg, EVT_AFTERSAVE);
3509         CM_FlushField(msg, eVltMsgNum);
3510
3511         /* For IGnet mail, we have to save a new copy into the spooler for
3512          * each recipient, with the R and D fields set to the recipient and
3513          * destination-node.  This has two ugly side effects: all other
3514          * recipients end up being unlisted in this recipient's copy of the
3515          * message, and it has to deliver multiple messages to the same
3516          * node.  We'll revisit this again in a year or so when everyone has
3517          * a network spool receiver that can handle the new style messages.
3518          */
3519         if ((recps != NULL) && (recps->num_ignet > 0))
3520                 for (i=0; i<num_tokens(recps->recp_ignet, '|'); ++i) {
3521                         extract_token(recipient, recps->recp_ignet, i,
3522                                       '|', sizeof recipient);
3523
3524                         hold_R = msg->cm_fields[eRecipient];
3525                         hold_D = msg->cm_fields[eDestination];
3526                         msg->cm_fields[eRecipient] = malloc(SIZ);
3527                         msg->cm_fields[eDestination] = malloc(128);
3528                         extract_token(msg->cm_fields[eRecipient], recipient, 0, '@', SIZ);
3529                         extract_token(msg->cm_fields[eDestination], recipient, 1, '@', 128);
3530                 
3531                         serialize_message(&smr, msg);
3532                         if (smr.len > 0) {
3533                                 snprintf(submit_filename, sizeof submit_filename,
3534                                          "%s/netmail.%04lx.%04x.%04x",
3535                                          ctdl_netin_dir,
3536                                          (long) getpid(), CCC->cs_pid, ++seqnum);
3537                                 network_fp = fopen(submit_filename, "wb+");
3538                                 if (network_fp != NULL) {
3539                                         rv = fwrite(smr.ser, smr.len, 1, network_fp);
3540                                         if (rv == -1) {
3541                                                 MSG_syslog(LOG_EMERG, "CtdlSubmitMsg(): Couldn't write network spool file: %s\n",
3542                                                            strerror(errno));
3543                                         }
3544                                         fclose(network_fp);
3545                                 }
3546                                 free(smr.ser);
3547                         }
3548
3549                         free(msg->cm_fields[eRecipient]);
3550                         free(msg->cm_fields[eDestination]);
3551                         msg->cm_fields[eRecipient] = hold_R;
3552                         msg->cm_fields[eDestination] = hold_D;
3553                 }
3554
3555         /* Go back to the room we started from */
3556         MSG_syslog(LOG_DEBUG, "Returning to original room %s\n", hold_rm);
3557         if (strcasecmp(hold_rm, CCC->room.QRname))
3558                 CtdlUserGoto(hold_rm, 0, 1, NULL, NULL);
3559
3560         /* For internet mail, generate delivery instructions.
3561          * Yes, this is recursive.  Deal with it.  Infinite recursion does
3562          * not happen because the delivery instructions message does not
3563          * contain a recipient.
3564          */
3565         if ((recps != NULL) && (recps->num_internet > 0)) {
3566                 StrBuf *SpoolMsg = NewStrBuf();
3567                 long nTokens;
3568
3569                 MSGM_syslog(LOG_DEBUG, "Generating delivery instructions\n");
3570
3571                 StrBufPrintf(SpoolMsg,
3572                              "Content-type: "SPOOLMIME"\n"
3573                              "\n"
3574                              "msgid|%ld\n"
3575                              "submitted|%ld\n"
3576                              "bounceto|%s\n",
3577                              newmsgid,
3578                              (long)time(NULL),
3579                              bounce_to);
3580
3581                 if (recps->envelope_from != NULL) {
3582                         StrBufAppendBufPlain(SpoolMsg, HKEY("envelope_from|"), 0);
3583                         StrBufAppendBufPlain(SpoolMsg, recps->envelope_from, -1, 0);
3584                         StrBufAppendBufPlain(SpoolMsg, HKEY("\n"), 0);
3585                 }
3586                 if (recps->sending_room != NULL) {
3587                         StrBufAppendBufPlain(SpoolMsg, HKEY("source_room|"), 0);
3588                         StrBufAppendBufPlain(SpoolMsg, recps->sending_room, -1, 0);
3589                         StrBufAppendBufPlain(SpoolMsg, HKEY("\n"), 0);
3590                 }
3591
3592                 nTokens = num_tokens(recps->recp_internet, '|');
3593                 for (i = 0; i < nTokens; i++) {
3594                         long len;
3595                         len = extract_token(recipient, recps->recp_internet, i, '|', sizeof recipient);
3596                         if (len > 0) {
3597                                 StrBufAppendBufPlain(SpoolMsg, HKEY("remote|"), 0);
3598                                 StrBufAppendBufPlain(SpoolMsg, recipient, len, 0);
3599                                 StrBufAppendBufPlain(SpoolMsg, HKEY("|0||\n"), 0);
3600                         }
3601                 }
3602
3603                 imsg = malloc(sizeof(struct CtdlMessage));
3604                 memset(imsg, 0, sizeof(struct CtdlMessage));
3605                 imsg->cm_magic = CTDLMESSAGE_MAGIC;
3606                 imsg->cm_anon_type = MES_NORMAL;
3607                 imsg->cm_format_type = FMT_RFC822;
3608                 imsg->cm_fields[eMsgSubject] = strdup("QMSG");
3609                 imsg->cm_fields[eAuthor] = strdup("Citadel");
3610                 imsg->cm_fields[eJournal] = strdup("do not journal");
3611                 imsg->cm_fields[eMesageText] = SmashStrBuf(&SpoolMsg);  /* imsg owns this memory now */
3612                 CtdlSubmitMsg(imsg, NULL, SMTP_SPOOLOUT_ROOM, QP_EADDR);
3613                 CM_Free(imsg);
3614         }
3615
3616         /*
3617          * Any addresses to harvest for someone's address book?
3618          */
3619         if ( (CCC->logged_in) && (recps != NULL) ) {
3620                 collected_addresses = harvest_collected_addresses(msg);
3621         }
3622
3623         if (collected_addresses != NULL) {
3624                 aptr = (struct addresses_to_be_filed *)
3625                         malloc(sizeof(struct addresses_to_be_filed));
3626                 CtdlMailboxName(actual_rm, sizeof actual_rm,
3627                                 &CCC->user, USERCONTACTSROOM);
3628                 aptr->roomname = strdup(actual_rm);
3629                 aptr->collected_addresses = collected_addresses;
3630                 begin_critical_section(S_ATBF);
3631                 aptr->next = atbf;
3632                 atbf = aptr;
3633                 end_critical_section(S_ATBF);
3634         }
3635
3636         /*
3637          * Determine whether this message qualifies for journaling.
3638          */
3639         if (!CM_IsEmpty(msg, eJournal)) {
3640                 qualified_for_journaling = 0;
3641         }
3642         else {
3643                 if (recps == NULL) {
3644                         qualified_for_journaling = config.c_journal_pubmsgs;
3645                 }
3646                 else if (recps->num_local + recps->num_ignet + recps->num_internet > 0) {
3647                         qualified_for_journaling = config.c_journal_email;
3648                 }
3649                 else {
3650                         qualified_for_journaling = config.c_journal_pubmsgs;
3651                 }
3652         }
3653
3654         /*
3655          * Do we have to perform journaling?  If so, hand off the saved
3656          * RFC822 version will be handed off to the journaler for background
3657          * submit.  Otherwise, we have to free the memory ourselves.
3658          */
3659         if (saved_rfc822_version != NULL) {
3660                 if (qualified_for_journaling) {
3661                         JournalBackgroundSubmit(msg, saved_rfc822_version, recps);
3662                 }
3663                 else {
3664                         FreeStrBuf(&saved_rfc822_version);
3665                 }
3666         }
3667
3668         /* Done. */
3669         return(newmsgid);
3670 }
3671
3672
3673 /*
3674  * Convenience function for generating small administrative messages.
3675  */
3676 void quickie_message(const char *from,
3677                      const char *fromaddr,
3678                      const char *to,
3679                      char *room,
3680                      const char *text, 
3681                      int format_type,
3682                      const char *subject)
3683 {
3684         struct CtdlMessage *msg;
3685         struct recptypes *recp = NULL;
3686
3687         msg = malloc(sizeof(struct CtdlMessage));
3688         memset(msg, 0, sizeof(struct CtdlMessage));
3689         msg->cm_magic = CTDLMESSAGE_MAGIC;
3690         msg->cm_anon_type = MES_NORMAL;
3691         msg->cm_format_type = format_type;
3692
3693         if (from != NULL) {
3694                 msg->cm_fields[eAuthor] = strdup(from);
3695         }
3696         else if (fromaddr != NULL) {
3697                 msg->cm_fields[eAuthor] = strdup(fromaddr);
3698                 if (strchr(msg->cm_fields[eAuthor], '@')) {
3699                         *strchr(msg->cm_fields[eAuthor], '@') = 0;
3700                 }
3701         }
3702         else {
3703                 msg->cm_fields[eAuthor] = strdup("Citadel");
3704         }
3705
3706         if (fromaddr != NULL) msg->cm_fields[erFc822Addr] = strdup(fromaddr);
3707         if (room != NULL) msg->cm_fields[eOriginalRoom] = strdup(room);
3708         msg->cm_fields[eNodeName] = strdup(NODENAME);
3709         if (to != NULL) {
3710                 msg->cm_fields[eRecipient] = strdup(to);
3711                 recp = validate_recipients(to, NULL, 0);
3712         }
3713         if (subject != NULL) {
3714                 msg->cm_fields[eMsgSubject] = strdup(subject);
3715         }
3716         msg->cm_fields[eMesageText] = strdup(text);
3717
3718         CtdlSubmitMsg(msg, recp, room, 0);
3719         CM_Free(msg);
3720         if (recp != NULL) free_recipients(recp);
3721 }
3722
3723 void flood_protect_quickie_message(const char *from,
3724                                    const char *fromaddr,
3725                                    const char *to,
3726                                    char *room,
3727                                    const char *text, 
3728                                    int format_type,
3729                                    const char *subject,
3730                                    int nCriterions,
3731                                    const char **CritStr,
3732                                    long *CritStrLen,
3733                                    long ccid,
3734                                    long ioid,
3735                                    time_t NOW)
3736 {
3737         int i;
3738         u_char rawdigest[MD5_DIGEST_LEN];
3739         struct MD5Context md5context;
3740         StrBuf *guid;
3741         char timestamp[64];
3742         long tslen;
3743         time_t tsday = NOW / (8*60*60); /* just care for a day... */
3744
3745         tslen = snprintf(timestamp, sizeof(timestamp), "%ld", tsday);
3746         MD5Init(&md5context);
3747
3748         for (i = 0; i < nCriterions; i++)
3749                 MD5Update(&md5context,
3750                           (const unsigned char*)CritStr[i], CritStrLen[i]);
3751         MD5Update(&md5context,
3752                   (const unsigned char*)timestamp, tslen);
3753         MD5Final(rawdigest, &md5context);
3754
3755         guid = NewStrBufPlain(NULL,
3756                               MD5_DIGEST_LEN * 2 + 12);
3757         StrBufHexEscAppend(guid, NULL, rawdigest, MD5_DIGEST_LEN);
3758         StrBufAppendBufPlain(guid, HKEY("_fldpt"), 0);
3759         if (StrLength(guid) > 40)
3760                 StrBufCutAt(guid, 40, NULL);
3761
3762         if (CheckIfAlreadySeen("FPAideMessage",
3763                                guid,
3764                                NOW,
3765                                tsday,
3766                                eUpdate,
3767                                ccid,
3768                                ioid)!= 0)
3769         {
3770                 FreeStrBuf(&guid);
3771                 /* yes, we did. flood protection kicks in. */
3772                 syslog(LOG_DEBUG,
3773                        "not sending message again\n");
3774                 return;
3775         }
3776         FreeStrBuf(&guid);
3777         /* no, this message isn't sent recently; go ahead. */
3778         quickie_message(from,
3779                         fromaddr,
3780                         to,
3781                         room,
3782                         text, 
3783                         format_type,
3784                         subject);
3785 }
3786
3787
3788 /*
3789  * Back end function used by CtdlMakeMessage() and similar functions
3790  */
3791 StrBuf *CtdlReadMessageBodyBuf(char *terminator,        /* token signalling EOT */
3792                                long tlen,
3793                                size_t maxlen,           /* maximum message length */
3794                                StrBuf *exist,           /* if non-null, append to it;
3795                                                            exist is ALWAYS freed  */
3796                                int crlf,                /* CRLF newlines instead of LF */
3797                                int *sock                /* socket handle or 0 for this session's client socket */
3798         ) 
3799 {
3800         StrBuf *Message;
3801         StrBuf *LineBuf;
3802         int flushing = 0;
3803         int finished = 0;
3804         int dotdot = 0;
3805
3806         LineBuf = NewStrBufPlain(NULL, SIZ);
3807         if (exist == NULL) {
3808                 Message = NewStrBufPlain(NULL, 4 * SIZ);
3809         }
3810         else {
3811                 Message = NewStrBufDup(exist);
3812         }
3813
3814         /* Do we need to change leading ".." to "." for SMTP escaping? */
3815         if ((tlen == 1) && (*terminator == '.')) {
3816                 dotdot = 1;
3817         }
3818
3819         /* read in the lines of message text one by one */
3820         do {
3821                 if (sock != NULL) {
3822                         if ((CtdlSockGetLine(sock, LineBuf, 5) < 0) ||
3823                             (*sock == -1))
3824                                 finished = 1;
3825                 }
3826                 else {
3827                         if (CtdlClientGetLine(LineBuf) < 0) finished = 1;
3828                 }
3829                 if ((StrLength(LineBuf) == tlen) && 
3830                     (!strcmp(ChrPtr(LineBuf), terminator)))
3831                         finished = 1;
3832
3833                 if ( (!flushing) && (!finished) ) {
3834                         if (crlf) {
3835                                 StrBufAppendBufPlain(LineBuf, HKEY("\r\n"), 0);
3836                         }
3837                         else {
3838                                 StrBufAppendBufPlain(LineBuf, HKEY("\n"), 0);
3839                         }
3840                         
3841                         /* Unescape SMTP-style input of two dots at the beginning of the line */
3842                         if ((dotdot) &&
3843                             (StrLength(LineBuf) == 2) && 
3844                             (!strcmp(ChrPtr(LineBuf), "..")))
3845                         {
3846                                 StrBufCutLeft(LineBuf, 1);
3847                         }
3848                         
3849                         StrBufAppendBuf(Message, LineBuf, 0);
3850                 }
3851
3852                 /* if we've hit the max msg length, flush the rest */
3853                 if (StrLength(Message) >= maxlen) flushing = 1;
3854
3855         } while (!finished);
3856         FreeStrBuf(&LineBuf);
3857         return Message;
3858 }
3859
3860 void DeleteAsyncMsg(ReadAsyncMsg **Msg)
3861 {
3862         if (*Msg == NULL)
3863                 return;
3864         FreeStrBuf(&(*Msg)->MsgBuf);
3865
3866         free(*Msg);
3867         *Msg = NULL;
3868 }
3869
3870 ReadAsyncMsg *NewAsyncMsg(const char *terminator,       /* token signalling EOT */
3871                           long tlen,
3872                           size_t maxlen,                /* maximum message length */
3873                           size_t expectlen,             /* if we expect a message, how long should it be? */
3874                           StrBuf *exist,                /* if non-null, append to it;
3875                                                            exist is ALWAYS freed  */
3876                           long eLen,                    /* length of exist */
3877                           int crlf                      /* CRLF newlines instead of LF */
3878         )
3879 {
3880         ReadAsyncMsg *NewMsg;
3881
3882         NewMsg = (ReadAsyncMsg *)malloc(sizeof(ReadAsyncMsg));
3883         memset(NewMsg, 0, sizeof(ReadAsyncMsg));
3884
3885         if (exist == NULL) {
3886                 long len;
3887
3888                 if (expectlen == 0) {
3889                         len = 4 * SIZ;
3890                 }
3891                 else {
3892                         len = expectlen + 10;
3893                 }
3894                 NewMsg->MsgBuf = NewStrBufPlain(NULL, len);
3895         }
3896         else {
3897                 NewMsg->MsgBuf = NewStrBufDup(exist);
3898         }
3899         /* Do we need to change leading ".." to "." for SMTP escaping? */
3900         if ((tlen == 1) && (*terminator == '.')) {
3901                 NewMsg->dodot = 1;
3902         }
3903
3904         NewMsg->terminator = terminator;
3905         NewMsg->tlen = tlen;
3906
3907         NewMsg->maxlen = maxlen;
3908
3909         NewMsg->crlf = crlf;
3910
3911         return NewMsg;
3912 }
3913
3914 /*
3915  * Back end function used by CtdlMakeMessage() and similar functions
3916  */
3917 eReadState CtdlReadMessageBodyAsync(AsyncIO *IO)
3918 {
3919         ReadAsyncMsg *ReadMsg;
3920         int MsgFinished = 0;
3921         eReadState Finished = eMustReadMore;
3922
3923 #ifdef BIGBAD_IODBG
3924         char fn [SIZ];
3925         FILE *fd;
3926         const char *pch = ChrPtr(IO->SendBuf.Buf);
3927         const char *pchh = IO->SendBuf.ReadWritePointer;
3928         long nbytes;
3929         
3930         if (pchh == NULL)
3931                 pchh = pch;
3932         
3933         nbytes = StrLength(IO->SendBuf.Buf) - (pchh - pch);
3934         snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
3935                  ((CitContext*)(IO->CitContext))->ServiceName,
3936                  IO->SendBuf.fd);
3937         
3938         fd = fopen(fn, "a+");
3939 #endif
3940
3941         ReadMsg = IO->ReadMsg;
3942
3943         /* read in the lines of message text one by one */
3944         do {
3945                 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
3946                 
3947                 switch (Finished) {
3948                 case eMustReadMore: /// read new from socket... 
3949 #ifdef BIGBAD_IODBG
3950                         if (IO->RecvBuf.ReadWritePointer != NULL) {
3951                                 nbytes = StrLength(IO->RecvBuf.Buf) - (IO->RecvBuf.ReadWritePointer - ChrPtr(IO->RecvBuf.Buf));
3952                                 fprintf(fd, "Read; Line unfinished: %ld Bytes still in buffer [", nbytes);
3953                                 
3954                                 fwrite(IO->RecvBuf.ReadWritePointer, nbytes, 1, fd);
3955                         
3956                                 fprintf(fd, "]\n");
3957                         } else {
3958                                 fprintf(fd, "BufferEmpty! \n");
3959                         }
3960                         fclose(fd);
3961 #endif
3962                         return Finished;
3963                     break;
3964                 case eBufferNotEmpty: /* shouldn't happen... */
3965                 case eReadSuccess: /// done for now...
3966                     break;
3967                 case eReadFail: /// WHUT?
3968                     ///todo: shut down! 
3969                         break;
3970                 }
3971             
3972
3973                 if ((StrLength(IO->IOBuf) == ReadMsg->tlen) && 
3974                     (!strcmp(ChrPtr(IO->IOBuf), ReadMsg->terminator))) {
3975                         MsgFinished = 1;
3976 #ifdef BIGBAD_IODBG
3977                         fprintf(fd, "found Terminator; Message Size: %d\n", StrLength(ReadMsg->MsgBuf));
3978 #endif
3979                 }
3980                 else if (!ReadMsg->flushing) {
3981
3982 #ifdef BIGBAD_IODBG
3983                         fprintf(fd, "Read Line: [%d][%s]\n", StrLength(IO->IOBuf), ChrPtr(IO->IOBuf));
3984 #endif
3985
3986                         /* Unescape SMTP-style input of two dots at the beginning of the line */
3987                         if ((ReadMsg->dodot) &&
3988                             (StrLength(IO->IOBuf) == 2) &&  /* TODO: do we just unescape lines with two dots or any line? */
3989                             (!strcmp(ChrPtr(IO->IOBuf), "..")))
3990                         {
3991 #ifdef BIGBAD_IODBG
3992                                 fprintf(fd, "UnEscaped!\n");
3993 #endif
3994                                 StrBufCutLeft(IO->IOBuf, 1);
3995                         }
3996
3997                         if (ReadMsg->crlf) {
3998                                 StrBufAppendBufPlain(IO->IOBuf, HKEY("\r\n"), 0);
3999                         }
4000                         else {
4001                                 StrBufAppendBufPlain(IO->IOBuf, HKEY("\n"), 0);
4002                         }
4003
4004                         StrBufAppendBuf(ReadMsg->MsgBuf, IO->IOBuf, 0);
4005                 }
4006
4007                 /* if we've hit the max msg length, flush the rest */
4008                 if (StrLength(ReadMsg->MsgBuf) >= ReadMsg->maxlen) ReadMsg->flushing = 1;
4009
4010         } while (!MsgFinished);
4011
4012 #ifdef BIGBAD_IODBG
4013         fprintf(fd, "Done with reading; %s.\n, ",
4014                 (MsgFinished)?"Message Finished": "FAILED");
4015         fclose(fd);
4016 #endif
4017         if (MsgFinished)
4018                 return eReadSuccess;
4019         else 
4020                 return eAbort;
4021 }
4022
4023
4024 /*
4025  * Back end function used by CtdlMakeMessage() and similar functions
4026  */
4027 char *CtdlReadMessageBody(char *terminator,     /* token signalling EOT */
4028                           long tlen,
4029                           size_t maxlen,                /* maximum message length */
4030                           StrBuf *exist,                /* if non-null, append to it;
4031                                                    exist is ALWAYS freed  */
4032                           int crlf,             /* CRLF newlines instead of LF */
4033                           int *sock             /* socket handle or 0 for this session's client socket */
4034         ) 
4035 {
4036         StrBuf *Message;
4037
4038         Message = CtdlReadMessageBodyBuf(terminator,
4039                                          tlen,
4040                                          maxlen,
4041                                          exist,
4042                                          crlf,
4043                                          sock);
4044         if (Message == NULL)
4045                 return NULL;
4046         else
4047                 return SmashStrBuf(&Message);
4048 }
4049
4050
4051 /*
4052  * Build a binary message to be saved on disk.
4053  * (NOTE: if you supply 'preformatted_text', the buffer you give it
4054  * will become part of the message.  This means you are no longer
4055  * responsible for managing that memory -- it will be freed along with
4056  * the rest of the fields when CM_Free() is called.)
4057  */
4058
4059 struct CtdlMessage *CtdlMakeMessage(
4060         struct ctdluser *author,        /* author's user structure */
4061         char *recipient,                /* NULL if it's not mail */
4062         char *recp_cc,                  /* NULL if it's not mail */
4063         char *room,                     /* room where it's going */
4064         int type,                       /* see MES_ types in header file */
4065         int format_type,                /* variformat, plain text, MIME... */
4066         char *fake_name,                /* who we're masquerading as */
4067         char *my_email,                 /* which of my email addresses to use (empty is ok) */
4068         char *subject,                  /* Subject (optional) */
4069         char *supplied_euid,            /* ...or NULL if this is irrelevant */
4070         char *preformatted_text,        /* ...or NULL to read text from client */
4071         char *references                /* Thread references */
4072         ) {
4073         char dest_node[256];
4074         char buf[1024];
4075         struct CtdlMessage *msg;
4076         StrBuf *FakeAuthor;
4077         StrBuf *FakeEncAuthor = NULL;
4078
4079         msg = malloc(sizeof(struct CtdlMessage));
4080         memset(msg, 0, sizeof(struct CtdlMessage));
4081         msg->cm_magic = CTDLMESSAGE_MAGIC;
4082         msg->cm_anon_type = type;
4083         msg->cm_format_type = format_type;
4084
4085         /* Don't confuse the poor folks if it's not routed mail. */
4086         strcpy(dest_node, "");
4087
4088         if (recipient != NULL) striplt(recipient);
4089         if (recp_cc != NULL) striplt(recp_cc);
4090
4091         /* Path or Return-Path */
4092         if (my_email == NULL) my_email = "";
4093
4094         if (!IsEmptyStr(my_email)) {
4095                 msg->cm_fields[eMessagePath] = strdup(my_email);
4096         }
4097         else {
4098                 snprintf(buf, sizeof buf, "%s", author->fullname);
4099                 msg->cm_fields[eMessagePath] = strdup(buf);
4100         }
4101         convert_spaces_to_underscores(msg->cm_fields[eMessagePath]);
4102
4103         snprintf(buf, sizeof buf, "%ld", (long)time(NULL));     /* timestamp */
4104         msg->cm_fields[eTimestamp] = strdup(buf);
4105
4106         if ((fake_name != NULL) && (fake_name[0])) {            /* author */
4107                 FakeAuthor = NewStrBufPlain (fake_name, -1);
4108         }
4109         else {
4110                 FakeAuthor = NewStrBufPlain (author->fullname, -1);
4111         }
4112         StrBufRFC2047encode(&FakeEncAuthor, FakeAuthor);
4113         msg->cm_fields[eAuthor] = SmashStrBuf(&FakeEncAuthor);
4114         FreeStrBuf(&FakeAuthor);
4115
4116         if (CC->room.QRflags & QR_MAILBOX) {            /* room */
4117                 msg->cm_fields[eOriginalRoom] = strdup(&CC->room.QRname[11]);
4118         }
4119         else {
4120                 msg->cm_fields[eOriginalRoom] = strdup(CC->room.QRname);
4121         }
4122
4123         msg->cm_fields[eNodeName] = strdup(NODENAME);           /* nodename */
4124         msg->cm_fields[eHumanNode] = strdup(HUMANNODE);         /* hnodename */
4125
4126         if ((recipient != NULL) && (recipient[0] != 0)) {
4127                 msg->cm_fields[eRecipient] = strdup(recipient);
4128         }
4129         if ((recp_cc != NULL) && (recp_cc[0] != 0)) {
4130                 msg->cm_fields[eCarbonCopY] = strdup(recp_cc);
4131         }
4132         if (dest_node[0] != 0) {
4133                 msg->cm_fields[eDestination] = strdup(dest_node);
4134         }
4135
4136         if (!IsEmptyStr(my_email)) {
4137                 msg->cm_fields[erFc822Addr] = strdup(my_email);
4138         }
4139         else if ( (author == &CC->user) && (!IsEmptyStr(CC->cs_inet_email)) ) {
4140                 msg->cm_fields[erFc822Addr] = strdup(CC->cs_inet_email);
4141         }
4142
4143         if (subject != NULL) {
4144                 long length;
4145                 striplt(subject);
4146                 length = strlen(subject);
4147                 if (length > 0) {
4148                         long i;
4149                         long IsAscii;
4150                         IsAscii = -1;
4151                         i = 0;
4152                         while ((subject[i] != '\0') &&
4153                                (IsAscii = isascii(subject[i]) != 0 ))
4154                                 i++;
4155                         if (IsAscii != 0)
4156                                 msg->cm_fields[eMsgSubject] = strdup(subject);
4157                         else /* ok, we've got utf8 in the string. */
4158                         {
4159                                 msg->cm_fields[eMsgSubject] = rfc2047encode(subject, length);
4160                         }
4161
4162                 }
4163         }
4164
4165         if (supplied_euid != NULL) {
4166                 msg->cm_fields[eExclusiveID] = strdup(supplied_euid);
4167         }
4168
4169         if ((references != NULL) && (!IsEmptyStr(references))) {
4170                 if (msg->cm_fields[eWeferences] != NULL)
4171                         free(msg->cm_fields[eWeferences]);
4172                 msg->cm_fields[eWeferences] = strdup(references);
4173         }
4174
4175         if (preformatted_text != NULL) {
4176                 msg->cm_fields[eMesageText] = preformatted_text;
4177         }
4178         else {
4179                 msg->cm_fields[eMesageText] = CtdlReadMessageBody(HKEY("000"), config.c_maxmsglen, NULL, 0, 0);
4180         }
4181
4182         return(msg);
4183 }
4184
4185 /*
4186  * Check to see whether we have permission to post a message in the current
4187  * room.  Returns a *CITADEL ERROR CODE* and puts a message in errmsgbuf, or
4188  * returns 0 on success.
4189  */
4190 int CtdlDoIHavePermissionToPostInThisRoom(
4191         char *errmsgbuf, 
4192         size_t n, 
4193         const char* RemoteIdentifier,
4194         int PostPublic,
4195         int is_reply
4196         ) {
4197         int ra;
4198
4199         if (!(CC->logged_in) && 
4200             (PostPublic == POST_LOGGED_IN)) {
4201                 snprintf(errmsgbuf, n, "Not logged in.");
4202                 return (ERROR + NOT_LOGGED_IN);
4203         }
4204         else if (PostPublic == CHECK_EXISTANCE) {
4205                 return (0); // We're Evaling whether a recipient exists
4206         }
4207         else if (!(CC->logged_in)) {
4208                 
4209                 if ((CC->room.QRflags & QR_READONLY)) {
4210                         snprintf(errmsgbuf, n, "Not logged in.");
4211                         return (ERROR + NOT_LOGGED_IN);
4212                 }
4213                 if (CC->room.QRflags2 & QR2_MODERATED) {
4214                         snprintf(errmsgbuf, n, "Not logged in Moderation feature not yet implemented!");
4215                         return (ERROR + NOT_LOGGED_IN);
4216                 }
4217                 if ((PostPublic!=POST_LMTP) &&(CC->room.QRflags2 & QR2_SMTP_PUBLIC) == 0) {
4218
4219                         return CtdlNetconfigCheckRoomaccess(errmsgbuf, n, RemoteIdentifier);
4220                 }
4221                 return (0);
4222
4223         }
4224
4225         if ((CC->user.axlevel < AxProbU)
4226             && ((CC->room.QRflags & QR_MAILBOX) == 0)) {
4227                 snprintf(errmsgbuf, n, "Need to be validated to enter (except in %s> to sysop)", MAILROOM);
4228                 return (ERROR + HIGHER_ACCESS_REQUIRED);
4229         }
4230
4231         CtdlRoomAccess(&CC->room, &CC->user, &ra, NULL);
4232
4233         if (ra & UA_POSTALLOWED) {
4234                 strcpy(errmsgbuf, "OK to post or reply here");
4235                 return(0);
4236         }
4237
4238         if ( (ra & UA_REPLYALLOWED) && (is_reply) ) {
4239                 /*
4240                  * To be thorough, we ought to check to see if the message they are
4241                  * replying to is actually a valid one in this room, but unless this
4242                  * actually becomes a problem we'll go with high performance instead.
4243                  */
4244                 strcpy(errmsgbuf, "OK to reply here");
4245                 return(0);
4246         }
4247
4248         if ( (ra & UA_REPLYALLOWED) && (!is_reply) ) {
4249                 /* Clarify what happened with a better error message */
4250                 snprintf(errmsgbuf, n, "You may only reply to existing messages here.");
4251                 return (ERROR + HIGHER_ACCESS_REQUIRED);
4252         }
4253
4254         snprintf(errmsgbuf, n, "Higher access is required to post in this room.");
4255         return (ERROR + HIGHER_ACCESS_REQUIRED);
4256
4257 }
4258
4259
4260 /*
4261  * Check to see if the specified user has Internet mail permission
4262  * (returns nonzero if permission is granted)
4263  */
4264 int CtdlCheckInternetMailPermission(struct ctdluser *who) {
4265
4266         /* Do not allow twits to send Internet mail */
4267         if (who->axlevel <= AxProbU) return(0);
4268
4269         /* Globally enabled? */
4270         if (config.c_restrict == 0) return(1);
4271
4272         /* User flagged ok? */
4273         if (who->flags & US_INTERNET) return(2);
4274
4275         /* Admin level access? */
4276         if (who->axlevel >= AxAideU) return(3);
4277
4278         /* No mail for you! */
4279         return(0);
4280 }
4281
4282
4283 /*
4284  * Validate recipients, count delivery types and errors, and handle aliasing
4285  * FIXME check for dupes!!!!!
4286  *
4287  * Returns 0 if all addresses are ok, ret->num_error = -1 if no addresses 
4288  * were specified, or the number of addresses found invalid.
4289  *
4290  * Caller needs to free the result using free_recipients()
4291  */
4292 struct recptypes *validate_recipients(const char *supplied_recipients, 
4293                                       const char *RemoteIdentifier, 
4294                                       int Flags) {
4295         struct CitContext *CCC = CC;
4296         struct recptypes *ret;
4297         char *recipients = NULL;
4298         char *org_recp;
4299         char this_recp[256];
4300         char this_recp_cooked[256];
4301         char append[SIZ];
4302         long len;
4303         int num_recps = 0;
4304         int i, j;
4305         int mailtype;
4306         int invalid;
4307         struct ctdluser tempUS;
4308         struct ctdlroom tempQR;
4309         struct ctdlroom tempQR2;
4310         int err = 0;
4311         char errmsg[SIZ];
4312         int in_quotes = 0;
4313
4314         /* Initialize */
4315         ret = (struct recptypes *) malloc(sizeof(struct recptypes));
4316         if (ret == NULL) return(NULL);
4317
4318         /* Set all strings to null and numeric values to zero */
4319         memset(ret, 0, sizeof(struct recptypes));
4320
4321         if (supplied_recipients == NULL) {
4322                 recipients = strdup("");
4323         }
4324         else {
4325                 recipients = strdup(supplied_recipients);
4326         }
4327
4328         /* Allocate some memory.  Yes, this allocates 500% more memory than we will
4329          * actually need, but it's healthier for the heap than doing lots of tiny
4330          * realloc() calls instead.
4331          */
4332         len = strlen(recipients) + 1024;
4333         ret->errormsg = malloc(len);
4334         ret->recp_local = malloc(len);
4335         ret->recp_internet = malloc(len);
4336         ret->recp_ignet = malloc(len);
4337         ret->recp_room = malloc(len);
4338         ret->display_recp = malloc(len);
4339         ret->recp_orgroom = malloc(len);
4340         org_recp = malloc(len);
4341
4342         ret->errormsg[0] = 0;
4343         ret->recp_local[0] = 0;
4344         ret->recp_internet[0] = 0;
4345         ret->recp_ignet[0] = 0;
4346         ret->recp_room[0] = 0;
4347         ret->recp_orgroom[0] = 0;
4348         ret->display_recp[0] = 0;
4349
4350         ret->recptypes_magic = RECPTYPES_MAGIC;
4351
4352         /* Change all valid separator characters to commas */
4353         for (i=0; !IsEmptyStr(&recipients[i]); ++i) {
4354                 if ((recipients[i] == ';') || (recipients[i] == '|')) {
4355                         recipients[i] = ',';
4356                 }
4357         }
4358
4359         /* Now start extracting recipients... */
4360
4361         while (!IsEmptyStr(recipients)) {
4362                 for (i=0; i<=strlen(recipients); ++i) {
4363                         if (recipients[i] == '\"') in_quotes = 1 - in_quotes;
4364                         if ( ( (recipients[i] == ',') && (!in_quotes) ) || (recipients[i] == 0) ) {
4365                                 safestrncpy(this_recp, recipients, i+1);
4366                                 this_recp[i] = 0;
4367                                 if (recipients[i] == ',') {
4368                                         strcpy(recipients, &recipients[i+1]);
4369                                 }
4370                                 else {
4371                                         strcpy(recipients, "");
4372                                 }
4373                                 break;
4374                         }
4375                 }
4376
4377                 striplt(this_recp);
4378                 if (IsEmptyStr(this_recp))
4379                         break;
4380                 MSG_syslog(LOG_DEBUG, "Evaluating recipient #%d: %s\n", num_recps, this_recp);
4381                 ++num_recps;
4382
4383                 strcpy(org_recp, this_recp);
4384                 alias(this_recp);
4385                 alias(this_recp);
4386                 mailtype = alias(this_recp);
4387
4388                 for (j = 0; !IsEmptyStr(&this_recp[j]); ++j) {
4389                         if (this_recp[j]=='_') {
4390                                 this_recp_cooked[j] = ' ';
4391                         }
4392                         else {
4393                                 this_recp_cooked[j] = this_recp[j];
4394                         }
4395                 }
4396                 this_recp_cooked[j] = '\0';
4397                 invalid = 0;
4398                 errmsg[0] = 0;
4399                 switch(mailtype) {
4400                 case MES_LOCAL:
4401                         if (!strcasecmp(this_recp, "sysop")) {
4402                                 ++ret->num_room;
4403                                 strcpy(this_recp, config.c_aideroom);
4404                                 if (!IsEmptyStr(ret->recp_room)) {
4405                                         strcat(ret->recp_room, "|");
4406                                 }
4407                                 strcat(ret->recp_room, this_recp);
4408                         }
4409                         else if ( (!strncasecmp(this_recp, "room_", 5))
4410                                   && (!CtdlGetRoom(&tempQR, &this_recp_cooked[5])) ) {
4411
4412                                 /* Save room so we can restore it later */
4413                                 tempQR2 = CCC->room;
4414                                 CCC->room = tempQR;
4415                                         
4416                                 /* Check permissions to send mail to this room */
4417                                 err = CtdlDoIHavePermissionToPostInThisRoom(
4418                                         errmsg, 
4419                                         sizeof errmsg, 
4420                                         RemoteIdentifier,
4421                                         Flags,
4422                                         0                       /* 0 = not a reply */
4423                                         );
4424                                 if (err)
4425                                 {
4426                                         ++ret->num_error;
4427                                         invalid = 1;
4428                                 } 
4429                                 else {
4430                                         ++ret->num_room;
4431                                         if (!IsEmptyStr(ret->recp_room)) {
4432                                                 strcat(ret->recp_room, "|");
4433                                         }
4434                                         strcat(ret->recp_room, &this_recp_cooked[5]);
4435
4436                                         if (!IsEmptyStr(ret->recp_orgroom)) {
4437                                                 strcat(ret->recp_orgroom, "|");
4438                                         }
4439                                         strcat(ret->recp_orgroom, org_recp);
4440
4441                                 }
4442                                         
4443                                 /* Restore room in case something needs it */
4444                                 CCC->room = tempQR2;
4445
4446                         }
4447                         else if (CtdlGetUser(&tempUS, this_recp) == 0) {
4448                                 ++ret->num_local;
4449                                 strcpy(this_recp, tempUS.fullname);
4450                                 if (!IsEmptyStr(ret->recp_local)) {
4451                                         strcat(ret->recp_local, "|");
4452                                 }
4453                                 strcat(ret->recp_local, this_recp);
4454                         }
4455                         else if (CtdlGetUser(&tempUS, this_recp_cooked) == 0) {
4456                                 ++ret->num_local;
4457                                 strcpy(this_recp, tempUS.fullname);
4458                                 if (!IsEmptyStr(ret->recp_local)) {
4459                                         strcat(ret->recp_local, "|");
4460                                 }
4461                                 strcat(ret->recp_local, this_recp);
4462                         }
4463                         else {
4464                                 ++ret->num_error;
4465                                 invalid = 1;
4466                         }
4467                         break;
4468                 case MES_INTERNET:
4469                         /* Yes, you're reading this correctly: if the target
4470                          * domain points back to the local system or an attached
4471                          * Citadel directory, the address is invalid.  That's
4472                          * because if the address were valid, we would have
4473                          * already translated it to a local address by now.
4474                          */
4475                         if (IsDirectory(this_recp, 0)) {
4476                                 ++ret->num_error;
4477                                 invalid = 1;
4478                         }
4479                         else {
4480                                 ++ret->num_internet;
4481                                 if (!IsEmptyStr(ret->recp_internet)) {
4482                                         strcat(ret->recp_internet, "|");
4483                                 }
4484                                 strcat(ret->recp_internet, this_recp);
4485                         }
4486                         break;
4487                 case MES_IGNET:
4488                         ++ret->num_ignet;
4489                         if (!IsEmptyStr(ret->recp_ignet)) {
4490                                 strcat(ret->recp_ignet, "|");
4491                         }
4492                         strcat(ret->recp_ignet, this_recp);
4493                         break;
4494                 case MES_ERROR:
4495                         ++ret->num_error;
4496                         invalid = 1;
4497                         break;
4498                 }
4499                 if (invalid) {
4500                         if (IsEmptyStr(errmsg)) {
4501                                 snprintf(append, sizeof append, "Invalid recipient: %s", this_recp);
4502                         }
4503                         else {
4504                                 snprintf(append, sizeof append, "%s", errmsg);
4505                         }
4506                         if ( (strlen(ret->errormsg) + strlen(append) + 3) < SIZ) {
4507                                 if (!IsEmptyStr(ret->errormsg)) {
4508                                         strcat(ret->errormsg, "; ");
4509                                 }
4510                                 strcat(ret->errormsg, append);
4511                         }
4512                 }
4513                 else {
4514                         if (IsEmptyStr(ret->display_recp)) {
4515                                 strcpy(append, this_recp);
4516                         }
4517                         else {
4518                                 snprintf(append, sizeof append, ", %s", this_recp);
4519                         }
4520                         if ( (strlen(ret->display_recp)+strlen(append)) < SIZ) {
4521                                 strcat(ret->display_recp, append);
4522                         }
4523                 }
4524         }
4525         free(org_recp);
4526
4527         if ((ret->num_local + ret->num_internet + ret->num_ignet +
4528              ret->num_room + ret->num_error) == 0) {
4529                 ret->num_error = (-1);
4530                 strcpy(ret->errormsg, "No recipients specified.");
4531         }
4532
4533         MSGM_syslog(LOG_DEBUG, "validate_recipients()\n");
4534         MSG_syslog(LOG_DEBUG, " local: %d <%s>\n", ret->num_local, ret->recp_local);
4535         MSG_syslog(LOG_DEBUG, "  room: %d <%s>\n", ret->num_room, ret->recp_room);
4536         MSG_syslog(LOG_DEBUG, "  inet: %d <%s>\n", ret->num_internet, ret->recp_internet);
4537         MSG_syslog(LOG_DEBUG, " ignet: %d <%s>\n", ret->num_ignet, ret->recp_ignet);
4538         MSG_syslog(LOG_DEBUG, " error: %d <%s>\n", ret->num_error, ret->errormsg);
4539
4540         free(recipients);
4541         return(ret);
4542 }
4543
4544
4545 /*
4546  * Destructor for struct recptypes
4547  */
4548 void free_recipients(struct recptypes *valid) {
4549
4550         if (valid == NULL) {
4551                 return;
4552         }
4553
4554         if (valid->recptypes_magic != RECPTYPES_MAGIC) {
4555                 struct CitContext *CCC = CC;
4556                 MSGM_syslog(LOG_EMERG, "Attempt to call free_recipients() on some other data type!\n");
4557                 abort();
4558         }
4559
4560         if (valid->errormsg != NULL)            free(valid->errormsg);
4561         if (valid->recp_local != NULL)          free(valid->recp_local);
4562         if (valid->recp_internet != NULL)       free(valid->recp_internet);
4563         if (valid->recp_ignet != NULL)          free(valid->recp_ignet);
4564         if (valid->recp_room != NULL)           free(valid->recp_room);
4565         if (valid->recp_orgroom != NULL)        free(valid->recp_orgroom);
4566         if (valid->display_recp != NULL)        free(valid->display_recp);
4567         if (valid->bounce_to != NULL)           free(valid->bounce_to);
4568         if (valid->envelope_from != NULL)       free(valid->envelope_from);
4569         if (valid->sending_room != NULL)        free(valid->sending_room);
4570         free(valid);
4571 }
4572
4573
4574
4575 /*
4576  * message entry  -  mode 0 (normal)
4577  */
4578 void cmd_ent0(char *entargs)
4579 {
4580         struct CitContext *CCC = CC;
4581         int post = 0;
4582         char recp[SIZ];
4583         char cc[SIZ];
4584         char bcc[SIZ];
4585         char supplied_euid[128];
4586         int anon_flag = 0;
4587         int format_type = 0;
4588         char newusername[256];
4589         char newuseremail[256];
4590         struct CtdlMessage *msg;
4591         int anonymous = 0;
4592         char errmsg[SIZ];
4593         int err = 0;
4594         struct recptypes *valid = NULL;
4595         struct recptypes *valid_to = NULL;
4596         struct recptypes *valid_cc = NULL;
4597         struct recptypes *valid_bcc = NULL;
4598         char subject[SIZ];
4599         int subject_required = 0;
4600         int do_confirm = 0;
4601         long msgnum;
4602         int i, j;
4603         char buf[256];
4604         int newuseremail_ok = 0;
4605         char references[SIZ];
4606         char *ptr;
4607
4608         unbuffer_output();
4609
4610         post = extract_int(entargs, 0);
4611         extract_token(recp, entargs, 1, '|', sizeof recp);
4612         anon_flag = extract_int(entargs, 2);
4613         format_type = extract_int(entargs, 3);
4614         extract_token(subject, entargs, 4, '|', sizeof subject);
4615         extract_token(newusername, entargs, 5, '|', sizeof newusername);
4616         do_confirm = extract_int(entargs, 6);
4617         extract_token(cc, entargs, 7, '|', sizeof cc);
4618         extract_token(bcc, entargs, 8, '|', sizeof bcc);
4619         switch(CC->room.QRdefaultview) {
4620         case VIEW_NOTES:
4621         case VIEW_WIKI:
4622                 extract_token(supplied_euid, entargs, 9, '|', sizeof supplied_euid);
4623                 break;
4624         default:
4625                 supplied_euid[0] = 0;
4626                 break;
4627         }
4628         extract_token(newuseremail, entargs, 10, '|', sizeof newuseremail);
4629         extract_token(references, entargs, 11, '|', sizeof references);
4630         for (ptr=references; *ptr != 0; ++ptr) {
4631                 if (*ptr == '!') *ptr = '|';
4632         }
4633
4634         /* first check to make sure the request is valid. */
4635
4636         err = CtdlDoIHavePermissionToPostInThisRoom(
4637                 errmsg,
4638                 sizeof errmsg,
4639                 NULL,
4640                 POST_LOGGED_IN,
4641                 (!IsEmptyStr(references))               /* is this a reply?  or a top-level post? */
4642                 );
4643         if (err)
4644         {
4645                 cprintf("%d %s\n", err, errmsg);
4646                 return;
4647         }
4648
4649         /* Check some other permission type things. */
4650
4651         if (IsEmptyStr(newusername)) {
4652                 strcpy(newusername, CCC->user.fullname);
4653         }
4654         if (  (CCC->user.axlevel < AxAideU)
4655               && (strcasecmp(newusername, CCC->user.fullname))
4656               && (strcasecmp(newusername, CCC->cs_inet_fn))
4657                 ) {     
4658                 cprintf("%d You don't have permission to author messages as '%s'.\n",
4659                         ERROR + HIGHER_ACCESS_REQUIRED,
4660                         newusername
4661                         );
4662                 return;
4663         }
4664
4665
4666         if (IsEmptyStr(newuseremail)) {
4667                 newuseremail_ok = 1;
4668         }
4669
4670         if (!IsEmptyStr(newuseremail)) {
4671                 if (!strcasecmp(newuseremail, CCC->cs_inet_email)) {
4672                         newuseremail_ok = 1;
4673                 }
4674                 else if (!IsEmptyStr(CCC->cs_inet_other_emails)) {
4675                         j = num_tokens(CCC->cs_inet_other_emails, '|');
4676                         for (i=0; i<j; ++i) {
4677                                 extract_token(buf, CCC->cs_inet_other_emails, i, '|', sizeof buf);
4678                                 if (!strcasecmp(newuseremail, buf)) {
4679                                         newuseremail_ok = 1;
4680                                 }
4681                         }
4682                 }
4683         }
4684
4685         if (!newuseremail_ok) {
4686                 cprintf("%d You don't have permission to author messages as '%s'.\n",
4687                         ERROR + HIGHER_ACCESS_REQUIRED,
4688                         newuseremail
4689                         );
4690                 return;
4691         }
4692
4693         CCC->cs_flags |= CS_POSTING;
4694
4695         /* In mailbox rooms we have to behave a little differently --
4696          * make sure the user has specified at least one recipient.  Then
4697          * validate the recipient(s).  We do this for the Mail> room, as
4698          * well as any room which has the "Mailbox" view set - unless it
4699          * is the DRAFTS room which does not require recipients
4700          */
4701
4702         if ( (  ( (CCC->room.QRflags & QR_MAILBOX) && (!strcasecmp(&CCC->room.QRname[11], MAILROOM)) )
4703                 || ( (CCC->room.QRflags & QR_MAILBOX) && (CCC->curr_view == VIEW_MAILBOX) )
4704                      ) && (strcasecmp(&CCC->room.QRname[11], USERDRAFTROOM)) !=0 ) {
4705                 if (CCC->user.axlevel < AxProbU) {
4706                         strcpy(recp, "sysop");
4707                         strcpy(cc, "");
4708                         strcpy(bcc, "");
4709                 }
4710
4711                 valid_to = validate_recipients(recp, NULL, 0);
4712                 if (valid_to->num_error > 0) {
4713                         cprintf("%d %s\n", ERROR + NO_SUCH_USER, valid_to->errormsg);
4714                         free_recipients(valid_to);
4715                         return;
4716                 }
4717
4718                 valid_cc = validate_recipients(cc, NULL, 0);
4719                 if (valid_cc->num_error > 0) {
4720                         cprintf("%d %s\n", ERROR + NO_SUCH_USER, valid_cc->errormsg);
4721                         free_recipients(valid_to);
4722                         free_recipients(valid_cc);
4723                         return;
4724                 }
4725
4726                 valid_bcc = validate_recipients(bcc, NULL, 0);
4727                 if (valid_bcc->num_error > 0) {
4728                         cprintf("%d %s\n", ERROR + NO_SUCH_USER, valid_bcc->errormsg);
4729                         free_recipients(valid_to);
4730                         free_recipients(valid_cc);
4731                         free_recipients(valid_bcc);
4732                         return;
4733                 }
4734
4735                 /* Recipient required, but none were specified */
4736                 if ( (valid_to->num_error < 0) && (valid_cc->num_error < 0) && (valid_bcc->num_error < 0) ) {
4737                         free_recipients(valid_to);
4738                         free_recipients(valid_cc);
4739                         free_recipients(valid_bcc);
4740                         cprintf("%d At least one recipient is required.\n", ERROR + NO_SUCH_USER);
4741                         return;
4742                 }
4743
4744                 if (valid_to->num_internet + valid_cc->num_internet + valid_bcc->num_internet > 0) {
4745                         if (CtdlCheckInternetMailPermission(&CCC->user)==0) {
4746                                 cprintf("%d You do not have permission "
4747                                         "to send Internet mail.\n",
4748                                         ERROR + HIGHER_ACCESS_REQUIRED);
4749                                 free_recipients(valid_to);
4750                                 free_recipients(valid_cc);
4751                                 free_recipients(valid_bcc);
4752                                 return;
4753                         }
4754                 }
4755
4756                 if ( ( (valid_to->num_internet + valid_to->num_ignet + valid_cc->num_internet + valid_cc->num_ignet + valid_bcc->num_internet + valid_bcc->num_ignet) > 0)
4757                      && (CCC->user.axlevel < AxNetU) ) {
4758                         cprintf("%d Higher access required for network mail.\n",
4759                                 ERROR + HIGHER_ACCESS_REQUIRED);
4760                         free_recipients(valid_to);
4761                         free_recipients(valid_cc);
4762                         free_recipients(valid_bcc);
4763                         return;
4764                 }
4765         
4766                 if ((RESTRICT_INTERNET == 1)
4767                     && (valid_to->num_internet + valid_cc->num_internet + valid_bcc->num_internet > 0)
4768                     && ((CCC->user.flags & US_INTERNET) == 0)
4769                     && (!CCC->internal_pgm)) {
4770                         cprintf("%d You don't have access to Internet mail.\n",
4771                                 ERROR + HIGHER_ACCESS_REQUIRED);
4772                         free_recipients(valid_to);
4773                         free_recipients(valid_cc);
4774                         free_recipients(valid_bcc);
4775                         return;
4776                 }
4777
4778         }
4779
4780         /* Is this a room which has anonymous-only or anonymous-option? */
4781         anonymous = MES_NORMAL;
4782         if (CCC->room.QRflags & QR_ANONONLY) {
4783                 anonymous = MES_ANONONLY;
4784         }
4785         if (CCC->room.QRflags & QR_ANONOPT) {
4786                 if (anon_flag == 1) {   /* only if the user requested it */
4787                         anonymous = MES_ANONOPT;
4788                 }
4789         }
4790
4791         if ((CCC->room.QRflags & QR_MAILBOX) == 0) {
4792                 recp[0] = 0;
4793         }
4794
4795         /* Recommend to the client that the use of a message subject is
4796          * strongly recommended in this room, if either the SUBJECTREQ flag
4797          * is set, or if there is one or more Internet email recipients.
4798          */
4799         if (CCC->room.QRflags2 & QR2_SUBJECTREQ) subject_required = 1;
4800         if ((valid_to)  && (valid_to->num_internet > 0))        subject_required = 1;
4801         if ((valid_cc)  && (valid_cc->num_internet > 0))        subject_required = 1;
4802         if ((valid_bcc) && (valid_bcc->num_internet > 0))       subject_required = 1;
4803
4804         /* If we're only checking the validity of the request, return
4805          * success without creating the message.
4806          */
4807         if (post == 0) {
4808                 cprintf("%d %s|%d\n", CIT_OK,
4809                         ((valid_to != NULL) ? valid_to->display_recp : ""), 
4810                         subject_required);
4811                 free_recipients(valid_to);
4812                 free_recipients(valid_cc);
4813                 free_recipients(valid_bcc);
4814                 return;
4815         }
4816
4817         /* We don't need these anymore because we'll do it differently below */
4818         free_recipients(valid_to);
4819         free_recipients(valid_cc);
4820         free_recipients(valid_bcc);
4821
4822         /* Read in the message from the client. */
4823         if (do_confirm) {
4824                 cprintf("%d send message\n", START_CHAT_MODE);
4825         } else {
4826                 cprintf("%d send message\n", SEND_LISTING);
4827         }
4828
4829         msg = CtdlMakeMessage(&CCC->user, recp, cc,
4830                               CCC->room.QRname, anonymous, format_type,
4831                               newusername, newuseremail, subject,
4832                               ((!IsEmptyStr(supplied_euid)) ? supplied_euid : NULL),
4833                               NULL, references);
4834
4835         /* Put together one big recipients struct containing to/cc/bcc all in
4836          * one.  This is for the envelope.
4837          */
4838         char *all_recps = malloc(SIZ * 3);
4839         strcpy(all_recps, recp);
4840         if (!IsEmptyStr(cc)) {
4841                 if (!IsEmptyStr(all_recps)) {
4842                         strcat(all_recps, ",");
4843                 }
4844                 strcat(all_recps, cc);
4845         }
4846         if (!IsEmptyStr(bcc)) {
4847                 if (!IsEmptyStr(all_recps)) {
4848                         strcat(all_recps, ",");
4849                 }
4850                 strcat(all_recps, bcc);
4851         }
4852         if (!IsEmptyStr(all_recps)) {
4853                 valid = validate_recipients(all_recps, NULL, 0);
4854         }
4855         else {
4856                 valid = NULL;
4857         }
4858         free(all_recps);
4859
4860         if ((valid != NULL) && (valid->num_room == 1))
4861         {
4862                 /* posting into an ML room? set the envelope from 
4863                  * to the actual mail address so others get a valid
4864                  * reply-to-header.
4865                  */
4866                 msg->cm_fields[eenVelopeTo] = strdup(valid->recp_orgroom);
4867         }
4868
4869         if (msg != NULL) {
4870                 msgnum = CtdlSubmitMsg(msg, valid, "", QP_EADDR);
4871                 if (do_confirm) {
4872                         cprintf("%ld\n", msgnum);
4873
4874                         if (StrLength(CCC->StatusMessage) > 0) {
4875                                 cprintf("%s\n", ChrPtr(CCC->StatusMessage));
4876                         }
4877                         else if (msgnum >= 0L) {
4878                                 client_write(HKEY("Message accepted.\n"));
4879                         }
4880                         else {
4881                                 client_write(HKEY("Internal error.\n"));
4882                         }
4883
4884                         if (!CM_IsEmpty(msg, eExclusiveID)) {
4885                                 cprintf("%s\n", msg->cm_fields[eExclusiveID]);
4886                         } else {
4887                                 cprintf("\n");
4888                         }
4889                         cprintf("000\n");
4890                 }
4891
4892                 CM_Free(msg);
4893         }
4894         if (valid != NULL) {
4895                 free_recipients(valid);
4896         }
4897         return;
4898 }
4899
4900
4901
4902 /*
4903  * API function to delete messages which match a set of criteria
4904  * (returns the actual number of messages deleted)
4905  */
4906 int CtdlDeleteMessages(char *room_name,         /* which room */
4907                        long *dmsgnums,          /* array of msg numbers to be deleted */
4908                        int num_dmsgnums,        /* number of msgs to be deleted, or 0 for "any" */
4909                        char *content_type       /* or "" for any.  regular expressions expected. */
4910         )
4911 {
4912         struct CitContext *CCC = CC;
4913         struct ctdlroom qrbuf;
4914         struct cdbdata *cdbfr;
4915         long *msglist = NULL;
4916         long *dellist = NULL;
4917         int num_msgs = 0;
4918         int i, j;
4919         int num_deleted = 0;
4920         int delete_this;
4921         struct MetaData smi;
4922         regex_t re;
4923         regmatch_t pm;
4924         int need_to_free_re = 0;
4925
4926         if (content_type) if (!IsEmptyStr(content_type)) {
4927                         regcomp(&re, content_type, 0);
4928                         need_to_free_re = 1;
4929                 }
4930         MSG_syslog(LOG_DEBUG, " CtdlDeleteMessages(%s, %d msgs, %s)\n",
4931                    room_name, num_dmsgnums, content_type);
4932
4933         /* get room record, obtaining a lock... */
4934         if (CtdlGetRoomLock(&qrbuf, room_name) != 0) {
4935                 MSG_syslog(LOG_ERR, " CtdlDeleteMessages(): Room <%s> not found\n",
4936                            room_name);
4937                 if (need_to_free_re) regfree(&re);
4938                 return (0);     /* room not found */
4939         }
4940         cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf.QRnumber, sizeof(long));
4941
4942         if (cdbfr != NULL) {
4943                 dellist = malloc(cdbfr->len);
4944                 msglist = (long *) cdbfr->ptr;
4945                 cdbfr->ptr = NULL;      /* CtdlDeleteMessages() now owns this memory */
4946                 num_msgs = cdbfr->len / sizeof(long);
4947                 cdb_free(cdbfr);
4948         }
4949         if (num_msgs > 0) {
4950                 int have_contenttype = (content_type != NULL) && !IsEmptyStr(content_type);
4951                 int have_delmsgs = (num_dmsgnums == 0) || (dmsgnums == NULL);
4952                 int have_more_del = 1;
4953
4954                 num_msgs = sort_msglist(msglist, num_msgs);
4955                 if (num_dmsgnums > 1)
4956                         num_dmsgnums = sort_msglist(dmsgnums, num_dmsgnums);
4957 /*
4958                 {
4959                         StrBuf *dbg = NewStrBuf();
4960                         for (i = 0; i < num_dmsgnums; i++)
4961                                 StrBufAppendPrintf(dbg, ", %ld", dmsgnums[i]);
4962                         MSG_syslog(LOG_DEBUG, " Deleting before: %s", ChrPtr(dbg));
4963                         FreeStrBuf(&dbg);
4964                 }
4965 */
4966                 i = 0; j = 0;
4967                 while ((i < num_msgs) && (have_more_del)) {
4968                         delete_this = 0x00;
4969
4970                         /* Set/clear a bit for each criterion */
4971
4972                         /* 0 messages in the list or a null list means that we are
4973                          * interested in deleting any messages which meet the other criteria.
4974                          */
4975                         if (have_delmsgs) {
4976                                 delete_this |= 0x01;
4977                         }
4978                         else {
4979                                 while ((i < num_msgs) && (msglist[i] < dmsgnums[j])) i++;
4980
4981                                 if (i >= num_msgs)
4982                                         continue;
4983
4984                                 if (msglist[i] == dmsgnums[j]) {
4985                                         delete_this |= 0x01;
4986                                 }
4987                                 j++;
4988                                 have_more_del = (j < num_dmsgnums);
4989                         }
4990
4991                         if (have_contenttype) {
4992                                 GetMetaData(&smi, msglist[i]);
4993                                 if (regexec(&re, smi.meta_content_type, 1, &pm, 0) == 0) {
4994                                         delete_this |= 0x02;
4995                                 }
4996                         } else {
4997                                 delete_this |= 0x02;
4998                         }
4999
5000                         /* Delete message only if all bits are set */
5001                         if (delete_this == 0x03) {
5002                                 dellist[num_deleted++] = msglist[i];
5003                                 msglist[i] = 0L;
5004                         }
5005                         i++;
5006                 }
5007 /*
5008                 {
5009                         StrBuf *dbg = NewStrBuf();
5010                         for (i = 0; i < num_deleted; i++)
5011                                 StrBufAppendPrintf(dbg, ", %ld", dellist[i]);
5012                         MSG_syslog(LOG_DEBUG, " Deleting: %s", ChrPtr(dbg));
5013                         FreeStrBuf(&dbg);
5014                 }
5015 */
5016                 num_msgs = sort_msglist(msglist, num_msgs);
5017                 cdb_store(CDB_MSGLISTS, &qrbuf.QRnumber, (int)sizeof(long),
5018                           msglist, (int)(num_msgs * sizeof(long)));
5019
5020                 if (num_msgs > 0)
5021                         qrbuf.QRhighest = msglist[num_msgs - 1];
5022                 else
5023                         qrbuf.QRhighest = 0;
5024         }
5025         CtdlPutRoomLock(&qrbuf);
5026
5027         /* Go through the messages we pulled out of the index, and decrement
5028          * their reference counts by 1.  If this is the only room the message
5029          * was in, the reference count will reach zero and the message will
5030          * automatically be deleted from the database.  We do this in a
5031          * separate pass because there might be plug-in hooks getting called,
5032          * and we don't want that happening during an S_ROOMS critical
5033          * section.
5034          */
5035         if (num_deleted) {
5036                 for (i=0; i<num_deleted; ++i) {
5037                         PerformDeleteHooks(qrbuf.QRname, dellist[i]);
5038                 }
5039                 AdjRefCountList(dellist, num_deleted, -1);
5040         }
5041         /* Now free the memory we used, and go away. */
5042         if (msglist != NULL) free(msglist);
5043         if (dellist != NULL) free(dellist);
5044         MSG_syslog(LOG_DEBUG, " %d message(s) deleted.\n", num_deleted);
5045         if (need_to_free_re) regfree(&re);
5046         return (num_deleted);
5047 }
5048
5049
5050
5051 /*
5052  * Check whether the current user has permission to delete messages from
5053  * the current room (returns 1 for yes, 0 for no)
5054  */
5055 int CtdlDoIHavePermissionToDeleteMessagesFromThisRoom(void) {
5056         int ra;
5057         CtdlRoomAccess(&CC->room, &CC->user, &ra, NULL);
5058         if (ra & UA_DELETEALLOWED) return(1);
5059         return(0);
5060 }
5061
5062
5063
5064
5065 /*
5066  * Delete message from current room
5067  */
5068 void cmd_dele(char *args)
5069 {
5070         int num_deleted;
5071         int i;
5072         char msgset[SIZ];
5073         char msgtok[32];
5074         long *msgs;
5075         int num_msgs = 0;
5076
5077         extract_token(msgset, args, 0, '|', sizeof msgset);
5078         num_msgs = num_tokens(msgset, ',');
5079         if (num_msgs < 1) {
5080                 cprintf("%d Nothing to do.\n", CIT_OK);
5081                 return;
5082         }
5083
5084         if (CtdlDoIHavePermissionToDeleteMessagesFromThisRoom() == 0) {
5085                 cprintf("%d Higher access required.\n",
5086                         ERROR + HIGHER_ACCESS_REQUIRED);
5087                 return;
5088         }
5089
5090         /*
5091          * Build our message set to be moved/copied
5092          */
5093         msgs = malloc(num_msgs * sizeof(long));
5094         for (i=0; i<num_msgs; ++i) {
5095                 extract_token(msgtok, msgset, i, ',', sizeof msgtok);
5096                 msgs[i] = atol(msgtok);
5097         }
5098
5099         num_deleted = CtdlDeleteMessages(CC->room.QRname, msgs, num_msgs, "");
5100         free(msgs);
5101
5102         if (num_deleted) {
5103                 cprintf("%d %d message%s deleted.\n", CIT_OK,
5104                         num_deleted, ((num_deleted != 1) ? "s" : ""));
5105         } else {
5106                 cprintf("%d Message not found.\n", ERROR + MESSAGE_NOT_FOUND);
5107         }
5108 }
5109
5110
5111
5112
5113 /*
5114  * move or copy a message to another room
5115  */
5116 void cmd_move(char *args)
5117 {
5118         char msgset[SIZ];
5119         char msgtok[32];
5120         long *msgs;
5121         int num_msgs = 0;
5122
5123         char targ[ROOMNAMELEN];
5124         struct ctdlroom qtemp;
5125         int err;
5126         int is_copy = 0;
5127         int ra;
5128         int permit = 0;
5129         int i;
5130
5131         extract_token(msgset, args, 0, '|', sizeof msgset);
5132         num_msgs = num_tokens(msgset, ',');
5133         if (num_msgs < 1) {
5134                 cprintf("%d Nothing to do.\n", CIT_OK);
5135                 return;
5136         }
5137
5138         extract_token(targ, args, 1, '|', sizeof targ);
5139         convert_room_name_macros(targ, sizeof targ);
5140         targ[ROOMNAMELEN - 1] = 0;
5141         is_copy = extract_int(args, 2);
5142
5143         if (CtdlGetRoom(&qtemp, targ) != 0) {
5144                 cprintf("%d '%s' does not exist.\n", ERROR + ROOM_NOT_FOUND, targ);
5145                 return;
5146         }
5147
5148         if (!strcasecmp(qtemp.QRname, CC->room.QRname)) {
5149                 cprintf("%d Source and target rooms are the same.\n", ERROR + ALREADY_EXISTS);
5150                 return;
5151         }
5152
5153         CtdlGetUser(&CC->user, CC->curr_user);
5154         CtdlRoomAccess(&qtemp, &CC->user, &ra, NULL);
5155
5156         /* Check for permission to perform this operation.
5157          * Remember: "CC->room" is source, "qtemp" is target.
5158          */
5159         permit = 0;
5160
5161         /* Admins can move/copy */
5162         if (CC->user.axlevel >= AxAideU) permit = 1;
5163
5164         /* Room aides can move/copy */
5165         if (CC->user.usernum == CC->room.QRroomaide) permit = 1;
5166
5167         /* Permit move/copy from personal rooms */
5168         if ((CC->room.QRflags & QR_MAILBOX)
5169             && (qtemp.QRflags & QR_MAILBOX)) permit = 1;
5170
5171         /* Permit only copy from public to personal room */
5172         if ( (is_copy)
5173              && (!(CC->room.QRflags & QR_MAILBOX))
5174              && (qtemp.QRflags & QR_MAILBOX)) permit = 1;
5175
5176         /* Permit message removal from collaborative delete rooms */
5177         if (CC->room.QRflags2 & QR2_COLLABDEL) permit = 1;
5178
5179         /* Users allowed to post into the target room may move into it too. */
5180         if ((CC->room.QRflags & QR_MAILBOX) && 
5181             (qtemp.QRflags & UA_POSTALLOWED))  permit = 1;
5182
5183         /* User must have access to target room */
5184         if (!(ra & UA_KNOWN))  permit = 0;
5185
5186         if (!permit) {
5187                 cprintf("%d Higher access required.\n",
5188                         ERROR + HIGHER_ACCESS_REQUIRED);
5189                 return;
5190         }
5191
5192         /*
5193          * Build our message set to be moved/copied
5194          */
5195         msgs = malloc(num_msgs * sizeof(long));
5196         for (i=0; i<num_msgs; ++i) {
5197                 extract_token(msgtok, msgset, i, ',', sizeof msgtok);
5198                 msgs[i] = atol(msgtok);
5199         }
5200
5201         /*
5202          * Do the copy
5203          */
5204         err = CtdlSaveMsgPointersInRoom(targ, msgs, num_msgs, 1, NULL, 0);
5205         if (err != 0) {
5206                 cprintf("%d Cannot store message(s) in %s: error %d\n",
5207                         err, targ, err);
5208                 free(msgs);
5209                 return;
5210         }
5211
5212         /* Now delete the message from the source room,
5213          * if this is a 'move' rather than a 'copy' operation.
5214          */
5215         if (is_copy == 0) {
5216                 CtdlDeleteMessages(CC->room.QRname, msgs, num_msgs, "");
5217         }
5218         free(msgs);
5219
5220         cprintf("%d Message(s) %s.\n", CIT_OK, (is_copy ? "copied" : "moved") );
5221 }
5222
5223
5224
5225 /*
5226  * GetMetaData()  -  Get the supplementary record for a message
5227  */
5228 void GetMetaData(struct MetaData *smibuf, long msgnum)
5229 {
5230
5231         struct cdbdata *cdbsmi;
5232         long TheIndex;
5233
5234         memset(smibuf, 0, sizeof(struct MetaData));
5235         smibuf->meta_msgnum = msgnum;
5236         smibuf->meta_refcount = 1;      /* Default reference count is 1 */
5237
5238         /* Use the negative of the message number for its supp record index */
5239         TheIndex = (0L - msgnum);
5240
5241         cdbsmi = cdb_fetch(CDB_MSGMAIN, &TheIndex, sizeof(long));
5242         if (cdbsmi == NULL) {
5243                 return;         /* record not found; go with defaults */
5244         }
5245         memcpy(smibuf, cdbsmi->ptr,
5246                ((cdbsmi->len > sizeof(struct MetaData)) ?
5247                 sizeof(struct MetaData) : cdbsmi->len));
5248         cdb_free(cdbsmi);
5249         return;
5250 }
5251
5252
5253 /*
5254  * PutMetaData()  -  (re)write supplementary record for a message
5255  */
5256 void PutMetaData(struct MetaData *smibuf)
5257 {
5258         long TheIndex;
5259
5260         /* Use the negative of the message number for the metadata db index */
5261         TheIndex = (0L - smibuf->meta_msgnum);
5262
5263         cdb_store(CDB_MSGMAIN,
5264                   &TheIndex, (int)sizeof(long),
5265                   smibuf, (int)sizeof(struct MetaData));
5266
5267 }
5268
5269 /*
5270  * AdjRefCount  -  submit an adjustment to the reference count for a message.
5271  *                 (These are just queued -- we actually process them later.)
5272  */
5273 void AdjRefCount(long msgnum, int incr)
5274 {
5275         struct CitContext *CCC = CC;
5276         struct arcq new_arcq;
5277         int rv = 0;
5278
5279         MSG_syslog(LOG_DEBUG, "AdjRefCount() msg %ld ref count delta %+d\n", msgnum, incr);
5280
5281         begin_critical_section(S_SUPPMSGMAIN);
5282         if (arcfp == NULL) {
5283                 arcfp = fopen(file_arcq, "ab+");
5284                 chown(file_arcq, CTDLUID, (-1));
5285                 chmod(file_arcq, 0600);
5286         }
5287         end_critical_section(S_SUPPMSGMAIN);
5288
5289         /* msgnum < 0 means that we're trying to close the file */
5290         if (msgnum < 0) {
5291                 MSGM_syslog(LOG_DEBUG, "Closing the AdjRefCount queue file\n");
5292                 begin_critical_section(S_SUPPMSGMAIN);
5293                 if (arcfp != NULL) {
5294                         fclose(arcfp);
5295                         arcfp = NULL;
5296                 }
5297                 end_critical_section(S_SUPPMSGMAIN);
5298                 return;
5299         }
5300
5301         /*
5302          * If we can't open the queue, perform the operation synchronously.
5303          */
5304         if (arcfp == NULL) {
5305                 TDAP_AdjRefCount(msgnum, incr);
5306                 return;
5307         }
5308
5309         new_arcq.arcq_msgnum = msgnum;
5310         new_arcq.arcq_delta = incr;
5311         rv = fwrite(&new_arcq, sizeof(struct arcq), 1, arcfp);
5312         if (rv == -1) {
5313                 MSG_syslog(LOG_EMERG, "Couldn't write Refcount Queue File %s: %s\n",
5314                            file_arcq,
5315                            strerror(errno));
5316         }
5317         fflush(arcfp);
5318
5319         return;
5320 }
5321
5322 void AdjRefCountList(long *msgnum, long nmsg, int incr)
5323 {
5324         struct CitContext *CCC = CC;
5325         long i, the_size, offset;
5326         struct arcq *new_arcq;
5327         int rv = 0;
5328
5329         MSG_syslog(LOG_DEBUG, "AdjRefCountList() msg %ld ref count delta %+d\n", nmsg, incr);
5330
5331         begin_critical_section(S_SUPPMSGMAIN);
5332         if (arcfp == NULL) {
5333                 arcfp = fopen(file_arcq, "ab+");
5334                 chown(file_arcq, CTDLUID, (-1));
5335                 chmod(file_arcq, 0600);
5336         }
5337         end_critical_section(S_SUPPMSGMAIN);
5338
5339         /*
5340          * If we can't open the queue, perform the operation synchronously.
5341          */
5342         if (arcfp == NULL) {
5343                 for (i = 0; i < nmsg; i++)
5344                         TDAP_AdjRefCount(msgnum[i], incr);
5345                 return;
5346         }
5347
5348         the_size = sizeof(struct arcq) * nmsg;
5349         new_arcq = malloc(the_size);
5350         for (i = 0; i < nmsg; i++) {
5351                 new_arcq[i].arcq_msgnum = msgnum[i];
5352                 new_arcq[i].arcq_delta = incr;
5353         }
5354         rv = 0;
5355         offset = 0;
5356         while ((rv >= 0) && (offset < the_size))
5357         {
5358                 rv = fwrite(new_arcq + offset, 1, the_size - offset, arcfp);
5359                 if (rv == -1) {
5360                         MSG_syslog(LOG_EMERG, "Couldn't write Refcount Queue File %s: %s\n",
5361                                    file_arcq,
5362                                    strerror(errno));
5363                 }
5364                 else {
5365                         offset += rv;
5366                 }
5367         }
5368         free(new_arcq);
5369         fflush(arcfp);
5370
5371         return;
5372 }
5373
5374
5375 /*
5376  * TDAP_ProcessAdjRefCountQueue()
5377  *
5378  * Process the queue of message count adjustments that was created by calls
5379  * to AdjRefCount() ... by reading the queue and calling TDAP_AdjRefCount()
5380  * for each one.  This should be an "off hours" operation.
5381  */
5382 int TDAP_ProcessAdjRefCountQueue(void)
5383 {
5384         struct CitContext *CCC = CC;
5385         char file_arcq_temp[PATH_MAX];
5386         int r;
5387         FILE *fp;
5388         struct arcq arcq_rec;
5389         int num_records_processed = 0;
5390
5391         snprintf(file_arcq_temp, sizeof file_arcq_temp, "%s.%04x", file_arcq, rand());
5392
5393         begin_critical_section(S_SUPPMSGMAIN);
5394         if (arcfp != NULL) {
5395                 fclose(arcfp);
5396                 arcfp = NULL;
5397         }
5398
5399         r = link(file_arcq, file_arcq_temp);
5400         if (r != 0) {
5401                 MSG_syslog(LOG_CRIT, "%s: %s\n", file_arcq_temp, strerror(errno));
5402                 end_critical_section(S_SUPPMSGMAIN);
5403                 return(num_records_processed);
5404         }
5405
5406         unlink(file_arcq);
5407         end_critical_section(S_SUPPMSGMAIN);
5408
5409         fp = fopen(file_arcq_temp, "rb");
5410         if (fp == NULL) {
5411                 MSG_syslog(LOG_CRIT, "%s: %s\n", file_arcq_temp, strerror(errno));
5412                 return(num_records_processed);
5413         }
5414
5415         while (fread(&arcq_rec, sizeof(struct arcq), 1, fp) == 1) {
5416                 TDAP_AdjRefCount(arcq_rec.arcq_msgnum, arcq_rec.arcq_delta);
5417                 ++num_records_processed;
5418         }
5419
5420         fclose(fp);
5421         r = unlink(file_arcq_temp);
5422         if (r != 0) {
5423                 MSG_syslog(LOG_CRIT, "%s: %s\n", file_arcq_temp, strerror(errno));
5424         }
5425
5426         return(num_records_processed);
5427 }
5428
5429
5430
5431 /*
5432  * TDAP_AdjRefCount  -  adjust the reference count for a message.
5433  *                      This one does it "for real" because it's called by
5434  *                      the autopurger function that processes the queue
5435  *                      created by AdjRefCount().   If a message's reference
5436  *                      count becomes zero, we also delete the message from
5437  *                      disk and de-index it.
5438  */
5439 void TDAP_AdjRefCount(long msgnum, int incr)
5440 {
5441         struct CitContext *CCC = CC;
5442
5443         struct MetaData smi;
5444         long delnum;
5445
5446         /* This is a *tight* critical section; please keep it that way, as
5447          * it may get called while nested in other critical sections.  
5448          * Complicating this any further will surely cause deadlock!
5449          */
5450         begin_critical_section(S_SUPPMSGMAIN);
5451         GetMetaData(&smi, msgnum);
5452         smi.meta_refcount += incr;
5453         PutMetaData(&smi);
5454         end_critical_section(S_SUPPMSGMAIN);
5455         MSG_syslog(LOG_DEBUG, "TDAP_AdjRefCount() msg %ld ref count delta %+d, is now %d\n",
5456                    msgnum, incr, smi.meta_refcount
5457                 );
5458
5459         /* If the reference count is now zero, delete the message
5460          * (and its supplementary record as well).
5461          */
5462         if (smi.meta_refcount == 0) {
5463                 MSG_syslog(LOG_DEBUG, "Deleting message <%ld>\n", msgnum);
5464                 
5465                 /* Call delete hooks with NULL room to show it has gone altogether */
5466                 PerformDeleteHooks(NULL, msgnum);
5467
5468                 /* Remove from message base */
5469                 delnum = msgnum;
5470                 cdb_delete(CDB_MSGMAIN, &delnum, (int)sizeof(long));
5471                 cdb_delete(CDB_BIGMSGS, &delnum, (int)sizeof(long));
5472
5473                 /* Remove metadata record */
5474                 delnum = (0L - msgnum);
5475                 cdb_delete(CDB_MSGMAIN, &delnum, (int)sizeof(long));
5476         }
5477
5478 }
5479
5480 /*
5481  * Write a generic object to this room
5482  *
5483  * Note: this could be much more efficient.  Right now we use two temporary
5484  * files, and still pull the message into memory as with all others.
5485  */
5486 void CtdlWriteObject(char *req_room,                    /* Room to stuff it in */
5487                      char *content_type,                /* MIME type of this object */
5488                      char *raw_message,         /* Data to be written */
5489                      off_t raw_length,          /* Size of raw_message */
5490                      struct ctdluser *is_mailbox,       /* Mailbox room? */
5491                      int is_binary,                     /* Is encoding necessary? */
5492                      int is_unique,                     /* Del others of this type? */
5493                      unsigned int flags         /* Internal save flags */
5494         )
5495 {
5496         struct CitContext *CCC = CC;
5497         struct ctdlroom qrbuf;
5498         char roomname[ROOMNAMELEN];
5499         struct CtdlMessage *msg;
5500         char *encoded_message = NULL;
5501
5502         if (is_mailbox != NULL) {
5503                 CtdlMailboxName(roomname, sizeof roomname, is_mailbox, req_room);
5504         }
5505         else {
5506                 safestrncpy(roomname, req_room, sizeof(roomname));
5507         }
5508
5509         MSG_syslog(LOG_DEBUG, "Raw length is %ld\n", (long)raw_length);
5510
5511         if (is_binary) {
5512                 encoded_message = malloc((size_t) (((raw_length * 134) / 100) + 4096 ) );
5513         }
5514         else {
5515                 encoded_message = malloc((size_t)(raw_length + 4096));
5516         }
5517
5518         sprintf(encoded_message, "Content-type: %s\n", content_type);
5519
5520         if (is_binary) {
5521                 sprintf(&encoded_message[strlen(encoded_message)],
5522                         "Content-transfer-encoding: base64\n\n"
5523                         );
5524         }
5525         else {
5526                 sprintf(&encoded_message[strlen(encoded_message)],
5527                         "Content-transfer-encoding: 7bit\n\n"
5528                         );
5529         }
5530
5531         if (is_binary) {
5532                 CtdlEncodeBase64(
5533                         &encoded_message[strlen(encoded_message)],
5534                         raw_message,
5535                         (int)raw_length,
5536                         0
5537                         );
5538         }
5539         else {
5540                 memcpy(
5541                         &encoded_message[strlen(encoded_message)],
5542                         raw_message,
5543                         (int)(raw_length+1)
5544                         );
5545         }
5546
5547         MSGM_syslog(LOG_DEBUG, "Allocating\n");
5548         msg = malloc(sizeof(struct CtdlMessage));
5549         memset(msg, 0, sizeof(struct CtdlMessage));
5550         msg->cm_magic = CTDLMESSAGE_MAGIC;
5551         msg->cm_anon_type = MES_NORMAL;
5552         msg->cm_format_type = 4;
5553         msg->cm_fields[eAuthor] = strdup(CCC->user.fullname);
5554         msg->cm_fields[eOriginalRoom] = strdup(req_room);
5555         msg->cm_fields[eNodeName] = strdup(config.c_nodename);
5556         msg->cm_fields[eHumanNode] = strdup(config.c_humannode);
5557         msg->cm_flags = flags;
5558         
5559         msg->cm_fields[eMesageText] = encoded_message;
5560
5561         /* Create the requested room if we have to. */
5562         if (CtdlGetRoom(&qrbuf, roomname) != 0) {
5563                 CtdlCreateRoom(roomname, 
5564                                ( (is_mailbox != NULL) ? 5 : 3 ),
5565                                "", 0, 1, 0, VIEW_BBS);
5566         }
5567         /* If the caller specified this object as unique, delete all
5568          * other objects of this type that are currently in the room.
5569          */
5570         if (is_unique) {
5571                 MSG_syslog(LOG_DEBUG, "Deleted %d other msgs of this type\n",
5572                            CtdlDeleteMessages(roomname, NULL, 0, content_type)
5573                         );
5574         }
5575         /* Now write the data */
5576         CtdlSubmitMsg(msg, NULL, roomname, 0);
5577         CM_Free(msg);
5578 }
5579
5580
5581
5582
5583
5584
5585 void CtdlGetSysConfigBackend(long msgnum, void *userdata) {
5586         config_msgnum = msgnum;
5587 }
5588
5589
5590 char *CtdlGetSysConfig(char *sysconfname) {
5591         char hold_rm[ROOMNAMELEN];
5592         long msgnum;
5593         char *conf;
5594         struct CtdlMessage *msg;
5595         char buf[SIZ];
5596         
5597         strcpy(hold_rm, CC->room.QRname);
5598         if (CtdlGetRoom(&CC->room, SYSCONFIGROOM) != 0) {
5599                 CtdlGetRoom(&CC->room, hold_rm);
5600                 return NULL;
5601         }
5602
5603
5604         /* We want the last (and probably only) config in this room */
5605         begin_critical_section(S_CONFIG);
5606         config_msgnum = (-1L);
5607         CtdlForEachMessage(MSGS_LAST, 1, NULL, sysconfname, NULL,
5608                            CtdlGetSysConfigBackend, NULL);
5609         msgnum = config_msgnum;
5610         end_critical_section(S_CONFIG);
5611
5612         if (msgnum < 0L) {
5613                 conf = NULL;
5614         }
5615         else {
5616                 msg = CtdlFetchMessage(msgnum, 1);
5617                 if (msg != NULL) {
5618                         conf = strdup(msg->cm_fields[eMesageText]);
5619                         CM_Free(msg);
5620                 }
5621                 else {
5622                         conf = NULL;
5623                 }
5624         }
5625
5626         CtdlGetRoom(&CC->room, hold_rm);
5627
5628         if (conf != NULL) do {
5629                         extract_token(buf, conf, 0, '\n', sizeof buf);
5630                         strcpy(conf, &conf[strlen(buf)+1]);
5631                 } while ( (!IsEmptyStr(conf)) && (!IsEmptyStr(buf)) );
5632
5633         return(conf);
5634 }
5635
5636
5637 void CtdlPutSysConfig(char *sysconfname, char *sysconfdata) {
5638         CtdlWriteObject(SYSCONFIGROOM, sysconfname, sysconfdata, (strlen(sysconfdata)+1), NULL, 0, 1, 0);
5639 }
5640
5641
5642 /*
5643  * Determine whether a given Internet address belongs to the current user
5644  */
5645 int CtdlIsMe(char *addr, int addr_buf_len)
5646 {
5647         struct recptypes *recp;
5648         int i;
5649
5650         recp = validate_recipients(addr, NULL, 0);
5651         if (recp == NULL) return(0);
5652
5653         if (recp->num_local == 0) {
5654                 free_recipients(recp);
5655                 return(0);
5656         }
5657
5658         for (i=0; i<recp->num_local; ++i) {
5659                 extract_token(addr, recp->recp_local, i, '|', addr_buf_len);
5660                 if (!strcasecmp(addr, CC->user.fullname)) {
5661                         free_recipients(recp);
5662                         return(1);
5663                 }
5664         }
5665
5666         free_recipients(recp);
5667         return(0);
5668 }
5669
5670
5671 /*
5672  * Citadel protocol command to do the same
5673  */
5674 void cmd_isme(char *argbuf) {
5675         char addr[256];
5676
5677         if (CtdlAccessCheck(ac_logged_in)) return;
5678         extract_token(addr, argbuf, 0, '|', sizeof addr);
5679
5680         if (CtdlIsMe(addr, sizeof addr)) {
5681                 cprintf("%d %s\n", CIT_OK, addr);
5682         }
5683         else {
5684                 cprintf("%d Not you.\n", ERROR + ILLEGAL_VALUE);
5685         }
5686
5687 }
5688
5689
5690 /*****************************************************************************/
5691 /*                      MODULE INITIALIZATION STUFF                          */
5692 /*****************************************************************************/
5693 void SetMessageDebugEnabled(const int n)
5694 {
5695         MessageDebugEnabled = n;
5696 }
5697 CTDL_MODULE_INIT(msgbase)
5698 {
5699         if (!threading) {
5700                 CtdlRegisterDebugFlagHook(HKEY("messages"), SetMessageDebugEnabled, &MessageDebugEnabled);
5701
5702                 CtdlRegisterProtoHook(cmd_msgs, "MSGS", "Output a list of messages in the current room");
5703                 CtdlRegisterProtoHook(cmd_msg0, "MSG0", "Output a message in plain text format");
5704                 CtdlRegisterProtoHook(cmd_msg2, "MSG2", "Output a message in RFC822 format");
5705                 CtdlRegisterProtoHook(cmd_msg3, "MSG3", "Output a message in raw format (deprecated)");
5706                 CtdlRegisterProtoHook(cmd_msg4, "MSG4", "Output a message in the client's preferred format");
5707                 CtdlRegisterProtoHook(cmd_msgp, "MSGP", "Select preferred format for MSG4 output");
5708                 CtdlRegisterProtoHook(cmd_opna, "OPNA", "Open an attachment for download");
5709                 CtdlRegisterProtoHook(cmd_dlat, "DLAT", "Download an attachment");
5710                 CtdlRegisterProtoHook(cmd_ent0, "ENT0", "Enter a message");
5711                 CtdlRegisterProtoHook(cmd_dele, "DELE", "Delete a message");
5712                 CtdlRegisterProtoHook(cmd_move, "MOVE", "Move or copy a message to another room");
5713                 CtdlRegisterProtoHook(cmd_isme, "ISME", "Determine whether an email address belongs to a user");
5714         }
5715
5716         /* return our Subversion id for the Log */
5717         return "msgbase";
5718 }