prune dead code
[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-2017 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         FILE *fp;
414         int a, i;
415         char aaa[SIZ], bbb[SIZ];
416         char *ignetcfg = NULL;
417         char *ignetmap = NULL;
418         int at = 0;
419         char node[64];
420         char testnode[64];
421         char buf[SIZ];
422
423         char original_name[256];
424         safestrncpy(original_name, name, sizeof original_name);
425
426         striplt(name);
427         remove_any_whitespace_to_the_left_or_right_of_at_symbol(name);
428         stripallbut(name, '<', '>');
429
430         fp = fopen(file_mail_aliases, "r");
431         if (fp == NULL) {
432                 fp = fopen("/dev/null", "r");
433         }
434         if (fp == NULL) {
435                 return (MES_ERROR);
436         }
437         strcpy(aaa, "");
438         strcpy(bbb, "");
439         while (fgets(aaa, sizeof aaa, fp) != NULL) {
440                 while (isspace(name[0]))
441                         strcpy(name, &name[1]);
442                 aaa[strlen(aaa) - 1] = 0;
443                 strcpy(bbb, "");
444                 for (a = 0; aaa[a] != '\0'; ++a) {
445                         if (aaa[a] == ',') {
446                                 strcpy(bbb, &aaa[a + 1]);
447                                 aaa[a] = 0;
448                                 break;
449                         }
450                 }
451                 if (!strcasecmp(name, aaa))
452                         strcpy(name, bbb);
453         }
454         fclose(fp);
455
456         /* Hit the Global Address Book */
457         if (CtdlDirectoryLookup(aaa, name, sizeof aaa) == 0) {
458                 strcpy(name, aaa);
459         }
460
461         if (strcasecmp(original_name, name)) {
462                 syslog(LOG_INFO, "internet_addressing: %s is being forwarded to %s", original_name, name);
463         }
464
465         /* Change "user @ xxx" to "user" if xxx is an alias for this host */
466         for (a=0; name[a] != '\0'; ++a) {
467                 if (name[a] == '@') {
468                         if (CtdlHostAlias(&name[a+1]) == hostalias_localhost) {
469                                 name[a] = 0;
470                                 syslog(LOG_DEBUG, "internet_addressing: changed to <%s>", name);
471                                 break;
472                         }
473                 }
474         }
475
476         /* determine local or remote type, see citadel.h */
477         at = haschar(name, '@');
478         if (at == 0) return(MES_LOCAL);         /* no @'s - local address */
479         if (at > 1) return(MES_ERROR);          /* >1 @'s - invalid address */
480         remove_any_whitespace_to_the_left_or_right_of_at_symbol(name);
481
482         /* figure out the delivery mode */
483         extract_token(node, name, 1, '@', sizeof node);
484
485         /* If there are one or more dots in the nodename, we assume that it
486          * is an FQDN and will attempt SMTP delivery to the Internet.
487          */
488         if (haschar(node, '.') > 0) {
489                 return(MES_INTERNET);
490         }
491
492         /* Otherwise we look in the IGnet maps for a valid Citadel node.
493          * Try directly-connected nodes first...
494          */
495         ignetcfg = CtdlGetSysConfig(IGNETCFG);
496         for (i=0; i<num_tokens(ignetcfg, '\n'); ++i) {
497                 extract_token(buf, ignetcfg, i, '\n', sizeof buf);
498                 extract_token(testnode, buf, 0, '|', sizeof testnode);
499                 if (!strcasecmp(node, testnode)) {
500                         free(ignetcfg);
501                         return(MES_IGNET);
502                 }
503         }
504         free(ignetcfg);
505
506         /*
507          * Then try nodes that are two or more hops away.
508          */
509         ignetmap = CtdlGetSysConfig(IGNETMAP);
510         for (i=0; i<num_tokens(ignetmap, '\n'); ++i) {
511                 extract_token(buf, ignetmap, i, '\n', sizeof buf);
512                 extract_token(testnode, buf, 0, '|', sizeof testnode);
513                 if (!strcasecmp(node, testnode)) {
514                         free(ignetmap);
515                         return(MES_IGNET);
516                 }
517         }
518         free(ignetmap);
519
520         /* If we get to this point it's an invalid node name */
521         return (MES_ERROR);
522 }
523
524
525
526 /*
527  * Validate recipients, count delivery types and errors, and handle aliasing
528  * FIXME check for dupes!!!!!
529  *
530  * Returns 0 if all addresses are ok, ret->num_error = -1 if no addresses 
531  * were specified, or the number of addresses found invalid.
532  *
533  * Caller needs to free the result using free_recipients()
534  */
535 recptypes *validate_recipients(const char *supplied_recipients, 
536                                const char *RemoteIdentifier, 
537                                int Flags) {
538         struct CitContext *CCC = CC;
539         recptypes *ret;
540         char *recipients = NULL;
541         char *org_recp;
542         char this_recp[256];
543         char this_recp_cooked[256];
544         char append[SIZ];
545         long len;
546         int num_recps = 0;
547         int i, j;
548         int mailtype;
549         int invalid;
550         struct ctdluser tempUS;
551         struct ctdlroom tempQR;
552         struct ctdlroom tempQR2;
553         int err = 0;
554         char errmsg[SIZ];
555         int in_quotes = 0;
556
557         /* Initialize */
558         ret = (recptypes *) malloc(sizeof(recptypes));
559         if (ret == NULL) return(NULL);
560
561         /* Set all strings to null and numeric values to zero */
562         memset(ret, 0, sizeof(recptypes));
563
564         if (supplied_recipients == NULL) {
565                 recipients = strdup("");
566         }
567         else {
568                 recipients = strdup(supplied_recipients);
569         }
570
571         /* Allocate some memory.  Yes, this allocates 500% more memory than we will
572          * actually need, but it's healthier for the heap than doing lots of tiny
573          * realloc() calls instead.
574          */
575         len = strlen(recipients) + 1024;
576         ret->errormsg = malloc(len);
577         ret->recp_local = malloc(len);
578         ret->recp_internet = malloc(len);
579         ret->recp_ignet = malloc(len);
580         ret->recp_room = malloc(len);
581         ret->display_recp = malloc(len);
582         ret->recp_orgroom = malloc(len);
583         org_recp = malloc(len);
584
585         ret->errormsg[0] = 0;
586         ret->recp_local[0] = 0;
587         ret->recp_internet[0] = 0;
588         ret->recp_ignet[0] = 0;
589         ret->recp_room[0] = 0;
590         ret->recp_orgroom[0] = 0;
591         ret->display_recp[0] = 0;
592
593         ret->recptypes_magic = RECPTYPES_MAGIC;
594
595         /* Change all valid separator characters to commas */
596         for (i=0; !IsEmptyStr(&recipients[i]); ++i) {
597                 if ((recipients[i] == ';') || (recipients[i] == '|')) {
598                         recipients[i] = ',';
599                 }
600         }
601
602         /* Now start extracting recipients... */
603
604         while (!IsEmptyStr(recipients)) {
605                 for (i=0; i<=strlen(recipients); ++i) {
606                         if (recipients[i] == '\"') in_quotes = 1 - in_quotes;
607                         if ( ( (recipients[i] == ',') && (!in_quotes) ) || (recipients[i] == 0) ) {
608                                 safestrncpy(this_recp, recipients, i+1);
609                                 this_recp[i] = 0;
610                                 if (recipients[i] == ',') {
611                                         strcpy(recipients, &recipients[i+1]);
612                                 }
613                                 else {
614                                         strcpy(recipients, "");
615                                 }
616                                 break;
617                         }
618                 }
619
620                 striplt(this_recp);
621                 if (IsEmptyStr(this_recp))
622                         break;
623                 syslog(LOG_DEBUG, "internet_addressing: evaluating recipient #%d: %s", num_recps, this_recp);
624                 ++num_recps;
625
626                 strcpy(org_recp, this_recp);
627                 alias(this_recp);
628                 alias(this_recp);
629                 mailtype = alias(this_recp);
630
631                 for (j = 0; !IsEmptyStr(&this_recp[j]); ++j) {
632                         if (this_recp[j]=='_') {
633                                 this_recp_cooked[j] = ' ';
634                         }
635                         else {
636                                 this_recp_cooked[j] = this_recp[j];
637                         }
638                 }
639                 this_recp_cooked[j] = '\0';
640                 invalid = 0;
641                 errmsg[0] = 0;
642                 switch(mailtype) {
643                 case MES_LOCAL:
644                         if (!strcasecmp(this_recp, "sysop")) {
645                                 ++ret->num_room;
646                                 strcpy(this_recp, CtdlGetConfigStr("c_aideroom"));
647                                 if (!IsEmptyStr(ret->recp_room)) {
648                                         strcat(ret->recp_room, "|");
649                                 }
650                                 strcat(ret->recp_room, this_recp);
651                         }
652                         else if ( (!strncasecmp(this_recp, "room_", 5))
653                                   && (!CtdlGetRoom(&tempQR, &this_recp_cooked[5])) ) {
654
655                                 /* Save room so we can restore it later */
656                                 tempQR2 = CCC->room;
657                                 CCC->room = tempQR;
658                                         
659                                 /* Check permissions to send mail to this room */
660                                 err = CtdlDoIHavePermissionToPostInThisRoom(
661                                         errmsg, 
662                                         sizeof errmsg, 
663                                         RemoteIdentifier,
664                                         Flags,
665                                         0                       /* 0 = not a reply */
666                                         );
667                                 if (err)
668                                 {
669                                         ++ret->num_error;
670                                         invalid = 1;
671                                 } 
672                                 else {
673                                         ++ret->num_room;
674                                         if (!IsEmptyStr(ret->recp_room)) {
675                                                 strcat(ret->recp_room, "|");
676                                         }
677                                         strcat(ret->recp_room, &this_recp_cooked[5]);
678
679                                         if (!IsEmptyStr(ret->recp_orgroom)) {
680                                                 strcat(ret->recp_orgroom, "|");
681                                         }
682                                         strcat(ret->recp_orgroom, org_recp);
683
684                                 }
685                                         
686                                 /* Restore room in case something needs it */
687                                 CCC->room = tempQR2;
688
689                         }
690                         else if (CtdlGetUser(&tempUS, this_recp) == 0) {
691                                 ++ret->num_local;
692                                 strcpy(this_recp, tempUS.fullname);
693                                 if (!IsEmptyStr(ret->recp_local)) {
694                                         strcat(ret->recp_local, "|");
695                                 }
696                                 strcat(ret->recp_local, this_recp);
697                         }
698                         else if (CtdlGetUser(&tempUS, this_recp_cooked) == 0) {
699                                 ++ret->num_local;
700                                 strcpy(this_recp, tempUS.fullname);
701                                 if (!IsEmptyStr(ret->recp_local)) {
702                                         strcat(ret->recp_local, "|");
703                                 }
704                                 strcat(ret->recp_local, this_recp);
705                         }
706                         else {
707                                 ++ret->num_error;
708                                 invalid = 1;
709                         }
710                         break;
711                 case MES_INTERNET:
712                         /* Yes, you're reading this correctly: if the target
713                          * domain points back to the local system or an attached
714                          * Citadel directory, the address is invalid.  That's
715                          * because if the address were valid, we would have
716                          * already translated it to a local address by now.
717                          */
718                         if (IsDirectory(this_recp, 0)) {
719                                 ++ret->num_error;
720                                 invalid = 1;
721                         }
722                         else {
723                                 ++ret->num_internet;
724                                 if (!IsEmptyStr(ret->recp_internet)) {
725                                         strcat(ret->recp_internet, "|");
726                                 }
727                                 strcat(ret->recp_internet, this_recp);
728                         }
729                         break;
730                 case MES_IGNET:
731                         ++ret->num_ignet;
732                         if (!IsEmptyStr(ret->recp_ignet)) {
733                                 strcat(ret->recp_ignet, "|");
734                         }
735                         strcat(ret->recp_ignet, this_recp);
736                         break;
737                 case MES_ERROR:
738                         ++ret->num_error;
739                         invalid = 1;
740                         break;
741                 }
742                 if (invalid) {
743                         if (IsEmptyStr(errmsg)) {
744                                 snprintf(append, sizeof append, "Invalid recipient: %s", this_recp);
745                         }
746                         else {
747                                 snprintf(append, sizeof append, "%s", errmsg);
748                         }
749                         if ( (strlen(ret->errormsg) + strlen(append) + 3) < SIZ) {
750                                 if (!IsEmptyStr(ret->errormsg)) {
751                                         strcat(ret->errormsg, "; ");
752                                 }
753                                 strcat(ret->errormsg, append);
754                         }
755                 }
756                 else {
757                         if (IsEmptyStr(ret->display_recp)) {
758                                 strcpy(append, this_recp);
759                         }
760                         else {
761                                 snprintf(append, sizeof append, ", %s", this_recp);
762                         }
763                         if ( (strlen(ret->display_recp)+strlen(append)) < SIZ) {
764                                 strcat(ret->display_recp, append);
765                         }
766                 }
767         }
768         free(org_recp);
769
770         if ((ret->num_local + ret->num_internet + ret->num_ignet +
771              ret->num_room + ret->num_error) == 0) {
772                 ret->num_error = (-1);
773                 strcpy(ret->errormsg, "No recipients specified.");
774         }
775
776         syslog(LOG_DEBUG, "internet_addressing: validate_recipients() = %d local, %d room, %d SMTP, %d IGnet, %d error",
777                 ret->num_local, ret->num_room, ret->num_internet, ret->num_ignet, ret->num_error
778         );
779
780         free(recipients);
781         return(ret);
782 }
783
784
785 /*
786  * Destructor for recptypes
787  */
788 void free_recipients(recptypes *valid) {
789
790         if (valid == NULL) {
791                 return;
792         }
793
794         if (valid->recptypes_magic != RECPTYPES_MAGIC) {
795                 syslog(LOG_ERR, "internet_addressing: attempt to call free_recipients() on some other data type!");
796                 abort();
797         }
798
799         if (valid->errormsg != NULL)            free(valid->errormsg);
800         if (valid->recp_local != NULL)          free(valid->recp_local);
801         if (valid->recp_internet != NULL)       free(valid->recp_internet);
802         if (valid->recp_ignet != NULL)          free(valid->recp_ignet);
803         if (valid->recp_room != NULL)           free(valid->recp_room);
804         if (valid->recp_orgroom != NULL)        free(valid->recp_orgroom);
805         if (valid->display_recp != NULL)        free(valid->display_recp);
806         if (valid->bounce_to != NULL)           free(valid->bounce_to);
807         if (valid->envelope_from != NULL)       free(valid->envelope_from);
808         if (valid->sending_room != NULL)        free(valid->sending_room);
809         free(valid);
810 }
811
812
813 char *qp_encode_email_addrs(char *source)
814 {
815         char *user, *node, *name;
816         const char headerStr[] = "=?UTF-8?Q?";
817         char *Encoded;
818         char *EncodedName;
819         char *nPtr;
820         int need_to_encode = 0;
821         long SourceLen;
822         long EncodedMaxLen;
823         long nColons = 0;
824         long *AddrPtr;
825         long *AddrUtf8;
826         long nAddrPtrMax = 50;
827         long nmax;
828         int InQuotes = 0;
829         int i, n;
830
831         if (source == NULL) return source;
832         if (IsEmptyStr(source)) return source;
833         syslog(LOG_DEBUG, "internet_addressing: qp_encode_email_addrs <%s>", source);
834
835         AddrPtr = malloc (sizeof (long) * nAddrPtrMax);
836         AddrUtf8 = malloc (sizeof (long) * nAddrPtrMax);
837         memset(AddrUtf8, 0, sizeof (long) * nAddrPtrMax);
838         *AddrPtr = 0;
839         i = 0;
840         while (!IsEmptyStr (&source[i])) {
841                 if (nColons >= nAddrPtrMax){
842                         long *ptr;
843
844                         ptr = (long *) malloc(sizeof (long) * nAddrPtrMax * 2);
845                         memcpy (ptr, AddrPtr, sizeof (long) * nAddrPtrMax);
846                         free (AddrPtr), AddrPtr = ptr;
847
848                         ptr = (long *) malloc(sizeof (long) * nAddrPtrMax * 2);
849                         memset(&ptr[nAddrPtrMax], 0, 
850                                sizeof (long) * nAddrPtrMax);
851
852                         memcpy (ptr, AddrUtf8, sizeof (long) * nAddrPtrMax);
853                         free (AddrUtf8), AddrUtf8 = ptr;
854                         nAddrPtrMax *= 2;                               
855                 }
856                 if (((unsigned char) source[i] < 32) || 
857                     ((unsigned char) source[i] > 126)) {
858                         need_to_encode = 1;
859                         AddrUtf8[nColons] = 1;
860                 }
861                 if (source[i] == '"')
862                         InQuotes = !InQuotes;
863                 if (!InQuotes && source[i] == ',') {
864                         AddrPtr[nColons] = i;
865                         nColons++;
866                 }
867                 i++;
868         }
869         if (need_to_encode == 0) {
870                 free(AddrPtr);
871                 free(AddrUtf8);
872                 return source;
873         }
874
875         SourceLen = i;
876         EncodedMaxLen = nColons * (sizeof(headerStr) + 3) + SourceLen * 3;
877         Encoded = (char*) malloc (EncodedMaxLen);
878
879         for (i = 0; i < nColons; i++)
880                 source[AddrPtr[i]++] = '\0';
881         /* TODO: if libidn, this might get larger*/
882         user = malloc(SourceLen + 1);
883         node = malloc(SourceLen + 1);
884         name = malloc(SourceLen + 1);
885
886         nPtr = Encoded;
887         *nPtr = '\0';
888         for (i = 0; i < nColons && nPtr != NULL; i++) {
889                 nmax = EncodedMaxLen - (nPtr - Encoded);
890                 if (AddrUtf8[i]) {
891                         process_rfc822_addr(&source[AddrPtr[i]], 
892                                             user,
893                                             node,
894                                             name);
895                         /* TODO: libIDN here ! */
896                         if (IsEmptyStr(name)) {
897                                 n = snprintf(nPtr, nmax, 
898                                              (i==0)?"%s@%s" : ",%s@%s",
899                                              user, node);
900                         }
901                         else {
902                                 EncodedName = rfc2047encode(name, strlen(name));                        
903                                 n = snprintf(nPtr, nmax, 
904                                              (i==0)?"%s <%s@%s>" : ",%s <%s@%s>",
905                                              EncodedName, user, node);
906                                 free(EncodedName);
907                         }
908                 }
909                 else { 
910                         n = snprintf(nPtr, nmax, 
911                                      (i==0)?"%s" : ",%s",
912                                      &source[AddrPtr[i]]);
913                 }
914                 if (n > 0 )
915                         nPtr += n;
916                 else { 
917                         char *ptr, *nnPtr;
918                         ptr = (char*) malloc(EncodedMaxLen * 2);
919                         memcpy(ptr, Encoded, EncodedMaxLen);
920                         nnPtr = ptr + (nPtr - Encoded), nPtr = nnPtr;
921                         free(Encoded), Encoded = ptr;
922                         EncodedMaxLen *= 2;
923                         i--; /* do it once more with properly lengthened buffer */
924                 }
925         }
926         for (i = 0; i < nColons; i++)
927                 source[--AddrPtr[i]] = ',';
928
929         free(user);
930         free(node);
931         free(name);
932         free(AddrUtf8);
933         free(AddrPtr);
934         return Encoded;
935 }
936
937
938 /*
939  * Unfold a multi-line field into a single line, removing multi-whitespaces
940  */
941 void unfold_rfc822_field(char **field, char **FieldEnd) 
942 {
943         int quote = 0;
944         char *pField = *field;
945         char *sField;
946         char *pFieldEnd = *FieldEnd;
947
948         while (isspace(*pField))
949                 pField++;
950         /* remove leading/trailing whitespace */
951         ;
952
953         while (isspace(*pFieldEnd))
954                 pFieldEnd --;
955
956         *FieldEnd = pFieldEnd;
957         /* convert non-space whitespace to spaces, and remove double blanks */
958         for (sField = *field = pField; 
959              sField < pFieldEnd; 
960              pField++, sField++)
961         {
962                 if ((*sField=='\r') || (*sField=='\n'))
963                 {
964                         int Offset = 1;
965                         while (((*(sField + Offset) == '\r') ||
966                                 (*(sField + Offset) == '\n') ||
967                                 (isspace(*(sField + Offset)))) && 
968                                (sField + Offset < pFieldEnd))
969                                 Offset ++;
970                         sField += Offset;
971                         *pField = *sField;
972                 }
973                 else {
974                         if (*sField=='\"') quote = 1 - quote;
975                         if (!quote) {
976                                 if (isspace(*sField))
977                                 {
978                                         *pField = ' ';
979                                         pField++;
980                                         sField++;
981                                         
982                                         while ((sField < pFieldEnd) && 
983                                                isspace(*sField))
984                                                 sField++;
985                                         *pField = *sField;
986                                 }
987                                 else *pField = *sField;
988                         }
989                         else *pField = *sField;
990                 }
991         }
992         *pField = '\0';
993         *FieldEnd = pField - 1;
994 }
995
996
997
998 /*
999  * Split an RFC822-style address into userid, host, and full name
1000  *
1001  */
1002 void process_rfc822_addr(const char *rfc822, char *user, char *node, char *name)
1003 {
1004         int a;
1005
1006         strcpy(user, "");
1007         strcpy(node, CtdlGetConfigStr("c_fqdn"));
1008         strcpy(name, "");
1009
1010         if (rfc822 == NULL) return;
1011
1012         /* extract full name - first, it's From minus <userid> */
1013         strcpy(name, rfc822);
1014         stripout(name, '<', '>');
1015
1016         /* strip anything to the left of a bang */
1017         while ((!IsEmptyStr(name)) && (haschar(name, '!') > 0))
1018                 strcpy(name, &name[1]);
1019
1020         /* and anything to the right of a @ or % */
1021         for (a = 0; name[a] != '\0'; ++a) {
1022                 if (name[a] == '@') {
1023                         name[a] = 0;
1024                         break;
1025                 }
1026                 if (name[a] == '%') {
1027                         name[a] = 0;
1028                         break;
1029                 }
1030         }
1031
1032         /* but if there are parentheses, that changes the rules... */
1033         if ((haschar(rfc822, '(') == 1) && (haschar(rfc822, ')') == 1)) {
1034                 strcpy(name, rfc822);
1035                 stripallbut(name, '(', ')');
1036         }
1037
1038         /* but if there are a set of quotes, that supersedes everything */
1039         if (haschar(rfc822, 34) == 2) {
1040                 strcpy(name, rfc822);
1041                 while ((!IsEmptyStr(name)) && (name[0] != 34)) {
1042                         strcpy(&name[0], &name[1]);
1043                 }
1044                 strcpy(&name[0], &name[1]);
1045                 for (a = 0; name[a] != '\0'; ++a)
1046                         if (name[a] == 34) {
1047                                 name[a] = 0;
1048                                 break;
1049                         }
1050         }
1051         /* extract user id */
1052         strcpy(user, rfc822);
1053
1054         /* first get rid of anything in parens */
1055         stripout(user, '(', ')');
1056
1057         /* if there's a set of angle brackets, strip it down to that */
1058         if ((haschar(user, '<') == 1) && (haschar(user, '>') == 1)) {
1059                 stripallbut(user, '<', '>');
1060         }
1061
1062         /* strip anything to the left of a bang */
1063         while ((!IsEmptyStr(user)) && (haschar(user, '!') > 0))
1064                 strcpy(user, &user[1]);
1065
1066         /* and anything to the right of a @ or % */
1067         for (a = 0; user[a] != '\0'; ++a) {
1068                 if (user[a] == '@') {
1069                         user[a] = 0;
1070                         break;
1071                 }
1072                 if (user[a] == '%') {
1073                         user[a] = 0;
1074                         break;
1075                 }
1076         }
1077
1078
1079         /* extract node name */
1080         strcpy(node, rfc822);
1081
1082         /* first get rid of anything in parens */
1083         stripout(node, '(', ')');
1084
1085         /* if there's a set of angle brackets, strip it down to that */
1086         if ((haschar(node, '<') == 1) && (haschar(node, '>') == 1)) {
1087                 stripallbut(node, '<', '>');
1088         }
1089
1090         /* If no node specified, tack ours on instead */
1091         if (
1092                 (haschar(node, '@')==0)
1093                 && (haschar(node, '%')==0)
1094                 && (haschar(node, '!')==0)
1095         ) {
1096                 strcpy(node, CtdlGetConfigStr("c_nodename"));
1097         }
1098
1099         else {
1100
1101                 /* strip anything to the left of a @ */
1102                 while ((!IsEmptyStr(node)) && (haschar(node, '@') > 0))
1103                         strcpy(node, &node[1]);
1104         
1105                 /* strip anything to the left of a % */
1106                 while ((!IsEmptyStr(node)) && (haschar(node, '%') > 0))
1107                         strcpy(node, &node[1]);
1108         
1109                 /* reduce multiple system bang paths to node!user */
1110                 while ((!IsEmptyStr(node)) && (haschar(node, '!') > 1))
1111                         strcpy(node, &node[1]);
1112         
1113                 /* now get rid of the user portion of a node!user string */
1114                 for (a = 0; node[a] != '\0'; ++a)
1115                         if (node[a] == '!') {
1116                                 node[a] = 0;
1117                                 break;
1118                         }
1119         }
1120
1121         /* strip leading and trailing spaces in all strings */
1122         striplt(user);
1123         striplt(node);
1124         striplt(name);
1125
1126         /* If we processed a string that had the address in angle brackets
1127          * but no name outside the brackets, we now have an empty name.  In
1128          * this case, use the user portion of the address as the name.
1129          */
1130         if ((IsEmptyStr(name)) && (!IsEmptyStr(user))) {
1131                 strcpy(name, user);
1132         }
1133 }
1134
1135
1136
1137 /*
1138  * convert_field() is a helper function for convert_internet_message().
1139  * Given start/end positions for an rfc822 field, it converts it to a Citadel
1140  * field if it wants to, and unfolds it if necessary.
1141  *
1142  * Returns 1 if the field was converted and inserted into the Citadel message
1143  * structure, implying that the source field should be removed from the
1144  * message text.
1145  */
1146 int convert_field(struct CtdlMessage *msg, const char *beg, const char *end) {
1147         char *key, *value, *valueend;
1148         long len;
1149         const char *pos;
1150         int i;
1151         const char *colonpos = NULL;
1152         int processed = 0;
1153         char user[1024];
1154         char node[1024];
1155         char name[1024];
1156         char addr[1024];
1157         time_t parsed_date;
1158         long valuelen;
1159
1160         for (pos = end; pos >= beg; pos--) {
1161                 if (*pos == ':') colonpos = pos;
1162         }
1163
1164         if (colonpos == NULL) return(0);        /* no colon? not a valid header line */
1165
1166         len = end - beg;
1167         key = malloc(len + 2);
1168         memcpy(key, beg, len + 1);
1169         key[len] = '\0';
1170         valueend = key + len;
1171         * ( key + (colonpos - beg) ) = '\0';
1172         value = &key[(colonpos - beg) + 1];
1173 /*      printf("Header: [%s]\nValue: [%s]\n", key, value); */
1174         unfold_rfc822_field(&value, &valueend);
1175         valuelen = valueend - value + 1;
1176 /*      printf("UnfoldedValue: [%s]\n", value); */
1177
1178         /*
1179          * Here's the big rfc822-to-citadel loop.
1180          */
1181
1182         /* Date/time is converted into a unix timestamp.  If the conversion
1183          * fails, we replace it with the time the message arrived locally.
1184          */
1185         if (!strcasecmp(key, "Date")) {
1186                 parsed_date = parsedate(value);
1187                 if (parsed_date < 0L) parsed_date = time(NULL);
1188
1189                 if (CM_IsEmpty(msg, eTimestamp))
1190                         CM_SetFieldLONG(msg, eTimestamp, parsed_date);
1191                 processed = 1;
1192         }
1193
1194         else if (!strcasecmp(key, "From")) {
1195                 process_rfc822_addr(value, user, node, name);
1196                 syslog(LOG_DEBUG, "internet_addressing: converted to <%s@%s> (%s)", user, node, name);
1197                 snprintf(addr, sizeof(addr), "%s@%s", user, node);
1198                 if (CM_IsEmpty(msg, eAuthor) && !IsEmptyStr(name))
1199                         CM_SetField(msg, eAuthor, name, strlen(name));
1200                 if (CM_IsEmpty(msg, erFc822Addr) && !IsEmptyStr(addr))
1201                         CM_SetField(msg, erFc822Addr, addr, strlen(addr));
1202                 processed = 1;
1203         }
1204
1205         else if (!strcasecmp(key, "Subject")) {
1206                 if (CM_IsEmpty(msg, eMsgSubject))
1207                         CM_SetField(msg, eMsgSubject, value, valuelen);
1208                 processed = 1;
1209         }
1210
1211         else if (!strcasecmp(key, "List-ID")) {
1212                 if (CM_IsEmpty(msg, eListID))
1213                         CM_SetField(msg, eListID, value, valuelen);
1214                 processed = 1;
1215         }
1216
1217         else if (!strcasecmp(key, "To")) {
1218                 if (CM_IsEmpty(msg, eRecipient))
1219                         CM_SetField(msg, eRecipient, value, valuelen);
1220                 processed = 1;
1221         }
1222
1223         else if (!strcasecmp(key, "CC")) {
1224                 if (CM_IsEmpty(msg, eCarbonCopY))
1225                         CM_SetField(msg, eCarbonCopY, value, valuelen);
1226                 processed = 1;
1227         }
1228
1229         else if (!strcasecmp(key, "Message-ID")) {
1230                 if (!CM_IsEmpty(msg, emessageId)) {
1231                         syslog(LOG_WARNING, "internet_addressing: duplicate message id");
1232                 }
1233                 else {
1234                         char *pValue;
1235                         long pValueLen;
1236
1237                         pValue = value;
1238                         pValueLen = valuelen;
1239                         /* Strip angle brackets */
1240                         while (haschar(pValue, '<') > 0) {
1241                                 pValue ++;
1242                                 pValueLen --;
1243                         }
1244
1245                         for (i = 0; i <= pValueLen; ++i)
1246                                 if (pValue[i] == '>') {
1247                                         pValueLen = i;
1248                                         break;
1249                                 }
1250
1251                         CM_SetField(msg, emessageId, pValue, pValueLen);
1252                 }
1253
1254                 processed = 1;
1255         }
1256
1257         else if (!strcasecmp(key, "Return-Path")) {
1258                 if (CM_IsEmpty(msg, eMessagePath))
1259                         CM_SetField(msg, eMessagePath, value, valuelen);
1260                 processed = 1;
1261         }
1262
1263         else if (!strcasecmp(key, "Envelope-To")) {
1264                 if (CM_IsEmpty(msg, eenVelopeTo))
1265                         CM_SetField(msg, eenVelopeTo, value, valuelen);
1266                 processed = 1;
1267         }
1268
1269         else if (!strcasecmp(key, "References")) {
1270                 CM_SetField(msg, eWeferences, value, valuelen);
1271                 processed = 1;
1272         }
1273
1274         else if (!strcasecmp(key, "Reply-To")) {
1275                 CM_SetField(msg, eReplyTo, value, valuelen);
1276                 processed = 1;
1277         }
1278
1279         else if (!strcasecmp(key, "In-reply-to")) {
1280                 if (CM_IsEmpty(msg, eWeferences)) /* References: supersedes In-reply-to: */
1281                         CM_SetField(msg, eWeferences, value, valuelen);
1282                 processed = 1;
1283         }
1284
1285
1286
1287         /* Clean up and move on. */
1288         free(key);      /* Don't free 'value', it's actually the same buffer */
1289         return processed;
1290 }
1291
1292
1293 /*
1294  * Convert RFC822 references format (References) to Citadel references format (Weferences)
1295  */
1296 void convert_references_to_wefewences(char *str) {
1297         int bracket_nesting = 0;
1298         char *ptr = str;
1299         char *moveptr = NULL;
1300         char ch;
1301
1302         while(*ptr) {
1303                 ch = *ptr;
1304                 if (ch == '>') {
1305                         --bracket_nesting;
1306                         if (bracket_nesting < 0) bracket_nesting = 0;
1307                 }
1308                 if ((ch == '>') && (bracket_nesting == 0) && (*(ptr+1)) && (ptr>str) ) {
1309                         *ptr = '|';
1310                         ++ptr;
1311                 }
1312                 else if (bracket_nesting > 0) {
1313                         ++ptr;
1314                 }
1315                 else {
1316                         moveptr = ptr;
1317                         while (*moveptr) {
1318                                 *moveptr = *(moveptr+1);
1319                                 ++moveptr;
1320                         }
1321                 }
1322                 if (ch == '<') ++bracket_nesting;
1323         }
1324
1325 }
1326
1327
1328 /*
1329  * Convert an RFC822 message (headers + body) to a CtdlMessage structure.
1330  * NOTE: the supplied buffer becomes part of the CtdlMessage structure, and
1331  * will be deallocated when CM_Free() is called.  Therefore, the
1332  * supplied buffer should be DEREFERENCED.  It should not be freed or used
1333  * again.
1334  */
1335 struct CtdlMessage *convert_internet_message(char *rfc822) {
1336         StrBuf *RFCBuf = NewStrBufPlain(rfc822, -1);
1337         free (rfc822);
1338         return convert_internet_message_buf(&RFCBuf);
1339 }
1340
1341
1342
1343 struct CtdlMessage *convert_internet_message_buf(StrBuf **rfc822)
1344 {
1345         struct CtdlMessage *msg;
1346         const char *pos, *beg, *end, *totalend;
1347         int done, alldone = 0;
1348         int converted;
1349         StrBuf *OtherHeaders;
1350
1351         msg = malloc(sizeof(struct CtdlMessage));
1352         if (msg == NULL) return msg;
1353
1354         memset(msg, 0, sizeof(struct CtdlMessage));
1355         msg->cm_magic = CTDLMESSAGE_MAGIC;      /* self check */
1356         msg->cm_anon_type = 0;                  /* never anonymous */
1357         msg->cm_format_type = FMT_RFC822;       /* internet message */
1358
1359         pos = ChrPtr(*rfc822);
1360         totalend = pos + StrLength(*rfc822);
1361         done = 0;
1362         OtherHeaders = NewStrBufPlain(NULL, StrLength(*rfc822));
1363
1364         while (!alldone) {
1365
1366                 /* Locate beginning and end of field, keeping in mind that
1367                  * some fields might be multiline
1368                  */
1369                 end = beg = pos;
1370
1371                 while ((end < totalend) && 
1372                        (end == beg) && 
1373                        (done == 0) ) 
1374                 {
1375
1376                         if ( (*pos=='\n') && ((*(pos+1))!=0x20) && ((*(pos+1))!=0x09) )
1377                         {
1378                                 end = pos;
1379                         }
1380
1381                         /* done with headers? */
1382                         if ((*pos=='\n') &&
1383                             ( (*(pos+1)=='\n') ||
1384                               (*(pos+1)=='\r')) ) 
1385                         {
1386                                 alldone = 1;
1387                         }
1388
1389                         if (pos >= (totalend - 1) )
1390                         {
1391                                 end = pos;
1392                                 done = 1;
1393                         }
1394
1395                         ++pos;
1396
1397                 }
1398
1399                 /* At this point we have a field.  Are we interested in it? */
1400                 converted = convert_field(msg, beg, end);
1401
1402                 /* Strip the field out of the RFC822 header if we used it */
1403                 if (!converted) {
1404                         StrBufAppendBufPlain(OtherHeaders, beg, end - beg, 0);
1405                         StrBufAppendBufPlain(OtherHeaders, HKEY("\n"), 0);
1406                 }
1407
1408                 /* If we've hit the end of the message, bail out */
1409                 if (pos >= totalend)
1410                         alldone = 1;
1411         }
1412         StrBufAppendBufPlain(OtherHeaders, HKEY("\n"), 0);
1413         if (pos < totalend)
1414                 StrBufAppendBufPlain(OtherHeaders, pos, totalend - pos, 0);
1415         FreeStrBuf(rfc822);
1416         CM_SetAsFieldSB(msg, eMesageText, &OtherHeaders);
1417
1418         /* Follow-up sanity checks... */
1419
1420         /* If there's no timestamp on this message, set it to now. */
1421         if (CM_IsEmpty(msg, eTimestamp)) {
1422                 CM_SetFieldLONG(msg, eTimestamp, time(NULL));
1423         }
1424
1425         /* If a W (references, or rather, Wefewences) field is present, we
1426          * have to convert it from RFC822 format to Citadel format.
1427          */
1428         if (!CM_IsEmpty(msg, eWeferences)) {
1429                 /// todo: API!
1430                 convert_references_to_wefewences(msg->cm_fields[eWeferences]);
1431         }
1432
1433         return msg;
1434 }
1435
1436
1437
1438 /*
1439  * Look for a particular header field in an RFC822 message text.  If the
1440  * requested field is found, it is unfolded (if necessary) and returned to
1441  * the caller.  The field name is stripped out, leaving only its contents.
1442  * The caller is responsible for freeing the returned buffer.  If the requested
1443  * field is not present, or anything else goes wrong, it returns NULL.
1444  */
1445 char *rfc822_fetch_field(const char *rfc822, const char *fieldname) {
1446         char *fieldbuf = NULL;
1447         const char *end_of_headers;
1448         const char *field_start;
1449         const char *ptr;
1450         char *cont;
1451         char fieldhdr[SIZ];
1452
1453         /* Should never happen, but sometimes we get stupid */
1454         if (rfc822 == NULL) return(NULL);
1455         if (fieldname == NULL) return(NULL);
1456
1457         snprintf(fieldhdr, sizeof fieldhdr, "%s:", fieldname);
1458
1459         /* Locate the end of the headers, so we don't run past that point */
1460         end_of_headers = cbmstrcasestr(rfc822, "\n\r\n");
1461         if (end_of_headers == NULL) {
1462                 end_of_headers = cbmstrcasestr(rfc822, "\n\n");
1463         }
1464         if (end_of_headers == NULL) return (NULL);
1465
1466         field_start = cbmstrcasestr(rfc822, fieldhdr);
1467         if (field_start == NULL) return(NULL);
1468         if (field_start > end_of_headers) return(NULL);
1469
1470         fieldbuf = malloc(SIZ);
1471         strcpy(fieldbuf, "");
1472
1473         ptr = field_start;
1474         ptr = cmemreadline(ptr, fieldbuf, SIZ-strlen(fieldbuf) );
1475         while ( (isspace(ptr[0])) && (ptr < end_of_headers) ) {
1476                 strcat(fieldbuf, " ");
1477                 cont = &fieldbuf[strlen(fieldbuf)];
1478                 ptr = cmemreadline(ptr, cont, SIZ-strlen(fieldbuf) );
1479                 striplt(cont);
1480         }
1481
1482         strcpy(fieldbuf, &fieldbuf[strlen(fieldhdr)]);
1483         striplt(fieldbuf);
1484
1485         return(fieldbuf);
1486 }
1487
1488
1489
1490 /*****************************************************************************
1491  *                      DIRECTORY MANAGEMENT FUNCTIONS                       *
1492  *****************************************************************************/
1493
1494 /*
1495  * Generate the index key for an Internet e-mail address to be looked up
1496  * in the database.
1497  */
1498 void directory_key(char *key, char *addr) {
1499         int i;
1500         int keylen = 0;
1501
1502         for (i=0; !IsEmptyStr(&addr[i]); ++i) {
1503                 if (!isspace(addr[i])) {
1504                         key[keylen++] = tolower(addr[i]);
1505                 }
1506         }
1507         key[keylen++] = 0;
1508
1509         syslog(LOG_DEBUG, "internet_addressing: directory key is <%s>", key);
1510 }
1511
1512
1513 /* Return nonzero if the supplied address is in a domain we keep in
1514  * the directory
1515  */
1516 int IsDirectory(char *addr, int allow_masq_domains) {
1517         char domain[256];
1518         int h;
1519
1520         extract_token(domain, addr, 1, '@', sizeof domain);
1521         striplt(domain);
1522
1523         h = CtdlHostAlias(domain);
1524
1525         if ( (h == hostalias_masq) && allow_masq_domains)
1526                 return(1);
1527         
1528         if ( (h == hostalias_localhost) || (h == hostalias_directory) ) {
1529                 return(1);
1530         }
1531         else {
1532                 return(0);
1533         }
1534 }
1535
1536
1537 /*
1538  * Initialize the directory database (erasing anything already there)
1539  */
1540 void CtdlDirectoryInit(void) {
1541         cdb_trunc(CDB_DIRECTORY);
1542 }
1543
1544
1545 /*
1546  * Add an Internet e-mail address to the directory for a user
1547  */
1548 int CtdlDirectoryAddUser(char *internet_addr, char *citadel_addr) {
1549         char key[SIZ];
1550
1551         if (IsDirectory(internet_addr, 0) == 0) 
1552                 return 0;
1553         syslog(LOG_DEBUG, "internet_addressing: create directory entry: %s --> %s", internet_addr, citadel_addr);
1554         directory_key(key, internet_addr);
1555         cdb_store(CDB_DIRECTORY, key, strlen(key), citadel_addr, strlen(citadel_addr)+1 );
1556         return 1;
1557 }
1558
1559
1560 /*
1561  * Delete an Internet e-mail address from the directory.
1562  *
1563  * (NOTE: we don't actually use or need the citadel_addr variable; it's merely
1564  * here because the callback API expects to be able to send it.)
1565  */
1566 int CtdlDirectoryDelUser(char *internet_addr, char *citadel_addr) {
1567         char key[SIZ];
1568         
1569         syslog(LOG_DEBUG, "internet_addressing: delete directory entry: %s --> %s", internet_addr, citadel_addr);
1570         directory_key(key, internet_addr);
1571         return cdb_delete(CDB_DIRECTORY, key, strlen(key) ) == 0;
1572 }
1573
1574
1575 /*
1576  * Look up an Internet e-mail address in the directory.
1577  * On success: returns 0, and Citadel address stored in 'target'
1578  * On failure: returns nonzero
1579  */
1580 int CtdlDirectoryLookup(char *target, char *internet_addr, size_t targbuflen) {
1581         struct cdbdata *cdbrec;
1582         char key[SIZ];
1583
1584         /* Dump it in there unchanged, just for kicks */
1585         safestrncpy(target, internet_addr, targbuflen);
1586
1587         /* Only do lookups for addresses with hostnames in them */
1588         if (num_tokens(internet_addr, '@') != 2) return(-1);
1589
1590         /* Only do lookups for domains in the directory */
1591         if (IsDirectory(internet_addr, 0) == 0) return(-1);
1592
1593         directory_key(key, internet_addr);
1594         cdbrec = cdb_fetch(CDB_DIRECTORY, key, strlen(key) );
1595         if (cdbrec != NULL) {
1596                 safestrncpy(target, cdbrec->ptr, targbuflen);
1597                 cdb_free(cdbrec);
1598                 return(0);
1599         }
1600
1601         return(-1);
1602 }
1603
1604
1605 /*
1606  * Harvest any email addresses that someone might want to have in their
1607  * "collected addresses" book.
1608  */
1609 char *harvest_collected_addresses(struct CtdlMessage *msg) {
1610         char *coll = NULL;
1611         char addr[256];
1612         char user[256], node[256], name[256];
1613         int is_harvestable;
1614         int i, j, h;
1615         eMsgField field = 0;
1616
1617         if (msg == NULL) return(NULL);
1618
1619         is_harvestable = 1;
1620         strcpy(addr, "");       
1621         if (!CM_IsEmpty(msg, eAuthor)) {
1622                 strcat(addr, msg->cm_fields[eAuthor]);
1623         }
1624         if (!CM_IsEmpty(msg, erFc822Addr)) {
1625                 strcat(addr, " <");
1626                 strcat(addr, msg->cm_fields[erFc822Addr]);
1627                 strcat(addr, ">");
1628                 if (IsDirectory(msg->cm_fields[erFc822Addr], 0)) {
1629                         is_harvestable = 0;
1630                 }
1631         }
1632
1633         if (is_harvestable) {
1634                 coll = strdup(addr);
1635         }
1636         else {
1637                 coll = strdup("");
1638         }
1639
1640         if (coll == NULL) return(NULL);
1641
1642         /* Scan both the R (To) and Y (CC) fields */
1643         for (i = 0; i < 2; ++i) {
1644                 if (i == 0) field = eRecipient;
1645                 if (i == 1) field = eCarbonCopY;
1646
1647                 if (!CM_IsEmpty(msg, field)) {
1648                         for (j=0; j<num_tokens(msg->cm_fields[field], ','); ++j) {
1649                                 extract_token(addr, msg->cm_fields[field], j, ',', sizeof addr);
1650                                 if (strstr(addr, "=?") != NULL)
1651                                         utf8ify_rfc822_string(addr);
1652                                 process_rfc822_addr(addr, user, node, name);
1653                                 h = CtdlHostAlias(node);
1654                                 if ( (h != hostalias_localhost) && (h != hostalias_directory) ) {
1655                                         coll = realloc(coll, strlen(coll) + strlen(addr) + 4);
1656                                         if (coll == NULL) return(NULL);
1657                                         if (!IsEmptyStr(coll)) {
1658                                                 strcat(coll, ",");
1659                                         }
1660                                         striplt(addr);
1661                                         strcat(coll, addr);
1662                                 }
1663                         }
1664                 }
1665         }
1666
1667         if (IsEmptyStr(coll)) {
1668                 free(coll);
1669                 return(NULL);
1670         }
1671         return(coll);
1672 }