moved whitespace around
[citadel.git] / citadel / server / internet_addressing.c
1 // This file contains functions which handle the mapping of Internet addresses
2 // to users on the Citadel system.
3 //
4 // Copyright (c) 1987-2024 by the citadel.org team
5 //
6 // This program is open source software.  Use, duplication, or disclosure is subject to the GNU General Public License version 3.
7
8 #include "sysdep.h"
9 #include <stdlib.h>
10 #include <unistd.h>
11 #include <stdio.h>
12 #include <fcntl.h>
13 #include <ctype.h>
14 #include <signal.h>
15 #include <pwd.h>
16 #include <errno.h>
17 #include <sys/types.h>
18 #include <time.h>
19 #include <sys/wait.h>
20 #include <string.h>
21 #include <limits.h>
22 #include <libcitadel.h>
23 #include "citadel_defs.h"
24 #include "server.h"
25 #include "sysdep_decls.h"
26 #include "citserver.h"
27 #include "support.h"
28 #include "config.h"
29 #include "msgbase.h"
30 #include "internet_addressing.h"
31 #include "user_ops.h"
32 #include "room_ops.h"
33 #include "parsedate.h"
34 #include "database.h"
35 #include "ctdl_module.h"
36
37
38 char *inetcfg = NULL;
39
40 // Return nonzero if the supplied name is an alias for this host.
41 int CtdlHostAlias(char *fqdn) {
42         int config_lines;
43         int i;
44         char buf[256];
45         char host[256], type[256];
46         int found = 0;
47
48         if (fqdn == NULL)                                       return(hostalias_nomatch);
49         if (IsEmptyStr(fqdn))                                   return(hostalias_nomatch);
50         if (!strcasecmp(fqdn, "localhost"))                     return(hostalias_localhost);
51         if (!strcasecmp(fqdn, CtdlGetConfigStr("c_fqdn")))      return(hostalias_localhost);
52         if (!strcasecmp(fqdn, CtdlGetConfigStr("c_nodename")))  return(hostalias_localhost);
53         if (inetcfg == NULL)                                    return(hostalias_nomatch);
54
55         config_lines = num_tokens(inetcfg, '\n');
56         for (i=0; i<config_lines; ++i) {
57                 extract_token(buf, inetcfg, i, '\n', sizeof buf);
58                 extract_token(host, buf, 0, '|', sizeof host);
59                 extract_token(type, buf, 1, '|', sizeof type);
60
61                 found = 0;
62
63                 // Process these in a specific order, in case there are multiple matches.
64                 // We want localhost to override masq, for example.
65
66                 if ( (!strcasecmp(type, "masqdomain")) && (!strcasecmp(fqdn, host))) {
67                         found = hostalias_masq;
68                 }
69
70                 if ( (!strcasecmp(type, "localhost")) && (!strcasecmp(fqdn, host))) {
71                         found = hostalias_localhost;
72                 }
73
74                 // "directory" used to be a distributed version of "localhost" but they're both the same now
75                 if ( (!strcasecmp(type, "directory")) && (!strcasecmp(fqdn, host))) {
76                         found = hostalias_localhost;
77                 }
78
79                 if (found) return(found);
80         }
81         return(hostalias_nomatch);
82 }
83
84
85 // Determine whether a given Internet address belongs to the current user
86 int CtdlIsMe(char *addr, int addr_buf_len) {
87         struct recptypes *recp;
88         int i;
89
90         recp = validate_recipients(addr, 0);
91         if (recp == NULL) return(0);
92
93         if (recp->num_local == 0) {
94                 free_recipients(recp);
95                 return(0);
96         }
97
98         for (i=0; i<recp->num_local; ++i) {
99                 extract_token(addr, recp->recp_local, i, '|', addr_buf_len);
100                 if (!strcasecmp(addr, CC->user.fullname)) {
101                         free_recipients(recp);
102                         return(1);
103                 }
104         }
105
106         free_recipients(recp);
107         return(0);
108 }
109
110
111 // If the last item in a list of recipients was truncated to a partial address,
112 // remove it completely in order to avoid choking library functions.
113 void sanitize_truncated_recipient(char *str) {
114         if (!str) return;
115         if (num_tokens(str, ',') < 2) return;
116
117         int len = strlen(str);
118         if (len < 900) return;
119         if (len > 998) str[998] = 0;
120
121         char *cptr = strrchr(str, ',');
122         if (!cptr) return;
123
124         char *lptr = strchr(cptr, '<');
125         char *rptr = strchr(cptr, '>');
126
127         if ( (lptr) && (rptr) && (rptr > lptr) ) return;
128
129         *cptr = 0;
130 }
131
132
133 // This function is self explanatory.
134 // (What can I say, I'm in a weird mood today...)
135 void remove_any_whitespace_to_the_left_or_right_of_at_symbol(char *name) {
136         char *ptr;
137         if (!name) return;
138
139         for (ptr=name; *ptr; ++ptr) {
140                 while ( (isspace(*ptr)) && (*(ptr+1)=='@') ) {
141                         strcpy(ptr, ptr+1);
142                         if (ptr > name) --ptr;
143                 }
144                 while ( (*ptr=='@') && (*(ptr+1)!=0) && (isspace(*(ptr+1))) ) {
145                         strcpy(ptr+1, ptr+2);
146                 }
147         }
148 }
149
150
151 // values that can be returned by expand_aliases()
152 enum {
153         EA_ERROR,               // Can't send message due to bad address
154         EA_MULTIPLE,            // Alias expanded into multiple recipients -- run me again!
155         EA_LOCAL,               // Local message, do no network processing
156         EA_INTERNET,            // Convert msg and send as Internet mail
157         EA_SKIP                 // This recipient has been invalidated -- skip it!
158 };
159
160
161 // Process alias and routing info for email addresses
162 int expand_aliases(char *name, char *aliases) {
163         int a;
164         char aaa[SIZ];
165         int at = 0;
166
167         if (aliases) {
168                 int num_aliases = num_tokens(aliases, '\n');
169                 for (a=0; a<num_aliases; ++a) {
170                         extract_token(aaa, aliases, a, '\n', sizeof aaa);
171                         char *bar = strchr(aaa, '|');
172                         if (bar) {
173                                 bar[0] = 0;
174                                 ++bar;
175                                 string_trim(aaa);
176                                 string_trim(bar);
177                                 if ( (!IsEmptyStr(aaa)) && (!strcasecmp(name, aaa)) ) {
178                                         syslog(LOG_DEBUG, "internet_addressing: global alias <%s> to <%s>", name, bar);
179                                         strcpy(name, bar);
180                                 }
181                         }
182                 }
183                 if (strchr(name, ',')) {
184                         return(EA_MULTIPLE);
185                 }
186         }
187
188         char original_name[256];                                // Now go for the regular aliases
189         safestrncpy(original_name, name, sizeof original_name);
190
191         // should these checks still be here, or maybe move them to split_recps() ?
192         string_trim(name);
193         remove_any_whitespace_to_the_left_or_right_of_at_symbol(name);
194         stripallbut(name, '<', '>');
195
196         // Hit the email address directory
197         if (CtdlDirectoryLookup(aaa, name, sizeof aaa) == 0) {
198                 strcpy(name, aaa);
199         }
200
201         if (strcasecmp(original_name, name)) {
202                 syslog(LOG_INFO, "internet_addressing: directory alias <%s> to <%s>", original_name, name);
203         }
204
205         // Change "user @ xxx" to "user" if xxx is an alias for this host
206         for (a=0; name[a] != '\0'; ++a) {
207                 if (name[a] == '@') {
208                         if (CtdlHostAlias(&name[a+1]) == hostalias_localhost) {
209                                 name[a] = 0;
210                                 syslog(LOG_DEBUG, "internet_addressing: host is local, recipient is <%s>", name);
211                                 break;
212                         }
213                 }
214         }
215
216         // Is this a local or remote recipient?
217         at = haschar(name, '@');
218         if (at == 0) {
219                 return(EA_LOCAL);                       // no @'s = local address
220         }
221         else if (at == 1) {
222                 return(EA_INTERNET);                    // one @ = internet address
223         }
224         else {
225                 return(EA_ERROR);                       // more than one @ = badly formed address
226         }
227 }
228
229
230 // Return a supplied list of email addresses as an array, removing superfluous information and syntax.
231 // If an existing Array is supplied as "append_to" it will do so; otherwise a new Array is allocated.
232 Array *split_recps(char *addresses, Array *append_to) {
233
234         if (IsEmptyStr(addresses)) {            // nothing supplied, nothing returned
235                 return(NULL);
236         }
237
238         // Copy the supplied address list into our own memory space, because we are going to modify it.
239         char *a = strdup(addresses);
240         if (a == NULL) {
241                 syslog(LOG_ERR, "internet_addressing: malloc() failed: %m");
242                 return(NULL);
243         }
244
245         // Strip out anything in double quotes
246         char *l = NULL;
247         char *r = NULL;
248         do {
249                 l = strchr(a, '\"');
250                 r = strrchr(a, '\"');
251                 if (r > l) {
252                         strcpy(l, r+1);
253                 }
254         } while (r > l);
255
256         // Transform all qualifying delimiters to commas
257         char *t;
258         for (t=a; t[0]; ++t) {
259                 if ((t[0]==';') || (t[0]=='|')) {
260                         t[0]=',';
261                 }
262         }
263
264         // Tokenize the recipients into an array.  No single recipient should be larger than 256 bytes.
265         Array *recipients_array = NULL;
266         if (append_to) {
267                 recipients_array = append_to;                   // Append to an existing array of recipients
268         }
269         else {
270                 recipients_array = array_new(256);              // This is a new array of recipients
271         }
272
273         int num_addresses = num_tokens(a, ',');
274         int i;
275         for (i=0; i<num_addresses; ++i) {
276                 char this_address[256];
277                 extract_token(this_address, a, i, ',', sizeof this_address);
278                 string_trim(this_address);                              // strip leading and trailing whitespace
279                 stripout(this_address, '(', ')');               // remove any portion in parentheses
280                 stripallbut(this_address, '<', '>');            // if angle brackets are present, keep only what is inside them
281                 if (!IsEmptyStr(this_address)) {
282                         array_append(recipients_array, this_address);
283                 }
284         }
285
286         free(a);                                                // We don't need this buffer anymore.
287         return(recipients_array);                               // Return the completed array to the caller.
288 }
289
290
291 // Validate recipients, count delivery types and errors, and handle aliasing
292 //
293 // Returns 0 if all addresses are ok, ret->num_error = -1 if no addresses 
294 // were specified, or the number of addresses found invalid.
295 //
296 // Caller needs to free the result using free_recipients()
297 //
298 struct recptypes *validate_recipients(char *recipients_in, int Flags) {
299         struct recptypes *ret;
300         char append[SIZ];
301         long len;
302         int mailtype;
303         int invalid;
304         struct ctdluser tempUS;
305         struct ctdlroom original_room;
306         int err = 0;
307         char errmsg[SIZ];
308         char *org_recp;
309         char this_recp[256];
310
311         ret = (struct recptypes *) malloc(sizeof(struct recptypes));                    // Initialize
312         if (ret == NULL) return(NULL);
313         memset(ret, 0, sizeof(struct recptypes));                                       // set all values to null/zero
314
315         len = strlen(recipients_in) + 1024;                                             // allocate memory
316         ret->errormsg = malloc(len);
317         ret->recp_local = malloc(len);
318         ret->recp_internet = malloc(len);
319         ret->recp_room = malloc(len);
320         ret->display_recp = malloc(len);
321         ret->recp_orgroom = malloc(len);
322
323         ret->errormsg[0] = 0;
324         ret->recp_local[0] = 0;
325         ret->recp_internet[0] = 0;
326         ret->recp_room[0] = 0;
327         ret->recp_orgroom[0] = 0;
328         ret->display_recp[0] = 0;
329         ret->recptypes_magic = RECPTYPES_MAGIC;
330
331         Array *recp_array = split_recps(recipients_in, NULL);
332
333         char *aliases = CtdlGetSysConfig(GLOBAL_ALIASES);                               // First hit the Global Alias Table
334
335         int r;
336         for (r=0; (recp_array && r<array_len(recp_array)); ++r) {
337                 org_recp = (char *)array_get_element_at(recp_array, r);
338                 strncpy(this_recp, org_recp, sizeof this_recp);
339
340                 int i;
341                 for (i=0; i<3; ++i) {                                                   // pass three times through the aliaser
342                         mailtype = expand_aliases(this_recp, aliases);
343         
344                         // If an alias expanded to multiple recipients, strip off those recipients and append them
345                         // to the end of the array.  This loop will hit those again when it gets there.
346                         if (mailtype == EA_MULTIPLE) {
347                                 recp_array = split_recps(this_recp, recp_array);
348                         }
349                 }
350
351                 // This loop searches for duplicate recipients in the final list and marks them to be skipped.
352                 int j;
353                 for (j=0; j<r; ++j) {
354                         if (!strcasecmp(this_recp, (char *)array_get_element_at(recp_array, j) )) {
355                                 mailtype = EA_SKIP;
356                         }
357                 }
358
359                 syslog(LOG_DEBUG, "Recipient #%d of type %d is <%s>", r, mailtype, this_recp);
360                 invalid = 0;
361                 errmsg[0] = 0;
362                 switch(mailtype) {
363                 case EA_LOCAL:                                  // There are several types of "local" recipients.
364
365                         // Old BBS conventions require mail to "sysop" to go somewhere.  Send it to the admin room.
366                         if (!strcasecmp(this_recp, "sysop")) {
367                                 ++ret->num_room;
368                                 strcpy(this_recp, CtdlGetConfigStr("c_aideroom"));
369                                 if (!IsEmptyStr(ret->recp_room)) {
370                                         strcat(ret->recp_room, "|");
371                                 }
372                                 strcat(ret->recp_room, this_recp);
373                         }
374
375                         // This handles rooms which can receive posts via email.
376                         else if (!strncasecmp(this_recp, "room_", 5)) {
377                                 original_room = CC->room;                               // Remember where we parked
378
379                                 char mail_to_room[ROOMNAMELEN];
380                                 char *m;
381                                 strncpy(mail_to_room, &this_recp[5], sizeof mail_to_room);
382                                 for (m = mail_to_room; *m; ++m) {
383                                         if (m[0] == '_') m[0]=' ';
384                                 }
385                                 if (!CtdlGetRoom(&CC->room, mail_to_room)) {            // Find the room they asked for
386
387                                         err = CtdlDoIHavePermissionToPostInThisRoom(    // check for write permissions to room
388                                                 errmsg, 
389                                                 sizeof errmsg, 
390                                                 Flags,
391                                                 0                                       // 0 means "this is not a reply"
392                                         );
393                                         if (err) {
394                                                 ++ret->num_error;
395                                                 invalid = 1;
396                                         } 
397                                         else {
398                                                 ++ret->num_room;
399                                                 if (!IsEmptyStr(ret->recp_room)) {
400                                                         strcat(ret->recp_room, "|");
401                                                 }
402                                                 strcat(ret->recp_room, CC->room.QRname);
403         
404                                                 if (!IsEmptyStr(ret->recp_orgroom)) {
405                                                         strcat(ret->recp_orgroom, "|");
406                                                 }
407                                                 strcat(ret->recp_orgroom, this_recp);
408         
409                                         }
410                                 }
411                                 else {                                                  // no such room exists
412                                         ++ret->num_error;
413                                         invalid = 1;
414                                 }
415                                                 
416                                 // Restore this session's original room location.
417                                 CC->room = original_room;
418
419                         }
420
421                         // This handles the most common case, which is mail to a user's inbox.
422                         // (the next line depends on left-to-right evaluation)
423                         else if ((CtdlGetUser(&tempUS, this_recp) == 0) && (tempUS.usernum > 0)) {
424                                 ++ret->num_local;
425                                 strcpy(this_recp, tempUS.fullname);
426                                 if (!IsEmptyStr(ret->recp_local)) {
427                                         strcat(ret->recp_local, "|");
428                                 }
429                                 strcat(ret->recp_local, this_recp);
430                         }
431
432                         // No match for this recipient
433                         else {
434                                 ++ret->num_error;
435                                 invalid = 1;
436                         }
437                         break;
438                 case EA_INTERNET:
439                         // Yes, you're reading this correctly: if the target domain points back to the local system,
440                         // the address is invalid.  That's because if the address were valid, we would have
441                         // already translated it to a local address by now.
442                         if (IsDirectory(this_recp, 0)) {
443                                 ++ret->num_error;
444                                 invalid = 1;
445                         }
446                         else {
447                                 ++ret->num_internet;
448                                 if (!IsEmptyStr(ret->recp_internet)) {
449                                         strcat(ret->recp_internet, "|");
450                                 }
451                                 strcat(ret->recp_internet, this_recp);
452                         }
453                         break;
454                 case EA_MULTIPLE:
455                 case EA_SKIP:
456                         // no action required, anything in this slot has already been processed elsewhere
457                         break;
458                 case EA_ERROR:
459                         ++ret->num_error;
460                         invalid = 1;
461                         break;
462                 }
463                 if (invalid) {
464                         if (IsEmptyStr(errmsg)) {
465                                 snprintf(append, sizeof append, "Invalid recipient: %s", this_recp);
466                         }
467                         else {
468                                 snprintf(append, sizeof append, "%s", errmsg);
469                         }
470                         if ( (strlen(ret->errormsg) + strlen(append) + 3) < SIZ) {
471                                 if (!IsEmptyStr(ret->errormsg)) {
472                                         strcat(ret->errormsg, "; ");
473                                 }
474                                 strcat(ret->errormsg, append);
475                         }
476                 }
477                 else {
478                         if (IsEmptyStr(ret->display_recp)) {
479                                 strcpy(append, this_recp);
480                         }
481                         else {
482                                 snprintf(append, sizeof append, ", %s", this_recp);
483                         }
484                         if ( (strlen(ret->display_recp)+strlen(append)) < SIZ) {
485                                 strcat(ret->display_recp, append);
486                         }
487                 }
488         }
489
490         if (aliases != NULL) {          // ok, we're done with the global alias list now
491                 free(aliases);
492         }
493
494         if ( (ret->num_local + ret->num_internet + ret->num_room + ret->num_error) == 0) {
495                 ret->num_error = (-1);
496                 strcpy(ret->errormsg, "No recipients specified.");
497         }
498
499         syslog(LOG_DEBUG, "internet_addressing: validate_recipients() = %d local, %d room, %d SMTP, %d error",
500                 ret->num_local, ret->num_room, ret->num_internet, ret->num_error
501         );
502
503         if (recp_array) {
504                 array_free(recp_array);
505         }
506
507         return(ret);
508 }
509
510
511 // Destructor for recptypes
512 void free_recipients(struct recptypes *valid) {
513
514         if (valid == NULL) {
515                 return;
516         }
517
518         if (valid->recptypes_magic != RECPTYPES_MAGIC) {
519                 syslog(LOG_ERR, "internet_addressing: attempt to call free_recipients() on some other data type!");
520                 exit(CTDLEXIT_BAD_MAGIC);
521         }
522
523         if (valid->errormsg != NULL)            free(valid->errormsg);
524         if (valid->recp_local != NULL)          free(valid->recp_local);
525         if (valid->recp_internet != NULL)       free(valid->recp_internet);
526         if (valid->recp_room != NULL)           free(valid->recp_room);
527         if (valid->recp_orgroom != NULL)        free(valid->recp_orgroom);
528         if (valid->display_recp != NULL)        free(valid->display_recp);
529         if (valid->bounce_to != NULL)           free(valid->bounce_to);
530         if (valid->envelope_from != NULL)       free(valid->envelope_from);
531         if (valid->sending_room != NULL)        free(valid->sending_room);
532         free(valid);
533 }
534
535
536 char *qp_encode_email_addrs(char *source) {
537         char *user, *node, *name;
538         const char headerStr[] = "=?UTF-8?Q?";
539         char *Encoded;
540         char *EncodedName;
541         char *nPtr;
542         int need_to_encode = 0;
543         long SourceLen;
544         long EncodedMaxLen;
545         long nColons = 0;
546         long *AddrPtr;
547         long *AddrUtf8;
548         long nAddrPtrMax = 50;
549         long nmax;
550         int InQuotes = 0;
551         int i, n;
552
553         if (source == NULL) return source;
554         if (IsEmptyStr(source)) return source;
555         syslog(LOG_DEBUG, "internet_addressing: qp_encode_email_addrs <%s>", source);
556
557         AddrPtr = malloc (sizeof (long) * nAddrPtrMax);
558         AddrUtf8 = malloc (sizeof (long) * nAddrPtrMax);
559         memset(AddrUtf8, 0, sizeof (long) * nAddrPtrMax);
560         *AddrPtr = 0;
561         i = 0;
562         while (!IsEmptyStr (&source[i])) {
563                 if (nColons >= nAddrPtrMax){
564                         long *ptr;
565
566                         ptr = (long *) malloc(sizeof (long) * nAddrPtrMax * 2);
567                         memcpy (ptr, AddrPtr, sizeof (long) * nAddrPtrMax);
568                         free (AddrPtr), AddrPtr = ptr;
569
570                         ptr = (long *) malloc(sizeof (long) * nAddrPtrMax * 2);
571                         memset(&ptr[nAddrPtrMax], 0, sizeof (long) * nAddrPtrMax);
572
573                         memcpy (ptr, AddrUtf8, sizeof (long) * nAddrPtrMax);
574                         free (AddrUtf8), AddrUtf8 = ptr;
575                         nAddrPtrMax *= 2;                               
576                 }
577                 if (((unsigned char) source[i] < 32) || ((unsigned char) source[i] > 126)) {
578                         need_to_encode = 1;
579                         AddrUtf8[nColons] = 1;
580                 }
581                 if (source[i] == '"') {
582                         InQuotes = !InQuotes;
583                 }
584                 if (!InQuotes && source[i] == ',') {
585                         AddrPtr[nColons] = i;
586                         nColons++;
587                 }
588                 i++;
589         }
590         if (need_to_encode == 0) {
591                 free(AddrPtr);
592                 free(AddrUtf8);
593                 return source;
594         }
595
596         SourceLen = i;
597         EncodedMaxLen = nColons * (sizeof(headerStr) + 3) + SourceLen * 3;
598         Encoded = (char*) malloc (EncodedMaxLen);
599
600         for (i = 0; i < nColons; i++) {
601                 source[AddrPtr[i]++] = '\0';
602         }
603         // TODO: if libidn, this might get larger
604         user = malloc(SourceLen + 1);
605         node = malloc(SourceLen + 1);
606         name = malloc(SourceLen + 1);
607
608         nPtr = Encoded;
609         *nPtr = '\0';
610         for (i = 0; i < nColons && nPtr != NULL; i++) {
611                 nmax = EncodedMaxLen - (nPtr - Encoded);
612                 if (AddrUtf8[i]) {
613                         process_rfc822_addr(&source[AddrPtr[i]], user, node, name);
614                         // TODO: libIDN here !
615                         if (IsEmptyStr(name)) {
616                                 n = snprintf(nPtr, nmax, (i==0)?"%s@%s" : ",%s@%s", user, node);
617                         }
618                         else {
619                                 EncodedName = rfc2047encode(name, strlen(name));                        
620                                 n = snprintf(nPtr, nmax, (i==0)?"%s <%s@%s>" : ",%s <%s@%s>", EncodedName, user, node);
621                                 free(EncodedName);
622                         }
623                 }
624                 else { 
625                         n = snprintf(nPtr, nmax, (i==0)?"%s" : ",%s", &source[AddrPtr[i]]);
626                 }
627                 if (n > 0 )
628                         nPtr += n;
629                 else { 
630                         char *ptr, *nnPtr;
631                         ptr = (char*) malloc(EncodedMaxLen * 2);
632                         memcpy(ptr, Encoded, EncodedMaxLen);
633                         nnPtr = ptr + (nPtr - Encoded), nPtr = nnPtr;
634                         free(Encoded), Encoded = ptr;
635                         EncodedMaxLen *= 2;
636                         i--; // do it once more with properly lengthened buffer
637                 }
638         }
639         for (i = 0; i < nColons; i++)
640                 source[--AddrPtr[i]] = ',';
641
642         free(user);
643         free(node);
644         free(name);
645         free(AddrUtf8);
646         free(AddrPtr);
647         return Encoded;
648 }
649
650
651 // Unfold a multi-line field into a single line, removing multi-whitespaces
652 void unfold_rfc822_field(char **field, char **FieldEnd) 
653 {
654         int quote = 0;
655         char *pField = *field;
656         char *sField;
657         char *pFieldEnd = *FieldEnd;
658
659         while (isspace(*pField))
660                 pField++;
661         // remove leading/trailing whitespace
662         ;
663
664         while (isspace(*pFieldEnd))
665                 pFieldEnd --;
666
667         *FieldEnd = pFieldEnd;
668         // convert non-space whitespace to spaces, and remove double blanks
669         for (sField = *field = pField; sField < pFieldEnd; pField++, sField++) {
670                 if ((*sField=='\r') || (*sField=='\n')) {
671                         int offset = 1;
672                         while ( ( (*(sField + offset) == '\r') || (*(sField + offset) == '\n' )) && (sField + offset < pFieldEnd) ) {
673                                 offset ++;
674                         }
675                         sField += offset;
676                         *pField = *sField;
677                 }
678                 else {
679                         if (*sField=='\"') quote = 1 - quote;
680                         if (!quote) {
681                                 if (isspace(*sField)) {
682                                         *pField = ' ';
683                                         pField++;
684                                         sField++;
685                                         
686                                         while ((sField < pFieldEnd) && isspace(*sField))
687                                                 sField++;
688                                         *pField = *sField;
689                                 }
690                                 else *pField = *sField;
691                         }
692                         else *pField = *sField;
693                 }
694         }
695         *pField = '\0';
696         *FieldEnd = pField - 1;
697 }
698
699
700 // Split an RFC822-style address into userid, host, and full name
701 void process_rfc822_addr(const char *rfc822, char *user, char *node, char *name) {
702         int a;
703
704         strcpy(user, "");
705         strcpy(node, CtdlGetConfigStr("c_fqdn"));
706         strcpy(name, "");
707
708         if (rfc822 == NULL) return;
709
710         // extract full name - first, it's From minus <userid>
711         strcpy(name, rfc822);
712         stripout(name, '<', '>');
713
714         // and anything to the right of a @
715         for (a = 0; name[a] != '\0'; ++a) {
716                 if (name[a] == '@') {
717                         name[a] = 0;
718                         break;
719                 }
720         }
721
722         // but if there are parentheses, that changes the rules...
723         if ((haschar(rfc822, '(') == 1) && (haschar(rfc822, ')') == 1)) {
724                 strcpy(name, rfc822);
725                 stripallbut(name, '(', ')');
726         }
727
728         // but if there are a set of quotes, that supersedes everything
729         if (haschar(rfc822, 34) == 2) {
730                 strcpy(name, rfc822);
731                 while ((!IsEmptyStr(name)) && (name[0] != 34)) {
732                         strcpy(&name[0], &name[1]);
733                 }
734                 strcpy(&name[0], &name[1]);
735                 for (a = 0; name[a] != '\0'; ++a)
736                         if (name[a] == 34) {
737                                 name[a] = 0;
738                                 break;
739                         }
740         }
741         // extract user id
742         strcpy(user, rfc822);
743
744         // first get rid of anything in parens
745         stripout(user, '(', ')');
746
747         // if there's a set of angle brackets, strip it down to that
748         if ((haschar(user, '<') == 1) && (haschar(user, '>') == 1)) {
749                 stripallbut(user, '<', '>');
750         }
751
752         // and anything to the right of a @
753         for (a = 0; user[a] != '\0'; ++a) {
754                 if (user[a] == '@') {
755                         user[a] = 0;
756                         break;
757                 }
758         }
759
760         // extract node name
761         strcpy(node, rfc822);
762
763         // first get rid of anything in parens
764         stripout(node, '(', ')');
765
766         // if there's a set of angle brackets, strip it down to that
767         if ((haschar(node, '<') == 1) && (haschar(node, '>') == 1)) {
768                 stripallbut(node, '<', '>');
769         }
770
771         // If no node specified, tack ours on instead
772         if (haschar(node, '@') == 0) {
773                 strcpy(node, CtdlGetConfigStr("c_nodename"));
774         }
775         else {
776                 // strip anything to the left of a @
777                 while ((!IsEmptyStr(node)) && (haschar(node, '@') > 0)) {
778                         strcpy(node, &node[1]);
779                 }
780         }
781
782         // strip leading and trailing spaces in all strings
783         string_trim(user);
784         string_trim(node);
785         string_trim(name);
786
787         // If we processed a string that had the address in angle brackets
788         // but no name outside the brackets, we now have an empty name.  In
789         // this case, use the user portion of the address as the name.
790         if ((IsEmptyStr(name)) && (!IsEmptyStr(user))) {
791                 strcpy(name, user);
792         }
793 }
794
795
796 // convert_field() is a helper function for convert_internet_message().
797 // Given start/end positions for an rfc822 field, it converts it to a Citadel
798 // field if it wants to, and unfolds it if necessary.
799 //
800 // Returns 1 if the field was converted and inserted into the Citadel message
801 // structure, implying that the source field should be removed from the
802 // message text.
803 int convert_field(struct CtdlMessage *msg, const char *beg, const char *end) {
804         char *key, *value, *valueend;
805         long len;
806         const char *pos;
807         int i;
808         const char *colonpos = NULL;
809         int processed = 0;
810         char user[1024];
811         char node[1024];
812         char name[1024];
813         char addr[1024];
814         time_t parsed_date;
815         long valuelen;
816
817         for (pos = end; pos >= beg; pos--) {
818                 if (*pos == ':') colonpos = pos;
819         }
820
821         if (colonpos == NULL) return(0);        // no colon? not a valid header line
822
823         len = end - beg;
824         key = malloc(len + 2);
825         memcpy(key, beg, len + 1);
826         key[len] = '\0';
827         valueend = key + len;
828         * ( key + (colonpos - beg) ) = '\0';
829         value = &key[(colonpos - beg) + 1];
830         // printf("Header: [%s]\nValue: [%s]\n", key, value);
831         unfold_rfc822_field(&value, &valueend);
832         valuelen = valueend - value + 1;
833         // printf("UnfoldedValue: [%s]\n", value);
834
835         // Here's the big rfc822-to-citadel loop.
836
837         // Date/time is converted into a unix timestamp.  If the conversion
838         // fails, we replace it with the time the message arrived locally.
839         if (!strcasecmp(key, "Date")) {
840                 parsed_date = parsedate(value);
841                 if (parsed_date < 0L) parsed_date = time(NULL);
842
843                 if (CM_IsEmpty(msg, eTimestamp))
844                         CM_SetFieldLONG(msg, eTimestamp, parsed_date);
845                 processed = 1;
846         }
847
848         else if (!strcasecmp(key, "From")) {
849                 process_rfc822_addr(value, user, node, name);
850                 syslog(LOG_DEBUG, "internet_addressing: converted to <%s@%s> (%s)", user, node, name);
851                 snprintf(addr, sizeof(addr), "%s@%s", user, node);
852                 if (CM_IsEmpty(msg, eAuthor) && !IsEmptyStr(name)) {
853                         CM_SetField(msg, eAuthor, name);
854                 }
855                 if (CM_IsEmpty(msg, erFc822Addr) && !IsEmptyStr(addr)) {
856                         CM_SetField(msg, erFc822Addr, addr);
857                 }
858                 processed = 1;
859         }
860
861         else if (!strcasecmp(key, "Subject")) {
862                 if (CM_IsEmpty(msg, eMsgSubject))
863                         CM_SetField(msg, eMsgSubject, value);
864                 processed = 1;
865         }
866
867         else if (!strcasecmp(key, "List-ID")) {
868                 if (CM_IsEmpty(msg, eListID))
869                         CM_SetField(msg, eListID, value);
870                 processed = 1;
871         }
872
873         else if (!strcasecmp(key, "To")) {
874                 if (CM_IsEmpty(msg, eRecipient))
875                         CM_SetField(msg, eRecipient, value);
876                 processed = 1;
877         }
878
879         else if (!strcasecmp(key, "CC")) {
880                 if (CM_IsEmpty(msg, eCarbonCopY))
881                         CM_SetField(msg, eCarbonCopY, value);
882                 processed = 1;
883         }
884
885         else if (!strcasecmp(key, "Message-ID")) {
886                 if (!CM_IsEmpty(msg, emessageId)) {
887                         syslog(LOG_WARNING, "internet_addressing: duplicate message id");
888                 }
889                 else {
890                         char *pValue;
891                         long pValueLen;
892
893                         pValue = value;
894                         pValueLen = valuelen;
895                         // Strip angle brackets
896                         while (haschar(pValue, '<') > 0) {
897                                 pValue ++;
898                                 pValueLen --;
899                         }
900
901                         for (i = 0; i <= pValueLen; ++i)
902                                 if (pValue[i] == '>') {
903                                         pValueLen = i;
904                                         break;
905                                 }
906
907                         CM_SetField(msg, emessageId, pValue);
908                 }
909
910                 processed = 1;
911         }
912
913         else if (!strcasecmp(key, "Return-Path")) {
914                 if (CM_IsEmpty(msg, eMessagePath))
915                         CM_SetField(msg, eMessagePath, value);
916                 processed = 1;
917         }
918
919         else if (!strcasecmp(key, "Envelope-To")) {
920                 if (CM_IsEmpty(msg, eenVelopeTo))
921                         CM_SetField(msg, eenVelopeTo, value);
922                 processed = 1;
923         }
924
925         else if (!strcasecmp(key, "References")) {
926                 CM_SetField(msg, eWeferences, value);
927                 processed = 1;
928         }
929
930         else if (!strcasecmp(key, "Reply-To")) {
931                 CM_SetField(msg, eReplyTo, value);
932                 processed = 1;
933         }
934
935         else if (!strcasecmp(key, "In-reply-to")) {
936                 if (CM_IsEmpty(msg, eWeferences)) // References: supersedes In-reply-to:
937                         CM_SetField(msg, eWeferences, value);
938                 processed = 1;
939         }
940
941         // Clean up and move on.
942         free(key);      // Don't free 'value', it's actually the same buffer
943         return processed;
944 }
945
946
947 // Convert RFC822 references format (References) to Citadel references format (Weferences)
948 void convert_references_to_wefewences(char *str) {
949         int bracket_nesting = 0;
950         char *ptr = str;
951         char *moveptr = NULL;
952         char ch;
953
954         while(*ptr) {
955                 ch = *ptr;
956                 if (ch == '>') {
957                         --bracket_nesting;
958                         if (bracket_nesting < 0) bracket_nesting = 0;
959                 }
960                 if ((ch == '>') && (bracket_nesting == 0) && (*(ptr+1)) && (ptr>str) ) {
961                         *ptr = '|';
962                         ++ptr;
963                 }
964                 else if (bracket_nesting > 0) {
965                         ++ptr;
966                 }
967                 else {
968                         moveptr = ptr;
969                         while (*moveptr) {
970                                 *moveptr = *(moveptr+1);
971                                 ++moveptr;
972                         }
973                 }
974                 if (ch == '<') ++bracket_nesting;
975         }
976
977 }
978
979
980 // Convert an RFC822 message (headers + body) to a CtdlMessage structure.
981 // NOTE: the supplied buffer becomes part of the CtdlMessage structure, and
982 // will be deallocated when CM_Free() is called.  Therefore, the
983 // supplied buffer should be DEREFERENCED.  It should not be freed or used
984 // again.
985 struct CtdlMessage *convert_internet_message(char *rfc822) {
986         StrBuf *RFCBuf = NewStrBufPlain(rfc822, -1);
987         free (rfc822);
988         return convert_internet_message_buf(&RFCBuf);
989 }
990
991
992 struct CtdlMessage *convert_internet_message_buf(StrBuf **rfc822) {
993         struct CtdlMessage *msg;
994         const char *pos, *beg, *end, *totalend;
995         int done, alldone = 0;
996         int converted;
997         StrBuf *OtherHeaders;
998
999         msg = malloc(sizeof(struct CtdlMessage));
1000         if (msg == NULL) return msg;
1001
1002         memset(msg, 0, sizeof(struct CtdlMessage));
1003         msg->cm_magic = CTDLMESSAGE_MAGIC;      // self check
1004         msg->cm_anon_type = 0;                  // never anonymous
1005         msg->cm_format_type = FMT_RFC822;       // internet message
1006
1007         pos = ChrPtr(*rfc822);
1008         totalend = pos + StrLength(*rfc822);
1009         done = 0;
1010         OtherHeaders = NewStrBufPlain(NULL, StrLength(*rfc822));
1011
1012         while (!alldone) {
1013
1014                 // Locate beginning and end of field, keeping in mind that
1015                 // some fields might be multiline
1016                 end = beg = pos;
1017
1018                 while ((end < totalend) && (end == beg) && (done == 0) ) {
1019
1020                         if ( (*pos=='\n') && ((*(pos+1))!=0x20) && ((*(pos+1))!=0x09) ) {
1021                                 end = pos;
1022                         }
1023
1024                         // done with headers?
1025                         if ((*pos=='\n') && ( (*(pos+1)=='\n') || (*(pos+1)=='\r')) ) {
1026                                 alldone = 1;
1027                         }
1028
1029                         if (pos >= (totalend - 1) ) {
1030                                 end = pos;
1031                                 done = 1;
1032                         }
1033
1034                         ++pos;
1035                 }
1036
1037                 // At this point we have a field.  Are we interested in it?
1038                 converted = convert_field(msg, beg, end);
1039
1040                 // Strip the field out of the RFC822 header if we used it
1041                 if (!converted) {
1042                         StrBufAppendBufPlain(OtherHeaders, beg, end - beg, 0);
1043                         StrBufAppendBufPlain(OtherHeaders, HKEY("\n"), 0);
1044                 }
1045
1046                 // If we've hit the end of the message, bail out
1047                 if (pos >= totalend)
1048                         alldone = 1;
1049         }
1050         StrBufAppendBufPlain(OtherHeaders, HKEY("\n"), 0);
1051         if (pos < totalend) {
1052                 StrBufAppendBufPlain(OtherHeaders, pos, totalend - pos, 0);
1053         }
1054         FreeStrBuf(rfc822);
1055         CM_SetAsFieldSB(msg, eMessageText, &OtherHeaders);
1056
1057         // Follow-up sanity checks...
1058
1059         // If there's no timestamp on this message, set it to now.
1060         if (CM_IsEmpty(msg, eTimestamp)) {
1061                 CM_SetFieldLONG(msg, eTimestamp, time(NULL));
1062         }
1063
1064         // If a W (references, or rather, Wefewences) field is present, we
1065         // have to convert it from RFC822 format to Citadel format.
1066         if (!CM_IsEmpty(msg, eWeferences)) {
1067                 /// todo: API!
1068                 convert_references_to_wefewences(msg->cm_fields[eWeferences]);
1069         }
1070
1071         return msg;
1072 }
1073
1074
1075 // Look for a particular header field in an RFC822 message text.  If the
1076 // requested field is found, it is unfolded (if necessary) and returned to
1077 // the caller.  The field name is stripped out, leaving only its contents.
1078 // The caller is responsible for freeing the returned buffer.  If the requested
1079 // field is not present, or anything else goes wrong, it returns NULL.
1080 char *rfc822_fetch_field(const char *rfc822, const char *fieldname) {
1081         char *fieldbuf = NULL;
1082         const char *end_of_headers;
1083         const char *field_start;
1084         const char *ptr;
1085         char *cont;
1086         char fieldhdr[SIZ];
1087
1088         // Should never happen, but sometimes we get stupid
1089         if (rfc822 == NULL) return(NULL);
1090         if (fieldname == NULL) return(NULL);
1091
1092         snprintf(fieldhdr, sizeof fieldhdr, "%s:", fieldname);
1093
1094         // Locate the end of the headers, so we don't run past that point
1095         end_of_headers = cbmstrcasestr(rfc822, "\n\r\n");
1096         if (end_of_headers == NULL) {
1097                 end_of_headers = cbmstrcasestr(rfc822, "\n\n");
1098         }
1099         if (end_of_headers == NULL) return (NULL);
1100
1101         field_start = cbmstrcasestr(rfc822, fieldhdr);
1102         if (field_start == NULL) return(NULL);
1103         if (field_start > end_of_headers) return(NULL);
1104
1105         fieldbuf = malloc(SIZ);
1106         strcpy(fieldbuf, "");
1107
1108         ptr = field_start;
1109         ptr = cmemreadline(ptr, fieldbuf, SIZ-strlen(fieldbuf) );
1110         while ( (isspace(ptr[0])) && (ptr < end_of_headers) ) {
1111                 strcat(fieldbuf, " ");
1112                 cont = &fieldbuf[strlen(fieldbuf)];
1113                 ptr = cmemreadline(ptr, cont, SIZ-strlen(fieldbuf) );
1114                 string_trim(cont);
1115         }
1116
1117         strcpy(fieldbuf, &fieldbuf[strlen(fieldhdr)]);
1118         string_trim(fieldbuf);
1119
1120         return(fieldbuf);
1121 }
1122
1123
1124 //      *****************************************************************************
1125 //                           DIRECTORY MANAGEMENT FUNCTIONS                       
1126 //      *****************************************************************************
1127
1128 // Generate the index key for an Internet e-mail address to be looked up
1129 // in the database.
1130 void directory_key(char *key, char *addr) {
1131         int i;
1132         int keylen = 0;
1133
1134         for (i=0; !IsEmptyStr(&addr[i]); ++i) {
1135                 if (!isspace(addr[i])) {
1136                         key[keylen++] = tolower(addr[i]);
1137                 }
1138         }
1139         key[keylen++] = 0;
1140         syslog(LOG_DEBUG, "internet_addressing: directory key is <%s>", key);
1141 }
1142
1143
1144 // Return nonzero if the supplied address is in one of "our" domains
1145 int IsDirectory(char *addr, int allow_masq_domains) {
1146         char domain[256];
1147         int h;
1148
1149         extract_token(domain, addr, 1, '@', sizeof domain);
1150         string_trim(domain);
1151
1152         h = CtdlHostAlias(domain);
1153
1154         if ( (h == hostalias_masq) && allow_masq_domains)
1155                 return(1);
1156         
1157         if (h == hostalias_localhost) {
1158                 return(1);
1159         }
1160         else {
1161                 return(0);
1162         }
1163 }
1164
1165
1166 // Add an Internet e-mail address to the directory for a user
1167 int CtdlDirectoryAddUser(char *internet_addr, char *citadel_addr) {
1168         char key[SIZ];
1169
1170         if (IsDirectory(internet_addr, 0) == 0) {
1171                 return 0;
1172         }
1173         syslog(LOG_DEBUG, "internet_addressing: create directory entry: %s --> %s", internet_addr, citadel_addr);
1174         directory_key(key, internet_addr);
1175         cdb_store(CDB_DIRECTORY, key, strlen(key), citadel_addr, strlen(citadel_addr)+1 );
1176         return 1;
1177 }
1178
1179
1180 // Delete an Internet e-mail address from the directory.
1181 //
1182 // (NOTE: we don't actually use or need the citadel_addr variable; it's merely
1183 // here because the callback API expects to be able to send it.)
1184 int CtdlDirectoryDelUser(char *internet_addr, char *citadel_addr) {
1185         char key[SIZ];
1186         
1187         syslog(LOG_DEBUG, "internet_addressing: delete directory entry: %s --> %s", internet_addr, citadel_addr);
1188         directory_key(key, internet_addr);
1189         return cdb_delete(CDB_DIRECTORY, key, strlen(key) ) == 0;
1190 }
1191
1192
1193 // Look up an Internet e-mail address in the directory.
1194 // On success: returns 0, and Citadel address stored in 'target'
1195 // On failure: returns nonzero
1196 int CtdlDirectoryLookup(char *target, char *internet_addr, size_t targbuflen) {
1197         struct cdbdata cdbrec;
1198         char key[SIZ];
1199
1200         // Dump it in there unchanged, just for kicks
1201         if (target != NULL) {
1202                 safestrncpy(target, internet_addr, targbuflen);
1203         }
1204
1205         // Only do lookups for addresses with hostnames in them
1206         if (num_tokens(internet_addr, '@') != 2) return(-1);
1207
1208         // Only do lookups for domains in the directory
1209         if (IsDirectory(internet_addr, 0) == 0) return(-1);
1210
1211         directory_key(key, internet_addr);
1212         cdbrec = cdb_fetch(CDB_DIRECTORY, key, strlen(key));
1213         if (cdbrec.ptr != NULL) {
1214                 if (target != NULL) {
1215                         safestrncpy(target, cdbrec.ptr, targbuflen);
1216                 }
1217                 return(0);
1218         }
1219
1220         return(-1);
1221 }
1222
1223
1224 // Harvest any email addresses that someone might want to have in their "collected addresses" book.
1225 char *harvest_collected_addresses(struct CtdlMessage *msg) {
1226         char *coll = NULL;
1227         char addr[256];
1228         char user[256], node[256], name[256];
1229         int is_harvestable;
1230         int i, j, h;
1231         eMsgField field = 0;
1232
1233         if (msg == NULL) return(NULL);
1234
1235         is_harvestable = 1;
1236         strcpy(addr, "");       
1237         if (!CM_IsEmpty(msg, eAuthor)) {
1238                 strcat(addr, msg->cm_fields[eAuthor]);
1239         }
1240         if (!CM_IsEmpty(msg, erFc822Addr)) {
1241                 strcat(addr, " <");
1242                 strcat(addr, msg->cm_fields[erFc822Addr]);
1243                 strcat(addr, ">");
1244                 if (IsDirectory(msg->cm_fields[erFc822Addr], 0)) {
1245                         is_harvestable = 0;
1246                 }
1247         }
1248
1249         if (is_harvestable) {
1250                 coll = strdup(addr);
1251         }
1252         else {
1253                 coll = strdup("");
1254         }
1255
1256         if (coll == NULL) return(NULL);
1257
1258         // Scan both the R (To) and Y (CC) fields
1259         for (i = 0; i < 2; ++i) {
1260                 if (i == 0) field = eRecipient;
1261                 if (i == 1) field = eCarbonCopY;
1262
1263                 if (!CM_IsEmpty(msg, field)) {
1264                         for (j=0; j<num_tokens(msg->cm_fields[field], ','); ++j) {
1265                                 extract_token(addr, msg->cm_fields[field], j, ',', sizeof addr);
1266                                 if (strstr(addr, "=?") != NULL) {
1267                                         utf8ify_rfc822_string(addr);
1268                                 }
1269                                 process_rfc822_addr(addr, user, node, name);
1270                                 h = CtdlHostAlias(node);
1271                                 if (h != hostalias_localhost) {
1272                                         coll = realloc(coll, strlen(coll) + strlen(addr) + 4);
1273                                         if (coll == NULL) return(NULL);
1274                                         if (!IsEmptyStr(coll)) {
1275                                                 strcat(coll, ",");
1276                                         }
1277                                         string_trim(addr);
1278                                         strcat(coll, addr);
1279                                 }
1280                         }
1281                 }
1282         }
1283
1284         if (IsEmptyStr(coll)) {
1285                 free(coll);
1286                 return(NULL);
1287         }
1288         return(coll);
1289 }
1290
1291
1292 // Helper function for CtdlRebuildDirectoryIndex()
1293 void CtdlRebuildDirectoryIndex_backend(char *username, void *data) {
1294
1295         int j = 0;
1296         struct ctdluser usbuf;
1297
1298         if (CtdlGetUser(&usbuf, username) != 0) {
1299                 return;
1300         }
1301
1302         if ( (!IsEmptyStr(usbuf.fullname)) && (!IsEmptyStr(usbuf.emailaddrs)) ) {
1303                 for (j=0; j<num_tokens(usbuf.emailaddrs, '|'); ++j) {
1304                         char one_email[512];
1305                         extract_token(one_email, usbuf.emailaddrs, j, '|', sizeof one_email);
1306                         CtdlDirectoryAddUser(one_email, usbuf.fullname);
1307                 }
1308         }
1309 }
1310
1311
1312 // Initialize the directory database (erasing anything already there)
1313 void CtdlRebuildDirectoryIndex(void) {
1314         syslog(LOG_INFO, "internet_addressing: rebuilding email address directory index");
1315         cdb_trunc(CDB_DIRECTORY);
1316         ForEachUser(CtdlRebuildDirectoryIndex_backend, NULL);
1317 }
1318
1319
1320 // Configure Internet email addresses for a user account, updating the Directory Index in the process
1321 void CtdlSetEmailAddressesForUser(char *requested_user, char *new_emailaddrs) {
1322         struct ctdluser usbuf;
1323         int i;
1324         char buf[SIZ];
1325
1326         if (CtdlGetUserLock(&usbuf, requested_user) != 0) {     // We can lock because the DirectoryIndex functions don't lock.
1327                 return;                                         // Silently fail here if the specified user does not exist.
1328         }
1329
1330         syslog(LOG_DEBUG, "internet_addressing: setting email addresses for <%s> to <%s>", usbuf.fullname, new_emailaddrs);
1331
1332         // Delete all of the existing directory index records for the user (easier this way)
1333         for (i=0; i<num_tokens(usbuf.emailaddrs, '|'); ++i) {
1334                 extract_token(buf, usbuf.emailaddrs, i, '|', sizeof buf);
1335                 CtdlDirectoryDelUser(buf, requested_user);
1336         }
1337
1338         strcpy(usbuf.emailaddrs, new_emailaddrs);               // make it official.
1339
1340         // Index all of the new email addresses (they've already been sanitized)
1341         for (i=0; i<num_tokens(usbuf.emailaddrs, '|'); ++i) {
1342                 extract_token(buf, usbuf.emailaddrs, i, '|', sizeof buf);
1343                 CtdlDirectoryAddUser(buf, requested_user);
1344         }
1345
1346         CtdlPutUserLock(&usbuf);
1347 }
1348
1349
1350 // Auto-generate an Internet email address for a user account
1351 void AutoGenerateEmailAddressForUser(struct ctdluser *user) {
1352         char synthetic_email_addr[1024];
1353         int i, j;
1354         int u = 0;
1355
1356         for (i=0; u==0; ++i) {
1357                 if (i == 0) {
1358                         // first try just converting the user name to lowercase and replacing spaces with underscores
1359                         snprintf(synthetic_email_addr, sizeof synthetic_email_addr, "%s@%s", user->fullname, CtdlGetConfigStr("c_fqdn"));
1360                         for (j=0; ((synthetic_email_addr[j] != '\0')&&(synthetic_email_addr[j] != '@')); j++) {
1361                                 synthetic_email_addr[j] = tolower(synthetic_email_addr[j]);
1362                                 if (!isalnum(synthetic_email_addr[j])) {
1363                                         synthetic_email_addr[j] = '_';
1364                                 }
1365                         }
1366                 }
1367                 else if (i == 1) {
1368                         // then try 'ctdl' followed by the user number
1369                         snprintf(synthetic_email_addr, sizeof synthetic_email_addr, "ctdl%08lx@%s", user->usernum, CtdlGetConfigStr("c_fqdn"));
1370                 }
1371                 else if (i > 1) {
1372                         // oof.  just keep trying other numbers until we find one
1373                         snprintf(synthetic_email_addr, sizeof synthetic_email_addr, "ctdl%08x@%s", i, CtdlGetConfigStr("c_fqdn"));
1374                 }
1375                 u = CtdlDirectoryLookup(NULL, synthetic_email_addr, 0);
1376                 syslog(LOG_DEBUG, "user_ops: address <%s> lookup returned <%d>", synthetic_email_addr, u);
1377         }
1378
1379         CtdlSetEmailAddressesForUser(user->fullname, synthetic_email_addr);
1380         strncpy(CC->user.emailaddrs, synthetic_email_addr, sizeof(user->emailaddrs));
1381         syslog(LOG_DEBUG, "user_ops: auto-generated email address <%s> for <%s>", synthetic_email_addr, user->fullname);
1382 }
1383
1384
1385 // Determine whether the supplied email address is subscribed to the supplied room's mailing list service.
1386 int is_email_subscribed_to_list(char *email, char *room_name) {
1387         struct ctdlroom room;
1388         long roomnum;
1389         char *roomnetconfig;
1390         int found_it = 0;
1391
1392         if (CtdlGetRoom(&room, room_name)) {
1393                 return(0);                                      // room not found, so definitely not subscribed
1394         }
1395
1396         // If this room has the QR2_SMTP_PUBLIC flag set, anyone may email a post to this room, even non-subscribers.
1397         if (room.QRflags2 & QR2_SMTP_PUBLIC) {
1398                 return(1);
1399         }
1400
1401         roomnum = room.QRnumber;
1402         roomnetconfig = LoadRoomNetConfigFile(roomnum);
1403         if (roomnetconfig == NULL) {
1404                 return(0);
1405         }
1406
1407         // We're going to do a very sloppy match here and simply search for the specified email address
1408         // anywhere in the room's netconfig.  If you don't like this, fix it yourself.
1409         if (bmstrcasestr(roomnetconfig, email)) {
1410                 found_it = 1;
1411         }
1412         else {
1413                 found_it = 0;
1414         }
1415
1416         free(roomnetconfig);
1417         return(found_it);
1418 }