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>
35 #include "sysdep_decls.h"
36 #include "citserver.h"
41 #include "internet_addressing.h"
44 #include "parsedate.h"
59 struct spamstrings_t *spamstrings = NULL;
63 * Return nonzero if the supplied name is an alias for this host.
65 int CtdlHostAlias(char *fqdn) {
69 char host[256], type[256];
71 if (fqdn == NULL) return(hostalias_nomatch);
72 if (IsEmptyStr(fqdn)) return(hostalias_nomatch);
73 if (!strcasecmp(fqdn, "localhost")) return(hostalias_localhost);
74 if (!strcasecmp(fqdn, config.c_fqdn)) return(hostalias_localhost);
75 if (!strcasecmp(fqdn, config.c_nodename)) return(hostalias_localhost);
76 if (inetcfg == NULL) return(hostalias_nomatch);
78 config_lines = num_tokens(inetcfg, '\n');
79 for (i=0; i<config_lines; ++i) {
80 extract_token(buf, inetcfg, i, '\n', sizeof buf);
81 extract_token(host, buf, 0, '|', sizeof host);
82 extract_token(type, buf, 1, '|', sizeof type);
84 if ( (!strcasecmp(type, "localhost"))
85 && (!strcasecmp(fqdn, host)))
86 return(hostalias_localhost);
88 if ( (!strcasecmp(type, "gatewaydomain"))
89 && (!strcasecmp(&fqdn[strlen(fqdn)-strlen(host)], host)))
90 return(hostalias_gatewaydomain);
92 if ( (!strcasecmp(type, "directory"))
93 && (!strcasecmp(&fqdn[strlen(fqdn)-strlen(host)], host)))
94 return(hostalias_directory);
96 if ( (!strcasecmp(type, "masqdomain"))
97 && (!strcasecmp(&fqdn[strlen(fqdn)-strlen(host)], host)))
98 return(hostalias_masq);
102 return(hostalias_nomatch);
112 * Return 0 if a given string fuzzy-matches a Citadel user account
114 * FIXME ... this needs to be updated to handle aliases.
116 int fuzzy_match(struct ctdluser *us, char *matchstring) {
119 if ( (!strncasecmp(matchstring, "cit", 3))
120 && (atol(&matchstring[3]) == us->usernum)) {
125 for (a=0; a<strlen(us->fullname); ++a) {
126 if (!strncasecmp(&us->fullname[a],
127 matchstring, strlen(matchstring))) {
136 * Unfold a multi-line field into a single line, removing multi-whitespaces
138 void unfold_rfc822_field(char *field) {
142 striplt(field); /* remove leading/trailing whitespace */
144 /* convert non-space whitespace to spaces, and remove double blanks */
145 for (i=0; i<strlen(field); ++i) {
146 if (field[i]=='\"') quote = 1 - quote;
148 if (isspace(field[i])) field[i] = ' ';
149 while (isspace(field[i]) && isspace(field[i+1])) {
150 strcpy(&field[i+1], &field[i+2]);
159 * Split an RFC822-style address into userid, host, and full name
162 void process_rfc822_addr(const char *rfc822, char *user, char *node, char *name)
167 strcpy(node, config.c_fqdn);
170 if (rfc822 == NULL) return;
172 /* extract full name - first, it's From minus <userid> */
173 strcpy(name, rfc822);
174 stripout(name, '<', '>');
176 /* strip anything to the left of a bang */
177 while ((!IsEmptyStr(name)) && (haschar(name, '!') > 0))
178 strcpy(name, &name[1]);
180 /* and anything to the right of a @ or % */
181 for (a = 0; a < strlen(name); ++a) {
188 /* but if there are parentheses, that changes the rules... */
189 if ((haschar(rfc822, '(') == 1) && (haschar(rfc822, ')') == 1)) {
190 strcpy(name, rfc822);
191 stripallbut(name, '(', ')');
194 /* but if there are a set of quotes, that supersedes everything */
195 if (haschar(rfc822, 34) == 2) {
196 strcpy(name, rfc822);
197 while ((!IsEmptyStr(name)) && (name[0] != 34)) {
198 strcpy(&name[0], &name[1]);
200 strcpy(&name[0], &name[1]);
201 for (a = 0; a < strlen(name); ++a)
205 /* extract user id */
206 strcpy(user, rfc822);
208 /* first get rid of anything in parens */
209 stripout(user, '(', ')');
211 /* if there's a set of angle brackets, strip it down to that */
212 if ((haschar(user, '<') == 1) && (haschar(user, '>') == 1)) {
213 stripallbut(user, '<', '>');
216 /* strip anything to the left of a bang */
217 while ((!IsEmptyStr(user)) && (haschar(user, '!') > 0))
218 strcpy(user, &user[1]);
220 /* and anything to the right of a @ or % */
221 for (a = 0; a < strlen(user); ++a) {
229 /* extract node name */
230 strcpy(node, rfc822);
232 /* first get rid of anything in parens */
233 stripout(node, '(', ')');
235 /* if there's a set of angle brackets, strip it down to that */
236 if ((haschar(node, '<') == 1) && (haschar(node, '>') == 1)) {
237 stripallbut(node, '<', '>');
240 /* If no node specified, tack ours on instead */
242 (haschar(node, '@')==0)
243 && (haschar(node, '%')==0)
244 && (haschar(node, '!')==0)
246 strcpy(node, config.c_nodename);
251 /* strip anything to the left of a @ */
252 while ((!IsEmptyStr(node)) && (haschar(node, '@') > 0))
253 strcpy(node, &node[1]);
255 /* strip anything to the left of a % */
256 while ((!IsEmptyStr(node)) && (haschar(node, '%') > 0))
257 strcpy(node, &node[1]);
259 /* reduce multiple system bang paths to node!user */
260 while ((!IsEmptyStr(node)) && (haschar(node, '!') > 1))
261 strcpy(node, &node[1]);
263 /* now get rid of the user portion of a node!user string */
264 for (a = 0; a < strlen(node); ++a)
269 /* strip leading and trailing spaces in all strings */
274 /* If we processed a string that had the address in angle brackets
275 * but no name outside the brackets, we now have an empty name. In
276 * this case, use the user portion of the address as the name.
278 if ((IsEmptyStr(name)) && (!IsEmptyStr(user))) {
286 * convert_field() is a helper function for convert_internet_message().
287 * Given start/end positions for an rfc822 field, it converts it to a Citadel
288 * field if it wants to, and unfolds it if necessary.
290 * Returns 1 if the field was converted and inserted into the Citadel message
291 * structure, implying that the source field should be removed from the
294 int convert_field(struct CtdlMessage *msg, int beg, int end) {
307 rfc822 = msg->cm_fields['M']; /* M field contains rfc822 text */
308 for (i = end; i >= beg; --i) {
309 if (rfc822[i] == ':') colonpos = i;
312 if (colonpos < 0) return(0); /* no colon? not a valid header line */
314 key = malloc((end - beg) + 2);
315 safestrncpy(key, &rfc822[beg], (end-beg)+1);
316 key[colonpos - beg] = 0;
317 value = &key[(colonpos - beg) + 1];
318 unfold_rfc822_field(value);
321 * Here's the big rfc822-to-citadel loop.
324 /* Date/time is converted into a unix timestamp. If the conversion
325 * fails, we replace it with the time the message arrived locally.
327 if (!strcasecmp(key, "Date")) {
328 parsed_date = parsedate(value);
329 if (parsed_date < 0L) parsed_date = time(NULL);
330 snprintf(buf, sizeof buf, "%ld", (long)parsed_date );
331 if (msg->cm_fields['T'] == NULL)
332 msg->cm_fields['T'] = strdup(buf);
336 else if (!strcasecmp(key, "From")) {
337 process_rfc822_addr(value, user, node, name);
338 lprintf(CTDL_DEBUG, "Converted to <%s@%s> (%s)\n", user, node, name);
339 snprintf(addr, sizeof addr, "%s@%s", user, node);
340 if (msg->cm_fields['A'] == NULL)
341 msg->cm_fields['A'] = strdup(name);
343 if (msg->cm_fields['F'] == NULL)
344 msg->cm_fields['F'] = strdup(addr);
348 else if (!strcasecmp(key, "Subject")) {
349 if (msg->cm_fields['U'] == NULL)
350 msg->cm_fields['U'] = strdup(value);
354 else if (!strcasecmp(key, "To")) {
355 if (msg->cm_fields['R'] == NULL)
356 msg->cm_fields['R'] = strdup(value);
360 else if (!strcasecmp(key, "CC")) {
361 if (msg->cm_fields['Y'] == NULL)
362 msg->cm_fields['Y'] = strdup(value);
366 else if (!strcasecmp(key, "Message-ID")) {
367 if (msg->cm_fields['I'] != NULL) {
368 lprintf(CTDL_WARNING, "duplicate message id\n");
371 if (msg->cm_fields['I'] == NULL) {
372 msg->cm_fields['I'] = strdup(value);
374 /* Strip angle brackets */
375 while (haschar(msg->cm_fields['I'], '<') > 0) {
376 strcpy(&msg->cm_fields['I'][0],
377 &msg->cm_fields['I'][1]);
379 for (i = 0; i<strlen(msg->cm_fields['I']); ++i)
380 if (msg->cm_fields['I'][i] == '>')
381 msg->cm_fields['I'][i] = 0;
387 else if (!strcasecmp(key, "Return-Path")) {
388 if (msg->cm_fields['P'] == NULL)
389 msg->cm_fields['P'] = strdup(value);
393 else if (!strcasecmp(key, "Envelope-To")) {
394 if (msg->cm_fields['V'] == NULL)
395 msg->cm_fields['V'] = strdup(value);
399 /* Clean up and move on. */
400 free(key); /* Don't free 'value', it's actually the same buffer */
406 * Convert an RFC822 message (headers + body) to a CtdlMessage structure.
407 * NOTE: the supplied buffer becomes part of the CtdlMessage structure, and
408 * will be deallocated when CtdlFreeMessage() is called. Therefore, the
409 * supplied buffer should be DEREFERENCED. It should not be freed or used
412 struct CtdlMessage *convert_internet_message(char *rfc822) {
414 struct CtdlMessage *msg;
415 int pos, beg, end, msglen;
420 msg = malloc(sizeof(struct CtdlMessage));
421 if (msg == NULL) return msg;
423 memset(msg, 0, sizeof(struct CtdlMessage));
424 msg->cm_magic = CTDLMESSAGE_MAGIC; /* self check */
425 msg->cm_anon_type = 0; /* never anonymous */
426 msg->cm_format_type = FMT_RFC822; /* internet message */
427 msg->cm_fields['M'] = rfc822;
434 /* Locate beginning and end of field, keeping in mind that
435 * some fields might be multiline
440 msglen = strlen(rfc822);
441 while ( (end < 0) && (done == 0) ) {
443 if ((rfc822[pos]=='\n')
444 && (!isspace(rfc822[pos+1]))) {
448 /* done with headers? */
449 if ( (rfc822[pos]=='\n')
450 && ( (rfc822[pos+1]=='\n')
451 ||(rfc822[pos+1]=='\r')) ) {
456 if (pos >= (msglen-1) ) {
465 /* At this point we have a field. Are we interested in it? */
466 converted = convert_field(msg, beg, end);
468 /* Strip the field out of the RFC822 header if we used it */
470 strcpy(&rfc822[beg], &rfc822[pos]);
474 /* If we've hit the end of the message, bail out */
475 if (pos > strlen(rfc822)) done = 1;
478 /* Follow-up sanity checks... */
480 /* If there's no timestamp on this message, set it to now. */
481 if (msg->cm_fields['T'] == NULL) {
482 snprintf(buf, sizeof buf, "%ld", (long)time(NULL));
483 msg->cm_fields['T'] = strdup(buf);
492 * Look for a particular header field in an RFC822 message text. If the
493 * requested field is found, it is unfolded (if necessary) and returned to
494 * the caller. The field name is stripped out, leaving only its contents.
495 * The caller is responsible for freeing the returned buffer. If the requested
496 * field is not present, or anything else goes wrong, it returns NULL.
498 char *rfc822_fetch_field(char *rfc822, char *fieldname) {
499 char *fieldbuf = NULL;
500 char *end_of_headers;
506 /* Should never happen, but sometimes we get stupid */
507 if (rfc822 == NULL) return(NULL);
508 if (fieldname == NULL) return(NULL);
510 snprintf(fieldhdr, sizeof fieldhdr, "%s:", fieldname);
512 /* Locate the end of the headers, so we don't run past that point */
513 end_of_headers = bmstrcasestr(rfc822, "\n\r\n");
514 if (end_of_headers == NULL) {
515 end_of_headers = bmstrcasestr(rfc822, "\n\n");
517 if (end_of_headers == NULL) return (NULL);
519 field_start = bmstrcasestr(rfc822, fieldhdr);
520 if (field_start == NULL) return(NULL);
521 if (field_start > end_of_headers) return(NULL);
523 fieldbuf = malloc(SIZ);
524 strcpy(fieldbuf, "");
527 ptr = memreadline(ptr, fieldbuf, SIZ-strlen(fieldbuf) );
528 while ( (isspace(ptr[0])) && (ptr < end_of_headers) ) {
529 strcat(fieldbuf, " ");
530 cont = &fieldbuf[strlen(fieldbuf)];
531 ptr = memreadline(ptr, cont, SIZ-strlen(fieldbuf) );
535 strcpy(fieldbuf, &fieldbuf[strlen(fieldhdr)]);
543 /*****************************************************************************
544 * DIRECTORY MANAGEMENT FUNCTIONS *
545 *****************************************************************************/
548 * Generate the index key for an Internet e-mail address to be looked up
551 void directory_key(char *key, char *addr) {
555 for (i=0; i<strlen(addr); ++i) {
556 if (!isspace(addr[i])) {
557 key[keylen++] = tolower(addr[i]);
562 lprintf(CTDL_DEBUG, "Directory key is <%s>\n", key);
567 /* Return nonzero if the supplied address is in a domain we keep in
570 int IsDirectory(char *addr, int allow_masq_domains) {
574 extract_token(domain, addr, 1, '@', sizeof domain);
577 h = CtdlHostAlias(domain);
579 if ( (h == hostalias_masq) && allow_masq_domains)
582 if ( (h == hostalias_localhost) || (h == hostalias_directory) ) {
592 * Initialize the directory database (erasing anything already there)
594 void CtdlDirectoryInit(void) {
595 cdb_trunc(CDB_DIRECTORY);
600 * Add an Internet e-mail address to the directory for a user
602 void CtdlDirectoryAddUser(char *internet_addr, char *citadel_addr) {
605 lprintf(CTDL_DEBUG, "Dir: %s --> %s\n",
606 internet_addr, citadel_addr);
607 if (IsDirectory(internet_addr, 0) == 0) return;
609 directory_key(key, internet_addr);
611 cdb_store(CDB_DIRECTORY, key, strlen(key),
612 citadel_addr, strlen(citadel_addr)+1 );
617 * Delete an Internet e-mail address from the directory.
619 * (NOTE: we don't actually use or need the citadel_addr variable; it's merely
620 * here because the callback API expects to be able to send it.)
622 void CtdlDirectoryDelUser(char *internet_addr, char *citadel_addr) {
625 directory_key(key, internet_addr);
626 cdb_delete(CDB_DIRECTORY, key, strlen(key) );
631 * Look up an Internet e-mail address in the directory.
632 * On success: returns 0, and Citadel address stored in 'target'
633 * On failure: returns nonzero
635 int CtdlDirectoryLookup(char *target, char *internet_addr, size_t targbuflen) {
636 struct cdbdata *cdbrec;
639 /* Dump it in there unchanged, just for kicks */
640 safestrncpy(target, internet_addr, targbuflen);
642 /* Only do lookups for addresses with hostnames in them */
643 if (num_tokens(internet_addr, '@') != 2) return(-1);
645 /* Only do lookups for domains in the directory */
646 if (IsDirectory(internet_addr, 0) == 0) return(-1);
648 directory_key(key, internet_addr);
649 cdbrec = cdb_fetch(CDB_DIRECTORY, key, strlen(key) );
650 if (cdbrec != NULL) {
651 safestrncpy(target, cdbrec->ptr, targbuflen);
661 * Harvest any email addresses that someone might want to have in their
662 * "collected addresses" book.
664 char *harvest_collected_addresses(struct CtdlMessage *msg) {
667 char user[256], node[256], name[256];
672 if (msg == NULL) return(NULL);
676 if (msg->cm_fields['A'] != NULL) {
677 strcat(addr, msg->cm_fields['A']);
679 if (msg->cm_fields['F'] != NULL) {
681 strcat(addr, msg->cm_fields['F']);
683 if (IsDirectory(msg->cm_fields['F'], 0)) {
688 if (is_harvestable) {
695 if (coll == NULL) return(NULL);
697 /* Scan both the R (To) and Y (CC) fields */
698 for (i = 0; i < 2; ++i) {
699 if (i == 0) field = 'R' ;
700 if (i == 1) field = 'Y' ;
702 if (msg->cm_fields[field] != NULL) {
703 for (j=0; j<num_tokens(msg->cm_fields[field], ','); ++j) {
704 extract_token(addr, msg->cm_fields[field], j, ',', sizeof addr);
705 process_rfc822_addr(addr, user, node, name);
706 h = CtdlHostAlias(node);
707 if ( (h != hostalias_localhost) && (h != hostalias_directory) ) {
708 coll = realloc(coll, strlen(coll) + strlen(addr) + 4);
709 if (coll == NULL) return(NULL);
710 if (!IsEmptyStr(coll)) {
720 if (IsEmptyStr(coll)) {