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