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