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