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