* Holy war on strlen: use IsEmptyStr where apropriate.
[citadel.git] / citadel / msgbase.c
1 /*
2  * $Id$
3  *
4  * Implements the message store.
5  *
6  */
7
8 #include "sysdep.h"
9 #include <stdlib.h>
10 #include <unistd.h>
11 #include <stdio.h>
12 #include <fcntl.h>
13
14 #if TIME_WITH_SYS_TIME
15 # include <sys/time.h>
16 # include <time.h>
17 #else
18 # if HAVE_SYS_TIME_H
19 #  include <sys/time.h>
20 # else
21 #  include <time.h>
22 # endif
23 #endif
24
25
26 #include <ctype.h>
27 #include <string.h>
28 #include <limits.h>
29 #include <errno.h>
30 #include <stdarg.h>
31 #include <sys/stat.h>
32 #include <sys/types.h>
33 #include <regex.h>
34 #include "citadel.h"
35 #include "server.h"
36 #include "serv_extensions.h"
37 #include "database.h"
38 #include "msgbase.h"
39 #include "support.h"
40 #include "sysdep_decls.h"
41 #include "citserver.h"
42 #include "room_ops.h"
43 #include "user_ops.h"
44 #include "file_ops.h"
45 #include "config.h"
46 #include "control.h"
47 #include "tools.h"
48 #include "mime_parser.h"
49 #include "html.h"
50 #include "genstamp.h"
51 #include "internet_addressing.h"
52 #include "vcard.h"
53 #include "euidindex.h"
54 #include "journaling.h"
55 #include "citadel_dirs.h"
56
57
58 long config_msgnum;
59 struct addresses_to_be_filed *atbf = NULL;
60
61 /* This temp file holds the queue of operations for AdjRefCount() */
62 static FILE *arcfp = NULL;
63
64 /* 
65  * This really belongs in serv_network.c, but I don't know how to export
66  * symbols between modules.
67  */
68 struct FilterList *filterlist = NULL;
69
70
71 /*
72  * These are the four-character field headers we use when outputting
73  * messages in Citadel format (as opposed to RFC822 format).
74  */
75 char *msgkeys[] = {
76         NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 
77         NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 
78         NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 
79         NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 
80         NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 
81         NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 
82         NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 
83         NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 
84         NULL, 
85         "from",
86         NULL, NULL, NULL,
87         "exti",
88         "rfca",
89         NULL, 
90         "hnod",
91         "msgn",
92         "jrnl",
93         NULL, NULL,
94         "text",
95         "node",
96         "room",
97         "path",
98         NULL,
99         "rcpt",
100         "spec",
101         "time",
102         "subj",
103         NULL,
104         NULL,
105         NULL,
106         "cccc",
107         NULL
108 };
109
110 /*
111  * This function is self explanatory.
112  * (What can I say, I'm in a weird mood today...)
113  */
114 void remove_any_whitespace_to_the_left_or_right_of_at_symbol(char *name)
115 {
116         int i;
117
118         for (i = 0; i < strlen(name); ++i) {
119                 if (name[i] == '@') {
120                         while (isspace(name[i - 1]) && i > 0) {
121                                 strcpy(&name[i - 1], &name[i]);
122                                 --i;
123                         }
124                         while (isspace(name[i + 1])) {
125                                 strcpy(&name[i + 1], &name[i + 2]);
126                         }
127                 }
128         }
129 }
130
131
132 /*
133  * Aliasing for network mail.
134  * (Error messages have been commented out, because this is a server.)
135  */
136 int alias(char *name)
137 {                               /* process alias and routing info for mail */
138         FILE *fp;
139         int a, i;
140         char aaa[SIZ], bbb[SIZ];
141         char *ignetcfg = NULL;
142         char *ignetmap = NULL;
143         int at = 0;
144         char node[64];
145         char testnode[64];
146         char buf[SIZ];
147
148         char original_name[256];
149         safestrncpy(original_name, name, sizeof original_name);
150
151         striplt(name);
152         remove_any_whitespace_to_the_left_or_right_of_at_symbol(name);
153         stripallbut(name, '<', '>');
154
155         fp = fopen(file_mail_aliases, "r");
156         if (fp == NULL) {
157                 fp = fopen("/dev/null", "r");
158         }
159         if (fp == NULL) {
160                 return (MES_ERROR);
161         }
162         strcpy(aaa, "");
163         strcpy(bbb, "");
164         while (fgets(aaa, sizeof aaa, fp) != NULL) {
165                 while (isspace(name[0]))
166                         strcpy(name, &name[1]);
167                 aaa[strlen(aaa) - 1] = 0;
168                 strcpy(bbb, "");
169                 for (a = 0; a < strlen(aaa); ++a) {
170                         if (aaa[a] == ',') {
171                                 strcpy(bbb, &aaa[a + 1]);
172                                 aaa[a] = 0;
173                         }
174                 }
175                 if (!strcasecmp(name, aaa))
176                         strcpy(name, bbb);
177         }
178         fclose(fp);
179
180         /* Hit the Global Address Book */
181         if (CtdlDirectoryLookup(aaa, name, sizeof aaa) == 0) {
182                 strcpy(name, aaa);
183         }
184
185         if (strcasecmp(original_name, name)) {
186                 lprintf(CTDL_INFO, "%s is being forwarded to %s\n", original_name, name);
187         }
188
189         /* Change "user @ xxx" to "user" if xxx is an alias for this host */
190         for (a=0; a<strlen(name); ++a) {
191                 if (name[a] == '@') {
192                         if (CtdlHostAlias(&name[a+1]) == hostalias_localhost) {
193                                 name[a] = 0;
194                                 lprintf(CTDL_INFO, "Changed to <%s>\n", name);
195                         }
196                 }
197         }
198
199         /* determine local or remote type, see citadel.h */
200         at = haschar(name, '@');
201         if (at == 0) return(MES_LOCAL);         /* no @'s - local address */
202         if (at > 1) return(MES_ERROR);          /* >1 @'s - invalid address */
203         remove_any_whitespace_to_the_left_or_right_of_at_symbol(name);
204
205         /* figure out the delivery mode */
206         extract_token(node, name, 1, '@', sizeof node);
207
208         /* If there are one or more dots in the nodename, we assume that it
209          * is an FQDN and will attempt SMTP delivery to the Internet.
210          */
211         if (haschar(node, '.') > 0) {
212                 return(MES_INTERNET);
213         }
214
215         /* Otherwise we look in the IGnet maps for a valid Citadel node.
216          * Try directly-connected nodes first...
217          */
218         ignetcfg = CtdlGetSysConfig(IGNETCFG);
219         for (i=0; i<num_tokens(ignetcfg, '\n'); ++i) {
220                 extract_token(buf, ignetcfg, i, '\n', sizeof buf);
221                 extract_token(testnode, buf, 0, '|', sizeof testnode);
222                 if (!strcasecmp(node, testnode)) {
223                         free(ignetcfg);
224                         return(MES_IGNET);
225                 }
226         }
227         free(ignetcfg);
228
229         /*
230          * Then try nodes that are two or more hops away.
231          */
232         ignetmap = CtdlGetSysConfig(IGNETMAP);
233         for (i=0; i<num_tokens(ignetmap, '\n'); ++i) {
234                 extract_token(buf, ignetmap, i, '\n', sizeof buf);
235                 extract_token(testnode, buf, 0, '|', sizeof testnode);
236                 if (!strcasecmp(node, testnode)) {
237                         free(ignetmap);
238                         return(MES_IGNET);
239                 }
240         }
241         free(ignetmap);
242
243         /* If we get to this point it's an invalid node name */
244         return (MES_ERROR);
245 }
246
247
248 /*
249  * Back end for the MSGS command: output message number only.
250  */
251 void simple_listing(long msgnum, void *userdata)
252 {
253         cprintf("%ld\n", msgnum);
254 }
255
256
257
258 /*
259  * Back end for the MSGS command: output header summary.
260  */
261 void headers_listing(long msgnum, void *userdata)
262 {
263         struct CtdlMessage *msg;
264
265         msg = CtdlFetchMessage(msgnum, 0);
266         if (msg == NULL) {
267                 cprintf("%ld|0|||||\n", msgnum);
268                 return;
269         }
270
271         cprintf("%ld|%s|%s|%s|%s|%s|\n",
272                 msgnum,
273                 (msg->cm_fields['T'] ? msg->cm_fields['T'] : "0"),
274                 (msg->cm_fields['A'] ? msg->cm_fields['A'] : ""),
275                 (msg->cm_fields['N'] ? msg->cm_fields['N'] : ""),
276                 (msg->cm_fields['F'] ? msg->cm_fields['F'] : ""),
277                 (msg->cm_fields['U'] ? msg->cm_fields['U'] : "")
278         );
279         CtdlFreeMessage(msg);
280 }
281
282
283
284 /* Determine if a given message matches the fields in a message template.
285  * Return 0 for a successful match.
286  */
287 int CtdlMsgCmp(struct CtdlMessage *msg, struct CtdlMessage *template) {
288         int i;
289
290         /* If there aren't any fields in the template, all messages will
291          * match.
292          */
293         if (template == NULL) return(0);
294
295         /* Null messages are bogus. */
296         if (msg == NULL) return(1);
297
298         for (i='A'; i<='Z'; ++i) {
299                 if (template->cm_fields[i] != NULL) {
300                         if (msg->cm_fields[i] == NULL) {
301                                 return 1;
302                         }
303                         if (strcasecmp(msg->cm_fields[i],
304                                 template->cm_fields[i])) return 1;
305                 }
306         }
307
308         /* All compares succeeded: we have a match! */
309         return 0;
310 }
311
312
313
314 /*
315  * Retrieve the "seen" message list for the current room.
316  */
317 void CtdlGetSeen(char *buf, int which_set) {
318         struct visit vbuf;
319
320         /* Learn about the user and room in question */
321         CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
322
323         if (which_set == ctdlsetseen_seen)
324                 safestrncpy(buf, vbuf.v_seen, SIZ);
325         if (which_set == ctdlsetseen_answered)
326                 safestrncpy(buf, vbuf.v_answered, SIZ);
327 }
328
329
330
331 /*
332  * Manipulate the "seen msgs" string (or other message set strings)
333  */
334 void CtdlSetSeen(long *target_msgnums, int num_target_msgnums,
335                 int target_setting, int which_set,
336                 struct ctdluser *which_user, struct ctdlroom *which_room) {
337         struct cdbdata *cdbfr;
338         int i, j, k;
339         int is_seen = 0;
340         int was_seen = 0;
341         long lo = (-1L);
342         long hi = (-1L);
343         long t = (-1L);
344         int trimming = 0;
345         struct visit vbuf;
346         long *msglist;
347         int num_msgs = 0;
348         char vset[SIZ];
349         char *is_set;   /* actually an array of booleans */
350         int num_sets;
351         int s;
352         char setstr[SIZ], lostr[SIZ], histr[SIZ];
353         size_t tmp;
354
355         /* Don't bother doing *anything* if we were passed a list of zero messages */
356         if (num_target_msgnums < 1) {
357                 return;
358         }
359
360         lprintf(CTDL_DEBUG, "CtdlSetSeen(%d msgs starting with %ld, %d, %d)\n",
361                 num_target_msgnums, target_msgnums[0],
362                 target_setting, which_set);
363
364         /* Learn about the user and room in question */
365         CtdlGetRelationship(&vbuf,
366                 ((which_user != NULL) ? which_user : &CC->user),
367                 ((which_room != NULL) ? which_room : &CC->room)
368         );
369
370         /* Load the message list */
371         cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
372         if (cdbfr != NULL) {
373                 msglist = (long *) cdbfr->ptr;
374                 cdbfr->ptr = NULL;      /* CtdlSetSeen() now owns this memory */
375                 num_msgs = cdbfr->len / sizeof(long);
376                 cdb_free(cdbfr);
377         } else {
378                 return; /* No messages at all?  No further action. */
379         }
380
381         is_set = malloc(num_msgs * sizeof(char));
382         memset(is_set, 0, (num_msgs * sizeof(char)) );
383
384         /* Decide which message set we're manipulating */
385         switch(which_set) {
386                 case ctdlsetseen_seen:
387                         safestrncpy(vset, vbuf.v_seen, sizeof vset);
388                         break;
389                 case ctdlsetseen_answered:
390                         safestrncpy(vset, vbuf.v_answered, sizeof vset);
391                         break;
392         }
393
394         /* lprintf(CTDL_DEBUG, "before optimize: %s\n", vset); */
395
396         /* Translate the existing sequence set into an array of booleans */
397         num_sets = num_tokens(vset, ',');
398         for (s=0; s<num_sets; ++s) {
399                 extract_token(setstr, vset, s, ',', sizeof setstr);
400
401                 extract_token(lostr, setstr, 0, ':', sizeof lostr);
402                 if (num_tokens(setstr, ':') >= 2) {
403                         extract_token(histr, setstr, 1, ':', sizeof histr);
404                         if (!strcmp(histr, "*")) {
405                                 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
406                         }
407                 }
408                 else {
409                         strcpy(histr, lostr);
410                 }
411                 lo = atol(lostr);
412                 hi = atol(histr);
413
414                 for (i = 0; i < num_msgs; ++i) {
415                         if ((msglist[i] >= lo) && (msglist[i] <= hi)) {
416                                 is_set[i] = 1;
417                         }
418                 }
419         }
420
421         /* Now translate the array of booleans back into a sequence set */
422         strcpy(vset, "");
423         lo = (-1L);
424         hi = (-1L);
425
426         for (i=0; i<num_msgs; ++i) {
427
428                 is_seen = is_set[i];    /* Default to existing setting */
429
430                 for (k=0; k<num_target_msgnums; ++k) {
431                         if (msglist[i] == target_msgnums[k]) {
432                                 is_seen = target_setting;
433                         }
434                 }
435
436                 if (is_seen) {
437                         if (lo < 0L) lo = msglist[i];
438                         hi = msglist[i];
439                 }
440
441                 if (  ((is_seen == 0) && (was_seen == 1))
442                    || ((is_seen == 1) && (i == num_msgs-1)) ) {
443
444                         /* begin trim-o-matic code */
445                         j=9;
446                         trimming = 0;
447                         while ( (strlen(vset) + 20) > sizeof vset) {
448                                 remove_token(vset, 0, ',');
449                                 trimming = 1;
450                                 if (j--) break; /* loop no more than 9 times */
451                         }
452                         if ( (trimming) && (which_set == ctdlsetseen_seen) ) {
453                                 t = atol(vset);
454                                 if (t<2) t=2;
455                                 --t;
456                                 snprintf(lostr, sizeof lostr,
457                                         "1:%ld,%s", t, vset);
458                                 safestrncpy(vset, lostr, sizeof vset);
459                         }
460                         /* end trim-o-matic code */
461
462                         tmp = strlen(vset);
463                         if (tmp > 0) {
464                                 strcat(vset, ",");
465                                 ++tmp;
466                         }
467                         if (lo == hi) {
468                                 snprintf(&vset[tmp], (sizeof vset) - tmp,
469                                          "%ld", lo);
470                         }
471                         else {
472                                 snprintf(&vset[tmp], (sizeof vset) - tmp,
473                                          "%ld:%ld", lo, hi);
474                         }
475                         lo = (-1L);
476                         hi = (-1L);
477                 }
478                 was_seen = is_seen;
479         }
480
481         /* Decide which message set we're manipulating */
482         switch (which_set) {
483                 case ctdlsetseen_seen:
484                         safestrncpy(vbuf.v_seen, vset, sizeof vbuf.v_seen);
485                         break;
486                 case ctdlsetseen_answered:
487                         safestrncpy(vbuf.v_answered, vset,
488                                                 sizeof vbuf.v_answered);
489                         break;
490         }
491         free(is_set);
492
493         /* lprintf(CTDL_DEBUG, " after optimize: %s\n", vset); */
494         free(msglist);
495         CtdlSetRelationship(&vbuf,
496                 ((which_user != NULL) ? which_user : &CC->user),
497                 ((which_room != NULL) ? which_room : &CC->room)
498         );
499 }
500
501
502 /*
503  * API function to perform an operation for each qualifying message in the
504  * current room.  (Returns the number of messages processed.)
505  */
506 int CtdlForEachMessage(int mode, long ref, char *search_string,
507                         char *content_type,
508                         struct CtdlMessage *compare,
509                         void (*CallBack) (long, void *),
510                         void *userdata)
511 {
512
513         int a, i, j;
514         struct visit vbuf;
515         struct cdbdata *cdbfr;
516         long *msglist = NULL;
517         int num_msgs = 0;
518         int num_processed = 0;
519         long thismsg;
520         struct MetaData smi;
521         struct CtdlMessage *msg = NULL;
522         int is_seen = 0;
523         long lastold = 0L;
524         int printed_lastold = 0;
525         int num_search_msgs = 0;
526         long *search_msgs = NULL;
527         regex_t re;
528         int need_to_free_re = 0;
529         regmatch_t pm;
530
531         if (content_type) if (!IsEmptyStr(content_type)) {
532                 regcomp(&re, content_type, 0);
533                 need_to_free_re = 1;
534         }
535
536         /* Learn about the user and room in question */
537         getuser(&CC->user, CC->curr_user);
538         CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
539
540         /* Load the message list */
541         cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
542         if (cdbfr != NULL) {
543                 msglist = (long *) cdbfr->ptr;
544                 cdbfr->ptr = NULL;      /* CtdlForEachMessage() now owns this memory */
545                 num_msgs = cdbfr->len / sizeof(long);
546                 cdb_free(cdbfr);
547         } else {
548                 if (need_to_free_re) regfree(&re);
549                 return 0;       /* No messages at all?  No further action. */
550         }
551
552
553         /*
554          * Now begin the traversal.
555          */
556         if (num_msgs > 0) for (a = 0; a < num_msgs; ++a) {
557
558                 /* If the caller is looking for a specific MIME type, filter
559                  * out all messages which are not of the type requested.
560                  */
561                 if (content_type != NULL) if (!IsEmptyStr(content_type)) {
562
563                         /* This call to GetMetaData() sits inside this loop
564                          * so that we only do the extra database read per msg
565                          * if we need to.  Doing the extra read all the time
566                          * really kills the server.  If we ever need to use
567                          * metadata for another search criterion, we need to
568                          * move the read somewhere else -- but still be smart
569                          * enough to only do the read if the caller has
570                          * specified something that will need it.
571                          */
572                         GetMetaData(&smi, msglist[a]);
573
574                         /* if (strcasecmp(smi.meta_content_type, content_type)) { old non-regex way */
575                         if (regexec(&re, smi.meta_content_type, 1, &pm, 0) != 0) {
576                                 msglist[a] = 0L;
577                         }
578                 }
579         }
580
581         num_msgs = sort_msglist(msglist, num_msgs);
582
583         /* If a template was supplied, filter out the messages which
584          * don't match.  (This could induce some delays!)
585          */
586         if (num_msgs > 0) {
587                 if (compare != NULL) {
588                         for (a = 0; a < num_msgs; ++a) {
589                                 msg = CtdlFetchMessage(msglist[a], 1);
590                                 if (msg != NULL) {
591                                         if (CtdlMsgCmp(msg, compare)) {
592                                                 msglist[a] = 0L;
593                                         }
594                                         CtdlFreeMessage(msg);
595                                 }
596                         }
597                 }
598         }
599
600         /* If a search string was specified, get a message list from
601          * the full text index and remove messages which aren't on both
602          * lists.
603          *
604          * How this works:
605          * Since the lists are sorted and strictly ascending, and the
606          * output list is guaranteed to be shorter than or equal to the
607          * input list, we overwrite the bottom of the input list.  This
608          * eliminates the need to memmove big chunks of the list over and
609          * over again.
610          */
611         if ( (num_msgs > 0) && (mode == MSGS_SEARCH) && (search_string) ) {
612
613                 /* Call search module via hook mechanism.
614                  * NULL means use any search function available.
615                  * otherwise replace with a char * to name of search routine
616                  */
617                 CtdlModuleDoSearch(&num_search_msgs, &search_msgs, search_string, "fulltext");
618
619                 if (num_search_msgs > 0) {
620         
621                         int orig_num_msgs;
622
623                         orig_num_msgs = num_msgs;
624                         num_msgs = 0;
625                         for (i=0; i<orig_num_msgs; ++i) {
626                                 for (j=0; j<num_search_msgs; ++j) {
627                                         if (msglist[i] == search_msgs[j]) {
628                                                 msglist[num_msgs++] = msglist[i];
629                                         }
630                                 }
631                         }
632                 }
633                 else {
634                         num_msgs = 0;   /* No messages qualify */
635                 }
636                 if (search_msgs != NULL) free(search_msgs);
637
638                 /* Now that we've purged messages which don't contain the search
639                  * string, treat a MSGS_SEARCH just like a MSGS_ALL from this
640                  * point on.
641                  */
642                 mode = MSGS_ALL;
643         }
644
645         /*
646          * Now iterate through the message list, according to the
647          * criteria supplied by the caller.
648          */
649         if (num_msgs > 0)
650                 for (a = 0; a < num_msgs; ++a) {
651                         thismsg = msglist[a];
652                         if (mode == MSGS_ALL) {
653                                 is_seen = 0;
654                         }
655                         else {
656                                 is_seen = is_msg_in_sequence_set(
657                                                         vbuf.v_seen, thismsg);
658                                 if (is_seen) lastold = thismsg;
659                         }
660                         if ((thismsg > 0L)
661                             && (
662
663                                        (mode == MSGS_ALL)
664                                        || ((mode == MSGS_OLD) && (is_seen))
665                                        || ((mode == MSGS_NEW) && (!is_seen))
666                                        || ((mode == MSGS_LAST) && (a >= (num_msgs - ref)))
667                                    || ((mode == MSGS_FIRST) && (a < ref))
668                                 || ((mode == MSGS_GT) && (thismsg > ref))
669                                 || ((mode == MSGS_EQ) && (thismsg == ref))
670                             )
671                             ) {
672                                 if ((mode == MSGS_NEW) && (CC->user.flags & US_LASTOLD) && (lastold > 0L) && (printed_lastold == 0) && (!is_seen)) {
673                                         if (CallBack)
674                                                 CallBack(lastold, userdata);
675                                         printed_lastold = 1;
676                                         ++num_processed;
677                                 }
678                                 if (CallBack) CallBack(thismsg, userdata);
679                                 ++num_processed;
680                         }
681                 }
682         free(msglist);          /* Clean up */
683         if (need_to_free_re) regfree(&re);
684         return num_processed;
685 }
686
687
688
689 /*
690  * cmd_msgs()  -  get list of message #'s in this room
691  *              implements the MSGS server command using CtdlForEachMessage()
692  */
693 void cmd_msgs(char *cmdbuf)
694 {
695         int mode = 0;
696         char which[16];
697         char buf[256];
698         char tfield[256];
699         char tvalue[256];
700         int cm_ref = 0;
701         int i;
702         int with_template = 0;
703         struct CtdlMessage *template = NULL;
704         int with_headers = 0;
705         char search_string[1024];
706
707         extract_token(which, cmdbuf, 0, '|', sizeof which);
708         cm_ref = extract_int(cmdbuf, 1);
709         extract_token(search_string, cmdbuf, 1, '|', sizeof search_string);
710         with_template = extract_int(cmdbuf, 2);
711         with_headers = extract_int(cmdbuf, 3);
712
713         strcat(which, "   ");
714         if (!strncasecmp(which, "OLD", 3))
715                 mode = MSGS_OLD;
716         else if (!strncasecmp(which, "NEW", 3))
717                 mode = MSGS_NEW;
718         else if (!strncasecmp(which, "FIRST", 5))
719                 mode = MSGS_FIRST;
720         else if (!strncasecmp(which, "LAST", 4))
721                 mode = MSGS_LAST;
722         else if (!strncasecmp(which, "GT", 2))
723                 mode = MSGS_GT;
724         else if (!strncasecmp(which, "SEARCH", 6))
725                 mode = MSGS_SEARCH;
726         else
727                 mode = MSGS_ALL;
728
729         if ((!(CC->logged_in)) && (!(CC->internal_pgm))) {
730                 cprintf("%d not logged in\n", ERROR + NOT_LOGGED_IN);
731                 return;
732         }
733
734         if ( (mode == MSGS_SEARCH) && (!config.c_enable_fulltext) ) {
735                 cprintf("%d Full text index is not enabled on this server.\n",
736                         ERROR + CMD_NOT_SUPPORTED);
737                 return;
738         }
739
740         if (with_template) {
741                 unbuffer_output();
742                 cprintf("%d Send template then receive message list\n",
743                         START_CHAT_MODE);
744                 template = (struct CtdlMessage *)
745                         malloc(sizeof(struct CtdlMessage));
746                 memset(template, 0, sizeof(struct CtdlMessage));
747                 template->cm_magic = CTDLMESSAGE_MAGIC;
748                 template->cm_anon_type = MES_NORMAL;
749
750                 while(client_getln(buf, sizeof buf), strcmp(buf,"000")) {
751                         extract_token(tfield, buf, 0, '|', sizeof tfield);
752                         extract_token(tvalue, buf, 1, '|', sizeof tvalue);
753                         for (i='A'; i<='Z'; ++i) if (msgkeys[i]!=NULL) {
754                                 if (!strcasecmp(tfield, msgkeys[i])) {
755                                         template->cm_fields[i] =
756                                                 strdup(tvalue);
757                                 }
758                         }
759                 }
760                 buffer_output();
761         }
762         else {
763                 cprintf("%d  \n", LISTING_FOLLOWS);
764         }
765
766         CtdlForEachMessage(mode,
767                         ( (mode == MSGS_SEARCH) ? 0 : cm_ref ),
768                         ( (mode == MSGS_SEARCH) ? search_string : NULL ),
769                         NULL,
770                         template,
771                         (with_headers ? headers_listing : simple_listing),
772                         NULL
773         );
774         if (template != NULL) CtdlFreeMessage(template);
775         cprintf("000\n");
776 }
777
778
779
780
781 /* 
782  * help_subst()  -  support routine for help file viewer
783  */
784 void help_subst(char *strbuf, char *source, char *dest)
785 {
786         char workbuf[SIZ];
787         int p;
788
789         while (p = pattern2(strbuf, source), (p >= 0)) {
790                 strcpy(workbuf, &strbuf[p + strlen(source)]);
791                 strcpy(&strbuf[p], dest);
792                 strcat(strbuf, workbuf);
793         }
794 }
795
796
797 void do_help_subst(char *buffer)
798 {
799         char buf2[16];
800
801         help_subst(buffer, "^nodename", config.c_nodename);
802         help_subst(buffer, "^humannode", config.c_humannode);
803         help_subst(buffer, "^fqdn", config.c_fqdn);
804         help_subst(buffer, "^username", CC->user.fullname);
805         snprintf(buf2, sizeof buf2, "%ld", CC->user.usernum);
806         help_subst(buffer, "^usernum", buf2);
807         help_subst(buffer, "^sysadm", config.c_sysadm);
808         help_subst(buffer, "^variantname", CITADEL);
809         snprintf(buf2, sizeof buf2, "%d", config.c_maxsessions);
810         help_subst(buffer, "^maxsessions", buf2);
811         help_subst(buffer, "^bbsdir", ctdl_bbsbase_dir);
812 }
813
814
815
816 /*
817  * memfmout()  -  Citadel text formatter and paginator.
818  *           Although the original purpose of this routine was to format
819  *           text to the reader's screen width, all we're really using it
820  *           for here is to format text out to 80 columns before sending it
821  *           to the client.  The client software may reformat it again.
822  */
823 void memfmout(
824         char *mptr,             /* where are we going to get our text from? */
825         char subst,             /* nonzero if we should do substitutions */
826         char *nl)               /* string to terminate lines with */
827 {
828         int a, b, c;
829         int real = 0;
830         int old = 0;
831         cit_uint8_t ch;
832         char aaa[140];
833         char buffer[SIZ];
834         static int width = 80;
835
836         strcpy(aaa, "");
837         old = 255;
838         strcpy(buffer, "");
839         c = 1;                  /* c is the current pos */
840
841         do {
842                 if (subst) {
843                         while (ch = *mptr, ((ch != 0) && (strlen(buffer) < 126))) {
844                                 ch = *mptr++;
845                                 buffer[strlen(buffer) + 1] = 0;
846                                 buffer[strlen(buffer)] = ch;
847                         }
848
849                         if (buffer[0] == '^')
850                                 do_help_subst(buffer);
851
852                         buffer[strlen(buffer) + 1] = 0;
853                         a = buffer[0];
854                         strcpy(buffer, &buffer[1]);
855                 } else {
856                         ch = *mptr++;
857                 }
858
859                 old = real;
860                 real = ch;
861
862                 if (((ch == 13) || (ch == 10)) && (old != 13) && (old != 10)) {
863                         ch = 32;
864                 }
865                 if (((old == 13) || (old == 10)) && (isspace(real))) {
866                         cprintf("%s", nl);
867                         c = 1;
868                 }
869                 if (ch > 32) {
870                         if (((strlen(aaa) + c) > (width - 5)) && (strlen(aaa) > (width - 5))) {
871                                 cprintf("%s%s", nl, aaa);
872                                 c = strlen(aaa);
873                                 aaa[0] = 0;
874                         }
875                         b = strlen(aaa);
876                         aaa[b] = ch;
877                         aaa[b + 1] = 0;
878                 }
879                 if (ch == 32) {
880                         if ((strlen(aaa) + c) > (width - 5)) {
881                                 cprintf("%s", nl);
882                                 c = 1;
883                         }
884                         cprintf("%s ", aaa);
885                         ++c;
886                         c = c + strlen(aaa);
887                         strcpy(aaa, "");
888                 }
889                 if ((ch == 13) || (ch == 10)) {
890                         cprintf("%s%s", aaa, nl);
891                         c = 1;
892                         strcpy(aaa, "");
893                 }
894
895         } while (ch > 0);
896
897         cprintf("%s%s", aaa, nl);
898 }
899
900
901
902 /*
903  * Callback function for mime parser that simply lists the part
904  */
905 void list_this_part(char *name, char *filename, char *partnum, char *disp,
906                     void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
907                     void *cbuserdata)
908 {
909         struct ma_info *ma;
910         
911         ma = (struct ma_info *)cbuserdata;
912         if (ma->is_ma == 0) {
913                 cprintf("part=%s|%s|%s|%s|%s|%ld\n",
914                         name, filename, partnum, disp, cbtype, (long)length);
915         }
916 }
917
918 /* 
919  * Callback function for multipart prefix
920  */
921 void list_this_pref(char *name, char *filename, char *partnum, char *disp,
922                     void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
923                     void *cbuserdata)
924 {
925         struct ma_info *ma;
926         
927         ma = (struct ma_info *)cbuserdata;
928         if (!strcasecmp(cbtype, "multipart/alternative")) {
929                 ++ma->is_ma;
930         }
931
932         if (ma->is_ma == 0) {
933                 cprintf("pref=%s|%s\n", partnum, cbtype);
934         }
935 }
936
937 /* 
938  * Callback function for multipart sufffix
939  */
940 void list_this_suff(char *name, char *filename, char *partnum, char *disp,
941                     void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
942                     void *cbuserdata)
943 {
944         struct ma_info *ma;
945         
946         ma = (struct ma_info *)cbuserdata;
947         if (ma->is_ma == 0) {
948                 cprintf("suff=%s|%s\n", partnum, cbtype);
949         }
950         if (!strcasecmp(cbtype, "multipart/alternative")) {
951                 --ma->is_ma;
952         }
953 }
954
955
956 /*
957  * Callback function for mime parser that opens a section for downloading
958  */
959 void mime_download(char *name, char *filename, char *partnum, char *disp,
960                    void *content, char *cbtype, char *cbcharset, size_t length,
961                    char *encoding, void *cbuserdata)
962 {
963
964         /* Silently go away if there's already a download open... */
965         if (CC->download_fp != NULL)
966                 return;
967
968         /* ...or if this is not the desired section */
969         if (strcasecmp(CC->download_desired_section, partnum))
970                 return;
971
972         CC->download_fp = tmpfile();
973         if (CC->download_fp == NULL)
974                 return;
975
976         fwrite(content, length, 1, CC->download_fp);
977         fflush(CC->download_fp);
978         rewind(CC->download_fp);
979
980         OpenCmdResult(filename, cbtype);
981 }
982
983
984
985 /*
986  * Callback function for mime parser that outputs a section all at once
987  */
988 void mime_spew_section(char *name, char *filename, char *partnum, char *disp,
989                    void *content, char *cbtype, char *cbcharset, size_t length,
990                    char *encoding, void *cbuserdata)
991 {
992         int *found_it = (int *)cbuserdata;
993
994         /* ...or if this is not the desired section */
995         if (strcasecmp(CC->download_desired_section, partnum))
996                 return;
997
998         *found_it = 1;
999
1000         cprintf("%d %d\n", BINARY_FOLLOWS, (int)length);
1001         client_write(content, length);
1002 }
1003
1004
1005
1006 /*
1007  * Load a message from disk into memory.
1008  * This is used by CtdlOutputMsg() and other fetch functions.
1009  *
1010  * NOTE: Caller is responsible for freeing the returned CtdlMessage struct
1011  *       using the CtdlMessageFree() function.
1012  */
1013 struct CtdlMessage *CtdlFetchMessage(long msgnum, int with_body)
1014 {
1015         struct cdbdata *dmsgtext;
1016         struct CtdlMessage *ret = NULL;
1017         char *mptr;
1018         char *upper_bound;
1019         cit_uint8_t ch;
1020         cit_uint8_t field_header;
1021
1022         lprintf(CTDL_DEBUG, "CtdlFetchMessage(%ld, %d)\n", msgnum, with_body);
1023
1024         dmsgtext = cdb_fetch(CDB_MSGMAIN, &msgnum, sizeof(long));
1025         if (dmsgtext == NULL) {
1026                 return NULL;
1027         }
1028         mptr = dmsgtext->ptr;
1029         upper_bound = mptr + dmsgtext->len;
1030
1031         /* Parse the three bytes that begin EVERY message on disk.
1032          * The first is always 0xFF, the on-disk magic number.
1033          * The second is the anonymous/public type byte.
1034          * The third is the format type byte (vari, fixed, or MIME).
1035          */
1036         ch = *mptr++;
1037         if (ch != 255) {
1038                 lprintf(CTDL_ERR,
1039                         "Message %ld appears to be corrupted.\n",
1040                         msgnum);
1041                 cdb_free(dmsgtext);
1042                 return NULL;
1043         }
1044         ret = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
1045         memset(ret, 0, sizeof(struct CtdlMessage));
1046
1047         ret->cm_magic = CTDLMESSAGE_MAGIC;
1048         ret->cm_anon_type = *mptr++;    /* Anon type byte */
1049         ret->cm_format_type = *mptr++;  /* Format type byte */
1050
1051         /*
1052          * The rest is zero or more arbitrary fields.  Load them in.
1053          * We're done when we encounter either a zero-length field or
1054          * have just processed the 'M' (message text) field.
1055          */
1056         do {
1057                 if (mptr >= upper_bound) {
1058                         break;
1059                 }
1060                 field_header = *mptr++;
1061                 ret->cm_fields[field_header] = strdup(mptr);
1062
1063                 while (*mptr++ != 0);   /* advance to next field */
1064
1065         } while ((mptr < upper_bound) && (field_header != 'M'));
1066
1067         cdb_free(dmsgtext);
1068
1069         /* Always make sure there's something in the msg text field.  If
1070          * it's NULL, the message text is most likely stored separately,
1071          * so go ahead and fetch that.  Failing that, just set a dummy
1072          * body so other code doesn't barf.
1073          */
1074         if ( (ret->cm_fields['M'] == NULL) && (with_body) ) {
1075                 dmsgtext = cdb_fetch(CDB_BIGMSGS, &msgnum, sizeof(long));
1076                 if (dmsgtext != NULL) {
1077                         ret->cm_fields['M'] = strdup(dmsgtext->ptr);
1078                         cdb_free(dmsgtext);
1079                 }
1080         }
1081         if (ret->cm_fields['M'] == NULL) {
1082                 ret->cm_fields['M'] = strdup("\r\n\r\n (no text)\r\n");
1083         }
1084
1085         /* Perform "before read" hooks (aborting if any return nonzero) */
1086         if (PerformMessageHooks(ret, EVT_BEFOREREAD) > 0) {
1087                 CtdlFreeMessage(ret);
1088                 return NULL;
1089         }
1090
1091         return (ret);
1092 }
1093
1094
1095 /*
1096  * Returns 1 if the supplied pointer points to a valid Citadel message.
1097  * If the pointer is NULL or the magic number check fails, returns 0.
1098  */
1099 int is_valid_message(struct CtdlMessage *msg) {
1100         if (msg == NULL)
1101                 return 0;
1102         if ((msg->cm_magic) != CTDLMESSAGE_MAGIC) {
1103                 lprintf(CTDL_WARNING, "is_valid_message() -- self-check failed\n");
1104                 return 0;
1105         }
1106         return 1;
1107 }
1108
1109
1110 /*
1111  * 'Destructor' for struct CtdlMessage
1112  */
1113 void CtdlFreeMessage(struct CtdlMessage *msg)
1114 {
1115         int i;
1116
1117         if (is_valid_message(msg) == 0) 
1118         {
1119                 if (msg != NULL) free (msg);
1120                 return;
1121         }
1122
1123         for (i = 0; i < 256; ++i)
1124                 if (msg->cm_fields[i] != NULL) {
1125                         free(msg->cm_fields[i]);
1126                 }
1127
1128         msg->cm_magic = 0;      /* just in case */
1129         free(msg);
1130 }
1131
1132
1133 /*
1134  * Pre callback function for multipart/alternative
1135  *
1136  * NOTE: this differs from the standard behavior for a reason.  Normally when
1137  *       displaying multipart/alternative you want to show the _last_ usable
1138  *       format in the message.  Here we show the _first_ one, because it's
1139  *       usually text/plain.  Since this set of functions is designed for text
1140  *       output to non-MIME-aware clients, this is the desired behavior.
1141  *
1142  */
1143 void fixed_output_pre(char *name, char *filename, char *partnum, char *disp,
1144                 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
1145                 void *cbuserdata)
1146 {
1147         struct ma_info *ma;
1148         
1149         ma = (struct ma_info *)cbuserdata;
1150         lprintf(CTDL_DEBUG, "fixed_output_pre() type=<%s>\n", cbtype);  
1151         if (!strcasecmp(cbtype, "multipart/alternative")) {
1152                 ++ma->is_ma;
1153                 ma->did_print = 0;
1154         }
1155         if (!strcasecmp(cbtype, "message/rfc822")) {
1156                 ++ma->freeze;
1157         }
1158 }
1159
1160 /*
1161  * Post callback function for multipart/alternative
1162  */
1163 void fixed_output_post(char *name, char *filename, char *partnum, char *disp,
1164                 void *content, char *cbtype, char *cbcharset, size_t length,
1165                 char *encoding, void *cbuserdata)
1166 {
1167         struct ma_info *ma;
1168         
1169         ma = (struct ma_info *)cbuserdata;
1170         lprintf(CTDL_DEBUG, "fixed_output_post() type=<%s>\n", cbtype); 
1171         if (!strcasecmp(cbtype, "multipart/alternative")) {
1172                 --ma->is_ma;
1173                 ma->did_print = 0;
1174         }
1175         if (!strcasecmp(cbtype, "message/rfc822")) {
1176                 --ma->freeze;
1177         }
1178 }
1179
1180 /*
1181  * Inline callback function for mime parser that wants to display text
1182  */
1183 void fixed_output(char *name, char *filename, char *partnum, char *disp,
1184                 void *content, char *cbtype, char *cbcharset, size_t length,
1185                 char *encoding, void *cbuserdata)
1186 {
1187         char *ptr;
1188         char *wptr;
1189         size_t wlen;
1190         struct ma_info *ma;
1191
1192         ma = (struct ma_info *)cbuserdata;
1193
1194         lprintf(CTDL_DEBUG,
1195                 "fixed_output() part %s: %s (%s) (%ld bytes)\n",
1196                 partnum, filename, cbtype, (long)length);
1197
1198         /*
1199          * If we're in the middle of a multipart/alternative scope and
1200          * we've already printed another section, skip this one.
1201          */     
1202         if ( (ma->is_ma) && (ma->did_print) ) {
1203                 lprintf(CTDL_DEBUG, "Skipping part %s (%s)\n",
1204                         partnum, cbtype);
1205                 return;
1206         }
1207         ma->did_print = 1;
1208
1209         if ( (!strcasecmp(cbtype, "text/plain")) 
1210            || (IsEmptyStr(cbtype)) ) {
1211                 wptr = content;
1212                 if (length > 0) {
1213                         client_write(wptr, length);
1214                         if (wptr[length-1] != '\n') {
1215                                 cprintf("\n");
1216                         }
1217                 }
1218                 return;
1219         }
1220
1221         if (!strcasecmp(cbtype, "text/html")) {
1222                 ptr = html_to_ascii(content, length, 80, 0);
1223                 wlen = strlen(ptr);
1224                 client_write(ptr, wlen);
1225                 if (ptr[wlen-1] != '\n') {
1226                         cprintf("\n");
1227                 }
1228                 free(ptr);
1229                 return;
1230         }
1231
1232         if (ma->use_fo_hooks) {
1233                 if (PerformFixedOutputHooks(cbtype, content, length)) {
1234                 /* above function returns nonzero if it handled the part */
1235                         return;
1236                 }
1237         }
1238
1239         if (strncasecmp(cbtype, "multipart/", 10)) {
1240                 cprintf("Part %s: %s (%s) (%ld bytes)\r\n",
1241                         partnum, filename, cbtype, (long)length);
1242                 return;
1243         }
1244 }
1245
1246 /*
1247  * The client is elegant and sophisticated and wants to be choosy about
1248  * MIME content types, so figure out which multipart/alternative part
1249  * we're going to send.
1250  *
1251  * We use a system of weights.  When we find a part that matches one of the
1252  * MIME types we've declared as preferential, we can store it in ma->chosen_part
1253  * and then set ma->chosen_pref to that MIME type's position in our preference
1254  * list.  If we then hit another match, we only replace the first match if
1255  * the preference value is lower.
1256  */
1257 void choose_preferred(char *name, char *filename, char *partnum, char *disp,
1258                 void *content, char *cbtype, char *cbcharset, size_t length,
1259                 char *encoding, void *cbuserdata)
1260 {
1261         char buf[1024];
1262         int i;
1263         struct ma_info *ma;
1264         
1265         ma = (struct ma_info *)cbuserdata;
1266
1267         if (ma->is_ma > 0) {
1268                 for (i=0; i<num_tokens(CC->preferred_formats, '|'); ++i) {
1269                         extract_token(buf, CC->preferred_formats, i, '|', sizeof buf);
1270                         if ( (!strcasecmp(buf, cbtype)) && (!ma->freeze) ) {
1271                                 if (i < ma->chosen_pref) {
1272                                         safestrncpy(ma->chosen_part, partnum, sizeof ma->chosen_part);
1273                                         ma->chosen_pref = i;
1274                                 }
1275                         }
1276                 }
1277         }
1278 }
1279
1280 /*
1281  * Now that we've chosen our preferred part, output it.
1282  */
1283 void output_preferred(char *name, char *filename, char *partnum, char *disp,
1284                 void *content, char *cbtype, char *cbcharset, size_t length,
1285                 char *encoding, void *cbuserdata)
1286 {
1287         int i;
1288         char buf[128];
1289         int add_newline = 0;
1290         char *text_content;
1291         struct ma_info *ma;
1292         
1293         ma = (struct ma_info *)cbuserdata;
1294
1295         /* This is not the MIME part you're looking for... */
1296         if (strcasecmp(partnum, ma->chosen_part)) return;
1297
1298         /* If the content-type of this part is in our preferred formats
1299          * list, we can simply output it verbatim.
1300          */
1301         for (i=0; i<num_tokens(CC->preferred_formats, '|'); ++i) {
1302                 extract_token(buf, CC->preferred_formats, i, '|', sizeof buf);
1303                 if (!strcasecmp(buf, cbtype)) {
1304                         /* Yeah!  Go!  W00t!! */
1305
1306                         text_content = (char *)content;
1307                         if (text_content[length-1] != '\n') {
1308                                 ++add_newline;
1309                         }
1310                         cprintf("Content-type: %s", cbtype);
1311                         if (!IsEmptyStr(cbcharset)) {
1312                                 cprintf("; charset=%s", cbcharset);
1313                         }
1314                         cprintf("\nContent-length: %d\n",
1315                                 (int)(length + add_newline) );
1316                         if (!IsEmptyStr(encoding)) {
1317                                 cprintf("Content-transfer-encoding: %s\n", encoding);
1318                         }
1319                         else {
1320                                 cprintf("Content-transfer-encoding: 7bit\n");
1321                         }
1322                         cprintf("X-Citadel-MSG4-Partnum: %s\n", partnum);
1323                         cprintf("\n");
1324                         client_write(content, length);
1325                         if (add_newline) cprintf("\n");
1326                         return;
1327                 }
1328         }
1329
1330         /* No translations required or possible: output as text/plain */
1331         cprintf("Content-type: text/plain\n\n");
1332         fixed_output(name, filename, partnum, disp, content, cbtype, cbcharset,
1333                         length, encoding, cbuserdata);
1334 }
1335
1336
1337 struct encapmsg {
1338         char desired_section[64];
1339         char *msg;
1340         size_t msglen;
1341 };
1342
1343
1344 /*
1345  * Callback function for
1346  */
1347 void extract_encapsulated_message(char *name, char *filename, char *partnum, char *disp,
1348                    void *content, char *cbtype, char *cbcharset, size_t length,
1349                    char *encoding, void *cbuserdata)
1350 {
1351         struct encapmsg *encap;
1352
1353         encap = (struct encapmsg *)cbuserdata;
1354
1355         /* Only proceed if this is the desired section... */
1356         if (!strcasecmp(encap->desired_section, partnum)) {
1357                 encap->msglen = length;
1358                 encap->msg = malloc(length + 2);
1359                 memcpy(encap->msg, content, length);
1360                 return;
1361         }
1362
1363 }
1364
1365
1366
1367
1368 /*
1369  * Get a message off disk.  (returns om_* values found in msgbase.h)
1370  * 
1371  */
1372 int CtdlOutputMsg(long msg_num,         /* message number (local) to fetch */
1373                 int mode,               /* how would you like that message? */
1374                 int headers_only,       /* eschew the message body? */
1375                 int do_proto,           /* do Citadel protocol responses? */
1376                 int crlf,               /* Use CRLF newlines instead of LF? */
1377                 char *section           /* NULL or a message/rfc822 section */
1378 ) {
1379         struct CtdlMessage *TheMessage = NULL;
1380         int retcode = om_no_such_msg;
1381         struct encapmsg encap;
1382
1383         lprintf(CTDL_DEBUG, "CtdlOutputMsg() msgnum=%ld, mode=%d, section=%s\n", 
1384                 msg_num, mode,
1385                 (section ? section : "<>")
1386         );
1387
1388         if ((!(CC->logged_in)) && (!(CC->internal_pgm))) {
1389                 if (do_proto) cprintf("%d Not logged in.\n",
1390                         ERROR + NOT_LOGGED_IN);
1391                 return(om_not_logged_in);
1392         }
1393
1394         /* FIXME: check message id against msglist for this room */
1395
1396         /*
1397          * Fetch the message from disk.  If we're in any sort of headers
1398          * only mode, request that we don't even bother loading the body
1399          * into memory.
1400          */
1401         if ( (headers_only == HEADERS_FAST) || (headers_only == HEADERS_ONLY) ) {
1402                 TheMessage = CtdlFetchMessage(msg_num, 0);
1403         }
1404         else {
1405                 TheMessage = CtdlFetchMessage(msg_num, 1);
1406         }
1407
1408         if (TheMessage == NULL) {
1409                 if (do_proto) cprintf("%d Can't locate msg %ld on disk\n",
1410                         ERROR + MESSAGE_NOT_FOUND, msg_num);
1411                 return(om_no_such_msg);
1412         }
1413
1414         /* Here is the weird form of this command, to process only an
1415          * encapsulated message/rfc822 section.
1416          */
1417         if (section) if (!IsEmptyStr(section)) if (strcmp(section, "0")) {
1418                 memset(&encap, 0, sizeof encap);
1419                 safestrncpy(encap.desired_section, section, sizeof encap.desired_section);
1420                 mime_parser(TheMessage->cm_fields['M'],
1421                         NULL,
1422                         *extract_encapsulated_message,
1423                         NULL, NULL, (void *)&encap, 0
1424                 );
1425                 CtdlFreeMessage(TheMessage);
1426                 TheMessage = NULL;
1427
1428                 if (encap.msg) {
1429                         encap.msg[encap.msglen] = 0;
1430                         TheMessage = convert_internet_message(encap.msg);
1431                         encap.msg = NULL;       /* no free() here, TheMessage owns it now */
1432
1433                         /* Now we let it fall through to the bottom of this
1434                          * function, because TheMessage now contains the
1435                          * encapsulated message instead of the top-level
1436                          * message.  Isn't that neat?
1437                          */
1438
1439                 }
1440                 else {
1441                         if (do_proto) cprintf("%d msg %ld has no part %s\n",
1442                                 ERROR + MESSAGE_NOT_FOUND, msg_num, section);
1443                         retcode = om_no_such_msg;
1444                 }
1445
1446         }
1447
1448         /* Ok, output the message now */
1449         retcode = CtdlOutputPreLoadedMsg(
1450                 TheMessage, mode,
1451                 headers_only, do_proto, crlf);
1452         CtdlFreeMessage(TheMessage);
1453
1454         return(retcode);
1455 }
1456
1457
1458 /*
1459  * Get a message off disk.  (returns om_* values found in msgbase.h)
1460  * 
1461  */
1462 int CtdlOutputPreLoadedMsg(
1463                 struct CtdlMessage *TheMessage,
1464                 int mode,               /* how would you like that message? */
1465                 int headers_only,       /* eschew the message body? */
1466                 int do_proto,           /* do Citadel protocol responses? */
1467                 int crlf                /* Use CRLF newlines instead of LF? */
1468 ) {
1469         int i, k;
1470         char buf[SIZ];
1471         cit_uint8_t ch;
1472         char allkeys[30];
1473         char display_name[256];
1474         char *mptr;
1475         char *nl;       /* newline string */
1476         int suppress_f = 0;
1477         int subject_found = 0;
1478         struct ma_info ma;
1479
1480         /* Buffers needed for RFC822 translation.  These are all filled
1481          * using functions that are bounds-checked, and therefore we can
1482          * make them substantially smaller than SIZ.
1483          */
1484         char suser[100];
1485         char luser[100];
1486         char fuser[100];
1487         char snode[100];
1488         char lnode[100];
1489         char mid[100];
1490         char datestamp[100];
1491
1492         lprintf(CTDL_DEBUG, "CtdlOutputPreLoadedMsg(TheMessage=%s, %d, %d, %d, %d\n",
1493                 ((TheMessage == NULL) ? "NULL" : "not null"),
1494                 mode, headers_only, do_proto, crlf);
1495
1496         strcpy(mid, "unknown");
1497         nl = (crlf ? "\r\n" : "\n");
1498
1499         if (!is_valid_message(TheMessage)) {
1500                 lprintf(CTDL_ERR,
1501                         "ERROR: invalid preloaded message for output\n");
1502                 return(om_no_such_msg);
1503         }
1504
1505         /* Are we downloading a MIME component? */
1506         if (mode == MT_DOWNLOAD) {
1507                 if (TheMessage->cm_format_type != FMT_RFC822) {
1508                         if (do_proto)
1509                                 cprintf("%d This is not a MIME message.\n",
1510                                 ERROR + ILLEGAL_VALUE);
1511                 } else if (CC->download_fp != NULL) {
1512                         if (do_proto) cprintf(
1513                                 "%d You already have a download open.\n",
1514                                 ERROR + RESOURCE_BUSY);
1515                 } else {
1516                         /* Parse the message text component */
1517                         mptr = TheMessage->cm_fields['M'];
1518                         mime_parser(mptr, NULL, *mime_download, NULL, NULL, NULL, 0);
1519                         /* If there's no file open by this time, the requested
1520                          * section wasn't found, so print an error
1521                          */
1522                         if (CC->download_fp == NULL) {
1523                                 if (do_proto) cprintf(
1524                                         "%d Section %s not found.\n",
1525                                         ERROR + FILE_NOT_FOUND,
1526                                         CC->download_desired_section);
1527                         }
1528                 }
1529                 return((CC->download_fp != NULL) ? om_ok : om_mime_error);
1530         }
1531
1532         /* MT_SPEW_SECTION is like MT_DOWNLOAD except it outputs the whole MIME part
1533          * in a single server operation instead of opening a download file.
1534          */
1535         if (mode == MT_SPEW_SECTION) {
1536                 if (TheMessage->cm_format_type != FMT_RFC822) {
1537                         if (do_proto)
1538                                 cprintf("%d This is not a MIME message.\n",
1539                                 ERROR + ILLEGAL_VALUE);
1540                 } else {
1541                         /* Parse the message text component */
1542                         int found_it = 0;
1543
1544                         mptr = TheMessage->cm_fields['M'];
1545                         mime_parser(mptr, NULL, *mime_spew_section, NULL, NULL, (void *)&found_it, 0);
1546                         /* If section wasn't found, print an error
1547                          */
1548                         if (!found_it) {
1549                                 if (do_proto) cprintf(
1550                                         "%d Section %s not found.\n",
1551                                         ERROR + FILE_NOT_FOUND,
1552                                         CC->download_desired_section);
1553                         }
1554                 }
1555                 return((CC->download_fp != NULL) ? om_ok : om_mime_error);
1556         }
1557
1558         /* now for the user-mode message reading loops */
1559         if (do_proto) cprintf("%d msg:\n", LISTING_FOLLOWS);
1560
1561         /* Does the caller want to skip the headers? */
1562         if (headers_only == HEADERS_NONE) goto START_TEXT;
1563
1564         /* Tell the client which format type we're using. */
1565         if ( (mode == MT_CITADEL) && (do_proto) ) {
1566                 cprintf("type=%d\n", TheMessage->cm_format_type);
1567         }
1568
1569         /* nhdr=yes means that we're only displaying headers, no body */
1570         if ( (TheMessage->cm_anon_type == MES_ANONONLY)
1571            && (mode == MT_CITADEL)
1572            && (do_proto)
1573            ) {
1574                 cprintf("nhdr=yes\n");
1575         }
1576
1577         /* begin header processing loop for Citadel message format */
1578
1579         if ((mode == MT_CITADEL) || (mode == MT_MIME)) {
1580
1581                 safestrncpy(display_name, "<unknown>", sizeof display_name);
1582                 if (TheMessage->cm_fields['A']) {
1583                         strcpy(buf, TheMessage->cm_fields['A']);
1584                         if (TheMessage->cm_anon_type == MES_ANONONLY) {
1585                                 safestrncpy(display_name, "****", sizeof display_name);
1586                         }
1587                         else if (TheMessage->cm_anon_type == MES_ANONOPT) {
1588                                 safestrncpy(display_name, "anonymous", sizeof display_name);
1589                         }
1590                         else {
1591                                 safestrncpy(display_name, buf, sizeof display_name);
1592                         }
1593                         if ((is_room_aide())
1594                             && ((TheMessage->cm_anon_type == MES_ANONONLY)
1595                              || (TheMessage->cm_anon_type == MES_ANONOPT))) {
1596                                 size_t tmp = strlen(display_name);
1597                                 snprintf(&display_name[tmp],
1598                                          sizeof display_name - tmp,
1599                                          " [%s]", buf);
1600                         }
1601                 }
1602
1603                 /* Don't show Internet address for users on the
1604                  * local Citadel network.
1605                  */
1606                 suppress_f = 0;
1607                 if (TheMessage->cm_fields['N'] != NULL)
1608                    if (!IsEmptyStr(TheMessage->cm_fields['N']))
1609                       if (haschar(TheMessage->cm_fields['N'], '.') == 0) {
1610                         suppress_f = 1;
1611                 }
1612                 
1613                 /* Now spew the header fields in the order we like them. */
1614                 safestrncpy(allkeys, FORDER, sizeof allkeys);
1615                 for (i=0; i<strlen(allkeys); ++i) {
1616                         k = (int) allkeys[i];
1617                         if (k != 'M') {
1618                                 if ( (TheMessage->cm_fields[k] != NULL)
1619                                    && (msgkeys[k] != NULL) ) {
1620                                         if (k == 'A') {
1621                                                 if (do_proto) cprintf("%s=%s\n",
1622                                                         msgkeys[k],
1623                                                         display_name);
1624                                         }
1625                                         else if ((k == 'F') && (suppress_f)) {
1626                                                 /* do nothing */
1627                                         }
1628                                         /* Masquerade display name if needed */
1629                                         else {
1630                                                 if (do_proto) cprintf("%s=%s\n",
1631                                                         msgkeys[k],
1632                                                         TheMessage->cm_fields[k]
1633                                         );
1634                                         }
1635                                 }
1636                         }
1637                 }
1638
1639         }
1640
1641         /* begin header processing loop for RFC822 transfer format */
1642
1643         strcpy(suser, "");
1644         strcpy(luser, "");
1645         strcpy(fuser, "");
1646         strcpy(snode, NODENAME);
1647         strcpy(lnode, HUMANNODE);
1648         if (mode == MT_RFC822) {
1649                 for (i = 0; i < 256; ++i) {
1650                         if (TheMessage->cm_fields[i]) {
1651                                 mptr = TheMessage->cm_fields[i];
1652
1653                                 if (i == 'A') {
1654                                         safestrncpy(luser, mptr, sizeof luser);
1655                                         safestrncpy(suser, mptr, sizeof suser);
1656                                 }
1657                                 else if (i == 'Y') {
1658                                         cprintf("CC: %s%s", mptr, nl);
1659                                 }
1660                                 else if (i == 'P') {
1661                                         cprintf("Return-Path: %s%s", mptr, nl);
1662                                 }
1663                                 else if (i == 'V') {
1664                                         cprintf("Envelope-To: %s%s", mptr, nl);
1665                                 }
1666                                 else if (i == 'U') {
1667                                         cprintf("Subject: %s%s", mptr, nl);
1668                                         subject_found = 1;
1669                                 }
1670                                 else if (i == 'I')
1671                                         safestrncpy(mid, mptr, sizeof mid);
1672                                 else if (i == 'H')
1673                                         safestrncpy(lnode, mptr, sizeof lnode);
1674                                 else if (i == 'F')
1675                                         safestrncpy(fuser, mptr, sizeof fuser);
1676                                 /* else if (i == 'O')
1677                                         cprintf("X-Citadel-Room: %s%s",
1678                                                 mptr, nl); */
1679                                 else if (i == 'N')
1680                                         safestrncpy(snode, mptr, sizeof snode);
1681                                 else if (i == 'R')
1682                                         cprintf("To: %s%s", mptr, nl);
1683                                 else if (i == 'T') {
1684                                         datestring(datestamp, sizeof datestamp,
1685                                                 atol(mptr), DATESTRING_RFC822);
1686                                         cprintf("Date: %s%s", datestamp, nl);
1687                                 }
1688                         }
1689                 }
1690                 if (subject_found == 0) {
1691                         cprintf("Subject: (no subject)%s", nl);
1692                 }
1693         }
1694
1695         for (i=0; i<strlen(suser); ++i) {
1696                 suser[i] = tolower(suser[i]);
1697                 if (!isalnum(suser[i])) suser[i]='_';
1698         }
1699
1700         if (mode == MT_RFC822) {
1701                 if (!strcasecmp(snode, NODENAME)) {
1702                         safestrncpy(snode, FQDN, sizeof snode);
1703                 }
1704
1705                 /* Construct a fun message id */
1706                 cprintf("Message-ID: <%s", mid);
1707                 if (strchr(mid, '@')==NULL) {
1708                         cprintf("@%s", snode);
1709                 }
1710                 cprintf(">%s", nl);
1711
1712                 if (!is_room_aide() && (TheMessage->cm_anon_type == MES_ANONONLY)) {
1713                         cprintf("From: \"----\" <x@x.org>%s", nl);
1714                 }
1715                 else if (!is_room_aide() && (TheMessage->cm_anon_type == MES_ANONOPT)) {
1716                         cprintf("From: \"anonymous\" <x@x.org>%s", nl);
1717                 }
1718                 else if (strlen(fuser) > 0) {
1719                         cprintf("From: \"%s\" <%s>%s", luser, fuser, nl);
1720                 }
1721                 else {
1722                         cprintf("From: \"%s\" <%s@%s>%s", luser, suser, snode, nl);
1723                 }
1724
1725                 cprintf("Organization: %s%s", lnode, nl);
1726
1727                 /* Blank line signifying RFC822 end-of-headers */
1728                 if (TheMessage->cm_format_type != FMT_RFC822) {
1729                         cprintf("%s", nl);
1730                 }
1731         }
1732
1733         /* end header processing loop ... at this point, we're in the text */
1734 START_TEXT:
1735         if (headers_only == HEADERS_FAST) goto DONE;
1736         mptr = TheMessage->cm_fields['M'];
1737
1738         /* Tell the client about the MIME parts in this message */
1739         if (TheMessage->cm_format_type == FMT_RFC822) {
1740                 if ( (mode == MT_CITADEL) || (mode == MT_MIME) ) {
1741                         memset(&ma, 0, sizeof(struct ma_info));
1742                         mime_parser(mptr, NULL,
1743                                 (do_proto ? *list_this_part : NULL),
1744                                 (do_proto ? *list_this_pref : NULL),
1745                                 (do_proto ? *list_this_suff : NULL),
1746                                 (void *)&ma, 0);
1747                 }
1748                 else if (mode == MT_RFC822) {   /* unparsed RFC822 dump */
1749                         char *start_of_text = NULL;
1750                         start_of_text = strstr(mptr, "\n\r\n");
1751                         if (start_of_text == NULL) start_of_text = strstr(mptr, "\n\n");
1752                         if (start_of_text == NULL) start_of_text = mptr;
1753                         ++start_of_text;
1754                         start_of_text = strstr(start_of_text, "\n");
1755                         ++start_of_text;
1756
1757                         char outbuf[1024];
1758                         int outlen = 0;
1759                         int nllen = strlen(nl);
1760                         while (ch=*mptr, ch!=0) {
1761                                 if (ch==13) {
1762                                         /* do nothing */
1763                                 }
1764                                 else {
1765                                         if (
1766                                                 ((headers_only == HEADERS_NONE) && (mptr >= start_of_text))
1767                                            ||   ((headers_only == HEADERS_ONLY) && (mptr < start_of_text))
1768                                            ||   ((headers_only != HEADERS_NONE) && (headers_only != HEADERS_ONLY))
1769                                         ) {
1770                                                 if (ch == 10) {
1771                                                         sprintf(&outbuf[outlen], "%s", nl);
1772                                                         outlen += nllen;
1773                                                 }
1774                                                 else {
1775                                                         outbuf[outlen++] = ch;
1776                                                 }
1777                                         }
1778                                 }
1779                                 ++mptr;
1780                                 if (outlen > 1000) {
1781                                         client_write(outbuf, outlen);
1782                                         outlen = 0;
1783                                 }
1784                         }
1785                         if (outlen > 0) {
1786                                 client_write(outbuf, outlen);
1787                                 outlen = 0;
1788                         }
1789
1790                         goto DONE;
1791                 }
1792         }
1793
1794         if (headers_only == HEADERS_ONLY) {
1795                 goto DONE;
1796         }
1797
1798         /* signify start of msg text */
1799         if ( (mode == MT_CITADEL) || (mode == MT_MIME) ) {
1800                 if (do_proto) cprintf("text\n");
1801         }
1802
1803         /* If the format type on disk is 1 (fixed-format), then we want
1804          * everything to be output completely literally ... regardless of
1805          * what message transfer format is in use.
1806          */
1807         if (TheMessage->cm_format_type == FMT_FIXED) {
1808                 if (mode == MT_MIME) {
1809                         cprintf("Content-type: text/plain\n\n");
1810                 }
1811                 strcpy(buf, "");
1812                 while (ch = *mptr++, ch > 0) {
1813                         if (ch == 13)
1814                                 ch = 10;
1815                         if ((ch == 10) || (strlen(buf) > 250)) {
1816                                 cprintf("%s%s", buf, nl);
1817                                 strcpy(buf, "");
1818                         } else {
1819                                 buf[strlen(buf) + 1] = 0;
1820                                 buf[strlen(buf)] = ch;
1821                         }
1822                 }
1823                 if (!IsEmptyStr(buf))
1824                         cprintf("%s%s", buf, nl);
1825         }
1826
1827         /* If the message on disk is format 0 (Citadel vari-format), we
1828          * output using the formatter at 80 columns.  This is the final output
1829          * form if the transfer format is RFC822, but if the transfer format
1830          * is Citadel proprietary, it'll still work, because the indentation
1831          * for new paragraphs is correct and the client will reformat the
1832          * message to the reader's screen width.
1833          */
1834         if (TheMessage->cm_format_type == FMT_CITADEL) {
1835                 if (mode == MT_MIME) {
1836                         cprintf("Content-type: text/x-citadel-variformat\n\n");
1837                 }
1838                 memfmout(mptr, 0, nl);
1839         }
1840
1841         /* If the message on disk is format 4 (MIME), we've gotta hand it
1842          * off to the MIME parser.  The client has already been told that
1843          * this message is format 1 (fixed format), so the callback function
1844          * we use will display those parts as-is.
1845          */
1846         if (TheMessage->cm_format_type == FMT_RFC822) {
1847                 memset(&ma, 0, sizeof(struct ma_info));
1848
1849                 if (mode == MT_MIME) {
1850                         ma.use_fo_hooks = 0;
1851                         strcpy(ma.chosen_part, "1");
1852                         ma.chosen_pref = 9999;
1853                         mime_parser(mptr, NULL,
1854                                 *choose_preferred, *fixed_output_pre,
1855                                 *fixed_output_post, (void *)&ma, 0);
1856                         mime_parser(mptr, NULL,
1857                                 *output_preferred, NULL, NULL, (void *)&ma, 0);
1858                 }
1859                 else {
1860                         ma.use_fo_hooks = 1;
1861                         mime_parser(mptr, NULL,
1862                                 *fixed_output, *fixed_output_pre,
1863                                 *fixed_output_post, (void *)&ma, 0);
1864                 }
1865
1866         }
1867
1868 DONE:   /* now we're done */
1869         if (do_proto) cprintf("000\n");
1870         return(om_ok);
1871 }
1872
1873
1874
1875 /*
1876  * display a message (mode 0 - Citadel proprietary)
1877  */
1878 void cmd_msg0(char *cmdbuf)
1879 {
1880         long msgid;
1881         int headers_only = HEADERS_ALL;
1882
1883         msgid = extract_long(cmdbuf, 0);
1884         headers_only = extract_int(cmdbuf, 1);
1885
1886         CtdlOutputMsg(msgid, MT_CITADEL, headers_only, 1, 0, NULL);
1887         return;
1888 }
1889
1890
1891 /*
1892  * display a message (mode 2 - RFC822)
1893  */
1894 void cmd_msg2(char *cmdbuf)
1895 {
1896         long msgid;
1897         int headers_only = HEADERS_ALL;
1898
1899         msgid = extract_long(cmdbuf, 0);
1900         headers_only = extract_int(cmdbuf, 1);
1901
1902         CtdlOutputMsg(msgid, MT_RFC822, headers_only, 1, 1, NULL);
1903 }
1904
1905
1906
1907 /* 
1908  * display a message (mode 3 - IGnet raw format - internal programs only)
1909  */
1910 void cmd_msg3(char *cmdbuf)
1911 {
1912         long msgnum;
1913         struct CtdlMessage *msg = NULL;
1914         struct ser_ret smr;
1915
1916         if (CC->internal_pgm == 0) {
1917                 cprintf("%d This command is for internal programs only.\n",
1918                         ERROR + HIGHER_ACCESS_REQUIRED);
1919                 return;
1920         }
1921
1922         msgnum = extract_long(cmdbuf, 0);
1923         msg = CtdlFetchMessage(msgnum, 1);
1924         if (msg == NULL) {
1925                 cprintf("%d Message %ld not found.\n", 
1926                         ERROR + MESSAGE_NOT_FOUND, msgnum);
1927                 return;
1928         }
1929
1930         serialize_message(&smr, msg);
1931         CtdlFreeMessage(msg);
1932
1933         if (smr.len == 0) {
1934                 cprintf("%d Unable to serialize message\n",
1935                         ERROR + INTERNAL_ERROR);
1936                 return;
1937         }
1938
1939         cprintf("%d %ld\n", BINARY_FOLLOWS, (long)smr.len);
1940         client_write((char *)smr.ser, (int)smr.len);
1941         free(smr.ser);
1942 }
1943
1944
1945
1946 /* 
1947  * Display a message using MIME content types
1948  */
1949 void cmd_msg4(char *cmdbuf)
1950 {
1951         long msgid;
1952         char section[64];
1953
1954         msgid = extract_long(cmdbuf, 0);
1955         extract_token(section, cmdbuf, 1, '|', sizeof section);
1956         CtdlOutputMsg(msgid, MT_MIME, 0, 1, 0, (section[0] ? section : NULL) );
1957 }
1958
1959
1960
1961 /* 
1962  * Client tells us its preferred message format(s)
1963  */
1964 void cmd_msgp(char *cmdbuf)
1965 {
1966         safestrncpy(CC->preferred_formats, cmdbuf,
1967                         sizeof(CC->preferred_formats));
1968         cprintf("%d ok\n", CIT_OK);
1969 }
1970
1971
1972 /*
1973  * Open a component of a MIME message as a download file 
1974  */
1975 void cmd_opna(char *cmdbuf)
1976 {
1977         long msgid;
1978         char desired_section[128];
1979
1980         msgid = extract_long(cmdbuf, 0);
1981         extract_token(desired_section, cmdbuf, 1, '|', sizeof desired_section);
1982         safestrncpy(CC->download_desired_section, desired_section,
1983                 sizeof CC->download_desired_section);
1984         CtdlOutputMsg(msgid, MT_DOWNLOAD, 0, 1, 1, NULL);
1985 }                       
1986
1987
1988 /*
1989  * Open a component of a MIME message and transmit it all at once
1990  */
1991 void cmd_dlat(char *cmdbuf)
1992 {
1993         long msgid;
1994         char desired_section[128];
1995
1996         msgid = extract_long(cmdbuf, 0);
1997         extract_token(desired_section, cmdbuf, 1, '|', sizeof desired_section);
1998         safestrncpy(CC->download_desired_section, desired_section,
1999                 sizeof CC->download_desired_section);
2000         CtdlOutputMsg(msgid, MT_SPEW_SECTION, 0, 1, 1, NULL);
2001 }                       
2002
2003
2004 /*
2005  * Save one or more message pointers into a specified room
2006  * (Returns 0 for success, nonzero for failure)
2007  * roomname may be NULL to use the current room
2008  *
2009  * Note that the 'supplied_msg' field may be set to NULL, in which case
2010  * the message will be fetched from disk, by number, if we need to perform
2011  * replication checks.  This adds an additional database read, so if the
2012  * caller already has the message in memory then it should be supplied.  (Obviously
2013  * this mode of operation only works if we're saving a single message.)
2014  */
2015 int CtdlSaveMsgPointersInRoom(char *roomname, long newmsgidlist[], int num_newmsgs,
2016                                 int do_repl_check, struct CtdlMessage *supplied_msg)
2017 {
2018         int i, j, unique;
2019         char hold_rm[ROOMNAMELEN];
2020         struct cdbdata *cdbfr;
2021         int num_msgs;
2022         long *msglist;
2023         long highest_msg = 0L;
2024
2025         long msgid = 0;
2026         struct CtdlMessage *msg = NULL;
2027
2028         long *msgs_to_be_merged = NULL;
2029         int num_msgs_to_be_merged = 0;
2030
2031         lprintf(CTDL_DEBUG,
2032                 "CtdlSaveMsgPointersInRoom(room=%s, num_msgs=%d, repl=%d)\n",
2033                 roomname, num_newmsgs, do_repl_check);
2034
2035         strcpy(hold_rm, CC->room.QRname);
2036
2037         /* Sanity checks */
2038         if (newmsgidlist == NULL) return(ERROR + INTERNAL_ERROR);
2039         if (num_newmsgs < 1) return(ERROR + INTERNAL_ERROR);
2040         if (num_newmsgs > 1) supplied_msg = NULL;
2041
2042         /* Now the regular stuff */
2043         if (lgetroom(&CC->room,
2044            ((roomname != NULL) ? roomname : CC->room.QRname) )
2045            != 0) {
2046                 lprintf(CTDL_ERR, "No such room <%s>\n", roomname);
2047                 return(ERROR + ROOM_NOT_FOUND);
2048         }
2049
2050
2051         msgs_to_be_merged = malloc(sizeof(long) * num_newmsgs);
2052         num_msgs_to_be_merged = 0;
2053
2054
2055         cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
2056         if (cdbfr == NULL) {
2057                 msglist = NULL;
2058                 num_msgs = 0;
2059         } else {
2060                 msglist = (long *) cdbfr->ptr;
2061                 cdbfr->ptr = NULL;      /* CtdlSaveMsgPointerInRoom() now owns this memory */
2062                 num_msgs = cdbfr->len / sizeof(long);
2063                 cdb_free(cdbfr);
2064         }
2065
2066
2067         /* Create a list of msgid's which were supplied by the caller, but do
2068          * not already exist in the target room.  It is absolutely taboo to
2069          * have more than one reference to the same message in a room.
2070          */
2071         for (i=0; i<num_newmsgs; ++i) {
2072                 unique = 1;
2073                 if (num_msgs > 0) for (j=0; j<num_msgs; ++j) {
2074                         if (msglist[j] == newmsgidlist[i]) {
2075                                 unique = 0;
2076                         }
2077                 }
2078                 if (unique) {
2079                         msgs_to_be_merged[num_msgs_to_be_merged++] = newmsgidlist[i];
2080                 }
2081         }
2082
2083         lprintf(9, "%d unique messages to be merged\n", num_msgs_to_be_merged);
2084
2085         /*
2086          * Now merge the new messages
2087          */
2088         msglist = realloc(msglist, (sizeof(long) * (num_msgs + num_msgs_to_be_merged)) );
2089         if (msglist == NULL) {
2090                 lprintf(CTDL_ALERT, "ERROR: can't realloc message list!\n");
2091         }
2092         memcpy(&msglist[num_msgs], msgs_to_be_merged, (sizeof(long) * num_msgs_to_be_merged) );
2093         num_msgs += num_msgs_to_be_merged;
2094
2095         /* Sort the message list, so all the msgid's are in order */
2096         num_msgs = sort_msglist(msglist, num_msgs);
2097
2098         /* Determine the highest message number */
2099         highest_msg = msglist[num_msgs - 1];
2100
2101         /* Write it back to disk. */
2102         cdb_store(CDB_MSGLISTS, &CC->room.QRnumber, (int)sizeof(long),
2103                   msglist, (int)(num_msgs * sizeof(long)));
2104
2105         /* Free up the memory we used. */
2106         free(msglist);
2107
2108         /* Update the highest-message pointer and unlock the room. */
2109         CC->room.QRhighest = highest_msg;
2110         lputroom(&CC->room);
2111
2112         /* Perform replication checks if necessary */
2113         if ( (DoesThisRoomNeedEuidIndexing(&CC->room)) && (do_repl_check) ) {
2114                 lprintf(CTDL_DEBUG, "CtdlSaveMsgPointerInRoom() doing repl checks\n");
2115
2116                 for (i=0; i<num_msgs_to_be_merged; ++i) {
2117                         msgid = msgs_to_be_merged[i];
2118         
2119                         if (supplied_msg != NULL) {
2120                                 msg = supplied_msg;
2121                         }
2122                         else {
2123                                 msg = CtdlFetchMessage(msgid, 0);
2124                         }
2125         
2126                         if (msg != NULL) {
2127                                 ReplicationChecks(msg);
2128                 
2129                                 /* If the message has an Exclusive ID, index that... */
2130                                 if (msg->cm_fields['E'] != NULL) {
2131                                         index_message_by_euid(msg->cm_fields['E'], &CC->room, msgid);
2132                                 }
2133
2134                                 /* Free up the memory we may have allocated */
2135                                 if (msg != supplied_msg) {
2136                                         CtdlFreeMessage(msg);
2137                                 }
2138                         }
2139         
2140                 }
2141         }
2142
2143         else {
2144                 lprintf(CTDL_DEBUG, "CtdlSaveMsgPointerInRoom() skips repl checks\n");
2145         }
2146
2147         /* Submit this room for processing by hooks */
2148         PerformRoomHooks(&CC->room);
2149
2150         /* Go back to the room we were in before we wandered here... */
2151         getroom(&CC->room, hold_rm);
2152
2153         /* Bump the reference count for all messages which were merged */
2154         for (i=0; i<num_msgs_to_be_merged; ++i) {
2155                 AdjRefCount(msgs_to_be_merged[i], +1);
2156         }
2157
2158         /* Free up memory... */
2159         if (msgs_to_be_merged != NULL) {
2160                 free(msgs_to_be_merged);
2161         }
2162
2163         /* Return success. */
2164         return (0);
2165 }
2166
2167
2168 /*
2169  * This is the same as CtdlSaveMsgPointersInRoom() but it only accepts
2170  * a single message.
2171  */
2172 int CtdlSaveMsgPointerInRoom(char *roomname, long msgid,
2173                         int do_repl_check, struct CtdlMessage *supplied_msg)
2174 {
2175         return CtdlSaveMsgPointersInRoom(roomname, &msgid, 1, do_repl_check, supplied_msg);
2176 }
2177
2178
2179
2180
2181 /*
2182  * Message base operation to save a new message to the message store
2183  * (returns new message number)
2184  *
2185  * This is the back end for CtdlSubmitMsg() and should not be directly
2186  * called by server-side modules.
2187  *
2188  */
2189 long send_message(struct CtdlMessage *msg) {
2190         long newmsgid;
2191         long retval;
2192         char msgidbuf[256];
2193         struct ser_ret smr;
2194         int is_bigmsg = 0;
2195         char *holdM = NULL;
2196
2197         /* Get a new message number */
2198         newmsgid = get_new_message_number();
2199         snprintf(msgidbuf, sizeof msgidbuf, "%010ld@%s", newmsgid, config.c_fqdn);
2200
2201         /* Generate an ID if we don't have one already */
2202         if (msg->cm_fields['I']==NULL) {
2203                 msg->cm_fields['I'] = strdup(msgidbuf);
2204         }
2205
2206         /* If the message is big, set its body aside for storage elsewhere */
2207         if (msg->cm_fields['M'] != NULL) {
2208                 if (strlen(msg->cm_fields['M']) > BIGMSG) {
2209                         is_bigmsg = 1;
2210                         holdM = msg->cm_fields['M'];
2211                         msg->cm_fields['M'] = NULL;
2212                 }
2213         }
2214
2215         /* Serialize our data structure for storage in the database */  
2216         serialize_message(&smr, msg);
2217
2218         if (is_bigmsg) {
2219                 msg->cm_fields['M'] = holdM;
2220         }
2221
2222         if (smr.len == 0) {
2223                 cprintf("%d Unable to serialize message\n",
2224                         ERROR + INTERNAL_ERROR);
2225                 return (-1L);
2226         }
2227
2228         /* Write our little bundle of joy into the message base */
2229         if (cdb_store(CDB_MSGMAIN, &newmsgid, (int)sizeof(long),
2230                       smr.ser, smr.len) < 0) {
2231                 lprintf(CTDL_ERR, "Can't store message\n");
2232                 retval = 0L;
2233         } else {
2234                 if (is_bigmsg) {
2235                         cdb_store(CDB_BIGMSGS,
2236                                 &newmsgid,
2237                                 (int)sizeof(long),
2238                                 holdM,
2239                                 (strlen(holdM) + 1)
2240                         );
2241                 }
2242                 retval = newmsgid;
2243         }
2244
2245         /* Free the memory we used for the serialized message */
2246         free(smr.ser);
2247
2248         /* Return the *local* message ID to the caller
2249          * (even if we're storing an incoming network message)
2250          */
2251         return(retval);
2252 }
2253
2254
2255
2256 /*
2257  * Serialize a struct CtdlMessage into the format used on disk and network.
2258  * 
2259  * This function loads up a "struct ser_ret" (defined in server.h) which
2260  * contains the length of the serialized message and a pointer to the
2261  * serialized message in memory.  THE LATTER MUST BE FREED BY THE CALLER.
2262  */
2263 void serialize_message(struct ser_ret *ret,             /* return values */
2264                         struct CtdlMessage *msg)        /* unserialized msg */
2265 {
2266         size_t wlen, fieldlen;
2267         int i;
2268         static char *forder = FORDER;
2269
2270         /*
2271          * Check for valid message format
2272          */
2273         if (is_valid_message(msg) == 0) {
2274                 lprintf(CTDL_ERR, "serialize_message() aborting due to invalid message\n");
2275                 ret->len = 0;
2276                 ret->ser = NULL;
2277                 return;
2278         }
2279
2280         ret->len = 3;
2281         for (i=0; i<26; ++i) if (msg->cm_fields[(int)forder[i]] != NULL)
2282                 ret->len = ret->len +
2283                         strlen(msg->cm_fields[(int)forder[i]]) + 2;
2284
2285         ret->ser = malloc(ret->len);
2286         if (ret->ser == NULL) {
2287                 lprintf(CTDL_ERR, "serialize_message() malloc(%ld) failed: %s\n",
2288                         (long)ret->len, strerror(errno));
2289                 ret->len = 0;
2290                 ret->ser = NULL;
2291                 return;
2292         }
2293
2294         ret->ser[0] = 0xFF;
2295         ret->ser[1] = msg->cm_anon_type;
2296         ret->ser[2] = msg->cm_format_type;
2297         wlen = 3;
2298
2299         for (i=0; i<26; ++i) if (msg->cm_fields[(int)forder[i]] != NULL) {
2300                 fieldlen = strlen(msg->cm_fields[(int)forder[i]]);
2301                 ret->ser[wlen++] = (char)forder[i];
2302                 safestrncpy((char *)&ret->ser[wlen], msg->cm_fields[(int)forder[i]], fieldlen+1);
2303                 wlen = wlen + fieldlen + 1;
2304         }
2305         if (ret->len != wlen) lprintf(CTDL_ERR, "ERROR: len=%ld wlen=%ld\n",
2306                 (long)ret->len, (long)wlen);
2307
2308         return;
2309 }
2310
2311
2312
2313 /*
2314  * Check to see if any messages already exist in the current room which
2315  * carry the same Exclusive ID as this one.  If any are found, delete them.
2316  */
2317 void ReplicationChecks(struct CtdlMessage *msg) {
2318         long old_msgnum = (-1L);
2319
2320         if (DoesThisRoomNeedEuidIndexing(&CC->room) == 0) return;
2321
2322         lprintf(CTDL_DEBUG, "Performing replication checks in <%s>\n",
2323                 CC->room.QRname);
2324
2325         /* No exclusive id?  Don't do anything. */
2326         if (msg == NULL) return;
2327         if (msg->cm_fields['E'] == NULL) return;
2328         if (IsEmptyStr(msg->cm_fields['E'])) return;
2329         /*lprintf(CTDL_DEBUG, "Exclusive ID: <%s> for room <%s>\n",
2330                 msg->cm_fields['E'], CC->room.QRname);*/
2331
2332         old_msgnum = locate_message_by_euid(msg->cm_fields['E'], &CC->room);
2333         if (old_msgnum > 0L) {
2334                 lprintf(CTDL_DEBUG, "ReplicationChecks() replacing message %ld\n", old_msgnum);
2335                 CtdlDeleteMessages(CC->room.QRname, &old_msgnum, 1, "");
2336         }
2337 }
2338
2339
2340
2341 /*
2342  * Save a message to disk and submit it into the delivery system.
2343  */
2344 long CtdlSubmitMsg(struct CtdlMessage *msg,     /* message to save */
2345                 struct recptypes *recps,        /* recipients (if mail) */
2346                 char *force                     /* force a particular room? */
2347 ) {
2348         char submit_filename[128];
2349         char generated_timestamp[32];
2350         char hold_rm[ROOMNAMELEN];
2351         char actual_rm[ROOMNAMELEN];
2352         char force_room[ROOMNAMELEN];
2353         char content_type[SIZ];                 /* We have to learn this */
2354         char recipient[SIZ];
2355         long newmsgid;
2356         char *mptr = NULL;
2357         struct ctdluser userbuf;
2358         int a, i;
2359         struct MetaData smi;
2360         FILE *network_fp = NULL;
2361         static int seqnum = 1;
2362         struct CtdlMessage *imsg = NULL;
2363         char *instr = NULL;
2364         size_t instr_alloc = 0;
2365         struct ser_ret smr;
2366         char *hold_R, *hold_D;
2367         char *collected_addresses = NULL;
2368         struct addresses_to_be_filed *aptr = NULL;
2369         char *saved_rfc822_version = NULL;
2370         int qualified_for_journaling = 0;
2371
2372         lprintf(CTDL_DEBUG, "CtdlSubmitMsg() called\n");
2373         if (is_valid_message(msg) == 0) return(-1);     /* self check */
2374
2375         /* If this message has no timestamp, we take the liberty of
2376          * giving it one, right now.
2377          */
2378         if (msg->cm_fields['T'] == NULL) {
2379                 snprintf(generated_timestamp, sizeof generated_timestamp, "%ld", (long)time(NULL));
2380                 msg->cm_fields['T'] = strdup(generated_timestamp);
2381         }
2382
2383         /* If this message has no path, we generate one.
2384          */
2385         if (msg->cm_fields['P'] == NULL) {
2386                 if (msg->cm_fields['A'] != NULL) {
2387                         msg->cm_fields['P'] = strdup(msg->cm_fields['A']);
2388                         for (a=0; a<strlen(msg->cm_fields['P']); ++a) {
2389                                 if (isspace(msg->cm_fields['P'][a])) {
2390                                         msg->cm_fields['P'][a] = ' ';
2391                                 }
2392                         }
2393                 }
2394                 else {
2395                         msg->cm_fields['P'] = strdup("unknown");
2396                 }
2397         }
2398
2399         if (force == NULL) {
2400                 strcpy(force_room, "");
2401         }
2402         else {
2403                 strcpy(force_room, force);
2404         }
2405
2406         /* Learn about what's inside, because it's what's inside that counts */
2407         if (msg->cm_fields['M'] == NULL) {
2408                 lprintf(CTDL_ERR, "ERROR: attempt to save message with NULL body\n");
2409                 return(-2);
2410         }
2411
2412         switch (msg->cm_format_type) {
2413         case 0:
2414                 strcpy(content_type, "text/x-citadel-variformat");
2415                 break;
2416         case 1:
2417                 strcpy(content_type, "text/plain");
2418                 break;
2419         case 4:
2420                 strcpy(content_type, "text/plain");
2421                 mptr = bmstrcasestr(msg->cm_fields['M'], "Content-type:");
2422                 if (mptr != NULL) {
2423                         safestrncpy(content_type, &mptr[13], sizeof content_type);
2424                         striplt(content_type);
2425                         for (a = 0; a < strlen(content_type); ++a) {
2426                                 if ((content_type[a] == ';')
2427                                     || (content_type[a] == ' ')
2428                                     || (content_type[a] == 13)
2429                                     || (content_type[a] == 10)) {
2430                                         content_type[a] = 0;
2431                                 }
2432                         }
2433                 }
2434         }
2435
2436         /* Goto the correct room */
2437         lprintf(CTDL_DEBUG, "Selected room %s\n", (recps) ? CC->room.QRname : SENTITEMS);
2438         strcpy(hold_rm, CC->room.QRname);
2439         strcpy(actual_rm, CC->room.QRname);
2440         if (recps != NULL) {
2441                 strcpy(actual_rm, SENTITEMS);
2442         }
2443
2444         /* If the user is a twit, move to the twit room for posting */
2445         if (TWITDETECT) {
2446                 if (CC->user.axlevel == 2) {
2447                         strcpy(hold_rm, actual_rm);
2448                         strcpy(actual_rm, config.c_twitroom);
2449                         lprintf(CTDL_DEBUG, "Diverting to twit room\n");
2450                 }
2451         }
2452
2453         /* ...or if this message is destined for Aide> then go there. */
2454         if (!IsEmptyStr(force_room)) {
2455                 strcpy(actual_rm, force_room);
2456         }
2457
2458         lprintf(CTDL_DEBUG, "Final selection: %s\n", actual_rm);
2459         if (strcasecmp(actual_rm, CC->room.QRname)) {
2460                 /* getroom(&CC->room, actual_rm); */
2461                 usergoto(actual_rm, 0, 1, NULL, NULL);
2462         }
2463
2464         /*
2465          * If this message has no O (room) field, generate one.
2466          */
2467         if (msg->cm_fields['O'] == NULL) {
2468                 msg->cm_fields['O'] = strdup(CC->room.QRname);
2469         }
2470
2471         /* Perform "before save" hooks (aborting if any return nonzero) */
2472         lprintf(CTDL_DEBUG, "Performing before-save hooks\n");
2473         if (PerformMessageHooks(msg, EVT_BEFORESAVE) > 0) return(-3);
2474
2475         /*
2476          * If this message has an Exclusive ID, and the room is replication
2477          * checking enabled, then do replication checks.
2478          */
2479         if (DoesThisRoomNeedEuidIndexing(&CC->room)) {
2480                 ReplicationChecks(msg);
2481         }
2482
2483         /* Save it to disk */
2484         lprintf(CTDL_DEBUG, "Saving to disk\n");
2485         newmsgid = send_message(msg);
2486         if (newmsgid <= 0L) return(-5);
2487
2488         /* Write a supplemental message info record.  This doesn't have to
2489          * be a critical section because nobody else knows about this message
2490          * yet.
2491          */
2492         lprintf(CTDL_DEBUG, "Creating MetaData record\n");
2493         memset(&smi, 0, sizeof(struct MetaData));
2494         smi.meta_msgnum = newmsgid;
2495         smi.meta_refcount = 0;
2496         safestrncpy(smi.meta_content_type, content_type,
2497                         sizeof smi.meta_content_type);
2498
2499         /*
2500          * Measure how big this message will be when rendered as RFC822.
2501          * We do this for two reasons:
2502          * 1. We need the RFC822 length for the new metadata record, so the
2503          *    POP and IMAP services don't have to calculate message lengths
2504          *    while the user is waiting (multiplied by potentially hundreds
2505          *    or thousands of messages).
2506          * 2. If journaling is enabled, we will need an RFC822 version of the
2507          *    message to attach to the journalized copy.
2508          */
2509         if (CC->redirect_buffer != NULL) {
2510                 lprintf(CTDL_ALERT, "CC->redirect_buffer is not NULL during message submission!\n");
2511                 abort();
2512         }
2513         CC->redirect_buffer = malloc(SIZ);
2514         CC->redirect_len = 0;
2515         CC->redirect_alloc = SIZ;
2516         CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_ALL, 0, 1);
2517         smi.meta_rfc822_length = CC->redirect_len;
2518         saved_rfc822_version = CC->redirect_buffer;
2519         CC->redirect_buffer = NULL;
2520         CC->redirect_len = 0;
2521         CC->redirect_alloc = 0;
2522
2523         PutMetaData(&smi);
2524
2525         /* Now figure out where to store the pointers */
2526         lprintf(CTDL_DEBUG, "Storing pointers\n");
2527
2528         /* If this is being done by the networker delivering a private
2529          * message, we want to BYPASS saving the sender's copy (because there
2530          * is no local sender; it would otherwise go to the Trashcan).
2531          */
2532         if ((!CC->internal_pgm) || (recps == NULL)) {
2533                 if (CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 1, msg) != 0) {
2534                         lprintf(CTDL_ERR, "ERROR saving message pointer!\n");
2535                         CtdlSaveMsgPointerInRoom(config.c_aideroom, newmsgid, 0, msg);
2536                 }
2537         }
2538
2539         /* For internet mail, drop a copy in the outbound queue room */
2540         if (recps != NULL)
2541          if (recps->num_internet > 0) {
2542                 CtdlSaveMsgPointerInRoom(SMTP_SPOOLOUT_ROOM, newmsgid, 0, msg);
2543         }
2544
2545         /* If other rooms are specified, drop them there too. */
2546         if (recps != NULL)
2547          if (recps->num_room > 0)
2548           for (i=0; i<num_tokens(recps->recp_room, '|'); ++i) {
2549                 extract_token(recipient, recps->recp_room, i,
2550                                         '|', sizeof recipient);
2551                 lprintf(CTDL_DEBUG, "Delivering to room <%s>\n", recipient);
2552                 CtdlSaveMsgPointerInRoom(recipient, newmsgid, 0, msg);
2553         }
2554
2555         /* Bump this user's messages posted counter. */
2556         lprintf(CTDL_DEBUG, "Updating user\n");
2557         lgetuser(&CC->user, CC->curr_user);
2558         CC->user.posted = CC->user.posted + 1;
2559         lputuser(&CC->user);
2560
2561         /* If this is private, local mail, make a copy in the
2562          * recipient's mailbox and bump the reference count.
2563          */
2564         if (recps != NULL)
2565          if (recps->num_local > 0)
2566           for (i=0; i<num_tokens(recps->recp_local, '|'); ++i) {
2567                 extract_token(recipient, recps->recp_local, i,
2568                                         '|', sizeof recipient);
2569                 lprintf(CTDL_DEBUG, "Delivering private local mail to <%s>\n",
2570                         recipient);
2571                 if (getuser(&userbuf, recipient) == 0) {
2572                         // Add a flag so the Funambol module knows its mail
2573                         msg->cm_fields['W'] = strdup(recipient);
2574                         MailboxName(actual_rm, sizeof actual_rm, &userbuf, MAILROOM);
2575                         CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 0, msg);
2576                         BumpNewMailCounter(userbuf.usernum);
2577                         if (!IsEmptyStr(config.c_funambol_host)) {
2578                         /* Generate a instruction message for the Funambol notification
2579                          * server, in the same style as the SMTP queue
2580                          */
2581                            instr_alloc = 1024;
2582                            instr = malloc(instr_alloc);
2583                            snprintf(instr, instr_alloc,
2584                         "Content-type: %s\n\nmsgid|%ld\nsubmitted|%ld\n"
2585                         "bounceto|%s@%s\n",
2586                         SPOOLMIME, newmsgid, (long)time(NULL),
2587                         msg->cm_fields['A'], msg->cm_fields['N']
2588                         );
2589
2590                            imsg = malloc(sizeof(struct CtdlMessage));
2591                            memset(imsg, 0, sizeof(struct CtdlMessage));
2592                            imsg->cm_magic = CTDLMESSAGE_MAGIC;
2593                            imsg->cm_anon_type = MES_NORMAL;
2594                            imsg->cm_format_type = FMT_RFC822;
2595                            imsg->cm_fields['A'] = strdup("Citadel");
2596                            imsg->cm_fields['J'] = strdup("do not journal");
2597                            imsg->cm_fields['M'] = instr;        /* imsg owns this memory now */
2598                            imsg->cm_fields['W'] = strdup(recipient);
2599                            CtdlSubmitMsg(imsg, NULL, FNBL_QUEUE_ROOM);
2600                            CtdlFreeMessage(imsg);
2601                         }
2602                 }
2603                 else {
2604                         lprintf(CTDL_DEBUG, "No user <%s>\n", recipient);
2605                         CtdlSaveMsgPointerInRoom(config.c_aideroom,
2606                                 newmsgid, 0, msg);
2607                 }
2608         }
2609
2610         /* Perform "after save" hooks */
2611         lprintf(CTDL_DEBUG, "Performing after-save hooks\n");
2612         PerformMessageHooks(msg, EVT_AFTERSAVE);
2613
2614         /* For IGnet mail, we have to save a new copy into the spooler for
2615          * each recipient, with the R and D fields set to the recipient and
2616          * destination-node.  This has two ugly side effects: all other
2617          * recipients end up being unlisted in this recipient's copy of the
2618          * message, and it has to deliver multiple messages to the same
2619          * node.  We'll revisit this again in a year or so when everyone has
2620          * a network spool receiver that can handle the new style messages.
2621          */
2622         if (recps != NULL)
2623          if (recps->num_ignet > 0)
2624           for (i=0; i<num_tokens(recps->recp_ignet, '|'); ++i) {
2625                 extract_token(recipient, recps->recp_ignet, i,
2626                                 '|', sizeof recipient);
2627
2628                 hold_R = msg->cm_fields['R'];
2629                 hold_D = msg->cm_fields['D'];
2630                 msg->cm_fields['R'] = malloc(SIZ);
2631                 msg->cm_fields['D'] = malloc(128);
2632                 extract_token(msg->cm_fields['R'], recipient, 0, '@', SIZ);
2633                 extract_token(msg->cm_fields['D'], recipient, 1, '@', 128);
2634                 
2635                 serialize_message(&smr, msg);
2636                 if (smr.len > 0) {
2637                         snprintf(submit_filename, sizeof submit_filename,
2638                                          "%s/netmail.%04lx.%04x.%04x",
2639                                          ctdl_netin_dir,
2640                                          (long) getpid(), CC->cs_pid, ++seqnum);
2641                         network_fp = fopen(submit_filename, "wb+");
2642                         if (network_fp != NULL) {
2643                                 fwrite(smr.ser, smr.len, 1, network_fp);
2644                                 fclose(network_fp);
2645                         }
2646                         free(smr.ser);
2647                 }
2648
2649                 free(msg->cm_fields['R']);
2650                 free(msg->cm_fields['D']);
2651                 msg->cm_fields['R'] = hold_R;
2652                 msg->cm_fields['D'] = hold_D;
2653         }
2654
2655         /* Go back to the room we started from */
2656         lprintf(CTDL_DEBUG, "Returning to original room %s\n", hold_rm);
2657         if (strcasecmp(hold_rm, CC->room.QRname))
2658                 usergoto(hold_rm, 0, 1, NULL, NULL);
2659
2660         /* For internet mail, generate delivery instructions.
2661          * Yes, this is recursive.  Deal with it.  Infinite recursion does
2662          * not happen because the delivery instructions message does not
2663          * contain a recipient.
2664          */
2665         if (recps != NULL)
2666          if (recps->num_internet > 0) {
2667                 lprintf(CTDL_DEBUG, "Generating delivery instructions\n");
2668                 instr_alloc = 1024;
2669                 instr = malloc(instr_alloc);
2670                 snprintf(instr, instr_alloc,
2671                         "Content-type: %s\n\nmsgid|%ld\nsubmitted|%ld\n"
2672                         "bounceto|%s@%s\n",
2673                         SPOOLMIME, newmsgid, (long)time(NULL),
2674                         msg->cm_fields['A'], msg->cm_fields['N']
2675                 );
2676
2677                 for (i=0; i<num_tokens(recps->recp_internet, '|'); ++i) {
2678                         size_t tmp = strlen(instr);
2679                         extract_token(recipient, recps->recp_internet, i, '|', sizeof recipient);
2680                         if ((tmp + strlen(recipient) + 32) > instr_alloc) {
2681                                 instr_alloc = instr_alloc * 2;
2682                                 instr = realloc(instr, instr_alloc);
2683                         }
2684                         snprintf(&instr[tmp], instr_alloc - tmp, "remote|%s|0||\n", recipient);
2685                 }
2686
2687                 imsg = malloc(sizeof(struct CtdlMessage));
2688                 memset(imsg, 0, sizeof(struct CtdlMessage));
2689                 imsg->cm_magic = CTDLMESSAGE_MAGIC;
2690                 imsg->cm_anon_type = MES_NORMAL;
2691                 imsg->cm_format_type = FMT_RFC822;
2692                 imsg->cm_fields['A'] = strdup("Citadel");
2693                 imsg->cm_fields['J'] = strdup("do not journal");
2694                 imsg->cm_fields['M'] = instr;   /* imsg owns this memory now */
2695                 CtdlSubmitMsg(imsg, NULL, SMTP_SPOOLOUT_ROOM);
2696                 CtdlFreeMessage(imsg);
2697         }
2698
2699         /*
2700          * Any addresses to harvest for someone's address book?
2701          */
2702         if ( (CC->logged_in) && (recps != NULL) ) {
2703                 collected_addresses = harvest_collected_addresses(msg);
2704         }
2705
2706         if (collected_addresses != NULL) {
2707                 begin_critical_section(S_ATBF);
2708                 aptr = (struct addresses_to_be_filed *)
2709                         malloc(sizeof(struct addresses_to_be_filed));
2710                 aptr->next = atbf;
2711                 MailboxName(actual_rm, sizeof actual_rm,
2712                         &CC->user, USERCONTACTSROOM);
2713                 aptr->roomname = strdup(actual_rm);
2714                 aptr->collected_addresses = collected_addresses;
2715                 atbf = aptr;
2716                 end_critical_section(S_ATBF);
2717         }
2718
2719         /*
2720          * Determine whether this message qualifies for journaling.
2721          */
2722         if (msg->cm_fields['J'] != NULL) {
2723                 qualified_for_journaling = 0;
2724         }
2725         else {
2726                 if (recps == NULL) {
2727                         qualified_for_journaling = config.c_journal_pubmsgs;
2728                 }
2729                 else if (recps->num_local + recps->num_ignet + recps->num_internet > 0) {
2730                         qualified_for_journaling = config.c_journal_email;
2731                 }
2732                 else {
2733                         qualified_for_journaling = config.c_journal_pubmsgs;
2734                 }
2735         }
2736
2737         /*
2738          * Do we have to perform journaling?  If so, hand off the saved
2739          * RFC822 version will be handed off to the journaler for background
2740          * submit.  Otherwise, we have to free the memory ourselves.
2741          */
2742         if (saved_rfc822_version != NULL) {
2743                 if (qualified_for_journaling) {
2744                         JournalBackgroundSubmit(msg, saved_rfc822_version, recps);
2745                 }
2746                 else {
2747                         free(saved_rfc822_version);
2748                 }
2749         }
2750
2751         /* Done. */
2752         return(newmsgid);
2753 }
2754
2755
2756
2757
2758
2759 /*
2760  * Convenience function for generating small administrative messages.
2761  */
2762 void quickie_message(char *from, char *fromaddr, char *to, char *room, char *text, 
2763                         int format_type, char *subject)
2764 {
2765         struct CtdlMessage *msg;
2766         struct recptypes *recp = NULL;
2767
2768         msg = malloc(sizeof(struct CtdlMessage));
2769         memset(msg, 0, sizeof(struct CtdlMessage));
2770         msg->cm_magic = CTDLMESSAGE_MAGIC;
2771         msg->cm_anon_type = MES_NORMAL;
2772         msg->cm_format_type = format_type;
2773
2774         if (from != NULL) {
2775                 msg->cm_fields['A'] = strdup(from);
2776         }
2777         else if (fromaddr != NULL) {
2778                 msg->cm_fields['A'] = strdup(fromaddr);
2779                 if (strchr(msg->cm_fields['A'], '@')) {
2780                         *strchr(msg->cm_fields['A'], '@') = 0;
2781                 }
2782         }
2783         else {
2784                 msg->cm_fields['A'] = strdup("Citadel");
2785         }
2786
2787         if (fromaddr != NULL) msg->cm_fields['F'] = strdup(fromaddr);
2788         if (room != NULL) msg->cm_fields['O'] = strdup(room);
2789         msg->cm_fields['N'] = strdup(NODENAME);
2790         if (to != NULL) {
2791                 msg->cm_fields['R'] = strdup(to);
2792                 recp = validate_recipients(to);
2793         }
2794         if (subject != NULL) {
2795                 msg->cm_fields['U'] = strdup(subject);
2796         }
2797         msg->cm_fields['M'] = strdup(text);
2798
2799         CtdlSubmitMsg(msg, recp, room);
2800         CtdlFreeMessage(msg);
2801         if (recp != NULL) free_recipients(recp);
2802 }
2803
2804
2805
2806 /*
2807  * Back end function used by CtdlMakeMessage() and similar functions
2808  */
2809 char *CtdlReadMessageBody(char *terminator,     /* token signalling EOT */
2810                         size_t maxlen,          /* maximum message length */
2811                         char *exist,            /* if non-null, append to it;
2812                                                    exist is ALWAYS freed  */
2813                         int crlf                /* CRLF newlines instead of LF */
2814                         ) {
2815         char buf[1024];
2816         int linelen;
2817         size_t message_len = 0;
2818         size_t buffer_len = 0;
2819         char *ptr;
2820         char *m;
2821         int flushing = 0;
2822         int finished = 0;
2823         int dotdot = 0;
2824
2825         if (exist == NULL) {
2826                 m = malloc(4096);
2827                 m[0] = 0;
2828                 buffer_len = 4096;
2829                 message_len = 0;
2830         }
2831         else {
2832                 message_len = strlen(exist);
2833                 buffer_len = message_len + 4096;
2834                 m = realloc(exist, buffer_len);
2835                 if (m == NULL) {
2836                         free(exist);
2837                         return m;
2838                 }
2839         }
2840
2841         /* Do we need to change leading ".." to "." for SMTP escaping? */
2842         if (!strcmp(terminator, ".")) {
2843                 dotdot = 1;
2844         }
2845
2846         /* flush the input if we have nowhere to store it */
2847         if (m == NULL) {
2848                 flushing = 1;
2849         }
2850
2851         /* read in the lines of message text one by one */
2852         do {
2853                 if (client_getln(buf, (sizeof buf - 3)) < 1) finished = 1;
2854                 if (!strcmp(buf, terminator)) finished = 1;
2855                 if (crlf) {
2856                         strcat(buf, "\r\n");
2857                 }
2858                 else {
2859                         strcat(buf, "\n");
2860                 }
2861
2862                 /* Unescape SMTP-style input of two dots at the beginning of the line */
2863                 if (dotdot) {
2864                         if (!strncmp(buf, "..", 2)) {
2865                                 strcpy(buf, &buf[1]);
2866                         }
2867                 }
2868
2869                 if ( (!flushing) && (!finished) ) {
2870                         /* Measure the line */
2871                         linelen = strlen(buf);
2872         
2873                         /* augment the buffer if we have to */
2874                         if ((message_len + linelen) >= buffer_len) {
2875                                 ptr = realloc(m, (buffer_len * 2) );
2876                                 if (ptr == NULL) {      /* flush if can't allocate */
2877                                         flushing = 1;
2878                                 } else {
2879                                         buffer_len = (buffer_len * 2);
2880                                         m = ptr;
2881                                         lprintf(CTDL_DEBUG, "buffer_len is now %ld\n", (long)buffer_len);
2882                                 }
2883                         }
2884         
2885                         /* Add the new line to the buffer.  NOTE: this loop must avoid
2886                         * using functions like strcat() and strlen() because they
2887                         * traverse the entire buffer upon every call, and doing that
2888                         * for a multi-megabyte message slows it down beyond usability.
2889                         */
2890                         strcpy(&m[message_len], buf);
2891                         message_len += linelen;
2892                 }
2893
2894                 /* if we've hit the max msg length, flush the rest */
2895                 if (message_len >= maxlen) flushing = 1;
2896
2897         } while (!finished);
2898         return(m);
2899 }
2900
2901
2902
2903
2904 /*
2905  * Build a binary message to be saved on disk.
2906  * (NOTE: if you supply 'preformatted_text', the buffer you give it
2907  * will become part of the message.  This means you are no longer
2908  * responsible for managing that memory -- it will be freed along with
2909  * the rest of the fields when CtdlFreeMessage() is called.)
2910  */
2911
2912 struct CtdlMessage *CtdlMakeMessage(
2913         struct ctdluser *author,        /* author's user structure */
2914         char *recipient,                /* NULL if it's not mail */
2915         char *recp_cc,                  /* NULL if it's not mail */
2916         char *room,                     /* room where it's going */
2917         int type,                       /* see MES_ types in header file */
2918         int format_type,                /* variformat, plain text, MIME... */
2919         char *fake_name,                /* who we're masquerading as */
2920         char *my_email,                 /* which of my email addresses to use (empty is ok) */
2921         char *subject,                  /* Subject (optional) */
2922         char *supplied_euid,            /* ...or NULL if this is irrelevant */
2923         char *preformatted_text         /* ...or NULL to read text from client */
2924 ) {
2925         char dest_node[256];
2926         char buf[1024];
2927         struct CtdlMessage *msg;
2928         int i;
2929
2930         msg = malloc(sizeof(struct CtdlMessage));
2931         memset(msg, 0, sizeof(struct CtdlMessage));
2932         msg->cm_magic = CTDLMESSAGE_MAGIC;
2933         msg->cm_anon_type = type;
2934         msg->cm_format_type = format_type;
2935
2936         /* Don't confuse the poor folks if it's not routed mail. */
2937         strcpy(dest_node, "");
2938
2939         striplt(recipient);
2940         striplt(recp_cc);
2941
2942         /* Path or Return-Path */
2943         if (my_email == NULL) my_email = "";
2944
2945         if (!IsEmptyStr(my_email)) {
2946                 msg->cm_fields['P'] = strdup(my_email);
2947         }
2948         else {
2949                 snprintf(buf, sizeof buf, "%s", author->fullname);
2950                 msg->cm_fields['P'] = strdup(buf);
2951         }
2952         for (i=0; (msg->cm_fields['P'][i]!=0); ++i) {
2953                 if (isspace(msg->cm_fields['P'][i])) {
2954                         msg->cm_fields['P'][i] = '_';
2955                 }
2956         }
2957
2958         snprintf(buf, sizeof buf, "%ld", (long)time(NULL));     /* timestamp */
2959         msg->cm_fields['T'] = strdup(buf);
2960
2961         if (fake_name[0])                                       /* author */
2962                 msg->cm_fields['A'] = strdup(fake_name);
2963         else
2964                 msg->cm_fields['A'] = strdup(author->fullname);
2965
2966         if (CC->room.QRflags & QR_MAILBOX) {            /* room */
2967                 msg->cm_fields['O'] = strdup(&CC->room.QRname[11]);
2968         }
2969         else {
2970                 msg->cm_fields['O'] = strdup(CC->room.QRname);
2971         }
2972
2973         msg->cm_fields['N'] = strdup(NODENAME);         /* nodename */
2974         msg->cm_fields['H'] = strdup(HUMANNODE);                /* hnodename */
2975
2976         if (recipient[0] != 0) {
2977                 msg->cm_fields['R'] = strdup(recipient);
2978         }
2979         if (recp_cc[0] != 0) {
2980                 msg->cm_fields['Y'] = strdup(recp_cc);
2981         }
2982         if (dest_node[0] != 0) {
2983                 msg->cm_fields['D'] = strdup(dest_node);
2984         }
2985
2986         if (!IsEmptyStr(my_email)) {
2987                 msg->cm_fields['F'] = strdup(my_email);
2988         }
2989         else if ( (author == &CC->user) && (!IsEmptyStr(CC->cs_inet_email)) ) {
2990                 msg->cm_fields['F'] = strdup(CC->cs_inet_email);
2991         }
2992
2993         if (subject != NULL) {
2994                 long length;
2995                 striplt(subject);
2996                 length = strlen(subject);
2997                 if (length > 0) {
2998                         long i;
2999                         long IsAscii;
3000                         IsAscii = -1;
3001                         i = 0;
3002                         while ((subject[i] != '\0') &&
3003                                (IsAscii = isascii(subject[i]) != 0 ))
3004                                 i++;
3005                         if (IsAscii != 0)
3006                                 msg->cm_fields['U'] = strdup(subject);
3007                         else /* ok, we've got utf8 in the string. */
3008                         {
3009                                 msg->cm_fields['U'] = rfc2047encode(subject, length);
3010                         }
3011
3012                 }
3013         }
3014
3015         if (supplied_euid != NULL) {
3016                 msg->cm_fields['E'] = strdup(supplied_euid);
3017         }
3018
3019         if (preformatted_text != NULL) {
3020                 msg->cm_fields['M'] = preformatted_text;
3021         }
3022         else {
3023                 msg->cm_fields['M'] = CtdlReadMessageBody("000", config.c_maxmsglen, NULL, 0);
3024         }
3025
3026         return(msg);
3027 }
3028
3029
3030 /*
3031  * Check to see whether we have permission to post a message in the current
3032  * room.  Returns a *CITADEL ERROR CODE* and puts a message in errmsgbuf, or
3033  * returns 0 on success.
3034  */
3035 int CtdlDoIHavePermissionToPostInThisRoom(char *errmsgbuf, size_t n) {
3036         int ra;
3037
3038         if (!(CC->logged_in)) {
3039                 snprintf(errmsgbuf, n, "Not logged in.");
3040                 return (ERROR + NOT_LOGGED_IN);
3041         }
3042
3043         if ((CC->user.axlevel < 2)
3044             && ((CC->room.QRflags & QR_MAILBOX) == 0)) {
3045                 snprintf(errmsgbuf, n, "Need to be validated to enter "
3046                                 "(except in %s> to sysop)", MAILROOM);
3047                 return (ERROR + HIGHER_ACCESS_REQUIRED);
3048         }
3049
3050         CtdlRoomAccess(&CC->room, &CC->user, &ra, NULL);
3051         if (!(ra & UA_POSTALLOWED)) {
3052                 snprintf(errmsgbuf, n, "Higher access is required to post in this room.");
3053                 return (ERROR + HIGHER_ACCESS_REQUIRED);
3054         }
3055
3056         strcpy(errmsgbuf, "Ok");
3057         return(0);
3058 }
3059
3060
3061 /*
3062  * Check to see if the specified user has Internet mail permission
3063  * (returns nonzero if permission is granted)
3064  */
3065 int CtdlCheckInternetMailPermission(struct ctdluser *who) {
3066
3067         /* Do not allow twits to send Internet mail */
3068         if (who->axlevel <= 2) return(0);
3069
3070         /* Globally enabled? */
3071         if (config.c_restrict == 0) return(1);
3072
3073         /* User flagged ok? */
3074         if (who->flags & US_INTERNET) return(2);
3075
3076         /* Aide level access? */
3077         if (who->axlevel >= 6) return(3);
3078
3079         /* No mail for you! */
3080         return(0);
3081 }
3082
3083
3084 /*
3085  * Validate recipients, count delivery types and errors, and handle aliasing
3086  * FIXME check for dupes!!!!!
3087  *
3088  * Returns 0 if all addresses are ok, ret->num_error = -1 if no addresses 
3089  * were specified, or the number of addresses found invalid.
3090  *
3091  * Caller needs to free the result using free_recipients()
3092  */
3093 struct recptypes *validate_recipients(char *supplied_recipients) {
3094         struct recptypes *ret;
3095         char *recipients = NULL;
3096         char this_recp[256];
3097         char this_recp_cooked[256];
3098         char append[SIZ];
3099         int num_recps = 0;
3100         int i, j;
3101         int mailtype;
3102         int invalid;
3103         struct ctdluser tempUS;
3104         struct ctdlroom tempQR;
3105         int in_quotes = 0;
3106
3107         /* Initialize */
3108         ret = (struct recptypes *) malloc(sizeof(struct recptypes));
3109         if (ret == NULL) return(NULL);
3110
3111         /* Set all strings to null and numeric values to zero */
3112         memset(ret, 0, sizeof(struct recptypes));
3113
3114         if (supplied_recipients == NULL) {
3115                 recipients = strdup("");
3116         }
3117         else {
3118                 recipients = strdup(supplied_recipients);
3119         }
3120
3121         /* Allocate some memory.  Yes, this allocates 500% more memory than we will
3122          * actually need, but it's healthier for the heap than doing lots of tiny
3123          * realloc() calls instead.
3124          */
3125
3126         ret->errormsg = malloc(strlen(recipients) + 1024);
3127         ret->recp_local = malloc(strlen(recipients) + 1024);
3128         ret->recp_internet = malloc(strlen(recipients) + 1024);
3129         ret->recp_ignet = malloc(strlen(recipients) + 1024);
3130         ret->recp_room = malloc(strlen(recipients) + 1024);
3131         ret->display_recp = malloc(strlen(recipients) + 1024);
3132
3133         ret->errormsg[0] = 0;
3134         ret->recp_local[0] = 0;
3135         ret->recp_internet[0] = 0;
3136         ret->recp_ignet[0] = 0;
3137         ret->recp_room[0] = 0;
3138         ret->display_recp[0] = 0;
3139
3140         ret->recptypes_magic = RECPTYPES_MAGIC;
3141
3142         /* Change all valid separator characters to commas */
3143         for (i=0; i<strlen(recipients); ++i) {
3144                 if ((recipients[i] == ';') || (recipients[i] == '|')) {
3145                         recipients[i] = ',';
3146                 }
3147         }
3148
3149         /* Now start extracting recipients... */
3150
3151         while (!IsEmptyStr(recipients)) {
3152
3153                 for (i=0; i<=strlen(recipients); ++i) {
3154                         if (recipients[i] == '\"') in_quotes = 1 - in_quotes;
3155                         if ( ( (recipients[i] == ',') && (!in_quotes) ) || (recipients[i] == 0) ) {
3156                                 safestrncpy(this_recp, recipients, i+1);
3157                                 this_recp[i] = 0;
3158                                 if (recipients[i] == ',') {
3159                                         strcpy(recipients, &recipients[i+1]);
3160                                 }
3161                                 else {
3162                                         strcpy(recipients, "");
3163                                 }
3164                                 break;
3165                         }
3166                 }
3167
3168                 striplt(this_recp);
3169                 lprintf(CTDL_DEBUG, "Evaluating recipient #%d: %s\n", num_recps, this_recp);
3170                 ++num_recps;
3171                 mailtype = alias(this_recp);
3172                 mailtype = alias(this_recp);
3173                 mailtype = alias(this_recp);
3174                 for (j=0; j<=strlen(this_recp); ++j) {
3175                         if (this_recp[j]=='_') {
3176                                 this_recp_cooked[j] = ' ';
3177                         }
3178                         else {
3179                                 this_recp_cooked[j] = this_recp[j];
3180                         }
3181                 }
3182                 invalid = 0;
3183                 switch(mailtype) {
3184                         case MES_LOCAL:
3185                                 if (!strcasecmp(this_recp, "sysop")) {
3186                                         ++ret->num_room;
3187                                         strcpy(this_recp, config.c_aideroom);
3188                                         if (!IsEmptyStr(ret->recp_room)) {
3189                                                 strcat(ret->recp_room, "|");
3190                                         }
3191                                         strcat(ret->recp_room, this_recp);
3192                                 }
3193                                 else if (getuser(&tempUS, this_recp) == 0) {
3194                                         ++ret->num_local;
3195                                         strcpy(this_recp, tempUS.fullname);
3196                                         if (!IsEmptyStr(ret->recp_local)) {
3197                                                 strcat(ret->recp_local, "|");
3198                                         }
3199                                         strcat(ret->recp_local, this_recp);
3200                                 }
3201                                 else if (getuser(&tempUS, this_recp_cooked) == 0) {
3202                                         ++ret->num_local;
3203                                         strcpy(this_recp, tempUS.fullname);
3204                                         if (!IsEmptyStr(ret->recp_local)) {
3205                                                 strcat(ret->recp_local, "|");
3206                                         }
3207                                         strcat(ret->recp_local, this_recp);
3208                                 }
3209                                 else if ( (!strncasecmp(this_recp, "room_", 5))
3210                                       && (!getroom(&tempQR, &this_recp_cooked[5])) ) {
3211                                         ++ret->num_room;
3212                                         if (!IsEmptyStr(ret->recp_room)) {
3213                                                 strcat(ret->recp_room, "|");
3214                                         }
3215                                         strcat(ret->recp_room, &this_recp_cooked[5]);
3216                                 }
3217                                 else {
3218                                         ++ret->num_error;
3219                                         invalid = 1;
3220                                 }
3221                                 break;
3222                         case MES_INTERNET:
3223                                 /* Yes, you're reading this correctly: if the target
3224                                  * domain points back to the local system or an attached
3225                                  * Citadel directory, the address is invalid.  That's
3226                                  * because if the address were valid, we would have
3227                                  * already translated it to a local address by now.
3228                                  */
3229                                 if (IsDirectory(this_recp, 0)) {
3230                                         ++ret->num_error;
3231                                         invalid = 1;
3232                                 }
3233                                 else {
3234                                         ++ret->num_internet;
3235                                         if (!IsEmptyStr(ret->recp_internet)) {
3236                                                 strcat(ret->recp_internet, "|");
3237                                         }
3238                                         strcat(ret->recp_internet, this_recp);
3239                                 }
3240                                 break;
3241                         case MES_IGNET:
3242                                 ++ret->num_ignet;
3243                                 if (!IsEmptyStr(ret->recp_ignet)) {
3244                                         strcat(ret->recp_ignet, "|");
3245                                 }
3246                                 strcat(ret->recp_ignet, this_recp);
3247                                 break;
3248                         case MES_ERROR:
3249                                 ++ret->num_error;
3250                                 invalid = 1;
3251                                 break;
3252                 }
3253                 if (invalid) {
3254                         if (IsEmptyStr(ret->errormsg)) {
3255                                 snprintf(append, sizeof append,
3256                                          "Invalid recipient: %s",
3257                                          this_recp);
3258                         }
3259                         else {
3260                                 snprintf(append, sizeof append, ", %s", this_recp);
3261                         }
3262                         if ( (strlen(ret->errormsg) + strlen(append)) < SIZ) {
3263                                 strcat(ret->errormsg, append);
3264                         }
3265                 }
3266                 else {
3267                         if (IsEmptyStr(ret->display_recp)) {
3268                                 strcpy(append, this_recp);
3269                         }
3270                         else {
3271                                 snprintf(append, sizeof append, ", %s", this_recp);
3272                         }
3273                         if ( (strlen(ret->display_recp)+strlen(append)) < SIZ) {
3274                                 strcat(ret->display_recp, append);
3275                         }
3276                 }
3277         }
3278
3279         if ((ret->num_local + ret->num_internet + ret->num_ignet +
3280            ret->num_room + ret->num_error) == 0) {
3281                 ret->num_error = (-1);
3282                 strcpy(ret->errormsg, "No recipients specified.");
3283         }
3284
3285         lprintf(CTDL_DEBUG, "validate_recipients()\n");
3286         lprintf(CTDL_DEBUG, " local: %d <%s>\n", ret->num_local, ret->recp_local);
3287         lprintf(CTDL_DEBUG, "  room: %d <%s>\n", ret->num_room, ret->recp_room);
3288         lprintf(CTDL_DEBUG, "  inet: %d <%s>\n", ret->num_internet, ret->recp_internet);
3289         lprintf(CTDL_DEBUG, " ignet: %d <%s>\n", ret->num_ignet, ret->recp_ignet);
3290         lprintf(CTDL_DEBUG, " error: %d <%s>\n", ret->num_error, ret->errormsg);
3291
3292         free(recipients);
3293         return(ret);
3294 }
3295
3296
3297 /*
3298  * Destructor for struct recptypes
3299  */
3300 void free_recipients(struct recptypes *valid) {
3301
3302         if (valid == NULL) {
3303                 return;
3304         }
3305
3306         if (valid->recptypes_magic != RECPTYPES_MAGIC) {
3307                 lprintf(CTDL_EMERG, "Attempt to call free_recipients() on some other data type!\n");
3308                 abort();
3309         }
3310
3311         if (valid->errormsg != NULL)            free(valid->errormsg);
3312         if (valid->recp_local != NULL)          free(valid->recp_local);
3313         if (valid->recp_internet != NULL)       free(valid->recp_internet);
3314         if (valid->recp_ignet != NULL)          free(valid->recp_ignet);
3315         if (valid->recp_room != NULL)           free(valid->recp_room);
3316         if (valid->display_recp != NULL)        free(valid->display_recp);
3317         free(valid);
3318 }
3319
3320
3321
3322 /*
3323  * message entry  -  mode 0 (normal)
3324  */
3325 void cmd_ent0(char *entargs)
3326 {
3327         int post = 0;
3328         char recp[SIZ];
3329         char cc[SIZ];
3330         char bcc[SIZ];
3331         char supplied_euid[128];
3332         int anon_flag = 0;
3333         int format_type = 0;
3334         char newusername[256];
3335         char newuseremail[256];
3336         struct CtdlMessage *msg;
3337         int anonymous = 0;
3338         char errmsg[SIZ];
3339         int err = 0;
3340         struct recptypes *valid = NULL;
3341         struct recptypes *valid_to = NULL;
3342         struct recptypes *valid_cc = NULL;
3343         struct recptypes *valid_bcc = NULL;
3344         char subject[SIZ];
3345         int subject_required = 0;
3346         int do_confirm = 0;
3347         long msgnum;
3348         int i, j;
3349         char buf[256];
3350         int newuseremail_ok = 0;
3351
3352         unbuffer_output();
3353
3354         post = extract_int(entargs, 0);
3355         extract_token(recp, entargs, 1, '|', sizeof recp);
3356         anon_flag = extract_int(entargs, 2);
3357         format_type = extract_int(entargs, 3);
3358         extract_token(subject, entargs, 4, '|', sizeof subject);
3359         extract_token(newusername, entargs, 5, '|', sizeof newusername);
3360         do_confirm = extract_int(entargs, 6);
3361         extract_token(cc, entargs, 7, '|', sizeof cc);
3362         extract_token(bcc, entargs, 8, '|', sizeof bcc);
3363         switch(CC->room.QRdefaultview) {
3364                 case VIEW_NOTES:
3365                 case VIEW_WIKI:
3366                         extract_token(supplied_euid, entargs, 9, '|', sizeof supplied_euid);
3367                         break;
3368                 default:
3369                         supplied_euid[0] = 0;
3370                         break;
3371         }
3372         extract_token(newuseremail, entargs, 10, '|', sizeof newuseremail);
3373
3374         /* first check to make sure the request is valid. */
3375
3376         err = CtdlDoIHavePermissionToPostInThisRoom(errmsg, sizeof errmsg);
3377         if (err)
3378         {
3379                 cprintf("%d %s\n", err, errmsg);
3380                 return;
3381         }
3382
3383         /* Check some other permission type things. */
3384
3385         if (IsEmptyStr(newusername)) {
3386                 strcpy(newusername, CC->user.fullname);
3387         }
3388         if (  (CC->user.axlevel < 6)
3389            && (strcasecmp(newusername, CC->user.fullname))
3390            && (strcasecmp(newusername, CC->cs_inet_fn))
3391         ) {     
3392                 cprintf("%d You don't have permission to author messages as '%s'.\n",
3393                         ERROR + HIGHER_ACCESS_REQUIRED,
3394                         newusername
3395                 );
3396                 return;
3397         }
3398
3399
3400         if (IsEmptyStr(newuseremail)) {
3401                 newuseremail_ok = 1;
3402         }
3403
3404         if (!IsEmptyStr(newuseremail)) {
3405                 if (!strcasecmp(newuseremail, CC->cs_inet_email)) {
3406                         newuseremail_ok = 1;
3407                 }
3408                 else if (!IsEmptyStr(CC->cs_inet_other_emails)) {
3409                         j = num_tokens(CC->cs_inet_other_emails, '|');
3410                         for (i=0; i<j; ++i) {
3411                                 extract_token(buf, CC->cs_inet_other_emails, i, '|', sizeof buf);
3412                                 if (!strcasecmp(newuseremail, buf)) {
3413                                         newuseremail_ok = 1;
3414                                 }
3415                         }
3416                 }
3417         }
3418
3419         if (!newuseremail_ok) {
3420                 cprintf("%d You don't have permission to author messages as '%s'.\n",
3421                         ERROR + HIGHER_ACCESS_REQUIRED,
3422                         newuseremail
3423                 );
3424                 return;
3425         }
3426
3427         CC->cs_flags |= CS_POSTING;
3428
3429         /* In mailbox rooms we have to behave a little differently --
3430          * make sure the user has specified at least one recipient.  Then
3431          * validate the recipient(s).  We do this for the Mail> room, as
3432          * well as any room which has the "Mailbox" view set.
3433          */
3434
3435         if (  ( (CC->room.QRflags & QR_MAILBOX) && (!strcasecmp(&CC->room.QRname[11], MAILROOM)) )
3436            || ( (CC->room.QRflags & QR_MAILBOX) && (CC->curr_view == VIEW_MAILBOX) )
3437         ) {
3438                 if (CC->user.axlevel < 2) {
3439                         strcpy(recp, "sysop");
3440                         strcpy(cc, "");
3441                         strcpy(bcc, "");
3442                 }
3443
3444                 valid_to = validate_recipients(recp);
3445                 if (valid_to->num_error > 0) {
3446                         cprintf("%d Invalid recipient (To)\n", ERROR + NO_SUCH_USER);
3447                         free_recipients(valid_to);
3448                         return;
3449                 }
3450
3451                 valid_cc = validate_recipients(cc);
3452                 if (valid_cc->num_error > 0) {
3453                         cprintf("%d Invalid recipient (CC)\n", ERROR + NO_SUCH_USER);
3454                         free_recipients(valid_to);
3455                         free_recipients(valid_cc);
3456                         return;
3457                 }
3458
3459                 valid_bcc = validate_recipients(bcc);
3460                 if (valid_bcc->num_error > 0) {
3461                         cprintf("%d Invalid recipient (BCC)\n", ERROR + NO_SUCH_USER);
3462                         free_recipients(valid_to);
3463                         free_recipients(valid_cc);
3464                         free_recipients(valid_bcc);
3465                         return;
3466                 }
3467
3468                 /* Recipient required, but none were specified */
3469                 if ( (valid_to->num_error < 0) && (valid_cc->num_error < 0) && (valid_bcc->num_error < 0) ) {
3470                         free_recipients(valid_to);
3471                         free_recipients(valid_cc);
3472                         free_recipients(valid_bcc);
3473                         cprintf("%d At least one recipient is required.\n", ERROR + NO_SUCH_USER);
3474                         return;
3475                 }
3476
3477                 if (valid_to->num_internet + valid_cc->num_internet + valid_bcc->num_internet > 0) {
3478                         if (CtdlCheckInternetMailPermission(&CC->user)==0) {
3479                                 cprintf("%d You do not have permission "
3480                                         "to send Internet mail.\n",
3481                                         ERROR + HIGHER_ACCESS_REQUIRED);
3482                                 free_recipients(valid_to);
3483                                 free_recipients(valid_cc);
3484                                 free_recipients(valid_bcc);
3485                                 return;
3486                         }
3487                 }
3488
3489                 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)
3490                    && (CC->user.axlevel < 4) ) {
3491                         cprintf("%d Higher access required for network mail.\n",
3492                                 ERROR + HIGHER_ACCESS_REQUIRED);
3493                         free_recipients(valid_to);
3494                         free_recipients(valid_cc);
3495                         free_recipients(valid_bcc);
3496                         return;
3497                 }
3498         
3499                 if ((RESTRICT_INTERNET == 1)
3500                     && (valid_to->num_internet + valid_cc->num_internet + valid_bcc->num_internet > 0)
3501                     && ((CC->user.flags & US_INTERNET) == 0)
3502                     && (!CC->internal_pgm)) {
3503                         cprintf("%d You don't have access to Internet mail.\n",
3504                                 ERROR + HIGHER_ACCESS_REQUIRED);
3505                         free_recipients(valid_to);
3506                         free_recipients(valid_cc);
3507                         free_recipients(valid_bcc);
3508                         return;
3509                 }
3510
3511         }
3512
3513         /* Is this a room which has anonymous-only or anonymous-option? */
3514         anonymous = MES_NORMAL;
3515         if (CC->room.QRflags & QR_ANONONLY) {
3516                 anonymous = MES_ANONONLY;
3517         }
3518         if (CC->room.QRflags & QR_ANONOPT) {
3519                 if (anon_flag == 1) {   /* only if the user requested it */
3520                         anonymous = MES_ANONOPT;
3521                 }
3522         }
3523
3524         if ((CC->room.QRflags & QR_MAILBOX) == 0) {
3525                 recp[0] = 0;
3526         }
3527
3528         /* Recommend to the client that the use of a message subject is
3529          * strongly recommended in this room, if either the SUBJECTREQ flag
3530          * is set, or if there is one or more Internet email recipients.
3531          */
3532         if (CC->room.QRflags2 & QR2_SUBJECTREQ) subject_required = 1;
3533         if (valid_to) if (valid_to->num_internet > 0) subject_required = 1;
3534         if (valid_cc) if (valid_cc->num_internet > 0) subject_required = 1;
3535         if (valid_bcc) if (valid_bcc->num_internet > 0) subject_required = 1;
3536
3537         /* If we're only checking the validity of the request, return
3538          * success without creating the message.
3539          */
3540         if (post == 0) {
3541                 cprintf("%d %s|%d\n", CIT_OK,
3542                         ((valid_to != NULL) ? valid_to->display_recp : ""), 
3543                         subject_required);
3544                 free_recipients(valid_to);
3545                 free_recipients(valid_cc);
3546                 free_recipients(valid_bcc);
3547                 return;
3548         }
3549
3550         /* We don't need these anymore because we'll do it differently below */
3551         free_recipients(valid_to);
3552         free_recipients(valid_cc);
3553         free_recipients(valid_bcc);
3554
3555         /* Read in the message from the client. */
3556         if (do_confirm) {
3557                 cprintf("%d send message\n", START_CHAT_MODE);
3558         } else {
3559                 cprintf("%d send message\n", SEND_LISTING);
3560         }
3561
3562         msg = CtdlMakeMessage(&CC->user, recp, cc,
3563                 CC->room.QRname, anonymous, format_type,
3564                 newusername, newuseremail, subject,
3565                 ((!IsEmptyStr(supplied_euid)) ? supplied_euid : NULL),
3566                 NULL);
3567
3568         /* Put together one big recipients struct containing to/cc/bcc all in
3569          * one.  This is for the envelope.
3570          */
3571         char *all_recps = malloc(SIZ * 3);
3572         strcpy(all_recps, recp);
3573         if (!IsEmptyStr(cc)) {
3574                 if (!IsEmptyStr(all_recps)) {
3575                         strcat(all_recps, ",");
3576                 }
3577                 strcat(all_recps, cc);
3578         }
3579         if (!IsEmptyStr(bcc)) {
3580                 if (!IsEmptyStr(all_recps)) {
3581                         strcat(all_recps, ",");
3582                 }
3583                 strcat(all_recps, bcc);
3584         }
3585         if (!IsEmptyStr(all_recps)) {
3586                 valid = validate_recipients(all_recps);
3587         }
3588         else {
3589                 valid = NULL;
3590         }
3591         free(all_recps);
3592
3593         if (msg != NULL) {
3594                 msgnum = CtdlSubmitMsg(msg, valid, "");
3595
3596                 if (do_confirm) {
3597                         cprintf("%ld\n", msgnum);
3598                         if (msgnum >= 0L) {
3599                                 cprintf("Message accepted.\n");
3600                         }
3601                         else {
3602                                 cprintf("Internal error.\n");
3603                         }
3604                         if (msg->cm_fields['E'] != NULL) {
3605                                 cprintf("%s\n", msg->cm_fields['E']);
3606                         } else {
3607                                 cprintf("\n");
3608                         }
3609                         cprintf("000\n");
3610                 }
3611
3612                 CtdlFreeMessage(msg);
3613         }
3614         if (valid != NULL) {
3615                 free_recipients(valid);
3616         }
3617         return;
3618 }
3619
3620
3621
3622 /*
3623  * API function to delete messages which match a set of criteria
3624  * (returns the actual number of messages deleted)
3625  */
3626 int CtdlDeleteMessages(char *room_name,         /* which room */
3627                         long *dmsgnums,         /* array of msg numbers to be deleted */
3628                         int num_dmsgnums,       /* number of msgs to be deleted, or 0 for "any" */
3629                         char *content_type      /* or "" for any.  regular expressions expected. */
3630 )
3631 {
3632         struct ctdlroom qrbuf;
3633         struct cdbdata *cdbfr;
3634         long *msglist = NULL;
3635         long *dellist = NULL;
3636         int num_msgs = 0;
3637         int i, j;
3638         int num_deleted = 0;
3639         int delete_this;
3640         struct MetaData smi;
3641         regex_t re;
3642         regmatch_t pm;
3643         int need_to_free_re = 0;
3644
3645         if (content_type) if (!IsEmptyStr(content_type)) {
3646                 regcomp(&re, content_type, 0);
3647                 need_to_free_re = 1;
3648         }
3649         lprintf(CTDL_DEBUG, "CtdlDeleteMessages(%s, %d msgs, %s)\n",
3650                 room_name, num_dmsgnums, content_type);
3651
3652         /* get room record, obtaining a lock... */
3653         if (lgetroom(&qrbuf, room_name) != 0) {
3654                 lprintf(CTDL_ERR, "CtdlDeleteMessages(): Room <%s> not found\n",
3655                         room_name);
3656                 if (need_to_free_re) regfree(&re);
3657                 return (0);     /* room not found */
3658         }
3659         cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf.QRnumber, sizeof(long));
3660
3661         if (cdbfr != NULL) {
3662                 dellist = malloc(cdbfr->len);
3663                 msglist = (long *) cdbfr->ptr;
3664                 cdbfr->ptr = NULL;      /* CtdlDeleteMessages() now owns this memory */
3665                 num_msgs = cdbfr->len / sizeof(long);
3666                 cdb_free(cdbfr);
3667         }
3668         if (num_msgs > 0) {
3669                 for (i = 0; i < num_msgs; ++i) {
3670                         delete_this = 0x00;
3671
3672                         /* Set/clear a bit for each criterion */
3673
3674                         /* 0 messages in the list or a null list means that we are
3675                          * interested in deleting any messages which meet the other criteria.
3676                          */
3677                         if ((num_dmsgnums == 0) || (dmsgnums == NULL)) {
3678                                 delete_this |= 0x01;
3679                         }
3680                         else {
3681                                 for (j=0; j<num_dmsgnums; ++j) {
3682                                         if (msglist[i] == dmsgnums[j]) {
3683                                                 delete_this |= 0x01;
3684                                         }
3685                                 }
3686                         }
3687
3688                         if (IsEmptyStr(content_type)) {
3689                                 delete_this |= 0x02;
3690                         } else {
3691                                 GetMetaData(&smi, msglist[i]);
3692                                 if (regexec(&re, smi.meta_content_type, 1, &pm, 0) == 0) {
3693                                         delete_this |= 0x02;
3694                                 }
3695                         }
3696
3697                         /* Delete message only if all bits are set */
3698                         if (delete_this == 0x03) {
3699                                 dellist[num_deleted++] = msglist[i];
3700                                 msglist[i] = 0L;
3701                         }
3702                 }
3703
3704                 num_msgs = sort_msglist(msglist, num_msgs);
3705                 cdb_store(CDB_MSGLISTS, &qrbuf.QRnumber, (int)sizeof(long),
3706                           msglist, (int)(num_msgs * sizeof(long)));
3707
3708                 qrbuf.QRhighest = msglist[num_msgs - 1];
3709         }
3710         lputroom(&qrbuf);
3711
3712         /* Go through the messages we pulled out of the index, and decrement
3713          * their reference counts by 1.  If this is the only room the message
3714          * was in, the reference count will reach zero and the message will
3715          * automatically be deleted from the database.  We do this in a
3716          * separate pass because there might be plug-in hooks getting called,
3717          * and we don't want that happening during an S_ROOMS critical
3718          * section.
3719          */
3720         if (num_deleted) for (i=0; i<num_deleted; ++i) {
3721                 PerformDeleteHooks(qrbuf.QRname, dellist[i]);
3722                 AdjRefCount(dellist[i], -1);
3723         }
3724
3725         /* Now free the memory we used, and go away. */
3726         if (msglist != NULL) free(msglist);
3727         if (dellist != NULL) free(dellist);
3728         lprintf(CTDL_DEBUG, "%d message(s) deleted.\n", num_deleted);
3729         if (need_to_free_re) regfree(&re);
3730         return (num_deleted);
3731 }
3732
3733
3734
3735 /*
3736  * Check whether the current user has permission to delete messages from
3737  * the current room (returns 1 for yes, 0 for no)
3738  */
3739 int CtdlDoIHavePermissionToDeleteMessagesFromThisRoom(void) {
3740         int ra;
3741         CtdlRoomAccess(&CC->room, &CC->user, &ra, NULL);
3742         if (ra & UA_DELETEALLOWED) return(1);
3743         return(0);
3744 }
3745
3746
3747
3748
3749 /*
3750  * Delete message from current room
3751  */
3752 void cmd_dele(char *args)
3753 {
3754         int num_deleted;
3755         int i;
3756         char msgset[SIZ];
3757         char msgtok[32];
3758         long *msgs;
3759         int num_msgs = 0;
3760
3761         extract_token(msgset, args, 0, '|', sizeof msgset);
3762         num_msgs = num_tokens(msgset, ',');
3763         if (num_msgs < 1) {
3764                 cprintf("%d Nothing to do.\n", CIT_OK);
3765                 return;
3766         }
3767
3768         if (CtdlDoIHavePermissionToDeleteMessagesFromThisRoom() == 0) {
3769                 cprintf("%d Higher access required.\n",
3770                         ERROR + HIGHER_ACCESS_REQUIRED);
3771                 return;
3772         }
3773
3774         /*
3775          * Build our message set to be moved/copied
3776          */
3777         msgs = malloc(num_msgs * sizeof(long));
3778         for (i=0; i<num_msgs; ++i) {
3779                 extract_token(msgtok, msgset, i, ',', sizeof msgtok);
3780                 msgs[i] = atol(msgtok);
3781         }
3782
3783         num_deleted = CtdlDeleteMessages(CC->room.QRname, msgs, num_msgs, "");
3784         free(msgs);
3785
3786         if (num_deleted) {
3787                 cprintf("%d %d message%s deleted.\n", CIT_OK,
3788                         num_deleted, ((num_deleted != 1) ? "s" : ""));
3789         } else {
3790                 cprintf("%d Message not found.\n", ERROR + MESSAGE_NOT_FOUND);
3791         }
3792 }
3793
3794
3795 /*
3796  * Back end API function for moves and deletes (multiple messages)
3797  */
3798 int CtdlCopyMsgsToRoom(long *msgnums, int num_msgs, char *dest) {
3799         int err;
3800
3801         err = CtdlSaveMsgPointersInRoom(dest, msgnums, num_msgs, 1, NULL);
3802         if (err != 0) return(err);
3803
3804         return(0);
3805 }
3806
3807
3808
3809
3810 /*
3811  * move or copy a message to another room
3812  */
3813 void cmd_move(char *args)
3814 {
3815         char msgset[SIZ];
3816         char msgtok[32];
3817         long *msgs;
3818         int num_msgs = 0;
3819
3820         char targ[ROOMNAMELEN];
3821         struct ctdlroom qtemp;
3822         int err;
3823         int is_copy = 0;
3824         int ra;
3825         int permit = 0;
3826         int i;
3827
3828         extract_token(msgset, args, 0, '|', sizeof msgset);
3829         num_msgs = num_tokens(msgset, ',');
3830         if (num_msgs < 1) {
3831                 cprintf("%d Nothing to do.\n", CIT_OK);
3832                 return;
3833         }
3834
3835         extract_token(targ, args, 1, '|', sizeof targ);
3836         convert_room_name_macros(targ, sizeof targ);
3837         targ[ROOMNAMELEN - 1] = 0;
3838         is_copy = extract_int(args, 2);
3839
3840         if (getroom(&qtemp, targ) != 0) {
3841                 cprintf("%d '%s' does not exist.\n",
3842                         ERROR + ROOM_NOT_FOUND, targ);
3843                 return;
3844         }
3845
3846         getuser(&CC->user, CC->curr_user);
3847         CtdlRoomAccess(&qtemp, &CC->user, &ra, NULL);
3848
3849         /* Check for permission to perform this operation.
3850          * Remember: "CC->room" is source, "qtemp" is target.
3851          */
3852         permit = 0;
3853
3854         /* Aides can move/copy */
3855         if (CC->user.axlevel >= 6) permit = 1;
3856
3857         /* Room aides can move/copy */
3858         if (CC->user.usernum == CC->room.QRroomaide) permit = 1;
3859
3860         /* Permit move/copy from personal rooms */
3861         if ((CC->room.QRflags & QR_MAILBOX)
3862            && (qtemp.QRflags & QR_MAILBOX)) permit = 1;
3863
3864         /* Permit only copy from public to personal room */
3865         if ( (is_copy)
3866            && (!(CC->room.QRflags & QR_MAILBOX))
3867            && (qtemp.QRflags & QR_MAILBOX)) permit = 1;
3868
3869         /* Permit message removal from collaborative delete rooms */
3870         if (CC->room.QRflags2 & QR2_COLLABDEL) permit = 1;
3871
3872         /* User must have access to target room */
3873         if (!(ra & UA_KNOWN))  permit = 0;
3874
3875         if (!permit) {
3876                 cprintf("%d Higher access required.\n",
3877                         ERROR + HIGHER_ACCESS_REQUIRED);
3878                 return;
3879         }
3880
3881         /*
3882          * Build our message set to be moved/copied
3883          */
3884         msgs = malloc(num_msgs * sizeof(long));
3885         for (i=0; i<num_msgs; ++i) {
3886                 extract_token(msgtok, msgset, i, ',', sizeof msgtok);
3887                 msgs[i] = atol(msgtok);
3888         }
3889
3890         /*
3891          * Do the copy
3892          */
3893         err = CtdlCopyMsgsToRoom(msgs, num_msgs, targ);
3894         if (err != 0) {
3895                 cprintf("%d Cannot store message(s) in %s: error %d\n",
3896                         err, targ, err);
3897                 free(msgs);
3898                 return;
3899         }
3900
3901         /* Now delete the message from the source room,
3902          * if this is a 'move' rather than a 'copy' operation.
3903          */
3904         if (is_copy == 0) {
3905                 CtdlDeleteMessages(CC->room.QRname, msgs, num_msgs, "");
3906         }
3907         free(msgs);
3908
3909         cprintf("%d Message(s) %s.\n", CIT_OK, (is_copy ? "copied" : "moved") );
3910 }
3911
3912
3913
3914 /*
3915  * GetMetaData()  -  Get the supplementary record for a message
3916  */
3917 void GetMetaData(struct MetaData *smibuf, long msgnum)
3918 {
3919
3920         struct cdbdata *cdbsmi;
3921         long TheIndex;
3922
3923         memset(smibuf, 0, sizeof(struct MetaData));
3924         smibuf->meta_msgnum = msgnum;
3925         smibuf->meta_refcount = 1;      /* Default reference count is 1 */
3926
3927         /* Use the negative of the message number for its supp record index */
3928         TheIndex = (0L - msgnum);
3929
3930         cdbsmi = cdb_fetch(CDB_MSGMAIN, &TheIndex, sizeof(long));
3931         if (cdbsmi == NULL) {
3932                 return;         /* record not found; go with defaults */
3933         }
3934         memcpy(smibuf, cdbsmi->ptr,
3935                ((cdbsmi->len > sizeof(struct MetaData)) ?
3936                 sizeof(struct MetaData) : cdbsmi->len));
3937         cdb_free(cdbsmi);
3938         return;
3939 }
3940
3941
3942 /*
3943  * PutMetaData()  -  (re)write supplementary record for a message
3944  */
3945 void PutMetaData(struct MetaData *smibuf)
3946 {
3947         long TheIndex;
3948
3949         /* Use the negative of the message number for the metadata db index */
3950         TheIndex = (0L - smibuf->meta_msgnum);
3951
3952         cdb_store(CDB_MSGMAIN,
3953                   &TheIndex, (int)sizeof(long),
3954                   smibuf, (int)sizeof(struct MetaData));
3955
3956 }
3957
3958 /*
3959  * AdjRefCount  -  submit an adjustment to the reference count for a message.
3960  *                 (These are just queued -- we actually process them later.)
3961  */
3962 void AdjRefCount(long msgnum, int incr)
3963 {
3964         struct arcq new_arcq;
3965
3966         begin_critical_section(S_SUPPMSGMAIN);
3967         if (arcfp == NULL) {
3968                 arcfp = fopen(file_arcq, "ab+");
3969         }
3970         end_critical_section(S_SUPPMSGMAIN);
3971
3972         /* msgnum < 0 means that we're trying to close the file */
3973         if (msgnum < 0) {
3974                 lprintf(CTDL_DEBUG, "Closing the AdjRefCount queue file\n");
3975                 begin_critical_section(S_SUPPMSGMAIN);
3976                 if (arcfp != NULL) {
3977                         fclose(arcfp);
3978                         arcfp = NULL;
3979                 }
3980                 end_critical_section(S_SUPPMSGMAIN);
3981                 return;
3982         }
3983
3984         /*
3985          * If we can't open the queue, perform the operation synchronously.
3986          */
3987         if (arcfp == NULL) {
3988                 TDAP_AdjRefCount(msgnum, incr);
3989                 return;
3990         }
3991
3992         new_arcq.arcq_msgnum = msgnum;
3993         new_arcq.arcq_delta = incr;
3994         fwrite(&new_arcq, sizeof(struct arcq), 1, arcfp);
3995         fflush(arcfp);
3996
3997         return;
3998 }
3999
4000
4001 /*
4002  * TDAP_ProcessAdjRefCountQueue()
4003  *
4004  * Process the queue of message count adjustments that was created by calls
4005  * to AdjRefCount() ... by reading the queue and calling TDAP_AdjRefCount()
4006  * for each one.  This should be an "off hours" operation.
4007  */
4008 int TDAP_ProcessAdjRefCountQueue(void)
4009 {
4010         char file_arcq_temp[PATH_MAX];
4011         int r;
4012         FILE *fp;
4013         struct arcq arcq_rec;
4014         int num_records_processed = 0;
4015
4016         snprintf(file_arcq_temp, sizeof file_arcq_temp, "%s2", file_arcq);
4017
4018         begin_critical_section(S_SUPPMSGMAIN);
4019         if (arcfp != NULL) {
4020                 fclose(arcfp);
4021                 arcfp = NULL;
4022         }
4023
4024         r = link(file_arcq, file_arcq_temp);
4025         if (r != 0) {
4026                 lprintf(CTDL_CRIT, "%s: %s\n", file_arcq_temp, strerror(errno));
4027                 end_critical_section(S_SUPPMSGMAIN);
4028                 return(num_records_processed);
4029         }
4030
4031         unlink(file_arcq);
4032         end_critical_section(S_SUPPMSGMAIN);
4033
4034         fp = fopen(file_arcq_temp, "rb");
4035         if (fp == NULL) {
4036                 lprintf(CTDL_CRIT, "%s: %s\n", file_arcq_temp, strerror(errno));
4037                 return(num_records_processed);
4038         }
4039
4040         while (fread(&arcq_rec, sizeof(struct arcq), 1, fp) == 1) {
4041                 TDAP_AdjRefCount(arcq_rec.arcq_msgnum, arcq_rec.arcq_delta);
4042                 ++num_records_processed;
4043         }
4044
4045         fclose(fp);
4046         r = unlink(file_arcq_temp);
4047         if (r != 0) {
4048                 lprintf(CTDL_CRIT, "%s: %s\n", file_arcq_temp, strerror(errno));
4049         }
4050
4051         return(num_records_processed);
4052 }
4053
4054
4055
4056 /*
4057  * TDAP_AdjRefCount  -  adjust the reference count for a message.
4058  *                      This one does it "for real" because it's called by
4059  *                      the autopurger function that processes the queue
4060  *                      created by AdjRefCount().   If a message's reference
4061  *                      count becomes zero, we also delete the message from
4062  *                      disk and de-index it.
4063  */
4064 void TDAP_AdjRefCount(long msgnum, int incr)
4065 {
4066
4067         struct MetaData smi;
4068         long delnum;
4069
4070         /* This is a *tight* critical section; please keep it that way, as
4071          * it may get called while nested in other critical sections.  
4072          * Complicating this any further will surely cause deadlock!
4073          */
4074         begin_critical_section(S_SUPPMSGMAIN);
4075         GetMetaData(&smi, msgnum);
4076         smi.meta_refcount += incr;
4077         PutMetaData(&smi);
4078         end_critical_section(S_SUPPMSGMAIN);
4079         lprintf(CTDL_DEBUG, "msg %ld ref count delta %d, is now %d\n",
4080                 msgnum, incr, smi.meta_refcount);
4081
4082         /* If the reference count is now zero, delete the message
4083          * (and its supplementary record as well).
4084          */
4085         if (smi.meta_refcount == 0) {
4086                 lprintf(CTDL_DEBUG, "Deleting message <%ld>\n", msgnum);
4087                 
4088                 /* Call delete hooks with NULL room to show it has gone altogether */
4089                 PerformDeleteHooks(NULL, msgnum);
4090
4091                 /* Remove from message base */
4092                 delnum = msgnum;
4093                 cdb_delete(CDB_MSGMAIN, &delnum, (int)sizeof(long));
4094                 cdb_delete(CDB_BIGMSGS, &delnum, (int)sizeof(long));
4095
4096                 /* Remove metadata record */
4097                 delnum = (0L - msgnum);
4098                 cdb_delete(CDB_MSGMAIN, &delnum, (int)sizeof(long));
4099         }
4100
4101 }
4102
4103 /*
4104  * Write a generic object to this room
4105  *
4106  * Note: this could be much more efficient.  Right now we use two temporary
4107  * files, and still pull the message into memory as with all others.
4108  */
4109 void CtdlWriteObject(char *req_room,            /* Room to stuff it in */
4110                         char *content_type,     /* MIME type of this object */
4111                         char *tempfilename,     /* Where to fetch it from */
4112                         struct ctdluser *is_mailbox,    /* Mailbox room? */
4113                         int is_binary,          /* Is encoding necessary? */
4114                         int is_unique,          /* Del others of this type? */
4115                         unsigned int flags      /* Internal save flags */
4116                         )
4117 {
4118
4119         FILE *fp;
4120         struct ctdlroom qrbuf;
4121         char roomname[ROOMNAMELEN];
4122         struct CtdlMessage *msg;
4123
4124         char *raw_message = NULL;
4125         char *encoded_message = NULL;
4126         off_t raw_length = 0;
4127
4128         if (is_mailbox != NULL) {
4129                 MailboxName(roomname, sizeof roomname, is_mailbox, req_room);
4130         }
4131         else {
4132                 safestrncpy(roomname, req_room, sizeof(roomname));
4133         }
4134
4135         fp = fopen(tempfilename, "rb");
4136         if (fp == NULL) {
4137                 lprintf(CTDL_CRIT, "Cannot open %s: %s\n",
4138                         tempfilename, strerror(errno));
4139                 return;
4140         }
4141         fseek(fp, 0L, SEEK_END);
4142         raw_length = ftell(fp);
4143         rewind(fp);
4144         lprintf(CTDL_DEBUG, "Raw length is %ld\n", (long)raw_length);
4145
4146         raw_message = malloc((size_t)raw_length + 2);
4147         fread(raw_message, (size_t)raw_length, 1, fp);
4148         fclose(fp);
4149
4150         if (is_binary) {
4151                 encoded_message = malloc((size_t)
4152                         (((raw_length * 134) / 100) + 4096 ) );
4153         }
4154         else {
4155                 encoded_message = malloc((size_t)(raw_length + 4096));
4156         }
4157
4158         sprintf(encoded_message, "Content-type: %s\n", content_type);
4159
4160         if (is_binary) {
4161                 sprintf(&encoded_message[strlen(encoded_message)],
4162                         "Content-transfer-encoding: base64\n\n"
4163                 );
4164         }
4165         else {
4166                 sprintf(&encoded_message[strlen(encoded_message)],
4167                         "Content-transfer-encoding: 7bit\n\n"
4168                 );
4169         }
4170
4171         if (is_binary) {
4172                 CtdlEncodeBase64(
4173                         &encoded_message[strlen(encoded_message)],
4174                         raw_message,
4175                         (int)raw_length
4176                 );
4177         }
4178         else {
4179                 raw_message[raw_length] = 0;
4180                 memcpy(
4181                         &encoded_message[strlen(encoded_message)],
4182                         raw_message,
4183                         (int)(raw_length+1)
4184                 );
4185         }
4186
4187         free(raw_message);
4188
4189         lprintf(CTDL_DEBUG, "Allocating\n");
4190         msg = malloc(sizeof(struct CtdlMessage));
4191         memset(msg, 0, sizeof(struct CtdlMessage));
4192         msg->cm_magic = CTDLMESSAGE_MAGIC;
4193         msg->cm_anon_type = MES_NORMAL;
4194         msg->cm_format_type = 4;
4195         msg->cm_fields['A'] = strdup(CC->user.fullname);
4196         msg->cm_fields['O'] = strdup(req_room);
4197         msg->cm_fields['N'] = strdup(config.c_nodename);
4198         msg->cm_fields['H'] = strdup(config.c_humannode);
4199         msg->cm_flags = flags;
4200         
4201         msg->cm_fields['M'] = encoded_message;
4202
4203         /* Create the requested room if we have to. */
4204         if (getroom(&qrbuf, roomname) != 0) {
4205                 create_room(roomname, 
4206                         ( (is_mailbox != NULL) ? 5 : 3 ),
4207                         "", 0, 1, 0, VIEW_BBS);
4208         }
4209         /* If the caller specified this object as unique, delete all
4210          * other objects of this type that are currently in the room.
4211          */
4212         if (is_unique) {
4213                 lprintf(CTDL_DEBUG, "Deleted %d other msgs of this type\n",
4214                         CtdlDeleteMessages(roomname, NULL, 0, content_type)
4215                 );
4216         }
4217         /* Now write the data */
4218         CtdlSubmitMsg(msg, NULL, roomname);
4219         CtdlFreeMessage(msg);
4220 }
4221
4222
4223
4224
4225
4226
4227 void CtdlGetSysConfigBackend(long msgnum, void *userdata) {
4228         config_msgnum = msgnum;
4229 }
4230
4231
4232 char *CtdlGetSysConfig(char *sysconfname) {
4233         char hold_rm[ROOMNAMELEN];
4234         long msgnum;
4235         char *conf;
4236         struct CtdlMessage *msg;
4237         char buf[SIZ];
4238         
4239         strcpy(hold_rm, CC->room.QRname);
4240         if (getroom(&CC->room, SYSCONFIGROOM) != 0) {
4241                 getroom(&CC->room, hold_rm);
4242                 return NULL;
4243         }
4244
4245
4246         /* We want the last (and probably only) config in this room */
4247         begin_critical_section(S_CONFIG);
4248         config_msgnum = (-1L);
4249         CtdlForEachMessage(MSGS_LAST, 1, NULL, sysconfname, NULL,
4250                 CtdlGetSysConfigBackend, NULL);
4251         msgnum = config_msgnum;
4252         end_critical_section(S_CONFIG);
4253
4254         if (msgnum < 0L) {
4255                 conf = NULL;
4256         }
4257         else {
4258                 msg = CtdlFetchMessage(msgnum, 1);
4259                 if (msg != NULL) {
4260                         conf = strdup(msg->cm_fields['M']);
4261                         CtdlFreeMessage(msg);
4262                 }
4263                 else {
4264                         conf = NULL;
4265                 }
4266         }
4267
4268         getroom(&CC->room, hold_rm);
4269
4270         if (conf != NULL) do {
4271                 extract_token(buf, conf, 0, '\n', sizeof buf);
4272                 strcpy(conf, &conf[strlen(buf)+1]);
4273         } while ( (!IsEmptyStr(conf)) && (!IsEmptyStr(buf)) );
4274
4275         return(conf);
4276 }
4277
4278 void CtdlPutSysConfig(char *sysconfname, char *sysconfdata) {
4279         char temp[PATH_MAX];
4280         FILE *fp;
4281
4282         CtdlMakeTempFileName(temp, sizeof temp);
4283
4284         fp = fopen(temp, "w");
4285         if (fp == NULL) return;
4286         fprintf(fp, "%s", sysconfdata);
4287         fclose(fp);
4288
4289         /* this handy API function does all the work for us */
4290         CtdlWriteObject(SYSCONFIGROOM, sysconfname, temp, NULL, 0, 1, 0);
4291         unlink(temp);
4292 }
4293
4294
4295 /*
4296  * Determine whether a given Internet address belongs to the current user
4297  */
4298 int CtdlIsMe(char *addr, int addr_buf_len)
4299 {
4300         struct recptypes *recp;
4301         int i;
4302
4303         recp = validate_recipients(addr);
4304         if (recp == NULL) return(0);
4305
4306         if (recp->num_local == 0) {
4307                 free_recipients(recp);
4308                 return(0);
4309         }
4310
4311         for (i=0; i<recp->num_local; ++i) {
4312                 extract_token(addr, recp->recp_local, i, '|', addr_buf_len);
4313                 if (!strcasecmp(addr, CC->user.fullname)) {
4314                         free_recipients(recp);
4315                         return(1);
4316                 }
4317         }
4318
4319         free_recipients(recp);
4320         return(0);
4321 }
4322
4323
4324 /*
4325  * Citadel protocol command to do the same
4326  */
4327 void cmd_isme(char *argbuf) {
4328         char addr[256];
4329
4330         if (CtdlAccessCheck(ac_logged_in)) return;
4331         extract_token(addr, argbuf, 0, '|', sizeof addr);
4332
4333         if (CtdlIsMe(addr, sizeof addr)) {
4334                 cprintf("%d %s\n", CIT_OK, addr);
4335         }
4336         else {
4337                 cprintf("%d Not you.\n", ERROR + ILLEGAL_VALUE);
4338         }
4339
4340 }