a125d01e36d9bed841a1732550c5c529c2a037b3
[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, CC->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                 return NULL;
1217         }
1218         mptr = dmsgtext->ptr;
1219         upper_bound = mptr + dmsgtext->len;
1220
1221         /* Parse the three bytes that begin EVERY message on disk.
1222          * The first is always 0xFF, the on-disk magic number.
1223          * The second is the anonymous/public type byte.
1224          * The third is the format type byte (vari, fixed, or MIME).
1225          */
1226         ch = *mptr++;
1227         if (ch != 255) {
1228                 MSG_syslog(LOG_ERR, "Message %ld appears to be corrupted.\n", msgnum);
1229                 cdb_free(dmsgtext);
1230                 return NULL;
1231         }
1232         ret = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
1233         memset(ret, 0, sizeof(struct CtdlMessage));
1234
1235         ret->cm_magic = CTDLMESSAGE_MAGIC;
1236         ret->cm_anon_type = *mptr++;    /* Anon type byte */
1237         ret->cm_format_type = *mptr++;  /* Format type byte */
1238
1239         /*
1240          * The rest is zero or more arbitrary fields.  Load them in.
1241          * We're done when we encounter either a zero-length field or
1242          * have just processed the 'M' (message text) field.
1243          */
1244         do {
1245                 if (mptr >= upper_bound) {
1246                         break;
1247                 }
1248                 field_header = *mptr++;
1249                 ret->cm_fields[field_header] = strdup(mptr);
1250
1251                 while (*mptr++ != 0);   /* advance to next field */
1252
1253         } while ((mptr < upper_bound) && (field_header != 'M'));
1254
1255         cdb_free(dmsgtext);
1256
1257         /* Always make sure there's something in the msg text field.  If
1258          * it's NULL, the message text is most likely stored separately,
1259          * so go ahead and fetch that.  Failing that, just set a dummy
1260          * body so other code doesn't barf.
1261          */
1262         if ( (ret->cm_fields['M'] == NULL) && (with_body) ) {
1263                 dmsgtext = cdb_fetch(CDB_BIGMSGS, &msgnum, sizeof(long));
1264                 if (dmsgtext != NULL) {
1265                         ret->cm_fields['M'] = dmsgtext->ptr;
1266                         dmsgtext->ptr = NULL;
1267                         cdb_free(dmsgtext);
1268                 }
1269         }
1270         if (ret->cm_fields['M'] == NULL) {
1271                 ret->cm_fields['M'] = strdup("\r\n\r\n (no text)\r\n");
1272         }
1273
1274         /* Perform "before read" hooks (aborting if any return nonzero) */
1275         if (PerformMessageHooks(ret, EVT_BEFOREREAD) > 0) {
1276                 CtdlFreeMessage(ret);
1277                 return NULL;
1278         }
1279
1280         return (ret);
1281 }
1282
1283
1284 /*
1285  * Returns 1 if the supplied pointer points to a valid Citadel message.
1286  * If the pointer is NULL or the magic number check fails, returns 0.
1287  */
1288 int is_valid_message(struct CtdlMessage *msg) {
1289         if (msg == NULL)
1290                 return 0;
1291         if ((msg->cm_magic) != CTDLMESSAGE_MAGIC) {
1292                 struct CitContext *CCC = CC;
1293                 MSGM_syslog(LOG_WARNING, "is_valid_message() -- self-check failed\n");
1294                 return 0;
1295         }
1296         return 1;
1297 }
1298
1299 void CtdlFreeMessageContents(struct CtdlMessage *msg)
1300 {
1301         int i;
1302
1303         for (i = 0; i < 256; ++i)
1304                 if (msg->cm_fields[i] != NULL) {
1305                         free(msg->cm_fields[i]);
1306                 }
1307
1308         msg->cm_magic = 0;      /* just in case */
1309 }
1310 /*
1311  * 'Destructor' for struct CtdlMessage
1312  */
1313 void CtdlFreeMessage(struct CtdlMessage *msg)
1314 {
1315         if (is_valid_message(msg) == 0) 
1316         {
1317                 if (msg != NULL) free (msg);
1318                 return;
1319         }
1320         CtdlFreeMessageContents(msg);
1321         free(msg);
1322 }
1323
1324 int DupCMField(int i, struct CtdlMessage *OrgMsg, struct CtdlMessage *NewMsg)
1325 {
1326         long len;
1327         len = strlen(OrgMsg->cm_fields[i]);
1328         NewMsg->cm_fields[i] = malloc(len + 1);
1329         if (NewMsg->cm_fields[i] == NULL)
1330                 return 0;
1331         memcpy(NewMsg->cm_fields[i], OrgMsg->cm_fields[i], len);
1332         NewMsg->cm_fields[i][len] = '\0';
1333         return 1;
1334 }
1335
1336 struct CtdlMessage * CtdlDuplicateMessage(struct CtdlMessage *OrgMsg)
1337 {
1338         int i;
1339         struct CtdlMessage *NewMsg;
1340
1341         if (is_valid_message(OrgMsg) == 0) 
1342                 return NULL;
1343         NewMsg = (struct CtdlMessage *)malloc(sizeof(struct CtdlMessage));
1344         if (NewMsg == NULL)
1345                 return NULL;
1346
1347         memcpy(NewMsg, OrgMsg, sizeof(struct CtdlMessage));
1348
1349         memset(&NewMsg->cm_fields, 0, sizeof(char*) * 256);
1350         
1351         for (i = 0; i < 256; ++i)
1352         {
1353                 if (OrgMsg->cm_fields[i] != NULL)
1354                 {
1355                         if (!DupCMField(i, OrgMsg, NewMsg))
1356                         {
1357                                 CtdlFreeMessage(NewMsg);
1358                                 return NULL;
1359                         }
1360                 }
1361         }
1362
1363         return NewMsg;
1364 }
1365
1366
1367
1368 /*
1369  * Pre callback function for multipart/alternative
1370  *
1371  * NOTE: this differs from the standard behavior for a reason.  Normally when
1372  *       displaying multipart/alternative you want to show the _last_ usable
1373  *       format in the message.  Here we show the _first_ one, because it's
1374  *       usually text/plain.  Since this set of functions is designed for text
1375  *       output to non-MIME-aware clients, this is the desired behavior.
1376  *
1377  */
1378 void fixed_output_pre(char *name, char *filename, char *partnum, char *disp,
1379                 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
1380                 char *cbid, void *cbuserdata)
1381 {
1382         struct CitContext *CCC = CC;
1383         struct ma_info *ma;
1384         
1385         ma = (struct ma_info *)cbuserdata;
1386         MSG_syslog(LOG_DEBUG, "fixed_output_pre() type=<%s>\n", cbtype);        
1387         if (!strcasecmp(cbtype, "multipart/alternative")) {
1388                 ++ma->is_ma;
1389                 ma->did_print = 0;
1390         }
1391         if (!strcasecmp(cbtype, "message/rfc822")) {
1392                 ++ma->freeze;
1393         }
1394 }
1395
1396 /*
1397  * Post callback function for multipart/alternative
1398  */
1399 void fixed_output_post(char *name, char *filename, char *partnum, char *disp,
1400                 void *content, char *cbtype, char *cbcharset, size_t length,
1401                 char *encoding, char *cbid, void *cbuserdata)
1402 {
1403         struct CitContext *CCC = CC;
1404         struct ma_info *ma;
1405         
1406         ma = (struct ma_info *)cbuserdata;
1407         MSG_syslog(LOG_DEBUG, "fixed_output_post() type=<%s>\n", cbtype);       
1408         if (!strcasecmp(cbtype, "multipart/alternative")) {
1409                 --ma->is_ma;
1410                 ma->did_print = 0;
1411         }
1412         if (!strcasecmp(cbtype, "message/rfc822")) {
1413                 --ma->freeze;
1414         }
1415 }
1416
1417 /*
1418  * Inline callback function for mime parser that wants to display text
1419  */
1420 void fixed_output(char *name, char *filename, char *partnum, char *disp,
1421                 void *content, char *cbtype, char *cbcharset, size_t length,
1422                 char *encoding, char *cbid, void *cbuserdata)
1423 {
1424         struct CitContext *CCC = CC;
1425         char *ptr;
1426         char *wptr;
1427         size_t wlen;
1428         struct ma_info *ma;
1429
1430         ma = (struct ma_info *)cbuserdata;
1431
1432         MSG_syslog(LOG_DEBUG,
1433                 "fixed_output() part %s: %s (%s) (%ld bytes)\n",
1434                 partnum, filename, cbtype, (long)length);
1435
1436         /*
1437          * If we're in the middle of a multipart/alternative scope and
1438          * we've already printed another section, skip this one.
1439          */     
1440         if ( (ma->is_ma) && (ma->did_print) ) {
1441                 MSG_syslog(LOG_DEBUG, "Skipping part %s (%s)\n", partnum, cbtype);
1442                 return;
1443         }
1444         ma->did_print = 1;
1445
1446         if ( (!strcasecmp(cbtype, "text/plain")) 
1447            || (IsEmptyStr(cbtype)) ) {
1448                 wptr = content;
1449                 if (length > 0) {
1450                         client_write(wptr, length);
1451                         if (wptr[length-1] != '\n') {
1452                                 cprintf("\n");
1453                         }
1454                 }
1455                 return;
1456         }
1457
1458         if (!strcasecmp(cbtype, "text/html")) {
1459                 ptr = html_to_ascii(content, length, 80, 0);
1460                 wlen = strlen(ptr);
1461                 client_write(ptr, wlen);
1462                 if ((wlen > 0) && (ptr[wlen-1] != '\n')) {
1463                         cprintf("\n");
1464                 }
1465                 free(ptr);
1466                 return;
1467         }
1468
1469         if (ma->use_fo_hooks) {
1470                 if (PerformFixedOutputHooks(cbtype, content, length)) {
1471                 /* above function returns nonzero if it handled the part */
1472                         return;
1473                 }
1474         }
1475
1476         if (strncasecmp(cbtype, "multipart/", 10)) {
1477                 cprintf("Part %s: %s (%s) (%ld bytes)\r\n",
1478                         partnum, filename, cbtype, (long)length);
1479                 return;
1480         }
1481 }
1482
1483 /*
1484  * The client is elegant and sophisticated and wants to be choosy about
1485  * MIME content types, so figure out which multipart/alternative part
1486  * we're going to send.
1487  *
1488  * We use a system of weights.  When we find a part that matches one of the
1489  * MIME types we've declared as preferential, we can store it in ma->chosen_part
1490  * and then set ma->chosen_pref to that MIME type's position in our preference
1491  * list.  If we then hit another match, we only replace the first match if
1492  * the preference value is lower.
1493  */
1494 void choose_preferred(char *name, char *filename, char *partnum, char *disp,
1495                 void *content, char *cbtype, char *cbcharset, size_t length,
1496                 char *encoding, char *cbid, void *cbuserdata)
1497 {
1498         struct CitContext *CCC = CC;
1499         char buf[1024];
1500         int i;
1501         struct ma_info *ma;
1502         
1503         ma = (struct ma_info *)cbuserdata;
1504
1505         // NOTE: REMOVING THIS CONDITIONAL FIXES BUG 220
1506         //       http://bugzilla.citadel.org/show_bug.cgi?id=220
1507         // I don't know if there are any side effects!  Please TEST TEST TEST
1508         //if (ma->is_ma > 0) {
1509
1510         for (i=0; i<num_tokens(CCC->preferred_formats, '|'); ++i) {
1511                 extract_token(buf, CCC->preferred_formats, i, '|', sizeof buf);
1512                 if ( (!strcasecmp(buf, cbtype)) && (!ma->freeze) ) {
1513                         if (i < ma->chosen_pref) {
1514                                 MSG_syslog(LOG_DEBUG, "Setting chosen part: <%s>\n", partnum);
1515                                 safestrncpy(ma->chosen_part, partnum, sizeof ma->chosen_part);
1516                                 ma->chosen_pref = i;
1517                         }
1518                 }
1519         }
1520 }
1521
1522 /*
1523  * Now that we've chosen our preferred part, output it.
1524  */
1525 void output_preferred(char *name, 
1526                       char *filename, 
1527                       char *partnum, 
1528                       char *disp,
1529                       void *content, 
1530                       char *cbtype, 
1531                       char *cbcharset, 
1532                       size_t length,
1533                       char *encoding, 
1534                       char *cbid, 
1535                       void *cbuserdata)
1536 {
1537         struct CitContext *CCC = CC;
1538         int i;
1539         char buf[128];
1540         int add_newline = 0;
1541         char *text_content;
1542         struct ma_info *ma;
1543         char *decoded = NULL;
1544         size_t bytes_decoded;
1545         int rc = 0;
1546
1547         ma = (struct ma_info *)cbuserdata;
1548
1549         /* This is not the MIME part you're looking for... */
1550         if (strcasecmp(partnum, ma->chosen_part)) return;
1551
1552         /* If the content-type of this part is in our preferred formats
1553          * list, we can simply output it verbatim.
1554          */
1555         for (i=0; i<num_tokens(CCC->preferred_formats, '|'); ++i) {
1556                 extract_token(buf, CCC->preferred_formats, i, '|', sizeof buf);
1557                 if (!strcasecmp(buf, cbtype)) {
1558                         /* Yeah!  Go!  W00t!! */
1559                         if (ma->dont_decode == 0) 
1560                                 rc = mime_decode_now (content, 
1561                                                       length,
1562                                                       encoding,
1563                                                       &decoded,
1564                                                       &bytes_decoded);
1565                         if (rc < 0)
1566                                 break; /* Give us the chance, maybe theres another one. */
1567
1568                         if (rc == 0) text_content = (char *)content;
1569                         else {
1570                                 text_content = decoded;
1571                                 length = bytes_decoded;
1572                         }
1573
1574                         if (text_content[length-1] != '\n') {
1575                                 ++add_newline;
1576                         }
1577                         cprintf("Content-type: %s", cbtype);
1578                         if (!IsEmptyStr(cbcharset)) {
1579                                 cprintf("; charset=%s", cbcharset);
1580                         }
1581                         cprintf("\nContent-length: %d\n",
1582                                 (int)(length + add_newline) );
1583                         if (!IsEmptyStr(encoding)) {
1584                                 cprintf("Content-transfer-encoding: %s\n", encoding);
1585                         }
1586                         else {
1587                                 cprintf("Content-transfer-encoding: 7bit\n");
1588                         }
1589                         cprintf("X-Citadel-MSG4-Partnum: %s\n", partnum);
1590                         cprintf("\n");
1591                         if (client_write(text_content, length) == -1)
1592                         {
1593                                 MSGM_syslog(LOG_ERR, "output_preferred(): aborting due to write failure.\n");
1594                                 return;
1595                         }
1596                         if (add_newline) cprintf("\n");
1597                         if (decoded != NULL) free(decoded);
1598                         return;
1599                 }
1600         }
1601
1602         /* No translations required or possible: output as text/plain */
1603         cprintf("Content-type: text/plain\n\n");
1604         rc = 0;
1605         if (ma->dont_decode == 0)
1606                 rc = mime_decode_now (content, 
1607                                       length,
1608                                       encoding,
1609                                       &decoded,
1610                                       &bytes_decoded);
1611         if (rc < 0)
1612                 return; /* Give us the chance, maybe theres another one. */
1613         
1614         if (rc == 0) text_content = (char *)content;
1615         else {
1616                 text_content = decoded;
1617                 length = bytes_decoded;
1618         }
1619
1620         fixed_output(name, filename, partnum, disp, text_content, cbtype, cbcharset,
1621                         length, encoding, cbid, cbuserdata);
1622         if (decoded != NULL) free(decoded);
1623 }
1624
1625
1626 struct encapmsg {
1627         char desired_section[64];
1628         char *msg;
1629         size_t msglen;
1630 };
1631
1632
1633 /*
1634  * Callback function for
1635  */
1636 void extract_encapsulated_message(char *name, char *filename, char *partnum, char *disp,
1637                    void *content, char *cbtype, char *cbcharset, size_t length,
1638                    char *encoding, char *cbid, void *cbuserdata)
1639 {
1640         struct encapmsg *encap;
1641
1642         encap = (struct encapmsg *)cbuserdata;
1643
1644         /* Only proceed if this is the desired section... */
1645         if (!strcasecmp(encap->desired_section, partnum)) {
1646                 encap->msglen = length;
1647                 encap->msg = malloc(length + 2);
1648                 memcpy(encap->msg, content, length);
1649                 return;
1650         }
1651 }
1652
1653
1654 /*
1655  * Determine whether the specified message exists in the cached_msglist
1656  * (This is a security check)
1657  */
1658 int check_cached_msglist(long msgnum) {
1659         struct CitContext *CCC = CC;
1660
1661         /* cases in which we skip the check */
1662         if (!CCC) return om_ok;                                         /* not a session */
1663         if (CCC->client_socket <= 0) return om_ok;                      /* not a client session */
1664         if (CCC->cached_msglist == NULL) return om_access_denied;       /* no msglist fetched */
1665         if (CCC->cached_num_msgs == 0) return om_access_denied;         /* nothing to check */
1666
1667
1668         /* Do a binary search within the cached_msglist for the requested msgnum */
1669         int min = 0;
1670         int max = (CC->cached_num_msgs - 1);
1671
1672         while (max >= min) {
1673                 int middle = min + (max-min) / 2 ;
1674                 if (msgnum == CCC->cached_msglist[middle]) {
1675                         return om_ok;
1676                 }
1677                 if (msgnum > CC->cached_msglist[middle]) {
1678                         min = middle + 1;
1679                 }
1680                 else {
1681                         max = middle - 1;
1682                 }
1683         }
1684
1685         return om_access_denied;
1686 }
1687
1688
1689 /* 
1690  * Determine whether the currently logged in session has permission to read
1691  * messages in the current room.
1692  */
1693 int CtdlDoIHavePermissionToReadMessagesInThisRoom(void) {
1694         if (    (!(CC->logged_in))
1695                 && (!(CC->internal_pgm))
1696                 && (!config.c_guest_logins)
1697         ) {
1698                 return(om_not_logged_in);
1699         }
1700         return(om_ok);
1701 }
1702
1703
1704 /*
1705  * Get a message off disk.  (returns om_* values found in msgbase.h)
1706  * 
1707  */
1708 int CtdlOutputMsg(long msg_num,         /* message number (local) to fetch */
1709                   int mode,             /* how would you like that message? */
1710                   int headers_only,     /* eschew the message body? */
1711                   int do_proto,         /* do Citadel protocol responses? */
1712                   int crlf,             /* Use CRLF newlines instead of LF? */
1713                   char *section,        /* NULL or a message/rfc822 section */
1714                   int flags,            /* various flags; see msgbase.h */
1715                   char **Author,
1716                   char **Address
1717 ) {
1718         struct CitContext *CCC = CC;
1719         struct CtdlMessage *TheMessage = NULL;
1720         int retcode = CIT_OK;
1721         struct encapmsg encap;
1722         int r;
1723
1724         MSG_syslog(LOG_DEBUG, "CtdlOutputMsg(msgnum=%ld, mode=%d, section=%s)\n", 
1725                 msg_num, mode,
1726                 (section ? section : "<>")
1727         );
1728
1729         r = CtdlDoIHavePermissionToReadMessagesInThisRoom();
1730         if (r != om_ok) {
1731                 if (do_proto) {
1732                         if (r == om_not_logged_in) {
1733                                 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
1734                         }
1735                         else {
1736                                 cprintf("%d An unknown error has occurred.\n", ERROR);
1737                         }
1738                 }
1739                 return(r);
1740         }
1741
1742         /*
1743          * Check to make sure the message is actually IN this room
1744          */
1745         r = check_cached_msglist(msg_num);
1746         if (r == om_access_denied) {
1747                 /* Not in the cache?  We get ONE shot to check it again. */
1748                 CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL, NULL, NULL);
1749                 r = check_cached_msglist(msg_num);
1750         }
1751         if (r != om_ok) {
1752                 MSG_syslog(LOG_DEBUG, "Security check fail: message %ld is not in %s\n",
1753                            msg_num, CCC->room.QRname
1754                 );
1755                 if (do_proto) {
1756                         if (r == om_access_denied) {
1757                                 cprintf("%d message %ld was not found in this room\n",
1758                                         ERROR + HIGHER_ACCESS_REQUIRED,
1759                                         msg_num
1760                                 );
1761                         }
1762                 }
1763                 return(r);
1764         }
1765
1766         /*
1767          * Fetch the message from disk.  If we're in HEADERS_FAST mode,
1768          * request that we don't even bother loading the body into memory.
1769          */
1770         if (headers_only == HEADERS_FAST) {
1771                 TheMessage = CtdlFetchMessage(msg_num, 0);
1772         }
1773         else {
1774                 TheMessage = CtdlFetchMessage(msg_num, 1);
1775         }
1776
1777         if (TheMessage == NULL) {
1778                 if (do_proto) cprintf("%d Can't locate msg %ld on disk\n",
1779                         ERROR + MESSAGE_NOT_FOUND, msg_num);
1780                 return(om_no_such_msg);
1781         }
1782
1783         /* Here is the weird form of this command, to process only an
1784          * encapsulated message/rfc822 section.
1785          */
1786         if (section) if (!IsEmptyStr(section)) if (strcmp(section, "0")) {
1787                 memset(&encap, 0, sizeof encap);
1788                 safestrncpy(encap.desired_section, section, sizeof encap.desired_section);
1789                 mime_parser(TheMessage->cm_fields['M'],
1790                         NULL,
1791                         *extract_encapsulated_message,
1792                         NULL, NULL, (void *)&encap, 0
1793                 );
1794
1795                 if ((Author != NULL) && (*Author == NULL))
1796                 {
1797                         *Author = TheMessage->cm_fields['A'];
1798                         TheMessage->cm_fields['A'] = NULL;
1799                 }
1800                 if ((Address != NULL) && (*Address == NULL))
1801                 {       
1802                         *Address = TheMessage->cm_fields['F'];
1803                         TheMessage->cm_fields['F'] = NULL;
1804                 }
1805                 CtdlFreeMessage(TheMessage);
1806                 TheMessage = NULL;
1807
1808                 if (encap.msg) {
1809                         encap.msg[encap.msglen] = 0;
1810                         TheMessage = convert_internet_message(encap.msg);
1811                         encap.msg = NULL;       /* no free() here, TheMessage owns it now */
1812
1813                         /* Now we let it fall through to the bottom of this
1814                          * function, because TheMessage now contains the
1815                          * encapsulated message instead of the top-level
1816                          * message.  Isn't that neat?
1817                          */
1818
1819                 }
1820                 else {
1821                         if (do_proto) {
1822                                 cprintf("%d msg %ld has no part %s\n",
1823                                         ERROR + MESSAGE_NOT_FOUND,
1824                                         msg_num,
1825                                         section);
1826                         }
1827                         retcode = om_no_such_msg;
1828                 }
1829
1830         }
1831
1832         /* Ok, output the message now */
1833         if (retcode == CIT_OK)
1834                 retcode = CtdlOutputPreLoadedMsg(TheMessage, mode, headers_only, do_proto, crlf, flags);
1835         if ((Author != NULL) && (*Author == NULL))
1836         {
1837                 *Author = TheMessage->cm_fields['A'];
1838                 TheMessage->cm_fields['A'] = NULL;
1839         }
1840         if ((Address != NULL) && (*Address == NULL))
1841         {       
1842                 *Address = TheMessage->cm_fields['F'];
1843                 TheMessage->cm_fields['F'] = NULL;
1844         }
1845
1846         CtdlFreeMessage(TheMessage);
1847
1848         return(retcode);
1849 }
1850
1851
1852 char *qp_encode_email_addrs(char *source)
1853 {
1854         struct CitContext *CCC = CC;
1855         char *user, *node, *name;
1856         const char headerStr[] = "=?UTF-8?Q?";
1857         char *Encoded;
1858         char *EncodedName;
1859         char *nPtr;
1860         int need_to_encode = 0;
1861         long SourceLen;
1862         long EncodedMaxLen;
1863         long nColons = 0;
1864         long *AddrPtr;
1865         long *AddrUtf8;
1866         long nAddrPtrMax = 50;
1867         long nmax;
1868         int InQuotes = 0;
1869         int i, n;
1870
1871         if (source == NULL) return source;
1872         if (IsEmptyStr(source)) return source;
1873         if (MessageDebugEnabled != 0) cit_backtrace();
1874         MSG_syslog(LOG_DEBUG, "qp_encode_email_addrs: [%s]\n", source);
1875
1876         AddrPtr = malloc (sizeof (long) * nAddrPtrMax);
1877         AddrUtf8 = malloc (sizeof (long) * nAddrPtrMax);
1878         memset(AddrUtf8, 0, sizeof (long) * nAddrPtrMax);
1879         *AddrPtr = 0;
1880         i = 0;
1881         while (!IsEmptyStr (&source[i])) {
1882                 if (nColons >= nAddrPtrMax){
1883                         long *ptr;
1884
1885                         ptr = (long *) malloc(sizeof (long) * nAddrPtrMax * 2);
1886                         memcpy (ptr, AddrPtr, sizeof (long) * nAddrPtrMax);
1887                         free (AddrPtr), AddrPtr = ptr;
1888
1889                         ptr = (long *) malloc(sizeof (long) * nAddrPtrMax * 2);
1890                         memset(&ptr[nAddrPtrMax], 0, 
1891                                sizeof (long) * nAddrPtrMax);
1892
1893                         memcpy (ptr, AddrUtf8, sizeof (long) * nAddrPtrMax);
1894                         free (AddrUtf8), AddrUtf8 = ptr;
1895                         nAddrPtrMax *= 2;                               
1896                 }
1897                 if (((unsigned char) source[i] < 32) || 
1898                     ((unsigned char) source[i] > 126)) {
1899                         need_to_encode = 1;
1900                         AddrUtf8[nColons] = 1;
1901                 }
1902                 if (source[i] == '"')
1903                         InQuotes = !InQuotes;
1904                 if (!InQuotes && source[i] == ',') {
1905                         AddrPtr[nColons] = i;
1906                         nColons++;
1907                 }
1908                 i++;
1909         }
1910         if (need_to_encode == 0) {
1911                 free(AddrPtr);
1912                 free(AddrUtf8);
1913                 return source;
1914         }
1915
1916         SourceLen = i;
1917         EncodedMaxLen = nColons * (sizeof(headerStr) + 3) + SourceLen * 3;
1918         Encoded = (char*) malloc (EncodedMaxLen);
1919
1920         for (i = 0; i < nColons; i++)
1921                 source[AddrPtr[i]++] = '\0';
1922         /* TODO: if libidn, this might get larger*/
1923         user = malloc(SourceLen + 1);
1924         node = malloc(SourceLen + 1);
1925         name = malloc(SourceLen + 1);
1926
1927         nPtr = Encoded;
1928         *nPtr = '\0';
1929         for (i = 0; i < nColons && nPtr != NULL; i++) {
1930                 nmax = EncodedMaxLen - (nPtr - Encoded);
1931                 if (AddrUtf8[i]) {
1932                         process_rfc822_addr(&source[AddrPtr[i]], 
1933                                             user,
1934                                             node,
1935                                             name);
1936                         /* TODO: libIDN here ! */
1937                         if (IsEmptyStr(name)) {
1938                                 n = snprintf(nPtr, nmax, 
1939                                              (i==0)?"%s@%s" : ",%s@%s",
1940                                              user, node);
1941                         }
1942                         else {
1943                                 EncodedName = rfc2047encode(name, strlen(name));                        
1944                                 n = snprintf(nPtr, nmax, 
1945                                              (i==0)?"%s <%s@%s>" : ",%s <%s@%s>",
1946                                              EncodedName, user, node);
1947                                 free(EncodedName);
1948                         }
1949                 }
1950                 else { 
1951                         n = snprintf(nPtr, nmax, 
1952                                      (i==0)?"%s" : ",%s",
1953                                      &source[AddrPtr[i]]);
1954                 }
1955                 if (n > 0 )
1956                         nPtr += n;
1957                 else { 
1958                         char *ptr, *nnPtr;
1959                         ptr = (char*) malloc(EncodedMaxLen * 2);
1960                         memcpy(ptr, Encoded, EncodedMaxLen);
1961                         nnPtr = ptr + (nPtr - Encoded), nPtr = nnPtr;
1962                         free(Encoded), Encoded = ptr;
1963                         EncodedMaxLen *= 2;
1964                         i--; /* do it once more with properly lengthened buffer */
1965                 }
1966         }
1967         for (i = 0; i < nColons; i++)
1968                 source[--AddrPtr[i]] = ',';
1969
1970         free(user);
1971         free(node);
1972         free(name);
1973         free(AddrUtf8);
1974         free(AddrPtr);
1975         return Encoded;
1976 }
1977
1978
1979 /* If the last item in a list of recipients was truncated to a partial address,
1980  * remove it completely in order to avoid choking libSieve
1981  */
1982 void sanitize_truncated_recipient(char *str)
1983 {
1984         if (!str) return;
1985         if (num_tokens(str, ',') < 2) return;
1986
1987         int len = strlen(str);
1988         if (len < 900) return;
1989         if (len > 998) str[998] = 0;
1990
1991         char *cptr = strrchr(str, ',');
1992         if (!cptr) return;
1993
1994         char *lptr = strchr(cptr, '<');
1995         char *rptr = strchr(cptr, '>');
1996
1997         if ( (lptr) && (rptr) && (rptr > lptr) ) return;
1998
1999         *cptr = 0;
2000 }
2001
2002
2003 void OutputCtdlMsgHeaders(
2004         struct CtdlMessage *TheMessage,
2005         int do_proto)           /* do Citadel protocol responses? */
2006 {
2007         char allkeys[30];
2008         int i, k, n;
2009         int suppress_f = 0;
2010         char buf[SIZ];
2011         char display_name[256];
2012
2013         /* begin header processing loop for Citadel message format */
2014         safestrncpy(display_name, "<unknown>", sizeof display_name);
2015         if (TheMessage->cm_fields['A']) {
2016                 strcpy(buf, TheMessage->cm_fields['A']);
2017                 if (TheMessage->cm_anon_type == MES_ANONONLY) {
2018                         safestrncpy(display_name, "****", sizeof display_name);
2019                 }
2020                 else if (TheMessage->cm_anon_type == MES_ANONOPT) {
2021                         safestrncpy(display_name, "anonymous", sizeof display_name);
2022                 }
2023                 else {
2024                         safestrncpy(display_name, buf, sizeof display_name);
2025                 }
2026                 if ((is_room_aide())
2027                     && ((TheMessage->cm_anon_type == MES_ANONONLY)
2028                         || (TheMessage->cm_anon_type == MES_ANONOPT))) {
2029                         size_t tmp = strlen(display_name);
2030                         snprintf(&display_name[tmp],
2031                                  sizeof display_name - tmp,
2032                                  " [%s]", buf);
2033                 }
2034         }
2035
2036         /* Don't show Internet address for users on the
2037          * local Citadel network.
2038          */
2039         suppress_f = 0;
2040         if (TheMessage->cm_fields['N'] != NULL)
2041                 if (!IsEmptyStr(TheMessage->cm_fields['N']))
2042                         if (haschar(TheMessage->cm_fields['N'], '.') == 0) {
2043                                 suppress_f = 1;
2044                         }
2045
2046         /* Now spew the header fields in the order we like them. */
2047         n = safestrncpy(allkeys, FORDER, sizeof allkeys);
2048         for (i=0; i<n; ++i) {
2049                 k = (int) allkeys[i];
2050                 if (k != 'M') {
2051                         if ( (TheMessage->cm_fields[k] != NULL)
2052                              && (msgkeys[k] != NULL) ) {
2053                                 if ((k == 'V') || (k == 'R') || (k == 'Y')) {
2054                                         sanitize_truncated_recipient(TheMessage->cm_fields[k]);
2055                                 }
2056                                 if (k == 'A') {
2057                                         if (do_proto) cprintf("%s=%s\n",
2058                                                               msgkeys[k],
2059                                                               display_name);
2060                                 }
2061                                 else if ((k == 'F') && (suppress_f)) {
2062                                         /* do nothing */
2063                                 }
2064                                 /* Masquerade display name if needed */
2065                                 else {
2066                                         if (do_proto) cprintf("%s=%s\n",
2067                                                               msgkeys[k],
2068                                                               TheMessage->cm_fields[k]
2069                                                 );
2070                                 }
2071                         }
2072                 }
2073         }
2074
2075 }
2076
2077 void OutputRFC822MsgHeaders(
2078         struct CtdlMessage *TheMessage,
2079         int flags,              /* should the bessage be exported clean */
2080         const char *nl,
2081         char *mid, long sizeof_mid,
2082         char *suser, long sizeof_suser,
2083         char *luser, long sizeof_luser,
2084         char *fuser, long sizeof_fuser,
2085         char *snode, long sizeof_snode)
2086 {
2087         char datestamp[100];
2088         int subject_found = 0;
2089         char buf[SIZ];
2090         int i, j, k;
2091         char *mptr = NULL;
2092         char *mpptr = NULL;
2093         char *hptr;
2094
2095         for (i = 0; i < 256; ++i) {
2096                 if (TheMessage->cm_fields[i]) {
2097                         mptr = mpptr = TheMessage->cm_fields[i];
2098                                 
2099                         if (i == 'A') {
2100                                 safestrncpy(luser, mptr, sizeof_luser);
2101                                 safestrncpy(suser, mptr, sizeof_suser);
2102                         }
2103                         else if (i == 'Y') {
2104                                 if ((flags & QP_EADDR) != 0) {
2105                                         mptr = qp_encode_email_addrs(mptr);
2106                                 }
2107                                 sanitize_truncated_recipient(mptr);
2108                                 cprintf("CC: %s%s", mptr, nl);
2109                         }
2110                         else if (i == 'P') {
2111                                 cprintf("Return-Path: %s%s", mptr, nl);
2112                         }
2113                         else if (i == 'L') {
2114                                 cprintf("List-ID: %s%s", mptr, nl);
2115                         }
2116                         else if (i == 'V') {
2117                                 if ((flags & QP_EADDR) != 0) 
2118                                         mptr = qp_encode_email_addrs(mptr);
2119                                 hptr = mptr;
2120                                 while ((*hptr != '\0') && isspace(*hptr))
2121                                         hptr ++;
2122                                 if (!IsEmptyStr(hptr))
2123                                         cprintf("Envelope-To: %s%s", hptr, nl);
2124                         }
2125                         else if (i == 'U') {
2126                                 cprintf("Subject: %s%s", mptr, nl);
2127                                 subject_found = 1;
2128                         }
2129                         else if (i == 'I')
2130                                 safestrncpy(mid, mptr, sizeof_mid); /// TODO: detect @ here and copy @nodename in if not found.
2131                         else if (i == 'F')
2132                                 safestrncpy(fuser, mptr, sizeof_fuser);
2133                         /* else if (i == 'O')
2134                            cprintf("X-Citadel-Room: %s%s",
2135                            mptr, nl); */
2136                         else if (i == 'N')
2137                                 safestrncpy(snode, mptr, sizeof_snode);
2138                         else if (i == 'R')
2139                         {
2140                                 if (haschar(mptr, '@') == 0)
2141                                 {
2142                                         sanitize_truncated_recipient(mptr);
2143                                         cprintf("To: %s@%s", mptr, config.c_fqdn);
2144                                         cprintf("%s", nl);
2145                                 }
2146                                 else
2147                                 {
2148                                         if ((flags & QP_EADDR) != 0) {
2149                                                 mptr = qp_encode_email_addrs(mptr);
2150                                         }
2151                                         sanitize_truncated_recipient(mptr);
2152                                         cprintf("To: %s", mptr);
2153                                         cprintf("%s", nl);
2154                                 }
2155                         }
2156                         else if (i == 'T') {
2157                                 datestring(datestamp, sizeof datestamp,
2158                                            atol(mptr), DATESTRING_RFC822);
2159                                 cprintf("Date: %s%s", datestamp, nl);
2160                         }
2161                         else if (i == 'W') {
2162                                 cprintf("References: ");
2163                                 k = num_tokens(mptr, '|');
2164                                 for (j=0; j<k; ++j) {
2165                                         extract_token(buf, mptr, j, '|', sizeof buf);
2166                                         cprintf("<%s>", buf);
2167                                         if (j == (k-1)) {
2168                                                 cprintf("%s", nl);
2169                                         }
2170                                         else {
2171                                                 cprintf(" ");
2172                                         }
2173                                 }
2174                         }
2175                         else if (i == 'K') {
2176                                 hptr = mptr;
2177                                 while ((*hptr != '\0') && isspace(*hptr))
2178                                         hptr ++;
2179                                 if (!IsEmptyStr(hptr))
2180                                         cprintf("Reply-To: %s%s", mptr, nl);
2181                         }
2182                         if (mptr != mpptr)
2183                                 free (mptr);
2184                 }
2185         }
2186         if (subject_found == 0) {
2187                 cprintf("Subject: (no subject)%s", nl);
2188         }
2189 }
2190
2191
2192 void Dump_RFC822HeadersBody(
2193         struct CtdlMessage *TheMessage,
2194         int headers_only,       /* eschew the message body? */
2195         int flags,              /* should the bessage be exported clean? */
2196
2197         const char *nl)
2198 {
2199         cit_uint8_t prev_ch;
2200         int eoh = 0;
2201         const char *StartOfText = StrBufNOTNULL;
2202         char outbuf[1024];
2203         int outlen = 0;
2204         int nllen = strlen(nl);
2205         char *mptr;
2206
2207         mptr = TheMessage->cm_fields['M'];
2208
2209
2210         prev_ch = '\0';
2211         while (*mptr != '\0') {
2212                 if (*mptr == '\r') {
2213                         /* do nothing */
2214                 }
2215                 else {
2216                         if ((!eoh) &&
2217                             (*mptr == '\n'))
2218                         {
2219                                 eoh = (*(mptr+1) == '\r') && (*(mptr+2) == '\n');
2220                                 if (!eoh)
2221                                         eoh = *(mptr+1) == '\n';
2222                                 if (eoh)
2223                                 {
2224                                         StartOfText = mptr;
2225                                         StartOfText = strchr(StartOfText, '\n');
2226                                         StartOfText = strchr(StartOfText, '\n');
2227                                 }
2228                         }
2229                         if (((headers_only == HEADERS_NONE) && (mptr >= StartOfText)) ||
2230                             ((headers_only == HEADERS_ONLY) && (mptr < StartOfText)) ||
2231                             ((headers_only != HEADERS_NONE) && 
2232                              (headers_only != HEADERS_ONLY))
2233                                 ) {
2234                                 if (*mptr == '\n') {
2235                                         memcpy(&outbuf[outlen], nl, nllen);
2236                                         outlen += nllen;
2237                                         outbuf[outlen] = '\0';
2238                                 }
2239                                 else {
2240                                         outbuf[outlen++] = *mptr;
2241                                 }
2242                         }
2243                 }
2244                 if (flags & ESC_DOT)
2245                 {
2246                         if ((prev_ch == '\n') && 
2247                             (*mptr == '.') && 
2248                             ((*(mptr+1) == '\r') || (*(mptr+1) == '\n')))
2249                         {
2250                                 outbuf[outlen++] = '.';
2251                         }
2252                         prev_ch = *mptr;
2253                 }
2254                 ++mptr;
2255                 if (outlen > 1000) {
2256                         if (client_write(outbuf, outlen) == -1)
2257                         {
2258                                 struct CitContext *CCC = CC;
2259                                 MSGM_syslog(LOG_ERR, "Dump_RFC822HeadersBody(): aborting due to write failure.\n");
2260                                 return;
2261                         }
2262                         outlen = 0;
2263                 }
2264         }
2265         if (outlen > 0) {
2266                 client_write(outbuf, outlen);
2267         }
2268 }
2269
2270
2271
2272 /* If the format type on disk is 1 (fixed-format), then we want
2273  * everything to be output completely literally ... regardless of
2274  * what message transfer format is in use.
2275  */
2276 void DumpFormatFixed(
2277         struct CtdlMessage *TheMessage,
2278         int mode,               /* how would you like that message? */
2279         const char *nl)
2280 {
2281         cit_uint8_t ch;
2282         char buf[SIZ];
2283         int buflen;
2284         int xlline = 0;
2285         int nllen = strlen (nl);
2286         char *mptr;
2287
2288         mptr = TheMessage->cm_fields['M'];
2289         
2290         if (mode == MT_MIME) {
2291                 cprintf("Content-type: text/plain\n\n");
2292         }
2293         *buf = '\0';
2294         buflen = 0;
2295         while (ch = *mptr++, ch > 0) {
2296                 if (ch == '\n')
2297                         ch = '\r';
2298
2299                 if ((buflen > 250) && (!xlline)){
2300                         int tbuflen;
2301                         tbuflen = buflen;
2302
2303                         while ((buflen > 0) && 
2304                                (!isspace(buf[buflen])))
2305                                 buflen --;
2306                         if (buflen == 0) {
2307                                 xlline = 1;
2308                         }
2309                         else {
2310                                 mptr -= tbuflen - buflen;
2311                                 buf[buflen] = '\0';
2312                                 ch = '\r';
2313                         }
2314                 }
2315                 /* if we reach the outer bounds of our buffer, 
2316                    abort without respect what whe purge. */
2317                 if (xlline && 
2318                     ((isspace(ch)) || 
2319                      (buflen > SIZ - nllen - 2)))
2320                         ch = '\r';
2321
2322                 if (ch == '\r') {
2323                         memcpy (&buf[buflen], nl, nllen);
2324                         buflen += nllen;
2325                         buf[buflen] = '\0';
2326
2327                         if (client_write(buf, buflen) == -1)
2328                         {
2329                                 struct CitContext *CCC = CC;
2330                                 MSGM_syslog(LOG_ERR, "DumpFormatFixed(): aborting due to write failure.\n");
2331                                 return;
2332                         }
2333                         *buf = '\0';
2334                         buflen = 0;
2335                         xlline = 0;
2336                 } else {
2337                         buf[buflen] = ch;
2338                         buflen++;
2339                 }
2340         }
2341         buf[buflen] = '\0';
2342         if (!IsEmptyStr(buf))
2343                 cprintf("%s%s", buf, nl);
2344 }
2345
2346 /*
2347  * Get a message off disk.  (returns om_* values found in msgbase.h)
2348  */
2349 int CtdlOutputPreLoadedMsg(
2350                 struct CtdlMessage *TheMessage,
2351                 int mode,               /* how would you like that message? */
2352                 int headers_only,       /* eschew the message body? */
2353                 int do_proto,           /* do Citadel protocol responses? */
2354                 int crlf,               /* Use CRLF newlines instead of LF? */
2355                 int flags               /* should the bessage be exported clean? */
2356 ) {
2357         struct CitContext *CCC = CC;
2358         int i;
2359         char *mptr = NULL;
2360         const char *nl; /* newline string */
2361         struct ma_info ma;
2362
2363         /* Buffers needed for RFC822 translation.  These are all filled
2364          * using functions that are bounds-checked, and therefore we can
2365          * make them substantially smaller than SIZ.
2366          */
2367         char suser[100];
2368         char luser[100];
2369         char fuser[100];
2370         char snode[100];
2371         char mid[100];
2372
2373         MSG_syslog(LOG_DEBUG, "CtdlOutputPreLoadedMsg(TheMessage=%s, %d, %d, %d, %d\n",
2374                    ((TheMessage == NULL) ? "NULL" : "not null"),
2375                    mode, headers_only, do_proto, crlf);
2376
2377         strcpy(mid, "unknown");
2378         nl = (crlf ? "\r\n" : "\n");
2379
2380         if (!is_valid_message(TheMessage)) {
2381                 MSGM_syslog(LOG_ERR,
2382                             "ERROR: invalid preloaded message for output\n");
2383                 cit_backtrace ();
2384                 return(om_no_such_msg);
2385         }
2386
2387         /* Suppress envelope recipients if required to avoid disclosing BCC addresses.
2388          * Pad it with spaces in order to avoid changing the RFC822 length of the message.
2389          */
2390         if ( (flags & SUPPRESS_ENV_TO) && (TheMessage->cm_fields['V'] != NULL) ) {
2391                 memset(TheMessage->cm_fields['V'], ' ', strlen(TheMessage->cm_fields['V']));
2392         }
2393                 
2394         /* Are we downloading a MIME component? */
2395         if (mode == MT_DOWNLOAD) {
2396                 if (TheMessage->cm_format_type != FMT_RFC822) {
2397                         if (do_proto)
2398                                 cprintf("%d This is not a MIME message.\n",
2399                                 ERROR + ILLEGAL_VALUE);
2400                 } else if (CCC->download_fp != NULL) {
2401                         if (do_proto) cprintf(
2402                                 "%d You already have a download open.\n",
2403                                 ERROR + RESOURCE_BUSY);
2404                 } else {
2405                         /* Parse the message text component */
2406                         mptr = TheMessage->cm_fields['M'];
2407                         mime_parser(mptr, NULL, *mime_download, NULL, NULL, NULL, 0);
2408                         /* If there's no file open by this time, the requested
2409                          * section wasn't found, so print an error
2410                          */
2411                         if (CCC->download_fp == NULL) {
2412                                 if (do_proto) cprintf(
2413                                         "%d Section %s not found.\n",
2414                                         ERROR + FILE_NOT_FOUND,
2415                                         CCC->download_desired_section);
2416                         }
2417                 }
2418                 return((CCC->download_fp != NULL) ? om_ok : om_mime_error);
2419         }
2420
2421         /* MT_SPEW_SECTION is like MT_DOWNLOAD except it outputs the whole MIME part
2422          * in a single server operation instead of opening a download file.
2423          */
2424         if (mode == MT_SPEW_SECTION) {
2425                 if (TheMessage->cm_format_type != FMT_RFC822) {
2426                         if (do_proto)
2427                                 cprintf("%d This is not a MIME message.\n",
2428                                 ERROR + ILLEGAL_VALUE);
2429                 } else {
2430                         /* Parse the message text component */
2431                         int found_it = 0;
2432
2433                         mptr = TheMessage->cm_fields['M'];
2434                         mime_parser(mptr, NULL, *mime_spew_section, NULL, NULL, (void *)&found_it, 0);
2435                         /* If section wasn't found, print an error
2436                          */
2437                         if (!found_it) {
2438                                 if (do_proto) cprintf(
2439                                         "%d Section %s not found.\n",
2440                                         ERROR + FILE_NOT_FOUND,
2441                                         CCC->download_desired_section);
2442                         }
2443                 }
2444                 return((CCC->download_fp != NULL) ? om_ok : om_mime_error);
2445         }
2446
2447         /* now for the user-mode message reading loops */
2448         if (do_proto) cprintf("%d msg:\n", LISTING_FOLLOWS);
2449
2450         /* Does the caller want to skip the headers? */
2451         if (headers_only == HEADERS_NONE) goto START_TEXT;
2452
2453         /* Tell the client which format type we're using. */
2454         if ( (mode == MT_CITADEL) && (do_proto) ) {
2455                 cprintf("type=%d\n", TheMessage->cm_format_type);
2456         }
2457
2458         /* nhdr=yes means that we're only displaying headers, no body */
2459         if ( (TheMessage->cm_anon_type == MES_ANONONLY)
2460            && ((mode == MT_CITADEL) || (mode == MT_MIME))
2461            && (do_proto)
2462            ) {
2463                 cprintf("nhdr=yes\n");
2464         }
2465
2466         if ((mode == MT_CITADEL) || (mode == MT_MIME)) 
2467                 OutputCtdlMsgHeaders(TheMessage, do_proto);
2468
2469
2470         /* begin header processing loop for RFC822 transfer format */
2471         strcpy(suser, "");
2472         strcpy(luser, "");
2473         strcpy(fuser, "");
2474         strcpy(snode, NODENAME);
2475         if (mode == MT_RFC822) 
2476                 OutputRFC822MsgHeaders(
2477                         TheMessage,
2478                         flags,
2479                         nl,
2480                         mid, sizeof(mid),
2481                         suser, sizeof(suser),
2482                         luser, sizeof(luser),
2483                         fuser, sizeof(fuser),
2484                         snode, sizeof(snode)
2485                         );
2486
2487
2488         for (i=0; !IsEmptyStr(&suser[i]); ++i) {
2489                 suser[i] = tolower(suser[i]);
2490                 if (!isalnum(suser[i])) suser[i]='_';
2491         }
2492
2493         if (mode == MT_RFC822) {
2494                 if (!strcasecmp(snode, NODENAME)) {
2495                         safestrncpy(snode, FQDN, sizeof snode);
2496                 }
2497
2498                 /* Construct a fun message id */
2499                 cprintf("Message-ID: <%s", mid);/// todo: this possibly breaks threadding mails.
2500                 if (strchr(mid, '@')==NULL) {
2501                         cprintf("@%s", snode);
2502                 }
2503                 cprintf(">%s", nl);
2504
2505                 if (!is_room_aide() && (TheMessage->cm_anon_type == MES_ANONONLY)) {
2506                         cprintf("From: \"----\" <x@x.org>%s", nl);
2507                 }
2508                 else if (!is_room_aide() && (TheMessage->cm_anon_type == MES_ANONOPT)) {
2509                         cprintf("From: \"anonymous\" <x@x.org>%s", nl);
2510                 }
2511                 else if (!IsEmptyStr(fuser)) {
2512                         cprintf("From: \"%s\" <%s>%s", luser, fuser, nl);
2513                 }
2514                 else {
2515                         cprintf("From: \"%s\" <%s@%s>%s", luser, suser, snode, nl);
2516                 }
2517
2518                 /* Blank line signifying RFC822 end-of-headers */
2519                 if (TheMessage->cm_format_type != FMT_RFC822) {
2520                         cprintf("%s", nl);
2521                 }
2522         }
2523
2524         /* end header processing loop ... at this point, we're in the text */
2525 START_TEXT:
2526         if (headers_only == HEADERS_FAST) goto DONE;
2527
2528         /* Tell the client about the MIME parts in this message */
2529         if (TheMessage->cm_format_type == FMT_RFC822) {
2530                 if ( (mode == MT_CITADEL) || (mode == MT_MIME) ) {
2531                         mptr = TheMessage->cm_fields['M'];
2532                         memset(&ma, 0, sizeof(struct ma_info));
2533                         mime_parser(mptr, NULL,
2534                                 (do_proto ? *list_this_part : NULL),
2535                                 (do_proto ? *list_this_pref : NULL),
2536                                 (do_proto ? *list_this_suff : NULL),
2537                                 (void *)&ma, 1);
2538                 }
2539                 else if (mode == MT_RFC822) {   /* unparsed RFC822 dump */
2540                         Dump_RFC822HeadersBody(
2541                                 TheMessage,
2542                                 headers_only,
2543                                 flags,
2544                                 nl);
2545                         goto DONE;
2546                 }
2547         }
2548
2549         if (headers_only == HEADERS_ONLY) {
2550                 goto DONE;
2551         }
2552
2553         /* signify start of msg text */
2554         if ( (mode == MT_CITADEL) || (mode == MT_MIME) ) {
2555                 if (do_proto) cprintf("text\n");
2556         }
2557
2558         if (TheMessage->cm_format_type == FMT_FIXED) 
2559                 DumpFormatFixed(
2560                         TheMessage,
2561                         mode,           /* how would you like that message? */
2562                         nl);
2563
2564         /* If the message on disk is format 0 (Citadel vari-format), we
2565          * output using the formatter at 80 columns.  This is the final output
2566          * form if the transfer format is RFC822, but if the transfer format
2567          * is Citadel proprietary, it'll still work, because the indentation
2568          * for new paragraphs is correct and the client will reformat the
2569          * message to the reader's screen width.
2570          */
2571         if (TheMessage->cm_format_type == FMT_CITADEL) {
2572                 mptr = TheMessage->cm_fields['M'];
2573
2574                 if (mode == MT_MIME) {
2575                         cprintf("Content-type: text/x-citadel-variformat\n\n");
2576                 }
2577                 memfmout(mptr, nl);
2578         }
2579
2580         /* If the message on disk is format 4 (MIME), we've gotta hand it
2581          * off to the MIME parser.  The client has already been told that
2582          * this message is format 1 (fixed format), so the callback function
2583          * we use will display those parts as-is.
2584          */
2585         if (TheMessage->cm_format_type == FMT_RFC822) {
2586                 memset(&ma, 0, sizeof(struct ma_info));
2587
2588                 if (mode == MT_MIME) {
2589                         ma.use_fo_hooks = 0;
2590                         strcpy(ma.chosen_part, "1");
2591                         ma.chosen_pref = 9999;
2592                         ma.dont_decode = CCC->msg4_dont_decode;
2593                         mime_parser(mptr, NULL,
2594                                 *choose_preferred, *fixed_output_pre,
2595                                 *fixed_output_post, (void *)&ma, 1);
2596                         mime_parser(mptr, NULL,
2597                                 *output_preferred, NULL, NULL, (void *)&ma, 1);
2598                 }
2599                 else {
2600                         ma.use_fo_hooks = 1;
2601                         mime_parser(mptr, NULL,
2602                                 *fixed_output, *fixed_output_pre,
2603                                 *fixed_output_post, (void *)&ma, 0);
2604                 }
2605
2606         }
2607
2608 DONE:   /* now we're done */
2609         if (do_proto) cprintf("000\n");
2610         return(om_ok);
2611 }
2612
2613
2614 /*
2615  * display a message (mode 0 - Citadel proprietary)
2616  */
2617 void cmd_msg0(char *cmdbuf)
2618 {
2619         long msgid;
2620         int headers_only = HEADERS_ALL;
2621
2622         msgid = extract_long(cmdbuf, 0);
2623         headers_only = extract_int(cmdbuf, 1);
2624
2625         CtdlOutputMsg(msgid, MT_CITADEL, headers_only, 1, 0, NULL, 0, NULL, NULL);
2626         return;
2627 }
2628
2629
2630 /*
2631  * display a message (mode 2 - RFC822)
2632  */
2633 void cmd_msg2(char *cmdbuf)
2634 {
2635         long msgid;
2636         int headers_only = HEADERS_ALL;
2637
2638         msgid = extract_long(cmdbuf, 0);
2639         headers_only = extract_int(cmdbuf, 1);
2640
2641         CtdlOutputMsg(msgid, MT_RFC822, headers_only, 1, 1, NULL, 0, NULL, NULL);
2642 }
2643
2644
2645
2646 /* 
2647  * display a message (mode 3 - IGnet raw format - internal programs only)
2648  */
2649 void cmd_msg3(char *cmdbuf)
2650 {
2651         long msgnum;
2652         struct CtdlMessage *msg = NULL;
2653         struct ser_ret smr;
2654
2655         if (CC->internal_pgm == 0) {
2656                 cprintf("%d This command is for internal programs only.\n",
2657                         ERROR + HIGHER_ACCESS_REQUIRED);
2658                 return;
2659         }
2660
2661         msgnum = extract_long(cmdbuf, 0);
2662         msg = CtdlFetchMessage(msgnum, 1);
2663         if (msg == NULL) {
2664                 cprintf("%d Message %ld not found.\n", 
2665                         ERROR + MESSAGE_NOT_FOUND, msgnum);
2666                 return;
2667         }
2668
2669         serialize_message(&smr, msg);
2670         CtdlFreeMessage(msg);
2671
2672         if (smr.len == 0) {
2673                 cprintf("%d Unable to serialize message\n",
2674                         ERROR + INTERNAL_ERROR);
2675                 return;
2676         }
2677
2678         cprintf("%d %ld\n", BINARY_FOLLOWS, (long)smr.len);
2679         client_write((char *)smr.ser, (int)smr.len);
2680         free(smr.ser);
2681 }
2682
2683
2684
2685 /* 
2686  * Display a message using MIME content types
2687  */
2688 void cmd_msg4(char *cmdbuf)
2689 {
2690         long msgid;
2691         char section[64];
2692
2693         msgid = extract_long(cmdbuf, 0);
2694         extract_token(section, cmdbuf, 1, '|', sizeof section);
2695         CtdlOutputMsg(msgid, MT_MIME, 0, 1, 0, (section[0] ? section : NULL) , 0, NULL, NULL);
2696 }
2697
2698
2699
2700 /* 
2701  * Client tells us its preferred message format(s)
2702  */
2703 void cmd_msgp(char *cmdbuf)
2704 {
2705         if (!strcasecmp(cmdbuf, "dont_decode")) {
2706                 CC->msg4_dont_decode = 1;
2707                 cprintf("%d MSG4 will not pre-decode messages.\n", CIT_OK);
2708         }
2709         else {
2710                 safestrncpy(CC->preferred_formats, cmdbuf, sizeof(CC->preferred_formats));
2711                 cprintf("%d Preferred MIME formats have been set.\n", CIT_OK);
2712         }
2713 }
2714
2715
2716 /*
2717  * Open a component of a MIME message as a download file 
2718  */
2719 void cmd_opna(char *cmdbuf)
2720 {
2721         long msgid;
2722         char desired_section[128];
2723
2724         msgid = extract_long(cmdbuf, 0);
2725         extract_token(desired_section, cmdbuf, 1, '|', sizeof desired_section);
2726         safestrncpy(CC->download_desired_section, desired_section,
2727                 sizeof CC->download_desired_section);
2728         CtdlOutputMsg(msgid, MT_DOWNLOAD, 0, 1, 1, NULL, 0, NULL, NULL);
2729 }                       
2730
2731
2732 /*
2733  * Open a component of a MIME message and transmit it all at once
2734  */
2735 void cmd_dlat(char *cmdbuf)
2736 {
2737         long msgid;
2738         char desired_section[128];
2739
2740         msgid = extract_long(cmdbuf, 0);
2741         extract_token(desired_section, cmdbuf, 1, '|', sizeof desired_section);
2742         safestrncpy(CC->download_desired_section, desired_section,
2743                 sizeof CC->download_desired_section);
2744         CtdlOutputMsg(msgid, MT_SPEW_SECTION, 0, 1, 1, NULL, 0, NULL, NULL);
2745 }
2746
2747
2748 /*
2749  * Save one or more message pointers into a specified room
2750  * (Returns 0 for success, nonzero for failure)
2751  * roomname may be NULL to use the current room
2752  *
2753  * Note that the 'supplied_msg' field may be set to NULL, in which case
2754  * the message will be fetched from disk, by number, if we need to perform
2755  * replication checks.  This adds an additional database read, so if the
2756  * caller already has the message in memory then it should be supplied.  (Obviously
2757  * this mode of operation only works if we're saving a single message.)
2758  */
2759 int CtdlSaveMsgPointersInRoom(char *roomname, long newmsgidlist[], int num_newmsgs,
2760                         int do_repl_check, struct CtdlMessage *supplied_msg, int suppress_refcount_adj
2761 ) {
2762         struct CitContext *CCC = CC;
2763         int i, j, unique;
2764         char hold_rm[ROOMNAMELEN];
2765         struct cdbdata *cdbfr;
2766         int num_msgs;
2767         long *msglist;
2768         long highest_msg = 0L;
2769
2770         long msgid = 0;
2771         struct CtdlMessage *msg = NULL;
2772
2773         long *msgs_to_be_merged = NULL;
2774         int num_msgs_to_be_merged = 0;
2775
2776         MSG_syslog(LOG_DEBUG,
2777                    "CtdlSaveMsgPointersInRoom(room=%s, num_msgs=%d, repl=%d, suppress_rca=%d)\n",
2778                    roomname, num_newmsgs, do_repl_check, suppress_refcount_adj
2779         );
2780
2781         strcpy(hold_rm, CCC->room.QRname);
2782
2783         /* Sanity checks */
2784         if (newmsgidlist == NULL) return(ERROR + INTERNAL_ERROR);
2785         if (num_newmsgs < 1) return(ERROR + INTERNAL_ERROR);
2786         if (num_newmsgs > 1) supplied_msg = NULL;
2787
2788         /* Now the regular stuff */
2789         if (CtdlGetRoomLock(&CCC->room,
2790            ((roomname != NULL) ? roomname : CCC->room.QRname) )
2791            != 0) {
2792                 MSG_syslog(LOG_ERR, "No such room <%s>\n", roomname);
2793                 return(ERROR + ROOM_NOT_FOUND);
2794         }
2795
2796
2797         msgs_to_be_merged = malloc(sizeof(long) * num_newmsgs);
2798         num_msgs_to_be_merged = 0;
2799
2800
2801         cdbfr = cdb_fetch(CDB_MSGLISTS, &CCC->room.QRnumber, sizeof(long));
2802         if (cdbfr == NULL) {
2803                 msglist = NULL;
2804                 num_msgs = 0;
2805         } else {
2806                 msglist = (long *) cdbfr->ptr;
2807                 cdbfr->ptr = NULL;      /* CtdlSaveMsgPointerInRoom() now owns this memory */
2808                 num_msgs = cdbfr->len / sizeof(long);
2809                 cdb_free(cdbfr);
2810         }
2811
2812
2813         /* Create a list of msgid's which were supplied by the caller, but do
2814          * not already exist in the target room.  It is absolutely taboo to
2815          * have more than one reference to the same message in a room.
2816          */
2817         for (i=0; i<num_newmsgs; ++i) {
2818                 unique = 1;
2819                 if (num_msgs > 0) for (j=0; j<num_msgs; ++j) {
2820                         if (msglist[j] == newmsgidlist[i]) {
2821                                 unique = 0;
2822                         }
2823                 }
2824                 if (unique) {
2825                         msgs_to_be_merged[num_msgs_to_be_merged++] = newmsgidlist[i];
2826                 }
2827         }
2828
2829         MSG_syslog(LOG_DEBUG, "%d unique messages to be merged\n", num_msgs_to_be_merged);
2830
2831         /*
2832          * Now merge the new messages
2833          */
2834         msglist = realloc(msglist, (sizeof(long) * (num_msgs + num_msgs_to_be_merged)) );
2835         if (msglist == NULL) {
2836                 MSGM_syslog(LOG_ALERT, "ERROR: can't realloc message list!\n");
2837                 free(msgs_to_be_merged);
2838                 return (ERROR + INTERNAL_ERROR);
2839         }
2840         memcpy(&msglist[num_msgs], msgs_to_be_merged, (sizeof(long) * num_msgs_to_be_merged) );
2841         num_msgs += num_msgs_to_be_merged;
2842
2843         /* Sort the message list, so all the msgid's are in order */
2844         num_msgs = sort_msglist(msglist, num_msgs);
2845
2846         /* Determine the highest message number */
2847         highest_msg = msglist[num_msgs - 1];
2848
2849         /* Write it back to disk. */
2850         cdb_store(CDB_MSGLISTS, &CCC->room.QRnumber, (int)sizeof(long),
2851                   msglist, (int)(num_msgs * sizeof(long)));
2852
2853         /* Free up the memory we used. */
2854         free(msglist);
2855
2856         /* Update the highest-message pointer and unlock the room. */
2857         CCC->room.QRhighest = highest_msg;
2858         CtdlPutRoomLock(&CCC->room);
2859
2860         /* Perform replication checks if necessary */
2861         if ( (DoesThisRoomNeedEuidIndexing(&CCC->room)) && (do_repl_check) ) {
2862                 MSGM_syslog(LOG_DEBUG, "CtdlSaveMsgPointerInRoom() doing repl checks\n");
2863
2864                 for (i=0; i<num_msgs_to_be_merged; ++i) {
2865                         msgid = msgs_to_be_merged[i];
2866         
2867                         if (supplied_msg != NULL) {
2868                                 msg = supplied_msg;
2869                         }
2870                         else {
2871                                 msg = CtdlFetchMessage(msgid, 0);
2872                         }
2873         
2874                         if (msg != NULL) {
2875                                 ReplicationChecks(msg);
2876                 
2877                                 /* If the message has an Exclusive ID, index that... */
2878                                 if (msg->cm_fields['E'] != NULL) {
2879                                         index_message_by_euid(msg->cm_fields['E'], &CCC->room, msgid);
2880                                 }
2881
2882                                 /* Free up the memory we may have allocated */
2883                                 if (msg != supplied_msg) {
2884                                         CtdlFreeMessage(msg);
2885                                 }
2886                         }
2887         
2888                 }
2889         }
2890
2891         else {
2892                 MSGM_syslog(LOG_DEBUG, "CtdlSaveMsgPointerInRoom() skips repl checks\n");
2893         }
2894
2895         /* Submit this room for processing by hooks */
2896         PerformRoomHooks(&CCC->room);
2897
2898         /* Go back to the room we were in before we wandered here... */
2899         CtdlGetRoom(&CCC->room, hold_rm);
2900
2901         /* Bump the reference count for all messages which were merged */
2902         if (!suppress_refcount_adj) {
2903                 AdjRefCountList(msgs_to_be_merged, num_msgs_to_be_merged, +1);
2904         }
2905
2906         /* Free up memory... */
2907         if (msgs_to_be_merged != NULL) {
2908                 free(msgs_to_be_merged);
2909         }
2910
2911         /* Return success. */
2912         return (0);
2913 }
2914
2915
2916 /*
2917  * This is the same as CtdlSaveMsgPointersInRoom() but it only accepts
2918  * a single message.
2919  */
2920 int CtdlSaveMsgPointerInRoom(char *roomname, long msgid,
2921                              int do_repl_check, struct CtdlMessage *supplied_msg)
2922 {
2923         return CtdlSaveMsgPointersInRoom(roomname, &msgid, 1, do_repl_check, supplied_msg, 0);
2924 }
2925
2926
2927
2928
2929 /*
2930  * Message base operation to save a new message to the message store
2931  * (returns new message number)
2932  *
2933  * This is the back end for CtdlSubmitMsg() and should not be directly
2934  * called by server-side modules.
2935  *
2936  */
2937 long send_message(struct CtdlMessage *msg) {
2938         struct CitContext *CCC = CC;
2939         long newmsgid;
2940         long retval;
2941         char msgidbuf[256];
2942         struct ser_ret smr;
2943         int is_bigmsg = 0;
2944         char *holdM = NULL;
2945
2946         /* Get a new message number */
2947         newmsgid = get_new_message_number();
2948         snprintf(msgidbuf, sizeof msgidbuf, "%08lX-%08lX@%s",
2949                  (long unsigned int) time(NULL),
2950                  (long unsigned int) newmsgid,
2951                  config.c_fqdn
2952                 );
2953
2954         /* Generate an ID if we don't have one already */
2955         if (msg->cm_fields['I']==NULL) {
2956                 msg->cm_fields['I'] = strdup(msgidbuf);
2957         }
2958
2959         /* If the message is big, set its body aside for storage elsewhere */
2960         if (msg->cm_fields['M'] != NULL) {
2961                 if (strlen(msg->cm_fields['M']) > BIGMSG) {
2962                         is_bigmsg = 1;
2963                         holdM = msg->cm_fields['M'];
2964                         msg->cm_fields['M'] = NULL;
2965                 }
2966         }
2967
2968         /* Serialize our data structure for storage in the database */  
2969         serialize_message(&smr, msg);
2970
2971         if (is_bigmsg) {
2972                 msg->cm_fields['M'] = holdM;
2973         }
2974
2975         if (smr.len == 0) {
2976                 cprintf("%d Unable to serialize message\n",
2977                         ERROR + INTERNAL_ERROR);
2978                 return (-1L);
2979         }
2980
2981         /* Write our little bundle of joy into the message base */
2982         if (cdb_store(CDB_MSGMAIN, &newmsgid, (int)sizeof(long),
2983                       smr.ser, smr.len) < 0) {
2984                 MSGM_syslog(LOG_ERR, "Can't store message\n");
2985                 retval = 0L;
2986         } else {
2987                 if (is_bigmsg) {
2988                         cdb_store(CDB_BIGMSGS,
2989                                   &newmsgid,
2990                                   (int)sizeof(long),
2991                                   holdM,
2992                                   (strlen(holdM) + 1)
2993                                 );
2994                 }
2995                 retval = newmsgid;
2996         }
2997
2998         /* Free the memory we used for the serialized message */
2999         free(smr.ser);
3000
3001         /* Return the *local* message ID to the caller
3002          * (even if we're storing an incoming network message)
3003          */
3004         return(retval);
3005 }
3006
3007
3008
3009 /*
3010  * Serialize a struct CtdlMessage into the format used on disk and network.
3011  * 
3012  * This function loads up a "struct ser_ret" (defined in server.h) which
3013  * contains the length of the serialized message and a pointer to the
3014  * serialized message in memory.  THE LATTER MUST BE FREED BY THE CALLER.
3015  */
3016 void serialize_message(struct ser_ret *ret,             /* return values */
3017                        struct CtdlMessage *msg) /* unserialized msg */
3018 {
3019         struct CitContext *CCC = CC;
3020         size_t wlen, fieldlen;
3021         int i;
3022         static char *forder = FORDER;
3023
3024         /*
3025          * Check for valid message format
3026          */
3027         if (is_valid_message(msg) == 0) {
3028                 MSGM_syslog(LOG_ERR, "serialize_message() aborting due to invalid message\n");
3029                 ret->len = 0;
3030                 ret->ser = NULL;
3031                 return;
3032         }
3033
3034         ret->len = 3;
3035         for (i=0; i<26; ++i) if (msg->cm_fields[(int)forder[i]] != NULL)
3036                                      ret->len = ret->len +
3037                                              strlen(msg->cm_fields[(int)forder[i]]) + 2;
3038
3039         ret->ser = malloc(ret->len);
3040         if (ret->ser == NULL) {
3041                 MSG_syslog(LOG_ERR, "serialize_message() malloc(%ld) failed: %s\n",
3042                            (long)ret->len, strerror(errno));
3043                 ret->len = 0;
3044                 ret->ser = NULL;
3045                 return;
3046         }
3047
3048         ret->ser[0] = 0xFF;
3049         ret->ser[1] = msg->cm_anon_type;
3050         ret->ser[2] = msg->cm_format_type;
3051         wlen = 3;
3052
3053         for (i=0; i<26; ++i) if (msg->cm_fields[(int)forder[i]] != NULL) {
3054                         fieldlen = strlen(msg->cm_fields[(int)forder[i]]);
3055                         ret->ser[wlen++] = (char)forder[i];
3056                         safestrncpy((char *)&ret->ser[wlen], msg->cm_fields[(int)forder[i]], fieldlen+1);
3057                         wlen = wlen + fieldlen + 1;
3058                 }
3059         if (ret->len != wlen) {
3060                 MSG_syslog(LOG_ERR, "ERROR: len=%ld wlen=%ld\n",
3061                            (long)ret->len, (long)wlen);
3062         }
3063
3064         return;
3065 }
3066
3067
3068 /*
3069  * Check to see if any messages already exist in the current room which
3070  * carry the same Exclusive ID as this one.  If any are found, delete them.
3071  */
3072 void ReplicationChecks(struct CtdlMessage *msg) {
3073         struct CitContext *CCC = CC;
3074         long old_msgnum = (-1L);
3075
3076         if (DoesThisRoomNeedEuidIndexing(&CCC->room) == 0) return;
3077
3078         MSG_syslog(LOG_DEBUG, "Performing replication checks in <%s>\n",
3079                    CCC->room.QRname);
3080
3081         /* No exclusive id?  Don't do anything. */
3082         if (msg == NULL) return;
3083         if (msg->cm_fields['E'] == NULL) return;
3084         if (IsEmptyStr(msg->cm_fields['E'])) return;
3085         /*MSG_syslog(LOG_DEBUG, "Exclusive ID: <%s> for room <%s>\n",
3086           msg->cm_fields['E'], CCC->room.QRname);*/
3087
3088         old_msgnum = CtdlLocateMessageByEuid(msg->cm_fields['E'], &CCC->room);
3089         if (old_msgnum > 0L) {
3090                 MSG_syslog(LOG_DEBUG, "ReplicationChecks() replacing message %ld\n", old_msgnum);
3091                 CtdlDeleteMessages(CCC->room.QRname, &old_msgnum, 1, "");
3092         }
3093 }
3094
3095
3096
3097 /*
3098  * Save a message to disk and submit it into the delivery system.
3099  */
3100 long CtdlSubmitMsg(struct CtdlMessage *msg,     /* message to save */
3101                    struct recptypes *recps,     /* recipients (if mail) */
3102                    const char *force,           /* force a particular room? */
3103                    int flags                    /* should the message be exported clean? */
3104         )
3105 {
3106         char submit_filename[128];
3107         char generated_timestamp[32];
3108         char hold_rm[ROOMNAMELEN];
3109         char actual_rm[ROOMNAMELEN];
3110         char force_room[ROOMNAMELEN];
3111         char content_type[SIZ];                 /* We have to learn this */
3112         char recipient[SIZ];
3113         const char *room;
3114         long newmsgid;
3115         const char *mptr = NULL;
3116         struct ctdluser userbuf;
3117         int a, i;
3118         struct MetaData smi;
3119         FILE *network_fp = NULL;
3120         static int seqnum = 1;
3121         struct CtdlMessage *imsg = NULL;
3122         char *instr = NULL;
3123         size_t instr_alloc = 0;
3124         struct ser_ret smr;
3125         char *hold_R, *hold_D;
3126         char *collected_addresses = NULL;
3127         struct addresses_to_be_filed *aptr = NULL;
3128         StrBuf *saved_rfc822_version = NULL;
3129         int qualified_for_journaling = 0;
3130         CitContext *CCC = MyContext();
3131         char bounce_to[1024] = "";
3132         int rv = 0;
3133
3134         MSGM_syslog(LOG_DEBUG, "CtdlSubmitMsg() called\n");
3135         if (is_valid_message(msg) == 0) return(-1);     /* self check */
3136
3137         /* If this message has no timestamp, we take the liberty of
3138          * giving it one, right now.
3139          */
3140         if (msg->cm_fields['T'] == NULL) {
3141                 snprintf(generated_timestamp, sizeof generated_timestamp, "%ld", (long)time(NULL));
3142                 msg->cm_fields['T'] = strdup(generated_timestamp);
3143         }
3144
3145         /* If this message has no path, we generate one.
3146          */
3147         if (msg->cm_fields['P'] == NULL) {
3148                 if (msg->cm_fields['A'] != NULL) {
3149                         msg->cm_fields['P'] = strdup(msg->cm_fields['A']);
3150                         for (a=0; !IsEmptyStr(&msg->cm_fields['P'][a]); ++a) {
3151                                 if (isspace(msg->cm_fields['P'][a])) {
3152                                         msg->cm_fields['P'][a] = ' ';
3153                                 }
3154                         }
3155                 }
3156                 else {
3157                         msg->cm_fields['P'] = strdup("unknown");
3158                 }
3159         }
3160
3161         if (force == NULL) {
3162                 strcpy(force_room, "");
3163         }
3164         else {
3165                 strcpy(force_room, force);
3166         }
3167
3168         /* Learn about what's inside, because it's what's inside that counts */
3169         if (msg->cm_fields['M'] == NULL) {
3170                 MSGM_syslog(LOG_ERR, "ERROR: attempt to save message with NULL body\n");
3171                 return(-2);
3172         }
3173
3174         switch (msg->cm_format_type) {
3175         case 0:
3176                 strcpy(content_type, "text/x-citadel-variformat");
3177                 break;
3178         case 1:
3179                 strcpy(content_type, "text/plain");
3180                 break;
3181         case 4:
3182                 strcpy(content_type, "text/plain");
3183                 mptr = bmstrcasestr(msg->cm_fields['M'], "Content-type:");
3184                 if (mptr != NULL) {
3185                         char *aptr;
3186                         safestrncpy(content_type, &mptr[13], sizeof content_type);
3187                         striplt(content_type);
3188                         aptr = content_type;
3189                         while (!IsEmptyStr(aptr)) {
3190                                 if ((*aptr == ';')
3191                                     || (*aptr == ' ')
3192                                     || (*aptr == 13)
3193                                     || (*aptr == 10)) {
3194                                         *aptr = 0;
3195                                 }
3196                                 else aptr++;
3197                         }
3198                 }
3199         }
3200
3201         /* Goto the correct room */
3202         room = (recps) ? CCC->room.QRname : SENTITEMS;
3203         MSG_syslog(LOG_DEBUG, "Selected room %s\n", room);
3204         strcpy(hold_rm, CCC->room.QRname);
3205         strcpy(actual_rm, CCC->room.QRname);
3206         if (recps != NULL) {
3207                 strcpy(actual_rm, SENTITEMS);
3208         }
3209
3210         /* If the user is a twit, move to the twit room for posting */
3211         if (TWITDETECT) {
3212                 if (CCC->user.axlevel == AxProbU) {
3213                         strcpy(hold_rm, actual_rm);
3214                         strcpy(actual_rm, config.c_twitroom);
3215                         MSGM_syslog(LOG_DEBUG, "Diverting to twit room\n");
3216                 }
3217         }
3218
3219         /* ...or if this message is destined for Aide> then go there. */
3220         if (!IsEmptyStr(force_room)) {
3221                 strcpy(actual_rm, force_room);
3222         }
3223
3224         MSG_syslog(LOG_INFO, "Final selection: %s (%s)\n", actual_rm, room);
3225         if (strcasecmp(actual_rm, CCC->room.QRname)) {
3226                 /* CtdlGetRoom(&CCC->room, actual_rm); */
3227                 CtdlUserGoto(actual_rm, 0, 1, NULL, NULL);
3228         }
3229
3230         /*
3231          * If this message has no O (room) field, generate one.
3232          */
3233         if (msg->cm_fields['O'] == NULL) {
3234                 msg->cm_fields['O'] = strdup(CCC->room.QRname);
3235         }
3236
3237         /* Perform "before save" hooks (aborting if any return nonzero) */
3238         MSGM_syslog(LOG_DEBUG, "Performing before-save hooks\n");
3239         if (PerformMessageHooks(msg, EVT_BEFORESAVE) > 0) return(-3);
3240
3241         /*
3242          * If this message has an Exclusive ID, and the room is replication
3243          * checking enabled, then do replication checks.
3244          */
3245         if (DoesThisRoomNeedEuidIndexing(&CCC->room)) {
3246                 ReplicationChecks(msg);
3247         }
3248
3249         /* Save it to disk */
3250         MSGM_syslog(LOG_DEBUG, "Saving to disk\n");
3251         newmsgid = send_message(msg);
3252         if (newmsgid <= 0L) return(-5);
3253
3254         /* Write a supplemental message info record.  This doesn't have to
3255          * be a critical section because nobody else knows about this message
3256          * yet.
3257          */
3258         MSGM_syslog(LOG_DEBUG, "Creating MetaData record\n");
3259         memset(&smi, 0, sizeof(struct MetaData));
3260         smi.meta_msgnum = newmsgid;
3261         smi.meta_refcount = 0;
3262         safestrncpy(smi.meta_content_type, content_type,
3263                     sizeof smi.meta_content_type);
3264
3265         /*
3266          * Measure how big this message will be when rendered as RFC822.
3267          * We do this for two reasons:
3268          * 1. We need the RFC822 length for the new metadata record, so the
3269          *    POP and IMAP services don't have to calculate message lengths
3270          *    while the user is waiting (multiplied by potentially hundreds
3271          *    or thousands of messages).
3272          * 2. If journaling is enabled, we will need an RFC822 version of the
3273          *    message to attach to the journalized copy.
3274          */
3275         if (CCC->redirect_buffer != NULL) {
3276                 MSGM_syslog(LOG_ALERT, "CCC->redirect_buffer is not NULL during message submission!\n");
3277                 abort();
3278         }
3279         CCC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
3280         CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_ALL, 0, 1, QP_EADDR);
3281         smi.meta_rfc822_length = StrLength(CCC->redirect_buffer);
3282         saved_rfc822_version = CCC->redirect_buffer;
3283         CCC->redirect_buffer = NULL;
3284
3285         PutMetaData(&smi);
3286
3287         /* Now figure out where to store the pointers */
3288         MSGM_syslog(LOG_DEBUG, "Storing pointers\n");
3289
3290         /* If this is being done by the networker delivering a private
3291          * message, we want to BYPASS saving the sender's copy (because there
3292          * is no local sender; it would otherwise go to the Trashcan).
3293          */
3294         if ((!CCC->internal_pgm) || (recps == NULL)) {
3295                 if (CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 1, msg) != 0) {
3296                         MSGM_syslog(LOG_ERR, "ERROR saving message pointer!\n");
3297                         CtdlSaveMsgPointerInRoom(config.c_aideroom, newmsgid, 0, msg);
3298                 }
3299         }
3300
3301         /* For internet mail, drop a copy in the outbound queue room */
3302         if ((recps != NULL) && (recps->num_internet > 0)) {
3303                 CtdlSaveMsgPointerInRoom(SMTP_SPOOLOUT_ROOM, newmsgid, 0, msg);
3304         }
3305
3306         /* If other rooms are specified, drop them there too. */
3307         if ((recps != NULL) && (recps->num_room > 0))
3308                 for (i=0; i<num_tokens(recps->recp_room, '|'); ++i) {
3309                         extract_token(recipient, recps->recp_room, i,
3310                                       '|', sizeof recipient);
3311                         MSG_syslog(LOG_DEBUG, "Delivering to room <%s>\n", recipient);///// xxxx
3312                         CtdlSaveMsgPointerInRoom(recipient, newmsgid, 0, msg);
3313                 }
3314
3315         /* Bump this user's messages posted counter. */
3316         MSGM_syslog(LOG_DEBUG, "Updating user\n");
3317         CtdlGetUserLock(&CCC->user, CCC->curr_user);
3318         CCC->user.posted = CCC->user.posted + 1;
3319         CtdlPutUserLock(&CCC->user);
3320
3321         /* Decide where bounces need to be delivered */
3322         if ((recps != NULL) && (recps->bounce_to != NULL)) {
3323                 safestrncpy(bounce_to, recps->bounce_to, sizeof bounce_to);
3324         }
3325         else if (CCC->logged_in) {
3326                 snprintf(bounce_to, sizeof bounce_to, "%s@%s", CCC->user.fullname, config.c_nodename);
3327         }
3328         else {
3329                 snprintf(bounce_to, sizeof bounce_to, "%s@%s", msg->cm_fields['A'], msg->cm_fields['N']);
3330         }
3331
3332         /* If this is private, local mail, make a copy in the
3333          * recipient's mailbox and bump the reference count.
3334          */
3335         if ((recps != NULL) && (recps->num_local > 0))
3336                 for (i=0; i<num_tokens(recps->recp_local, '|'); ++i) {
3337                         extract_token(recipient, recps->recp_local, i,
3338                                       '|', sizeof recipient);
3339                         MSG_syslog(LOG_DEBUG, "Delivering private local mail to <%s>\n",
3340                                recipient);
3341                         if (CtdlGetUser(&userbuf, recipient) == 0) {
3342                                 CtdlMailboxName(actual_rm, sizeof actual_rm, &userbuf, MAILROOM);
3343                                 CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 0, msg);
3344                                 CtdlBumpNewMailCounter(userbuf.usernum);
3345                                 if (!IsEmptyStr(config.c_funambol_host) || !IsEmptyStr(config.c_pager_program)) {
3346                                         /* Generate a instruction message for the Funambol notification
3347                                          * server, in the same style as the SMTP queue
3348                                          */
3349                                         instr_alloc = 1024;
3350                                         instr = malloc(instr_alloc);
3351                                         snprintf(instr, instr_alloc,
3352                                                  "Content-type: %s\n\nmsgid|%ld\nsubmitted|%ld\n"
3353                                                  "bounceto|%s\n",
3354                                                  SPOOLMIME, newmsgid, (long)time(NULL),
3355                                                  bounce_to
3356                                                 );
3357                                 
3358                                         imsg = malloc(sizeof(struct CtdlMessage));
3359                                         memset(imsg, 0, sizeof(struct CtdlMessage));
3360                                         imsg->cm_magic = CTDLMESSAGE_MAGIC;
3361                                         imsg->cm_anon_type = MES_NORMAL;
3362                                         imsg->cm_format_type = FMT_RFC822;
3363                                         imsg->cm_fields['U'] = strdup("QMSG");
3364                                         imsg->cm_fields['A'] = strdup("Citadel");
3365                                         imsg->cm_fields['J'] = strdup("do not journal");
3366                                         imsg->cm_fields['M'] = instr;   /* imsg owns this memory now */
3367                                         imsg->cm_fields['2'] = strdup(recipient);
3368                                         CtdlSubmitMsg(imsg, NULL, FNBL_QUEUE_ROOM, 0);
3369                                         CtdlFreeMessage(imsg);
3370                                 }
3371                         }
3372                         else {
3373                                 MSG_syslog(LOG_DEBUG, "No user <%s>\n", recipient);
3374                                 CtdlSaveMsgPointerInRoom(config.c_aideroom, newmsgid, 0, msg);
3375                         }
3376                 }
3377
3378         /* Perform "after save" hooks */
3379         MSGM_syslog(LOG_DEBUG, "Performing after-save hooks\n");
3380         if (msg->cm_fields['3'] != NULL) free(msg->cm_fields['3']);
3381         msg->cm_fields['3'] = malloc(20);
3382         snprintf(msg->cm_fields['3'], 20, "%ld", newmsgid);
3383         PerformMessageHooks(msg, EVT_AFTERSAVE);
3384         free(msg->cm_fields['3']);
3385         msg->cm_fields['3'] = NULL;
3386
3387         /* For IGnet mail, we have to save a new copy into the spooler for
3388          * each recipient, with the R and D fields set to the recipient and
3389          * destination-node.  This has two ugly side effects: all other
3390          * recipients end up being unlisted in this recipient's copy of the
3391          * message, and it has to deliver multiple messages to the same
3392          * node.  We'll revisit this again in a year or so when everyone has
3393          * a network spool receiver that can handle the new style messages.
3394          */
3395         if ((recps != NULL) && (recps->num_ignet > 0))
3396                 for (i=0; i<num_tokens(recps->recp_ignet, '|'); ++i) {
3397                         extract_token(recipient, recps->recp_ignet, i,
3398                                       '|', sizeof recipient);
3399
3400                         hold_R = msg->cm_fields['R'];
3401                         hold_D = msg->cm_fields['D'];
3402                         msg->cm_fields['R'] = malloc(SIZ);
3403                         msg->cm_fields['D'] = malloc(128);
3404                         extract_token(msg->cm_fields['R'], recipient, 0, '@', SIZ);
3405                         extract_token(msg->cm_fields['D'], recipient, 1, '@', 128);
3406                 
3407                         serialize_message(&smr, msg);
3408                         if (smr.len > 0) {
3409                                 snprintf(submit_filename, sizeof submit_filename,
3410                                          "%s/netmail.%04lx.%04x.%04x",
3411                                          ctdl_netin_dir,
3412                                          (long) getpid(), CCC->cs_pid, ++seqnum);
3413                                 network_fp = fopen(submit_filename, "wb+");
3414                                 if (network_fp != NULL) {
3415                                         rv = fwrite(smr.ser, smr.len, 1, network_fp);
3416                                         if (rv == -1) {
3417                                                 MSG_syslog(LOG_EMERG, "CtdlSubmitMsg(): Couldn't write network spool file: %s\n",
3418                                                            strerror(errno));
3419                                         }
3420                                         fclose(network_fp);
3421                                 }
3422                                 free(smr.ser);
3423                         }
3424
3425                         free(msg->cm_fields['R']);
3426                         free(msg->cm_fields['D']);
3427                         msg->cm_fields['R'] = hold_R;
3428                         msg->cm_fields['D'] = hold_D;
3429                 }
3430
3431         /* Go back to the room we started from */
3432         MSG_syslog(LOG_DEBUG, "Returning to original room %s\n", hold_rm);
3433         if (strcasecmp(hold_rm, CCC->room.QRname))
3434                 CtdlUserGoto(hold_rm, 0, 1, NULL, NULL);
3435
3436         /* For internet mail, generate delivery instructions.
3437          * Yes, this is recursive.  Deal with it.  Infinite recursion does
3438          * not happen because the delivery instructions message does not
3439          * contain a recipient.
3440          */
3441         if ((recps != NULL) && (recps->num_internet > 0)) {
3442                 StrBuf *SpoolMsg = NewStrBuf();
3443                 long nTokens;
3444
3445                 MSGM_syslog(LOG_DEBUG, "Generating delivery instructions\n");
3446
3447                 StrBufPrintf(SpoolMsg,
3448                              "Content-type: "SPOOLMIME"\n"
3449                              "\n"
3450                              "msgid|%ld\n"
3451                              "submitted|%ld\n"
3452                              "bounceto|%s\n",
3453                              newmsgid,
3454                              (long)time(NULL),
3455                              bounce_to);
3456
3457                 if (recps->envelope_from != NULL) {
3458                         StrBufAppendBufPlain(SpoolMsg, HKEY("envelope_from|"), 0);
3459                         StrBufAppendBufPlain(SpoolMsg, recps->envelope_from, -1, 0);
3460                         StrBufAppendBufPlain(SpoolMsg, HKEY("\n"), 0);
3461                 }
3462                 if (recps->sending_room != NULL) {
3463                         StrBufAppendBufPlain(SpoolMsg, HKEY("source_room|"), 0);
3464                         StrBufAppendBufPlain(SpoolMsg, recps->sending_room, -1, 0);
3465                         StrBufAppendBufPlain(SpoolMsg, HKEY("\n"), 0);
3466                 }
3467
3468                 nTokens = num_tokens(recps->recp_internet, '|');
3469                 for (i = 0; i < nTokens; i++) {
3470                         long len;
3471                         len = extract_token(recipient, recps->recp_internet, i, '|', sizeof recipient);
3472                         if (len > 0) {
3473                                 StrBufAppendBufPlain(SpoolMsg, HKEY("remote|"), 0);
3474                                 StrBufAppendBufPlain(SpoolMsg, recipient, len, 0);
3475                                 StrBufAppendBufPlain(SpoolMsg, HKEY("|0||\n"), 0);
3476                         }
3477                 }
3478
3479                 imsg = malloc(sizeof(struct CtdlMessage));
3480                 memset(imsg, 0, sizeof(struct CtdlMessage));
3481                 imsg->cm_magic = CTDLMESSAGE_MAGIC;
3482                 imsg->cm_anon_type = MES_NORMAL;
3483                 imsg->cm_format_type = FMT_RFC822;
3484                 imsg->cm_fields['U'] = strdup("QMSG");
3485                 imsg->cm_fields['A'] = strdup("Citadel");
3486                 imsg->cm_fields['J'] = strdup("do not journal");
3487                 imsg->cm_fields['M'] = SmashStrBuf(&SpoolMsg);  /* imsg owns this memory now */
3488                 CtdlSubmitMsg(imsg, NULL, SMTP_SPOOLOUT_ROOM, QP_EADDR);
3489                 CtdlFreeMessage(imsg);
3490         }
3491
3492         /*
3493          * Any addresses to harvest for someone's address book?
3494          */
3495         if ( (CCC->logged_in) && (recps != NULL) ) {
3496                 collected_addresses = harvest_collected_addresses(msg);
3497         }
3498
3499         if (collected_addresses != NULL) {
3500                 aptr = (struct addresses_to_be_filed *)
3501                         malloc(sizeof(struct addresses_to_be_filed));
3502                 CtdlMailboxName(actual_rm, sizeof actual_rm,
3503                                 &CCC->user, USERCONTACTSROOM);
3504                 aptr->roomname = strdup(actual_rm);
3505                 aptr->collected_addresses = collected_addresses;
3506                 begin_critical_section(S_ATBF);
3507                 aptr->next = atbf;
3508                 atbf = aptr;
3509                 end_critical_section(S_ATBF);
3510         }
3511
3512         /*
3513          * Determine whether this message qualifies for journaling.
3514          */
3515         if (msg->cm_fields['J'] != NULL) {
3516                 qualified_for_journaling = 0;
3517         }
3518         else {
3519                 if (recps == NULL) {
3520                         qualified_for_journaling = config.c_journal_pubmsgs;
3521                 }
3522                 else if (recps->num_local + recps->num_ignet + recps->num_internet > 0) {
3523                         qualified_for_journaling = config.c_journal_email;
3524                 }
3525                 else {
3526                         qualified_for_journaling = config.c_journal_pubmsgs;
3527                 }
3528         }
3529
3530         /*
3531          * Do we have to perform journaling?  If so, hand off the saved
3532          * RFC822 version will be handed off to the journaler for background
3533          * submit.  Otherwise, we have to free the memory ourselves.
3534          */
3535         if (saved_rfc822_version != NULL) {
3536                 if (qualified_for_journaling) {
3537                         JournalBackgroundSubmit(msg, saved_rfc822_version, recps);
3538                 }
3539                 else {
3540                         FreeStrBuf(&saved_rfc822_version);
3541                 }
3542         }
3543
3544         /* Done. */
3545         return(newmsgid);
3546 }
3547
3548
3549 /*
3550  * Convenience function for generating small administrative messages.
3551  */
3552 void quickie_message(const char *from,
3553                      const char *fromaddr,
3554                      const char *to,
3555                      char *room,
3556                      const char *text, 
3557                      int format_type,
3558                      const char *subject)
3559 {
3560         struct CtdlMessage *msg;
3561         struct recptypes *recp = NULL;
3562
3563         msg = malloc(sizeof(struct CtdlMessage));
3564         memset(msg, 0, sizeof(struct CtdlMessage));
3565         msg->cm_magic = CTDLMESSAGE_MAGIC;
3566         msg->cm_anon_type = MES_NORMAL;
3567         msg->cm_format_type = format_type;
3568
3569         if (from != NULL) {
3570                 msg->cm_fields['A'] = strdup(from);
3571         }
3572         else if (fromaddr != NULL) {
3573                 msg->cm_fields['A'] = strdup(fromaddr);
3574                 if (strchr(msg->cm_fields['A'], '@')) {
3575                         *strchr(msg->cm_fields['A'], '@') = 0;
3576                 }
3577         }
3578         else {
3579                 msg->cm_fields['A'] = strdup("Citadel");
3580         }
3581
3582         if (fromaddr != NULL) msg->cm_fields['F'] = strdup(fromaddr);
3583         if (room != NULL) msg->cm_fields['O'] = strdup(room);
3584         msg->cm_fields['N'] = strdup(NODENAME);
3585         if (to != NULL) {
3586                 msg->cm_fields['R'] = strdup(to);
3587                 recp = validate_recipients(to, NULL, 0);
3588         }
3589         if (subject != NULL) {
3590                 msg->cm_fields['U'] = strdup(subject);
3591         }
3592         msg->cm_fields['M'] = strdup(text);
3593
3594         CtdlSubmitMsg(msg, recp, room, 0);
3595         CtdlFreeMessage(msg);
3596         if (recp != NULL) free_recipients(recp);
3597 }
3598
3599 void flood_protect_quickie_message(const char *from,
3600                                    const char *fromaddr,
3601                                    const char *to,
3602                                    char *room,
3603                                    const char *text, 
3604                                    int format_type,
3605                                    const char *subject,
3606                                    int nCriterions,
3607                                    const char **CritStr,
3608                                    long *CritStrLen)
3609 {
3610         int i;
3611         struct UseTable ut;
3612         u_char rawdigest[MD5_DIGEST_LEN];
3613         struct MD5Context md5context;
3614         StrBuf *guid;
3615         struct cdbdata *cdbut;
3616         char timestamp[64];
3617         long tslen;
3618         time_t ts = time(NULL);
3619         time_t tsday = ts / (8*60*60); /* just care for a day... */
3620
3621         tslen = snprintf(timestamp, sizeof(timestamp), "%ld", tsday);
3622         MD5Init(&md5context);
3623
3624         for (i = 0; i < nCriterions; i++)
3625                 MD5Update(&md5context,
3626                           (const unsigned char*)CritStr[i], CritStrLen[i]);
3627         MD5Update(&md5context,
3628                   (const unsigned char*)timestamp, tslen);
3629         MD5Final(rawdigest, &md5context);
3630
3631         guid = NewStrBufPlain(NULL,
3632                               MD5_DIGEST_LEN * 2 + 12);
3633         StrBufHexEscAppend(guid, NULL, rawdigest, MD5_DIGEST_LEN);
3634         StrBufAppendBufPlain(guid, HKEY("_fldpt"), 0);
3635         if (StrLength(guid) > 40)
3636                 StrBufCutAt(guid, 40, NULL);
3637         /* Find out if we've already sent a similar message */
3638         memcpy(ut.ut_msgid, SKEY(guid));
3639         ut.ut_timestamp = ts;
3640
3641         cdbut = cdb_fetch(CDB_USETABLE, SKEY(guid));
3642
3643         if (cdbut != NULL) {
3644                 /* yes, we did. flood protection kicks in. */
3645                 syslog(LOG_DEBUG,
3646                        "not sending message again\n");
3647                 cdb_free(cdbut);
3648         }
3649
3650         /* rewrite the record anyway, to update the timestamp */
3651         cdb_store(CDB_USETABLE,
3652                   SKEY(guid),
3653                   &ut, sizeof(struct UseTable) );
3654         
3655         FreeStrBuf(&guid);
3656
3657         if (cdbut != NULL) return;
3658         /* no, this message isn't sent recently; go ahead. */
3659         quickie_message(from,
3660                         fromaddr,
3661                         to,
3662                         room,
3663                         text, 
3664                         format_type,
3665                         subject);
3666 }
3667
3668
3669 /*
3670  * Back end function used by CtdlMakeMessage() and similar functions
3671  */
3672 StrBuf *CtdlReadMessageBodyBuf(char *terminator,        /* token signalling EOT */
3673                                long tlen,
3674                                size_t maxlen,           /* maximum message length */
3675                                StrBuf *exist,           /* if non-null, append to it;
3676                                                            exist is ALWAYS freed  */
3677                                int crlf,                /* CRLF newlines instead of LF */
3678                                int *sock                /* socket handle or 0 for this session's client socket */
3679         ) 
3680 {
3681         StrBuf *Message;
3682         StrBuf *LineBuf;
3683         int flushing = 0;
3684         int finished = 0;
3685         int dotdot = 0;
3686
3687         LineBuf = NewStrBufPlain(NULL, SIZ);
3688         if (exist == NULL) {
3689                 Message = NewStrBufPlain(NULL, 4 * SIZ);
3690         }
3691         else {
3692                 Message = NewStrBufDup(exist);
3693         }
3694
3695         /* Do we need to change leading ".." to "." for SMTP escaping? */
3696         if ((tlen == 1) && (*terminator == '.')) {
3697                 dotdot = 1;
3698         }
3699
3700         /* read in the lines of message text one by one */
3701         do {
3702                 if (sock != NULL) {
3703                         if ((CtdlSockGetLine(sock, LineBuf, 5) < 0) ||
3704                             (*sock == -1))
3705                                 finished = 1;
3706                 }
3707                 else {
3708                         if (CtdlClientGetLine(LineBuf) < 0) finished = 1;
3709                 }
3710                 if ((StrLength(LineBuf) == tlen) && 
3711                     (!strcmp(ChrPtr(LineBuf), terminator)))
3712                         finished = 1;
3713
3714                 if ( (!flushing) && (!finished) ) {
3715                         if (crlf) {
3716                                 StrBufAppendBufPlain(LineBuf, HKEY("\r\n"), 0);
3717                         }
3718                         else {
3719                                 StrBufAppendBufPlain(LineBuf, HKEY("\n"), 0);
3720                         }
3721                         
3722                         /* Unescape SMTP-style input of two dots at the beginning of the line */
3723                         if ((dotdot) &&
3724                             (StrLength(LineBuf) == 2) && 
3725                             (!strcmp(ChrPtr(LineBuf), "..")))
3726                         {
3727                                 StrBufCutLeft(LineBuf, 1);
3728                         }
3729                         
3730                         StrBufAppendBuf(Message, LineBuf, 0);
3731                 }
3732
3733                 /* if we've hit the max msg length, flush the rest */
3734                 if (StrLength(Message) >= maxlen) flushing = 1;
3735
3736         } while (!finished);
3737         FreeStrBuf(&LineBuf);
3738         return Message;
3739 }
3740
3741 void DeleteAsyncMsg(ReadAsyncMsg **Msg)
3742 {
3743         if (*Msg == NULL)
3744                 return;
3745         FreeStrBuf(&(*Msg)->MsgBuf);
3746
3747         free(*Msg);
3748         *Msg = NULL;
3749 }
3750
3751 ReadAsyncMsg *NewAsyncMsg(const char *terminator,       /* token signalling EOT */
3752                           long tlen,
3753                           size_t maxlen,                /* maximum message length */
3754                           size_t expectlen,             /* if we expect a message, how long should it be? */
3755                           StrBuf *exist,                /* if non-null, append to it;
3756                                                            exist is ALWAYS freed  */
3757                           long eLen,                    /* length of exist */
3758                           int crlf                      /* CRLF newlines instead of LF */
3759         )
3760 {
3761         ReadAsyncMsg *NewMsg;
3762
3763         NewMsg = (ReadAsyncMsg *)malloc(sizeof(ReadAsyncMsg));
3764         memset(NewMsg, 0, sizeof(ReadAsyncMsg));
3765
3766         if (exist == NULL) {
3767                 long len;
3768
3769                 if (expectlen == 0) {
3770                         len = 4 * SIZ;
3771                 }
3772                 else {
3773                         len = expectlen + 10;
3774                 }
3775                 NewMsg->MsgBuf = NewStrBufPlain(NULL, len);
3776         }
3777         else {
3778                 NewMsg->MsgBuf = NewStrBufDup(exist);
3779         }
3780         /* Do we need to change leading ".." to "." for SMTP escaping? */
3781         if ((tlen == 1) && (*terminator == '.')) {
3782                 NewMsg->dodot = 1;
3783         }
3784
3785         NewMsg->terminator = terminator;
3786         NewMsg->tlen = tlen;
3787
3788         NewMsg->maxlen = maxlen;
3789
3790         NewMsg->crlf = crlf;
3791
3792         return NewMsg;
3793 }
3794
3795 /*
3796  * Back end function used by CtdlMakeMessage() and similar functions
3797  */
3798 eReadState CtdlReadMessageBodyAsync(AsyncIO *IO)
3799 {
3800         ReadAsyncMsg *ReadMsg;
3801         int MsgFinished = 0;
3802         eReadState Finished = eMustReadMore;
3803
3804 #ifdef BIGBAD_IODBG
3805         char fn [SIZ];
3806         FILE *fd;
3807         const char *pch = ChrPtr(IO->SendBuf.Buf);
3808         const char *pchh = IO->SendBuf.ReadWritePointer;
3809         long nbytes;
3810         
3811         if (pchh == NULL)
3812                 pchh = pch;
3813         
3814         nbytes = StrLength(IO->SendBuf.Buf) - (pchh - pch);
3815         snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
3816                  ((CitContext*)(IO->CitContext))->ServiceName,
3817                  IO->SendBuf.fd);
3818         
3819         fd = fopen(fn, "a+");
3820 #endif
3821
3822         ReadMsg = IO->ReadMsg;
3823
3824         /* read in the lines of message text one by one */
3825         do {
3826                 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
3827                 
3828                 switch (Finished) {
3829                 case eMustReadMore: /// read new from socket... 
3830 #ifdef BIGBAD_IODBG
3831                         if (IO->RecvBuf.ReadWritePointer != NULL) {
3832                                 nbytes = StrLength(IO->RecvBuf.Buf) - (IO->RecvBuf.ReadWritePointer - ChrPtr(IO->RecvBuf.Buf));
3833                                 fprintf(fd, "Read; Line unfinished: %ld Bytes still in buffer [", nbytes);
3834                                 
3835                                 fwrite(IO->RecvBuf.ReadWritePointer, nbytes, 1, fd);
3836                         
3837                                 fprintf(fd, "]\n");
3838                         } else {
3839                                 fprintf(fd, "BufferEmpty! \n");
3840                         }
3841                         fclose(fd);
3842 #endif
3843                         return Finished;
3844                     break;
3845                 case eBufferNotEmpty: /* shouldn't happen... */
3846                 case eReadSuccess: /// done for now...
3847                     break;
3848                 case eReadFail: /// WHUT?
3849                     ///todo: shut down! 
3850                         break;
3851                 }
3852             
3853
3854                 if ((StrLength(IO->IOBuf) == ReadMsg->tlen) && 
3855                     (!strcmp(ChrPtr(IO->IOBuf), ReadMsg->terminator))) {
3856                         MsgFinished = 1;
3857 #ifdef BIGBAD_IODBG
3858                         fprintf(fd, "found Terminator; Message Size: %d\n", StrLength(ReadMsg->MsgBuf));
3859 #endif
3860                 }
3861                 else if (!ReadMsg->flushing) {
3862
3863 #ifdef BIGBAD_IODBG
3864                         fprintf(fd, "Read Line: [%d][%s]\n", StrLength(IO->IOBuf), ChrPtr(IO->IOBuf));
3865 #endif
3866
3867                         /* Unescape SMTP-style input of two dots at the beginning of the line */
3868                         if ((ReadMsg->dodot) &&
3869                             (StrLength(IO->IOBuf) == 2) &&  /* TODO: do we just unescape lines with two dots or any line? */
3870                             (!strcmp(ChrPtr(IO->IOBuf), "..")))
3871                         {
3872 #ifdef BIGBAD_IODBG
3873                                 fprintf(fd, "UnEscaped!\n");
3874 #endif
3875                                 StrBufCutLeft(IO->IOBuf, 1);
3876                         }
3877
3878                         if (ReadMsg->crlf) {
3879                                 StrBufAppendBufPlain(IO->IOBuf, HKEY("\r\n"), 0);
3880                         }
3881                         else {
3882                                 StrBufAppendBufPlain(IO->IOBuf, HKEY("\n"), 0);
3883                         }
3884
3885                         StrBufAppendBuf(ReadMsg->MsgBuf, IO->IOBuf, 0);
3886                 }
3887
3888                 /* if we've hit the max msg length, flush the rest */
3889                 if (StrLength(ReadMsg->MsgBuf) >= ReadMsg->maxlen) ReadMsg->flushing = 1;
3890
3891         } while (!MsgFinished);
3892
3893 #ifdef BIGBAD_IODBG
3894         fprintf(fd, "Done with reading; %s.\n, ",
3895                 (MsgFinished)?"Message Finished": "FAILED");
3896         fclose(fd);
3897 #endif
3898         if (MsgFinished)
3899                 return eReadSuccess;
3900         else 
3901                 return eAbort;
3902 }
3903
3904
3905 /*
3906  * Back end function used by CtdlMakeMessage() and similar functions
3907  */
3908 char *CtdlReadMessageBody(char *terminator,     /* token signalling EOT */
3909                           long tlen,
3910                           size_t maxlen,                /* maximum message length */
3911                           StrBuf *exist,                /* if non-null, append to it;
3912                                                    exist is ALWAYS freed  */
3913                           int crlf,             /* CRLF newlines instead of LF */
3914                           int *sock             /* socket handle or 0 for this session's client socket */
3915         ) 
3916 {
3917         StrBuf *Message;
3918
3919         Message = CtdlReadMessageBodyBuf(terminator,
3920                                          tlen,
3921                                          maxlen,
3922                                          exist,
3923                                          crlf,
3924                                          sock);
3925         if (Message == NULL)
3926                 return NULL;
3927         else
3928                 return SmashStrBuf(&Message);
3929 }
3930
3931
3932 /*
3933  * Build a binary message to be saved on disk.
3934  * (NOTE: if you supply 'preformatted_text', the buffer you give it
3935  * will become part of the message.  This means you are no longer
3936  * responsible for managing that memory -- it will be freed along with
3937  * the rest of the fields when CtdlFreeMessage() is called.)
3938  */
3939
3940 struct CtdlMessage *CtdlMakeMessage(
3941         struct ctdluser *author,        /* author's user structure */
3942         char *recipient,                /* NULL if it's not mail */
3943         char *recp_cc,                  /* NULL if it's not mail */
3944         char *room,                     /* room where it's going */
3945         int type,                       /* see MES_ types in header file */
3946         int format_type,                /* variformat, plain text, MIME... */
3947         char *fake_name,                /* who we're masquerading as */
3948         char *my_email,                 /* which of my email addresses to use (empty is ok) */
3949         char *subject,                  /* Subject (optional) */
3950         char *supplied_euid,            /* ...or NULL if this is irrelevant */
3951         char *preformatted_text,        /* ...or NULL to read text from client */
3952         char *references                /* Thread references */
3953         ) {
3954         char dest_node[256];
3955         char buf[1024];
3956         struct CtdlMessage *msg;
3957         StrBuf *FakeAuthor;
3958         StrBuf *FakeEncAuthor = NULL;
3959
3960         msg = malloc(sizeof(struct CtdlMessage));
3961         memset(msg, 0, sizeof(struct CtdlMessage));
3962         msg->cm_magic = CTDLMESSAGE_MAGIC;
3963         msg->cm_anon_type = type;
3964         msg->cm_format_type = format_type;
3965
3966         /* Don't confuse the poor folks if it's not routed mail. */
3967         strcpy(dest_node, "");
3968
3969         if (recipient != NULL) striplt(recipient);
3970         if (recp_cc != NULL) striplt(recp_cc);
3971
3972         /* Path or Return-Path */
3973         if (my_email == NULL) my_email = "";
3974
3975         if (!IsEmptyStr(my_email)) {
3976                 msg->cm_fields['P'] = strdup(my_email);
3977         }
3978         else {
3979                 snprintf(buf, sizeof buf, "%s", author->fullname);
3980                 msg->cm_fields['P'] = strdup(buf);
3981         }
3982         convert_spaces_to_underscores(msg->cm_fields['P']);
3983
3984         snprintf(buf, sizeof buf, "%ld", (long)time(NULL));     /* timestamp */
3985         msg->cm_fields['T'] = strdup(buf);
3986
3987         if ((fake_name != NULL) && (fake_name[0])) {            /* author */
3988                 FakeAuthor = NewStrBufPlain (fake_name, -1);
3989         }
3990         else {
3991                 FakeAuthor = NewStrBufPlain (author->fullname, -1);
3992         }
3993         StrBufRFC2047encode(&FakeEncAuthor, FakeAuthor);
3994         msg->cm_fields['A'] = SmashStrBuf(&FakeEncAuthor);
3995         FreeStrBuf(&FakeAuthor);
3996
3997         if (CC->room.QRflags & QR_MAILBOX) {            /* room */
3998                 msg->cm_fields['O'] = strdup(&CC->room.QRname[11]);
3999         }
4000         else {
4001                 msg->cm_fields['O'] = strdup(CC->room.QRname);
4002         }
4003
4004         msg->cm_fields['N'] = strdup(NODENAME);         /* nodename */
4005         msg->cm_fields['H'] = strdup(HUMANNODE);                /* hnodename */
4006
4007         if ((recipient != NULL) && (recipient[0] != 0)) {
4008                 msg->cm_fields['R'] = strdup(recipient);
4009         }
4010         if ((recp_cc != NULL) && (recp_cc[0] != 0)) {
4011                 msg->cm_fields['Y'] = strdup(recp_cc);
4012         }
4013         if (dest_node[0] != 0) {
4014                 msg->cm_fields['D'] = strdup(dest_node);
4015         }
4016
4017         if (!IsEmptyStr(my_email)) {
4018                 msg->cm_fields['F'] = strdup(my_email);
4019         }
4020         else if ( (author == &CC->user) && (!IsEmptyStr(CC->cs_inet_email)) ) {
4021                 msg->cm_fields['F'] = strdup(CC->cs_inet_email);
4022         }
4023
4024         if (subject != NULL) {
4025                 long length;
4026                 striplt(subject);
4027                 length = strlen(subject);
4028                 if (length > 0) {
4029                         long i;
4030                         long IsAscii;
4031                         IsAscii = -1;
4032                         i = 0;
4033                         while ((subject[i] != '\0') &&
4034                                (IsAscii = isascii(subject[i]) != 0 ))
4035                                 i++;
4036                         if (IsAscii != 0)
4037                                 msg->cm_fields['U'] = strdup(subject);
4038                         else /* ok, we've got utf8 in the string. */
4039                         {
4040                                 msg->cm_fields['U'] = rfc2047encode(subject, length);
4041                         }
4042
4043                 }
4044         }
4045
4046         if (supplied_euid != NULL) {
4047                 msg->cm_fields['E'] = strdup(supplied_euid);
4048         }
4049
4050         if ((references != NULL) && (!IsEmptyStr(references))) {
4051                 if (msg->cm_fields['W'] != NULL)
4052                         free(msg->cm_fields['W']);
4053                 msg->cm_fields['W'] = strdup(references);
4054         }
4055
4056         if (preformatted_text != NULL) {
4057                 msg->cm_fields['M'] = preformatted_text;
4058         }
4059         else {
4060                 msg->cm_fields['M'] = CtdlReadMessageBody(HKEY("000"), config.c_maxmsglen, NULL, 0, 0);
4061         }
4062
4063         return(msg);
4064 }
4065
4066 /*
4067  * Check to see whether we have permission to post a message in the current
4068  * room.  Returns a *CITADEL ERROR CODE* and puts a message in errmsgbuf, or
4069  * returns 0 on success.
4070  */
4071 int CtdlDoIHavePermissionToPostInThisRoom(
4072         char *errmsgbuf, 
4073         size_t n, 
4074         const char* RemoteIdentifier,
4075         int PostPublic,
4076         int is_reply
4077         ) {
4078         int ra;
4079
4080         if (!(CC->logged_in) && 
4081             (PostPublic == POST_LOGGED_IN)) {
4082                 snprintf(errmsgbuf, n, "Not logged in.");
4083                 return (ERROR + NOT_LOGGED_IN);
4084         }
4085         else if (PostPublic == CHECK_EXISTANCE) {
4086                 return (0); // We're Evaling whether a recipient exists
4087         }
4088         else if (!(CC->logged_in)) {
4089                 
4090                 if ((CC->room.QRflags & QR_READONLY)) {
4091                         snprintf(errmsgbuf, n, "Not logged in.");
4092                         return (ERROR + NOT_LOGGED_IN);
4093                 }
4094                 if (CC->room.QRflags2 & QR2_MODERATED) {
4095                         snprintf(errmsgbuf, n, "Not logged in Moderation feature not yet implemented!");
4096                         return (ERROR + NOT_LOGGED_IN);
4097                 }
4098                 if ((PostPublic!=POST_LMTP) &&(CC->room.QRflags2 & QR2_SMTP_PUBLIC) == 0) {
4099
4100                         return CtdlNetconfigCheckRoomaccess(errmsgbuf, n, RemoteIdentifier);
4101                 }
4102                 return (0);
4103
4104         }
4105
4106         if ((CC->user.axlevel < AxProbU)
4107             && ((CC->room.QRflags & QR_MAILBOX) == 0)) {
4108                 snprintf(errmsgbuf, n, "Need to be validated to enter (except in %s> to sysop)", MAILROOM);
4109                 return (ERROR + HIGHER_ACCESS_REQUIRED);
4110         }
4111
4112         CtdlRoomAccess(&CC->room, &CC->user, &ra, NULL);
4113
4114         if (ra & UA_POSTALLOWED) {
4115                 strcpy(errmsgbuf, "OK to post or reply here");
4116                 return(0);
4117         }
4118
4119         if ( (ra & UA_REPLYALLOWED) && (is_reply) ) {
4120                 /*
4121                  * To be thorough, we ought to check to see if the message they are
4122                  * replying to is actually a valid one in this room, but unless this
4123                  * actually becomes a problem we'll go with high performance instead.
4124                  */
4125                 strcpy(errmsgbuf, "OK to reply here");
4126                 return(0);
4127         }
4128
4129         if ( (ra & UA_REPLYALLOWED) && (!is_reply) ) {
4130                 /* Clarify what happened with a better error message */
4131                 snprintf(errmsgbuf, n, "You may only reply to existing messages here.");
4132                 return (ERROR + HIGHER_ACCESS_REQUIRED);
4133         }
4134
4135         snprintf(errmsgbuf, n, "Higher access is required to post in this room.");
4136         return (ERROR + HIGHER_ACCESS_REQUIRED);
4137
4138 }
4139
4140
4141 /*
4142  * Check to see if the specified user has Internet mail permission
4143  * (returns nonzero if permission is granted)
4144  */
4145 int CtdlCheckInternetMailPermission(struct ctdluser *who) {
4146
4147         /* Do not allow twits to send Internet mail */
4148         if (who->axlevel <= AxProbU) return(0);
4149
4150         /* Globally enabled? */
4151         if (config.c_restrict == 0) return(1);
4152
4153         /* User flagged ok? */
4154         if (who->flags & US_INTERNET) return(2);
4155
4156         /* Admin level access? */
4157         if (who->axlevel >= AxAideU) return(3);
4158
4159         /* No mail for you! */
4160         return(0);
4161 }
4162
4163
4164 /*
4165  * Validate recipients, count delivery types and errors, and handle aliasing
4166  * FIXME check for dupes!!!!!
4167  *
4168  * Returns 0 if all addresses are ok, ret->num_error = -1 if no addresses 
4169  * were specified, or the number of addresses found invalid.
4170  *
4171  * Caller needs to free the result using free_recipients()
4172  */
4173 struct recptypes *validate_recipients(const char *supplied_recipients, 
4174                                       const char *RemoteIdentifier, 
4175                                       int Flags) {
4176         struct CitContext *CCC = CC;
4177         struct recptypes *ret;
4178         char *recipients = NULL;
4179         char *org_recp;
4180         char this_recp[256];
4181         char this_recp_cooked[256];
4182         char append[SIZ];
4183         long len;
4184         int num_recps = 0;
4185         int i, j;
4186         int mailtype;
4187         int invalid;
4188         struct ctdluser tempUS;
4189         struct ctdlroom tempQR;
4190         struct ctdlroom tempQR2;
4191         int err = 0;
4192         char errmsg[SIZ];
4193         int in_quotes = 0;
4194
4195         /* Initialize */
4196         ret = (struct recptypes *) malloc(sizeof(struct recptypes));
4197         if (ret == NULL) return(NULL);
4198
4199         /* Set all strings to null and numeric values to zero */
4200         memset(ret, 0, sizeof(struct recptypes));
4201
4202         if (supplied_recipients == NULL) {
4203                 recipients = strdup("");
4204         }
4205         else {
4206                 recipients = strdup(supplied_recipients);
4207         }
4208
4209         /* Allocate some memory.  Yes, this allocates 500% more memory than we will
4210          * actually need, but it's healthier for the heap than doing lots of tiny
4211          * realloc() calls instead.
4212          */
4213         len = strlen(recipients) + 1024;
4214         ret->errormsg = malloc(len);
4215         ret->recp_local = malloc(len);
4216         ret->recp_internet = malloc(len);
4217         ret->recp_ignet = malloc(len);
4218         ret->recp_room = malloc(len);
4219         ret->display_recp = malloc(len);
4220         ret->recp_orgroom = malloc(len);
4221         org_recp = malloc(len);
4222
4223         ret->errormsg[0] = 0;
4224         ret->recp_local[0] = 0;
4225         ret->recp_internet[0] = 0;
4226         ret->recp_ignet[0] = 0;
4227         ret->recp_room[0] = 0;
4228         ret->recp_orgroom[0] = 0;
4229         ret->display_recp[0] = 0;
4230
4231         ret->recptypes_magic = RECPTYPES_MAGIC;
4232
4233         /* Change all valid separator characters to commas */
4234         for (i=0; !IsEmptyStr(&recipients[i]); ++i) {
4235                 if ((recipients[i] == ';') || (recipients[i] == '|')) {
4236                         recipients[i] = ',';
4237                 }
4238         }
4239
4240         /* Now start extracting recipients... */
4241
4242         while (!IsEmptyStr(recipients)) {
4243                 for (i=0; i<=strlen(recipients); ++i) {
4244                         if (recipients[i] == '\"') in_quotes = 1 - in_quotes;
4245                         if ( ( (recipients[i] == ',') && (!in_quotes) ) || (recipients[i] == 0) ) {
4246                                 safestrncpy(this_recp, recipients, i+1);
4247                                 this_recp[i] = 0;
4248                                 if (recipients[i] == ',') {
4249                                         strcpy(recipients, &recipients[i+1]);
4250                                 }
4251                                 else {
4252                                         strcpy(recipients, "");
4253                                 }
4254                                 break;
4255                         }
4256                 }
4257
4258                 striplt(this_recp);
4259                 if (IsEmptyStr(this_recp))
4260                         break;
4261                 MSG_syslog(LOG_DEBUG, "Evaluating recipient #%d: %s\n", num_recps, this_recp);
4262                 ++num_recps;
4263
4264                 strcpy(org_recp, this_recp);
4265                 alias(this_recp);
4266                 alias(this_recp);
4267                 mailtype = alias(this_recp);
4268
4269                 for (j = 0; !IsEmptyStr(&this_recp[j]); ++j) {
4270                         if (this_recp[j]=='_') {
4271                                 this_recp_cooked[j] = ' ';
4272                         }
4273                         else {
4274                                 this_recp_cooked[j] = this_recp[j];
4275                         }
4276                 }
4277                 this_recp_cooked[j] = '\0';
4278                 invalid = 0;
4279                 errmsg[0] = 0;
4280                 switch(mailtype) {
4281                 case MES_LOCAL:
4282                         if (!strcasecmp(this_recp, "sysop")) {
4283                                 ++ret->num_room;
4284                                 strcpy(this_recp, config.c_aideroom);
4285                                 if (!IsEmptyStr(ret->recp_room)) {
4286                                         strcat(ret->recp_room, "|");
4287                                 }
4288                                 strcat(ret->recp_room, this_recp);
4289                         }
4290                         else if ( (!strncasecmp(this_recp, "room_", 5))
4291                                   && (!CtdlGetRoom(&tempQR, &this_recp_cooked[5])) ) {
4292
4293                                 /* Save room so we can restore it later */
4294                                 tempQR2 = CCC->room;
4295                                 CCC->room = tempQR;
4296                                         
4297                                 /* Check permissions to send mail to this room */
4298                                 err = CtdlDoIHavePermissionToPostInThisRoom(
4299                                         errmsg, 
4300                                         sizeof errmsg, 
4301                                         RemoteIdentifier,
4302                                         Flags,
4303                                         0                       /* 0 = not a reply */
4304                                         );
4305                                 if (err)
4306                                 {
4307                                         ++ret->num_error;
4308                                         invalid = 1;
4309                                 } 
4310                                 else {
4311                                         ++ret->num_room;
4312                                         if (!IsEmptyStr(ret->recp_room)) {
4313                                                 strcat(ret->recp_room, "|");
4314                                         }
4315                                         strcat(ret->recp_room, &this_recp_cooked[5]);
4316
4317                                         if (!IsEmptyStr(ret->recp_orgroom)) {
4318                                                 strcat(ret->recp_orgroom, "|");
4319                                         }
4320                                         strcat(ret->recp_orgroom, org_recp);
4321
4322                                 }
4323                                         
4324                                 /* Restore room in case something needs it */
4325                                 CCC->room = tempQR2;
4326
4327                         }
4328                         else if (CtdlGetUser(&tempUS, this_recp) == 0) {
4329                                 ++ret->num_local;
4330                                 strcpy(this_recp, tempUS.fullname);
4331                                 if (!IsEmptyStr(ret->recp_local)) {
4332                                         strcat(ret->recp_local, "|");
4333                                 }
4334                                 strcat(ret->recp_local, this_recp);
4335                         }
4336                         else if (CtdlGetUser(&tempUS, this_recp_cooked) == 0) {
4337                                 ++ret->num_local;
4338                                 strcpy(this_recp, tempUS.fullname);
4339                                 if (!IsEmptyStr(ret->recp_local)) {
4340                                         strcat(ret->recp_local, "|");
4341                                 }
4342                                 strcat(ret->recp_local, this_recp);
4343                         }
4344                         else {
4345                                 ++ret->num_error;
4346                                 invalid = 1;
4347                         }
4348                         break;
4349                 case MES_INTERNET:
4350                         /* Yes, you're reading this correctly: if the target
4351                          * domain points back to the local system or an attached
4352                          * Citadel directory, the address is invalid.  That's
4353                          * because if the address were valid, we would have
4354                          * already translated it to a local address by now.
4355                          */
4356                         if (IsDirectory(this_recp, 0)) {
4357                                 ++ret->num_error;
4358                                 invalid = 1;
4359                         }
4360                         else {
4361                                 ++ret->num_internet;
4362                                 if (!IsEmptyStr(ret->recp_internet)) {
4363                                         strcat(ret->recp_internet, "|");
4364                                 }
4365                                 strcat(ret->recp_internet, this_recp);
4366                         }
4367                         break;
4368                 case MES_IGNET:
4369                         ++ret->num_ignet;
4370                         if (!IsEmptyStr(ret->recp_ignet)) {
4371                                 strcat(ret->recp_ignet, "|");
4372                         }
4373                         strcat(ret->recp_ignet, this_recp);
4374                         break;
4375                 case MES_ERROR:
4376                         ++ret->num_error;
4377                         invalid = 1;
4378                         break;
4379                 }
4380                 if (invalid) {
4381                         if (IsEmptyStr(errmsg)) {
4382                                 snprintf(append, sizeof append, "Invalid recipient: %s", this_recp);
4383                         }
4384                         else {
4385                                 snprintf(append, sizeof append, "%s", errmsg);
4386                         }
4387                         if ( (strlen(ret->errormsg) + strlen(append) + 3) < SIZ) {
4388                                 if (!IsEmptyStr(ret->errormsg)) {
4389                                         strcat(ret->errormsg, "; ");
4390                                 }
4391                                 strcat(ret->errormsg, append);
4392                         }
4393                 }
4394                 else {
4395                         if (IsEmptyStr(ret->display_recp)) {
4396                                 strcpy(append, this_recp);
4397                         }
4398                         else {
4399                                 snprintf(append, sizeof append, ", %s", this_recp);
4400                         }
4401                         if ( (strlen(ret->display_recp)+strlen(append)) < SIZ) {
4402                                 strcat(ret->display_recp, append);
4403                         }
4404                 }
4405         }
4406         free(org_recp);
4407
4408         if ((ret->num_local + ret->num_internet + ret->num_ignet +
4409              ret->num_room + ret->num_error) == 0) {
4410                 ret->num_error = (-1);
4411                 strcpy(ret->errormsg, "No recipients specified.");
4412         }
4413
4414         MSGM_syslog(LOG_DEBUG, "validate_recipients()\n");
4415         MSG_syslog(LOG_DEBUG, " local: %d <%s>\n", ret->num_local, ret->recp_local);
4416         MSG_syslog(LOG_DEBUG, "  room: %d <%s>\n", ret->num_room, ret->recp_room);
4417         MSG_syslog(LOG_DEBUG, "  inet: %d <%s>\n", ret->num_internet, ret->recp_internet);
4418         MSG_syslog(LOG_DEBUG, " ignet: %d <%s>\n", ret->num_ignet, ret->recp_ignet);
4419         MSG_syslog(LOG_DEBUG, " error: %d <%s>\n", ret->num_error, ret->errormsg);
4420
4421         free(recipients);
4422         return(ret);
4423 }
4424
4425
4426 /*
4427  * Destructor for struct recptypes
4428  */
4429 void free_recipients(struct recptypes *valid) {
4430
4431         if (valid == NULL) {
4432                 return;
4433         }
4434
4435         if (valid->recptypes_magic != RECPTYPES_MAGIC) {
4436                 struct CitContext *CCC = CC;
4437                 MSGM_syslog(LOG_EMERG, "Attempt to call free_recipients() on some other data type!\n");
4438                 abort();
4439         }
4440
4441         if (valid->errormsg != NULL)            free(valid->errormsg);
4442         if (valid->recp_local != NULL)          free(valid->recp_local);
4443         if (valid->recp_internet != NULL)       free(valid->recp_internet);
4444         if (valid->recp_ignet != NULL)          free(valid->recp_ignet);
4445         if (valid->recp_room != NULL)           free(valid->recp_room);
4446         if (valid->recp_orgroom != NULL)        free(valid->recp_orgroom);
4447         if (valid->display_recp != NULL)        free(valid->display_recp);
4448         if (valid->bounce_to != NULL)           free(valid->bounce_to);
4449         if (valid->envelope_from != NULL)       free(valid->envelope_from);
4450         if (valid->sending_room != NULL)        free(valid->sending_room);
4451         free(valid);
4452 }
4453
4454
4455
4456 /*
4457  * message entry  -  mode 0 (normal)
4458  */
4459 void cmd_ent0(char *entargs)
4460 {
4461         struct CitContext *CCC = CC;
4462         int post = 0;
4463         char recp[SIZ];
4464         char cc[SIZ];
4465         char bcc[SIZ];
4466         char supplied_euid[128];
4467         int anon_flag = 0;
4468         int format_type = 0;
4469         char newusername[256];
4470         char newuseremail[256];
4471         struct CtdlMessage *msg;
4472         int anonymous = 0;
4473         char errmsg[SIZ];
4474         int err = 0;
4475         struct recptypes *valid = NULL;
4476         struct recptypes *valid_to = NULL;
4477         struct recptypes *valid_cc = NULL;
4478         struct recptypes *valid_bcc = NULL;
4479         char subject[SIZ];
4480         int subject_required = 0;
4481         int do_confirm = 0;
4482         long msgnum;
4483         int i, j;
4484         char buf[256];
4485         int newuseremail_ok = 0;
4486         char references[SIZ];
4487         char *ptr;
4488
4489         unbuffer_output();
4490
4491         post = extract_int(entargs, 0);
4492         extract_token(recp, entargs, 1, '|', sizeof recp);
4493         anon_flag = extract_int(entargs, 2);
4494         format_type = extract_int(entargs, 3);
4495         extract_token(subject, entargs, 4, '|', sizeof subject);
4496         extract_token(newusername, entargs, 5, '|', sizeof newusername);
4497         do_confirm = extract_int(entargs, 6);
4498         extract_token(cc, entargs, 7, '|', sizeof cc);
4499         extract_token(bcc, entargs, 8, '|', sizeof bcc);
4500         switch(CC->room.QRdefaultview) {
4501         case VIEW_NOTES:
4502         case VIEW_WIKI:
4503                 extract_token(supplied_euid, entargs, 9, '|', sizeof supplied_euid);
4504                 break;
4505         default:
4506                 supplied_euid[0] = 0;
4507                 break;
4508         }
4509         extract_token(newuseremail, entargs, 10, '|', sizeof newuseremail);
4510         extract_token(references, entargs, 11, '|', sizeof references);
4511         for (ptr=references; *ptr != 0; ++ptr) {
4512                 if (*ptr == '!') *ptr = '|';
4513         }
4514
4515         /* first check to make sure the request is valid. */
4516
4517         err = CtdlDoIHavePermissionToPostInThisRoom(
4518                 errmsg,
4519                 sizeof errmsg,
4520                 NULL,
4521                 POST_LOGGED_IN,
4522                 (!IsEmptyStr(references))               /* is this a reply?  or a top-level post? */
4523                 );
4524         if (err)
4525         {
4526                 cprintf("%d %s\n", err, errmsg);
4527                 return;
4528         }
4529
4530         /* Check some other permission type things. */
4531
4532         if (IsEmptyStr(newusername)) {
4533                 strcpy(newusername, CCC->user.fullname);
4534         }
4535         if (  (CCC->user.axlevel < AxAideU)
4536               && (strcasecmp(newusername, CCC->user.fullname))
4537               && (strcasecmp(newusername, CCC->cs_inet_fn))
4538                 ) {     
4539                 cprintf("%d You don't have permission to author messages as '%s'.\n",
4540                         ERROR + HIGHER_ACCESS_REQUIRED,
4541                         newusername
4542                         );
4543                 return;
4544         }
4545
4546
4547         if (IsEmptyStr(newuseremail)) {
4548                 newuseremail_ok = 1;
4549         }
4550
4551         if (!IsEmptyStr(newuseremail)) {
4552                 if (!strcasecmp(newuseremail, CCC->cs_inet_email)) {
4553                         newuseremail_ok = 1;
4554                 }
4555                 else if (!IsEmptyStr(CCC->cs_inet_other_emails)) {
4556                         j = num_tokens(CCC->cs_inet_other_emails, '|');
4557                         for (i=0; i<j; ++i) {
4558                                 extract_token(buf, CCC->cs_inet_other_emails, i, '|', sizeof buf);
4559                                 if (!strcasecmp(newuseremail, buf)) {
4560                                         newuseremail_ok = 1;
4561                                 }
4562                         }
4563                 }
4564         }
4565
4566         if (!newuseremail_ok) {
4567                 cprintf("%d You don't have permission to author messages as '%s'.\n",
4568                         ERROR + HIGHER_ACCESS_REQUIRED,
4569                         newuseremail
4570                         );
4571                 return;
4572         }
4573
4574         CCC->cs_flags |= CS_POSTING;
4575
4576         /* In mailbox rooms we have to behave a little differently --
4577          * make sure the user has specified at least one recipient.  Then
4578          * validate the recipient(s).  We do this for the Mail> room, as
4579          * well as any room which has the "Mailbox" view set - unless it
4580          * is the DRAFTS room which does not require recipients
4581          */
4582
4583         if ( (  ( (CCC->room.QRflags & QR_MAILBOX) && (!strcasecmp(&CCC->room.QRname[11], MAILROOM)) )
4584                 || ( (CCC->room.QRflags & QR_MAILBOX) && (CCC->curr_view == VIEW_MAILBOX) )
4585                      ) && (strcasecmp(&CCC->room.QRname[11], USERDRAFTROOM)) !=0 ) {
4586                 if (CCC->user.axlevel < AxProbU) {
4587                         strcpy(recp, "sysop");
4588                         strcpy(cc, "");
4589                         strcpy(bcc, "");
4590                 }
4591
4592                 valid_to = validate_recipients(recp, NULL, 0);
4593                 if (valid_to->num_error > 0) {
4594                         cprintf("%d %s\n", ERROR + NO_SUCH_USER, valid_to->errormsg);
4595                         free_recipients(valid_to);
4596                         return;
4597                 }
4598
4599                 valid_cc = validate_recipients(cc, NULL, 0);
4600                 if (valid_cc->num_error > 0) {
4601                         cprintf("%d %s\n", ERROR + NO_SUCH_USER, valid_cc->errormsg);
4602                         free_recipients(valid_to);
4603                         free_recipients(valid_cc);
4604                         return;
4605                 }
4606
4607                 valid_bcc = validate_recipients(bcc, NULL, 0);
4608                 if (valid_bcc->num_error > 0) {
4609                         cprintf("%d %s\n", ERROR + NO_SUCH_USER, valid_bcc->errormsg);
4610                         free_recipients(valid_to);
4611                         free_recipients(valid_cc);
4612                         free_recipients(valid_bcc);
4613                         return;
4614                 }
4615
4616                 /* Recipient required, but none were specified */
4617                 if ( (valid_to->num_error < 0) && (valid_cc->num_error < 0) && (valid_bcc->num_error < 0) ) {
4618                         free_recipients(valid_to);
4619                         free_recipients(valid_cc);
4620                         free_recipients(valid_bcc);
4621                         cprintf("%d At least one recipient is required.\n", ERROR + NO_SUCH_USER);
4622                         return;
4623                 }
4624
4625                 if (valid_to->num_internet + valid_cc->num_internet + valid_bcc->num_internet > 0) {
4626                         if (CtdlCheckInternetMailPermission(&CCC->user)==0) {
4627                                 cprintf("%d You do not have permission "
4628                                         "to send Internet mail.\n",
4629                                         ERROR + HIGHER_ACCESS_REQUIRED);
4630                                 free_recipients(valid_to);
4631                                 free_recipients(valid_cc);
4632                                 free_recipients(valid_bcc);
4633                                 return;
4634                         }
4635                 }
4636
4637                 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)
4638                      && (CCC->user.axlevel < AxNetU) ) {
4639                         cprintf("%d Higher access required for network mail.\n",
4640                                 ERROR + HIGHER_ACCESS_REQUIRED);
4641                         free_recipients(valid_to);
4642                         free_recipients(valid_cc);
4643                         free_recipients(valid_bcc);
4644                         return;
4645                 }
4646         
4647                 if ((RESTRICT_INTERNET == 1)
4648                     && (valid_to->num_internet + valid_cc->num_internet + valid_bcc->num_internet > 0)
4649                     && ((CCC->user.flags & US_INTERNET) == 0)
4650                     && (!CCC->internal_pgm)) {
4651                         cprintf("%d You don't have access to Internet mail.\n",
4652                                 ERROR + HIGHER_ACCESS_REQUIRED);
4653                         free_recipients(valid_to);
4654                         free_recipients(valid_cc);
4655                         free_recipients(valid_bcc);
4656                         return;
4657                 }
4658
4659         }
4660
4661         /* Is this a room which has anonymous-only or anonymous-option? */
4662         anonymous = MES_NORMAL;
4663         if (CCC->room.QRflags & QR_ANONONLY) {
4664                 anonymous = MES_ANONONLY;
4665         }
4666         if (CCC->room.QRflags & QR_ANONOPT) {
4667                 if (anon_flag == 1) {   /* only if the user requested it */
4668                         anonymous = MES_ANONOPT;
4669                 }
4670         }
4671
4672         if ((CCC->room.QRflags & QR_MAILBOX) == 0) {
4673                 recp[0] = 0;
4674         }
4675
4676         /* Recommend to the client that the use of a message subject is
4677          * strongly recommended in this room, if either the SUBJECTREQ flag
4678          * is set, or if there is one or more Internet email recipients.
4679          */
4680         if (CCC->room.QRflags2 & QR2_SUBJECTREQ) subject_required = 1;
4681         if ((valid_to)  && (valid_to->num_internet > 0))        subject_required = 1;
4682         if ((valid_cc)  && (valid_cc->num_internet > 0))        subject_required = 1;
4683         if ((valid_bcc) && (valid_bcc->num_internet > 0))       subject_required = 1;
4684
4685         /* If we're only checking the validity of the request, return
4686          * success without creating the message.
4687          */
4688         if (post == 0) {
4689                 cprintf("%d %s|%d\n", CIT_OK,
4690                         ((valid_to != NULL) ? valid_to->display_recp : ""), 
4691                         subject_required);
4692                 free_recipients(valid_to);
4693                 free_recipients(valid_cc);
4694                 free_recipients(valid_bcc);
4695                 return;
4696         }
4697
4698         /* We don't need these anymore because we'll do it differently below */
4699         free_recipients(valid_to);
4700         free_recipients(valid_cc);
4701         free_recipients(valid_bcc);
4702
4703         /* Read in the message from the client. */
4704         if (do_confirm) {
4705                 cprintf("%d send message\n", START_CHAT_MODE);
4706         } else {
4707                 cprintf("%d send message\n", SEND_LISTING);
4708         }
4709
4710         msg = CtdlMakeMessage(&CCC->user, recp, cc,
4711                               CCC->room.QRname, anonymous, format_type,
4712                               newusername, newuseremail, subject,
4713                               ((!IsEmptyStr(supplied_euid)) ? supplied_euid : NULL),
4714                               NULL, references);
4715
4716         /* Put together one big recipients struct containing to/cc/bcc all in
4717          * one.  This is for the envelope.
4718          */
4719         char *all_recps = malloc(SIZ * 3);
4720         strcpy(all_recps, recp);
4721         if (!IsEmptyStr(cc)) {
4722                 if (!IsEmptyStr(all_recps)) {
4723                         strcat(all_recps, ",");
4724                 }
4725                 strcat(all_recps, cc);
4726         }
4727         if (!IsEmptyStr(bcc)) {
4728                 if (!IsEmptyStr(all_recps)) {
4729                         strcat(all_recps, ",");
4730                 }
4731                 strcat(all_recps, bcc);
4732         }
4733         if (!IsEmptyStr(all_recps)) {
4734                 valid = validate_recipients(all_recps, NULL, 0);
4735         }
4736         else {
4737                 valid = NULL;
4738         }
4739         free(all_recps);
4740
4741         if ((valid != NULL) && (valid->num_room == 1))
4742         {
4743                 /* posting into an ML room? set the envelope from 
4744                  * to the actual mail address so others get a valid
4745                  * reply-to-header.
4746                  */
4747                 msg->cm_fields['V'] = strdup(valid->recp_orgroom);
4748         }
4749
4750         if (msg != NULL) {
4751                 msgnum = CtdlSubmitMsg(msg, valid, "", QP_EADDR);
4752                 if (do_confirm) {
4753                         cprintf("%ld\n", msgnum);
4754
4755                         if (StrLength(CCC->StatusMessage) > 0) {
4756                                 cprintf("%s\n", ChrPtr(CCC->StatusMessage));
4757                         }
4758                         else if (msgnum >= 0L) {
4759                                 client_write(HKEY("Message accepted.\n"));
4760                         }
4761                         else {
4762                                 client_write(HKEY("Internal error.\n"));
4763                         }
4764
4765                         if (msg->cm_fields['E'] != NULL) {
4766                                 cprintf("%s\n", msg->cm_fields['E']);
4767                         } else {
4768                                 cprintf("\n");
4769                         }
4770                         cprintf("000\n");
4771                 }
4772
4773                 CtdlFreeMessage(msg);
4774         }
4775         if (valid != NULL) {
4776                 free_recipients(valid);
4777         }
4778         return;
4779 }
4780
4781
4782
4783 /*
4784  * API function to delete messages which match a set of criteria
4785  * (returns the actual number of messages deleted)
4786  */
4787 int CtdlDeleteMessages(char *room_name,         /* which room */
4788                        long *dmsgnums,          /* array of msg numbers to be deleted */
4789                        int num_dmsgnums,        /* number of msgs to be deleted, or 0 for "any" */
4790                        char *content_type       /* or "" for any.  regular expressions expected. */
4791         )
4792 {
4793         struct CitContext *CCC = CC;
4794         struct ctdlroom qrbuf;
4795         struct cdbdata *cdbfr;
4796         long *msglist = NULL;
4797         long *dellist = NULL;
4798         int num_msgs = 0;
4799         int i, j;
4800         int num_deleted = 0;
4801         int delete_this;
4802         struct MetaData smi;
4803         regex_t re;
4804         regmatch_t pm;
4805         int need_to_free_re = 0;
4806
4807         if (content_type) if (!IsEmptyStr(content_type)) {
4808                         regcomp(&re, content_type, 0);
4809                         need_to_free_re = 1;
4810                 }
4811         MSG_syslog(LOG_DEBUG, "CtdlDeleteMessages(%s, %d msgs, %s)\n",
4812                    room_name, num_dmsgnums, content_type);
4813
4814         /* get room record, obtaining a lock... */
4815         if (CtdlGetRoomLock(&qrbuf, room_name) != 0) {
4816                 MSG_syslog(LOG_ERR, "CtdlDeleteMessages(): Room <%s> not found\n",
4817                            room_name);
4818                 if (need_to_free_re) regfree(&re);
4819                 return (0);     /* room not found */
4820         }
4821         cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf.QRnumber, sizeof(long));
4822
4823         if (cdbfr != NULL) {
4824                 dellist = malloc(cdbfr->len);
4825                 msglist = (long *) cdbfr->ptr;
4826                 cdbfr->ptr = NULL;      /* CtdlDeleteMessages() now owns this memory */
4827                 num_msgs = cdbfr->len / sizeof(long);
4828                 cdb_free(cdbfr);
4829         }
4830         if (num_msgs > 0) {
4831                 int have_contenttype = (content_type != NULL) && !IsEmptyStr(content_type);
4832                 int have_delmsgs = (num_dmsgnums == 0) || (dmsgnums == NULL);
4833                 int have_more_del = 1;
4834
4835                 num_msgs = sort_msglist(msglist, num_msgs);
4836                 if (num_dmsgnums > 1)
4837                         num_dmsgnums = sort_msglist(dmsgnums, num_dmsgnums);
4838 /*
4839                 {
4840                         StrBuf *dbg = NewStrBuf();
4841                         for (i = 0; i < num_dmsgnums; i++)
4842                                 StrBufAppendPrintf(dbg, ", %ld", dmsgnums[i]);
4843                         MSG_syslog(LOG_DEBUG, "Deleting before: %s", ChrPtr(dbg));
4844                         FreeStrBuf(&dbg);
4845                 }
4846 */
4847                 i = 0; j = 0;
4848                 while ((i < num_msgs) && (have_more_del)) {
4849                         delete_this = 0x00;
4850
4851
4852                         /* Set/clear a bit for each criterion */
4853
4854                         /* 0 messages in the list or a null list means that we are
4855                          * interested in deleting any messages which meet the other criteria.
4856                          */
4857                         if (have_delmsgs) {
4858                                 delete_this |= 0x01;
4859                         }
4860                         else {
4861                                 while ((i < num_msgs) && (msglist[i] < dmsgnums[j])) i++;
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 }