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