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) {
120 if ( (!strncasecmp(matchstring, "cit", 3))
121 && (atol(&matchstring[3]) == us->usernum)) {
125 len = strlen(matchstring);
126 for (a=0; !IsEmptyStr(&us->fullname[a]); ++a) {
127 if (!strncasecmp(&us->fullname[a],
137 * Unfold a multi-line field into a single line, removing multi-whitespaces
139 void unfold_rfc822_field(char *field) {
143 striplt(field); /* remove leading/trailing whitespace */
145 /* convert non-space whitespace to spaces, and remove double blanks */
146 for (i=0; i<strlen(field); ++i) {
147 if (field[i]=='\"') quote = 1 - quote;
149 if (isspace(field[i])) field[i] = ' ';
150 while (isspace(field[i]) && isspace(field[i+1])) {
151 strcpy(&field[i+1], &field[i+2]);
160 * Split an RFC822-style address into userid, host, and full name
163 void process_rfc822_addr(const char *rfc822, char *user, char *node, char *name)
168 strcpy(node, config.c_fqdn);
171 if (rfc822 == NULL) return;
173 /* extract full name - first, it's From minus <userid> */
174 strcpy(name, rfc822);
175 stripout(name, '<', '>');
177 /* strip anything to the left of a bang */
178 while ((!IsEmptyStr(name)) && (haschar(name, '!') > 0))
179 strcpy(name, &name[1]);
181 /* and anything to the right of a @ or % */
182 for (a = 0; a < strlen(name); ++a) {
189 /* but if there are parentheses, that changes the rules... */
190 if ((haschar(rfc822, '(') == 1) && (haschar(rfc822, ')') == 1)) {
191 strcpy(name, rfc822);
192 stripallbut(name, '(', ')');
195 /* but if there are a set of quotes, that supersedes everything */
196 if (haschar(rfc822, 34) == 2) {
197 strcpy(name, rfc822);
198 while ((!IsEmptyStr(name)) && (name[0] != 34)) {
199 strcpy(&name[0], &name[1]);
201 strcpy(&name[0], &name[1]);
202 for (a = 0; a < strlen(name); ++a)
206 /* extract user id */
207 strcpy(user, rfc822);
209 /* first get rid of anything in parens */
210 stripout(user, '(', ')');
212 /* if there's a set of angle brackets, strip it down to that */
213 if ((haschar(user, '<') == 1) && (haschar(user, '>') == 1)) {
214 stripallbut(user, '<', '>');
217 /* strip anything to the left of a bang */
218 while ((!IsEmptyStr(user)) && (haschar(user, '!') > 0))
219 strcpy(user, &user[1]);
221 /* and anything to the right of a @ or % */
222 for (a = 0; a < strlen(user); ++a) {
230 /* extract node name */
231 strcpy(node, rfc822);
233 /* first get rid of anything in parens */
234 stripout(node, '(', ')');
236 /* if there's a set of angle brackets, strip it down to that */
237 if ((haschar(node, '<') == 1) && (haschar(node, '>') == 1)) {
238 stripallbut(node, '<', '>');
241 /* If no node specified, tack ours on instead */
243 (haschar(node, '@')==0)
244 && (haschar(node, '%')==0)
245 && (haschar(node, '!')==0)
247 strcpy(node, config.c_nodename);
252 /* strip anything to the left of a @ */
253 while ((!IsEmptyStr(node)) && (haschar(node, '@') > 0))
254 strcpy(node, &node[1]);
256 /* strip anything to the left of a % */
257 while ((!IsEmptyStr(node)) && (haschar(node, '%') > 0))
258 strcpy(node, &node[1]);
260 /* reduce multiple system bang paths to node!user */
261 while ((!IsEmptyStr(node)) && (haschar(node, '!') > 1))
262 strcpy(node, &node[1]);
264 /* now get rid of the user portion of a node!user string */
265 for (a = 0; a < strlen(node); ++a)
270 /* strip leading and trailing spaces in all strings */
275 /* If we processed a string that had the address in angle brackets
276 * but no name outside the brackets, we now have an empty name. In
277 * this case, use the user portion of the address as the name.
279 if ((IsEmptyStr(name)) && (!IsEmptyStr(user))) {
287 * convert_field() is a helper function for convert_internet_message().
288 * Given start/end positions for an rfc822 field, it converts it to a Citadel
289 * field if it wants to, and unfolds it if necessary.
291 * Returns 1 if the field was converted and inserted into the Citadel message
292 * structure, implying that the source field should be removed from the
295 int convert_field(struct CtdlMessage *msg, int beg, int end) {
308 rfc822 = msg->cm_fields['M']; /* M field contains rfc822 text */
309 for (i = end; i >= beg; --i) {
310 if (rfc822[i] == ':') colonpos = i;
313 if (colonpos < 0) return(0); /* no colon? not a valid header line */
315 key = malloc((end - beg) + 2);
316 safestrncpy(key, &rfc822[beg], (end-beg)+1);
317 key[colonpos - beg] = 0;
318 value = &key[(colonpos - beg) + 1];
319 unfold_rfc822_field(value);
322 * Here's the big rfc822-to-citadel loop.
325 /* Date/time is converted into a unix timestamp. If the conversion
326 * fails, we replace it with the time the message arrived locally.
328 if (!strcasecmp(key, "Date")) {
329 parsed_date = parsedate(value);
330 if (parsed_date < 0L) parsed_date = time(NULL);
331 snprintf(buf, sizeof buf, "%ld", (long)parsed_date );
332 if (msg->cm_fields['T'] == NULL)
333 msg->cm_fields['T'] = strdup(buf);
337 else if (!strcasecmp(key, "From")) {
338 process_rfc822_addr(value, user, node, name);
339 lprintf(CTDL_DEBUG, "Converted to <%s@%s> (%s)\n", user, node, name);
340 snprintf(addr, sizeof addr, "%s@%s", user, node);
341 if (msg->cm_fields['A'] == NULL)
342 msg->cm_fields['A'] = strdup(name);
344 if (msg->cm_fields['F'] == NULL)
345 msg->cm_fields['F'] = strdup(addr);
349 else if (!strcasecmp(key, "Subject")) {
350 if (msg->cm_fields['U'] == NULL)
351 msg->cm_fields['U'] = strdup(value);
355 else if (!strcasecmp(key, "To")) {
356 if (msg->cm_fields['R'] == NULL)
357 msg->cm_fields['R'] = strdup(value);
361 else if (!strcasecmp(key, "CC")) {
362 if (msg->cm_fields['Y'] == NULL)
363 msg->cm_fields['Y'] = strdup(value);
367 else if (!strcasecmp(key, "Message-ID")) {
368 if (msg->cm_fields['I'] != NULL) {
369 lprintf(CTDL_WARNING, "duplicate message id\n");
372 if (msg->cm_fields['I'] == NULL) {
373 msg->cm_fields['I'] = strdup(value);
375 /* Strip angle brackets */
376 while (haschar(msg->cm_fields['I'], '<') > 0) {
377 strcpy(&msg->cm_fields['I'][0],
378 &msg->cm_fields['I'][1]);
380 for (i = 0; i<strlen(msg->cm_fields['I']); ++i)
381 if (msg->cm_fields['I'][i] == '>')
382 msg->cm_fields['I'][i] = 0;
388 else if (!strcasecmp(key, "Return-Path")) {
389 if (msg->cm_fields['P'] == NULL)
390 msg->cm_fields['P'] = strdup(value);
394 else if (!strcasecmp(key, "Envelope-To")) {
395 if (msg->cm_fields['V'] == NULL)
396 msg->cm_fields['V'] = strdup(value);
400 /* Clean up and move on. */
401 free(key); /* Don't free 'value', it's actually the same buffer */
407 * Convert an RFC822 message (headers + body) to a CtdlMessage structure.
408 * NOTE: the supplied buffer becomes part of the CtdlMessage structure, and
409 * will be deallocated when CtdlFreeMessage() is called. Therefore, the
410 * supplied buffer should be DEREFERENCED. It should not be freed or used
413 struct CtdlMessage *convert_internet_message(char *rfc822) {
415 struct CtdlMessage *msg;
416 int pos, beg, end, msglen;
421 msg = malloc(sizeof(struct CtdlMessage));
422 if (msg == NULL) return msg;
424 memset(msg, 0, sizeof(struct CtdlMessage));
425 msg->cm_magic = CTDLMESSAGE_MAGIC; /* self check */
426 msg->cm_anon_type = 0; /* never anonymous */
427 msg->cm_format_type = FMT_RFC822; /* internet message */
428 msg->cm_fields['M'] = rfc822;
435 /* Locate beginning and end of field, keeping in mind that
436 * some fields might be multiline
441 msglen = strlen(rfc822);
442 while ( (end < 0) && (done == 0) ) {
444 if ((rfc822[pos]=='\n')
445 && (!isspace(rfc822[pos+1]))) {
449 /* done with headers? */
450 if ( (rfc822[pos]=='\n')
451 && ( (rfc822[pos+1]=='\n')
452 ||(rfc822[pos+1]=='\r')) ) {
457 if (pos >= (msglen-1) ) {
466 /* At this point we have a field. Are we interested in it? */
467 converted = convert_field(msg, beg, end);
469 /* Strip the field out of the RFC822 header if we used it */
471 strcpy(&rfc822[beg], &rfc822[pos]);
475 /* If we've hit the end of the message, bail out */
476 if (pos > strlen(rfc822)) done = 1;
479 /* Follow-up sanity checks... */
481 /* If there's no timestamp on this message, set it to now. */
482 if (msg->cm_fields['T'] == NULL) {
483 snprintf(buf, sizeof buf, "%ld", (long)time(NULL));
484 msg->cm_fields['T'] = strdup(buf);
493 * Look for a particular header field in an RFC822 message text. If the
494 * requested field is found, it is unfolded (if necessary) and returned to
495 * the caller. The field name is stripped out, leaving only its contents.
496 * The caller is responsible for freeing the returned buffer. If the requested
497 * field is not present, or anything else goes wrong, it returns NULL.
499 char *rfc822_fetch_field(char *rfc822, char *fieldname) {
500 char *fieldbuf = NULL;
501 char *end_of_headers;
507 /* Should never happen, but sometimes we get stupid */
508 if (rfc822 == NULL) return(NULL);
509 if (fieldname == NULL) return(NULL);
511 snprintf(fieldhdr, sizeof fieldhdr, "%s:", fieldname);
513 /* Locate the end of the headers, so we don't run past that point */
514 end_of_headers = bmstrcasestr(rfc822, "\n\r\n");
515 if (end_of_headers == NULL) {
516 end_of_headers = bmstrcasestr(rfc822, "\n\n");
518 if (end_of_headers == NULL) return (NULL);
520 field_start = bmstrcasestr(rfc822, fieldhdr);
521 if (field_start == NULL) return(NULL);
522 if (field_start > end_of_headers) return(NULL);
524 fieldbuf = malloc(SIZ);
525 strcpy(fieldbuf, "");
528 ptr = memreadline(ptr, fieldbuf, SIZ-strlen(fieldbuf) );
529 while ( (isspace(ptr[0])) && (ptr < end_of_headers) ) {
530 strcat(fieldbuf, " ");
531 cont = &fieldbuf[strlen(fieldbuf)];
532 ptr = memreadline(ptr, cont, SIZ-strlen(fieldbuf) );
536 strcpy(fieldbuf, &fieldbuf[strlen(fieldhdr)]);
544 /*****************************************************************************
545 * DIRECTORY MANAGEMENT FUNCTIONS *
546 *****************************************************************************/
549 * Generate the index key for an Internet e-mail address to be looked up
552 void directory_key(char *key, char *addr) {
556 for (i=0; !IsEmptyStr(&addr[i]); ++i) {
557 if (!isspace(addr[i])) {
558 key[keylen++] = tolower(addr[i]);
563 lprintf(CTDL_DEBUG, "Directory key is <%s>\n", key);
568 /* Return nonzero if the supplied address is in a domain we keep in
571 int IsDirectory(char *addr, int allow_masq_domains) {
575 extract_token(domain, addr, 1, '@', sizeof domain);
578 h = CtdlHostAlias(domain);
580 if ( (h == hostalias_masq) && allow_masq_domains)
583 if ( (h == hostalias_localhost) || (h == hostalias_directory) ) {
593 * Initialize the directory database (erasing anything already there)
595 void CtdlDirectoryInit(void) {
596 cdb_trunc(CDB_DIRECTORY);
601 * Add an Internet e-mail address to the directory for a user
603 void CtdlDirectoryAddUser(char *internet_addr, char *citadel_addr) {
606 lprintf(CTDL_DEBUG, "Dir: %s --> %s\n",
607 internet_addr, citadel_addr);
608 if (IsDirectory(internet_addr, 0) == 0) return;
610 directory_key(key, internet_addr);
612 cdb_store(CDB_DIRECTORY, key, strlen(key),
613 citadel_addr, strlen(citadel_addr)+1 );
618 * Delete an Internet e-mail address from the directory.
620 * (NOTE: we don't actually use or need the citadel_addr variable; it's merely
621 * here because the callback API expects to be able to send it.)
623 void CtdlDirectoryDelUser(char *internet_addr, char *citadel_addr) {
626 directory_key(key, internet_addr);
627 cdb_delete(CDB_DIRECTORY, key, strlen(key) );
632 * Look up an Internet e-mail address in the directory.
633 * On success: returns 0, and Citadel address stored in 'target'
634 * On failure: returns nonzero
636 int CtdlDirectoryLookup(char *target, char *internet_addr, size_t targbuflen) {
637 struct cdbdata *cdbrec;
640 /* Dump it in there unchanged, just for kicks */
641 safestrncpy(target, internet_addr, targbuflen);
643 /* Only do lookups for addresses with hostnames in them */
644 if (num_tokens(internet_addr, '@') != 2) return(-1);
646 /* Only do lookups for domains in the directory */
647 if (IsDirectory(internet_addr, 0) == 0) return(-1);
649 directory_key(key, internet_addr);
650 cdbrec = cdb_fetch(CDB_DIRECTORY, key, strlen(key) );
651 if (cdbrec != NULL) {
652 safestrncpy(target, cdbrec->ptr, targbuflen);
662 * Harvest any email addresses that someone might want to have in their
663 * "collected addresses" book.
665 char *harvest_collected_addresses(struct CtdlMessage *msg) {
668 char user[256], node[256], name[256];
673 if (msg == NULL) return(NULL);
677 if (msg->cm_fields['A'] != NULL) {
678 strcat(addr, msg->cm_fields['A']);
680 if (msg->cm_fields['F'] != NULL) {
682 strcat(addr, msg->cm_fields['F']);
684 if (IsDirectory(msg->cm_fields['F'], 0)) {
689 if (is_harvestable) {
696 if (coll == NULL) return(NULL);
698 /* Scan both the R (To) and Y (CC) fields */
699 for (i = 0; i < 2; ++i) {
700 if (i == 0) field = 'R' ;
701 if (i == 1) field = 'Y' ;
703 if (msg->cm_fields[field] != NULL) {
704 for (j=0; j<num_tokens(msg->cm_fields[field], ','); ++j) {
705 extract_token(addr, msg->cm_fields[field], j, ',', sizeof addr);
706 process_rfc822_addr(addr, user, node, name);
707 h = CtdlHostAlias(node);
708 if ( (h != hostalias_localhost) && (h != hostalias_directory) ) {
709 coll = realloc(coll, strlen(coll) + strlen(addr) + 4);
710 if (coll == NULL) return(NULL);
711 if (!IsEmptyStr(coll)) {
721 if (IsEmptyStr(coll)) {