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