2 * This file contains functions which handle the mapping of Internet addresses
3 * to users on the Citadel system.
15 #include <sys/types.h>
20 #include <libcitadel.h>
23 #include "sysdep_decls.h"
24 #include "citserver.h"
28 #include "internet_addressing.h"
31 #include "parsedate.h"
33 #include "ctdl_module.h"
38 /* This is the non-define version in case of s.b. needing to debug */
39 inline void FindNextEnd (char *bptr, char *end)
41 /* Find the next ?Q? */
42 end = strchr(bptr + 2, '?');
43 if (end == NULL) return NULL;
44 if (((*(end + 1) == 'B') || (*(end + 1) == 'Q')) &&
45 (*(end + 2) == '?')) {
46 /* skip on to the end of the cluster, the next ?= */
47 end = strstr(end + 3, "?=");
50 /* sort of half valid encoding, try to find an end. */
51 end = strstr(bptr, "?=");
55 #define FindNextEnd(bptr, end) { \
56 end = strchr(bptr + 2, '?'); \
58 if (((*(end + 1) == 'B') || (*(end + 1) == 'Q')) && (*(end + 2) == '?')) { \
59 end = strstr(end + 3, "?="); \
60 } else end = strstr(bptr, "?="); \
65 * Handle subjects with RFC2047 encoding such as:
66 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
68 void utf8ify_rfc822_string(char *buf) {
69 char *start, *end, *next, *nextend, *ptr;
74 iconv_t ic = (iconv_t)(-1) ;
75 char *ibuf; /**< Buffer of characters to be converted */
76 char *obuf; /**< Buffer for converted characters */
77 size_t ibuflen; /**< Length of input buffer */
78 size_t obuflen; /**< Length of output buffer */
79 char *isav; /**< Saved pointer to input buffer */
80 char *osav; /**< Saved pointer to output buffer */
83 int illegal_non_rfc2047_encoding = 0;
85 /* Sometimes, badly formed messages contain strings which were simply
86 * written out directly in some foreign character set instead of
87 * using RFC2047 encoding. This is illegal but we will attempt to
88 * handle it anyway by converting from a user-specified default
89 * charset to UTF-8 if we see any nonprintable characters.
92 for (i=0; i<len; ++i) {
93 if ((buf[i] < 32) || (buf[i] > 126)) {
94 illegal_non_rfc2047_encoding = 1;
95 i = len; ///< take a shortcut, it won't be more than one.
98 if (illegal_non_rfc2047_encoding) {
99 const char *default_header_charset = "iso-8859-1";
100 if ( (strcasecmp(default_header_charset, "UTF-8")) && (strcasecmp(default_header_charset, "us-ascii")) ) {
101 ctdl_iconv_open("UTF-8", default_header_charset, &ic);
102 if (ic != (iconv_t)(-1) ) {
105 safestrncpy(ibuf, buf, 1024);
106 ibuflen = strlen(ibuf);
108 obuf = (char *) malloc(obuflen);
110 iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
111 osav[1024-obuflen] = 0;
120 /* pre evaluate the first pair */
121 nextend = end = NULL;
123 start = strstr(buf, "=?");
125 FindNextEnd (start, end);
127 while ((start != NULL) && (end != NULL))
129 next = strstr(end, "=?");
131 FindNextEnd(next, nextend);
135 /* did we find two partitions */
136 if ((next != NULL) &&
140 while ((ptr < next) &&
146 /* did we find a gab just filled with blanks? */
151 len - (next - start));
153 /* now terminate the gab at the end */
154 delta = (next - end) - 2;
158 /* move next to its new location. */
163 /* our next-pair is our new first pair now. */
168 /* Now we handle foreign character sets properly encoded
171 start = strstr(buf, "=?");
172 FindNextEnd((start != NULL)? start : buf, end);
173 while (start != NULL && end != NULL && end > start)
175 extract_token(charset, start, 1, '?', sizeof charset);
176 extract_token(encoding, start, 2, '?', sizeof encoding);
177 extract_token(istr, start, 3, '?', sizeof istr);
181 if (!strcasecmp(encoding, "B")) { /**< base64 */
182 ibuflen = CtdlDecodeBase64(ibuf, istr, strlen(istr));
184 else if (!strcasecmp(encoding, "Q")) { /**< quoted-printable */
192 if (istr[pos] == '_') istr[pos] = ' ';
196 ibuflen = CtdlDecodeQuotedPrintable(ibuf, istr, len);
199 strcpy(ibuf, istr); /**< unknown encoding */
200 ibuflen = strlen(istr);
203 ctdl_iconv_open("UTF-8", charset, &ic);
204 if (ic != (iconv_t)(-1) ) {
206 obuf = (char *) malloc(obuflen);
208 iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
209 osav[1024-obuflen] = 0;
214 remove_token(end, 0, '?');
215 remove_token(end, 0, '?');
216 remove_token(end, 0, '?');
217 remove_token(end, 0, '?');
218 strcpy(end, &end[1]);
220 snprintf(newbuf, sizeof newbuf, "%s%s%s", buf, osav, end);
229 remove_token(end, 0, '?');
230 remove_token(end, 0, '?');
231 remove_token(end, 0, '?');
232 remove_token(end, 0, '?');
233 strcpy(end, &end[1]);
235 snprintf(newbuf, sizeof newbuf, "%s(unreadable)%s", buf, end);
242 * Since spammers will go to all sorts of absurd lengths to get their
243 * messages through, there are LOTS of corrupt headers out there.
244 * So, prevent a really badly formed RFC2047 header from throwing
245 * this function into an infinite loop.
248 if (passes > 20) return;
250 start = strstr(buf, "=?");
251 FindNextEnd((start != NULL)? start : buf, end);
256 inline void utf8ify_rfc822_string(char *a){};
267 char *inetcfg = NULL;
268 struct spamstrings_t *spamstrings = NULL;
272 * Return nonzero if the supplied name is an alias for this host.
274 int CtdlHostAlias(char *fqdn) {
278 char host[256], type[256];
281 if (fqdn == NULL) return(hostalias_nomatch);
282 if (IsEmptyStr(fqdn)) return(hostalias_nomatch);
283 if (!strcasecmp(fqdn, "localhost")) return(hostalias_localhost);
284 if (!strcasecmp(fqdn, config.c_fqdn)) return(hostalias_localhost);
285 if (!strcasecmp(fqdn, config.c_nodename)) return(hostalias_localhost);
286 if (inetcfg == NULL) return(hostalias_nomatch);
288 config_lines = num_tokens(inetcfg, '\n');
289 for (i=0; i<config_lines; ++i) {
290 extract_token(buf, inetcfg, i, '\n', sizeof buf);
291 extract_token(host, buf, 0, '|', sizeof host);
292 extract_token(type, buf, 1, '|', sizeof type);
296 /* Process these in a specific order, in case there are multiple matches.
297 * We want directory to override masq, for example.
300 if ( (!strcasecmp(type, "masqdomain")) && (!strcasecmp(fqdn, host))) {
301 found = hostalias_masq;
303 if ( (!strcasecmp(type, "localhost")) && (!strcasecmp(fqdn, host))) {
304 found = hostalias_localhost;
306 if ( (!strcasecmp(type, "directory")) && (!strcasecmp(fqdn, host))) {
307 found = hostalias_directory;
310 if (found) return(found);
313 return(hostalias_nomatch);
319 * Determine whether a given Internet address belongs to the current user
321 int CtdlIsMe(char *addr, int addr_buf_len)
326 recp = validate_recipients(addr, NULL, 0);
327 if (recp == NULL) return(0);
329 if (recp->num_local == 0) {
330 free_recipients(recp);
334 for (i=0; i<recp->num_local; ++i) {
335 extract_token(addr, recp->recp_local, i, '|', addr_buf_len);
336 if (!strcasecmp(addr, CC->user.fullname)) {
337 free_recipients(recp);
342 free_recipients(recp);
347 /* If the last item in a list of recipients was truncated to a partial address,
348 * remove it completely in order to avoid choking libSieve
350 void sanitize_truncated_recipient(char *str)
353 if (num_tokens(str, ',') < 2) return;
355 int len = strlen(str);
356 if (len < 900) return;
357 if (len > 998) str[998] = 0;
359 char *cptr = strrchr(str, ',');
362 char *lptr = strchr(cptr, '<');
363 char *rptr = strchr(cptr, '>');
365 if ( (lptr) && (rptr) && (rptr > lptr) ) return;
375 * This function is self explanatory.
376 * (What can I say, I'm in a weird mood today...)
378 void remove_any_whitespace_to_the_left_or_right_of_at_symbol(char *name)
382 for (i = 0; i < strlen(name); ++i) {
383 if (name[i] == '@') {
384 while (isspace(name[i - 1]) && i > 0) {
385 strcpy(&name[i - 1], &name[i]);
388 while (isspace(name[i + 1])) {
389 strcpy(&name[i + 1], &name[i + 2]);
397 * Aliasing for network mail.
398 * (Error messages have been commented out, because this is a server.)
400 int alias(char *name)
401 { /* process alias and routing info for mail */
402 struct CitContext *CCC = CC;
405 char aaa[SIZ], bbb[SIZ];
406 char *ignetcfg = NULL;
407 char *ignetmap = NULL;
413 char original_name[256];
414 safestrncpy(original_name, name, sizeof original_name);
417 remove_any_whitespace_to_the_left_or_right_of_at_symbol(name);
418 stripallbut(name, '<', '>');
420 fp = fopen(file_mail_aliases, "r");
422 fp = fopen("/dev/null", "r");
429 while (fgets(aaa, sizeof aaa, fp) != NULL) {
430 while (isspace(name[0]))
431 strcpy(name, &name[1]);
432 aaa[strlen(aaa) - 1] = 0;
434 for (a = 0; a < strlen(aaa); ++a) {
436 strcpy(bbb, &aaa[a + 1]);
440 if (!strcasecmp(name, aaa))
445 /* Hit the Global Address Book */
446 if (CtdlDirectoryLookup(aaa, name, sizeof aaa) == 0) {
450 if (strcasecmp(original_name, name)) {
451 MSG_syslog(LOG_INFO, "%s is being forwarded to %s\n", original_name, name);
454 /* Change "user @ xxx" to "user" if xxx is an alias for this host */
455 for (a=0; a<strlen(name); ++a) {
456 if (name[a] == '@') {
457 if (CtdlHostAlias(&name[a+1]) == hostalias_localhost) {
459 MSG_syslog(LOG_INFO, "Changed to <%s>\n", name);
464 /* determine local or remote type, see citadel.h */
465 at = haschar(name, '@');
466 if (at == 0) return(MES_LOCAL); /* no @'s - local address */
467 if (at > 1) return(MES_ERROR); /* >1 @'s - invalid address */
468 remove_any_whitespace_to_the_left_or_right_of_at_symbol(name);
470 /* figure out the delivery mode */
471 extract_token(node, name, 1, '@', sizeof node);
473 /* If there are one or more dots in the nodename, we assume that it
474 * is an FQDN and will attempt SMTP delivery to the Internet.
476 if (haschar(node, '.') > 0) {
477 return(MES_INTERNET);
480 /* Otherwise we look in the IGnet maps for a valid Citadel node.
481 * Try directly-connected nodes first...
483 ignetcfg = CtdlGetSysConfig(IGNETCFG);
484 for (i=0; i<num_tokens(ignetcfg, '\n'); ++i) {
485 extract_token(buf, ignetcfg, i, '\n', sizeof buf);
486 extract_token(testnode, buf, 0, '|', sizeof testnode);
487 if (!strcasecmp(node, testnode)) {
495 * Then try nodes that are two or more hops away.
497 ignetmap = CtdlGetSysConfig(IGNETMAP);
498 for (i=0; i<num_tokens(ignetmap, '\n'); ++i) {
499 extract_token(buf, ignetmap, i, '\n', sizeof buf);
500 extract_token(testnode, buf, 0, '|', sizeof testnode);
501 if (!strcasecmp(node, testnode)) {
508 /* If we get to this point it's an invalid node name */
515 * Validate recipients, count delivery types and errors, and handle aliasing
516 * FIXME check for dupes!!!!!
518 * Returns 0 if all addresses are ok, ret->num_error = -1 if no addresses
519 * were specified, or the number of addresses found invalid.
521 * Caller needs to free the result using free_recipients()
523 recptypes *validate_recipients(const char *supplied_recipients,
524 const char *RemoteIdentifier,
526 struct CitContext *CCC = CC;
528 char *recipients = NULL;
531 char this_recp_cooked[256];
538 struct ctdluser tempUS;
539 struct ctdlroom tempQR;
540 struct ctdlroom tempQR2;
546 ret = (recptypes *) malloc(sizeof(recptypes));
547 if (ret == NULL) return(NULL);
549 /* Set all strings to null and numeric values to zero */
550 memset(ret, 0, sizeof(recptypes));
552 if (supplied_recipients == NULL) {
553 recipients = strdup("");
556 recipients = strdup(supplied_recipients);
559 /* Allocate some memory. Yes, this allocates 500% more memory than we will
560 * actually need, but it's healthier for the heap than doing lots of tiny
561 * realloc() calls instead.
563 len = strlen(recipients) + 1024;
564 ret->errormsg = malloc(len);
565 ret->recp_local = malloc(len);
566 ret->recp_internet = malloc(len);
567 ret->recp_ignet = malloc(len);
568 ret->recp_room = malloc(len);
569 ret->display_recp = malloc(len);
570 ret->recp_orgroom = malloc(len);
571 org_recp = malloc(len);
573 ret->errormsg[0] = 0;
574 ret->recp_local[0] = 0;
575 ret->recp_internet[0] = 0;
576 ret->recp_ignet[0] = 0;
577 ret->recp_room[0] = 0;
578 ret->recp_orgroom[0] = 0;
579 ret->display_recp[0] = 0;
581 ret->recptypes_magic = RECPTYPES_MAGIC;
583 /* Change all valid separator characters to commas */
584 for (i=0; !IsEmptyStr(&recipients[i]); ++i) {
585 if ((recipients[i] == ';') || (recipients[i] == '|')) {
590 /* Now start extracting recipients... */
592 while (!IsEmptyStr(recipients)) {
593 for (i=0; i<=strlen(recipients); ++i) {
594 if (recipients[i] == '\"') in_quotes = 1 - in_quotes;
595 if ( ( (recipients[i] == ',') && (!in_quotes) ) || (recipients[i] == 0) ) {
596 safestrncpy(this_recp, recipients, i+1);
598 if (recipients[i] == ',') {
599 strcpy(recipients, &recipients[i+1]);
602 strcpy(recipients, "");
609 if (IsEmptyStr(this_recp))
611 MSG_syslog(LOG_DEBUG, "Evaluating recipient #%d: %s\n", num_recps, this_recp);
614 strcpy(org_recp, this_recp);
617 mailtype = alias(this_recp);
619 for (j = 0; !IsEmptyStr(&this_recp[j]); ++j) {
620 if (this_recp[j]=='_') {
621 this_recp_cooked[j] = ' ';
624 this_recp_cooked[j] = this_recp[j];
627 this_recp_cooked[j] = '\0';
632 if (!strcasecmp(this_recp, "sysop")) {
634 strcpy(this_recp, config.c_aideroom);
635 if (!IsEmptyStr(ret->recp_room)) {
636 strcat(ret->recp_room, "|");
638 strcat(ret->recp_room, this_recp);
640 else if ( (!strncasecmp(this_recp, "room_", 5))
641 && (!CtdlGetRoom(&tempQR, &this_recp_cooked[5])) ) {
643 /* Save room so we can restore it later */
647 /* Check permissions to send mail to this room */
648 err = CtdlDoIHavePermissionToPostInThisRoom(
653 0 /* 0 = not a reply */
662 if (!IsEmptyStr(ret->recp_room)) {
663 strcat(ret->recp_room, "|");
665 strcat(ret->recp_room, &this_recp_cooked[5]);
667 if (!IsEmptyStr(ret->recp_orgroom)) {
668 strcat(ret->recp_orgroom, "|");
670 strcat(ret->recp_orgroom, org_recp);
674 /* Restore room in case something needs it */
678 else if (CtdlGetUser(&tempUS, this_recp) == 0) {
680 strcpy(this_recp, tempUS.fullname);
681 if (!IsEmptyStr(ret->recp_local)) {
682 strcat(ret->recp_local, "|");
684 strcat(ret->recp_local, this_recp);
686 else if (CtdlGetUser(&tempUS, this_recp_cooked) == 0) {
688 strcpy(this_recp, tempUS.fullname);
689 if (!IsEmptyStr(ret->recp_local)) {
690 strcat(ret->recp_local, "|");
692 strcat(ret->recp_local, this_recp);
700 /* Yes, you're reading this correctly: if the target
701 * domain points back to the local system or an attached
702 * Citadel directory, the address is invalid. That's
703 * because if the address were valid, we would have
704 * already translated it to a local address by now.
706 if (IsDirectory(this_recp, 0)) {
712 if (!IsEmptyStr(ret->recp_internet)) {
713 strcat(ret->recp_internet, "|");
715 strcat(ret->recp_internet, this_recp);
720 if (!IsEmptyStr(ret->recp_ignet)) {
721 strcat(ret->recp_ignet, "|");
723 strcat(ret->recp_ignet, this_recp);
731 if (IsEmptyStr(errmsg)) {
732 snprintf(append, sizeof append, "Invalid recipient: %s", this_recp);
735 snprintf(append, sizeof append, "%s", errmsg);
737 if ( (strlen(ret->errormsg) + strlen(append) + 3) < SIZ) {
738 if (!IsEmptyStr(ret->errormsg)) {
739 strcat(ret->errormsg, "; ");
741 strcat(ret->errormsg, append);
745 if (IsEmptyStr(ret->display_recp)) {
746 strcpy(append, this_recp);
749 snprintf(append, sizeof append, ", %s", this_recp);
751 if ( (strlen(ret->display_recp)+strlen(append)) < SIZ) {
752 strcat(ret->display_recp, append);
758 if ((ret->num_local + ret->num_internet + ret->num_ignet +
759 ret->num_room + ret->num_error) == 0) {
760 ret->num_error = (-1);
761 strcpy(ret->errormsg, "No recipients specified.");
764 MSGM_syslog(LOG_DEBUG, "validate_recipients()\n");
765 MSG_syslog(LOG_DEBUG, " local: %d <%s>\n", ret->num_local, ret->recp_local);
766 MSG_syslog(LOG_DEBUG, " room: %d <%s>\n", ret->num_room, ret->recp_room);
767 MSG_syslog(LOG_DEBUG, " inet: %d <%s>\n", ret->num_internet, ret->recp_internet);
768 MSG_syslog(LOG_DEBUG, " ignet: %d <%s>\n", ret->num_ignet, ret->recp_ignet);
769 MSG_syslog(LOG_DEBUG, " error: %d <%s>\n", ret->num_error, ret->errormsg);
777 * Destructor for recptypes
779 void free_recipients(recptypes *valid) {
785 if (valid->recptypes_magic != RECPTYPES_MAGIC) {
786 struct CitContext *CCC = CC;
787 MSGM_syslog(LOG_EMERG, "Attempt to call free_recipients() on some other data type!\n");
791 if (valid->errormsg != NULL) free(valid->errormsg);
792 if (valid->recp_local != NULL) free(valid->recp_local);
793 if (valid->recp_internet != NULL) free(valid->recp_internet);
794 if (valid->recp_ignet != NULL) free(valid->recp_ignet);
795 if (valid->recp_room != NULL) free(valid->recp_room);
796 if (valid->recp_orgroom != NULL) free(valid->recp_orgroom);
797 if (valid->display_recp != NULL) free(valid->display_recp);
798 if (valid->bounce_to != NULL) free(valid->bounce_to);
799 if (valid->envelope_from != NULL) free(valid->envelope_from);
800 if (valid->sending_room != NULL) free(valid->sending_room);
805 char *qp_encode_email_addrs(char *source)
807 struct CitContext *CCC = CC;
808 char *user, *node, *name;
809 const char headerStr[] = "=?UTF-8?Q?";
813 int need_to_encode = 0;
819 long nAddrPtrMax = 50;
824 if (source == NULL) return source;
825 if (IsEmptyStr(source)) return source;
826 if (MessageDebugEnabled != 0) cit_backtrace();
827 MSG_syslog(LOG_DEBUG, "qp_encode_email_addrs: [%s]\n", source);
829 AddrPtr = malloc (sizeof (long) * nAddrPtrMax);
830 AddrUtf8 = malloc (sizeof (long) * nAddrPtrMax);
831 memset(AddrUtf8, 0, sizeof (long) * nAddrPtrMax);
834 while (!IsEmptyStr (&source[i])) {
835 if (nColons >= nAddrPtrMax){
838 ptr = (long *) malloc(sizeof (long) * nAddrPtrMax * 2);
839 memcpy (ptr, AddrPtr, sizeof (long) * nAddrPtrMax);
840 free (AddrPtr), AddrPtr = ptr;
842 ptr = (long *) malloc(sizeof (long) * nAddrPtrMax * 2);
843 memset(&ptr[nAddrPtrMax], 0,
844 sizeof (long) * nAddrPtrMax);
846 memcpy (ptr, AddrUtf8, sizeof (long) * nAddrPtrMax);
847 free (AddrUtf8), AddrUtf8 = ptr;
850 if (((unsigned char) source[i] < 32) ||
851 ((unsigned char) source[i] > 126)) {
853 AddrUtf8[nColons] = 1;
855 if (source[i] == '"')
856 InQuotes = !InQuotes;
857 if (!InQuotes && source[i] == ',') {
858 AddrPtr[nColons] = i;
863 if (need_to_encode == 0) {
870 EncodedMaxLen = nColons * (sizeof(headerStr) + 3) + SourceLen * 3;
871 Encoded = (char*) malloc (EncodedMaxLen);
873 for (i = 0; i < nColons; i++)
874 source[AddrPtr[i]++] = '\0';
875 /* TODO: if libidn, this might get larger*/
876 user = malloc(SourceLen + 1);
877 node = malloc(SourceLen + 1);
878 name = malloc(SourceLen + 1);
882 for (i = 0; i < nColons && nPtr != NULL; i++) {
883 nmax = EncodedMaxLen - (nPtr - Encoded);
885 process_rfc822_addr(&source[AddrPtr[i]],
889 /* TODO: libIDN here ! */
890 if (IsEmptyStr(name)) {
891 n = snprintf(nPtr, nmax,
892 (i==0)?"%s@%s" : ",%s@%s",
896 EncodedName = rfc2047encode(name, strlen(name));
897 n = snprintf(nPtr, nmax,
898 (i==0)?"%s <%s@%s>" : ",%s <%s@%s>",
899 EncodedName, user, node);
904 n = snprintf(nPtr, nmax,
906 &source[AddrPtr[i]]);
912 ptr = (char*) malloc(EncodedMaxLen * 2);
913 memcpy(ptr, Encoded, EncodedMaxLen);
914 nnPtr = ptr + (nPtr - Encoded), nPtr = nnPtr;
915 free(Encoded), Encoded = ptr;
917 i--; /* do it once more with properly lengthened buffer */
920 for (i = 0; i < nColons; i++)
921 source[--AddrPtr[i]] = ',';
933 * Return 0 if a given string fuzzy-matches a Citadel user account
935 * FIXME ... this needs to be updated to handle aliases.
937 int fuzzy_match(struct ctdluser *us, char *matchstring) {
941 if ( (!strncasecmp(matchstring, "cit", 3))
942 && (atol(&matchstring[3]) == us->usernum)) {
946 len = strlen(matchstring);
947 for (a=0; !IsEmptyStr(&us->fullname[a]); ++a) {
948 if (!strncasecmp(&us->fullname[a],
958 * Unfold a multi-line field into a single line, removing multi-whitespaces
960 void unfold_rfc822_field(char **field, char **FieldEnd)
963 char *pField = *field;
965 char *pFieldEnd = *FieldEnd;
967 while (isspace(*pField))
969 /* remove leading/trailing whitespace */
972 while (isspace(*pFieldEnd))
975 *FieldEnd = pFieldEnd;
976 /* convert non-space whitespace to spaces, and remove double blanks */
977 for (sField = *field = pField;
981 if ((*sField=='\r') || (*sField=='\n'))
984 while (((*(sField + Offset) == '\r') ||
985 (*(sField + Offset) == '\n') ||
986 (isspace(*(sField + Offset)))) &&
987 (sField + Offset < pFieldEnd))
993 if (*sField=='\"') quote = 1 - quote;
995 if (isspace(*sField))
1001 while ((sField < pFieldEnd) &&
1006 else *pField = *sField;
1008 else *pField = *sField;
1012 *FieldEnd = pField - 1;
1018 * Split an RFC822-style address into userid, host, and full name
1021 void process_rfc822_addr(const char *rfc822, char *user, char *node, char *name)
1026 strcpy(node, config.c_fqdn);
1029 if (rfc822 == NULL) return;
1031 /* extract full name - first, it's From minus <userid> */
1032 strcpy(name, rfc822);
1033 stripout(name, '<', '>');
1035 /* strip anything to the left of a bang */
1036 while ((!IsEmptyStr(name)) && (haschar(name, '!') > 0))
1037 strcpy(name, &name[1]);
1039 /* and anything to the right of a @ or % */
1040 for (a = 0; a < strlen(name); ++a) {
1047 /* but if there are parentheses, that changes the rules... */
1048 if ((haschar(rfc822, '(') == 1) && (haschar(rfc822, ')') == 1)) {
1049 strcpy(name, rfc822);
1050 stripallbut(name, '(', ')');
1053 /* but if there are a set of quotes, that supersedes everything */
1054 if (haschar(rfc822, 34) == 2) {
1055 strcpy(name, rfc822);
1056 while ((!IsEmptyStr(name)) && (name[0] != 34)) {
1057 strcpy(&name[0], &name[1]);
1059 strcpy(&name[0], &name[1]);
1060 for (a = 0; a < strlen(name); ++a)
1064 /* extract user id */
1065 strcpy(user, rfc822);
1067 /* first get rid of anything in parens */
1068 stripout(user, '(', ')');
1070 /* if there's a set of angle brackets, strip it down to that */
1071 if ((haschar(user, '<') == 1) && (haschar(user, '>') == 1)) {
1072 stripallbut(user, '<', '>');
1075 /* strip anything to the left of a bang */
1076 while ((!IsEmptyStr(user)) && (haschar(user, '!') > 0))
1077 strcpy(user, &user[1]);
1079 /* and anything to the right of a @ or % */
1080 for (a = 0; a < strlen(user); ++a) {
1088 /* extract node name */
1089 strcpy(node, rfc822);
1091 /* first get rid of anything in parens */
1092 stripout(node, '(', ')');
1094 /* if there's a set of angle brackets, strip it down to that */
1095 if ((haschar(node, '<') == 1) && (haschar(node, '>') == 1)) {
1096 stripallbut(node, '<', '>');
1099 /* If no node specified, tack ours on instead */
1101 (haschar(node, '@')==0)
1102 && (haschar(node, '%')==0)
1103 && (haschar(node, '!')==0)
1105 strcpy(node, config.c_nodename);
1110 /* strip anything to the left of a @ */
1111 while ((!IsEmptyStr(node)) && (haschar(node, '@') > 0))
1112 strcpy(node, &node[1]);
1114 /* strip anything to the left of a % */
1115 while ((!IsEmptyStr(node)) && (haschar(node, '%') > 0))
1116 strcpy(node, &node[1]);
1118 /* reduce multiple system bang paths to node!user */
1119 while ((!IsEmptyStr(node)) && (haschar(node, '!') > 1))
1120 strcpy(node, &node[1]);
1122 /* now get rid of the user portion of a node!user string */
1123 for (a = 0; a < strlen(node); ++a)
1128 /* strip leading and trailing spaces in all strings */
1133 /* If we processed a string that had the address in angle brackets
1134 * but no name outside the brackets, we now have an empty name. In
1135 * this case, use the user portion of the address as the name.
1137 if ((IsEmptyStr(name)) && (!IsEmptyStr(user))) {
1145 * convert_field() is a helper function for convert_internet_message().
1146 * Given start/end positions for an rfc822 field, it converts it to a Citadel
1147 * field if it wants to, and unfolds it if necessary.
1149 * Returns 1 if the field was converted and inserted into the Citadel message
1150 * structure, implying that the source field should be removed from the
1153 int convert_field(struct CtdlMessage *msg, const char *beg, const char *end) {
1154 char *key, *value, *valueend;
1158 const char *colonpos = NULL;
1167 for (pos = end; pos >= beg; pos--) {
1168 if (*pos == ':') colonpos = pos;
1171 if (colonpos == NULL) return(0); /* no colon? not a valid header line */
1174 key = malloc(len + 2);
1175 memcpy(key, beg, len + 1);
1177 valueend = key + len;
1178 * ( key + (colonpos - beg) ) = '\0';
1179 value = &key[(colonpos - beg) + 1];
1180 /* printf("Header: [%s]\nValue: [%s]\n", key, value); */
1181 unfold_rfc822_field(&value, &valueend);
1182 valuelen = valueend - value + 1;
1183 /* printf("UnfoldedValue: [%s]\n", value); */
1186 * Here's the big rfc822-to-citadel loop.
1189 /* Date/time is converted into a unix timestamp. If the conversion
1190 * fails, we replace it with the time the message arrived locally.
1192 if (!strcasecmp(key, "Date")) {
1193 parsed_date = parsedate(value);
1194 if (parsed_date < 0L) parsed_date = time(NULL);
1196 if (CM_IsEmpty(msg, eTimestamp))
1197 CM_SetFieldLONG(msg, eTimestamp, parsed_date);
1201 else if (!strcasecmp(key, "From")) {
1202 process_rfc822_addr(value, user, node, name);
1203 syslog(LOG_DEBUG, "Converted to <%s@%s> (%s)\n", user, node, name);
1204 snprintf(addr, sizeof(addr), "%s@%s", user, node);
1205 if (CM_IsEmpty(msg, eAuthor))
1206 CM_SetField(msg, eAuthor, name, strlen(name));
1207 if (CM_IsEmpty(msg, erFc822Addr))
1208 CM_SetField(msg, erFc822Addr, addr, strlen(addr));
1212 else if (!strcasecmp(key, "Subject")) {
1213 if (CM_IsEmpty(msg, eMsgSubject))
1214 CM_SetField(msg, eMsgSubject, value, valuelen);
1218 else if (!strcasecmp(key, "List-ID")) {
1219 if (CM_IsEmpty(msg, eListID))
1220 CM_SetField(msg, eListID, value, valuelen);
1224 else if (!strcasecmp(key, "To")) {
1225 if (CM_IsEmpty(msg, eRecipient))
1226 CM_SetField(msg, eRecipient, value, valuelen);
1230 else if (!strcasecmp(key, "CC")) {
1231 if (CM_IsEmpty(msg, eCarbonCopY))
1232 CM_SetField(msg, eCarbonCopY, value, valuelen);
1236 else if (!strcasecmp(key, "Message-ID")) {
1237 if (!CM_IsEmpty(msg, emessageId)) {
1238 syslog(LOG_WARNING, "duplicate message id\n");
1245 pValueLen = valuelen;
1246 /* Strip angle brackets */
1247 while (haschar(pValue, '<') > 0) {
1252 for (i = 0; i <= pValueLen; ++i)
1253 if (pValue[i] == '>') {
1258 CM_SetField(msg, emessageId, pValue, pValueLen);
1264 else if (!strcasecmp(key, "Return-Path")) {
1265 if (CM_IsEmpty(msg, eMessagePath))
1266 CM_SetField(msg, eMessagePath, value, valuelen);
1270 else if (!strcasecmp(key, "Envelope-To")) {
1271 if (CM_IsEmpty(msg, eenVelopeTo))
1272 CM_SetField(msg, eenVelopeTo, value, valuelen);
1276 else if (!strcasecmp(key, "References")) {
1277 CM_SetField(msg, eWeferences, value, valuelen);
1281 else if (!strcasecmp(key, "Reply-To")) {
1282 CM_SetField(msg, eReplyTo, value, valuelen);
1286 else if (!strcasecmp(key, "In-reply-to")) {
1287 if (CM_IsEmpty(msg, eWeferences)) /* References: supersedes In-reply-to: */
1288 CM_SetField(msg, eWeferences, value, valuelen);
1294 /* Clean up and move on. */
1295 free(key); /* Don't free 'value', it's actually the same buffer */
1301 * Convert RFC822 references format (References) to Citadel references format (Weferences)
1303 void convert_references_to_wefewences(char *str) {
1304 int bracket_nesting = 0;
1306 char *moveptr = NULL;
1313 if (bracket_nesting < 0) bracket_nesting = 0;
1315 if ((ch == '>') && (bracket_nesting == 0) && (*(ptr+1)) && (ptr>str) ) {
1319 else if (bracket_nesting > 0) {
1325 *moveptr = *(moveptr+1);
1329 if (ch == '<') ++bracket_nesting;
1336 * Convert an RFC822 message (headers + body) to a CtdlMessage structure.
1337 * NOTE: the supplied buffer becomes part of the CtdlMessage structure, and
1338 * will be deallocated when CM_Free() is called. Therefore, the
1339 * supplied buffer should be DEREFERENCED. It should not be freed or used
1342 struct CtdlMessage *convert_internet_message(char *rfc822) {
1343 StrBuf *RFCBuf = NewStrBufPlain(rfc822, -1);
1345 return convert_internet_message_buf(&RFCBuf);
1350 struct CtdlMessage *convert_internet_message_buf(StrBuf **rfc822)
1352 struct CtdlMessage *msg;
1353 const char *pos, *beg, *end, *totalend;
1354 int done, alldone = 0;
1356 StrBuf *OtherHeaders;
1358 msg = malloc(sizeof(struct CtdlMessage));
1359 if (msg == NULL) return msg;
1361 memset(msg, 0, sizeof(struct CtdlMessage));
1362 msg->cm_magic = CTDLMESSAGE_MAGIC; /* self check */
1363 msg->cm_anon_type = 0; /* never anonymous */
1364 msg->cm_format_type = FMT_RFC822; /* internet message */
1366 pos = ChrPtr(*rfc822);
1367 totalend = pos + StrLength(*rfc822);
1369 OtherHeaders = NewStrBufPlain(NULL, StrLength(*rfc822));
1373 /* Locate beginning and end of field, keeping in mind that
1374 * some fields might be multiline
1378 while ((end < totalend) &&
1383 if ( (*pos=='\n') && ((*(pos+1))!=0x20) && ((*(pos+1))!=0x09) )
1388 /* done with headers? */
1390 ( (*(pos+1)=='\n') ||
1396 if (pos >= (totalend - 1) )
1406 /* At this point we have a field. Are we interested in it? */
1407 converted = convert_field(msg, beg, end);
1409 /* Strip the field out of the RFC822 header if we used it */
1411 StrBufAppendBufPlain(OtherHeaders, beg, end - beg, 0);
1412 StrBufAppendBufPlain(OtherHeaders, HKEY("\n"), 0);
1415 /* If we've hit the end of the message, bail out */
1416 if (pos >= totalend)
1419 StrBufAppendBufPlain(OtherHeaders, HKEY("\n"), 0);
1421 StrBufAppendBufPlain(OtherHeaders, pos, totalend - pos, 0);
1423 CM_SetAsFieldSB(msg, eMesageText, &OtherHeaders);
1425 /* Follow-up sanity checks... */
1427 /* If there's no timestamp on this message, set it to now. */
1428 if (CM_IsEmpty(msg, eTimestamp)) {
1429 CM_SetFieldLONG(msg, eTimestamp, time(NULL));
1432 /* If a W (references, or rather, Wefewences) field is present, we
1433 * have to convert it from RFC822 format to Citadel format.
1435 if (!CM_IsEmpty(msg, eWeferences)) {
1437 convert_references_to_wefewences(msg->cm_fields[eWeferences]);
1446 * Look for a particular header field in an RFC822 message text. If the
1447 * requested field is found, it is unfolded (if necessary) and returned to
1448 * the caller. The field name is stripped out, leaving only its contents.
1449 * The caller is responsible for freeing the returned buffer. If the requested
1450 * field is not present, or anything else goes wrong, it returns NULL.
1452 char *rfc822_fetch_field(const char *rfc822, const char *fieldname) {
1453 char *fieldbuf = NULL;
1454 const char *end_of_headers;
1455 const char *field_start;
1460 /* Should never happen, but sometimes we get stupid */
1461 if (rfc822 == NULL) return(NULL);
1462 if (fieldname == NULL) return(NULL);
1464 snprintf(fieldhdr, sizeof fieldhdr, "%s:", fieldname);
1466 /* Locate the end of the headers, so we don't run past that point */
1467 end_of_headers = cbmstrcasestr(rfc822, "\n\r\n");
1468 if (end_of_headers == NULL) {
1469 end_of_headers = cbmstrcasestr(rfc822, "\n\n");
1471 if (end_of_headers == NULL) return (NULL);
1473 field_start = cbmstrcasestr(rfc822, fieldhdr);
1474 if (field_start == NULL) return(NULL);
1475 if (field_start > end_of_headers) return(NULL);
1477 fieldbuf = malloc(SIZ);
1478 strcpy(fieldbuf, "");
1481 ptr = cmemreadline(ptr, fieldbuf, SIZ-strlen(fieldbuf) );
1482 while ( (isspace(ptr[0])) && (ptr < end_of_headers) ) {
1483 strcat(fieldbuf, " ");
1484 cont = &fieldbuf[strlen(fieldbuf)];
1485 ptr = cmemreadline(ptr, cont, SIZ-strlen(fieldbuf) );
1489 strcpy(fieldbuf, &fieldbuf[strlen(fieldhdr)]);
1497 /*****************************************************************************
1498 * DIRECTORY MANAGEMENT FUNCTIONS *
1499 *****************************************************************************/
1502 * Generate the index key for an Internet e-mail address to be looked up
1505 void directory_key(char *key, char *addr) {
1509 for (i=0; !IsEmptyStr(&addr[i]); ++i) {
1510 if (!isspace(addr[i])) {
1511 key[keylen++] = tolower(addr[i]);
1516 syslog(LOG_DEBUG, "Directory key is <%s>\n", key);
1521 /* Return nonzero if the supplied address is in a domain we keep in
1524 int IsDirectory(char *addr, int allow_masq_domains) {
1528 extract_token(domain, addr, 1, '@', sizeof domain);
1531 h = CtdlHostAlias(domain);
1533 if ( (h == hostalias_masq) && allow_masq_domains)
1536 if ( (h == hostalias_localhost) || (h == hostalias_directory) ) {
1546 * Initialize the directory database (erasing anything already there)
1548 void CtdlDirectoryInit(void) {
1549 cdb_trunc(CDB_DIRECTORY);
1554 * Add an Internet e-mail address to the directory for a user
1556 int CtdlDirectoryAddUser(char *internet_addr, char *citadel_addr) {
1559 if (IsDirectory(internet_addr, 0) == 0)
1561 syslog(LOG_DEBUG, "Create directory entry: %s --> %s\n", internet_addr, citadel_addr);
1562 directory_key(key, internet_addr);
1563 cdb_store(CDB_DIRECTORY, key, strlen(key), citadel_addr, strlen(citadel_addr)+1 );
1569 * Delete an Internet e-mail address from the directory.
1571 * (NOTE: we don't actually use or need the citadel_addr variable; it's merely
1572 * here because the callback API expects to be able to send it.)
1574 int CtdlDirectoryDelUser(char *internet_addr, char *citadel_addr) {
1577 syslog(LOG_DEBUG, "Delete directory entry: %s --> %s\n", internet_addr, citadel_addr);
1578 directory_key(key, internet_addr);
1579 return cdb_delete(CDB_DIRECTORY, key, strlen(key) ) == 0;
1584 * Look up an Internet e-mail address in the directory.
1585 * On success: returns 0, and Citadel address stored in 'target'
1586 * On failure: returns nonzero
1588 int CtdlDirectoryLookup(char *target, char *internet_addr, size_t targbuflen) {
1589 struct cdbdata *cdbrec;
1592 /* Dump it in there unchanged, just for kicks */
1593 safestrncpy(target, internet_addr, targbuflen);
1595 /* Only do lookups for addresses with hostnames in them */
1596 if (num_tokens(internet_addr, '@') != 2) return(-1);
1598 /* Only do lookups for domains in the directory */
1599 if (IsDirectory(internet_addr, 0) == 0) return(-1);
1601 directory_key(key, internet_addr);
1602 cdbrec = cdb_fetch(CDB_DIRECTORY, key, strlen(key) );
1603 if (cdbrec != NULL) {
1604 safestrncpy(target, cdbrec->ptr, targbuflen);
1614 * Harvest any email addresses that someone might want to have in their
1615 * "collected addresses" book.
1617 char *harvest_collected_addresses(struct CtdlMessage *msg) {
1620 char user[256], node[256], name[256];
1623 eMsgField field = 0;
1625 if (msg == NULL) return(NULL);
1629 if (!CM_IsEmpty(msg, eAuthor)) {
1630 strcat(addr, msg->cm_fields[eAuthor]);
1632 if (!CM_IsEmpty(msg, erFc822Addr)) {
1634 strcat(addr, msg->cm_fields[erFc822Addr]);
1636 if (IsDirectory(msg->cm_fields[erFc822Addr], 0)) {
1641 if (is_harvestable) {
1642 coll = strdup(addr);
1648 if (coll == NULL) return(NULL);
1650 /* Scan both the R (To) and Y (CC) fields */
1651 for (i = 0; i < 2; ++i) {
1652 if (i == 0) field = eRecipient;
1653 if (i == 1) field = eCarbonCopY;
1655 if (!CM_IsEmpty(msg, field)) {
1656 for (j=0; j<num_tokens(msg->cm_fields[field], ','); ++j) {
1657 extract_token(addr, msg->cm_fields[field], j, ',', sizeof addr);
1658 if (strstr(addr, "=?") != NULL)
1659 utf8ify_rfc822_string(addr);
1660 process_rfc822_addr(addr, user, node, name);
1661 h = CtdlHostAlias(node);
1662 if ( (h != hostalias_localhost) && (h != hostalias_directory) ) {
1663 coll = realloc(coll, strlen(coll) + strlen(addr) + 4);
1664 if (coll == NULL) return(NULL);
1665 if (!IsEmptyStr(coll)) {
1675 if (IsEmptyStr(coll)) {