2 * This file contains functions which handle the mapping of Internet addresses
3 * to users on the Citadel system.
15 #include <sys/types.h>
17 #if TIME_WITH_SYS_TIME
18 # include <sys/time.h>
22 # include <sys/time.h>
31 #include <libcitadel.h>
34 #include "sysdep_decls.h"
35 #include "citserver.h"
39 #include "internet_addressing.h"
42 #include "parsedate.h"
44 #include "ctdl_module.h"
49 /* This is the non-define version in case of s.b. needing to debug */
50 inline void FindNextEnd (char *bptr, char *end)
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, "?=");
61 /* sort of half valid encoding, try to find an end. */
62 end = strstr(bptr, "?=");
66 #define FindNextEnd(bptr, end) { \
67 end = strchr(bptr + 2, '?'); \
69 if (((*(end + 1) == 'B') || (*(end + 1) == 'Q')) && (*(end + 2) == '?')) { \
70 end = strstr(end + 3, "?="); \
71 } else end = strstr(bptr, "?="); \
76 * Handle subjects with RFC2047 encoding such as:
77 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
79 void utf8ify_rfc822_string(char *buf) {
80 char *start, *end, *next, *nextend, *ptr;
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 */
94 int illegal_non_rfc2047_encoding = 0;
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.
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.
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) ) {
116 safestrncpy(ibuf, buf, 1024);
117 ibuflen = strlen(ibuf);
119 obuf = (char *) malloc(obuflen);
121 iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
122 osav[1024-obuflen] = 0;
131 /* pre evaluate the first pair */
132 nextend = end = NULL;
134 start = strstr(buf, "=?");
136 FindNextEnd (start, end);
138 while ((start != NULL) && (end != NULL))
140 next = strstr(end, "=?");
142 FindNextEnd(next, nextend);
146 /* did we find two partitions */
147 if ((next != NULL) &&
151 while ((ptr < next) &&
157 /* did we find a gab just filled with blanks? */
162 len - (next - start));
164 /* now terminate the gab at the end */
165 delta = (next - end) - 2;
169 /* move next to its new location. */
174 /* our next-pair is our new first pair now. */
179 /* Now we handle foreign character sets properly encoded
182 start = strstr(buf, "=?");
183 FindNextEnd((start != NULL)? start : buf, end);
184 while (start != NULL && end != NULL && end > start)
186 extract_token(charset, start, 1, '?', sizeof charset);
187 extract_token(encoding, start, 2, '?', sizeof encoding);
188 extract_token(istr, start, 3, '?', sizeof istr);
192 if (!strcasecmp(encoding, "B")) { /**< base64 */
193 ibuflen = CtdlDecodeBase64(ibuf, istr, strlen(istr));
195 else if (!strcasecmp(encoding, "Q")) { /**< quoted-printable */
203 if (istr[pos] == '_') istr[pos] = ' ';
207 ibuflen = CtdlDecodeQuotedPrintable(ibuf, istr, len);
210 strcpy(ibuf, istr); /**< unknown encoding */
211 ibuflen = strlen(istr);
214 ctdl_iconv_open("UTF-8", charset, &ic);
215 if (ic != (iconv_t)(-1) ) {
217 obuf = (char *) malloc(obuflen);
219 iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
220 osav[1024-obuflen] = 0;
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]);
231 snprintf(newbuf, sizeof newbuf, "%s%s%s", buf, osav, end);
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]);
246 snprintf(newbuf, sizeof newbuf, "%s(unreadable)%s", buf, end);
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.
259 if (passes > 20) return;
261 start = strstr(buf, "=?");
262 FindNextEnd((start != NULL)? start : buf, end);
267 inline void utf8ify_rfc822_string(char *a){};
278 char *inetcfg = NULL;
279 struct spamstrings_t *spamstrings = NULL;
283 * Return nonzero if the supplied name is an alias for this host.
285 int CtdlHostAlias(char *fqdn) {
289 char host[256], type[256];
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);
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);
307 /* Process these in a specific order, in case there are multiple matches.
308 * We want directory to override masq, for example.
311 if ( (!strcasecmp(type, "masqdomain")) && (!strcasecmp(fqdn, host))) {
312 found = hostalias_masq;
314 if ( (!strcasecmp(type, "localhost")) && (!strcasecmp(fqdn, host))) {
315 found = hostalias_localhost;
317 if ( (!strcasecmp(type, "directory")) && (!strcasecmp(fqdn, host))) {
318 found = hostalias_directory;
321 if (found) return(found);
324 return(hostalias_nomatch);
330 * Determine whether a given Internet address belongs to the current user
332 int CtdlIsMe(char *addr, int addr_buf_len)
334 struct recptypes *recp;
337 recp = validate_recipients(addr, NULL, 0);
338 if (recp == NULL) return(0);
340 if (recp->num_local == 0) {
341 free_recipients(recp);
345 for (i=0; i<recp->num_local; ++i) {
346 extract_token(addr, recp->recp_local, i, '|', addr_buf_len);
347 if (!strcasecmp(addr, CC->user.fullname)) {
348 free_recipients(recp);
353 free_recipients(recp);
359 * Citadel protocol command to do the same
361 void cmd_isme(char *argbuf) {
364 if (CtdlAccessCheck(ac_logged_in)) return;
365 extract_token(addr, argbuf, 0, '|', sizeof addr);
367 if (CtdlIsMe(addr, sizeof addr)) {
368 cprintf("%d %s\n", CIT_OK, addr);
371 cprintf("%d Not you.\n", ERROR + ILLEGAL_VALUE);
377 /* If the last item in a list of recipients was truncated to a partial address,
378 * remove it completely in order to avoid choking libSieve
380 void sanitize_truncated_recipient(char *str)
383 if (num_tokens(str, ',') < 2) return;
385 int len = strlen(str);
386 if (len < 900) return;
387 if (len > 998) str[998] = 0;
389 char *cptr = strrchr(str, ',');
392 char *lptr = strchr(cptr, '<');
393 char *rptr = strchr(cptr, '>');
395 if ( (lptr) && (rptr) && (rptr > lptr) ) return;
405 * This function is self explanatory.
406 * (What can I say, I'm in a weird mood today...)
408 void remove_any_whitespace_to_the_left_or_right_of_at_symbol(char *name)
412 for (i = 0; i < strlen(name); ++i) {
413 if (name[i] == '@') {
414 while (isspace(name[i - 1]) && i > 0) {
415 strcpy(&name[i - 1], &name[i]);
418 while (isspace(name[i + 1])) {
419 strcpy(&name[i + 1], &name[i + 2]);
427 * Aliasing for network mail.
428 * (Error messages have been commented out, because this is a server.)
430 int alias(char *name)
431 { /* process alias and routing info for mail */
432 struct CitContext *CCC = CC;
435 char aaa[SIZ], bbb[SIZ];
436 char *ignetcfg = NULL;
437 char *ignetmap = NULL;
443 char original_name[256];
444 safestrncpy(original_name, name, sizeof original_name);
447 remove_any_whitespace_to_the_left_or_right_of_at_symbol(name);
448 stripallbut(name, '<', '>');
450 fp = fopen(file_mail_aliases, "r");
452 fp = fopen("/dev/null", "r");
459 while (fgets(aaa, sizeof aaa, fp) != NULL) {
460 while (isspace(name[0]))
461 strcpy(name, &name[1]);
462 aaa[strlen(aaa) - 1] = 0;
464 for (a = 0; a < strlen(aaa); ++a) {
466 strcpy(bbb, &aaa[a + 1]);
470 if (!strcasecmp(name, aaa))
475 /* Hit the Global Address Book */
476 if (CtdlDirectoryLookup(aaa, name, sizeof aaa) == 0) {
480 if (strcasecmp(original_name, name)) {
481 MSG_syslog(LOG_INFO, "%s is being forwarded to %s\n", original_name, name);
484 /* Change "user @ xxx" to "user" if xxx is an alias for this host */
485 for (a=0; a<strlen(name); ++a) {
486 if (name[a] == '@') {
487 if (CtdlHostAlias(&name[a+1]) == hostalias_localhost) {
489 MSG_syslog(LOG_INFO, "Changed to <%s>\n", name);
494 /* determine local or remote type, see citadel.h */
495 at = haschar(name, '@');
496 if (at == 0) return(MES_LOCAL); /* no @'s - local address */
497 if (at > 1) return(MES_ERROR); /* >1 @'s - invalid address */
498 remove_any_whitespace_to_the_left_or_right_of_at_symbol(name);
500 /* figure out the delivery mode */
501 extract_token(node, name, 1, '@', sizeof node);
503 /* If there are one or more dots in the nodename, we assume that it
504 * is an FQDN and will attempt SMTP delivery to the Internet.
506 if (haschar(node, '.') > 0) {
507 return(MES_INTERNET);
510 /* Otherwise we look in the IGnet maps for a valid Citadel node.
511 * Try directly-connected nodes first...
513 ignetcfg = CtdlGetSysConfig(IGNETCFG);
514 for (i=0; i<num_tokens(ignetcfg, '\n'); ++i) {
515 extract_token(buf, ignetcfg, i, '\n', sizeof buf);
516 extract_token(testnode, buf, 0, '|', sizeof testnode);
517 if (!strcasecmp(node, testnode)) {
525 * Then try nodes that are two or more hops away.
527 ignetmap = CtdlGetSysConfig(IGNETMAP);
528 for (i=0; i<num_tokens(ignetmap, '\n'); ++i) {
529 extract_token(buf, ignetmap, i, '\n', sizeof buf);
530 extract_token(testnode, buf, 0, '|', sizeof testnode);
531 if (!strcasecmp(node, testnode)) {
538 /* If we get to this point it's an invalid node name */
545 * Validate recipients, count delivery types and errors, and handle aliasing
546 * FIXME check for dupes!!!!!
548 * Returns 0 if all addresses are ok, ret->num_error = -1 if no addresses
549 * were specified, or the number of addresses found invalid.
551 * Caller needs to free the result using free_recipients()
553 struct recptypes *validate_recipients(const char *supplied_recipients,
554 const char *RemoteIdentifier,
556 struct CitContext *CCC = CC;
557 struct recptypes *ret;
558 char *recipients = NULL;
561 char this_recp_cooked[256];
568 struct ctdluser tempUS;
569 struct ctdlroom tempQR;
570 struct ctdlroom tempQR2;
576 ret = (struct recptypes *) malloc(sizeof(struct recptypes));
577 if (ret == NULL) return(NULL);
579 /* Set all strings to null and numeric values to zero */
580 memset(ret, 0, sizeof(struct recptypes));
582 if (supplied_recipients == NULL) {
583 recipients = strdup("");
586 recipients = strdup(supplied_recipients);
589 /* Allocate some memory. Yes, this allocates 500% more memory than we will
590 * actually need, but it's healthier for the heap than doing lots of tiny
591 * realloc() calls instead.
593 len = strlen(recipients) + 1024;
594 ret->errormsg = malloc(len);
595 ret->recp_local = malloc(len);
596 ret->recp_internet = malloc(len);
597 ret->recp_ignet = malloc(len);
598 ret->recp_room = malloc(len);
599 ret->display_recp = malloc(len);
600 ret->recp_orgroom = malloc(len);
601 org_recp = malloc(len);
603 ret->errormsg[0] = 0;
604 ret->recp_local[0] = 0;
605 ret->recp_internet[0] = 0;
606 ret->recp_ignet[0] = 0;
607 ret->recp_room[0] = 0;
608 ret->recp_orgroom[0] = 0;
609 ret->display_recp[0] = 0;
611 ret->recptypes_magic = RECPTYPES_MAGIC;
613 /* Change all valid separator characters to commas */
614 for (i=0; !IsEmptyStr(&recipients[i]); ++i) {
615 if ((recipients[i] == ';') || (recipients[i] == '|')) {
620 /* Now start extracting recipients... */
622 while (!IsEmptyStr(recipients)) {
623 for (i=0; i<=strlen(recipients); ++i) {
624 if (recipients[i] == '\"') in_quotes = 1 - in_quotes;
625 if ( ( (recipients[i] == ',') && (!in_quotes) ) || (recipients[i] == 0) ) {
626 safestrncpy(this_recp, recipients, i+1);
628 if (recipients[i] == ',') {
629 strcpy(recipients, &recipients[i+1]);
632 strcpy(recipients, "");
639 if (IsEmptyStr(this_recp))
641 MSG_syslog(LOG_DEBUG, "Evaluating recipient #%d: %s\n", num_recps, this_recp);
644 strcpy(org_recp, this_recp);
647 mailtype = alias(this_recp);
649 for (j = 0; !IsEmptyStr(&this_recp[j]); ++j) {
650 if (this_recp[j]=='_') {
651 this_recp_cooked[j] = ' ';
654 this_recp_cooked[j] = this_recp[j];
657 this_recp_cooked[j] = '\0';
662 if (!strcasecmp(this_recp, "sysop")) {
664 strcpy(this_recp, config.c_aideroom);
665 if (!IsEmptyStr(ret->recp_room)) {
666 strcat(ret->recp_room, "|");
668 strcat(ret->recp_room, this_recp);
670 else if ( (!strncasecmp(this_recp, "room_", 5))
671 && (!CtdlGetRoom(&tempQR, &this_recp_cooked[5])) ) {
673 /* Save room so we can restore it later */
677 /* Check permissions to send mail to this room */
678 err = CtdlDoIHavePermissionToPostInThisRoom(
683 0 /* 0 = not a reply */
692 if (!IsEmptyStr(ret->recp_room)) {
693 strcat(ret->recp_room, "|");
695 strcat(ret->recp_room, &this_recp_cooked[5]);
697 if (!IsEmptyStr(ret->recp_orgroom)) {
698 strcat(ret->recp_orgroom, "|");
700 strcat(ret->recp_orgroom, org_recp);
704 /* Restore room in case something needs it */
708 else if (CtdlGetUser(&tempUS, this_recp) == 0) {
710 strcpy(this_recp, tempUS.fullname);
711 if (!IsEmptyStr(ret->recp_local)) {
712 strcat(ret->recp_local, "|");
714 strcat(ret->recp_local, this_recp);
716 else if (CtdlGetUser(&tempUS, this_recp_cooked) == 0) {
718 strcpy(this_recp, tempUS.fullname);
719 if (!IsEmptyStr(ret->recp_local)) {
720 strcat(ret->recp_local, "|");
722 strcat(ret->recp_local, this_recp);
730 /* Yes, you're reading this correctly: if the target
731 * domain points back to the local system or an attached
732 * Citadel directory, the address is invalid. That's
733 * because if the address were valid, we would have
734 * already translated it to a local address by now.
736 if (IsDirectory(this_recp, 0)) {
742 if (!IsEmptyStr(ret->recp_internet)) {
743 strcat(ret->recp_internet, "|");
745 strcat(ret->recp_internet, this_recp);
750 if (!IsEmptyStr(ret->recp_ignet)) {
751 strcat(ret->recp_ignet, "|");
753 strcat(ret->recp_ignet, this_recp);
761 if (IsEmptyStr(errmsg)) {
762 snprintf(append, sizeof append, "Invalid recipient: %s", this_recp);
765 snprintf(append, sizeof append, "%s", errmsg);
767 if ( (strlen(ret->errormsg) + strlen(append) + 3) < SIZ) {
768 if (!IsEmptyStr(ret->errormsg)) {
769 strcat(ret->errormsg, "; ");
771 strcat(ret->errormsg, append);
775 if (IsEmptyStr(ret->display_recp)) {
776 strcpy(append, this_recp);
779 snprintf(append, sizeof append, ", %s", this_recp);
781 if ( (strlen(ret->display_recp)+strlen(append)) < SIZ) {
782 strcat(ret->display_recp, append);
788 if ((ret->num_local + ret->num_internet + ret->num_ignet +
789 ret->num_room + ret->num_error) == 0) {
790 ret->num_error = (-1);
791 strcpy(ret->errormsg, "No recipients specified.");
794 MSGM_syslog(LOG_DEBUG, "validate_recipients()\n");
795 MSG_syslog(LOG_DEBUG, " local: %d <%s>\n", ret->num_local, ret->recp_local);
796 MSG_syslog(LOG_DEBUG, " room: %d <%s>\n", ret->num_room, ret->recp_room);
797 MSG_syslog(LOG_DEBUG, " inet: %d <%s>\n", ret->num_internet, ret->recp_internet);
798 MSG_syslog(LOG_DEBUG, " ignet: %d <%s>\n", ret->num_ignet, ret->recp_ignet);
799 MSG_syslog(LOG_DEBUG, " error: %d <%s>\n", ret->num_error, ret->errormsg);
807 * Destructor for struct recptypes
809 void free_recipients(struct recptypes *valid) {
815 if (valid->recptypes_magic != RECPTYPES_MAGIC) {
816 struct CitContext *CCC = CC;
817 MSGM_syslog(LOG_EMERG, "Attempt to call free_recipients() on some other data type!\n");
821 if (valid->errormsg != NULL) free(valid->errormsg);
822 if (valid->recp_local != NULL) free(valid->recp_local);
823 if (valid->recp_internet != NULL) free(valid->recp_internet);
824 if (valid->recp_ignet != NULL) free(valid->recp_ignet);
825 if (valid->recp_room != NULL) free(valid->recp_room);
826 if (valid->recp_orgroom != NULL) free(valid->recp_orgroom);
827 if (valid->display_recp != NULL) free(valid->display_recp);
828 if (valid->bounce_to != NULL) free(valid->bounce_to);
829 if (valid->envelope_from != NULL) free(valid->envelope_from);
830 if (valid->sending_room != NULL) free(valid->sending_room);
835 char *qp_encode_email_addrs(char *source)
837 struct CitContext *CCC = CC;
838 char *user, *node, *name;
839 const char headerStr[] = "=?UTF-8?Q?";
843 int need_to_encode = 0;
849 long nAddrPtrMax = 50;
854 if (source == NULL) return source;
855 if (IsEmptyStr(source)) return source;
856 if (MessageDebugEnabled != 0) cit_backtrace();
857 MSG_syslog(LOG_DEBUG, "qp_encode_email_addrs: [%s]\n", source);
859 AddrPtr = malloc (sizeof (long) * nAddrPtrMax);
860 AddrUtf8 = malloc (sizeof (long) * nAddrPtrMax);
861 memset(AddrUtf8, 0, sizeof (long) * nAddrPtrMax);
864 while (!IsEmptyStr (&source[i])) {
865 if (nColons >= nAddrPtrMax){
868 ptr = (long *) malloc(sizeof (long) * nAddrPtrMax * 2);
869 memcpy (ptr, AddrPtr, sizeof (long) * nAddrPtrMax);
870 free (AddrPtr), AddrPtr = ptr;
872 ptr = (long *) malloc(sizeof (long) * nAddrPtrMax * 2);
873 memset(&ptr[nAddrPtrMax], 0,
874 sizeof (long) * nAddrPtrMax);
876 memcpy (ptr, AddrUtf8, sizeof (long) * nAddrPtrMax);
877 free (AddrUtf8), AddrUtf8 = ptr;
880 if (((unsigned char) source[i] < 32) ||
881 ((unsigned char) source[i] > 126)) {
883 AddrUtf8[nColons] = 1;
885 if (source[i] == '"')
886 InQuotes = !InQuotes;
887 if (!InQuotes && source[i] == ',') {
888 AddrPtr[nColons] = i;
893 if (need_to_encode == 0) {
900 EncodedMaxLen = nColons * (sizeof(headerStr) + 3) + SourceLen * 3;
901 Encoded = (char*) malloc (EncodedMaxLen);
903 for (i = 0; i < nColons; i++)
904 source[AddrPtr[i]++] = '\0';
905 /* TODO: if libidn, this might get larger*/
906 user = malloc(SourceLen + 1);
907 node = malloc(SourceLen + 1);
908 name = malloc(SourceLen + 1);
912 for (i = 0; i < nColons && nPtr != NULL; i++) {
913 nmax = EncodedMaxLen - (nPtr - Encoded);
915 process_rfc822_addr(&source[AddrPtr[i]],
919 /* TODO: libIDN here ! */
920 if (IsEmptyStr(name)) {
921 n = snprintf(nPtr, nmax,
922 (i==0)?"%s@%s" : ",%s@%s",
926 EncodedName = rfc2047encode(name, strlen(name));
927 n = snprintf(nPtr, nmax,
928 (i==0)?"%s <%s@%s>" : ",%s <%s@%s>",
929 EncodedName, user, node);
934 n = snprintf(nPtr, nmax,
936 &source[AddrPtr[i]]);
942 ptr = (char*) malloc(EncodedMaxLen * 2);
943 memcpy(ptr, Encoded, EncodedMaxLen);
944 nnPtr = ptr + (nPtr - Encoded), nPtr = nnPtr;
945 free(Encoded), Encoded = ptr;
947 i--; /* do it once more with properly lengthened buffer */
950 for (i = 0; i < nColons; i++)
951 source[--AddrPtr[i]] = ',';
963 * Return 0 if a given string fuzzy-matches a Citadel user account
965 * FIXME ... this needs to be updated to handle aliases.
967 int fuzzy_match(struct ctdluser *us, char *matchstring) {
971 if ( (!strncasecmp(matchstring, "cit", 3))
972 && (atol(&matchstring[3]) == us->usernum)) {
976 len = strlen(matchstring);
977 for (a=0; !IsEmptyStr(&us->fullname[a]); ++a) {
978 if (!strncasecmp(&us->fullname[a],
988 * Unfold a multi-line field into a single line, removing multi-whitespaces
990 void unfold_rfc822_field(char **field, char **FieldEnd)
993 char *pField = *field;
995 char *pFieldEnd = *FieldEnd;
997 while (isspace(*pField))
999 /* remove leading/trailing whitespace */
1002 while (isspace(*pFieldEnd))
1005 *FieldEnd = pFieldEnd;
1006 /* convert non-space whitespace to spaces, and remove double blanks */
1007 for (sField = *field = pField;
1011 if ((*sField=='\r') || (*sField=='\n')) {
1013 if (*sField == '\n')
1018 if (*sField=='\"') quote = 1 - quote;
1020 if (isspace(*sField))
1026 while ((sField < pFieldEnd) &&
1031 else *pField = *sField;
1033 else *pField = *sField;
1037 *FieldEnd = pField - 1;
1043 * Split an RFC822-style address into userid, host, and full name
1046 void process_rfc822_addr(const char *rfc822, char *user, char *node, char *name)
1051 strcpy(node, config.c_fqdn);
1054 if (rfc822 == NULL) return;
1056 /* extract full name - first, it's From minus <userid> */
1057 strcpy(name, rfc822);
1058 stripout(name, '<', '>');
1060 /* strip anything to the left of a bang */
1061 while ((!IsEmptyStr(name)) && (haschar(name, '!') > 0))
1062 strcpy(name, &name[1]);
1064 /* and anything to the right of a @ or % */
1065 for (a = 0; a < strlen(name); ++a) {
1072 /* but if there are parentheses, that changes the rules... */
1073 if ((haschar(rfc822, '(') == 1) && (haschar(rfc822, ')') == 1)) {
1074 strcpy(name, rfc822);
1075 stripallbut(name, '(', ')');
1078 /* but if there are a set of quotes, that supersedes everything */
1079 if (haschar(rfc822, 34) == 2) {
1080 strcpy(name, rfc822);
1081 while ((!IsEmptyStr(name)) && (name[0] != 34)) {
1082 strcpy(&name[0], &name[1]);
1084 strcpy(&name[0], &name[1]);
1085 for (a = 0; a < strlen(name); ++a)
1089 /* extract user id */
1090 strcpy(user, rfc822);
1092 /* first get rid of anything in parens */
1093 stripout(user, '(', ')');
1095 /* if there's a set of angle brackets, strip it down to that */
1096 if ((haschar(user, '<') == 1) && (haschar(user, '>') == 1)) {
1097 stripallbut(user, '<', '>');
1100 /* strip anything to the left of a bang */
1101 while ((!IsEmptyStr(user)) && (haschar(user, '!') > 0))
1102 strcpy(user, &user[1]);
1104 /* and anything to the right of a @ or % */
1105 for (a = 0; a < strlen(user); ++a) {
1113 /* extract node name */
1114 strcpy(node, rfc822);
1116 /* first get rid of anything in parens */
1117 stripout(node, '(', ')');
1119 /* if there's a set of angle brackets, strip it down to that */
1120 if ((haschar(node, '<') == 1) && (haschar(node, '>') == 1)) {
1121 stripallbut(node, '<', '>');
1124 /* If no node specified, tack ours on instead */
1126 (haschar(node, '@')==0)
1127 && (haschar(node, '%')==0)
1128 && (haschar(node, '!')==0)
1130 strcpy(node, config.c_nodename);
1135 /* strip anything to the left of a @ */
1136 while ((!IsEmptyStr(node)) && (haschar(node, '@') > 0))
1137 strcpy(node, &node[1]);
1139 /* strip anything to the left of a % */
1140 while ((!IsEmptyStr(node)) && (haschar(node, '%') > 0))
1141 strcpy(node, &node[1]);
1143 /* reduce multiple system bang paths to node!user */
1144 while ((!IsEmptyStr(node)) && (haschar(node, '!') > 1))
1145 strcpy(node, &node[1]);
1147 /* now get rid of the user portion of a node!user string */
1148 for (a = 0; a < strlen(node); ++a)
1153 /* strip leading and trailing spaces in all strings */
1158 /* If we processed a string that had the address in angle brackets
1159 * but no name outside the brackets, we now have an empty name. In
1160 * this case, use the user portion of the address as the name.
1162 if ((IsEmptyStr(name)) && (!IsEmptyStr(user))) {
1170 * convert_field() is a helper function for convert_internet_message().
1171 * Given start/end positions for an rfc822 field, it converts it to a Citadel
1172 * field if it wants to, and unfolds it if necessary.
1174 * Returns 1 if the field was converted and inserted into the Citadel message
1175 * structure, implying that the source field should be removed from the
1178 int convert_field(struct CtdlMessage *msg, const char *beg, const char *end) {
1179 char *key, *value, *valueend;
1183 const char *colonpos = NULL;
1192 for (pos = end; pos >= beg; pos--) {
1193 if (*pos == ':') colonpos = pos;
1196 if (colonpos == NULL) return(0); /* no colon? not a valid header line */
1199 key = malloc(len + 2);
1200 memcpy(key, beg, len + 1);
1202 valueend = key + len;
1203 * ( key + (colonpos - beg) ) = '\0';
1204 value = &key[(colonpos - beg) + 1];
1205 /* printf("Header: [%s]\nValue: [%s]\n", key, value); */
1206 unfold_rfc822_field(&value, &valueend);
1207 valuelen = valueend - value + 1;
1208 /* printf("UnfoldedValue: [%s]\n", value); */
1211 * Here's the big rfc822-to-citadel loop.
1214 /* Date/time is converted into a unix timestamp. If the conversion
1215 * fails, we replace it with the time the message arrived locally.
1217 if (!strcasecmp(key, "Date")) {
1218 parsed_date = parsedate(value);
1219 if (parsed_date < 0L) parsed_date = time(NULL);
1221 if (CM_IsEmpty(msg, eTimestamp))
1222 CM_SetFieldLONG(msg, eTimestamp, parsed_date);
1226 else if (!strcasecmp(key, "From")) {
1227 process_rfc822_addr(value, user, node, name);
1228 syslog(LOG_DEBUG, "Converted to <%s@%s> (%s)\n", user, node, name);
1229 snprintf(addr, sizeof(addr), "%s@%s", user, node);
1230 if (CM_IsEmpty(msg, eAuthor))
1231 CM_SetField(msg, eAuthor, name, strlen(name));
1232 if (CM_IsEmpty(msg, erFc822Addr))
1233 CM_SetField(msg, erFc822Addr, addr, strlen(addr));
1237 else if (!strcasecmp(key, "Subject")) {
1238 if (CM_IsEmpty(msg, eMsgSubject))
1239 CM_SetField(msg, eMsgSubject, value, valuelen);
1243 else if (!strcasecmp(key, "List-ID")) {
1244 if (CM_IsEmpty(msg, eListID))
1245 CM_SetField(msg, eListID, value, valuelen);
1249 else if (!strcasecmp(key, "To")) {
1250 if (CM_IsEmpty(msg, eRecipient))
1251 CM_SetField(msg, eRecipient, value, valuelen);
1255 else if (!strcasecmp(key, "CC")) {
1256 if (CM_IsEmpty(msg, eCarbonCopY))
1257 CM_SetField(msg, eCarbonCopY, value, valuelen);
1261 else if (!strcasecmp(key, "Message-ID")) {
1262 if (!CM_IsEmpty(msg, emessageId)) {
1263 syslog(LOG_WARNING, "duplicate message id\n");
1270 pValueLen = valuelen;
1271 /* Strip angle brackets */
1272 while (haschar(pValue, '<') > 0) {
1277 for (i = 0; i <= pValueLen; ++i)
1278 if (pValue[i] == '>') {
1283 CM_SetField(msg, emessageId, pValue, pValueLen);
1289 else if (!strcasecmp(key, "Return-Path")) {
1290 if (CM_IsEmpty(msg, eMessagePath))
1291 CM_SetField(msg, eMessagePath, value, valuelen);
1295 else if (!strcasecmp(key, "Envelope-To")) {
1296 if (CM_IsEmpty(msg, eenVelopeTo))
1297 CM_SetField(msg, eenVelopeTo, value, valuelen);
1301 else if (!strcasecmp(key, "References")) {
1302 CM_SetField(msg, eWeferences, value, valuelen);
1306 else if (!strcasecmp(key, "Reply-To")) {
1307 CM_SetField(msg, eReplyTo, value, valuelen);
1311 else if (!strcasecmp(key, "In-reply-to")) {
1312 if (CM_IsEmpty(msg, eWeferences)) /* References: supersedes In-reply-to: */
1313 CM_SetField(msg, eWeferences, value, valuelen);
1319 /* Clean up and move on. */
1320 free(key); /* Don't free 'value', it's actually the same buffer */
1326 * Convert RFC822 references format (References) to Citadel references format (Weferences)
1328 void convert_references_to_wefewences(char *str) {
1329 int bracket_nesting = 0;
1331 char *moveptr = NULL;
1338 if (bracket_nesting < 0) bracket_nesting = 0;
1340 if ((ch == '>') && (bracket_nesting == 0) && (*(ptr+1)) && (ptr>str) ) {
1344 else if (bracket_nesting > 0) {
1350 *moveptr = *(moveptr+1);
1354 if (ch == '<') ++bracket_nesting;
1361 * Convert an RFC822 message (headers + body) to a CtdlMessage structure.
1362 * NOTE: the supplied buffer becomes part of the CtdlMessage structure, and
1363 * will be deallocated when CM_Free() is called. Therefore, the
1364 * supplied buffer should be DEREFERENCED. It should not be freed or used
1367 struct CtdlMessage *convert_internet_message(char *rfc822) {
1368 StrBuf *RFCBuf = NewStrBufPlain(rfc822, -1);
1370 return convert_internet_message_buf(&RFCBuf);
1375 struct CtdlMessage *convert_internet_message_buf(StrBuf **rfc822)
1377 struct CtdlMessage *msg;
1378 const char *pos, *beg, *end, *totalend;
1379 int done, alldone = 0;
1381 StrBuf *OtherHeaders;
1383 msg = malloc(sizeof(struct CtdlMessage));
1384 if (msg == NULL) return msg;
1386 memset(msg, 0, sizeof(struct CtdlMessage));
1387 msg->cm_magic = CTDLMESSAGE_MAGIC; /* self check */
1388 msg->cm_anon_type = 0; /* never anonymous */
1389 msg->cm_format_type = FMT_RFC822; /* internet message */
1391 pos = ChrPtr(*rfc822);
1392 totalend = pos + StrLength(*rfc822);
1394 OtherHeaders = NewStrBufPlain(NULL, StrLength(*rfc822));
1398 /* Locate beginning and end of field, keeping in mind that
1399 * some fields might be multiline
1403 while ((end < totalend) &&
1408 if ( (*pos=='\n') && ((*(pos+1))!=0x20) && ((*(pos+1))!=0x09) )
1413 /* done with headers? */
1415 ( (*(pos+1)=='\n') ||
1421 if (pos >= (totalend - 1) )
1431 /* At this point we have a field. Are we interested in it? */
1432 converted = convert_field(msg, beg, end);
1434 /* Strip the field out of the RFC822 header if we used it */
1436 StrBufAppendBufPlain(OtherHeaders, beg, end - beg, 0);
1437 StrBufAppendBufPlain(OtherHeaders, HKEY("\n"), 0);
1440 /* If we've hit the end of the message, bail out */
1441 if (pos >= totalend)
1444 StrBufAppendBufPlain(OtherHeaders, HKEY("\n"), 0);
1446 StrBufAppendBufPlain(OtherHeaders, pos, totalend - pos, 0);
1448 CM_SetAsFieldSB(msg, eMesageText, &OtherHeaders);
1450 /* Follow-up sanity checks... */
1452 /* If there's no timestamp on this message, set it to now. */
1453 if (CM_IsEmpty(msg, eTimestamp)) {
1454 CM_SetFieldLONG(msg, eTimestamp, time(NULL));
1457 /* If a W (references, or rather, Wefewences) field is present, we
1458 * have to convert it from RFC822 format to Citadel format.
1460 if (!CM_IsEmpty(msg, eWeferences)) {
1462 convert_references_to_wefewences(msg->cm_fields[eWeferences]);
1471 * Look for a particular header field in an RFC822 message text. If the
1472 * requested field is found, it is unfolded (if necessary) and returned to
1473 * the caller. The field name is stripped out, leaving only its contents.
1474 * The caller is responsible for freeing the returned buffer. If the requested
1475 * field is not present, or anything else goes wrong, it returns NULL.
1477 char *rfc822_fetch_field(const char *rfc822, const char *fieldname) {
1478 char *fieldbuf = NULL;
1479 const char *end_of_headers;
1480 const char *field_start;
1485 /* Should never happen, but sometimes we get stupid */
1486 if (rfc822 == NULL) return(NULL);
1487 if (fieldname == NULL) return(NULL);
1489 snprintf(fieldhdr, sizeof fieldhdr, "%s:", fieldname);
1491 /* Locate the end of the headers, so we don't run past that point */
1492 end_of_headers = cbmstrcasestr(rfc822, "\n\r\n");
1493 if (end_of_headers == NULL) {
1494 end_of_headers = cbmstrcasestr(rfc822, "\n\n");
1496 if (end_of_headers == NULL) return (NULL);
1498 field_start = cbmstrcasestr(rfc822, fieldhdr);
1499 if (field_start == NULL) return(NULL);
1500 if (field_start > end_of_headers) return(NULL);
1502 fieldbuf = malloc(SIZ);
1503 strcpy(fieldbuf, "");
1506 ptr = cmemreadline(ptr, fieldbuf, SIZ-strlen(fieldbuf) );
1507 while ( (isspace(ptr[0])) && (ptr < end_of_headers) ) {
1508 strcat(fieldbuf, " ");
1509 cont = &fieldbuf[strlen(fieldbuf)];
1510 ptr = cmemreadline(ptr, cont, SIZ-strlen(fieldbuf) );
1514 strcpy(fieldbuf, &fieldbuf[strlen(fieldhdr)]);
1522 /*****************************************************************************
1523 * DIRECTORY MANAGEMENT FUNCTIONS *
1524 *****************************************************************************/
1527 * Generate the index key for an Internet e-mail address to be looked up
1530 void directory_key(char *key, char *addr) {
1534 for (i=0; !IsEmptyStr(&addr[i]); ++i) {
1535 if (!isspace(addr[i])) {
1536 key[keylen++] = tolower(addr[i]);
1541 syslog(LOG_DEBUG, "Directory key is <%s>\n", key);
1546 /* Return nonzero if the supplied address is in a domain we keep in
1549 int IsDirectory(char *addr, int allow_masq_domains) {
1553 extract_token(domain, addr, 1, '@', sizeof domain);
1556 h = CtdlHostAlias(domain);
1558 if ( (h == hostalias_masq) && allow_masq_domains)
1561 if ( (h == hostalias_localhost) || (h == hostalias_directory) ) {
1571 * Initialize the directory database (erasing anything already there)
1573 void CtdlDirectoryInit(void) {
1574 cdb_trunc(CDB_DIRECTORY);
1579 * Add an Internet e-mail address to the directory for a user
1581 int CtdlDirectoryAddUser(char *internet_addr, char *citadel_addr) {
1584 if (IsDirectory(internet_addr, 0) == 0)
1586 syslog(LOG_DEBUG, "Create directory entry: %s --> %s\n", internet_addr, citadel_addr);
1587 directory_key(key, internet_addr);
1588 cdb_store(CDB_DIRECTORY, key, strlen(key), citadel_addr, strlen(citadel_addr)+1 );
1594 * Delete an Internet e-mail address from the directory.
1596 * (NOTE: we don't actually use or need the citadel_addr variable; it's merely
1597 * here because the callback API expects to be able to send it.)
1599 int CtdlDirectoryDelUser(char *internet_addr, char *citadel_addr) {
1602 syslog(LOG_DEBUG, "Delete directory entry: %s --> %s\n", internet_addr, citadel_addr);
1603 directory_key(key, internet_addr);
1604 return cdb_delete(CDB_DIRECTORY, key, strlen(key) ) == 0;
1609 * Look up an Internet e-mail address in the directory.
1610 * On success: returns 0, and Citadel address stored in 'target'
1611 * On failure: returns nonzero
1613 int CtdlDirectoryLookup(char *target, char *internet_addr, size_t targbuflen) {
1614 struct cdbdata *cdbrec;
1617 /* Dump it in there unchanged, just for kicks */
1618 safestrncpy(target, internet_addr, targbuflen);
1620 /* Only do lookups for addresses with hostnames in them */
1621 if (num_tokens(internet_addr, '@') != 2) return(-1);
1623 /* Only do lookups for domains in the directory */
1624 if (IsDirectory(internet_addr, 0) == 0) return(-1);
1626 directory_key(key, internet_addr);
1627 cdbrec = cdb_fetch(CDB_DIRECTORY, key, strlen(key) );
1628 if (cdbrec != NULL) {
1629 safestrncpy(target, cdbrec->ptr, targbuflen);
1639 * Harvest any email addresses that someone might want to have in their
1640 * "collected addresses" book.
1642 char *harvest_collected_addresses(struct CtdlMessage *msg) {
1645 char user[256], node[256], name[256];
1648 eMsgField field = 0;
1650 if (msg == NULL) return(NULL);
1654 if (!CM_IsEmpty(msg, eAuthor)) {
1655 strcat(addr, msg->cm_fields[eAuthor]);
1657 if (!CM_IsEmpty(msg, erFc822Addr)) {
1659 strcat(addr, msg->cm_fields[erFc822Addr]);
1661 if (IsDirectory(msg->cm_fields[erFc822Addr], 0)) {
1666 if (is_harvestable) {
1667 coll = strdup(addr);
1673 if (coll == NULL) return(NULL);
1675 /* Scan both the R (To) and Y (CC) fields */
1676 for (i = 0; i < 2; ++i) {
1677 if (i == 0) field = eRecipient;
1678 if (i == 1) field = eCarbonCopY;
1680 if (!CM_IsEmpty(msg, field)) {
1681 for (j=0; j<num_tokens(msg->cm_fields[field], ','); ++j) {
1682 extract_token(addr, msg->cm_fields[field], j, ',', sizeof addr);
1683 if (strstr(addr, "=?") != NULL)
1684 utf8ify_rfc822_string(addr);
1685 process_rfc822_addr(addr, user, node, name);
1686 h = CtdlHostAlias(node);
1687 if ( (h != hostalias_localhost) && (h != hostalias_directory) ) {
1688 coll = realloc(coll, strlen(coll) + strlen(addr) + 4);
1689 if (coll == NULL) return(NULL);
1690 if (!IsEmptyStr(coll)) {
1700 if (IsEmptyStr(coll)) {
1708 CTDL_MODULE_INIT(internet_addressing)
1711 CtdlRegisterProtoHook(cmd_isme, "ISME", "Determine whether an email address belongs to a user");
1713 return "internet_addressing";