4 * This file contains functions which handle the mapping of Internet addresses
5 * to users on the Citadel system.
17 #include <sys/types.h>
19 #if TIME_WITH_SYS_TIME
20 # include <sys/time.h>
24 # include <sys/time.h>
33 #include <libcitadel.h>
36 #include "sysdep_decls.h"
37 #include "citserver.h"
41 #include "internet_addressing.h"
44 #include "parsedate.h"
57 /* This is the non-define version in case of s.b. needing to debug */
58 inline void FindNextEnd (char *bptr, char *end)
60 /* Find the next ?Q? */
61 end = strchr(bptr + 2, '?');
62 if (end == NULL) return NULL;
63 if (((*(end + 1) == 'B') || (*(end + 1) == 'Q')) &&
64 (*(end + 2) == '?')) {
65 /* skip on to the end of the cluster, the next ?= */
66 end = strstr(end + 3, "?=");
69 /* sort of half valid encoding, try to find an end. */
70 end = strstr(bptr, "?=");
74 #define FindNextEnd(bptr, end) { \
75 end = strchr(bptr + 2, '?'); \
77 if (((*(end + 1) == 'B') || (*(end + 1) == 'Q')) && (*(end + 2) == '?')) { \
78 end = strstr(end + 3, "?="); \
79 } else end = strstr(bptr, "?="); \
84 * Handle subjects with RFC2047 encoding such as:
85 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
87 void utf8ify_rfc822_string(char *buf) {
88 char *start, *end, *next, *nextend, *ptr;
93 iconv_t ic = (iconv_t)(-1) ;
94 char *ibuf; /**< Buffer of characters to be converted */
95 char *obuf; /**< Buffer for converted characters */
96 size_t ibuflen; /**< Length of input buffer */
97 size_t obuflen; /**< Length of output buffer */
98 char *isav; /**< Saved pointer to input buffer */
99 char *osav; /**< Saved pointer to output buffer */
102 int illegal_non_rfc2047_encoding = 0;
104 /* Sometimes, badly formed messages contain strings which were simply
105 * written out directly in some foreign character set instead of
106 * using RFC2047 encoding. This is illegal but we will attempt to
107 * handle it anyway by converting from a user-specified default
108 * charset to UTF-8 if we see any nonprintable characters.
111 for (i=0; i<len; ++i) {
112 if ((buf[i] < 32) || (buf[i] > 126)) {
113 illegal_non_rfc2047_encoding = 1;
114 i = len; ///< take a shortcut, it won't be more than one.
117 if (illegal_non_rfc2047_encoding) {
118 const char *default_header_charset = "iso-8859-1";
119 if ( (strcasecmp(default_header_charset, "UTF-8")) && (strcasecmp(default_header_charset, "us-ascii")) ) {
120 ctdl_iconv_open("UTF-8", default_header_charset, &ic);
121 if (ic != (iconv_t)(-1) ) {
124 safestrncpy(ibuf, buf, 1024);
125 ibuflen = strlen(ibuf);
127 obuf = (char *) malloc(obuflen);
129 iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
130 osav[1024-obuflen] = 0;
139 /* pre evaluate the first pair */
140 nextend = end = NULL;
142 start = strstr(buf, "=?");
144 FindNextEnd (start, end);
146 while ((start != NULL) && (end != NULL))
148 next = strstr(end, "=?");
150 FindNextEnd(next, nextend);
154 /* did we find two partitions */
155 if ((next != NULL) &&
159 while ((ptr < next) &&
165 /* did we find a gab just filled with blanks? */
170 len - (next - start));
172 /* now terminate the gab at the end */
173 delta = (next - end) - 2;
177 /* move next to its new location. */
182 /* our next-pair is our new first pair now. */
187 /* Now we handle foreign character sets properly encoded
190 start = strstr(buf, "=?");
191 FindNextEnd((start != NULL)? start : buf, end);
192 while (start != NULL && end != NULL && end > start)
194 extract_token(charset, start, 1, '?', sizeof charset);
195 extract_token(encoding, start, 2, '?', sizeof encoding);
196 extract_token(istr, start, 3, '?', sizeof istr);
200 if (!strcasecmp(encoding, "B")) { /**< base64 */
201 ibuflen = CtdlDecodeBase64(ibuf, istr, strlen(istr));
203 else if (!strcasecmp(encoding, "Q")) { /**< quoted-printable */
211 if (istr[pos] == '_') istr[pos] = ' ';
215 ibuflen = CtdlDecodeQuotedPrintable(ibuf, istr, len);
218 strcpy(ibuf, istr); /**< unknown encoding */
219 ibuflen = strlen(istr);
222 ctdl_iconv_open("UTF-8", charset, &ic);
223 if (ic != (iconv_t)(-1) ) {
225 obuf = (char *) malloc(obuflen);
227 iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
228 osav[1024-obuflen] = 0;
233 remove_token(end, 0, '?');
234 remove_token(end, 0, '?');
235 remove_token(end, 0, '?');
236 remove_token(end, 0, '?');
237 strcpy(end, &end[1]);
239 snprintf(newbuf, sizeof newbuf, "%s%s%s", buf, osav, end);
248 remove_token(end, 0, '?');
249 remove_token(end, 0, '?');
250 remove_token(end, 0, '?');
251 remove_token(end, 0, '?');
252 strcpy(end, &end[1]);
254 snprintf(newbuf, sizeof newbuf, "%s(unreadable)%s", buf, end);
261 * Since spammers will go to all sorts of absurd lengths to get their
262 * messages through, there are LOTS of corrupt headers out there.
263 * So, prevent a really badly formed RFC2047 header from throwing
264 * this function into an infinite loop.
267 if (passes > 20) return;
269 start = strstr(buf, "=?");
270 FindNextEnd((start != NULL)? start : buf, end);
275 inline void utf8ify_rfc822_string(char *a){};
286 char *inetcfg = NULL;
287 struct spamstrings_t *spamstrings = NULL;
291 * Return nonzero if the supplied name is an alias for this host.
293 int CtdlHostAlias(char *fqdn) {
297 char host[256], type[256];
299 if (fqdn == NULL) return(hostalias_nomatch);
300 if (IsEmptyStr(fqdn)) return(hostalias_nomatch);
301 if (!strcasecmp(fqdn, "localhost")) return(hostalias_localhost);
302 if (!strcasecmp(fqdn, config.c_fqdn)) return(hostalias_localhost);
303 if (!strcasecmp(fqdn, config.c_nodename)) return(hostalias_localhost);
304 if (inetcfg == NULL) return(hostalias_nomatch);
306 config_lines = num_tokens(inetcfg, '\n');
307 for (i=0; i<config_lines; ++i) {
308 extract_token(buf, inetcfg, i, '\n', sizeof buf);
309 extract_token(host, buf, 0, '|', sizeof host);
310 extract_token(type, buf, 1, '|', sizeof type);
312 if ( (!strcasecmp(type, "localhost"))
313 && (!strcasecmp(fqdn, host)))
314 return(hostalias_localhost);
316 if ( (!strcasecmp(type, "directory"))
317 && (!strcasecmp(fqdn, host)))
318 return(hostalias_directory);
320 if ( (!strcasecmp(type, "masqdomain"))
321 && (!strcasecmp(fqdn, host)))
322 return(hostalias_masq);
326 return(hostalias_nomatch);
336 * Return 0 if a given string fuzzy-matches a Citadel user account
338 * FIXME ... this needs to be updated to handle aliases.
340 int fuzzy_match(struct ctdluser *us, char *matchstring) {
344 if ( (!strncasecmp(matchstring, "cit", 3))
345 && (atol(&matchstring[3]) == us->usernum)) {
349 len = strlen(matchstring);
350 for (a=0; !IsEmptyStr(&us->fullname[a]); ++a) {
351 if (!strncasecmp(&us->fullname[a],
361 * Unfold a multi-line field into a single line, removing multi-whitespaces
363 void unfold_rfc822_field(char *field) {
367 striplt(field); /* remove leading/trailing whitespace */
369 /* convert non-space whitespace to spaces, and remove double blanks */
370 for (i=0; i<strlen(field); ++i) {
371 if (field[i]=='\"') quote = 1 - quote;
373 if (isspace(field[i])) field[i] = ' ';
374 while (isspace(field[i]) && isspace(field[i+1])) {
375 strcpy(&field[i+1], &field[i+2]);
384 * Split an RFC822-style address into userid, host, and full name
387 void process_rfc822_addr(const char *rfc822, char *user, char *node, char *name)
392 strcpy(node, config.c_fqdn);
395 if (rfc822 == NULL) return;
397 /* extract full name - first, it's From minus <userid> */
398 strcpy(name, rfc822);
399 stripout(name, '<', '>');
401 /* strip anything to the left of a bang */
402 while ((!IsEmptyStr(name)) && (haschar(name, '!') > 0))
403 strcpy(name, &name[1]);
405 /* and anything to the right of a @ or % */
406 for (a = 0; a < strlen(name); ++a) {
413 /* but if there are parentheses, that changes the rules... */
414 if ((haschar(rfc822, '(') == 1) && (haschar(rfc822, ')') == 1)) {
415 strcpy(name, rfc822);
416 stripallbut(name, '(', ')');
419 /* but if there are a set of quotes, that supersedes everything */
420 if (haschar(rfc822, 34) == 2) {
421 strcpy(name, rfc822);
422 while ((!IsEmptyStr(name)) && (name[0] != 34)) {
423 strcpy(&name[0], &name[1]);
425 strcpy(&name[0], &name[1]);
426 for (a = 0; a < strlen(name); ++a)
430 /* extract user id */
431 strcpy(user, rfc822);
433 /* first get rid of anything in parens */
434 stripout(user, '(', ')');
436 /* if there's a set of angle brackets, strip it down to that */
437 if ((haschar(user, '<') == 1) && (haschar(user, '>') == 1)) {
438 stripallbut(user, '<', '>');
441 /* strip anything to the left of a bang */
442 while ((!IsEmptyStr(user)) && (haschar(user, '!') > 0))
443 strcpy(user, &user[1]);
445 /* and anything to the right of a @ or % */
446 for (a = 0; a < strlen(user); ++a) {
454 /* extract node name */
455 strcpy(node, rfc822);
457 /* first get rid of anything in parens */
458 stripout(node, '(', ')');
460 /* if there's a set of angle brackets, strip it down to that */
461 if ((haschar(node, '<') == 1) && (haschar(node, '>') == 1)) {
462 stripallbut(node, '<', '>');
465 /* If no node specified, tack ours on instead */
467 (haschar(node, '@')==0)
468 && (haschar(node, '%')==0)
469 && (haschar(node, '!')==0)
471 strcpy(node, config.c_nodename);
476 /* strip anything to the left of a @ */
477 while ((!IsEmptyStr(node)) && (haschar(node, '@') > 0))
478 strcpy(node, &node[1]);
480 /* strip anything to the left of a % */
481 while ((!IsEmptyStr(node)) && (haschar(node, '%') > 0))
482 strcpy(node, &node[1]);
484 /* reduce multiple system bang paths to node!user */
485 while ((!IsEmptyStr(node)) && (haschar(node, '!') > 1))
486 strcpy(node, &node[1]);
488 /* now get rid of the user portion of a node!user string */
489 for (a = 0; a < strlen(node); ++a)
494 /* strip leading and trailing spaces in all strings */
499 /* If we processed a string that had the address in angle brackets
500 * but no name outside the brackets, we now have an empty name. In
501 * this case, use the user portion of the address as the name.
503 if ((IsEmptyStr(name)) && (!IsEmptyStr(user))) {
511 * convert_field() is a helper function for convert_internet_message().
512 * Given start/end positions for an rfc822 field, it converts it to a Citadel
513 * field if it wants to, and unfolds it if necessary.
515 * Returns 1 if the field was converted and inserted into the Citadel message
516 * structure, implying that the source field should be removed from the
519 int convert_field(struct CtdlMessage *msg, int beg, int end) {
532 rfc822 = msg->cm_fields['M']; /* M field contains rfc822 text */
533 for (i = end; i >= beg; --i) {
534 if (rfc822[i] == ':') colonpos = i;
537 if (colonpos < 0) return(0); /* no colon? not a valid header line */
539 key = malloc((end - beg) + 2);
540 safestrncpy(key, &rfc822[beg], (end-beg)+1);
541 key[colonpos - beg] = 0;
542 value = &key[(colonpos - beg) + 1];
543 unfold_rfc822_field(value);
546 * Here's the big rfc822-to-citadel loop.
549 /* Date/time is converted into a unix timestamp. If the conversion
550 * fails, we replace it with the time the message arrived locally.
552 if (!strcasecmp(key, "Date")) {
553 parsed_date = parsedate(value);
554 if (parsed_date < 0L) parsed_date = time(NULL);
555 snprintf(buf, sizeof buf, "%ld", (long)parsed_date );
556 if (msg->cm_fields['T'] == NULL)
557 msg->cm_fields['T'] = strdup(buf);
561 else if (!strcasecmp(key, "From")) {
562 process_rfc822_addr(value, user, node, name);
563 CtdlLogPrintf(CTDL_DEBUG, "Converted to <%s@%s> (%s)\n", user, node, name);
564 snprintf(addr, sizeof addr, "%s@%s", user, node);
565 if (msg->cm_fields['A'] == NULL)
566 msg->cm_fields['A'] = strdup(name);
568 if (msg->cm_fields['F'] == NULL)
569 msg->cm_fields['F'] = strdup(addr);
573 else if (!strcasecmp(key, "Subject")) {
574 if (msg->cm_fields['U'] == NULL)
575 msg->cm_fields['U'] = strdup(value);
579 else if (!strcasecmp(key, "List-ID")) {
580 if (msg->cm_fields['L'] == NULL)
581 msg->cm_fields['L'] = strdup(value);
585 else if (!strcasecmp(key, "To")) {
586 if (msg->cm_fields['R'] == NULL)
587 msg->cm_fields['R'] = strdup(value);
591 else if (!strcasecmp(key, "CC")) {
592 if (msg->cm_fields['Y'] == NULL)
593 msg->cm_fields['Y'] = strdup(value);
597 else if (!strcasecmp(key, "Message-ID")) {
598 if (msg->cm_fields['I'] != NULL) {
599 CtdlLogPrintf(CTDL_WARNING, "duplicate message id\n");
602 if (msg->cm_fields['I'] == NULL) {
603 msg->cm_fields['I'] = strdup(value);
605 /* Strip angle brackets */
606 while (haschar(msg->cm_fields['I'], '<') > 0) {
607 strcpy(&msg->cm_fields['I'][0],
608 &msg->cm_fields['I'][1]);
610 for (i = 0; i<strlen(msg->cm_fields['I']); ++i)
611 if (msg->cm_fields['I'][i] == '>')
612 msg->cm_fields['I'][i] = 0;
618 else if (!strcasecmp(key, "Return-Path")) {
619 if (msg->cm_fields['P'] == NULL)
620 msg->cm_fields['P'] = strdup(value);
624 else if (!strcasecmp(key, "Envelope-To")) {
625 if (msg->cm_fields['V'] == NULL)
626 msg->cm_fields['V'] = strdup(value);
630 else if (!strcasecmp(key, "References")) {
631 if (msg->cm_fields['W'] != NULL) {
632 free(msg->cm_fields['W']);
634 msg->cm_fields['W'] = strdup(value);
638 else if (!strcasecmp(key, "In-reply-to")) {
639 if (msg->cm_fields['W'] == NULL) { /* References: supersedes In-reply-to: */
640 msg->cm_fields['W'] = strdup(value);
647 /* Clean up and move on. */
648 free(key); /* Don't free 'value', it's actually the same buffer */
654 * Convert RFC822 references format (References) to Citadel references format (Weferences)
656 void convert_references_to_wefewences(char *str) {
657 int bracket_nesting = 0;
659 char *moveptr = NULL;
666 if (bracket_nesting < 0) bracket_nesting = 0;
668 if ((ch == '>') && (bracket_nesting == 0) && (*(ptr+1)) && (ptr>str) ) {
672 else if (bracket_nesting > 0) {
678 *moveptr = *(moveptr+1);
682 if (ch == '<') ++bracket_nesting;
689 * Convert an RFC822 message (headers + body) to a CtdlMessage structure.
690 * NOTE: the supplied buffer becomes part of the CtdlMessage structure, and
691 * will be deallocated when CtdlFreeMessage() is called. Therefore, the
692 * supplied buffer should be DEREFERENCED. It should not be freed or used
695 struct CtdlMessage *convert_internet_message(char *rfc822) {
697 struct CtdlMessage *msg;
698 int pos, beg, end, msglen;
703 msg = malloc(sizeof(struct CtdlMessage));
704 if (msg == NULL) return msg;
706 memset(msg, 0, sizeof(struct CtdlMessage));
707 msg->cm_magic = CTDLMESSAGE_MAGIC; /* self check */
708 msg->cm_anon_type = 0; /* never anonymous */
709 msg->cm_format_type = FMT_RFC822; /* internet message */
710 msg->cm_fields['M'] = rfc822;
717 /* Locate beginning and end of field, keeping in mind that
718 * some fields might be multiline
723 msglen = strlen(rfc822);
724 while ( (end < 0) && (done == 0) ) {
726 if ((rfc822[pos]=='\n')
727 && (!isspace(rfc822[pos+1]))) {
731 /* done with headers? */
732 if ( (rfc822[pos]=='\n')
733 && ( (rfc822[pos+1]=='\n')
734 ||(rfc822[pos+1]=='\r')) ) {
739 if (pos >= (msglen-1) ) {
748 /* At this point we have a field. Are we interested in it? */
749 converted = convert_field(msg, beg, end);
751 /* Strip the field out of the RFC822 header if we used it */
753 strcpy(&rfc822[beg], &rfc822[pos]);
757 /* If we've hit the end of the message, bail out */
758 if (pos > strlen(rfc822)) done = 1;
761 /* Follow-up sanity checks... */
763 /* If there's no timestamp on this message, set it to now. */
764 if (msg->cm_fields['T'] == NULL) {
765 snprintf(buf, sizeof buf, "%ld", (long)time(NULL));
766 msg->cm_fields['T'] = strdup(buf);
769 /* If a W (references, or rather, Wefewences) field is present, we
770 * have to convert it from RFC822 format to Citadel format.
772 if (msg->cm_fields['W'] != NULL) {
773 convert_references_to_wefewences(msg->cm_fields['W']);
782 * Look for a particular header field in an RFC822 message text. If the
783 * requested field is found, it is unfolded (if necessary) and returned to
784 * the caller. The field name is stripped out, leaving only its contents.
785 * The caller is responsible for freeing the returned buffer. If the requested
786 * field is not present, or anything else goes wrong, it returns NULL.
788 char *rfc822_fetch_field(char *rfc822, char *fieldname) {
789 char *fieldbuf = NULL;
790 char *end_of_headers;
796 /* Should never happen, but sometimes we get stupid */
797 if (rfc822 == NULL) return(NULL);
798 if (fieldname == NULL) return(NULL);
800 snprintf(fieldhdr, sizeof fieldhdr, "%s:", fieldname);
802 /* Locate the end of the headers, so we don't run past that point */
803 end_of_headers = bmstrcasestr(rfc822, "\n\r\n");
804 if (end_of_headers == NULL) {
805 end_of_headers = bmstrcasestr(rfc822, "\n\n");
807 if (end_of_headers == NULL) return (NULL);
809 field_start = bmstrcasestr(rfc822, fieldhdr);
810 if (field_start == NULL) return(NULL);
811 if (field_start > end_of_headers) return(NULL);
813 fieldbuf = malloc(SIZ);
814 strcpy(fieldbuf, "");
817 ptr = memreadline(ptr, fieldbuf, SIZ-strlen(fieldbuf) );
818 while ( (isspace(ptr[0])) && (ptr < end_of_headers) ) {
819 strcat(fieldbuf, " ");
820 cont = &fieldbuf[strlen(fieldbuf)];
821 ptr = memreadline(ptr, cont, SIZ-strlen(fieldbuf) );
825 strcpy(fieldbuf, &fieldbuf[strlen(fieldhdr)]);
833 /*****************************************************************************
834 * DIRECTORY MANAGEMENT FUNCTIONS *
835 *****************************************************************************/
838 * Generate the index key for an Internet e-mail address to be looked up
841 void directory_key(char *key, char *addr) {
845 for (i=0; !IsEmptyStr(&addr[i]); ++i) {
846 if (!isspace(addr[i])) {
847 key[keylen++] = tolower(addr[i]);
852 CtdlLogPrintf(CTDL_DEBUG, "Directory key is <%s>\n", key);
857 /* Return nonzero if the supplied address is in a domain we keep in
860 int IsDirectory(char *addr, int allow_masq_domains) {
864 extract_token(domain, addr, 1, '@', sizeof domain);
867 h = CtdlHostAlias(domain);
869 if ( (h == hostalias_masq) && allow_masq_domains)
872 if ( (h == hostalias_localhost) || (h == hostalias_directory) ) {
882 * Initialize the directory database (erasing anything already there)
884 void CtdlDirectoryInit(void) {
885 cdb_trunc(CDB_DIRECTORY);
890 * Add an Internet e-mail address to the directory for a user
892 void CtdlDirectoryAddUser(char *internet_addr, char *citadel_addr) {
895 CtdlLogPrintf(CTDL_DEBUG, "Dir: %s --> %s\n",
896 internet_addr, citadel_addr);
897 if (IsDirectory(internet_addr, 0) == 0) return;
899 directory_key(key, internet_addr);
901 cdb_store(CDB_DIRECTORY, key, strlen(key),
902 citadel_addr, strlen(citadel_addr)+1 );
907 * Delete an Internet e-mail address from the directory.
909 * (NOTE: we don't actually use or need the citadel_addr variable; it's merely
910 * here because the callback API expects to be able to send it.)
912 void CtdlDirectoryDelUser(char *internet_addr, char *citadel_addr) {
915 directory_key(key, internet_addr);
916 cdb_delete(CDB_DIRECTORY, key, strlen(key) );
921 * Look up an Internet e-mail address in the directory.
922 * On success: returns 0, and Citadel address stored in 'target'
923 * On failure: returns nonzero
925 int CtdlDirectoryLookup(char *target, char *internet_addr, size_t targbuflen) {
926 struct cdbdata *cdbrec;
929 /* Dump it in there unchanged, just for kicks */
930 safestrncpy(target, internet_addr, targbuflen);
932 /* Only do lookups for addresses with hostnames in them */
933 if (num_tokens(internet_addr, '@') != 2) return(-1);
935 /* Only do lookups for domains in the directory */
936 if (IsDirectory(internet_addr, 0) == 0) return(-1);
938 directory_key(key, internet_addr);
939 cdbrec = cdb_fetch(CDB_DIRECTORY, key, strlen(key) );
940 if (cdbrec != NULL) {
941 safestrncpy(target, cdbrec->ptr, targbuflen);
951 * Harvest any email addresses that someone might want to have in their
952 * "collected addresses" book.
954 char *harvest_collected_addresses(struct CtdlMessage *msg) {
957 char user[256], node[256], name[256];
962 if (msg == NULL) return(NULL);
966 if (msg->cm_fields['A'] != NULL) {
967 strcat(addr, msg->cm_fields['A']);
969 if (msg->cm_fields['F'] != NULL) {
971 strcat(addr, msg->cm_fields['F']);
973 if (IsDirectory(msg->cm_fields['F'], 0)) {
978 if (is_harvestable) {
985 if (coll == NULL) return(NULL);
987 /* Scan both the R (To) and Y (CC) fields */
988 for (i = 0; i < 2; ++i) {
989 if (i == 0) field = 'R' ;
990 if (i == 1) field = 'Y' ;
992 if (msg->cm_fields[field] != NULL) {
993 for (j=0; j<num_tokens(msg->cm_fields[field], ','); ++j) {
994 extract_token(addr, msg->cm_fields[field], j, ',', sizeof addr);
995 if (strstr(addr, "=?") != NULL)
996 utf8ify_rfc822_string(addr);
997 process_rfc822_addr(addr, user, node, name);
998 h = CtdlHostAlias(node);
999 if ( (h != hostalias_localhost) && (h != hostalias_directory) ) {
1000 coll = realloc(coll, strlen(coll) + strlen(addr) + 4);
1001 if (coll == NULL) return(NULL);
1002 if (!IsEmptyStr(coll)) {
1012 if (IsEmptyStr(coll)) {