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