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