83fcf4c04eca5a7e3c8433799ef7c84444db2d92
[citadel.git] / citadel / internet_addressing.c
1 /*
2  * This file contains functions which handle the mapping of Internet addresses
3  * to users on the Citadel system.
4  */
5
6 #include "sysdep.h"
7 #include <stdlib.h>
8 #include <unistd.h>
9 #include <stdio.h>
10 #include <fcntl.h>
11 #include <ctype.h>
12 #include <signal.h>
13 #include <pwd.h>
14 #include <errno.h>
15 #include <sys/types.h>
16
17 #if TIME_WITH_SYS_TIME
18 # include <sys/time.h>
19 # include <time.h>
20 #else
21 # if HAVE_SYS_TIME_H
22 #  include <sys/time.h>
23 # else
24 #  include <time.h>
25 # endif
26 #endif
27
28 #include <sys/wait.h>
29 #include <string.h>
30 #include <limits.h>
31 #include <libcitadel.h>
32 #include "citadel.h"
33 #include "server.h"
34 #include "sysdep_decls.h"
35 #include "citserver.h"
36 #include "support.h"
37 #include "config.h"
38 #include "msgbase.h"
39 #include "internet_addressing.h"
40 #include "user_ops.h"
41 #include "room_ops.h"
42 #include "parsedate.h"
43 #include "database.h"
44 #include "ctdl_module.h"
45 #ifdef HAVE_ICONV
46 #include <iconv.h>
47
48 #if 0
49 /* This is the non-define version in case of s.b. needing to debug */
50 inline void FindNextEnd (char *bptr, char *end)
51 {
52         /* Find the next ?Q? */
53         end = strchr(bptr + 2, '?');
54         if (end == NULL) return NULL;
55         if (((*(end + 1) == 'B') || (*(end + 1) == 'Q')) && 
56             (*(end + 2) == '?')) {
57                 /* skip on to the end of the cluster, the next ?= */
58                 end = strstr(end + 3, "?=");
59         }
60         else
61                 /* sort of half valid encoding, try to find an end. */
62                 end = strstr(bptr, "?=");
63 }
64 #endif
65
66 #define FindNextEnd(bptr, end) { \
67         end = strchr(bptr + 2, '?'); \
68         if (end != NULL) { \
69                 if (((*(end + 1) == 'B') || (*(end + 1) == 'Q')) && (*(end + 2) == '?')) { \
70                         end = strstr(end + 3, "?="); \
71                 } else end = strstr(bptr, "?="); \
72         } \
73 }
74
75 /*
76  * Handle subjects with RFC2047 encoding such as:
77  * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
78  */
79 void utf8ify_rfc822_string(char *buf) {
80         char *start, *end, *next, *nextend, *ptr;
81         char newbuf[1024];
82         char charset[128];
83         char encoding[16];
84         char istr[1024];
85         iconv_t ic = (iconv_t)(-1) ;
86         char *ibuf;                     /**< Buffer of characters to be converted */
87         char *obuf;                     /**< Buffer for converted characters */
88         size_t ibuflen;                 /**< Length of input buffer */
89         size_t obuflen;                 /**< Length of output buffer */
90         char *isav;                     /**< Saved pointer to input buffer */
91         char *osav;                     /**< Saved pointer to output buffer */
92         int passes = 0;
93         int i, len, delta;
94         int illegal_non_rfc2047_encoding = 0;
95
96         /* Sometimes, badly formed messages contain strings which were simply
97          *  written out directly in some foreign character set instead of
98          *  using RFC2047 encoding.  This is illegal but we will attempt to
99          *  handle it anyway by converting from a user-specified default
100          *  charset to UTF-8 if we see any nonprintable characters.
101          */
102         len = strlen(buf);
103         for (i=0; i<len; ++i) {
104                 if ((buf[i] < 32) || (buf[i] > 126)) {
105                         illegal_non_rfc2047_encoding = 1;
106                         i = len; ///< take a shortcut, it won't be more than one.
107                 }
108         }
109         if (illegal_non_rfc2047_encoding) {
110                 const char *default_header_charset = "iso-8859-1";
111                 if ( (strcasecmp(default_header_charset, "UTF-8")) && (strcasecmp(default_header_charset, "us-ascii")) ) {
112                         ctdl_iconv_open("UTF-8", default_header_charset, &ic);
113                         if (ic != (iconv_t)(-1) ) {
114                                 ibuf = malloc(1024);
115                                 isav = ibuf;
116                                 safestrncpy(ibuf, buf, 1024);
117                                 ibuflen = strlen(ibuf);
118                                 obuflen = 1024;
119                                 obuf = (char *) malloc(obuflen);
120                                 osav = obuf;
121                                 iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
122                                 osav[1024-obuflen] = 0;
123                                 strcpy(buf, osav);
124                                 free(osav);
125                                 iconv_close(ic);
126                                 free(isav);
127                         }
128                 }
129         }
130
131         /* pre evaluate the first pair */
132         nextend = end = NULL;
133         len = strlen(buf);
134         start = strstr(buf, "=?");
135         if (start != NULL) 
136                 FindNextEnd (start, end);
137
138         while ((start != NULL) && (end != NULL))
139         {
140                 next = strstr(end, "=?");
141                 if (next != NULL)
142                         FindNextEnd(next, nextend);
143                 if (nextend == NULL)
144                         next = NULL;
145
146                 /* did we find two partitions */
147                 if ((next != NULL) && 
148                     ((next - end) > 2))
149                 {
150                         ptr = end + 2;
151                         while ((ptr < next) && 
152                                (isspace(*ptr) ||
153                                 (*ptr == '\r') ||
154                                 (*ptr == '\n') || 
155                                 (*ptr == '\t')))
156                                 ptr ++;
157                         /* did we find a gab just filled with blanks? */
158                         if (ptr == next)
159                         {
160                                 memmove (end + 2,
161                                          next,
162                                          len - (next - start));
163
164                                 /* now terminate the gab at the end */
165                                 delta = (next - end) - 2;
166                                 len -= delta;
167                                 buf[len] = '\0';
168
169                                 /* move next to its new location. */
170                                 next -= delta;
171                                 nextend -= delta;
172                         }
173                 }
174                 /* our next-pair is our new first pair now. */
175                 start = next;
176                 end = nextend;
177         }
178
179         /* Now we handle foreign character sets properly encoded
180          * in RFC2047 format.
181          */
182         start = strstr(buf, "=?");
183         FindNextEnd((start != NULL)? start : buf, end);
184         while (start != NULL && end != NULL && end > start)
185         {
186                 extract_token(charset, start, 1, '?', sizeof charset);
187                 extract_token(encoding, start, 2, '?', sizeof encoding);
188                 extract_token(istr, start, 3, '?', sizeof istr);
189
190                 ibuf = malloc(1024);
191                 isav = ibuf;
192                 if (!strcasecmp(encoding, "B")) {       /**< base64 */
193                         ibuflen = CtdlDecodeBase64(ibuf, istr, strlen(istr));
194                 }
195                 else if (!strcasecmp(encoding, "Q")) {  /**< quoted-printable */
196                         size_t len;
197                         long pos;
198                         
199                         len = strlen(istr);
200                         pos = 0;
201                         while (pos < len)
202                         {
203                                 if (istr[pos] == '_') istr[pos] = ' ';
204                                 pos++;
205                         }
206
207                         ibuflen = CtdlDecodeQuotedPrintable(ibuf, istr, len);
208                 }
209                 else {
210                         strcpy(ibuf, istr);             /**< unknown encoding */
211                         ibuflen = strlen(istr);
212                 }
213
214                 ctdl_iconv_open("UTF-8", charset, &ic);
215                 if (ic != (iconv_t)(-1) ) {
216                         obuflen = 1024;
217                         obuf = (char *) malloc(obuflen);
218                         osav = obuf;
219                         iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
220                         osav[1024-obuflen] = 0;
221
222                         end = start;
223                         end++;
224                         strcpy(start, "");
225                         remove_token(end, 0, '?');
226                         remove_token(end, 0, '?');
227                         remove_token(end, 0, '?');
228                         remove_token(end, 0, '?');
229                         strcpy(end, &end[1]);
230
231                         snprintf(newbuf, sizeof newbuf, "%s%s%s", buf, osav, end);
232                         strcpy(buf, newbuf);
233                         free(osav);
234                         iconv_close(ic);
235                 }
236                 else {
237                         end = start;
238                         end++;
239                         strcpy(start, "");
240                         remove_token(end, 0, '?');
241                         remove_token(end, 0, '?');
242                         remove_token(end, 0, '?');
243                         remove_token(end, 0, '?');
244                         strcpy(end, &end[1]);
245
246                         snprintf(newbuf, sizeof newbuf, "%s(unreadable)%s", buf, end);
247                         strcpy(buf, newbuf);
248                 }
249
250                 free(isav);
251
252                 /*
253                  * Since spammers will go to all sorts of absurd lengths to get their
254                  * messages through, there are LOTS of corrupt headers out there.
255                  * So, prevent a really badly formed RFC2047 header from throwing
256                  * this function into an infinite loop.
257                  */
258                 ++passes;
259                 if (passes > 20) return;
260
261                 start = strstr(buf, "=?");
262                 FindNextEnd((start != NULL)? start : buf, end);
263         }
264
265 }
266 #else
267 inline void utf8ify_rfc822_string(char *a){};
268
269 #endif
270
271
272
273 struct trynamebuf {
274         char buffer1[SIZ];
275         char buffer2[SIZ];
276 };
277
278 char *inetcfg = NULL;
279 struct spamstrings_t *spamstrings = NULL;
280
281
282 /*
283  * Return nonzero if the supplied name is an alias for this host.
284  */
285 int CtdlHostAlias(char *fqdn) {
286         int config_lines;
287         int i;
288         char buf[256];
289         char host[256], type[256];
290         int found = 0;
291
292         if (fqdn == NULL) return(hostalias_nomatch);
293         if (IsEmptyStr(fqdn)) return(hostalias_nomatch);
294         if (!strcasecmp(fqdn, "localhost")) return(hostalias_localhost);
295         if (!strcasecmp(fqdn, config.c_fqdn)) return(hostalias_localhost);
296         if (!strcasecmp(fqdn, config.c_nodename)) return(hostalias_localhost);
297         if (inetcfg == NULL) return(hostalias_nomatch);
298
299         config_lines = num_tokens(inetcfg, '\n');
300         for (i=0; i<config_lines; ++i) {
301                 extract_token(buf, inetcfg, i, '\n', sizeof buf);
302                 extract_token(host, buf, 0, '|', sizeof host);
303                 extract_token(type, buf, 1, '|', sizeof type);
304
305                 found = 0;
306
307                 /* Process these in a specific order, in case there are multiple matches.
308                  * We want directory to override masq, for example.
309                  */
310
311                 if ( (!strcasecmp(type, "masqdomain")) && (!strcasecmp(fqdn, host))) {
312                         found = hostalias_masq;
313                 }
314                 if ( (!strcasecmp(type, "localhost")) && (!strcasecmp(fqdn, host))) {
315                         found = hostalias_localhost;
316                 }
317                 if ( (!strcasecmp(type, "directory")) && (!strcasecmp(fqdn, host))) {
318                         found = hostalias_directory;
319                 }
320
321                 if (found) return(found);
322         }
323
324         return(hostalias_nomatch);
325 }
326
327
328
329 /*
330  * Determine whether a given Internet address belongs to the current user
331  */
332 int CtdlIsMe(char *addr, int addr_buf_len)
333 {
334         recptypes *recp;
335         int i;
336
337         recp = validate_recipients(addr, NULL, 0);
338         if (recp == NULL) return(0);
339
340         if (recp->num_local == 0) {
341                 free_recipients(recp);
342                 return(0);
343         }
344
345         for (i=0; i<recp->num_local; ++i) {
346                 extract_token(addr, recp->recp_local, i, '|', addr_buf_len);
347                 if (!strcasecmp(addr, CC->user.fullname)) {
348                         free_recipients(recp);
349                         return(1);
350                 }
351         }
352
353         free_recipients(recp);
354         return(0);
355 }
356
357
358 /* If the last item in a list of recipients was truncated to a partial address,
359  * remove it completely in order to avoid choking libSieve
360  */
361 void sanitize_truncated_recipient(char *str)
362 {
363         if (!str) return;
364         if (num_tokens(str, ',') < 2) return;
365
366         int len = strlen(str);
367         if (len < 900) return;
368         if (len > 998) str[998] = 0;
369
370         char *cptr = strrchr(str, ',');
371         if (!cptr) return;
372
373         char *lptr = strchr(cptr, '<');
374         char *rptr = strchr(cptr, '>');
375
376         if ( (lptr) && (rptr) && (rptr > lptr) ) return;
377
378         *cptr = 0;
379 }
380
381
382
383
384
385 /*
386  * This function is self explanatory.
387  * (What can I say, I'm in a weird mood today...)
388  */
389 void remove_any_whitespace_to_the_left_or_right_of_at_symbol(char *name)
390 {
391         int i;
392
393         for (i = 0; i < strlen(name); ++i) {
394                 if (name[i] == '@') {
395                         while (isspace(name[i - 1]) && i > 0) {
396                                 strcpy(&name[i - 1], &name[i]);
397                                 --i;
398                         }
399                         while (isspace(name[i + 1])) {
400                                 strcpy(&name[i + 1], &name[i + 2]);
401                         }
402                 }
403         }
404 }
405
406
407 /*
408  * Aliasing for network mail.
409  * (Error messages have been commented out, because this is a server.)
410  */
411 int alias(char *name)
412 {                               /* process alias and routing info for mail */
413         struct CitContext *CCC = CC;
414         FILE *fp;
415         int a, i;
416         char aaa[SIZ], bbb[SIZ];
417         char *ignetcfg = NULL;
418         char *ignetmap = NULL;
419         int at = 0;
420         char node[64];
421         char testnode[64];
422         char buf[SIZ];
423
424         char original_name[256];
425         safestrncpy(original_name, name, sizeof original_name);
426
427         striplt(name);
428         remove_any_whitespace_to_the_left_or_right_of_at_symbol(name);
429         stripallbut(name, '<', '>');
430
431         fp = fopen(file_mail_aliases, "r");
432         if (fp == NULL) {
433                 fp = fopen("/dev/null", "r");
434         }
435         if (fp == NULL) {
436                 return (MES_ERROR);
437         }
438         strcpy(aaa, "");
439         strcpy(bbb, "");
440         while (fgets(aaa, sizeof aaa, fp) != NULL) {
441                 while (isspace(name[0]))
442                         strcpy(name, &name[1]);
443                 aaa[strlen(aaa) - 1] = 0;
444                 strcpy(bbb, "");
445                 for (a = 0; a < strlen(aaa); ++a) {
446                         if (aaa[a] == ',') {
447                                 strcpy(bbb, &aaa[a + 1]);
448                                 aaa[a] = 0;
449                         }
450                 }
451                 if (!strcasecmp(name, aaa))
452                         strcpy(name, bbb);
453         }
454         fclose(fp);
455
456         /* Hit the Global Address Book */
457         if (CtdlDirectoryLookup(aaa, name, sizeof aaa) == 0) {
458                 strcpy(name, aaa);
459         }
460
461         if (strcasecmp(original_name, name)) {
462                 MSG_syslog(LOG_INFO, "%s is being forwarded to %s\n", original_name, name);
463         }
464
465         /* Change "user @ xxx" to "user" if xxx is an alias for this host */
466         for (a=0; a<strlen(name); ++a) {
467                 if (name[a] == '@') {
468                         if (CtdlHostAlias(&name[a+1]) == hostalias_localhost) {
469                                 name[a] = 0;
470                                 MSG_syslog(LOG_INFO, "Changed to <%s>\n", name);
471                         }
472                 }
473         }
474
475         /* determine local or remote type, see citadel.h */
476         at = haschar(name, '@');
477         if (at == 0) return(MES_LOCAL);         /* no @'s - local address */
478         if (at > 1) return(MES_ERROR);          /* >1 @'s - invalid address */
479         remove_any_whitespace_to_the_left_or_right_of_at_symbol(name);
480
481         /* figure out the delivery mode */
482         extract_token(node, name, 1, '@', sizeof node);
483
484         /* If there are one or more dots in the nodename, we assume that it
485          * is an FQDN and will attempt SMTP delivery to the Internet.
486          */
487         if (haschar(node, '.') > 0) {
488                 return(MES_INTERNET);
489         }
490
491         /* Otherwise we look in the IGnet maps for a valid Citadel node.
492          * Try directly-connected nodes first...
493          */
494         ignetcfg = CtdlGetSysConfig(IGNETCFG);
495         for (i=0; i<num_tokens(ignetcfg, '\n'); ++i) {
496                 extract_token(buf, ignetcfg, i, '\n', sizeof buf);
497                 extract_token(testnode, buf, 0, '|', sizeof testnode);
498                 if (!strcasecmp(node, testnode)) {
499                         free(ignetcfg);
500                         return(MES_IGNET);
501                 }
502         }
503         free(ignetcfg);
504
505         /*
506          * Then try nodes that are two or more hops away.
507          */
508         ignetmap = CtdlGetSysConfig(IGNETMAP);
509         for (i=0; i<num_tokens(ignetmap, '\n'); ++i) {
510                 extract_token(buf, ignetmap, i, '\n', sizeof buf);
511                 extract_token(testnode, buf, 0, '|', sizeof testnode);
512                 if (!strcasecmp(node, testnode)) {
513                         free(ignetmap);
514                         return(MES_IGNET);
515                 }
516         }
517         free(ignetmap);
518
519         /* If we get to this point it's an invalid node name */
520         return (MES_ERROR);
521 }
522
523
524
525 /*
526  * Validate recipients, count delivery types and errors, and handle aliasing
527  * FIXME check for dupes!!!!!
528  *
529  * Returns 0 if all addresses are ok, ret->num_error = -1 if no addresses 
530  * were specified, or the number of addresses found invalid.
531  *
532  * Caller needs to free the result using free_recipients()
533  */
534 recptypes *validate_recipients(const char *supplied_recipients, 
535                                const char *RemoteIdentifier, 
536                                int Flags) {
537         struct CitContext *CCC = CC;
538         recptypes *ret;
539         char *recipients = NULL;
540         char *org_recp;
541         char this_recp[256];
542         char this_recp_cooked[256];
543         char append[SIZ];
544         long len;
545         int num_recps = 0;
546         int i, j;
547         int mailtype;
548         int invalid;
549         struct ctdluser tempUS;
550         struct ctdlroom tempQR;
551         struct ctdlroom tempQR2;
552         int err = 0;
553         char errmsg[SIZ];
554         int in_quotes = 0;
555
556         /* Initialize */
557         ret = (recptypes *) malloc(sizeof(recptypes));
558         if (ret == NULL) return(NULL);
559
560         /* Set all strings to null and numeric values to zero */
561         memset(ret, 0, sizeof(recptypes));
562
563         if (supplied_recipients == NULL) {
564                 recipients = strdup("");
565         }
566         else {
567                 recipients = strdup(supplied_recipients);
568         }
569
570         /* Allocate some memory.  Yes, this allocates 500% more memory than we will
571          * actually need, but it's healthier for the heap than doing lots of tiny
572          * realloc() calls instead.
573          */
574         len = strlen(recipients) + 1024;
575         ret->errormsg = malloc(len);
576         ret->recp_local = malloc(len);
577         ret->recp_internet = malloc(len);
578         ret->recp_ignet = malloc(len);
579         ret->recp_room = malloc(len);
580         ret->display_recp = malloc(len);
581         ret->recp_orgroom = malloc(len);
582         org_recp = malloc(len);
583
584         ret->errormsg[0] = 0;
585         ret->recp_local[0] = 0;
586         ret->recp_internet[0] = 0;
587         ret->recp_ignet[0] = 0;
588         ret->recp_room[0] = 0;
589         ret->recp_orgroom[0] = 0;
590         ret->display_recp[0] = 0;
591
592         ret->recptypes_magic = RECPTYPES_MAGIC;
593
594         /* Change all valid separator characters to commas */
595         for (i=0; !IsEmptyStr(&recipients[i]); ++i) {
596                 if ((recipients[i] == ';') || (recipients[i] == '|')) {
597                         recipients[i] = ',';
598                 }
599         }
600
601         /* Now start extracting recipients... */
602
603         while (!IsEmptyStr(recipients)) {
604                 for (i=0; i<=strlen(recipients); ++i) {
605                         if (recipients[i] == '\"') in_quotes = 1 - in_quotes;
606                         if ( ( (recipients[i] == ',') && (!in_quotes) ) || (recipients[i] == 0) ) {
607                                 safestrncpy(this_recp, recipients, i+1);
608                                 this_recp[i] = 0;
609                                 if (recipients[i] == ',') {
610                                         strcpy(recipients, &recipients[i+1]);
611                                 }
612                                 else {
613                                         strcpy(recipients, "");
614                                 }
615                                 break;
616                         }
617                 }
618
619                 striplt(this_recp);
620                 if (IsEmptyStr(this_recp))
621                         break;
622                 MSG_syslog(LOG_DEBUG, "Evaluating recipient #%d: %s\n", num_recps, this_recp);
623                 ++num_recps;
624
625                 strcpy(org_recp, this_recp);
626                 alias(this_recp);
627                 alias(this_recp);
628                 mailtype = alias(this_recp);
629
630                 for (j = 0; !IsEmptyStr(&this_recp[j]); ++j) {
631                         if (this_recp[j]=='_') {
632                                 this_recp_cooked[j] = ' ';
633                         }
634                         else {
635                                 this_recp_cooked[j] = this_recp[j];
636                         }
637                 }
638                 this_recp_cooked[j] = '\0';
639                 invalid = 0;
640                 errmsg[0] = 0;
641                 switch(mailtype) {
642                 case MES_LOCAL:
643                         if (!strcasecmp(this_recp, "sysop")) {
644                                 ++ret->num_room;
645                                 strcpy(this_recp, config.c_aideroom);
646                                 if (!IsEmptyStr(ret->recp_room)) {
647                                         strcat(ret->recp_room, "|");
648                                 }
649                                 strcat(ret->recp_room, this_recp);
650                         }
651                         else if ( (!strncasecmp(this_recp, "room_", 5))
652                                   && (!CtdlGetRoom(&tempQR, &this_recp_cooked[5])) ) {
653
654                                 /* Save room so we can restore it later */
655                                 tempQR2 = CCC->room;
656                                 CCC->room = tempQR;
657                                         
658                                 /* Check permissions to send mail to this room */
659                                 err = CtdlDoIHavePermissionToPostInThisRoom(
660                                         errmsg, 
661                                         sizeof errmsg, 
662                                         RemoteIdentifier,
663                                         Flags,
664                                         0                       /* 0 = not a reply */
665                                         );
666                                 if (err)
667                                 {
668                                         ++ret->num_error;
669                                         invalid = 1;
670                                 } 
671                                 else {
672                                         ++ret->num_room;
673                                         if (!IsEmptyStr(ret->recp_room)) {
674                                                 strcat(ret->recp_room, "|");
675                                         }
676                                         strcat(ret->recp_room, &this_recp_cooked[5]);
677
678                                         if (!IsEmptyStr(ret->recp_orgroom)) {
679                                                 strcat(ret->recp_orgroom, "|");
680                                         }
681                                         strcat(ret->recp_orgroom, org_recp);
682
683                                 }
684                                         
685                                 /* Restore room in case something needs it */
686                                 CCC->room = tempQR2;
687
688                         }
689                         else if (CtdlGetUser(&tempUS, this_recp) == 0) {
690                                 ++ret->num_local;
691                                 strcpy(this_recp, tempUS.fullname);
692                                 if (!IsEmptyStr(ret->recp_local)) {
693                                         strcat(ret->recp_local, "|");
694                                 }
695                                 strcat(ret->recp_local, this_recp);
696                         }
697                         else if (CtdlGetUser(&tempUS, this_recp_cooked) == 0) {
698                                 ++ret->num_local;
699                                 strcpy(this_recp, tempUS.fullname);
700                                 if (!IsEmptyStr(ret->recp_local)) {
701                                         strcat(ret->recp_local, "|");
702                                 }
703                                 strcat(ret->recp_local, this_recp);
704                         }
705                         else {
706                                 ++ret->num_error;
707                                 invalid = 1;
708                         }
709                         break;
710                 case MES_INTERNET:
711                         /* Yes, you're reading this correctly: if the target
712                          * domain points back to the local system or an attached
713                          * Citadel directory, the address is invalid.  That's
714                          * because if the address were valid, we would have
715                          * already translated it to a local address by now.
716                          */
717                         if (IsDirectory(this_recp, 0)) {
718                                 ++ret->num_error;
719                                 invalid = 1;
720                         }
721                         else {
722                                 ++ret->num_internet;
723                                 if (!IsEmptyStr(ret->recp_internet)) {
724                                         strcat(ret->recp_internet, "|");
725                                 }
726                                 strcat(ret->recp_internet, this_recp);
727                         }
728                         break;
729                 case MES_IGNET:
730                         ++ret->num_ignet;
731                         if (!IsEmptyStr(ret->recp_ignet)) {
732                                 strcat(ret->recp_ignet, "|");
733                         }
734                         strcat(ret->recp_ignet, this_recp);
735                         break;
736                 case MES_ERROR:
737                         ++ret->num_error;
738                         invalid = 1;
739                         break;
740                 }
741                 if (invalid) {
742                         if (IsEmptyStr(errmsg)) {
743                                 snprintf(append, sizeof append, "Invalid recipient: %s", this_recp);
744                         }
745                         else {
746                                 snprintf(append, sizeof append, "%s", errmsg);
747                         }
748                         if ( (strlen(ret->errormsg) + strlen(append) + 3) < SIZ) {
749                                 if (!IsEmptyStr(ret->errormsg)) {
750                                         strcat(ret->errormsg, "; ");
751                                 }
752                                 strcat(ret->errormsg, append);
753                         }
754                 }
755                 else {
756                         if (IsEmptyStr(ret->display_recp)) {
757                                 strcpy(append, this_recp);
758                         }
759                         else {
760                                 snprintf(append, sizeof append, ", %s", this_recp);
761                         }
762                         if ( (strlen(ret->display_recp)+strlen(append)) < SIZ) {
763                                 strcat(ret->display_recp, append);
764                         }
765                 }
766         }
767         free(org_recp);
768
769         if ((ret->num_local + ret->num_internet + ret->num_ignet +
770              ret->num_room + ret->num_error) == 0) {
771                 ret->num_error = (-1);
772                 strcpy(ret->errormsg, "No recipients specified.");
773         }
774
775         MSGM_syslog(LOG_DEBUG, "validate_recipients()\n");
776         MSG_syslog(LOG_DEBUG, " local: %d <%s>\n", ret->num_local, ret->recp_local);
777         MSG_syslog(LOG_DEBUG, "  room: %d <%s>\n", ret->num_room, ret->recp_room);
778         MSG_syslog(LOG_DEBUG, "  inet: %d <%s>\n", ret->num_internet, ret->recp_internet);
779         MSG_syslog(LOG_DEBUG, " ignet: %d <%s>\n", ret->num_ignet, ret->recp_ignet);
780         MSG_syslog(LOG_DEBUG, " error: %d <%s>\n", ret->num_error, ret->errormsg);
781
782         free(recipients);
783         return(ret);
784 }
785
786
787 /*
788  * Destructor for recptypes
789  */
790 void free_recipients(recptypes *valid) {
791
792         if (valid == NULL) {
793                 return;
794         }
795
796         if (valid->recptypes_magic != RECPTYPES_MAGIC) {
797                 struct CitContext *CCC = CC;
798                 MSGM_syslog(LOG_EMERG, "Attempt to call free_recipients() on some other data type!\n");
799                 abort();
800         }
801
802         if (valid->errormsg != NULL)            free(valid->errormsg);
803         if (valid->recp_local != NULL)          free(valid->recp_local);
804         if (valid->recp_internet != NULL)       free(valid->recp_internet);
805         if (valid->recp_ignet != NULL)          free(valid->recp_ignet);
806         if (valid->recp_room != NULL)           free(valid->recp_room);
807         if (valid->recp_orgroom != NULL)        free(valid->recp_orgroom);
808         if (valid->display_recp != NULL)        free(valid->display_recp);
809         if (valid->bounce_to != NULL)           free(valid->bounce_to);
810         if (valid->envelope_from != NULL)       free(valid->envelope_from);
811         if (valid->sending_room != NULL)        free(valid->sending_room);
812         free(valid);
813 }
814
815
816 char *qp_encode_email_addrs(char *source)
817 {
818         struct CitContext *CCC = CC;
819         char *user, *node, *name;
820         const char headerStr[] = "=?UTF-8?Q?";
821         char *Encoded;
822         char *EncodedName;
823         char *nPtr;
824         int need_to_encode = 0;
825         long SourceLen;
826         long EncodedMaxLen;
827         long nColons = 0;
828         long *AddrPtr;
829         long *AddrUtf8;
830         long nAddrPtrMax = 50;
831         long nmax;
832         int InQuotes = 0;
833         int i, n;
834
835         if (source == NULL) return source;
836         if (IsEmptyStr(source)) return source;
837         if (MessageDebugEnabled != 0) cit_backtrace();
838         MSG_syslog(LOG_DEBUG, "qp_encode_email_addrs: [%s]\n", source);
839
840         AddrPtr = malloc (sizeof (long) * nAddrPtrMax);
841         AddrUtf8 = malloc (sizeof (long) * nAddrPtrMax);
842         memset(AddrUtf8, 0, sizeof (long) * nAddrPtrMax);
843         *AddrPtr = 0;
844         i = 0;
845         while (!IsEmptyStr (&source[i])) {
846                 if (nColons >= nAddrPtrMax){
847                         long *ptr;
848
849                         ptr = (long *) malloc(sizeof (long) * nAddrPtrMax * 2);
850                         memcpy (ptr, AddrPtr, sizeof (long) * nAddrPtrMax);
851                         free (AddrPtr), AddrPtr = ptr;
852
853                         ptr = (long *) malloc(sizeof (long) * nAddrPtrMax * 2);
854                         memset(&ptr[nAddrPtrMax], 0, 
855                                sizeof (long) * nAddrPtrMax);
856
857                         memcpy (ptr, AddrUtf8, sizeof (long) * nAddrPtrMax);
858                         free (AddrUtf8), AddrUtf8 = ptr;
859                         nAddrPtrMax *= 2;                               
860                 }
861                 if (((unsigned char) source[i] < 32) || 
862                     ((unsigned char) source[i] > 126)) {
863                         need_to_encode = 1;
864                         AddrUtf8[nColons] = 1;
865                 }
866                 if (source[i] == '"')
867                         InQuotes = !InQuotes;
868                 if (!InQuotes && source[i] == ',') {
869                         AddrPtr[nColons] = i;
870                         nColons++;
871                 }
872                 i++;
873         }
874         if (need_to_encode == 0) {
875                 free(AddrPtr);
876                 free(AddrUtf8);
877                 return source;
878         }
879
880         SourceLen = i;
881         EncodedMaxLen = nColons * (sizeof(headerStr) + 3) + SourceLen * 3;
882         Encoded = (char*) malloc (EncodedMaxLen);
883
884         for (i = 0; i < nColons; i++)
885                 source[AddrPtr[i]++] = '\0';
886         /* TODO: if libidn, this might get larger*/
887         user = malloc(SourceLen + 1);
888         node = malloc(SourceLen + 1);
889         name = malloc(SourceLen + 1);
890
891         nPtr = Encoded;
892         *nPtr = '\0';
893         for (i = 0; i < nColons && nPtr != NULL; i++) {
894                 nmax = EncodedMaxLen - (nPtr - Encoded);
895                 if (AddrUtf8[i]) {
896                         process_rfc822_addr(&source[AddrPtr[i]], 
897                                             user,
898                                             node,
899                                             name);
900                         /* TODO: libIDN here ! */
901                         if (IsEmptyStr(name)) {
902                                 n = snprintf(nPtr, nmax, 
903                                              (i==0)?"%s@%s" : ",%s@%s",
904                                              user, node);
905                         }
906                         else {
907                                 EncodedName = rfc2047encode(name, strlen(name));                        
908                                 n = snprintf(nPtr, nmax, 
909                                              (i==0)?"%s <%s@%s>" : ",%s <%s@%s>",
910                                              EncodedName, user, node);
911                                 free(EncodedName);
912                         }
913                 }
914                 else { 
915                         n = snprintf(nPtr, nmax, 
916                                      (i==0)?"%s" : ",%s",
917                                      &source[AddrPtr[i]]);
918                 }
919                 if (n > 0 )
920                         nPtr += n;
921                 else { 
922                         char *ptr, *nnPtr;
923                         ptr = (char*) malloc(EncodedMaxLen * 2);
924                         memcpy(ptr, Encoded, EncodedMaxLen);
925                         nnPtr = ptr + (nPtr - Encoded), nPtr = nnPtr;
926                         free(Encoded), Encoded = ptr;
927                         EncodedMaxLen *= 2;
928                         i--; /* do it once more with properly lengthened buffer */
929                 }
930         }
931         for (i = 0; i < nColons; i++)
932                 source[--AddrPtr[i]] = ',';
933
934         free(user);
935         free(node);
936         free(name);
937         free(AddrUtf8);
938         free(AddrPtr);
939         return Encoded;
940 }
941
942
943 /*
944  * Return 0 if a given string fuzzy-matches a Citadel user account
945  *
946  * FIXME ... this needs to be updated to handle aliases.
947  */
948 int fuzzy_match(struct ctdluser *us, char *matchstring) {
949         int a;
950         long len;
951
952         if ( (!strncasecmp(matchstring, "cit", 3)) 
953            && (atol(&matchstring[3]) == us->usernum)) {
954                 return 0;
955         }
956
957         len = strlen(matchstring);
958         for (a=0; !IsEmptyStr(&us->fullname[a]); ++a) {
959                 if (!strncasecmp(&us->fullname[a],
960                    matchstring, len)) {
961                         return 0;
962                 }
963         }
964         return -1;
965 }
966
967
968 /*
969  * Unfold a multi-line field into a single line, removing multi-whitespaces
970  */
971 void unfold_rfc822_field(char **field, char **FieldEnd) 
972 {
973         int quote = 0;
974         char *pField = *field;
975         char *sField;
976         char *pFieldEnd = *FieldEnd;
977
978         while (isspace(*pField))
979                 pField++;
980         /* remove leading/trailing whitespace */
981         ;
982
983         while (isspace(*pFieldEnd))
984                 pFieldEnd --;
985
986         *FieldEnd = pFieldEnd;
987         /* convert non-space whitespace to spaces, and remove double blanks */
988         for (sField = *field = pField; 
989              sField < pFieldEnd; 
990              pField++, sField++)
991         {
992                 if ((*sField=='\r') || (*sField=='\n'))
993                 {
994                         int Offset = 1;
995                         while (((*(sField + Offset) == '\r') ||
996                                 (*(sField + Offset) == '\n') ||
997                                 (isspace(*(sField + Offset)))) && 
998                                (sField + Offset < pFieldEnd))
999                                 Offset ++;
1000                         sField += Offset;
1001                         *pField = *sField;
1002                 }
1003                 else {
1004                         if (*sField=='\"') quote = 1 - quote;
1005                         if (!quote) {
1006                                 if (isspace(*sField))
1007                                 {
1008                                         *pField = ' ';
1009                                         pField++;
1010                                         sField++;
1011                                         
1012                                         while ((sField < pFieldEnd) && 
1013                                                isspace(*sField))
1014                                                 sField++;
1015                                         *pField = *sField;
1016                                 }
1017                                 else *pField = *sField;
1018                         }
1019                         else *pField = *sField;
1020                 }
1021         }
1022         *pField = '\0';
1023         *FieldEnd = pField - 1;
1024 }
1025
1026
1027
1028 /*
1029  * Split an RFC822-style address into userid, host, and full name
1030  *
1031  */
1032 void process_rfc822_addr(const char *rfc822, char *user, char *node, char *name)
1033 {
1034         int a;
1035
1036         strcpy(user, "");
1037         strcpy(node, config.c_fqdn);
1038         strcpy(name, "");
1039
1040         if (rfc822 == NULL) return;
1041
1042         /* extract full name - first, it's From minus <userid> */
1043         strcpy(name, rfc822);
1044         stripout(name, '<', '>');
1045
1046         /* strip anything to the left of a bang */
1047         while ((!IsEmptyStr(name)) && (haschar(name, '!') > 0))
1048                 strcpy(name, &name[1]);
1049
1050         /* and anything to the right of a @ or % */
1051         for (a = 0; a < strlen(name); ++a) {
1052                 if (name[a] == '@')
1053                         name[a] = 0;
1054                 if (name[a] == '%')
1055                         name[a] = 0;
1056         }
1057
1058         /* but if there are parentheses, that changes the rules... */
1059         if ((haschar(rfc822, '(') == 1) && (haschar(rfc822, ')') == 1)) {
1060                 strcpy(name, rfc822);
1061                 stripallbut(name, '(', ')');
1062         }
1063
1064         /* but if there are a set of quotes, that supersedes everything */
1065         if (haschar(rfc822, 34) == 2) {
1066                 strcpy(name, rfc822);
1067                 while ((!IsEmptyStr(name)) && (name[0] != 34)) {
1068                         strcpy(&name[0], &name[1]);
1069                 }
1070                 strcpy(&name[0], &name[1]);
1071                 for (a = 0; a < strlen(name); ++a)
1072                         if (name[a] == 34)
1073                                 name[a] = 0;
1074         }
1075         /* extract user id */
1076         strcpy(user, rfc822);
1077
1078         /* first get rid of anything in parens */
1079         stripout(user, '(', ')');
1080
1081         /* if there's a set of angle brackets, strip it down to that */
1082         if ((haschar(user, '<') == 1) && (haschar(user, '>') == 1)) {
1083                 stripallbut(user, '<', '>');
1084         }
1085
1086         /* strip anything to the left of a bang */
1087         while ((!IsEmptyStr(user)) && (haschar(user, '!') > 0))
1088                 strcpy(user, &user[1]);
1089
1090         /* and anything to the right of a @ or % */
1091         for (a = 0; a < strlen(user); ++a) {
1092                 if (user[a] == '@')
1093                         user[a] = 0;
1094                 if (user[a] == '%')
1095                         user[a] = 0;
1096         }
1097
1098
1099         /* extract node name */
1100         strcpy(node, rfc822);
1101
1102         /* first get rid of anything in parens */
1103         stripout(node, '(', ')');
1104
1105         /* if there's a set of angle brackets, strip it down to that */
1106         if ((haschar(node, '<') == 1) && (haschar(node, '>') == 1)) {
1107                 stripallbut(node, '<', '>');
1108         }
1109
1110         /* If no node specified, tack ours on instead */
1111         if (
1112                 (haschar(node, '@')==0)
1113                 && (haschar(node, '%')==0)
1114                 && (haschar(node, '!')==0)
1115         ) {
1116                 strcpy(node, config.c_nodename);
1117         }
1118
1119         else {
1120
1121                 /* strip anything to the left of a @ */
1122                 while ((!IsEmptyStr(node)) && (haschar(node, '@') > 0))
1123                         strcpy(node, &node[1]);
1124         
1125                 /* strip anything to the left of a % */
1126                 while ((!IsEmptyStr(node)) && (haschar(node, '%') > 0))
1127                         strcpy(node, &node[1]);
1128         
1129                 /* reduce multiple system bang paths to node!user */
1130                 while ((!IsEmptyStr(node)) && (haschar(node, '!') > 1))
1131                         strcpy(node, &node[1]);
1132         
1133                 /* now get rid of the user portion of a node!user string */
1134                 for (a = 0; a < strlen(node); ++a)
1135                         if (node[a] == '!')
1136                                 node[a] = 0;
1137         }
1138
1139         /* strip leading and trailing spaces in all strings */
1140         striplt(user);
1141         striplt(node);
1142         striplt(name);
1143
1144         /* If we processed a string that had the address in angle brackets
1145          * but no name outside the brackets, we now have an empty name.  In
1146          * this case, use the user portion of the address as the name.
1147          */
1148         if ((IsEmptyStr(name)) && (!IsEmptyStr(user))) {
1149                 strcpy(name, user);
1150         }
1151 }
1152
1153
1154
1155 /*
1156  * convert_field() is a helper function for convert_internet_message().
1157  * Given start/end positions for an rfc822 field, it converts it to a Citadel
1158  * field if it wants to, and unfolds it if necessary.
1159  *
1160  * Returns 1 if the field was converted and inserted into the Citadel message
1161  * structure, implying that the source field should be removed from the
1162  * message text.
1163  */
1164 int convert_field(struct CtdlMessage *msg, const char *beg, const char *end) {
1165         char *key, *value, *valueend;
1166         long len;
1167         const char *pos;
1168         int i;
1169         const char *colonpos = NULL;
1170         int processed = 0;
1171         char user[1024];
1172         char node[1024];
1173         char name[1024];
1174         char addr[1024];
1175         time_t parsed_date;
1176         long valuelen;
1177
1178         for (pos = end; pos >= beg; pos--) {
1179                 if (*pos == ':') colonpos = pos;
1180         }
1181
1182         if (colonpos == NULL) return(0);        /* no colon? not a valid header line */
1183
1184         len = end - beg;
1185         key = malloc(len + 2);
1186         memcpy(key, beg, len + 1);
1187         key[len] = '\0';
1188         valueend = key + len;
1189         * ( key + (colonpos - beg) ) = '\0';
1190         value = &key[(colonpos - beg) + 1];
1191 /*      printf("Header: [%s]\nValue: [%s]\n", key, value); */
1192         unfold_rfc822_field(&value, &valueend);
1193         valuelen = valueend - value + 1;
1194 /*      printf("UnfoldedValue: [%s]\n", value); */
1195
1196         /*
1197          * Here's the big rfc822-to-citadel loop.
1198          */
1199
1200         /* Date/time is converted into a unix timestamp.  If the conversion
1201          * fails, we replace it with the time the message arrived locally.
1202          */
1203         if (!strcasecmp(key, "Date")) {
1204                 parsed_date = parsedate(value);
1205                 if (parsed_date < 0L) parsed_date = time(NULL);
1206
1207                 if (CM_IsEmpty(msg, eTimestamp))
1208                         CM_SetFieldLONG(msg, eTimestamp, parsed_date);
1209                 processed = 1;
1210         }
1211
1212         else if (!strcasecmp(key, "From")) {
1213                 process_rfc822_addr(value, user, node, name);
1214                 syslog(LOG_DEBUG, "Converted to <%s@%s> (%s)\n", user, node, name);
1215                 snprintf(addr, sizeof(addr), "%s@%s", user, node);
1216                 if (CM_IsEmpty(msg, eAuthor))
1217                         CM_SetField(msg, eAuthor, name, strlen(name));
1218                 if (CM_IsEmpty(msg, erFc822Addr))
1219                         CM_SetField(msg, erFc822Addr, addr, strlen(addr));
1220                 processed = 1;
1221         }
1222
1223         else if (!strcasecmp(key, "Subject")) {
1224                 if (CM_IsEmpty(msg, eMsgSubject))
1225                         CM_SetField(msg, eMsgSubject, value, valuelen);
1226                 processed = 1;
1227         }
1228
1229         else if (!strcasecmp(key, "List-ID")) {
1230                 if (CM_IsEmpty(msg, eListID))
1231                         CM_SetField(msg, eListID, value, valuelen);
1232                 processed = 1;
1233         }
1234
1235         else if (!strcasecmp(key, "To")) {
1236                 if (CM_IsEmpty(msg, eRecipient))
1237                         CM_SetField(msg, eRecipient, value, valuelen);
1238                 processed = 1;
1239         }
1240
1241         else if (!strcasecmp(key, "CC")) {
1242                 if (CM_IsEmpty(msg, eCarbonCopY))
1243                         CM_SetField(msg, eCarbonCopY, value, valuelen);
1244                 processed = 1;
1245         }
1246
1247         else if (!strcasecmp(key, "Message-ID")) {
1248                 if (!CM_IsEmpty(msg, emessageId)) {
1249                         syslog(LOG_WARNING, "duplicate message id\n");
1250                 }
1251                 else {
1252                         char *pValue;
1253                         long pValueLen;
1254
1255                         pValue = value;
1256                         pValueLen = valuelen;
1257                         /* Strip angle brackets */
1258                         while (haschar(pValue, '<') > 0) {
1259                                 pValue ++;
1260                                 pValueLen --;
1261                         }
1262
1263                         for (i = 0; i <= pValueLen; ++i)
1264                                 if (pValue[i] == '>') {
1265                                         pValueLen = i;
1266                                         break;
1267                                 }
1268
1269                         CM_SetField(msg, emessageId, pValue, pValueLen);
1270                 }
1271
1272                 processed = 1;
1273         }
1274
1275         else if (!strcasecmp(key, "Return-Path")) {
1276                 if (CM_IsEmpty(msg, eMessagePath))
1277                         CM_SetField(msg, eMessagePath, value, valuelen);
1278                 processed = 1;
1279         }
1280
1281         else if (!strcasecmp(key, "Envelope-To")) {
1282                 if (CM_IsEmpty(msg, eenVelopeTo))
1283                         CM_SetField(msg, eenVelopeTo, value, valuelen);
1284                 processed = 1;
1285         }
1286
1287         else if (!strcasecmp(key, "References")) {
1288                 CM_SetField(msg, eWeferences, value, valuelen);
1289                 processed = 1;
1290         }
1291
1292         else if (!strcasecmp(key, "Reply-To")) {
1293                 CM_SetField(msg, eReplyTo, value, valuelen);
1294                 processed = 1;
1295         }
1296
1297         else if (!strcasecmp(key, "In-reply-to")) {
1298                 if (CM_IsEmpty(msg, eWeferences)) /* References: supersedes In-reply-to: */
1299                         CM_SetField(msg, eWeferences, value, valuelen);
1300                 processed = 1;
1301         }
1302
1303
1304
1305         /* Clean up and move on. */
1306         free(key);      /* Don't free 'value', it's actually the same buffer */
1307         return processed;
1308 }
1309
1310
1311 /*
1312  * Convert RFC822 references format (References) to Citadel references format (Weferences)
1313  */
1314 void convert_references_to_wefewences(char *str) {
1315         int bracket_nesting = 0;
1316         char *ptr = str;
1317         char *moveptr = NULL;
1318         char ch;
1319
1320         while(*ptr) {
1321                 ch = *ptr;
1322                 if (ch == '>') {
1323                         --bracket_nesting;
1324                         if (bracket_nesting < 0) bracket_nesting = 0;
1325                 }
1326                 if ((ch == '>') && (bracket_nesting == 0) && (*(ptr+1)) && (ptr>str) ) {
1327                         *ptr = '|';
1328                         ++ptr;
1329                 }
1330                 else if (bracket_nesting > 0) {
1331                         ++ptr;
1332                 }
1333                 else {
1334                         moveptr = ptr;
1335                         while (*moveptr) {
1336                                 *moveptr = *(moveptr+1);
1337                                 ++moveptr;
1338                         }
1339                 }
1340                 if (ch == '<') ++bracket_nesting;
1341         }
1342
1343 }
1344
1345
1346 /*
1347  * Convert an RFC822 message (headers + body) to a CtdlMessage structure.
1348  * NOTE: the supplied buffer becomes part of the CtdlMessage structure, and
1349  * will be deallocated when CM_Free() is called.  Therefore, the
1350  * supplied buffer should be DEREFERENCED.  It should not be freed or used
1351  * again.
1352  */
1353 struct CtdlMessage *convert_internet_message(char *rfc822) {
1354         StrBuf *RFCBuf = NewStrBufPlain(rfc822, -1);
1355         free (rfc822);
1356         return convert_internet_message_buf(&RFCBuf);
1357 }
1358
1359
1360
1361 struct CtdlMessage *convert_internet_message_buf(StrBuf **rfc822)
1362 {
1363         struct CtdlMessage *msg;
1364         const char *pos, *beg, *end, *totalend;
1365         int done, alldone = 0;
1366         int converted;
1367         StrBuf *OtherHeaders;
1368
1369         msg = malloc(sizeof(struct CtdlMessage));
1370         if (msg == NULL) return msg;
1371
1372         memset(msg, 0, sizeof(struct CtdlMessage));
1373         msg->cm_magic = CTDLMESSAGE_MAGIC;      /* self check */
1374         msg->cm_anon_type = 0;                  /* never anonymous */
1375         msg->cm_format_type = FMT_RFC822;       /* internet message */
1376
1377         pos = ChrPtr(*rfc822);
1378         totalend = pos + StrLength(*rfc822);
1379         done = 0;
1380         OtherHeaders = NewStrBufPlain(NULL, StrLength(*rfc822));
1381
1382         while (!alldone) {
1383
1384                 /* Locate beginning and end of field, keeping in mind that
1385                  * some fields might be multiline
1386                  */
1387                 end = beg = pos;
1388
1389                 while ((end < totalend) && 
1390                        (end == beg) && 
1391                        (done == 0) ) 
1392                 {
1393
1394                         if ( (*pos=='\n') && ((*(pos+1))!=0x20) && ((*(pos+1))!=0x09) )
1395                         {
1396                                 end = pos;
1397                         }
1398
1399                         /* done with headers? */
1400                         if ((*pos=='\n') &&
1401                             ( (*(pos+1)=='\n') ||
1402                               (*(pos+1)=='\r')) ) 
1403                         {
1404                                 alldone = 1;
1405                         }
1406
1407                         if (pos >= (totalend - 1) )
1408                         {
1409                                 end = pos;
1410                                 done = 1;
1411                         }
1412
1413                         ++pos;
1414
1415                 }
1416
1417                 /* At this point we have a field.  Are we interested in it? */
1418                 converted = convert_field(msg, beg, end);
1419
1420                 /* Strip the field out of the RFC822 header if we used it */
1421                 if (!converted) {
1422                         StrBufAppendBufPlain(OtherHeaders, beg, end - beg, 0);
1423                         StrBufAppendBufPlain(OtherHeaders, HKEY("\n"), 0);
1424                 }
1425
1426                 /* If we've hit the end of the message, bail out */
1427                 if (pos >= totalend)
1428                         alldone = 1;
1429         }
1430         StrBufAppendBufPlain(OtherHeaders, HKEY("\n"), 0);
1431         if (pos < totalend)
1432                 StrBufAppendBufPlain(OtherHeaders, pos, totalend - pos, 0);
1433         FreeStrBuf(rfc822);
1434         CM_SetAsFieldSB(msg, eMesageText, &OtherHeaders);
1435
1436         /* Follow-up sanity checks... */
1437
1438         /* If there's no timestamp on this message, set it to now. */
1439         if (CM_IsEmpty(msg, eTimestamp)) {
1440                 CM_SetFieldLONG(msg, eTimestamp, time(NULL));
1441         }
1442
1443         /* If a W (references, or rather, Wefewences) field is present, we
1444          * have to convert it from RFC822 format to Citadel format.
1445          */
1446         if (!CM_IsEmpty(msg, eWeferences)) {
1447                 /// todo: API!
1448                 convert_references_to_wefewences(msg->cm_fields[eWeferences]);
1449         }
1450
1451         return msg;
1452 }
1453
1454
1455
1456 /*
1457  * Look for a particular header field in an RFC822 message text.  If the
1458  * requested field is found, it is unfolded (if necessary) and returned to
1459  * the caller.  The field name is stripped out, leaving only its contents.
1460  * The caller is responsible for freeing the returned buffer.  If the requested
1461  * field is not present, or anything else goes wrong, it returns NULL.
1462  */
1463 char *rfc822_fetch_field(const char *rfc822, const char *fieldname) {
1464         char *fieldbuf = NULL;
1465         const char *end_of_headers;
1466         const char *field_start;
1467         const char *ptr;
1468         char *cont;
1469         char fieldhdr[SIZ];
1470
1471         /* Should never happen, but sometimes we get stupid */
1472         if (rfc822 == NULL) return(NULL);
1473         if (fieldname == NULL) return(NULL);
1474
1475         snprintf(fieldhdr, sizeof fieldhdr, "%s:", fieldname);
1476
1477         /* Locate the end of the headers, so we don't run past that point */
1478         end_of_headers = cbmstrcasestr(rfc822, "\n\r\n");
1479         if (end_of_headers == NULL) {
1480                 end_of_headers = cbmstrcasestr(rfc822, "\n\n");
1481         }
1482         if (end_of_headers == NULL) return (NULL);
1483
1484         field_start = cbmstrcasestr(rfc822, fieldhdr);
1485         if (field_start == NULL) return(NULL);
1486         if (field_start > end_of_headers) return(NULL);
1487
1488         fieldbuf = malloc(SIZ);
1489         strcpy(fieldbuf, "");
1490
1491         ptr = field_start;
1492         ptr = cmemreadline(ptr, fieldbuf, SIZ-strlen(fieldbuf) );
1493         while ( (isspace(ptr[0])) && (ptr < end_of_headers) ) {
1494                 strcat(fieldbuf, " ");
1495                 cont = &fieldbuf[strlen(fieldbuf)];
1496                 ptr = cmemreadline(ptr, cont, SIZ-strlen(fieldbuf) );
1497                 striplt(cont);
1498         }
1499
1500         strcpy(fieldbuf, &fieldbuf[strlen(fieldhdr)]);
1501         striplt(fieldbuf);
1502
1503         return(fieldbuf);
1504 }
1505
1506
1507
1508 /*****************************************************************************
1509  *                      DIRECTORY MANAGEMENT FUNCTIONS                       *
1510  *****************************************************************************/
1511
1512 /*
1513  * Generate the index key for an Internet e-mail address to be looked up
1514  * in the database.
1515  */
1516 void directory_key(char *key, char *addr) {
1517         int i;
1518         int keylen = 0;
1519
1520         for (i=0; !IsEmptyStr(&addr[i]); ++i) {
1521                 if (!isspace(addr[i])) {
1522                         key[keylen++] = tolower(addr[i]);
1523                 }
1524         }
1525         key[keylen++] = 0;
1526
1527         syslog(LOG_DEBUG, "Directory key is <%s>\n", key);
1528 }
1529
1530
1531
1532 /* Return nonzero if the supplied address is in a domain we keep in
1533  * the directory
1534  */
1535 int IsDirectory(char *addr, int allow_masq_domains) {
1536         char domain[256];
1537         int h;
1538
1539         extract_token(domain, addr, 1, '@', sizeof domain);
1540         striplt(domain);
1541
1542         h = CtdlHostAlias(domain);
1543
1544         if ( (h == hostalias_masq) && allow_masq_domains)
1545                 return(1);
1546         
1547         if ( (h == hostalias_localhost) || (h == hostalias_directory) ) {
1548                 return(1);
1549         }
1550         else {
1551                 return(0);
1552         }
1553 }
1554
1555
1556 /*
1557  * Initialize the directory database (erasing anything already there)
1558  */
1559 void CtdlDirectoryInit(void) {
1560         cdb_trunc(CDB_DIRECTORY);
1561 }
1562
1563
1564 /*
1565  * Add an Internet e-mail address to the directory for a user
1566  */
1567 int CtdlDirectoryAddUser(char *internet_addr, char *citadel_addr) {
1568         char key[SIZ];
1569
1570         if (IsDirectory(internet_addr, 0) == 0) 
1571                 return 0;
1572         syslog(LOG_DEBUG, "Create directory entry: %s --> %s\n", internet_addr, citadel_addr);
1573         directory_key(key, internet_addr);
1574         cdb_store(CDB_DIRECTORY, key, strlen(key), citadel_addr, strlen(citadel_addr)+1 );
1575         return 1;
1576 }
1577
1578
1579 /*
1580  * Delete an Internet e-mail address from the directory.
1581  *
1582  * (NOTE: we don't actually use or need the citadel_addr variable; it's merely
1583  * here because the callback API expects to be able to send it.)
1584  */
1585 int CtdlDirectoryDelUser(char *internet_addr, char *citadel_addr) {
1586         char key[SIZ];
1587
1588         syslog(LOG_DEBUG, "Delete directory entry: %s --> %s\n", internet_addr, citadel_addr);
1589         directory_key(key, internet_addr);
1590         return cdb_delete(CDB_DIRECTORY, key, strlen(key) ) == 0;
1591 }
1592
1593
1594 /*
1595  * Look up an Internet e-mail address in the directory.
1596  * On success: returns 0, and Citadel address stored in 'target'
1597  * On failure: returns nonzero
1598  */
1599 int CtdlDirectoryLookup(char *target, char *internet_addr, size_t targbuflen) {
1600         struct cdbdata *cdbrec;
1601         char key[SIZ];
1602
1603         /* Dump it in there unchanged, just for kicks */
1604         safestrncpy(target, internet_addr, targbuflen);
1605
1606         /* Only do lookups for addresses with hostnames in them */
1607         if (num_tokens(internet_addr, '@') != 2) return(-1);
1608
1609         /* Only do lookups for domains in the directory */
1610         if (IsDirectory(internet_addr, 0) == 0) return(-1);
1611
1612         directory_key(key, internet_addr);
1613         cdbrec = cdb_fetch(CDB_DIRECTORY, key, strlen(key) );
1614         if (cdbrec != NULL) {
1615                 safestrncpy(target, cdbrec->ptr, targbuflen);
1616                 cdb_free(cdbrec);
1617                 return(0);
1618         }
1619
1620         return(-1);
1621 }
1622
1623
1624 /*
1625  * Harvest any email addresses that someone might want to have in their
1626  * "collected addresses" book.
1627  */
1628 char *harvest_collected_addresses(struct CtdlMessage *msg) {
1629         char *coll = NULL;
1630         char addr[256];
1631         char user[256], node[256], name[256];
1632         int is_harvestable;
1633         int i, j, h;
1634         eMsgField field = 0;
1635
1636         if (msg == NULL) return(NULL);
1637
1638         is_harvestable = 1;
1639         strcpy(addr, "");       
1640         if (!CM_IsEmpty(msg, eAuthor)) {
1641                 strcat(addr, msg->cm_fields[eAuthor]);
1642         }
1643         if (!CM_IsEmpty(msg, erFc822Addr)) {
1644                 strcat(addr, " <");
1645                 strcat(addr, msg->cm_fields[erFc822Addr]);
1646                 strcat(addr, ">");
1647                 if (IsDirectory(msg->cm_fields[erFc822Addr], 0)) {
1648                         is_harvestable = 0;
1649                 }
1650         }
1651
1652         if (is_harvestable) {
1653                 coll = strdup(addr);
1654         }
1655         else {
1656                 coll = strdup("");
1657         }
1658
1659         if (coll == NULL) return(NULL);
1660
1661         /* Scan both the R (To) and Y (CC) fields */
1662         for (i = 0; i < 2; ++i) {
1663                 if (i == 0) field = eRecipient;
1664                 if (i == 1) field = eCarbonCopY;
1665
1666                 if (!CM_IsEmpty(msg, field)) {
1667                         for (j=0; j<num_tokens(msg->cm_fields[field], ','); ++j) {
1668                                 extract_token(addr, msg->cm_fields[field], j, ',', sizeof addr);
1669                                 if (strstr(addr, "=?") != NULL)
1670                                         utf8ify_rfc822_string(addr);
1671                                 process_rfc822_addr(addr, user, node, name);
1672                                 h = CtdlHostAlias(node);
1673                                 if ( (h != hostalias_localhost) && (h != hostalias_directory) ) {
1674                                         coll = realloc(coll, strlen(coll) + strlen(addr) + 4);
1675                                         if (coll == NULL) return(NULL);
1676                                         if (!IsEmptyStr(coll)) {
1677                                                 strcat(coll, ",");
1678                                         }
1679                                         striplt(addr);
1680                                         strcat(coll, addr);
1681                                 }
1682                         }
1683                 }
1684         }
1685
1686         if (IsEmptyStr(coll)) {
1687                 free(coll);
1688                 return(NULL);
1689         }
1690         return(coll);
1691 }