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