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