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