d7473e8529687a8eac87868bd3714aecb9568327
[citadel.git] / citadel / internet_addressing.c
1 /*
2  * This file contains functions which handle the mapping of Internet addresses
3  * to users on the Citadel system.
4  *
5  * Copyright (c) 1987-2015 by the citadel.org team
6  *
7  * This program is open source software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License version 3.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  */
15
16
17 #include "sysdep.h"
18 #include <stdlib.h>
19 #include <unistd.h>
20 #include <stdio.h>
21 #include <fcntl.h>
22 #include <ctype.h>
23 #include <signal.h>
24 #include <pwd.h>
25 #include <errno.h>
26 #include <sys/types.h>
27 #include <time.h>
28 #include <sys/wait.h>
29 #include <string.h>
30 #include <limits.h>
31 #include <libcitadel.h>
32 #include "citadel.h"
33 #include "server.h"
34 #include "sysdep_decls.h"
35 #include "citserver.h"
36 #include "support.h"
37 #include "config.h"
38 #include "msgbase.h"
39 #include "internet_addressing.h"
40 #include "user_ops.h"
41 #include "room_ops.h"
42 #include "parsedate.h"
43 #include "database.h"
44 #include "ctdl_module.h"
45 #ifdef HAVE_ICONV
46 #include <iconv.h>
47
48 #if 0
49 /* This is the non-define version in case of s.b. needing to debug */
50 inline void FindNextEnd (char *bptr, char *end)
51 {
52         /* Find the next ?Q? */
53         end = strchr(bptr + 2, '?');
54         if (end == NULL) return NULL;
55         if (((*(end + 1) == 'B') || (*(end + 1) == 'Q')) && 
56             (*(end + 2) == '?')) {
57                 /* skip on to the end of the cluster, the next ?= */
58                 end = strstr(end + 3, "?=");
59         }
60         else
61                 /* sort of half valid encoding, try to find an end. */
62                 end = strstr(bptr, "?=");
63 }
64 #endif
65
66 #define FindNextEnd(bptr, end) { \
67         end = strchr(bptr + 2, '?'); \
68         if (end != NULL) { \
69                 if (((*(end + 1) == 'B') || (*(end + 1) == 'Q')) && (*(end + 2) == '?')) { \
70                         end = strstr(end + 3, "?="); \
71                 } else end = strstr(bptr, "?="); \
72         } \
73 }
74
75 /*
76  * Handle subjects with RFC2047 encoding such as:
77  * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
78  */
79 void utf8ify_rfc822_string(char *buf) {
80         char *start, *end, *next, *nextend, *ptr;
81         char newbuf[1024];
82         char charset[128];
83         char encoding[16];
84         char istr[1024];
85         iconv_t ic = (iconv_t)(-1) ;
86         char *ibuf;                     /**< Buffer of characters to be converted */
87         char *obuf;                     /**< Buffer for converted characters */
88         size_t ibuflen;                 /**< Length of input buffer */
89         size_t obuflen;                 /**< Length of output buffer */
90         char *isav;                     /**< Saved pointer to input buffer */
91         char *osav;                     /**< Saved pointer to output buffer */
92         int passes = 0;
93         int i, len, delta;
94         int illegal_non_rfc2047_encoding = 0;
95
96         /* Sometimes, badly formed messages contain strings which were simply
97          *  written out directly in some foreign character set instead of
98          *  using RFC2047 encoding.  This is illegal but we will attempt to
99          *  handle it anyway by converting from a user-specified default
100          *  charset to UTF-8 if we see any nonprintable characters.
101          */
102         len = strlen(buf);
103         for (i=0; i<len; ++i) {
104                 if ((buf[i] < 32) || (buf[i] > 126)) {
105                         illegal_non_rfc2047_encoding = 1;
106                         i = len; ///< take a shortcut, it won't be more than one.
107                 }
108         }
109         if (illegal_non_rfc2047_encoding) {
110                 const char *default_header_charset = "iso-8859-1";
111                 if ( (strcasecmp(default_header_charset, "UTF-8")) && (strcasecmp(default_header_charset, "us-ascii")) ) {
112                         ctdl_iconv_open("UTF-8", default_header_charset, &ic);
113                         if (ic != (iconv_t)(-1) ) {
114                                 ibuf = malloc(1024);
115                                 isav = ibuf;
116                                 safestrncpy(ibuf, buf, 1024);
117                                 ibuflen = strlen(ibuf);
118                                 obuflen = 1024;
119                                 obuf = (char *) malloc(obuflen);
120                                 osav = obuf;
121                                 iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
122                                 osav[1024-obuflen] = 0;
123                                 strcpy(buf, osav);
124                                 free(osav);
125                                 iconv_close(ic);
126                                 free(isav);
127                         }
128                 }
129         }
130
131         /* pre evaluate the first pair */
132         nextend = end = NULL;
133         len = strlen(buf);
134         start = strstr(buf, "=?");
135         if (start != NULL) 
136                 FindNextEnd (start, end);
137
138         while ((start != NULL) && (end != NULL))
139         {
140                 next = strstr(end, "=?");
141                 if (next != NULL)
142                         FindNextEnd(next, nextend);
143                 if (nextend == NULL)
144                         next = NULL;
145
146                 /* did we find two partitions */
147                 if ((next != NULL) && 
148                     ((next - end) > 2))
149                 {
150                         ptr = end + 2;
151                         while ((ptr < next) && 
152                                (isspace(*ptr) ||
153                                 (*ptr == '\r') ||
154                                 (*ptr == '\n') || 
155                                 (*ptr == '\t')))
156                                 ptr ++;
157                         /* did we find a gab just filled with blanks? */
158                         if (ptr == next)
159                         {
160                                 memmove (end + 2,
161                                          next,
162                                          len - (next - start));
163
164                                 /* now terminate the gab at the end */
165                                 delta = (next - end) - 2;
166                                 len -= delta;
167                                 buf[len] = '\0';
168
169                                 /* move next to its new location. */
170                                 next -= delta;
171                                 nextend -= delta;
172                         }
173                 }
174                 /* our next-pair is our new first pair now. */
175                 start = next;
176                 end = nextend;
177         }
178
179         /* Now we handle foreign character sets properly encoded
180          * in RFC2047 format.
181          */
182         start = strstr(buf, "=?");
183         FindNextEnd((start != NULL)? start : buf, end);
184         while (start != NULL && end != NULL && end > start)
185         {
186                 extract_token(charset, start, 1, '?', sizeof charset);
187                 extract_token(encoding, start, 2, '?', sizeof encoding);
188                 extract_token(istr, start, 3, '?', sizeof istr);
189
190                 ibuf = malloc(1024);
191                 isav = ibuf;
192                 if (!strcasecmp(encoding, "B")) {       /**< base64 */
193                         ibuflen = CtdlDecodeBase64(ibuf, istr, strlen(istr));
194                 }
195                 else if (!strcasecmp(encoding, "Q")) {  /**< quoted-printable */
196                         size_t len;
197                         unsigned long pos;
198                         
199                         len = strlen(istr);
200                         pos = 0;
201                         while (pos < len)
202                         {
203                                 if (istr[pos] == '_') istr[pos] = ' ';
204                                 pos++;
205                         }
206
207                         ibuflen = CtdlDecodeQuotedPrintable(ibuf, istr, len);
208                 }
209                 else {
210                         strcpy(ibuf, istr);             /**< unknown encoding */
211                         ibuflen = strlen(istr);
212                 }
213
214                 ctdl_iconv_open("UTF-8", charset, &ic);
215                 if (ic != (iconv_t)(-1) ) {
216                         obuflen = 1024;
217                         obuf = (char *) malloc(obuflen);
218                         osav = obuf;
219                         iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
220                         osav[1024-obuflen] = 0;
221
222                         end = start;
223                         end++;
224                         strcpy(start, "");
225                         remove_token(end, 0, '?');
226                         remove_token(end, 0, '?');
227                         remove_token(end, 0, '?');
228                         remove_token(end, 0, '?');
229                         strcpy(end, &end[1]);
230
231                         snprintf(newbuf, sizeof newbuf, "%s%s%s", buf, osav, end);
232                         strcpy(buf, newbuf);
233                         free(osav);
234                         iconv_close(ic);
235                 }
236                 else {
237                         end = start;
238                         end++;
239                         strcpy(start, "");
240                         remove_token(end, 0, '?');
241                         remove_token(end, 0, '?');
242                         remove_token(end, 0, '?');
243                         remove_token(end, 0, '?');
244                         strcpy(end, &end[1]);
245
246                         snprintf(newbuf, sizeof newbuf, "%s(unreadable)%s", buf, end);
247                         strcpy(buf, newbuf);
248                 }
249
250                 free(isav);
251
252                 /*
253                  * Since spammers will go to all sorts of absurd lengths to get their
254                  * messages through, there are LOTS of corrupt headers out there.
255                  * So, prevent a really badly formed RFC2047 header from throwing
256                  * this function into an infinite loop.
257                  */
258                 ++passes;
259                 if (passes > 20) return;
260
261                 start = strstr(buf, "=?");
262                 FindNextEnd((start != NULL)? start : buf, end);
263         }
264
265 }
266 #else
267 inline void utf8ify_rfc822_string(char *a){};
268
269 #endif
270
271
272
273 struct trynamebuf {
274         char buffer1[SIZ];
275         char buffer2[SIZ];
276 };
277
278 char *inetcfg = NULL;
279 struct spamstrings_t *spamstrings = NULL;
280
281
282 /*
283  * Return nonzero if the supplied name is an alias for this host.
284  */
285 int CtdlHostAlias(char *fqdn) {
286         int config_lines;
287         int i;
288         char buf[256];
289         char host[256], type[256];
290         int found = 0;
291
292         if (fqdn == NULL) return(hostalias_nomatch);
293         if (IsEmptyStr(fqdn)) return(hostalias_nomatch);
294         if (!strcasecmp(fqdn, "localhost")) return(hostalias_localhost);
295         if (!strcasecmp(fqdn, CtdlGetConfigStr("c_fqdn"))) return(hostalias_localhost);
296         if (!strcasecmp(fqdn, CtdlGetConfigStr("c_nodename"))) return(hostalias_localhost);
297         if (inetcfg == NULL) return(hostalias_nomatch);
298
299         config_lines = num_tokens(inetcfg, '\n');
300         for (i=0; i<config_lines; ++i) {
301                 extract_token(buf, inetcfg, i, '\n', sizeof buf);
302                 extract_token(host, buf, 0, '|', sizeof host);
303                 extract_token(type, buf, 1, '|', sizeof type);
304
305                 found = 0;
306
307                 /* Process these in a specific order, in case there are multiple matches.
308                  * We want directory to override masq, for example.
309                  */
310
311                 if ( (!strcasecmp(type, "masqdomain")) && (!strcasecmp(fqdn, host))) {
312                         found = hostalias_masq;
313                 }
314                 if ( (!strcasecmp(type, "localhost")) && (!strcasecmp(fqdn, host))) {
315                         found = hostalias_localhost;
316                 }
317                 if ( (!strcasecmp(type, "directory")) && (!strcasecmp(fqdn, host))) {
318                         found = hostalias_directory;
319                 }
320
321                 if (found) return(found);
322         }
323
324         return(hostalias_nomatch);
325 }
326
327
328
329 /*
330  * Determine whether a given Internet address belongs to the current user
331  */
332 int CtdlIsMe(char *addr, int addr_buf_len)
333 {
334         recptypes *recp;
335         int i;
336
337         recp = validate_recipients(addr, NULL, 0);
338         if (recp == NULL) return(0);
339
340         if (recp->num_local == 0) {
341                 free_recipients(recp);
342                 return(0);
343         }
344
345         for (i=0; i<recp->num_local; ++i) {
346                 extract_token(addr, recp->recp_local, i, '|', addr_buf_len);
347                 if (!strcasecmp(addr, CC->user.fullname)) {
348                         free_recipients(recp);
349                         return(1);
350                 }
351         }
352
353         free_recipients(recp);
354         return(0);
355 }
356
357
358 /* If the last item in a list of recipients was truncated to a partial address,
359  * remove it completely in order to avoid choking libSieve
360  */
361 void sanitize_truncated_recipient(char *str)
362 {
363         if (!str) return;
364         if (num_tokens(str, ',') < 2) return;
365
366         int len = strlen(str);
367         if (len < 900) return;
368         if (len > 998) str[998] = 0;
369
370         char *cptr = strrchr(str, ',');
371         if (!cptr) return;
372
373         char *lptr = strchr(cptr, '<');
374         char *rptr = strchr(cptr, '>');
375
376         if ( (lptr) && (rptr) && (rptr > lptr) ) return;
377
378         *cptr = 0;
379 }
380
381
382
383
384
385 /*
386  * This function is self explanatory.
387  * (What can I say, I'm in a weird mood today...)
388  */
389 void remove_any_whitespace_to_the_left_or_right_of_at_symbol(char *name)
390 {
391         unsigned int i;
392
393         for (i = 0; i < strlen(name); ++i) {
394                 if (name[i] == '@') {
395                         while (isspace(name[i - 1]) && i > 0) {
396                                 strcpy(&name[i - 1], &name[i]);
397                                 --i;
398                         }
399                         while (isspace(name[i + 1])) {
400                                 strcpy(&name[i + 1], &name[i + 2]);
401                         }
402                 }
403         }
404 }
405
406
407 /*
408  * Aliasing for network mail.
409  * (Error messages have been commented out, because this is a server.)
410  */
411 int alias(char *name)
412 {                               /* process alias and routing info for mail */
413         struct CitContext *CCC = CC;
414         FILE *fp;
415         int a, i;
416         char aaa[SIZ], bbb[SIZ];
417         char *ignetcfg = NULL;
418         char *ignetmap = NULL;
419         int at = 0;
420         char node[64];
421         char testnode[64];
422         char buf[SIZ];
423
424         char original_name[256];
425         safestrncpy(original_name, name, sizeof original_name);
426
427         striplt(name);
428         remove_any_whitespace_to_the_left_or_right_of_at_symbol(name);
429         stripallbut(name, '<', '>');
430
431         fp = fopen(file_mail_aliases, "r");
432         if (fp == NULL) {
433                 fp = fopen("/dev/null", "r");
434         }
435         if (fp == NULL) {
436                 return (MES_ERROR);
437         }
438         strcpy(aaa, "");
439         strcpy(bbb, "");
440         while (fgets(aaa, sizeof aaa, fp) != NULL) {
441                 while (isspace(name[0]))
442                         strcpy(name, &name[1]);
443                 aaa[strlen(aaa) - 1] = 0;
444                 strcpy(bbb, "");
445                 for (a = 0; aaa[a] != '\0'; ++a) {
446                         if (aaa[a] == ',') {
447                                 strcpy(bbb, &aaa[a + 1]);
448                                 aaa[a] = 0;
449                                 break;
450                         }
451                 }
452                 if (!strcasecmp(name, aaa))
453                         strcpy(name, bbb);
454         }
455         fclose(fp);
456
457         /* Hit the Global Address Book */
458         if (CtdlDirectoryLookup(aaa, name, sizeof aaa) == 0) {
459                 strcpy(name, aaa);
460         }
461
462         if (strcasecmp(original_name, name)) {
463                 MSG_syslog(LOG_INFO, "%s is being forwarded to %s\n", original_name, name);
464         }
465
466         /* Change "user @ xxx" to "user" if xxx is an alias for this host */
467         for (a=0; name[a] != '\0'; ++a) {
468                 if (name[a] == '@') {
469                         if (CtdlHostAlias(&name[a+1]) == hostalias_localhost) {
470                                 name[a] = 0;
471                                 MSG_syslog(LOG_INFO, "Changed to <%s>\n", name);
472                                 break;
473                         }
474                 }
475         }
476
477         /* determine local or remote type, see citadel.h */
478         at = haschar(name, '@');
479         if (at == 0) return(MES_LOCAL);         /* no @'s - local address */
480         if (at > 1) return(MES_ERROR);          /* >1 @'s - invalid address */
481         remove_any_whitespace_to_the_left_or_right_of_at_symbol(name);
482
483         /* figure out the delivery mode */
484         extract_token(node, name, 1, '@', sizeof node);
485
486         /* If there are one or more dots in the nodename, we assume that it
487          * is an FQDN and will attempt SMTP delivery to the Internet.
488          */
489         if (haschar(node, '.') > 0) {
490                 return(MES_INTERNET);
491         }
492
493         /* Otherwise we look in the IGnet maps for a valid Citadel node.
494          * Try directly-connected nodes first...
495          */
496         ignetcfg = CtdlGetSysConfig(IGNETCFG);
497         for (i=0; i<num_tokens(ignetcfg, '\n'); ++i) {
498                 extract_token(buf, ignetcfg, i, '\n', sizeof buf);
499                 extract_token(testnode, buf, 0, '|', sizeof testnode);
500                 if (!strcasecmp(node, testnode)) {
501                         free(ignetcfg);
502                         return(MES_IGNET);
503                 }
504         }
505         free(ignetcfg);
506
507         /*
508          * Then try nodes that are two or more hops away.
509          */
510         ignetmap = CtdlGetSysConfig(IGNETMAP);
511         for (i=0; i<num_tokens(ignetmap, '\n'); ++i) {
512                 extract_token(buf, ignetmap, i, '\n', sizeof buf);
513                 extract_token(testnode, buf, 0, '|', sizeof testnode);
514                 if (!strcasecmp(node, testnode)) {
515                         free(ignetmap);
516                         return(MES_IGNET);
517                 }
518         }
519         free(ignetmap);
520
521         /* If we get to this point it's an invalid node name */
522         return (MES_ERROR);
523 }
524
525
526
527 /*
528  * Validate recipients, count delivery types and errors, and handle aliasing
529  * FIXME check for dupes!!!!!
530  *
531  * Returns 0 if all addresses are ok, ret->num_error = -1 if no addresses 
532  * were specified, or the number of addresses found invalid.
533  *
534  * Caller needs to free the result using free_recipients()
535  */
536 recptypes *validate_recipients(const char *supplied_recipients, 
537                                const char *RemoteIdentifier, 
538                                int Flags) {
539         struct CitContext *CCC = CC;
540         recptypes *ret;
541         char *recipients = NULL;
542         char *org_recp;
543         char this_recp[256];
544         char this_recp_cooked[256];
545         char append[SIZ];
546         long len;
547         int num_recps = 0;
548         int i, j;
549         int mailtype;
550         int invalid;
551         struct ctdluser tempUS;
552         struct ctdlroom tempQR;
553         struct ctdlroom tempQR2;
554         int err = 0;
555         char errmsg[SIZ];
556         int in_quotes = 0;
557
558         /* Initialize */
559         ret = (recptypes *) malloc(sizeof(recptypes));
560         if (ret == NULL) return(NULL);
561
562         /* Set all strings to null and numeric values to zero */
563         memset(ret, 0, sizeof(recptypes));
564
565         if (supplied_recipients == NULL) {
566                 recipients = strdup("");
567         }
568         else {
569                 recipients = strdup(supplied_recipients);
570         }
571
572         /* Allocate some memory.  Yes, this allocates 500% more memory than we will
573          * actually need, but it's healthier for the heap than doing lots of tiny
574          * realloc() calls instead.
575          */
576         len = strlen(recipients) + 1024;
577         ret->errormsg = malloc(len);
578         ret->recp_local = malloc(len);
579         ret->recp_internet = malloc(len);
580         ret->recp_ignet = malloc(len);
581         ret->recp_room = malloc(len);
582         ret->display_recp = malloc(len);
583         ret->recp_orgroom = malloc(len);
584         org_recp = malloc(len);
585
586         ret->errormsg[0] = 0;
587         ret->recp_local[0] = 0;
588         ret->recp_internet[0] = 0;
589         ret->recp_ignet[0] = 0;
590         ret->recp_room[0] = 0;
591         ret->recp_orgroom[0] = 0;
592         ret->display_recp[0] = 0;
593
594         ret->recptypes_magic = RECPTYPES_MAGIC;
595
596         /* Change all valid separator characters to commas */
597         for (i=0; !IsEmptyStr(&recipients[i]); ++i) {
598                 if ((recipients[i] == ';') || (recipients[i] == '|')) {
599                         recipients[i] = ',';
600                 }
601         }
602
603         /* Now start extracting recipients... */
604
605         while (!IsEmptyStr(recipients)) {
606                 for (i=0; i<=strlen(recipients); ++i) {
607                         if (recipients[i] == '\"') in_quotes = 1 - in_quotes;
608                         if ( ( (recipients[i] == ',') && (!in_quotes) ) || (recipients[i] == 0) ) {
609                                 safestrncpy(this_recp, recipients, i+1);
610                                 this_recp[i] = 0;
611                                 if (recipients[i] == ',') {
612                                         strcpy(recipients, &recipients[i+1]);
613                                 }
614                                 else {
615                                         strcpy(recipients, "");
616                                 }
617                                 break;
618                         }
619                 }
620
621                 striplt(this_recp);
622                 if (IsEmptyStr(this_recp))
623                         break;
624                 MSG_syslog(LOG_DEBUG, "Evaluating recipient #%d: %s\n", num_recps, this_recp);
625                 ++num_recps;
626
627                 strcpy(org_recp, this_recp);
628                 alias(this_recp);
629                 alias(this_recp);
630                 mailtype = alias(this_recp);
631
632                 for (j = 0; !IsEmptyStr(&this_recp[j]); ++j) {
633                         if (this_recp[j]=='_') {
634                                 this_recp_cooked[j] = ' ';
635                         }
636                         else {
637                                 this_recp_cooked[j] = this_recp[j];
638                         }
639                 }
640                 this_recp_cooked[j] = '\0';
641                 invalid = 0;
642                 errmsg[0] = 0;
643                 switch(mailtype) {
644                 case MES_LOCAL:
645                         if (!strcasecmp(this_recp, "sysop")) {
646                                 ++ret->num_room;
647                                 strcpy(this_recp, CtdlGetConfigStr("c_aideroom"));
648                                 if (!IsEmptyStr(ret->recp_room)) {
649                                         strcat(ret->recp_room, "|");
650                                 }
651                                 strcat(ret->recp_room, this_recp);
652                         }
653                         else if ( (!strncasecmp(this_recp, "room_", 5))
654                                   && (!CtdlGetRoom(&tempQR, &this_recp_cooked[5])) ) {
655
656                                 /* Save room so we can restore it later */
657                                 tempQR2 = CCC->room;
658                                 CCC->room = tempQR;
659                                         
660                                 /* Check permissions to send mail to this room */
661                                 err = CtdlDoIHavePermissionToPostInThisRoom(
662                                         errmsg, 
663                                         sizeof errmsg, 
664                                         RemoteIdentifier,
665                                         Flags,
666                                         0                       /* 0 = not a reply */
667                                         );
668                                 if (err)
669                                 {
670                                         ++ret->num_error;
671                                         invalid = 1;
672                                 } 
673                                 else {
674                                         ++ret->num_room;
675                                         if (!IsEmptyStr(ret->recp_room)) {
676                                                 strcat(ret->recp_room, "|");
677                                         }
678                                         strcat(ret->recp_room, &this_recp_cooked[5]);
679
680                                         if (!IsEmptyStr(ret->recp_orgroom)) {
681                                                 strcat(ret->recp_orgroom, "|");
682                                         }
683                                         strcat(ret->recp_orgroom, org_recp);
684
685                                 }
686                                         
687                                 /* Restore room in case something needs it */
688                                 CCC->room = tempQR2;
689
690                         }
691                         else if (CtdlGetUser(&tempUS, this_recp) == 0) {
692                                 ++ret->num_local;
693                                 strcpy(this_recp, tempUS.fullname);
694                                 if (!IsEmptyStr(ret->recp_local)) {
695                                         strcat(ret->recp_local, "|");
696                                 }
697                                 strcat(ret->recp_local, this_recp);
698                         }
699                         else if (CtdlGetUser(&tempUS, this_recp_cooked) == 0) {
700                                 ++ret->num_local;
701                                 strcpy(this_recp, tempUS.fullname);
702                                 if (!IsEmptyStr(ret->recp_local)) {
703                                         strcat(ret->recp_local, "|");
704                                 }
705                                 strcat(ret->recp_local, this_recp);
706                         }
707                         else {
708                                 ++ret->num_error;
709                                 invalid = 1;
710                         }
711                         break;
712                 case MES_INTERNET:
713                         /* Yes, you're reading this correctly: if the target
714                          * domain points back to the local system or an attached
715                          * Citadel directory, the address is invalid.  That's
716                          * because if the address were valid, we would have
717                          * already translated it to a local address by now.
718                          */
719                         if (IsDirectory(this_recp, 0)) {
720                                 ++ret->num_error;
721                                 invalid = 1;
722                         }
723                         else {
724                                 ++ret->num_internet;
725                                 if (!IsEmptyStr(ret->recp_internet)) {
726                                         strcat(ret->recp_internet, "|");
727                                 }
728                                 strcat(ret->recp_internet, this_recp);
729                         }
730                         break;
731                 case MES_IGNET:
732                         ++ret->num_ignet;
733                         if (!IsEmptyStr(ret->recp_ignet)) {
734                                 strcat(ret->recp_ignet, "|");
735                         }
736                         strcat(ret->recp_ignet, this_recp);
737                         break;
738                 case MES_ERROR:
739                         ++ret->num_error;
740                         invalid = 1;
741                         break;
742                 }
743                 if (invalid) {
744                         if (IsEmptyStr(errmsg)) {
745                                 snprintf(append, sizeof append, "Invalid recipient: %s", this_recp);
746                         }
747                         else {
748                                 snprintf(append, sizeof append, "%s", errmsg);
749                         }
750                         if ( (strlen(ret->errormsg) + strlen(append) + 3) < SIZ) {
751                                 if (!IsEmptyStr(ret->errormsg)) {
752                                         strcat(ret->errormsg, "; ");
753                                 }
754                                 strcat(ret->errormsg, append);
755                         }
756                 }
757                 else {
758                         if (IsEmptyStr(ret->display_recp)) {
759                                 strcpy(append, this_recp);
760                         }
761                         else {
762                                 snprintf(append, sizeof append, ", %s", this_recp);
763                         }
764                         if ( (strlen(ret->display_recp)+strlen(append)) < SIZ) {
765                                 strcat(ret->display_recp, append);
766                         }
767                 }
768         }
769         free(org_recp);
770
771         if ((ret->num_local + ret->num_internet + ret->num_ignet +
772              ret->num_room + ret->num_error) == 0) {
773                 ret->num_error = (-1);
774                 strcpy(ret->errormsg, "No recipients specified.");
775         }
776
777         MSGM_syslog(LOG_DEBUG, "validate_recipients()\n");
778         MSG_syslog(LOG_DEBUG, " local: %d <%s>\n", ret->num_local, ret->recp_local);
779         MSG_syslog(LOG_DEBUG, "  room: %d <%s>\n", ret->num_room, ret->recp_room);
780         MSG_syslog(LOG_DEBUG, "  inet: %d <%s>\n", ret->num_internet, ret->recp_internet);
781         MSG_syslog(LOG_DEBUG, " ignet: %d <%s>\n", ret->num_ignet, ret->recp_ignet);
782         MSG_syslog(LOG_DEBUG, " error: %d <%s>\n", ret->num_error, ret->errormsg);
783
784         free(recipients);
785         return(ret);
786 }
787
788
789 /*
790  * Destructor for recptypes
791  */
792 void free_recipients(recptypes *valid) {
793
794         if (valid == NULL) {
795                 return;
796         }
797
798         if (valid->recptypes_magic != RECPTYPES_MAGIC) {
799                 struct CitContext *CCC = CC;
800                 MSGM_syslog(LOG_EMERG, "Attempt to call free_recipients() on some other data type!\n");
801                 abort();
802         }
803
804         if (valid->errormsg != NULL)            free(valid->errormsg);
805         if (valid->recp_local != NULL)          free(valid->recp_local);
806         if (valid->recp_internet != NULL)       free(valid->recp_internet);
807         if (valid->recp_ignet != NULL)          free(valid->recp_ignet);
808         if (valid->recp_room != NULL)           free(valid->recp_room);
809         if (valid->recp_orgroom != NULL)        free(valid->recp_orgroom);
810         if (valid->display_recp != NULL)        free(valid->display_recp);
811         if (valid->bounce_to != NULL)           free(valid->bounce_to);
812         if (valid->envelope_from != NULL)       free(valid->envelope_from);
813         if (valid->sending_room != NULL)        free(valid->sending_room);
814         free(valid);
815 }
816
817
818 char *qp_encode_email_addrs(char *source)
819 {
820         struct CitContext *CCC = CC;
821         char *user, *node, *name;
822         const char headerStr[] = "=?UTF-8?Q?";
823         char *Encoded;
824         char *EncodedName;
825         char *nPtr;
826         int need_to_encode = 0;
827         long SourceLen;
828         long EncodedMaxLen;
829         long nColons = 0;
830         long *AddrPtr;
831         long *AddrUtf8;
832         long nAddrPtrMax = 50;
833         long nmax;
834         int InQuotes = 0;
835         int i, n;
836
837         if (source == NULL) return source;
838         if (IsEmptyStr(source)) return source;
839         if (MessageDebugEnabled != 0) cit_backtrace();
840         MSG_syslog(LOG_DEBUG, "qp_encode_email_addrs: [%s]\n", source);
841
842         AddrPtr = malloc (sizeof (long) * nAddrPtrMax);
843         AddrUtf8 = malloc (sizeof (long) * nAddrPtrMax);
844         memset(AddrUtf8, 0, sizeof (long) * nAddrPtrMax);
845         *AddrPtr = 0;
846         i = 0;
847         while (!IsEmptyStr (&source[i])) {
848                 if (nColons >= nAddrPtrMax){
849                         long *ptr;
850
851                         ptr = (long *) malloc(sizeof (long) * nAddrPtrMax * 2);
852                         memcpy (ptr, AddrPtr, sizeof (long) * nAddrPtrMax);
853                         free (AddrPtr), AddrPtr = ptr;
854
855                         ptr = (long *) malloc(sizeof (long) * nAddrPtrMax * 2);
856                         memset(&ptr[nAddrPtrMax], 0, 
857                                sizeof (long) * nAddrPtrMax);
858
859                         memcpy (ptr, AddrUtf8, sizeof (long) * nAddrPtrMax);
860                         free (AddrUtf8), AddrUtf8 = ptr;
861                         nAddrPtrMax *= 2;                               
862                 }
863                 if (((unsigned char) source[i] < 32) || 
864                     ((unsigned char) source[i] > 126)) {
865                         need_to_encode = 1;
866                         AddrUtf8[nColons] = 1;
867                 }
868                 if (source[i] == '"')
869                         InQuotes = !InQuotes;
870                 if (!InQuotes && source[i] == ',') {
871                         AddrPtr[nColons] = i;
872                         nColons++;
873                 }
874                 i++;
875         }
876         if (need_to_encode == 0) {
877                 free(AddrPtr);
878                 free(AddrUtf8);
879                 return source;
880         }
881
882         SourceLen = i;
883         EncodedMaxLen = nColons * (sizeof(headerStr) + 3) + SourceLen * 3;
884         Encoded = (char*) malloc (EncodedMaxLen);
885
886         for (i = 0; i < nColons; i++)
887                 source[AddrPtr[i]++] = '\0';
888         /* TODO: if libidn, this might get larger*/
889         user = malloc(SourceLen + 1);
890         node = malloc(SourceLen + 1);
891         name = malloc(SourceLen + 1);
892
893         nPtr = Encoded;
894         *nPtr = '\0';
895         for (i = 0; i < nColons && nPtr != NULL; i++) {
896                 nmax = EncodedMaxLen - (nPtr - Encoded);
897                 if (AddrUtf8[i]) {
898                         process_rfc822_addr(&source[AddrPtr[i]], 
899                                             user,
900                                             node,
901                                             name);
902                         /* TODO: libIDN here ! */
903                         if (IsEmptyStr(name)) {
904                                 n = snprintf(nPtr, nmax, 
905                                              (i==0)?"%s@%s" : ",%s@%s",
906                                              user, node);
907                         }
908                         else {
909                                 EncodedName = rfc2047encode(name, strlen(name));                        
910                                 n = snprintf(nPtr, nmax, 
911                                              (i==0)?"%s <%s@%s>" : ",%s <%s@%s>",
912                                              EncodedName, user, node);
913                                 free(EncodedName);
914                         }
915                 }
916                 else { 
917                         n = snprintf(nPtr, nmax, 
918                                      (i==0)?"%s" : ",%s",
919                                      &source[AddrPtr[i]]);
920                 }
921                 if (n > 0 )
922                         nPtr += n;
923                 else { 
924                         char *ptr, *nnPtr;
925                         ptr = (char*) malloc(EncodedMaxLen * 2);
926                         memcpy(ptr, Encoded, EncodedMaxLen);
927                         nnPtr = ptr + (nPtr - Encoded), nPtr = nnPtr;
928                         free(Encoded), Encoded = ptr;
929                         EncodedMaxLen *= 2;
930                         i--; /* do it once more with properly lengthened buffer */
931                 }
932         }
933         for (i = 0; i < nColons; i++)
934                 source[--AddrPtr[i]] = ',';
935
936         free(user);
937         free(node);
938         free(name);
939         free(AddrUtf8);
940         free(AddrPtr);
941         return Encoded;
942 }
943
944
945 /*
946  * Return 0 if a given string fuzzy-matches a Citadel user account
947  *
948  * FIXME ... this needs to be updated to handle aliases.
949  */
950 int fuzzy_match(struct ctdluser *us, char *matchstring) {
951         int a;
952         long len;
953
954         if ( (!strncasecmp(matchstring, "cit", 3)) 
955            && (atol(&matchstring[3]) == us->usernum)) {
956                 return 0;
957         }
958
959         len = strlen(matchstring);
960         for (a=0; !IsEmptyStr(&us->fullname[a]); ++a) {
961                 if (!strncasecmp(&us->fullname[a],
962                    matchstring, len)) {
963                         return 0;
964                 }
965         }
966         return -1;
967 }
968
969
970 /*
971  * Unfold a multi-line field into a single line, removing multi-whitespaces
972  */
973 void unfold_rfc822_field(char **field, char **FieldEnd) 
974 {
975         int quote = 0;
976         char *pField = *field;
977         char *sField;
978         char *pFieldEnd = *FieldEnd;
979
980         while (isspace(*pField))
981                 pField++;
982         /* remove leading/trailing whitespace */
983         ;
984
985         while (isspace(*pFieldEnd))
986                 pFieldEnd --;
987
988         *FieldEnd = pFieldEnd;
989         /* convert non-space whitespace to spaces, and remove double blanks */
990         for (sField = *field = pField; 
991              sField < pFieldEnd; 
992              pField++, sField++)
993         {
994                 if ((*sField=='\r') || (*sField=='\n'))
995                 {
996                         int Offset = 1;
997                         while (((*(sField + Offset) == '\r') ||
998                                 (*(sField + Offset) == '\n') ||
999                                 (isspace(*(sField + Offset)))) && 
1000                                (sField + Offset < pFieldEnd))
1001                                 Offset ++;
1002                         sField += Offset;
1003                         *pField = *sField;
1004                 }
1005                 else {
1006                         if (*sField=='\"') quote = 1 - quote;
1007                         if (!quote) {
1008                                 if (isspace(*sField))
1009                                 {
1010                                         *pField = ' ';
1011                                         pField++;
1012                                         sField++;
1013                                         
1014                                         while ((sField < pFieldEnd) && 
1015                                                isspace(*sField))
1016                                                 sField++;
1017                                         *pField = *sField;
1018                                 }
1019                                 else *pField = *sField;
1020                         }
1021                         else *pField = *sField;
1022                 }
1023         }
1024         *pField = '\0';
1025         *FieldEnd = pField - 1;
1026 }
1027
1028
1029
1030 /*
1031  * Split an RFC822-style address into userid, host, and full name
1032  *
1033  */
1034 void process_rfc822_addr(const char *rfc822, char *user, char *node, char *name)
1035 {
1036         int a;
1037
1038         strcpy(user, "");
1039         strcpy(node, CtdlGetConfigStr("c_fqdn"));
1040         strcpy(name, "");
1041
1042         if (rfc822 == NULL) return;
1043
1044         /* extract full name - first, it's From minus <userid> */
1045         strcpy(name, rfc822);
1046         stripout(name, '<', '>');
1047
1048         /* strip anything to the left of a bang */
1049         while ((!IsEmptyStr(name)) && (haschar(name, '!') > 0))
1050                 strcpy(name, &name[1]);
1051
1052         /* and anything to the right of a @ or % */
1053         for (a = 0; name[a] != '\0'; ++a) {
1054                 if (name[a] == '@') {
1055                         name[a] = 0;
1056                         break;
1057                 }
1058                 if (name[a] == '%') {
1059                         name[a] = 0;
1060                         break;
1061                 }
1062         }
1063
1064         /* but if there are parentheses, that changes the rules... */
1065         if ((haschar(rfc822, '(') == 1) && (haschar(rfc822, ')') == 1)) {
1066                 strcpy(name, rfc822);
1067                 stripallbut(name, '(', ')');
1068         }
1069
1070         /* but if there are a set of quotes, that supersedes everything */
1071         if (haschar(rfc822, 34) == 2) {
1072                 strcpy(name, rfc822);
1073                 while ((!IsEmptyStr(name)) && (name[0] != 34)) {
1074                         strcpy(&name[0], &name[1]);
1075                 }
1076                 strcpy(&name[0], &name[1]);
1077                 for (a = 0; name[a] != '\0'; ++a)
1078                         if (name[a] == 34) {
1079                                 name[a] = 0;
1080                                 break;
1081                         }
1082         }
1083         /* extract user id */
1084         strcpy(user, rfc822);
1085
1086         /* first get rid of anything in parens */
1087         stripout(user, '(', ')');
1088
1089         /* if there's a set of angle brackets, strip it down to that */
1090         if ((haschar(user, '<') == 1) && (haschar(user, '>') == 1)) {
1091                 stripallbut(user, '<', '>');
1092         }
1093
1094         /* strip anything to the left of a bang */
1095         while ((!IsEmptyStr(user)) && (haschar(user, '!') > 0))
1096                 strcpy(user, &user[1]);
1097
1098         /* and anything to the right of a @ or % */
1099         for (a = 0; user[a] != '\0'; ++a) {
1100                 if (user[a] == '@') {
1101                         user[a] = 0;
1102                         break;
1103                 }
1104                 if (user[a] == '%') {
1105                         user[a] = 0;
1106                         break;
1107                 }
1108         }
1109
1110
1111         /* extract node name */
1112         strcpy(node, rfc822);
1113
1114         /* first get rid of anything in parens */
1115         stripout(node, '(', ')');
1116
1117         /* if there's a set of angle brackets, strip it down to that */
1118         if ((haschar(node, '<') == 1) && (haschar(node, '>') == 1)) {
1119                 stripallbut(node, '<', '>');
1120         }
1121
1122         /* If no node specified, tack ours on instead */
1123         if (
1124                 (haschar(node, '@')==0)
1125                 && (haschar(node, '%')==0)
1126                 && (haschar(node, '!')==0)
1127         ) {
1128                 strcpy(node, CtdlGetConfigStr("c_nodename"));
1129         }
1130
1131         else {
1132
1133                 /* strip anything to the left of a @ */
1134                 while ((!IsEmptyStr(node)) && (haschar(node, '@') > 0))
1135                         strcpy(node, &node[1]);
1136         
1137                 /* strip anything to the left of a % */
1138                 while ((!IsEmptyStr(node)) && (haschar(node, '%') > 0))
1139                         strcpy(node, &node[1]);
1140         
1141                 /* reduce multiple system bang paths to node!user */
1142                 while ((!IsEmptyStr(node)) && (haschar(node, '!') > 1))
1143                         strcpy(node, &node[1]);
1144         
1145                 /* now get rid of the user portion of a node!user string */
1146                 for (a = 0; node[a] != '\0'; ++a)
1147                         if (node[a] == '!') {
1148                                 node[a] = 0;
1149                                 break;
1150                         }
1151         }
1152
1153         /* strip leading and trailing spaces in all strings */
1154         striplt(user);
1155         striplt(node);
1156         striplt(name);
1157
1158         /* If we processed a string that had the address in angle brackets
1159          * but no name outside the brackets, we now have an empty name.  In
1160          * this case, use the user portion of the address as the name.
1161          */
1162         if ((IsEmptyStr(name)) && (!IsEmptyStr(user))) {
1163                 strcpy(name, user);
1164         }
1165 }
1166
1167
1168
1169 /*
1170  * convert_field() is a helper function for convert_internet_message().
1171  * Given start/end positions for an rfc822 field, it converts it to a Citadel
1172  * field if it wants to, and unfolds it if necessary.
1173  *
1174  * Returns 1 if the field was converted and inserted into the Citadel message
1175  * structure, implying that the source field should be removed from the
1176  * message text.
1177  */
1178 int convert_field(struct CtdlMessage *msg, const char *beg, const char *end) {
1179         struct CitContext *CCC = CC;
1180         char *key, *value, *valueend;
1181         long len;
1182         const char *pos;
1183         int i;
1184         const char *colonpos = NULL;
1185         int processed = 0;
1186         char user[1024];
1187         char node[1024];
1188         char name[1024];
1189         char addr[1024];
1190         time_t parsed_date;
1191         long valuelen;
1192
1193         for (pos = end; pos >= beg; pos--) {
1194                 if (*pos == ':') colonpos = pos;
1195         }
1196
1197         if (colonpos == NULL) return(0);        /* no colon? not a valid header line */
1198
1199         len = end - beg;
1200         key = malloc(len + 2);
1201         memcpy(key, beg, len + 1);
1202         key[len] = '\0';
1203         valueend = key + len;
1204         * ( key + (colonpos - beg) ) = '\0';
1205         value = &key[(colonpos - beg) + 1];
1206 /*      printf("Header: [%s]\nValue: [%s]\n", key, value); */
1207         unfold_rfc822_field(&value, &valueend);
1208         valuelen = valueend - value + 1;
1209 /*      printf("UnfoldedValue: [%s]\n", value); */
1210
1211         /*
1212          * Here's the big rfc822-to-citadel loop.
1213          */
1214
1215         /* Date/time is converted into a unix timestamp.  If the conversion
1216          * fails, we replace it with the time the message arrived locally.
1217          */
1218         if (!strcasecmp(key, "Date")) {
1219                 parsed_date = parsedate(value);
1220                 if (parsed_date < 0L) parsed_date = time(NULL);
1221
1222                 if (CM_IsEmpty(msg, eTimestamp))
1223                         CM_SetFieldLONG(msg, eTimestamp, parsed_date);
1224                 processed = 1;
1225         }
1226
1227         else if (!strcasecmp(key, "From")) {
1228                 process_rfc822_addr(value, user, node, name);
1229                 MSG_syslog(LOG_DEBUG, "Converted to <%s@%s> (%s)\n", user, node, name);
1230                 snprintf(addr, sizeof(addr), "%s@%s", user, node);
1231                 if (CM_IsEmpty(msg, eAuthor) && !IsEmptyStr(name))
1232                         CM_SetField(msg, eAuthor, name, strlen(name));
1233                 if (CM_IsEmpty(msg, erFc822Addr) && !IsEmptyStr(addr))
1234                         CM_SetField(msg, erFc822Addr, addr, strlen(addr));
1235                 processed = 1;
1236         }
1237
1238         else if (!strcasecmp(key, "Subject")) {
1239                 if (CM_IsEmpty(msg, eMsgSubject))
1240                         CM_SetField(msg, eMsgSubject, value, valuelen);
1241                 processed = 1;
1242         }
1243
1244         else if (!strcasecmp(key, "List-ID")) {
1245                 if (CM_IsEmpty(msg, eListID))
1246                         CM_SetField(msg, eListID, value, valuelen);
1247                 processed = 1;
1248         }
1249
1250         else if (!strcasecmp(key, "To")) {
1251                 if (CM_IsEmpty(msg, eRecipient))
1252                         CM_SetField(msg, eRecipient, value, valuelen);
1253                 processed = 1;
1254         }
1255
1256         else if (!strcasecmp(key, "CC")) {
1257                 if (CM_IsEmpty(msg, eCarbonCopY))
1258                         CM_SetField(msg, eCarbonCopY, value, valuelen);
1259                 processed = 1;
1260         }
1261
1262         else if (!strcasecmp(key, "Message-ID")) {
1263                 if (!CM_IsEmpty(msg, emessageId)) {
1264                         syslog(LOG_WARNING, "duplicate message id\n");
1265                 }
1266                 else {
1267                         char *pValue;
1268                         long pValueLen;
1269
1270                         pValue = value;
1271                         pValueLen = valuelen;
1272                         /* Strip angle brackets */
1273                         while (haschar(pValue, '<') > 0) {
1274                                 pValue ++;
1275                                 pValueLen --;
1276                         }
1277
1278                         for (i = 0; i <= pValueLen; ++i)
1279                                 if (pValue[i] == '>') {
1280                                         pValueLen = i;
1281                                         break;
1282                                 }
1283
1284                         CM_SetField(msg, emessageId, pValue, pValueLen);
1285                 }
1286
1287                 processed = 1;
1288         }
1289
1290         else if (!strcasecmp(key, "Return-Path")) {
1291                 if (CM_IsEmpty(msg, eMessagePath))
1292                         CM_SetField(msg, eMessagePath, value, valuelen);
1293                 processed = 1;
1294         }
1295
1296         else if (!strcasecmp(key, "Envelope-To")) {
1297                 if (CM_IsEmpty(msg, eenVelopeTo))
1298                         CM_SetField(msg, eenVelopeTo, value, valuelen);
1299                 processed = 1;
1300         }
1301
1302         else if (!strcasecmp(key, "References")) {
1303                 CM_SetField(msg, eWeferences, value, valuelen);
1304                 processed = 1;
1305         }
1306
1307         else if (!strcasecmp(key, "Reply-To")) {
1308                 CM_SetField(msg, eReplyTo, value, valuelen);
1309                 processed = 1;
1310         }
1311
1312         else if (!strcasecmp(key, "In-reply-to")) {
1313                 if (CM_IsEmpty(msg, eWeferences)) /* References: supersedes In-reply-to: */
1314                         CM_SetField(msg, eWeferences, value, valuelen);
1315                 processed = 1;
1316         }
1317
1318
1319
1320         /* Clean up and move on. */
1321         free(key);      /* Don't free 'value', it's actually the same buffer */
1322         return processed;
1323 }
1324
1325
1326 /*
1327  * Convert RFC822 references format (References) to Citadel references format (Weferences)
1328  */
1329 void convert_references_to_wefewences(char *str) {
1330         int bracket_nesting = 0;
1331         char *ptr = str;
1332         char *moveptr = NULL;
1333         char ch;
1334
1335         while(*ptr) {
1336                 ch = *ptr;
1337                 if (ch == '>') {
1338                         --bracket_nesting;
1339                         if (bracket_nesting < 0) bracket_nesting = 0;
1340                 }
1341                 if ((ch == '>') && (bracket_nesting == 0) && (*(ptr+1)) && (ptr>str) ) {
1342                         *ptr = '|';
1343                         ++ptr;
1344                 }
1345                 else if (bracket_nesting > 0) {
1346                         ++ptr;
1347                 }
1348                 else {
1349                         moveptr = ptr;
1350                         while (*moveptr) {
1351                                 *moveptr = *(moveptr+1);
1352                                 ++moveptr;
1353                         }
1354                 }
1355                 if (ch == '<') ++bracket_nesting;
1356         }
1357
1358 }
1359
1360
1361 /*
1362  * Convert an RFC822 message (headers + body) to a CtdlMessage structure.
1363  * NOTE: the supplied buffer becomes part of the CtdlMessage structure, and
1364  * will be deallocated when CM_Free() is called.  Therefore, the
1365  * supplied buffer should be DEREFERENCED.  It should not be freed or used
1366  * again.
1367  */
1368 struct CtdlMessage *convert_internet_message(char *rfc822) {
1369         StrBuf *RFCBuf = NewStrBufPlain(rfc822, -1);
1370         free (rfc822);
1371         return convert_internet_message_buf(&RFCBuf);
1372 }
1373
1374
1375
1376 struct CtdlMessage *convert_internet_message_buf(StrBuf **rfc822)
1377 {
1378         struct CtdlMessage *msg;
1379         const char *pos, *beg, *end, *totalend;
1380         int done, alldone = 0;
1381         int converted;
1382         StrBuf *OtherHeaders;
1383
1384         msg = malloc(sizeof(struct CtdlMessage));
1385         if (msg == NULL) return msg;
1386
1387         memset(msg, 0, sizeof(struct CtdlMessage));
1388         msg->cm_magic = CTDLMESSAGE_MAGIC;      /* self check */
1389         msg->cm_anon_type = 0;                  /* never anonymous */
1390         msg->cm_format_type = FMT_RFC822;       /* internet message */
1391
1392         pos = ChrPtr(*rfc822);
1393         totalend = pos + StrLength(*rfc822);
1394         done = 0;
1395         OtherHeaders = NewStrBufPlain(NULL, StrLength(*rfc822));
1396
1397         while (!alldone) {
1398
1399                 /* Locate beginning and end of field, keeping in mind that
1400                  * some fields might be multiline
1401                  */
1402                 end = beg = pos;
1403
1404                 while ((end < totalend) && 
1405                        (end == beg) && 
1406                        (done == 0) ) 
1407                 {
1408
1409                         if ( (*pos=='\n') && ((*(pos+1))!=0x20) && ((*(pos+1))!=0x09) )
1410                         {
1411                                 end = pos;
1412                         }
1413
1414                         /* done with headers? */
1415                         if ((*pos=='\n') &&
1416                             ( (*(pos+1)=='\n') ||
1417                               (*(pos+1)=='\r')) ) 
1418                         {
1419                                 alldone = 1;
1420                         }
1421
1422                         if (pos >= (totalend - 1) )
1423                         {
1424                                 end = pos;
1425                                 done = 1;
1426                         }
1427
1428                         ++pos;
1429
1430                 }
1431
1432                 /* At this point we have a field.  Are we interested in it? */
1433                 converted = convert_field(msg, beg, end);
1434
1435                 /* Strip the field out of the RFC822 header if we used it */
1436                 if (!converted) {
1437                         StrBufAppendBufPlain(OtherHeaders, beg, end - beg, 0);
1438                         StrBufAppendBufPlain(OtherHeaders, HKEY("\n"), 0);
1439                 }
1440
1441                 /* If we've hit the end of the message, bail out */
1442                 if (pos >= totalend)
1443                         alldone = 1;
1444         }
1445         StrBufAppendBufPlain(OtherHeaders, HKEY("\n"), 0);
1446         if (pos < totalend)
1447                 StrBufAppendBufPlain(OtherHeaders, pos, totalend - pos, 0);
1448         FreeStrBuf(rfc822);
1449         CM_SetAsFieldSB(msg, eMesageText, &OtherHeaders);
1450
1451         /* Follow-up sanity checks... */
1452
1453         /* If there's no timestamp on this message, set it to now. */
1454         if (CM_IsEmpty(msg, eTimestamp)) {
1455                 CM_SetFieldLONG(msg, eTimestamp, time(NULL));
1456         }
1457
1458         /* If a W (references, or rather, Wefewences) field is present, we
1459          * have to convert it from RFC822 format to Citadel format.
1460          */
1461         if (!CM_IsEmpty(msg, eWeferences)) {
1462                 /// todo: API!
1463                 convert_references_to_wefewences(msg->cm_fields[eWeferences]);
1464         }
1465
1466         return msg;
1467 }
1468
1469
1470
1471 /*
1472  * Look for a particular header field in an RFC822 message text.  If the
1473  * requested field is found, it is unfolded (if necessary) and returned to
1474  * the caller.  The field name is stripped out, leaving only its contents.
1475  * The caller is responsible for freeing the returned buffer.  If the requested
1476  * field is not present, or anything else goes wrong, it returns NULL.
1477  */
1478 char *rfc822_fetch_field(const char *rfc822, const char *fieldname) {
1479         char *fieldbuf = NULL;
1480         const char *end_of_headers;
1481         const char *field_start;
1482         const char *ptr;
1483         char *cont;
1484         char fieldhdr[SIZ];
1485
1486         /* Should never happen, but sometimes we get stupid */
1487         if (rfc822 == NULL) return(NULL);
1488         if (fieldname == NULL) return(NULL);
1489
1490         snprintf(fieldhdr, sizeof fieldhdr, "%s:", fieldname);
1491
1492         /* Locate the end of the headers, so we don't run past that point */
1493         end_of_headers = cbmstrcasestr(rfc822, "\n\r\n");
1494         if (end_of_headers == NULL) {
1495                 end_of_headers = cbmstrcasestr(rfc822, "\n\n");
1496         }
1497         if (end_of_headers == NULL) return (NULL);
1498
1499         field_start = cbmstrcasestr(rfc822, fieldhdr);
1500         if (field_start == NULL) return(NULL);
1501         if (field_start > end_of_headers) return(NULL);
1502
1503         fieldbuf = malloc(SIZ);
1504         strcpy(fieldbuf, "");
1505
1506         ptr = field_start;
1507         ptr = cmemreadline(ptr, fieldbuf, SIZ-strlen(fieldbuf) );
1508         while ( (isspace(ptr[0])) && (ptr < end_of_headers) ) {
1509                 strcat(fieldbuf, " ");
1510                 cont = &fieldbuf[strlen(fieldbuf)];
1511                 ptr = cmemreadline(ptr, cont, SIZ-strlen(fieldbuf) );
1512                 striplt(cont);
1513         }
1514
1515         strcpy(fieldbuf, &fieldbuf[strlen(fieldhdr)]);
1516         striplt(fieldbuf);
1517
1518         return(fieldbuf);
1519 }
1520
1521
1522
1523 /*****************************************************************************
1524  *                      DIRECTORY MANAGEMENT FUNCTIONS                       *
1525  *****************************************************************************/
1526
1527 /*
1528  * Generate the index key for an Internet e-mail address to be looked up
1529  * in the database.
1530  */
1531 void directory_key(char *key, char *addr) {
1532         int i;
1533         int keylen = 0;
1534         struct CitContext *CCC = CC;
1535
1536         for (i=0; !IsEmptyStr(&addr[i]); ++i) {
1537                 if (!isspace(addr[i])) {
1538                         key[keylen++] = tolower(addr[i]);
1539                 }
1540         }
1541         key[keylen++] = 0;
1542
1543         MSG_syslog(LOG_DEBUG, "Directory key is <%s>\n", key);
1544 }
1545
1546
1547
1548 /* Return nonzero if the supplied address is in a domain we keep in
1549  * the directory
1550  */
1551 int IsDirectory(char *addr, int allow_masq_domains) {
1552         char domain[256];
1553         int h;
1554
1555         extract_token(domain, addr, 1, '@', sizeof domain);
1556         striplt(domain);
1557
1558         h = CtdlHostAlias(domain);
1559
1560         if ( (h == hostalias_masq) && allow_masq_domains)
1561                 return(1);
1562         
1563         if ( (h == hostalias_localhost) || (h == hostalias_directory) ) {
1564                 return(1);
1565         }
1566         else {
1567                 return(0);
1568         }
1569 }
1570
1571
1572 /*
1573  * Initialize the directory database (erasing anything already there)
1574  */
1575 void CtdlDirectoryInit(void) {
1576         cdb_trunc(CDB_DIRECTORY);
1577 }
1578
1579
1580 /*
1581  * Add an Internet e-mail address to the directory for a user
1582  */
1583 int CtdlDirectoryAddUser(char *internet_addr, char *citadel_addr) {
1584         char key[SIZ];
1585         struct CitContext *CCC = CC;
1586
1587         if (IsDirectory(internet_addr, 0) == 0) 
1588                 return 0;
1589         MSG_syslog(LOG_DEBUG, "Create directory entry: %s --> %s\n", internet_addr, citadel_addr);
1590         directory_key(key, internet_addr);
1591         cdb_store(CDB_DIRECTORY, key, strlen(key), citadel_addr, strlen(citadel_addr)+1 );
1592         return 1;
1593 }
1594
1595
1596 /*
1597  * Delete an Internet e-mail address from the directory.
1598  *
1599  * (NOTE: we don't actually use or need the citadel_addr variable; it's merely
1600  * here because the callback API expects to be able to send it.)
1601  */
1602 int CtdlDirectoryDelUser(char *internet_addr, char *citadel_addr) {
1603         char key[SIZ];
1604         struct CitContext *CCC = CC;
1605         
1606         MSG_syslog(LOG_DEBUG, "Delete directory entry: %s --> %s\n", internet_addr, citadel_addr);
1607         directory_key(key, internet_addr);
1608         return cdb_delete(CDB_DIRECTORY, key, strlen(key) ) == 0;
1609 }
1610
1611
1612 /*
1613  * Look up an Internet e-mail address in the directory.
1614  * On success: returns 0, and Citadel address stored in 'target'
1615  * On failure: returns nonzero
1616  */
1617 int CtdlDirectoryLookup(char *target, char *internet_addr, size_t targbuflen) {
1618         struct cdbdata *cdbrec;
1619         char key[SIZ];
1620
1621         /* Dump it in there unchanged, just for kicks */
1622         safestrncpy(target, internet_addr, targbuflen);
1623
1624         /* Only do lookups for addresses with hostnames in them */
1625         if (num_tokens(internet_addr, '@') != 2) return(-1);
1626
1627         /* Only do lookups for domains in the directory */
1628         if (IsDirectory(internet_addr, 0) == 0) return(-1);
1629
1630         directory_key(key, internet_addr);
1631         cdbrec = cdb_fetch(CDB_DIRECTORY, key, strlen(key) );
1632         if (cdbrec != NULL) {
1633                 safestrncpy(target, cdbrec->ptr, targbuflen);
1634                 cdb_free(cdbrec);
1635                 return(0);
1636         }
1637
1638         return(-1);
1639 }
1640
1641
1642 /*
1643  * Harvest any email addresses that someone might want to have in their
1644  * "collected addresses" book.
1645  */
1646 char *harvest_collected_addresses(struct CtdlMessage *msg) {
1647         char *coll = NULL;
1648         char addr[256];
1649         char user[256], node[256], name[256];
1650         int is_harvestable;
1651         int i, j, h;
1652         eMsgField field = 0;
1653
1654         if (msg == NULL) return(NULL);
1655
1656         is_harvestable = 1;
1657         strcpy(addr, "");       
1658         if (!CM_IsEmpty(msg, eAuthor)) {
1659                 strcat(addr, msg->cm_fields[eAuthor]);
1660         }
1661         if (!CM_IsEmpty(msg, erFc822Addr)) {
1662                 strcat(addr, " <");
1663                 strcat(addr, msg->cm_fields[erFc822Addr]);
1664                 strcat(addr, ">");
1665                 if (IsDirectory(msg->cm_fields[erFc822Addr], 0)) {
1666                         is_harvestable = 0;
1667                 }
1668         }
1669
1670         if (is_harvestable) {
1671                 coll = strdup(addr);
1672         }
1673         else {
1674                 coll = strdup("");
1675         }
1676
1677         if (coll == NULL) return(NULL);
1678
1679         /* Scan both the R (To) and Y (CC) fields */
1680         for (i = 0; i < 2; ++i) {
1681                 if (i == 0) field = eRecipient;
1682                 if (i == 1) field = eCarbonCopY;
1683
1684                 if (!CM_IsEmpty(msg, field)) {
1685                         for (j=0; j<num_tokens(msg->cm_fields[field], ','); ++j) {
1686                                 extract_token(addr, msg->cm_fields[field], j, ',', sizeof addr);
1687                                 if (strstr(addr, "=?") != NULL)
1688                                         utf8ify_rfc822_string(addr);
1689                                 process_rfc822_addr(addr, user, node, name);
1690                                 h = CtdlHostAlias(node);
1691                                 if ( (h != hostalias_localhost) && (h != hostalias_directory) ) {
1692                                         coll = realloc(coll, strlen(coll) + strlen(addr) + 4);
1693                                         if (coll == NULL) return(NULL);
1694                                         if (!IsEmptyStr(coll)) {
1695                                                 strcat(coll, ",");
1696                                         }
1697                                         striplt(addr);
1698                                         strcat(coll, addr);
1699                                 }
1700                         }
1701                 }
1702         }
1703
1704         if (IsEmptyStr(coll)) {
1705                 free(coll);
1706                 return(NULL);
1707         }
1708         return(coll);
1709 }