* use iconv in citserver too
[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
81
82 inline char *FindNextEnd (char *bptr)
83 {
84         char * end;
85         /* Find the next ?Q? */
86         end = strchr(bptr + 2, '?');
87         if (end == NULL) return NULL;
88         if (((*(end + 1) == 'B') || (*(end + 1) == 'Q')) && 
89             (*(end + 2) == '?')) {
90                 /* skip on to the end of the cluster, the next ?= */
91                 end = strstr(end + 3, "?=");
92         }
93         else
94                 /* sort of half valid encoding, try to find an end. */
95                 end = strstr(bptr, "?=");
96         return end;
97 }
98
99 /*
100  * Handle subjects with RFC2047 encoding such as:
101  * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
102  */
103 void utf8ify_rfc822_string(char *buf) {
104         char *start, *end, *next, *nextend, *ptr;
105         char newbuf[1024];
106         char charset[128];
107         char encoding[16];
108         char istr[1024];
109         iconv_t ic = (iconv_t)(-1) ;
110         char *ibuf;                     /**< Buffer of characters to be converted */
111         char *obuf;                     /**< Buffer for converted characters */
112         size_t ibuflen;                 /**< Length of input buffer */
113         size_t obuflen;                 /**< Length of output buffer */
114         char *isav;                     /**< Saved pointer to input buffer */
115         char *osav;                     /**< Saved pointer to output buffer */
116         int passes = 0;
117         int i, len, delta;
118         int illegal_non_rfc2047_encoding = 0;
119
120         /* Sometimes, badly formed messages contain strings which were simply
121          *  written out directly in some foreign character set instead of
122          *  using RFC2047 encoding.  This is illegal but we will attempt to
123          *  handle it anyway by converting from a user-specified default
124          *  charset to UTF-8 if we see any nonprintable characters.
125          */
126         len = strlen(buf);
127         for (i=0; i<len; ++i) {
128                 if ((buf[i] < 32) || (buf[i] > 126)) {
129                         illegal_non_rfc2047_encoding = 1;
130                         i = len; ///< take a shortcut, it won't be more than one.
131                 }
132         }
133         if (illegal_non_rfc2047_encoding) {
134                 const char *default_header_charset = "iso-8859-1";
135                 if ( (strcasecmp(default_header_charset, "UTF-8")) && (strcasecmp(default_header_charset, "us-ascii")) ) {
136                         ic = ctdl_iconv_open("UTF-8", default_header_charset);
137                         if (ic != (iconv_t)(-1) ) {
138                                 ibuf = malloc(1024);
139                                 isav = ibuf;
140                                 safestrncpy(ibuf, buf, 1024);
141                                 ibuflen = strlen(ibuf);
142                                 obuflen = 1024;
143                                 obuf = (char *) malloc(obuflen);
144                                 osav = obuf;
145                                 iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
146                                 osav[1024-obuflen] = 0;
147                                 strcpy(buf, osav);
148                                 free(osav);
149                                 iconv_close(ic);
150                                 free(isav);
151                         }
152                 }
153         }
154
155         /* pre evaluate the first pair */
156         nextend = end = NULL;
157         len = strlen(buf);
158         start = strstr(buf, "=?");
159         if (start != NULL) 
160                 end = FindNextEnd (start);
161
162         while ((start != NULL) && (end != NULL))
163         {
164                 next = strstr(end, "=?");
165                 if (next != NULL)
166                         nextend = FindNextEnd(next);
167                 if (nextend == NULL)
168                         next = NULL;
169
170                 /* did we find two partitions */
171                 if ((next != NULL) && 
172                     ((next - end) > 2))
173                 {
174                         ptr = end + 2;
175                         while ((ptr < next) && 
176                                (isspace(*ptr) ||
177                                 (*ptr == '\r') ||
178                                 (*ptr == '\n') || 
179                                 (*ptr == '\t')))
180                                 ptr ++;
181                         /* did we find a gab just filled with blanks? */
182                         if (ptr == next)
183                         {
184                                 memmove (end + 2,
185                                          next,
186                                          len - (next - start));
187
188                                 /* now terminate the gab at the end */
189                                 delta = (next - end) - 2;
190                                 len -= delta;
191                                 buf[len] = '\0';
192
193                                 /* move next to its new location. */
194                                 next -= delta;
195                                 nextend -= delta;
196                         }
197                 }
198                 /* our next-pair is our new first pair now. */
199                 start = next;
200                 end = nextend;
201         }
202
203         /* Now we handle foreign character sets properly encoded
204          * in RFC2047 format.
205          */
206         while (start=strstr(buf, "=?"), end=FindNextEnd((start != NULL)? start : buf),
207                 ((start != NULL) && (end != NULL) && (end > start)) )
208         {
209                 extract_token(charset, start, 1, '?', sizeof charset);
210                 extract_token(encoding, start, 2, '?', sizeof encoding);
211                 extract_token(istr, start, 3, '?', sizeof istr);
212
213                 ibuf = malloc(1024);
214                 isav = ibuf;
215                 if (!strcasecmp(encoding, "B")) {       /**< base64 */
216                         ibuflen = CtdlDecodeBase64(ibuf, istr, strlen(istr));
217                 }
218                 else if (!strcasecmp(encoding, "Q")) {  /**< quoted-printable */
219                         size_t len;
220                         long pos;
221                         
222                         len = strlen(istr);
223                         pos = 0;
224                         while (pos < len)
225                         {
226                                 if (istr[pos] == '_') istr[pos] = ' ';
227                                 pos++;
228                         }
229
230                         ibuflen = CtdlDecodeQuotedPrintable(ibuf, istr, len);
231                 }
232                 else {
233                         strcpy(ibuf, istr);             /**< unknown encoding */
234                         ibuflen = strlen(istr);
235                 }
236
237                 ic = ctdl_iconv_open("UTF-8", charset);
238                 if (ic != (iconv_t)(-1) ) {
239                         obuflen = 1024;
240                         obuf = (char *) malloc(obuflen);
241                         osav = obuf;
242                         iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
243                         osav[1024-obuflen] = 0;
244
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%s%s", buf, osav, end);
255                         strcpy(buf, newbuf);
256                         free(osav);
257                         iconv_close(ic);
258                 }
259                 else {
260                         end = start;
261                         end++;
262                         strcpy(start, "");
263                         remove_token(end, 0, '?');
264                         remove_token(end, 0, '?');
265                         remove_token(end, 0, '?');
266                         remove_token(end, 0, '?');
267                         strcpy(end, &end[1]);
268
269                         snprintf(newbuf, sizeof newbuf, "%s(unreadable)%s", buf, end);
270                         strcpy(buf, newbuf);
271                 }
272
273                 free(isav);
274
275                 /*
276                  * Since spammers will go to all sorts of absurd lengths to get their
277                  * messages through, there are LOTS of corrupt headers out there.
278                  * So, prevent a really badly formed RFC2047 header from throwing
279                  * this function into an infinite loop.
280                  */
281                 ++passes;
282                 if (passes > 20) return;
283         }
284
285 }
286 #else
287 inline void utf8ify_rfc822_string(char *a){};
288
289 #endif
290
291
292
293 struct trynamebuf {
294         char buffer1[SIZ];
295         char buffer2[SIZ];
296 };
297
298 char *inetcfg = NULL;
299 struct spamstrings_t *spamstrings = NULL;
300
301
302 /*
303  * Return nonzero if the supplied name is an alias for this host.
304  */
305 int CtdlHostAlias(char *fqdn) {
306         int config_lines;
307         int i;
308         char buf[256];
309         char host[256], type[256];
310
311         if (fqdn == NULL) return(hostalias_nomatch);
312         if (IsEmptyStr(fqdn)) return(hostalias_nomatch);
313         if (!strcasecmp(fqdn, "localhost")) return(hostalias_localhost);
314         if (!strcasecmp(fqdn, config.c_fqdn)) return(hostalias_localhost);
315         if (!strcasecmp(fqdn, config.c_nodename)) return(hostalias_localhost);
316         if (inetcfg == NULL) return(hostalias_nomatch);
317
318         config_lines = num_tokens(inetcfg, '\n');
319         for (i=0; i<config_lines; ++i) {
320                 extract_token(buf, inetcfg, i, '\n', sizeof buf);
321                 extract_token(host, buf, 0, '|', sizeof host);
322                 extract_token(type, buf, 1, '|', sizeof type);
323
324                 if ( (!strcasecmp(type, "localhost"))
325                    && (!strcasecmp(fqdn, host)))
326                         return(hostalias_localhost);
327
328                 if ( (!strcasecmp(type, "directory"))
329                    && (!strcasecmp(&fqdn[strlen(fqdn)-strlen(host)], host)))
330                         return(hostalias_directory);
331
332                 if ( (!strcasecmp(type, "masqdomain"))
333                    && (!strcasecmp(&fqdn[strlen(fqdn)-strlen(host)], host)))
334                         return(hostalias_masq);
335
336         }
337
338         return(hostalias_nomatch);
339 }
340
341
342
343
344
345
346
347 /*
348  * Return 0 if a given string fuzzy-matches a Citadel user account
349  *
350  * FIXME ... this needs to be updated to handle aliases.
351  */
352 int fuzzy_match(struct ctdluser *us, char *matchstring) {
353         int a;
354         long len;
355
356         if ( (!strncasecmp(matchstring, "cit", 3)) 
357            && (atol(&matchstring[3]) == us->usernum)) {
358                 return 0;
359         }
360
361         len = strlen(matchstring);
362         for (a=0; !IsEmptyStr(&us->fullname[a]); ++a) {
363                 if (!strncasecmp(&us->fullname[a],
364                    matchstring, len)) {
365                         return 0;
366                 }
367         }
368         return -1;
369 }
370
371
372 /*
373  * Unfold a multi-line field into a single line, removing multi-whitespaces
374  */
375 void unfold_rfc822_field(char *field) {
376         int i;
377         int quote = 0;
378
379         striplt(field);         /* remove leading/trailing whitespace */
380
381         /* convert non-space whitespace to spaces, and remove double blanks */
382         for (i=0; i<strlen(field); ++i) {
383                 if (field[i]=='\"') quote = 1 - quote;
384                 if (!quote) {
385                         if (isspace(field[i])) field[i] = ' ';
386                         while (isspace(field[i]) && isspace(field[i+1])) {
387                                 strcpy(&field[i+1], &field[i+2]);
388                         }
389                 }
390         }
391 }
392
393
394
395 /*
396  * Split an RFC822-style address into userid, host, and full name
397  *
398  */
399 void process_rfc822_addr(const char *rfc822, char *user, char *node, char *name)
400 {
401         int a;
402
403         strcpy(user, "");
404         strcpy(node, config.c_fqdn);
405         strcpy(name, "");
406
407         if (rfc822 == NULL) return;
408
409         /* extract full name - first, it's From minus <userid> */
410         strcpy(name, rfc822);
411         stripout(name, '<', '>');
412
413         /* strip anything to the left of a bang */
414         while ((!IsEmptyStr(name)) && (haschar(name, '!') > 0))
415                 strcpy(name, &name[1]);
416
417         /* and anything to the right of a @ or % */
418         for (a = 0; a < strlen(name); ++a) {
419                 if (name[a] == '@')
420                         name[a] = 0;
421                 if (name[a] == '%')
422                         name[a] = 0;
423         }
424
425         /* but if there are parentheses, that changes the rules... */
426         if ((haschar(rfc822, '(') == 1) && (haschar(rfc822, ')') == 1)) {
427                 strcpy(name, rfc822);
428                 stripallbut(name, '(', ')');
429         }
430
431         /* but if there are a set of quotes, that supersedes everything */
432         if (haschar(rfc822, 34) == 2) {
433                 strcpy(name, rfc822);
434                 while ((!IsEmptyStr(name)) && (name[0] != 34)) {
435                         strcpy(&name[0], &name[1]);
436                 }
437                 strcpy(&name[0], &name[1]);
438                 for (a = 0; a < strlen(name); ++a)
439                         if (name[a] == 34)
440                                 name[a] = 0;
441         }
442         /* extract user id */
443         strcpy(user, rfc822);
444
445         /* first get rid of anything in parens */
446         stripout(user, '(', ')');
447
448         /* if there's a set of angle brackets, strip it down to that */
449         if ((haschar(user, '<') == 1) && (haschar(user, '>') == 1)) {
450                 stripallbut(user, '<', '>');
451         }
452
453         /* strip anything to the left of a bang */
454         while ((!IsEmptyStr(user)) && (haschar(user, '!') > 0))
455                 strcpy(user, &user[1]);
456
457         /* and anything to the right of a @ or % */
458         for (a = 0; a < strlen(user); ++a) {
459                 if (user[a] == '@')
460                         user[a] = 0;
461                 if (user[a] == '%')
462                         user[a] = 0;
463         }
464
465
466         /* extract node name */
467         strcpy(node, rfc822);
468
469         /* first get rid of anything in parens */
470         stripout(node, '(', ')');
471
472         /* if there's a set of angle brackets, strip it down to that */
473         if ((haschar(node, '<') == 1) && (haschar(node, '>') == 1)) {
474                 stripallbut(node, '<', '>');
475         }
476
477         /* If no node specified, tack ours on instead */
478         if (
479                 (haschar(node, '@')==0)
480                 && (haschar(node, '%')==0)
481                 && (haschar(node, '!')==0)
482         ) {
483                 strcpy(node, config.c_nodename);
484         }
485
486         else {
487
488                 /* strip anything to the left of a @ */
489                 while ((!IsEmptyStr(node)) && (haschar(node, '@') > 0))
490                         strcpy(node, &node[1]);
491         
492                 /* strip anything to the left of a % */
493                 while ((!IsEmptyStr(node)) && (haschar(node, '%') > 0))
494                         strcpy(node, &node[1]);
495         
496                 /* reduce multiple system bang paths to node!user */
497                 while ((!IsEmptyStr(node)) && (haschar(node, '!') > 1))
498                         strcpy(node, &node[1]);
499         
500                 /* now get rid of the user portion of a node!user string */
501                 for (a = 0; a < strlen(node); ++a)
502                         if (node[a] == '!')
503                                 node[a] = 0;
504         }
505
506         /* strip leading and trailing spaces in all strings */
507         striplt(user);
508         striplt(node);
509         striplt(name);
510
511         /* If we processed a string that had the address in angle brackets
512          * but no name outside the brackets, we now have an empty name.  In
513          * this case, use the user portion of the address as the name.
514          */
515         if ((IsEmptyStr(name)) && (!IsEmptyStr(user))) {
516                 strcpy(name, user);
517         }
518 }
519
520
521
522 /*
523  * convert_field() is a helper function for convert_internet_message().
524  * Given start/end positions for an rfc822 field, it converts it to a Citadel
525  * field if it wants to, and unfolds it if necessary.
526  *
527  * Returns 1 if the field was converted and inserted into the Citadel message
528  * structure, implying that the source field should be removed from the
529  * message text.
530  */
531 int convert_field(struct CtdlMessage *msg, int beg, int end) {
532         char *rfc822;
533         char *key, *value;
534         int i;
535         int colonpos = (-1);
536         int processed = 0;
537         char buf[SIZ];
538         char user[1024];
539         char node[1024];
540         char name[1024];
541         char addr[1024];
542         time_t parsed_date;
543
544         rfc822 = msg->cm_fields['M'];   /* M field contains rfc822 text */
545         for (i = end; i >= beg; --i) {
546                 if (rfc822[i] == ':') colonpos = i;
547         }
548
549         if (colonpos < 0) return(0);    /* no colon? not a valid header line */
550
551         key = malloc((end - beg) + 2);
552         safestrncpy(key, &rfc822[beg], (end-beg)+1);
553         key[colonpos - beg] = 0;
554         value = &key[(colonpos - beg) + 1];
555         unfold_rfc822_field(value);
556
557         /*
558          * Here's the big rfc822-to-citadel loop.
559          */
560
561         /* Date/time is converted into a unix timestamp.  If the conversion
562          * fails, we replace it with the time the message arrived locally.
563          */
564         if (!strcasecmp(key, "Date")) {
565                 parsed_date = parsedate(value);
566                 if (parsed_date < 0L) parsed_date = time(NULL);
567                 snprintf(buf, sizeof buf, "%ld", (long)parsed_date );
568                 if (msg->cm_fields['T'] == NULL)
569                         msg->cm_fields['T'] = strdup(buf);
570                 processed = 1;
571         }
572
573         else if (!strcasecmp(key, "From")) {
574                 process_rfc822_addr(value, user, node, name);
575                 CtdlLogPrintf(CTDL_DEBUG, "Converted to <%s@%s> (%s)\n", user, node, name);
576                 snprintf(addr, sizeof addr, "%s@%s", user, node);
577                 if (msg->cm_fields['A'] == NULL)
578                         msg->cm_fields['A'] = strdup(name);
579                 processed = 1;
580                 if (msg->cm_fields['F'] == NULL)
581                         msg->cm_fields['F'] = strdup(addr);
582                 processed = 1;
583         }
584
585         else if (!strcasecmp(key, "Subject")) {
586                 if (msg->cm_fields['U'] == NULL)
587                         msg->cm_fields['U'] = 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         CtdlLogPrintf(CTDL_DEBUG, "Dir: %s --> %s\n",
902                 internet_addr, citadel_addr);
903         if (IsDirectory(internet_addr, 0) == 0) return;
904
905         directory_key(key, internet_addr);
906
907         cdb_store(CDB_DIRECTORY, key, strlen(key),
908                 citadel_addr, strlen(citadel_addr)+1 );
909 }
910
911
912 /*
913  * Delete an Internet e-mail address from the directory.
914  *
915  * (NOTE: we don't actually use or need the citadel_addr variable; it's merely
916  * here because the callback API expects to be able to send it.)
917  */
918 void CtdlDirectoryDelUser(char *internet_addr, char *citadel_addr) {
919         char key[SIZ];
920
921         directory_key(key, internet_addr);
922         cdb_delete(CDB_DIRECTORY, key, strlen(key) );
923 }
924
925
926 /*
927  * Look up an Internet e-mail address in the directory.
928  * On success: returns 0, and Citadel address stored in 'target'
929  * On failure: returns nonzero
930  */
931 int CtdlDirectoryLookup(char *target, char *internet_addr, size_t targbuflen) {
932         struct cdbdata *cdbrec;
933         char key[SIZ];
934
935         /* Dump it in there unchanged, just for kicks */
936         safestrncpy(target, internet_addr, targbuflen);
937
938         /* Only do lookups for addresses with hostnames in them */
939         if (num_tokens(internet_addr, '@') != 2) return(-1);
940
941         /* Only do lookups for domains in the directory */
942         if (IsDirectory(internet_addr, 0) == 0) return(-1);
943
944         directory_key(key, internet_addr);
945         cdbrec = cdb_fetch(CDB_DIRECTORY, key, strlen(key) );
946         if (cdbrec != NULL) {
947                 safestrncpy(target, cdbrec->ptr, targbuflen);
948                 cdb_free(cdbrec);
949                 return(0);
950         }
951
952         return(-1);
953 }
954
955
956 /*
957  * Harvest any email addresses that someone might want to have in their
958  * "collected addresses" book.
959  */
960 char *harvest_collected_addresses(struct CtdlMessage *msg) {
961         char *coll = NULL;
962         char addr[256];
963         char user[256], node[256], name[256];
964         int is_harvestable;
965         int i, j, h;
966         int field = 0;
967
968         if (msg == NULL) return(NULL);
969
970         is_harvestable = 1;
971         strcpy(addr, "");       
972         if (msg->cm_fields['A'] != NULL) {
973                 strcat(addr, msg->cm_fields['A']);
974         }
975         if (msg->cm_fields['F'] != NULL) {
976                 strcat(addr, " <");
977                 strcat(addr, msg->cm_fields['F']);
978                 strcat(addr, ">");
979                 if (IsDirectory(msg->cm_fields['F'], 0)) {
980                         is_harvestable = 0;
981                 }
982         }
983
984         if (is_harvestable) {
985                 coll = strdup(addr);
986         }
987         else {
988                 coll = strdup("");
989         }
990
991         if (coll == NULL) return(NULL);
992
993         /* Scan both the R (To) and Y (CC) fields */
994         for (i = 0; i < 2; ++i) {
995                 if (i == 0) field = 'R' ;
996                 if (i == 1) field = 'Y' ;
997
998                 if (msg->cm_fields[field] != NULL) {
999                         for (j=0; j<num_tokens(msg->cm_fields[field], ','); ++j) {
1000                                 extract_token(addr, msg->cm_fields[field], j, ',', sizeof addr);
1001                                 utf8ify_rfc822_string(addr);
1002                                 process_rfc822_addr(addr, user, node, name);
1003                                 h = CtdlHostAlias(node);
1004                                 if ( (h != hostalias_localhost) && (h != hostalias_directory) ) {
1005                                         coll = realloc(coll, strlen(coll) + strlen(addr) + 4);
1006                                         if (coll == NULL) return(NULL);
1007                                         if (!IsEmptyStr(coll)) {
1008                                                 strcat(coll, ",");
1009                                         }
1010                                         striplt(addr);
1011                                         strcat(coll, addr);
1012                                 }
1013                         }
1014                 }
1015         }
1016
1017         if (IsEmptyStr(coll)) {
1018                 free(coll);
1019                 return(NULL);
1020         }
1021         return(coll);
1022 }