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