1 // This file contains functions which handle the mapping of Internet addresses
2 // to users on the Citadel system.
4 // Copyright (c) 1987-2023 by the citadel.org team
6 // This program is open source software. Use, duplication, or disclosure
7 // is subject to the terms of the GNU General Public License, version 3.
18 #include <sys/types.h>
23 #include <libcitadel.h>
24 #include "citadel_defs.h"
26 #include "sysdep_decls.h"
27 #include "citserver.h"
31 #include "internet_addressing.h"
34 #include "parsedate.h"
36 #include "ctdl_module.h"
42 // Return nonzero if the supplied name is an alias for this host.
43 int CtdlHostAlias(char *fqdn) {
47 char host[256], type[256];
50 if (fqdn == NULL) return(hostalias_nomatch);
51 if (IsEmptyStr(fqdn)) return(hostalias_nomatch);
52 if (!strcasecmp(fqdn, "localhost")) return(hostalias_localhost);
53 if (!strcasecmp(fqdn, CtdlGetConfigStr("c_fqdn"))) return(hostalias_localhost);
54 if (!strcasecmp(fqdn, CtdlGetConfigStr("c_nodename"))) return(hostalias_localhost);
55 if (inetcfg == NULL) return(hostalias_nomatch);
57 config_lines = num_tokens(inetcfg, '\n');
58 for (i=0; i<config_lines; ++i) {
59 extract_token(buf, inetcfg, i, '\n', sizeof buf);
60 extract_token(host, buf, 0, '|', sizeof host);
61 extract_token(type, buf, 1, '|', sizeof type);
65 // Process these in a specific order, in case there are multiple matches.
66 // We want localhost to override masq, for example.
68 if ( (!strcasecmp(type, "masqdomain")) && (!strcasecmp(fqdn, host))) {
69 found = hostalias_masq;
72 if ( (!strcasecmp(type, "localhost")) && (!strcasecmp(fqdn, host))) {
73 found = hostalias_localhost;
76 // "directory" used to be a distributed version of "localhost" but they're both the same now
77 if ( (!strcasecmp(type, "directory")) && (!strcasecmp(fqdn, host))) {
78 found = hostalias_localhost;
81 if (found) return(found);
83 return(hostalias_nomatch);
87 // Determine whether a given Internet address belongs to the current user
88 int CtdlIsMe(char *addr, int addr_buf_len) {
89 struct recptypes *recp;
92 recp = validate_recipients(addr, NULL, 0);
93 if (recp == NULL) return(0);
95 if (recp->num_local == 0) {
96 free_recipients(recp);
100 for (i=0; i<recp->num_local; ++i) {
101 extract_token(addr, recp->recp_local, i, '|', addr_buf_len);
102 if (!strcasecmp(addr, CC->user.fullname)) {
103 free_recipients(recp);
108 free_recipients(recp);
113 // If the last item in a list of recipients was truncated to a partial address,
114 // remove it completely in order to avoid choking library functions.
115 void sanitize_truncated_recipient(char *str) {
117 if (num_tokens(str, ',') < 2) return;
119 int len = strlen(str);
120 if (len < 900) return;
121 if (len > 998) str[998] = 0;
123 char *cptr = strrchr(str, ',');
126 char *lptr = strchr(cptr, '<');
127 char *rptr = strchr(cptr, '>');
129 if ( (lptr) && (rptr) && (rptr > lptr) ) return;
135 // This function is self explanatory.
136 // (What can I say, I'm in a weird mood today...)
137 void remove_any_whitespace_to_the_left_or_right_of_at_symbol(char *name) {
141 for (ptr=name; *ptr; ++ptr) {
142 while ( (isspace(*ptr)) && (*(ptr+1)=='@') ) {
144 if (ptr > name) --ptr;
146 while ( (*ptr=='@') && (*(ptr+1)!=0) && (isspace(*(ptr+1))) ) {
147 strcpy(ptr+1, ptr+2);
153 // values that can be returned by expand_aliases()
155 EA_ERROR, // Can't send message due to bad address
156 EA_MULTIPLE, // Alias expanded into multiple recipients -- run me again!
157 EA_LOCAL, // Local message, do no network processing
158 EA_INTERNET, // Convert msg and send as Internet mail
159 EA_SKIP // This recipient has been invalidated -- skip it!
163 // Process alias and routing info for email addresses
164 int expand_aliases(char *name, char *aliases) {
170 int num_aliases = num_tokens(aliases, '\n');
171 for (a=0; a<num_aliases; ++a) {
172 extract_token(aaa, aliases, a, '\n', sizeof aaa);
173 char *bar = strchr(aaa, '|');
179 if ( (!IsEmptyStr(aaa)) && (!strcasecmp(name, aaa)) ) {
180 syslog(LOG_DEBUG, "internet_addressing: global alias <%s> to <%s>", name, bar);
185 if (strchr(name, ',')) {
190 char original_name[256]; // Now go for the regular aliases
191 safestrncpy(original_name, name, sizeof original_name);
193 // should these checks still be here, or maybe move them to split_recps() ?
195 remove_any_whitespace_to_the_left_or_right_of_at_symbol(name);
196 stripallbut(name, '<', '>');
198 // Hit the email address directory
199 if (CtdlDirectoryLookup(aaa, name, sizeof aaa) == 0) {
203 if (strcasecmp(original_name, name)) {
204 syslog(LOG_INFO, "internet_addressing: directory alias <%s> to <%s>", original_name, name);
207 // Change "user @ xxx" to "user" if xxx is an alias for this host
208 for (a=0; name[a] != '\0'; ++a) {
209 if (name[a] == '@') {
210 if (CtdlHostAlias(&name[a+1]) == hostalias_localhost) {
212 syslog(LOG_DEBUG, "internet_addressing: host is local, recipient is <%s>", name);
218 // Is this a local or remote recipient?
219 at = haschar(name, '@');
221 return(EA_LOCAL); // no @'s = local address
224 return(EA_INTERNET); // one @ = internet address
227 return(EA_ERROR); // more than one @ = badly formed address
232 // Return a supplied list of email addresses as an array, removing superfluous information and syntax.
233 // If an existing Array is supplied as "append_to" it will do so; otherwise a new Array is allocated.
234 Array *split_recps(char *addresses, Array *append_to) {
236 if (IsEmptyStr(addresses)) { // nothing supplied, nothing returned
240 // Copy the supplied address list into our own memory space, because we are going to modify it.
241 char *a = strdup(addresses);
243 syslog(LOG_ERR, "internet_addressing: malloc() failed: %m");
247 // Strip out anything in double quotes
252 r = strrchr(a, '\"');
258 // Transform all qualifying delimiters to commas
260 for (t=a; t[0]; ++t) {
261 if ((t[0]==';') || (t[0]=='|')) {
266 // Tokenize the recipients into an array. No single recipient should be larger than 256 bytes.
267 Array *recipients_array = NULL;
269 recipients_array = append_to; // Append to an existing array of recipients
272 recipients_array = array_new(256); // This is a new array of recipients
275 int num_addresses = num_tokens(a, ',');
277 for (i=0; i<num_addresses; ++i) {
278 char this_address[256];
279 extract_token(this_address, a, i, ',', sizeof this_address);
280 string_trim(this_address); // strip leading and trailing whitespace
281 stripout(this_address, '(', ')'); // remove any portion in parentheses
282 stripallbut(this_address, '<', '>'); // if angle brackets are present, keep only what is inside them
283 if (!IsEmptyStr(this_address)) {
284 array_append(recipients_array, this_address);
288 free(a); // We don't need this buffer anymore.
289 return(recipients_array); // Return the completed array to the caller.
293 // Validate recipients, count delivery types and errors, and handle aliasing
295 // Returns 0 if all addresses are ok, ret->num_error = -1 if no addresses
296 // were specified, or the number of addresses found invalid.
298 // Caller needs to free the result using free_recipients()
300 struct recptypes *validate_recipients(char *supplied_recipients, const char *RemoteIdentifier, int Flags) {
301 struct recptypes *ret;
302 char *recipients = NULL;
307 struct ctdluser tempUS;
308 struct ctdlroom original_room;
314 ret = (struct recptypes *) malloc(sizeof(struct recptypes)); // Initialize
315 if (ret == NULL) return(NULL);
316 memset(ret, 0, sizeof(struct recptypes)); // set all values to null/zero
318 if (supplied_recipients == NULL) {
319 recipients = strdup("");
322 recipients = strdup(supplied_recipients);
325 len = strlen(recipients) + 1024; // allocate memory
326 ret->errormsg = malloc(len);
327 ret->recp_local = malloc(len);
328 ret->recp_internet = malloc(len);
329 ret->recp_room = malloc(len);
330 ret->display_recp = malloc(len);
331 ret->recp_orgroom = malloc(len);
333 ret->errormsg[0] = 0;
334 ret->recp_local[0] = 0;
335 ret->recp_internet[0] = 0;
336 ret->recp_room[0] = 0;
337 ret->recp_orgroom[0] = 0;
338 ret->display_recp[0] = 0;
339 ret->recptypes_magic = RECPTYPES_MAGIC;
341 Array *recp_array = split_recps(supplied_recipients, NULL);
343 char *aliases = CtdlGetSysConfig(GLOBAL_ALIASES); // First hit the Global Alias Table
346 for (r=0; (recp_array && r<array_len(recp_array)); ++r) {
347 org_recp = (char *)array_get_element_at(recp_array, r);
348 strncpy(this_recp, org_recp, sizeof this_recp);
351 for (i=0; i<3; ++i) { // pass three times through the aliaser
352 mailtype = expand_aliases(this_recp, aliases);
354 // If an alias expanded to multiple recipients, strip off those recipients and append them
355 // to the end of the array. This loop will hit those again when it gets there.
356 if (mailtype == EA_MULTIPLE) {
357 recp_array = split_recps(this_recp, recp_array);
361 // This loop searches for duplicate recipients in the final list and marks them to be skipped.
363 for (j=0; j<r; ++j) {
364 if (!strcasecmp(this_recp, (char *)array_get_element_at(recp_array, j) )) {
369 syslog(LOG_DEBUG, "Recipient #%d of type %d is <%s>", r, mailtype, this_recp);
373 case EA_LOCAL: // There are several types of "local" recipients.
375 // Old BBS conventions require mail to "sysop" to go somewhere. Send it to the admin room.
376 if (!strcasecmp(this_recp, "sysop")) {
378 strcpy(this_recp, CtdlGetConfigStr("c_aideroom"));
379 if (!IsEmptyStr(ret->recp_room)) {
380 strcat(ret->recp_room, "|");
382 strcat(ret->recp_room, this_recp);
385 // This handles rooms which can receive posts via email.
386 else if (!strncasecmp(this_recp, "room_", 5)) {
387 original_room = CC->room; // Remember where we parked
389 char mail_to_room[ROOMNAMELEN];
391 strncpy(mail_to_room, &this_recp[5], sizeof mail_to_room);
392 for (m = mail_to_room; *m; ++m) {
393 if (m[0] == '_') m[0]=' ';
395 if (!CtdlGetRoom(&CC->room, mail_to_room)) { // Find the room they asked for
397 err = CtdlDoIHavePermissionToPostInThisRoom( // check for write permissions to room
401 0 // 0 means "this is not a reply"
409 if (!IsEmptyStr(ret->recp_room)) {
410 strcat(ret->recp_room, "|");
412 strcat(ret->recp_room, CC->room.QRname);
414 if (!IsEmptyStr(ret->recp_orgroom)) {
415 strcat(ret->recp_orgroom, "|");
417 strcat(ret->recp_orgroom, this_recp);
421 else { // no such room exists
426 // Restore this session's original room location.
427 CC->room = original_room;
431 // This handles the most common case, which is mail to a user's inbox.
432 // (the next line depends on left-to-right evaluation)
433 else if ((CtdlGetUser(&tempUS, this_recp) == 0) && (tempUS.usernum > 0)) {
435 strcpy(this_recp, tempUS.fullname);
436 if (!IsEmptyStr(ret->recp_local)) {
437 strcat(ret->recp_local, "|");
439 strcat(ret->recp_local, this_recp);
442 // No match for this recipient
449 // Yes, you're reading this correctly: if the target domain points back to the local system,
450 // the address is invalid. That's because if the address were valid, we would have
451 // already translated it to a local address by now.
452 if (IsDirectory(this_recp, 0)) {
458 if (!IsEmptyStr(ret->recp_internet)) {
459 strcat(ret->recp_internet, "|");
461 strcat(ret->recp_internet, this_recp);
466 // no action required, anything in this slot has already been processed elsewhere
474 if (IsEmptyStr(errmsg)) {
475 snprintf(append, sizeof append, "Invalid recipient: %s", this_recp);
478 snprintf(append, sizeof append, "%s", errmsg);
480 if ( (strlen(ret->errormsg) + strlen(append) + 3) < SIZ) {
481 if (!IsEmptyStr(ret->errormsg)) {
482 strcat(ret->errormsg, "; ");
484 strcat(ret->errormsg, append);
488 if (IsEmptyStr(ret->display_recp)) {
489 strcpy(append, this_recp);
492 snprintf(append, sizeof append, ", %s", this_recp);
494 if ( (strlen(ret->display_recp)+strlen(append)) < SIZ) {
495 strcat(ret->display_recp, append);
500 if (aliases != NULL) { // ok, we're done with the global alias list now
504 if ( (ret->num_local + ret->num_internet + ret->num_room + ret->num_error) == 0) {
505 ret->num_error = (-1);
506 strcpy(ret->errormsg, "No recipients specified.");
509 syslog(LOG_DEBUG, "internet_addressing: validate_recipients() = %d local, %d room, %d SMTP, %d error",
510 ret->num_local, ret->num_room, ret->num_internet, ret->num_error
515 array_free(recp_array);
522 // Destructor for recptypes
523 void free_recipients(struct recptypes *valid) {
529 if (valid->recptypes_magic != RECPTYPES_MAGIC) {
530 syslog(LOG_ERR, "internet_addressing: attempt to call free_recipients() on some other data type!");
531 exit(CTDLEXIT_BAD_MAGIC);
534 if (valid->errormsg != NULL) free(valid->errormsg);
535 if (valid->recp_local != NULL) free(valid->recp_local);
536 if (valid->recp_internet != NULL) free(valid->recp_internet);
537 if (valid->recp_room != NULL) free(valid->recp_room);
538 if (valid->recp_orgroom != NULL) free(valid->recp_orgroom);
539 if (valid->display_recp != NULL) free(valid->display_recp);
540 if (valid->bounce_to != NULL) free(valid->bounce_to);
541 if (valid->envelope_from != NULL) free(valid->envelope_from);
542 if (valid->sending_room != NULL) free(valid->sending_room);
547 char *qp_encode_email_addrs(char *source) {
548 char *user, *node, *name;
549 const char headerStr[] = "=?UTF-8?Q?";
553 int need_to_encode = 0;
559 long nAddrPtrMax = 50;
564 if (source == NULL) return source;
565 if (IsEmptyStr(source)) return source;
566 syslog(LOG_DEBUG, "internet_addressing: qp_encode_email_addrs <%s>", source);
568 AddrPtr = malloc (sizeof (long) * nAddrPtrMax);
569 AddrUtf8 = malloc (sizeof (long) * nAddrPtrMax);
570 memset(AddrUtf8, 0, sizeof (long) * nAddrPtrMax);
573 while (!IsEmptyStr (&source[i])) {
574 if (nColons >= nAddrPtrMax){
577 ptr = (long *) malloc(sizeof (long) * nAddrPtrMax * 2);
578 memcpy (ptr, AddrPtr, sizeof (long) * nAddrPtrMax);
579 free (AddrPtr), AddrPtr = ptr;
581 ptr = (long *) malloc(sizeof (long) * nAddrPtrMax * 2);
582 memset(&ptr[nAddrPtrMax], 0, sizeof (long) * nAddrPtrMax);
584 memcpy (ptr, AddrUtf8, sizeof (long) * nAddrPtrMax);
585 free (AddrUtf8), AddrUtf8 = ptr;
588 if (((unsigned char) source[i] < 32) || ((unsigned char) source[i] > 126)) {
590 AddrUtf8[nColons] = 1;
592 if (source[i] == '"') {
593 InQuotes = !InQuotes;
595 if (!InQuotes && source[i] == ',') {
596 AddrPtr[nColons] = i;
601 if (need_to_encode == 0) {
608 EncodedMaxLen = nColons * (sizeof(headerStr) + 3) + SourceLen * 3;
609 Encoded = (char*) malloc (EncodedMaxLen);
611 for (i = 0; i < nColons; i++) {
612 source[AddrPtr[i]++] = '\0';
614 // TODO: if libidn, this might get larger
615 user = malloc(SourceLen + 1);
616 node = malloc(SourceLen + 1);
617 name = malloc(SourceLen + 1);
621 for (i = 0; i < nColons && nPtr != NULL; i++) {
622 nmax = EncodedMaxLen - (nPtr - Encoded);
624 process_rfc822_addr(&source[AddrPtr[i]], user, node, name);
625 // TODO: libIDN here !
626 if (IsEmptyStr(name)) {
627 n = snprintf(nPtr, nmax, (i==0)?"%s@%s" : ",%s@%s", user, node);
630 EncodedName = rfc2047encode(name, strlen(name));
631 n = snprintf(nPtr, nmax, (i==0)?"%s <%s@%s>" : ",%s <%s@%s>", EncodedName, user, node);
636 n = snprintf(nPtr, nmax, (i==0)?"%s" : ",%s", &source[AddrPtr[i]]);
642 ptr = (char*) malloc(EncodedMaxLen * 2);
643 memcpy(ptr, Encoded, EncodedMaxLen);
644 nnPtr = ptr + (nPtr - Encoded), nPtr = nnPtr;
645 free(Encoded), Encoded = ptr;
647 i--; // do it once more with properly lengthened buffer
650 for (i = 0; i < nColons; i++)
651 source[--AddrPtr[i]] = ',';
662 // Unfold a multi-line field into a single line, removing multi-whitespaces
663 void unfold_rfc822_field(char **field, char **FieldEnd)
666 char *pField = *field;
668 char *pFieldEnd = *FieldEnd;
670 while (isspace(*pField))
672 // remove leading/trailing whitespace
675 while (isspace(*pFieldEnd))
678 *FieldEnd = pFieldEnd;
679 // convert non-space whitespace to spaces, and remove double blanks
680 for (sField = *field = pField;
684 if ((*sField=='\r') || (*sField=='\n'))
687 while ( ( (*(sField + offset) == '\r') || (*(sField + offset) == '\n' )) && (sField + offset < pFieldEnd) ) {
694 if (*sField=='\"') quote = 1 - quote;
696 if (isspace(*sField)) {
701 while ((sField < pFieldEnd) &&
706 else *pField = *sField;
708 else *pField = *sField;
712 *FieldEnd = pField - 1;
716 // Split an RFC822-style address into userid, host, and full name
717 void process_rfc822_addr(const char *rfc822, char *user, char *node, char *name) {
721 strcpy(node, CtdlGetConfigStr("c_fqdn"));
724 if (rfc822 == NULL) return;
726 // extract full name - first, it's From minus <userid>
727 strcpy(name, rfc822);
728 stripout(name, '<', '>');
730 // and anything to the right of a @
731 for (a = 0; name[a] != '\0'; ++a) {
732 if (name[a] == '@') {
738 // but if there are parentheses, that changes the rules...
739 if ((haschar(rfc822, '(') == 1) && (haschar(rfc822, ')') == 1)) {
740 strcpy(name, rfc822);
741 stripallbut(name, '(', ')');
744 // but if there are a set of quotes, that supersedes everything
745 if (haschar(rfc822, 34) == 2) {
746 strcpy(name, rfc822);
747 while ((!IsEmptyStr(name)) && (name[0] != 34)) {
748 strcpy(&name[0], &name[1]);
750 strcpy(&name[0], &name[1]);
751 for (a = 0; name[a] != '\0'; ++a)
758 strcpy(user, rfc822);
760 // first get rid of anything in parens
761 stripout(user, '(', ')');
763 // if there's a set of angle brackets, strip it down to that
764 if ((haschar(user, '<') == 1) && (haschar(user, '>') == 1)) {
765 stripallbut(user, '<', '>');
768 // and anything to the right of a @
769 for (a = 0; user[a] != '\0'; ++a) {
770 if (user[a] == '@') {
777 strcpy(node, rfc822);
779 // first get rid of anything in parens
780 stripout(node, '(', ')');
782 // if there's a set of angle brackets, strip it down to that
783 if ((haschar(node, '<') == 1) && (haschar(node, '>') == 1)) {
784 stripallbut(node, '<', '>');
787 // If no node specified, tack ours on instead
788 if (haschar(node, '@') == 0) {
789 strcpy(node, CtdlGetConfigStr("c_nodename"));
792 // strip anything to the left of a @
793 while ((!IsEmptyStr(node)) && (haschar(node, '@') > 0)) {
794 strcpy(node, &node[1]);
798 // strip leading and trailing spaces in all strings
803 // If we processed a string that had the address in angle brackets
804 // but no name outside the brackets, we now have an empty name. In
805 // this case, use the user portion of the address as the name.
806 if ((IsEmptyStr(name)) && (!IsEmptyStr(user))) {
812 // convert_field() is a helper function for convert_internet_message().
813 // Given start/end positions for an rfc822 field, it converts it to a Citadel
814 // field if it wants to, and unfolds it if necessary.
816 // Returns 1 if the field was converted and inserted into the Citadel message
817 // structure, implying that the source field should be removed from the
819 int convert_field(struct CtdlMessage *msg, const char *beg, const char *end) {
820 char *key, *value, *valueend;
824 const char *colonpos = NULL;
833 for (pos = end; pos >= beg; pos--) {
834 if (*pos == ':') colonpos = pos;
837 if (colonpos == NULL) return(0); /* no colon? not a valid header line */
840 key = malloc(len + 2);
841 memcpy(key, beg, len + 1);
843 valueend = key + len;
844 * ( key + (colonpos - beg) ) = '\0';
845 value = &key[(colonpos - beg) + 1];
846 // printf("Header: [%s]\nValue: [%s]\n", key, value);
847 unfold_rfc822_field(&value, &valueend);
848 valuelen = valueend - value + 1;
849 // printf("UnfoldedValue: [%s]\n", value);
851 // Here's the big rfc822-to-citadel loop.
853 // Date/time is converted into a unix timestamp. If the conversion
854 // fails, we replace it with the time the message arrived locally.
855 if (!strcasecmp(key, "Date")) {
856 parsed_date = parsedate(value);
857 if (parsed_date < 0L) parsed_date = time(NULL);
859 if (CM_IsEmpty(msg, eTimestamp))
860 CM_SetFieldLONG(msg, eTimestamp, parsed_date);
864 else if (!strcasecmp(key, "From")) {
865 process_rfc822_addr(value, user, node, name);
866 syslog(LOG_DEBUG, "internet_addressing: converted to <%s@%s> (%s)", user, node, name);
867 snprintf(addr, sizeof(addr), "%s@%s", user, node);
868 if (CM_IsEmpty(msg, eAuthor) && !IsEmptyStr(name)) {
869 CM_SetField(msg, eAuthor, name);
871 if (CM_IsEmpty(msg, erFc822Addr) && !IsEmptyStr(addr)) {
872 CM_SetField(msg, erFc822Addr, addr);
877 else if (!strcasecmp(key, "Subject")) {
878 if (CM_IsEmpty(msg, eMsgSubject))
879 CM_SetField(msg, eMsgSubject, value);
883 else if (!strcasecmp(key, "List-ID")) {
884 if (CM_IsEmpty(msg, eListID))
885 CM_SetField(msg, eListID, value);
889 else if (!strcasecmp(key, "To")) {
890 if (CM_IsEmpty(msg, eRecipient))
891 CM_SetField(msg, eRecipient, value);
895 else if (!strcasecmp(key, "CC")) {
896 if (CM_IsEmpty(msg, eCarbonCopY))
897 CM_SetField(msg, eCarbonCopY, value);
901 else if (!strcasecmp(key, "Message-ID")) {
902 if (!CM_IsEmpty(msg, emessageId)) {
903 syslog(LOG_WARNING, "internet_addressing: duplicate message id");
910 pValueLen = valuelen;
911 // Strip angle brackets
912 while (haschar(pValue, '<') > 0) {
917 for (i = 0; i <= pValueLen; ++i)
918 if (pValue[i] == '>') {
923 CM_SetField(msg, emessageId, pValue);
929 else if (!strcasecmp(key, "Return-Path")) {
930 if (CM_IsEmpty(msg, eMessagePath))
931 CM_SetField(msg, eMessagePath, value);
935 else if (!strcasecmp(key, "Envelope-To")) {
936 if (CM_IsEmpty(msg, eenVelopeTo))
937 CM_SetField(msg, eenVelopeTo, value);
941 else if (!strcasecmp(key, "References")) {
942 CM_SetField(msg, eWeferences, value);
946 else if (!strcasecmp(key, "Reply-To")) {
947 CM_SetField(msg, eReplyTo, value);
951 else if (!strcasecmp(key, "In-reply-to")) {
952 if (CM_IsEmpty(msg, eWeferences)) // References: supersedes In-reply-to:
953 CM_SetField(msg, eWeferences, value);
959 // Clean up and move on.
960 free(key); // Don't free 'value', it's actually the same buffer
965 // Convert RFC822 references format (References) to Citadel references format (Weferences)
966 void convert_references_to_wefewences(char *str) {
967 int bracket_nesting = 0;
969 char *moveptr = NULL;
976 if (bracket_nesting < 0) bracket_nesting = 0;
978 if ((ch == '>') && (bracket_nesting == 0) && (*(ptr+1)) && (ptr>str) ) {
982 else if (bracket_nesting > 0) {
988 *moveptr = *(moveptr+1);
992 if (ch == '<') ++bracket_nesting;
998 // Convert an RFC822 message (headers + body) to a CtdlMessage structure.
999 // NOTE: the supplied buffer becomes part of the CtdlMessage structure, and
1000 // will be deallocated when CM_Free() is called. Therefore, the
1001 // supplied buffer should be DEREFERENCED. It should not be freed or used
1003 struct CtdlMessage *convert_internet_message(char *rfc822) {
1004 StrBuf *RFCBuf = NewStrBufPlain(rfc822, -1);
1006 return convert_internet_message_buf(&RFCBuf);
1010 struct CtdlMessage *convert_internet_message_buf(StrBuf **rfc822) {
1011 struct CtdlMessage *msg;
1012 const char *pos, *beg, *end, *totalend;
1013 int done, alldone = 0;
1015 StrBuf *OtherHeaders;
1017 msg = malloc(sizeof(struct CtdlMessage));
1018 if (msg == NULL) return msg;
1020 memset(msg, 0, sizeof(struct CtdlMessage));
1021 msg->cm_magic = CTDLMESSAGE_MAGIC; // self check
1022 msg->cm_anon_type = 0; // never anonymous
1023 msg->cm_format_type = FMT_RFC822; // internet message
1025 pos = ChrPtr(*rfc822);
1026 totalend = pos + StrLength(*rfc822);
1028 OtherHeaders = NewStrBufPlain(NULL, StrLength(*rfc822));
1032 /* Locate beginning and end of field, keeping in mind that
1033 * some fields might be multiline
1037 while ((end < totalend) && (end == beg) && (done == 0) ) {
1039 if ( (*pos=='\n') && ((*(pos+1))!=0x20) && ((*(pos+1))!=0x09) ) {
1043 /* done with headers? */
1044 if ((*pos=='\n') && ( (*(pos+1)=='\n') || (*(pos+1)=='\r')) ) {
1048 if (pos >= (totalend - 1) ) {
1057 /* At this point we have a field. Are we interested in it? */
1058 converted = convert_field(msg, beg, end);
1060 /* Strip the field out of the RFC822 header if we used it */
1062 StrBufAppendBufPlain(OtherHeaders, beg, end - beg, 0);
1063 StrBufAppendBufPlain(OtherHeaders, HKEY("\n"), 0);
1066 /* If we've hit the end of the message, bail out */
1067 if (pos >= totalend)
1070 StrBufAppendBufPlain(OtherHeaders, HKEY("\n"), 0);
1072 StrBufAppendBufPlain(OtherHeaders, pos, totalend - pos, 0);
1074 CM_SetAsFieldSB(msg, eMesageText, &OtherHeaders);
1076 /* Follow-up sanity checks... */
1078 /* If there's no timestamp on this message, set it to now. */
1079 if (CM_IsEmpty(msg, eTimestamp)) {
1080 CM_SetFieldLONG(msg, eTimestamp, time(NULL));
1083 /* If a W (references, or rather, Wefewences) field is present, we
1084 * have to convert it from RFC822 format to Citadel format.
1086 if (!CM_IsEmpty(msg, eWeferences)) {
1088 convert_references_to_wefewences(msg->cm_fields[eWeferences]);
1096 * Look for a particular header field in an RFC822 message text. If the
1097 * requested field is found, it is unfolded (if necessary) and returned to
1098 * the caller. The field name is stripped out, leaving only its contents.
1099 * The caller is responsible for freeing the returned buffer. If the requested
1100 * field is not present, or anything else goes wrong, it returns NULL.
1102 char *rfc822_fetch_field(const char *rfc822, const char *fieldname) {
1103 char *fieldbuf = NULL;
1104 const char *end_of_headers;
1105 const char *field_start;
1110 /* Should never happen, but sometimes we get stupid */
1111 if (rfc822 == NULL) return(NULL);
1112 if (fieldname == NULL) return(NULL);
1114 snprintf(fieldhdr, sizeof fieldhdr, "%s:", fieldname);
1116 /* Locate the end of the headers, so we don't run past that point */
1117 end_of_headers = cbmstrcasestr(rfc822, "\n\r\n");
1118 if (end_of_headers == NULL) {
1119 end_of_headers = cbmstrcasestr(rfc822, "\n\n");
1121 if (end_of_headers == NULL) return (NULL);
1123 field_start = cbmstrcasestr(rfc822, fieldhdr);
1124 if (field_start == NULL) return(NULL);
1125 if (field_start > end_of_headers) return(NULL);
1127 fieldbuf = malloc(SIZ);
1128 strcpy(fieldbuf, "");
1131 ptr = cmemreadline(ptr, fieldbuf, SIZ-strlen(fieldbuf) );
1132 while ( (isspace(ptr[0])) && (ptr < end_of_headers) ) {
1133 strcat(fieldbuf, " ");
1134 cont = &fieldbuf[strlen(fieldbuf)];
1135 ptr = cmemreadline(ptr, cont, SIZ-strlen(fieldbuf) );
1139 strcpy(fieldbuf, &fieldbuf[strlen(fieldhdr)]);
1140 string_trim(fieldbuf);
1146 /*****************************************************************************
1147 * DIRECTORY MANAGEMENT FUNCTIONS *
1148 *****************************************************************************/
1151 * Generate the index key for an Internet e-mail address to be looked up
1154 void directory_key(char *key, char *addr) {
1158 for (i=0; !IsEmptyStr(&addr[i]); ++i) {
1159 if (!isspace(addr[i])) {
1160 key[keylen++] = tolower(addr[i]);
1165 syslog(LOG_DEBUG, "internet_addressing: directory key is <%s>", key);
1170 * Return nonzero if the supplied address is in one of "our" domains
1172 int IsDirectory(char *addr, int allow_masq_domains) {
1176 extract_token(domain, addr, 1, '@', sizeof domain);
1177 string_trim(domain);
1179 h = CtdlHostAlias(domain);
1181 if ( (h == hostalias_masq) && allow_masq_domains)
1184 if (h == hostalias_localhost) {
1194 * Add an Internet e-mail address to the directory for a user
1196 int CtdlDirectoryAddUser(char *internet_addr, char *citadel_addr) {
1199 if (IsDirectory(internet_addr, 0) == 0) {
1202 syslog(LOG_DEBUG, "internet_addressing: create directory entry: %s --> %s", internet_addr, citadel_addr);
1203 directory_key(key, internet_addr);
1204 cdb_store(CDB_DIRECTORY, key, strlen(key), citadel_addr, strlen(citadel_addr)+1 );
1210 * Delete an Internet e-mail address from the directory.
1212 * (NOTE: we don't actually use or need the citadel_addr variable; it's merely
1213 * here because the callback API expects to be able to send it.)
1215 int CtdlDirectoryDelUser(char *internet_addr, char *citadel_addr) {
1218 syslog(LOG_DEBUG, "internet_addressing: delete directory entry: %s --> %s", internet_addr, citadel_addr);
1219 directory_key(key, internet_addr);
1220 return cdb_delete(CDB_DIRECTORY, key, strlen(key) ) == 0;
1225 * Look up an Internet e-mail address in the directory.
1226 * On success: returns 0, and Citadel address stored in 'target'
1227 * On failure: returns nonzero
1229 int CtdlDirectoryLookup(char *target, char *internet_addr, size_t targbuflen) {
1230 struct cdbdata cdbrec;
1233 /* Dump it in there unchanged, just for kicks */
1234 if (target != NULL) {
1235 safestrncpy(target, internet_addr, targbuflen);
1238 /* Only do lookups for addresses with hostnames in them */
1239 if (num_tokens(internet_addr, '@') != 2) return(-1);
1241 /* Only do lookups for domains in the directory */
1242 if (IsDirectory(internet_addr, 0) == 0) return(-1);
1244 directory_key(key, internet_addr);
1245 cdbrec = cdb_fetch(CDB_DIRECTORY, key, strlen(key));
1246 if (cdbrec.ptr != NULL) {
1247 if (target != NULL) {
1248 safestrncpy(target, cdbrec.ptr, targbuflen);
1258 * Harvest any email addresses that someone might want to have in their
1259 * "collected addresses" book.
1261 char *harvest_collected_addresses(struct CtdlMessage *msg) {
1264 char user[256], node[256], name[256];
1267 eMsgField field = 0;
1269 if (msg == NULL) return(NULL);
1273 if (!CM_IsEmpty(msg, eAuthor)) {
1274 strcat(addr, msg->cm_fields[eAuthor]);
1276 if (!CM_IsEmpty(msg, erFc822Addr)) {
1278 strcat(addr, msg->cm_fields[erFc822Addr]);
1280 if (IsDirectory(msg->cm_fields[erFc822Addr], 0)) {
1285 if (is_harvestable) {
1286 coll = strdup(addr);
1292 if (coll == NULL) return(NULL);
1294 /* Scan both the R (To) and Y (CC) fields */
1295 for (i = 0; i < 2; ++i) {
1296 if (i == 0) field = eRecipient;
1297 if (i == 1) field = eCarbonCopY;
1299 if (!CM_IsEmpty(msg, field)) {
1300 for (j=0; j<num_tokens(msg->cm_fields[field], ','); ++j) {
1301 extract_token(addr, msg->cm_fields[field], j, ',', sizeof addr);
1302 if (strstr(addr, "=?") != NULL) {
1303 utf8ify_rfc822_string(addr);
1305 process_rfc822_addr(addr, user, node, name);
1306 h = CtdlHostAlias(node);
1307 if (h != hostalias_localhost) {
1308 coll = realloc(coll, strlen(coll) + strlen(addr) + 4);
1309 if (coll == NULL) return(NULL);
1310 if (!IsEmptyStr(coll)) {
1320 if (IsEmptyStr(coll)) {
1329 * Helper function for CtdlRebuildDirectoryIndex()
1331 void CtdlRebuildDirectoryIndex_backend(char *username, void *data) {
1334 struct ctdluser usbuf;
1336 if (CtdlGetUser(&usbuf, username) != 0) {
1340 if ( (!IsEmptyStr(usbuf.fullname)) && (!IsEmptyStr(usbuf.emailaddrs)) ) {
1341 for (j=0; j<num_tokens(usbuf.emailaddrs, '|'); ++j) {
1342 char one_email[512];
1343 extract_token(one_email, usbuf.emailaddrs, j, '|', sizeof one_email);
1344 CtdlDirectoryAddUser(one_email, usbuf.fullname);
1351 * Initialize the directory database (erasing anything already there)
1353 void CtdlRebuildDirectoryIndex(void) {
1354 syslog(LOG_INFO, "internet_addressing: rebuilding email address directory index");
1355 cdb_trunc(CDB_DIRECTORY);
1356 ForEachUser(CtdlRebuildDirectoryIndex_backend, NULL);
1360 // Configure Internet email addresses for a user account, updating the Directory Index in the process
1361 void CtdlSetEmailAddressesForUser(char *requested_user, char *new_emailaddrs) {
1362 struct ctdluser usbuf;
1366 if (CtdlGetUserLock(&usbuf, requested_user) != 0) { // We can lock because the DirectoryIndex functions don't lock.
1367 return; // Silently fail here if the specified user does not exist.
1370 syslog(LOG_DEBUG, "internet_addressing: setting email addresses for <%s> to <%s>", usbuf.fullname, new_emailaddrs);
1372 // Delete all of the existing directory index records for the user (easier this way)
1373 for (i=0; i<num_tokens(usbuf.emailaddrs, '|'); ++i) {
1374 extract_token(buf, usbuf.emailaddrs, i, '|', sizeof buf);
1375 CtdlDirectoryDelUser(buf, requested_user);
1378 strcpy(usbuf.emailaddrs, new_emailaddrs); // make it official.
1380 // Index all of the new email addresses (they've already been sanitized)
1381 for (i=0; i<num_tokens(usbuf.emailaddrs, '|'); ++i) {
1382 extract_token(buf, usbuf.emailaddrs, i, '|', sizeof buf);
1383 CtdlDirectoryAddUser(buf, requested_user);
1386 CtdlPutUserLock(&usbuf);
1391 * Auto-generate an Internet email address for a user account
1393 void AutoGenerateEmailAddressForUser(struct ctdluser *user) {
1394 char synthetic_email_addr[1024];
1398 for (i=0; u==0; ++i) {
1400 // first try just converting the user name to lowercase and replacing spaces with underscores
1401 snprintf(synthetic_email_addr, sizeof synthetic_email_addr, "%s@%s", user->fullname, CtdlGetConfigStr("c_fqdn"));
1402 for (j=0; ((synthetic_email_addr[j] != '\0')&&(synthetic_email_addr[j] != '@')); j++) {
1403 synthetic_email_addr[j] = tolower(synthetic_email_addr[j]);
1404 if (!isalnum(synthetic_email_addr[j])) {
1405 synthetic_email_addr[j] = '_';
1410 // then try 'ctdl' followed by the user number
1411 snprintf(synthetic_email_addr, sizeof synthetic_email_addr, "ctdl%08lx@%s", user->usernum, CtdlGetConfigStr("c_fqdn"));
1414 // oof. just keep trying other numbers until we find one
1415 snprintf(synthetic_email_addr, sizeof synthetic_email_addr, "ctdl%08x@%s", i, CtdlGetConfigStr("c_fqdn"));
1417 u = CtdlDirectoryLookup(NULL, synthetic_email_addr, 0);
1418 syslog(LOG_DEBUG, "user_ops: address <%s> lookup returned <%d>", synthetic_email_addr, u);
1421 CtdlSetEmailAddressesForUser(user->fullname, synthetic_email_addr);
1422 strncpy(CC->user.emailaddrs, synthetic_email_addr, sizeof(user->emailaddrs));
1423 syslog(LOG_DEBUG, "user_ops: auto-generated email address <%s> for <%s>", synthetic_email_addr, user->fullname);
1427 // Determine whether the supplied email address is subscribed to the supplied room's mailing list service.
1428 int is_email_subscribed_to_list(char *email, char *room_name) {
1429 struct ctdlroom room;
1431 char *roomnetconfig;
1434 if (CtdlGetRoom(&room, room_name)) {
1435 return(0); // room not found, so definitely not subscribed
1438 // If this room has the QR2_SMTP_PUBLIC flag set, anyone may email a post to this room, even non-subscribers.
1439 if (room.QRflags2 & QR2_SMTP_PUBLIC) {
1443 roomnum = room.QRnumber;
1444 roomnetconfig = LoadRoomNetConfigFile(roomnum);
1445 if (roomnetconfig == NULL) {
1449 // We're going to do a very sloppy match here and simply search for the specified email address
1450 // anywhere in the room's netconfig. If you don't like this, fix it yourself.
1451 if (bmstrcasestr(roomnetconfig, email)) {
1458 free(roomnetconfig);