* quick check the email address for quoted printable encoding, so the de-qp'er doesn...
[citadel.git] / citadel / internet_addressing.c
1 /*
2  * $Id$
3  *
4  * This file contains functions which handle the mapping of Internet addresses
5  * to users on the Citadel system.
6  */
7
8 #include "sysdep.h"
9 #include <stdlib.h>
10 #include <unistd.h>
11 #include <stdio.h>
12 #include <fcntl.h>
13 #include <ctype.h>
14 #include <signal.h>
15 #include <pwd.h>
16 #include <errno.h>
17 #include <sys/types.h>
18
19 #if TIME_WITH_SYS_TIME
20 # include <sys/time.h>
21 # include <time.h>
22 #else
23 # if HAVE_SYS_TIME_H
24 #  include <sys/time.h>
25 # else
26 #  include <time.h>
27 # endif
28 #endif
29
30 #include <sys/wait.h>
31 #include <string.h>
32 #include <limits.h>
33 #include <libcitadel.h>
34 #include "citadel.h"
35 #include "server.h"
36 #include "sysdep_decls.h"
37 #include "citserver.h"
38 #include "support.h"
39 #include "config.h"
40 #include "msgbase.h"
41 #include "internet_addressing.h"
42 #include "user_ops.h"
43 #include "room_ops.h"
44 #include "parsedate.h"
45 #include "database.h"
46
47
48 #ifndef HAVE_SNPRINTF
49 #include "snprintf.h"
50 #endif
51
52
53 #ifdef HAVE_ICONV
54 #include <iconv.h>
55
56 /*
57  * Wrapper around iconv_open()
58  * Our version adds aliases for non-standard Microsoft charsets
59  * such as 'MS950', aliasing them to names like 'CP950'
60  *
61  * tocode       Target encoding
62  * fromcode     Source encoding
63  */
64 iconv_t ctdl_iconv_open(const char *tocode, const char *fromcode)
65 {
66         iconv_t ic = (iconv_t)(-1) ;
67         ic = iconv_open(tocode, fromcode);
68         if (ic == (iconv_t)(-1) ) {
69                 char alias_fromcode[64];
70                 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
71                         safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
72                         alias_fromcode[0] = 'C';
73                         alias_fromcode[1] = 'P';
74                         ic = iconv_open(tocode, alias_fromcode);
75                 }
76         }
77         return(ic);
78 }
79
80 #if 0
81 /* This is the non-define version in case of s.b. needing to debug */
82 inline void FindNextEnd (char *bptr, char *end)
83 {
84         /* Find the next ?Q? */
85         end = strchr(bptr + 2, '?');
86         if (end == NULL) return NULL;
87         if (((*(end + 1) == 'B') || (*(end + 1) == 'Q')) && 
88             (*(end + 2) == '?')) {
89                 /* skip on to the end of the cluster, the next ?= */
90                 end = strstr(end + 3, "?=");
91         }
92         else
93                 /* sort of half valid encoding, try to find an end. */
94                 end = strstr(bptr, "?=");
95 }
96 #endif
97
98 #define FindNextEnd(bptr, end) { \
99         end = strchr(bptr + 2, '?'); \
100         if (end != NULL) { \
101                 if (((*(end + 1) == 'B') || (*(end + 1) == 'Q')) && (*(end + 2) == '?')) { \
102                         end = strstr(end + 3, "?="); \
103                 } else end = strstr(bptr, "?="); \
104         } \
105 }
106
107 /*
108  * Handle subjects with RFC2047 encoding such as:
109  * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
110  */
111 void utf8ify_rfc822_string(char *buf) {
112         char *start, *end, *next, *nextend, *ptr;
113         char newbuf[1024];
114         char charset[128];
115         char encoding[16];
116         char istr[1024];
117         iconv_t ic = (iconv_t)(-1) ;
118         char *ibuf;                     /**< Buffer of characters to be converted */
119         char *obuf;                     /**< Buffer for converted characters */
120         size_t ibuflen;                 /**< Length of input buffer */
121         size_t obuflen;                 /**< Length of output buffer */
122         char *isav;                     /**< Saved pointer to input buffer */
123         char *osav;                     /**< Saved pointer to output buffer */
124         int passes = 0;
125         int i, len, delta;
126         int illegal_non_rfc2047_encoding = 0;
127
128         /* Sometimes, badly formed messages contain strings which were simply
129          *  written out directly in some foreign character set instead of
130          *  using RFC2047 encoding.  This is illegal but we will attempt to
131          *  handle it anyway by converting from a user-specified default
132          *  charset to UTF-8 if we see any nonprintable characters.
133          */
134         len = strlen(buf);
135         for (i=0; i<len; ++i) {
136                 if ((buf[i] < 32) || (buf[i] > 126)) {
137                         illegal_non_rfc2047_encoding = 1;
138                         i = len; ///< take a shortcut, it won't be more than one.
139                 }
140         }
141         if (illegal_non_rfc2047_encoding) {
142                 const char *default_header_charset = "iso-8859-1";
143                 if ( (strcasecmp(default_header_charset, "UTF-8")) && (strcasecmp(default_header_charset, "us-ascii")) ) {
144                         ic = ctdl_iconv_open("UTF-8", default_header_charset);
145                         if (ic != (iconv_t)(-1) ) {
146                                 ibuf = malloc(1024);
147                                 isav = ibuf;
148                                 safestrncpy(ibuf, buf, 1024);
149                                 ibuflen = strlen(ibuf);
150                                 obuflen = 1024;
151                                 obuf = (char *) malloc(obuflen);
152                                 osav = obuf;
153                                 iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
154                                 osav[1024-obuflen] = 0;
155                                 strcpy(buf, osav);
156                                 free(osav);
157                                 iconv_close(ic);
158                                 free(isav);
159                         }
160                 }
161         }
162
163         /* pre evaluate the first pair */
164         nextend = end = NULL;
165         len = strlen(buf);
166         start = strstr(buf, "=?");
167         if (start != NULL) 
168                 FindNextEnd (start, end);
169
170         while ((start != NULL) && (end != NULL))
171         {
172                 next = strstr(end, "=?");
173                 if (next != NULL)
174                         FindNextEnd(next, nextend);
175                 if (nextend == NULL)
176                         next = NULL;
177
178                 /* did we find two partitions */
179                 if ((next != NULL) && 
180                     ((next - end) > 2))
181                 {
182                         ptr = end + 2;
183                         while ((ptr < next) && 
184                                (isspace(*ptr) ||
185                                 (*ptr == '\r') ||
186                                 (*ptr == '\n') || 
187                                 (*ptr == '\t')))
188                                 ptr ++;
189                         /* did we find a gab just filled with blanks? */
190                         if (ptr == next)
191                         {
192                                 memmove (end + 2,
193                                          next,
194                                          len - (next - start));
195
196                                 /* now terminate the gab at the end */
197                                 delta = (next - end) - 2;
198                                 len -= delta;
199                                 buf[len] = '\0';
200
201                                 /* move next to its new location. */
202                                 next -= delta;
203                                 nextend -= delta;
204                         }
205                 }
206                 /* our next-pair is our new first pair now. */
207                 start = next;
208                 end = nextend;
209         }
210
211         /* Now we handle foreign character sets properly encoded
212          * in RFC2047 format.
213          */
214         start = strstr(buf, "=?");
215         FindNextEnd((start != NULL)? start : buf, end);
216         while (start != NULL && end != NULL && end > start)
217         {
218                 extract_token(charset, start, 1, '?', sizeof charset);
219                 extract_token(encoding, start, 2, '?', sizeof encoding);
220                 extract_token(istr, start, 3, '?', sizeof istr);
221
222                 ibuf = malloc(1024);
223                 isav = ibuf;
224                 if (!strcasecmp(encoding, "B")) {       /**< base64 */
225                         ibuflen = CtdlDecodeBase64(ibuf, istr, strlen(istr));
226                 }
227                 else if (!strcasecmp(encoding, "Q")) {  /**< quoted-printable */
228                         size_t len;
229                         long pos;
230                         
231                         len = strlen(istr);
232                         pos = 0;
233                         while (pos < len)
234                         {
235                                 if (istr[pos] == '_') istr[pos] = ' ';
236                                 pos++;
237                         }
238
239                         ibuflen = CtdlDecodeQuotedPrintable(ibuf, istr, len);
240                 }
241                 else {
242                         strcpy(ibuf, istr);             /**< unknown encoding */
243                         ibuflen = strlen(istr);
244                 }
245
246                 ic = ctdl_iconv_open("UTF-8", charset);
247                 if (ic != (iconv_t)(-1) ) {
248                         obuflen = 1024;
249                         obuf = (char *) malloc(obuflen);
250                         osav = obuf;
251                         iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
252                         osav[1024-obuflen] = 0;
253
254                         end = start;
255                         end++;
256                         strcpy(start, "");
257                         remove_token(end, 0, '?');
258                         remove_token(end, 0, '?');
259                         remove_token(end, 0, '?');
260                         remove_token(end, 0, '?');
261                         strcpy(end, &end[1]);
262
263                         snprintf(newbuf, sizeof newbuf, "%s%s%s", buf, osav, end);
264                         strcpy(buf, newbuf);
265                         free(osav);
266                         iconv_close(ic);
267                 }
268                 else {
269                         end = start;
270                         end++;
271                         strcpy(start, "");
272                         remove_token(end, 0, '?');
273                         remove_token(end, 0, '?');
274                         remove_token(end, 0, '?');
275                         remove_token(end, 0, '?');
276                         strcpy(end, &end[1]);
277
278                         snprintf(newbuf, sizeof newbuf, "%s(unreadable)%s", buf, end);
279                         strcpy(buf, newbuf);
280                 }
281
282                 free(isav);
283
284                 /*
285                  * Since spammers will go to all sorts of absurd lengths to get their
286                  * messages through, there are LOTS of corrupt headers out there.
287                  * So, prevent a really badly formed RFC2047 header from throwing
288                  * this function into an infinite loop.
289                  */
290                 ++passes;
291                 if (passes > 20) return;
292
293                 start = strstr(buf, "=?");
294                 FindNextEnd((start != NULL)? start : buf, end);
295         }
296
297 }
298 #else
299 inline void utf8ify_rfc822_string(char *a){};
300
301 #endif
302
303
304
305 struct trynamebuf {
306         char buffer1[SIZ];
307         char buffer2[SIZ];
308 };
309
310 char *inetcfg = NULL;
311 struct spamstrings_t *spamstrings = NULL;
312
313
314 /*
315  * Return nonzero if the supplied name is an alias for this host.
316  */
317 int CtdlHostAlias(char *fqdn) {
318         int config_lines;
319         int i;
320         char buf[256];
321         char host[256], type[256];
322
323         if (fqdn == NULL) return(hostalias_nomatch);
324         if (IsEmptyStr(fqdn)) return(hostalias_nomatch);
325         if (!strcasecmp(fqdn, "localhost")) return(hostalias_localhost);
326         if (!strcasecmp(fqdn, config.c_fqdn)) return(hostalias_localhost);
327         if (!strcasecmp(fqdn, config.c_nodename)) return(hostalias_localhost);
328         if (inetcfg == NULL) return(hostalias_nomatch);
329
330         config_lines = num_tokens(inetcfg, '\n');
331         for (i=0; i<config_lines; ++i) {
332                 extract_token(buf, inetcfg, i, '\n', sizeof buf);
333                 extract_token(host, buf, 0, '|', sizeof host);
334                 extract_token(type, buf, 1, '|', sizeof type);
335
336                 if ( (!strcasecmp(type, "localhost"))
337                    && (!strcasecmp(fqdn, host)))
338                         return(hostalias_localhost);
339
340                 if ( (!strcasecmp(type, "directory"))
341                    && (!strcasecmp(fqdn, host)))
342                         return(hostalias_directory);
343
344                 if ( (!strcasecmp(type, "masqdomain"))
345                    && (!strcasecmp(fqdn, host)))
346                         return(hostalias_masq);
347
348         }
349
350         return(hostalias_nomatch);
351 }
352
353
354
355
356
357
358
359 /*
360  * Return 0 if a given string fuzzy-matches a Citadel user account
361  *
362  * FIXME ... this needs to be updated to handle aliases.
363  */
364 int fuzzy_match(struct ctdluser *us, char *matchstring) {
365         int a;
366         long len;
367
368         if ( (!strncasecmp(matchstring, "cit", 3)) 
369            && (atol(&matchstring[3]) == us->usernum)) {
370                 return 0;
371         }
372
373         len = strlen(matchstring);
374         for (a=0; !IsEmptyStr(&us->fullname[a]); ++a) {
375                 if (!strncasecmp(&us->fullname[a],
376                    matchstring, len)) {
377                         return 0;
378                 }
379         }
380         return -1;
381 }
382
383
384 /*
385  * Unfold a multi-line field into a single line, removing multi-whitespaces
386  */
387 void unfold_rfc822_field(char *field) {
388         int i;
389         int quote = 0;
390
391         striplt(field);         /* remove leading/trailing whitespace */
392
393         /* convert non-space whitespace to spaces, and remove double blanks */
394         for (i=0; i<strlen(field); ++i) {
395                 if (field[i]=='\"') quote = 1 - quote;
396                 if (!quote) {
397                         if (isspace(field[i])) field[i] = ' ';
398                         while (isspace(field[i]) && isspace(field[i+1])) {
399                                 strcpy(&field[i+1], &field[i+2]);
400                         }
401                 }
402         }
403 }
404
405
406
407 /*
408  * Split an RFC822-style address into userid, host, and full name
409  *
410  */
411 void process_rfc822_addr(const char *rfc822, char *user, char *node, char *name)
412 {
413         int a;
414
415         strcpy(user, "");
416         strcpy(node, config.c_fqdn);
417         strcpy(name, "");
418
419         if (rfc822 == NULL) return;
420
421         /* extract full name - first, it's From minus <userid> */
422         strcpy(name, rfc822);
423         stripout(name, '<', '>');
424
425         /* strip anything to the left of a bang */
426         while ((!IsEmptyStr(name)) && (haschar(name, '!') > 0))
427                 strcpy(name, &name[1]);
428
429         /* and anything to the right of a @ or % */
430         for (a = 0; a < strlen(name); ++a) {
431                 if (name[a] == '@')
432                         name[a] = 0;
433                 if (name[a] == '%')
434                         name[a] = 0;
435         }
436
437         /* but if there are parentheses, that changes the rules... */
438         if ((haschar(rfc822, '(') == 1) && (haschar(rfc822, ')') == 1)) {
439                 strcpy(name, rfc822);
440                 stripallbut(name, '(', ')');
441         }
442
443         /* but if there are a set of quotes, that supersedes everything */
444         if (haschar(rfc822, 34) == 2) {
445                 strcpy(name, rfc822);
446                 while ((!IsEmptyStr(name)) && (name[0] != 34)) {
447                         strcpy(&name[0], &name[1]);
448                 }
449                 strcpy(&name[0], &name[1]);
450                 for (a = 0; a < strlen(name); ++a)
451                         if (name[a] == 34)
452                                 name[a] = 0;
453         }
454         /* extract user id */
455         strcpy(user, rfc822);
456
457         /* first get rid of anything in parens */
458         stripout(user, '(', ')');
459
460         /* if there's a set of angle brackets, strip it down to that */
461         if ((haschar(user, '<') == 1) && (haschar(user, '>') == 1)) {
462                 stripallbut(user, '<', '>');
463         }
464
465         /* strip anything to the left of a bang */
466         while ((!IsEmptyStr(user)) && (haschar(user, '!') > 0))
467                 strcpy(user, &user[1]);
468
469         /* and anything to the right of a @ or % */
470         for (a = 0; a < strlen(user); ++a) {
471                 if (user[a] == '@')
472                         user[a] = 0;
473                 if (user[a] == '%')
474                         user[a] = 0;
475         }
476
477
478         /* extract node name */
479         strcpy(node, rfc822);
480
481         /* first get rid of anything in parens */
482         stripout(node, '(', ')');
483
484         /* if there's a set of angle brackets, strip it down to that */
485         if ((haschar(node, '<') == 1) && (haschar(node, '>') == 1)) {
486                 stripallbut(node, '<', '>');
487         }
488
489         /* If no node specified, tack ours on instead */
490         if (
491                 (haschar(node, '@')==0)
492                 && (haschar(node, '%')==0)
493                 && (haschar(node, '!')==0)
494         ) {
495                 strcpy(node, config.c_nodename);
496         }
497
498         else {
499
500                 /* strip anything to the left of a @ */
501                 while ((!IsEmptyStr(node)) && (haschar(node, '@') > 0))
502                         strcpy(node, &node[1]);
503         
504                 /* strip anything to the left of a % */
505                 while ((!IsEmptyStr(node)) && (haschar(node, '%') > 0))
506                         strcpy(node, &node[1]);
507         
508                 /* reduce multiple system bang paths to node!user */
509                 while ((!IsEmptyStr(node)) && (haschar(node, '!') > 1))
510                         strcpy(node, &node[1]);
511         
512                 /* now get rid of the user portion of a node!user string */
513                 for (a = 0; a < strlen(node); ++a)
514                         if (node[a] == '!')
515                                 node[a] = 0;
516         }
517
518         /* strip leading and trailing spaces in all strings */
519         striplt(user);
520         striplt(node);
521         striplt(name);
522
523         /* If we processed a string that had the address in angle brackets
524          * but no name outside the brackets, we now have an empty name.  In
525          * this case, use the user portion of the address as the name.
526          */
527         if ((IsEmptyStr(name)) && (!IsEmptyStr(user))) {
528                 strcpy(name, user);
529         }
530 }
531
532
533
534 /*
535  * convert_field() is a helper function for convert_internet_message().
536  * Given start/end positions for an rfc822 field, it converts it to a Citadel
537  * field if it wants to, and unfolds it if necessary.
538  *
539  * Returns 1 if the field was converted and inserted into the Citadel message
540  * structure, implying that the source field should be removed from the
541  * message text.
542  */
543 int convert_field(struct CtdlMessage *msg, int beg, int end) {
544         char *rfc822;
545         char *key, *value;
546         int i;
547         int colonpos = (-1);
548         int processed = 0;
549         char buf[SIZ];
550         char user[1024];
551         char node[1024];
552         char name[1024];
553         char addr[1024];
554         time_t parsed_date;
555
556         rfc822 = msg->cm_fields['M'];   /* M field contains rfc822 text */
557         for (i = end; i >= beg; --i) {
558                 if (rfc822[i] == ':') colonpos = i;
559         }
560
561         if (colonpos < 0) return(0);    /* no colon? not a valid header line */
562
563         key = malloc((end - beg) + 2);
564         safestrncpy(key, &rfc822[beg], (end-beg)+1);
565         key[colonpos - beg] = 0;
566         value = &key[(colonpos - beg) + 1];
567         unfold_rfc822_field(value);
568
569         /*
570          * Here's the big rfc822-to-citadel loop.
571          */
572
573         /* Date/time is converted into a unix timestamp.  If the conversion
574          * fails, we replace it with the time the message arrived locally.
575          */
576         if (!strcasecmp(key, "Date")) {
577                 parsed_date = parsedate(value);
578                 if (parsed_date < 0L) parsed_date = time(NULL);
579                 snprintf(buf, sizeof buf, "%ld", (long)parsed_date );
580                 if (msg->cm_fields['T'] == NULL)
581                         msg->cm_fields['T'] = strdup(buf);
582                 processed = 1;
583         }
584
585         else if (!strcasecmp(key, "From")) {
586                 process_rfc822_addr(value, user, node, name);
587                 CtdlLogPrintf(CTDL_DEBUG, "Converted to <%s@%s> (%s)\n", user, node, name);
588                 snprintf(addr, sizeof addr, "%s@%s", user, node);
589                 if (msg->cm_fields['A'] == NULL)
590                         msg->cm_fields['A'] = strdup(name);
591                 processed = 1;
592                 if (msg->cm_fields['F'] == NULL)
593                         msg->cm_fields['F'] = strdup(addr);
594                 processed = 1;
595         }
596
597         else if (!strcasecmp(key, "Subject")) {
598                 if (msg->cm_fields['U'] == NULL)
599                         msg->cm_fields['U'] = strdup(value);
600                 processed = 1;
601         }
602
603         else if (!strcasecmp(key, "To")) {
604                 if (msg->cm_fields['R'] == NULL)
605                         msg->cm_fields['R'] = strdup(value);
606                 processed = 1;
607         }
608
609         else if (!strcasecmp(key, "CC")) {
610                 if (msg->cm_fields['Y'] == NULL)
611                         msg->cm_fields['Y'] = strdup(value);
612                 processed = 1;
613         }
614
615         else if (!strcasecmp(key, "Message-ID")) {
616                 if (msg->cm_fields['I'] != NULL) {
617                         CtdlLogPrintf(CTDL_WARNING, "duplicate message id\n");
618                 }
619
620                 if (msg->cm_fields['I'] == NULL) {
621                         msg->cm_fields['I'] = strdup(value);
622
623                         /* Strip angle brackets */
624                         while (haschar(msg->cm_fields['I'], '<') > 0) {
625                                 strcpy(&msg->cm_fields['I'][0],
626                                         &msg->cm_fields['I'][1]);
627                         }
628                         for (i = 0; i<strlen(msg->cm_fields['I']); ++i)
629                                 if (msg->cm_fields['I'][i] == '>')
630                                         msg->cm_fields['I'][i] = 0;
631                 }
632
633                 processed = 1;
634         }
635
636         else if (!strcasecmp(key, "Return-Path")) {
637                 if (msg->cm_fields['P'] == NULL)
638                         msg->cm_fields['P'] = strdup(value);
639                 processed = 1;
640         }
641
642         else if (!strcasecmp(key, "Envelope-To")) {
643                 if (msg->cm_fields['V'] == NULL)
644                         msg->cm_fields['V'] = strdup(value);
645                 processed = 1;
646         }
647
648         else if (!strcasecmp(key, "References")) {
649                 if (msg->cm_fields['W'] != NULL) {
650                         free(msg->cm_fields['W']);
651                 }
652                 msg->cm_fields['W'] = strdup(value);
653                 processed = 1;
654         }
655
656         else if (!strcasecmp(key, "In-reply-to")) {
657                 if (msg->cm_fields['W'] == NULL) {              /* References: supersedes In-reply-to: */
658                         msg->cm_fields['W'] = strdup(value);
659                 }
660                 processed = 1;
661         }
662
663
664
665         /* Clean up and move on. */
666         free(key);      /* Don't free 'value', it's actually the same buffer */
667         return(processed);
668 }
669
670
671 /*
672  * Convert RFC822 references format (References) to Citadel references format (Weferences)
673  */
674 void convert_references_to_wefewences(char *str) {
675         int bracket_nesting = 0;
676         char *ptr = str;
677         char *moveptr = NULL;
678         char ch;
679
680         while(*ptr) {
681                 ch = *ptr;
682                 if (ch == '>') {
683                         --bracket_nesting;
684                         if (bracket_nesting < 0) bracket_nesting = 0;
685                 }
686                 if ((ch == '>') && (bracket_nesting == 0) && (*(ptr+1)) && (ptr>str) ) {
687                         *ptr = '|';
688                         ++ptr;
689                 }
690                 else if (bracket_nesting > 0) {
691                         ++ptr;
692                 }
693                 else {
694                         moveptr = ptr;
695                         while (*moveptr) {
696                                 *moveptr = *(moveptr+1);
697                                 ++moveptr;
698                         }
699                 }
700                 if (ch == '<') ++bracket_nesting;
701         }
702
703 }
704
705
706 /*
707  * Convert an RFC822 message (headers + body) to a CtdlMessage structure.
708  * NOTE: the supplied buffer becomes part of the CtdlMessage structure, and
709  * will be deallocated when CtdlFreeMessage() is called.  Therefore, the
710  * supplied buffer should be DEREFERENCED.  It should not be freed or used
711  * again.
712  */
713 struct CtdlMessage *convert_internet_message(char *rfc822) {
714
715         struct CtdlMessage *msg;
716         int pos, beg, end, msglen;
717         int done;
718         char buf[SIZ];
719         int converted;
720
721         msg = malloc(sizeof(struct CtdlMessage));
722         if (msg == NULL) return msg;
723
724         memset(msg, 0, sizeof(struct CtdlMessage));
725         msg->cm_magic = CTDLMESSAGE_MAGIC;      /* self check */
726         msg->cm_anon_type = 0;                  /* never anonymous */
727         msg->cm_format_type = FMT_RFC822;       /* internet message */
728         msg->cm_fields['M'] = rfc822;
729
730         pos = 0;
731         done = 0;
732
733         while (!done) {
734
735                 /* Locate beginning and end of field, keeping in mind that
736                  * some fields might be multiline
737                  */
738                 beg = pos;
739                 end = (-1);
740
741                 msglen = strlen(rfc822);        
742                 while ( (end < 0) && (done == 0) ) {
743
744                         if ((rfc822[pos]=='\n')
745                            && (!isspace(rfc822[pos+1]))) {
746                                 end = pos;
747                         }
748
749                         /* done with headers? */
750                         if (   (rfc822[pos]=='\n')
751                            && ( (rfc822[pos+1]=='\n')
752                               ||(rfc822[pos+1]=='\r')) ) {
753                                 end = pos;
754                                 done = 1;
755                         }
756
757                         if (pos >= (msglen-1) ) {
758                                 end = pos;
759                                 done = 1;
760                         }
761
762                         ++pos;
763
764                 }
765
766                 /* At this point we have a field.  Are we interested in it? */
767                 converted = convert_field(msg, beg, end);
768
769                 /* Strip the field out of the RFC822 header if we used it */
770                 if (converted) {
771                         strcpy(&rfc822[beg], &rfc822[pos]);
772                         pos = beg;
773                 }
774
775                 /* If we've hit the end of the message, bail out */
776                 if (pos > strlen(rfc822)) done = 1;
777         }
778
779         /* Follow-up sanity checks... */
780
781         /* If there's no timestamp on this message, set it to now. */
782         if (msg->cm_fields['T'] == NULL) {
783                 snprintf(buf, sizeof buf, "%ld", (long)time(NULL));
784                 msg->cm_fields['T'] = strdup(buf);
785         }
786
787         /* If a W (references, or rather, Wefewences) field is present, we
788          * have to convert it from RFC822 format to Citadel format.
789          */
790         if (msg->cm_fields['W'] != NULL) {
791                 convert_references_to_wefewences(msg->cm_fields['W']);
792         }
793
794         return msg;
795 }
796
797
798
799 /*
800  * Look for a particular header field in an RFC822 message text.  If the
801  * requested field is found, it is unfolded (if necessary) and returned to
802  * the caller.  The field name is stripped out, leaving only its contents.
803  * The caller is responsible for freeing the returned buffer.  If the requested
804  * field is not present, or anything else goes wrong, it returns NULL.
805  */
806 char *rfc822_fetch_field(char *rfc822, char *fieldname) {
807         char *fieldbuf = NULL;
808         char *end_of_headers;
809         char *field_start;
810         char *ptr;
811         char *cont;
812         char fieldhdr[SIZ];
813
814         /* Should never happen, but sometimes we get stupid */
815         if (rfc822 == NULL) return(NULL);
816         if (fieldname == NULL) return(NULL);
817
818         snprintf(fieldhdr, sizeof fieldhdr, "%s:", fieldname);
819
820         /* Locate the end of the headers, so we don't run past that point */
821         end_of_headers = bmstrcasestr(rfc822, "\n\r\n");
822         if (end_of_headers == NULL) {
823                 end_of_headers = bmstrcasestr(rfc822, "\n\n");
824         }
825         if (end_of_headers == NULL) return (NULL);
826
827         field_start = bmstrcasestr(rfc822, fieldhdr);
828         if (field_start == NULL) return(NULL);
829         if (field_start > end_of_headers) return(NULL);
830
831         fieldbuf = malloc(SIZ);
832         strcpy(fieldbuf, "");
833
834         ptr = field_start;
835         ptr = memreadline(ptr, fieldbuf, SIZ-strlen(fieldbuf) );
836         while ( (isspace(ptr[0])) && (ptr < end_of_headers) ) {
837                 strcat(fieldbuf, " ");
838                 cont = &fieldbuf[strlen(fieldbuf)];
839                 ptr = memreadline(ptr, cont, SIZ-strlen(fieldbuf) );
840                 striplt(cont);
841         }
842
843         strcpy(fieldbuf, &fieldbuf[strlen(fieldhdr)]);
844         striplt(fieldbuf);
845
846         return(fieldbuf);
847 }
848
849
850
851 /*****************************************************************************
852  *                      DIRECTORY MANAGEMENT FUNCTIONS                       *
853  *****************************************************************************/
854
855 /*
856  * Generate the index key for an Internet e-mail address to be looked up
857  * in the database.
858  */
859 void directory_key(char *key, char *addr) {
860         int i;
861         int keylen = 0;
862
863         for (i=0; !IsEmptyStr(&addr[i]); ++i) {
864                 if (!isspace(addr[i])) {
865                         key[keylen++] = tolower(addr[i]);
866                 }
867         }
868         key[keylen++] = 0;
869
870         CtdlLogPrintf(CTDL_DEBUG, "Directory key is <%s>\n", key);
871 }
872
873
874
875 /* Return nonzero if the supplied address is in a domain we keep in
876  * the directory
877  */
878 int IsDirectory(char *addr, int allow_masq_domains) {
879         char domain[256];
880         int h;
881
882         extract_token(domain, addr, 1, '@', sizeof domain);
883         striplt(domain);
884
885         h = CtdlHostAlias(domain);
886
887         if ( (h == hostalias_masq) && allow_masq_domains)
888                 return(1);
889         
890         if ( (h == hostalias_localhost) || (h == hostalias_directory) ) {
891                 return(1);
892         }
893         else {
894                 return(0);
895         }
896 }
897
898
899 /*
900  * Initialize the directory database (erasing anything already there)
901  */
902 void CtdlDirectoryInit(void) {
903         cdb_trunc(CDB_DIRECTORY);
904 }
905
906
907 /*
908  * Add an Internet e-mail address to the directory for a user
909  */
910 void CtdlDirectoryAddUser(char *internet_addr, char *citadel_addr) {
911         char key[SIZ];
912
913         CtdlLogPrintf(CTDL_DEBUG, "Dir: %s --> %s\n",
914                 internet_addr, citadel_addr);
915         if (IsDirectory(internet_addr, 0) == 0) return;
916
917         directory_key(key, internet_addr);
918
919         cdb_store(CDB_DIRECTORY, key, strlen(key),
920                 citadel_addr, strlen(citadel_addr)+1 );
921 }
922
923
924 /*
925  * Delete an Internet e-mail address from the directory.
926  *
927  * (NOTE: we don't actually use or need the citadel_addr variable; it's merely
928  * here because the callback API expects to be able to send it.)
929  */
930 void CtdlDirectoryDelUser(char *internet_addr, char *citadel_addr) {
931         char key[SIZ];
932
933         directory_key(key, internet_addr);
934         cdb_delete(CDB_DIRECTORY, key, strlen(key) );
935 }
936
937
938 /*
939  * Look up an Internet e-mail address in the directory.
940  * On success: returns 0, and Citadel address stored in 'target'
941  * On failure: returns nonzero
942  */
943 int CtdlDirectoryLookup(char *target, char *internet_addr, size_t targbuflen) {
944         struct cdbdata *cdbrec;
945         char key[SIZ];
946
947         /* Dump it in there unchanged, just for kicks */
948         safestrncpy(target, internet_addr, targbuflen);
949
950         /* Only do lookups for addresses with hostnames in them */
951         if (num_tokens(internet_addr, '@') != 2) return(-1);
952
953         /* Only do lookups for domains in the directory */
954         if (IsDirectory(internet_addr, 0) == 0) return(-1);
955
956         directory_key(key, internet_addr);
957         cdbrec = cdb_fetch(CDB_DIRECTORY, key, strlen(key) );
958         if (cdbrec != NULL) {
959                 safestrncpy(target, cdbrec->ptr, targbuflen);
960                 cdb_free(cdbrec);
961                 return(0);
962         }
963
964         return(-1);
965 }
966
967
968 /*
969  * Harvest any email addresses that someone might want to have in their
970  * "collected addresses" book.
971  */
972 char *harvest_collected_addresses(struct CtdlMessage *msg) {
973         char *coll = NULL;
974         char addr[256];
975         char user[256], node[256], name[256];
976         int is_harvestable;
977         int i, j, h;
978         int field = 0;
979
980         if (msg == NULL) return(NULL);
981
982         is_harvestable = 1;
983         strcpy(addr, "");       
984         if (msg->cm_fields['A'] != NULL) {
985                 strcat(addr, msg->cm_fields['A']);
986         }
987         if (msg->cm_fields['F'] != NULL) {
988                 strcat(addr, " <");
989                 strcat(addr, msg->cm_fields['F']);
990                 strcat(addr, ">");
991                 if (IsDirectory(msg->cm_fields['F'], 0)) {
992                         is_harvestable = 0;
993                 }
994         }
995
996         if (is_harvestable) {
997                 coll = strdup(addr);
998         }
999         else {
1000                 coll = strdup("");
1001         }
1002
1003         if (coll == NULL) return(NULL);
1004
1005         /* Scan both the R (To) and Y (CC) fields */
1006         for (i = 0; i < 2; ++i) {
1007                 if (i == 0) field = 'R' ;
1008                 if (i == 1) field = 'Y' ;
1009
1010                 if (msg->cm_fields[field] != NULL) {
1011                         for (j=0; j<num_tokens(msg->cm_fields[field], ','); ++j) {
1012                                 extract_token(addr, msg->cm_fields[field], j, ',', sizeof addr);
1013                                 if (strstr(addr, "=?") != NULL)
1014                                         utf8ify_rfc822_string(addr);
1015                                 process_rfc822_addr(addr, user, node, name);
1016                                 h = CtdlHostAlias(node);
1017                                 if ( (h != hostalias_localhost) && (h != hostalias_directory) ) {
1018                                         coll = realloc(coll, strlen(coll) + strlen(addr) + 4);
1019                                         if (coll == NULL) return(NULL);
1020                                         if (!IsEmptyStr(coll)) {
1021                                                 strcat(coll, ",");
1022                                         }
1023                                         striplt(addr);
1024                                         strcat(coll, addr);
1025                                 }
1026                         }
1027                 }
1028         }
1029
1030         if (IsEmptyStr(coll)) {
1031                 free(coll);
1032                 return(NULL);
1033         }
1034         return(coll);
1035 }