* When submitting a message, harvest non-local addresses for potential
[citadel.git] / citadel / internet_addressing.c
1 /*
2  * $Id$
3  *
4  * This file contains functions which handle the mapping of Internet addresses
5  * to users on the Citadel system.
6  */
7
8 #ifdef DLL_EXPORT
9 #define IN_LIBCIT
10 #endif
11
12 #include "sysdep.h"
13 #include <stdlib.h>
14 #include <unistd.h>
15 #include <stdio.h>
16 #include <fcntl.h>
17 #include <ctype.h>
18 #include <signal.h>
19 #include <pwd.h>
20 #include <errno.h>
21 #include <sys/types.h>
22
23 #if TIME_WITH_SYS_TIME
24 # include <sys/time.h>
25 # include <time.h>
26 #else
27 # if HAVE_SYS_TIME_H
28 #  include <sys/time.h>
29 # else
30 #  include <time.h>
31 # endif
32 #endif
33
34 #include <sys/wait.h>
35 #include <string.h>
36 #include <limits.h>
37 #include "citadel.h"
38 #include "server.h"
39 #include "serv_extensions.h"
40 #include "sysdep_decls.h"
41 #include "citserver.h"
42 #include "support.h"
43 #include "config.h"
44 #include "tools.h"
45 #include "msgbase.h"
46 #include "internet_addressing.h"
47 #include "user_ops.h"
48 #include "room_ops.h"
49 #include "parsedate.h"
50 #include "database.h"
51
52
53 #ifndef HAVE_SNPRINTF
54 #include "snprintf.h"
55 #endif
56
57
58 struct trynamebuf {
59         char buffer1[SIZ];
60         char buffer2[SIZ];
61 };
62
63 char *inetcfg = NULL;
64 struct spamstrings_t *spamstrings = NULL;
65
66
67 /*
68  * Return nonzero if the supplied name is an alias for this host.
69  */
70 int CtdlHostAlias(char *fqdn) {
71         int config_lines;
72         int i;
73         char buf[256];
74         char host[256], type[256];
75
76         if (fqdn == NULL) return(hostalias_nomatch);
77         if (strlen(fqdn) == 0) return(hostalias_nomatch);
78         if (!strcasecmp(fqdn, "localhost")) return(hostalias_localhost);
79         if (!strcasecmp(fqdn, config.c_fqdn)) return(hostalias_localhost);
80         if (!strcasecmp(fqdn, config.c_nodename)) return(hostalias_localhost);
81         if (inetcfg == NULL) return(hostalias_nomatch);
82
83         config_lines = num_tokens(inetcfg, '\n');
84         for (i=0; i<config_lines; ++i) {
85                 extract_token(buf, inetcfg, i, '\n', sizeof buf);
86                 extract_token(host, buf, 0, '|', sizeof host);
87                 extract_token(type, buf, 1, '|', sizeof type);
88
89                 if ( (!strcasecmp(type, "localhost"))
90                    && (!strcasecmp(fqdn, host)))
91                         return(hostalias_localhost);
92
93                 if ( (!strcasecmp(type, "gatewaydomain"))
94                    && (!strcasecmp(&fqdn[strlen(fqdn)-strlen(host)], host)))
95                         return(hostalias_gatewaydomain);
96
97                 if ( (!strcasecmp(type, "directory"))
98                    && (!strcasecmp(&fqdn[strlen(fqdn)-strlen(host)], host)))
99                         return(hostalias_directory);
100
101         }
102
103         return(hostalias_nomatch);
104 }
105
106
107
108
109
110
111
112 /*
113  * Return 0 if a given string fuzzy-matches a Citadel user account
114  *
115  * FIXME ... this needs to be updated to handle aliases.
116  */
117 int fuzzy_match(struct ctdluser *us, char *matchstring) {
118         int a;
119
120         if ( (!strncasecmp(matchstring, "cit", 3)) 
121            && (atol(&matchstring[3]) == us->usernum)) {
122                 return 0;
123         }
124
125
126         for (a=0; a<strlen(us->fullname); ++a) {
127                 if (!strncasecmp(&us->fullname[a],
128                    matchstring, strlen(matchstring))) {
129                         return 0;
130                 }
131         }
132         return -1;
133 }
134
135
136 /*
137  * Unfold a multi-line field into a single line, removing multi-whitespaces
138  */
139 void unfold_rfc822_field(char *field) {
140         int i;
141         int quote = 0;
142
143         striplt(field);         /* remove leading/trailing whitespace */
144
145         /* convert non-space whitespace to spaces, and remove double blanks */
146         for (i=0; i<strlen(field); ++i) {
147                 if (field[i]=='\"') quote = 1 - quote;
148                 if (!quote) {
149                         if (isspace(field[i])) field[i] = ' ';
150                         while (isspace(field[i]) && isspace(field[i+1])) {
151                                 strcpy(&field[i+1], &field[i+2]);
152                         }
153                 }
154         }
155 }
156
157
158
159 /*
160  * Split an RFC822-style address into userid, host, and full name
161  *
162  */
163 void process_rfc822_addr(const char *rfc822, char *user, char *node, char *name)
164 {
165         int a;
166
167         strcpy(user, "");
168         strcpy(node, config.c_fqdn);
169         strcpy(name, "");
170
171         /* extract full name - first, it's From minus <userid> */
172         strcpy(name, rfc822);
173         stripout(name, '<', '>');
174
175         /* strip anything to the left of a bang */
176         while ((strlen(name) > 0) && (haschar(name, '!') > 0))
177                 strcpy(name, &name[1]);
178
179         /* and anything to the right of a @ or % */
180         for (a = 0; a < strlen(name); ++a) {
181                 if (name[a] == '@')
182                         name[a] = 0;
183                 if (name[a] == '%')
184                         name[a] = 0;
185         }
186
187         /* but if there are parentheses, that changes the rules... */
188         if ((haschar(rfc822, '(') == 1) && (haschar(rfc822, ')') == 1)) {
189                 strcpy(name, rfc822);
190                 stripallbut(name, '(', ')');
191         }
192
193         /* but if there are a set of quotes, that supersedes everything */
194         if (haschar(rfc822, 34) == 2) {
195                 strcpy(name, rfc822);
196                 while ((strlen(name) > 0) && (name[0] != 34)) {
197                         strcpy(&name[0], &name[1]);
198                 }
199                 strcpy(&name[0], &name[1]);
200                 for (a = 0; a < strlen(name); ++a)
201                         if (name[a] == 34)
202                                 name[a] = 0;
203         }
204         /* extract user id */
205         strcpy(user, rfc822);
206
207         /* first get rid of anything in parens */
208         stripout(user, '(', ')');
209
210         /* if there's a set of angle brackets, strip it down to that */
211         if ((haschar(user, '<') == 1) && (haschar(user, '>') == 1)) {
212                 stripallbut(user, '<', '>');
213         }
214
215         /* strip anything to the left of a bang */
216         while ((strlen(user) > 0) && (haschar(user, '!') > 0))
217                 strcpy(user, &user[1]);
218
219         /* and anything to the right of a @ or % */
220         for (a = 0; a < strlen(user); ++a) {
221                 if (user[a] == '@')
222                         user[a] = 0;
223                 if (user[a] == '%')
224                         user[a] = 0;
225         }
226
227
228         /* extract node name */
229         strcpy(node, rfc822);
230
231         /* first get rid of anything in parens */
232         stripout(node, '(', ')');
233
234         /* if there's a set of angle brackets, strip it down to that */
235         if ((haschar(node, '<') == 1) && (haschar(node, '>') == 1)) {
236                 stripallbut(node, '<', '>');
237         }
238
239         /* If no node specified, tack ours on instead */
240         if (
241                 (haschar(node, '@')==0)
242                 && (haschar(node, '%')==0)
243                 && (haschar(node, '!')==0)
244         ) {
245                 strcpy(node, config.c_nodename);
246         }
247
248         else {
249
250                 /* strip anything to the left of a @ */
251                 while ((strlen(node) > 0) && (haschar(node, '@') > 0))
252                         strcpy(node, &node[1]);
253         
254                 /* strip anything to the left of a % */
255                 while ((strlen(node) > 0) && (haschar(node, '%') > 0))
256                         strcpy(node, &node[1]);
257         
258                 /* reduce multiple system bang paths to node!user */
259                 while ((strlen(node) > 0) && (haschar(node, '!') > 1))
260                         strcpy(node, &node[1]);
261         
262                 /* now get rid of the user portion of a node!user string */
263                 for (a = 0; a < strlen(node); ++a)
264                         if (node[a] == '!')
265                                 node[a] = 0;
266         }
267
268         /* strip leading and trailing spaces in all strings */
269         striplt(user);
270         striplt(node);
271         striplt(name);
272
273         /* If we processed a string that had the address in angle brackets
274          * but no name outside the brackets, we now have an empty name.  In
275          * this case, use the user portion of the address as the name.
276          */
277         if ((strlen(name) == 0) && (strlen(user) > 0)) {
278                 strcpy(name, user);
279         }
280 }
281
282
283
284 /*
285  * convert_field() is a helper function for convert_internet_message().
286  * Given start/end positions for an rfc822 field, it converts it to a Citadel
287  * field if it wants to, and unfolds it if necessary.
288  *
289  * Returns 1 if the field was converted and inserted into the Citadel message
290  * structure, implying that the source field should be removed from the
291  * message text.
292  */
293 int convert_field(struct CtdlMessage *msg, int beg, int end) {
294         char *rfc822;
295         char *key, *value;
296         int i;
297         int colonpos = (-1);
298         int processed = 0;
299         char buf[SIZ];
300         char user[1024];
301         char node[1024];
302         char name[1024];
303         char addr[1024];
304         time_t parsed_date;
305
306         rfc822 = msg->cm_fields['M'];   /* M field contains rfc822 text */
307         for (i = end; i >= beg; --i) {
308                 if (rfc822[i] == ':') colonpos = i;
309         }
310
311         if (colonpos < 0) return(0);    /* no colon? not a valid header line */
312
313         key = malloc((end - beg) + 2);
314         safestrncpy(key, &rfc822[beg], (end-beg)+1);
315         key[colonpos - beg] = 0;
316         value = &key[(colonpos - beg) + 1];
317         unfold_rfc822_field(value);
318
319         /*
320          * Here's the big rfc822-to-citadel loop.
321          */
322
323         /* Date/time is converted into a unix timestamp.  If the conversion
324          * fails, we replace it with the time the message arrived locally.
325          */
326         if (!strcasecmp(key, "Date")) {
327                 parsed_date = parsedate(value);
328                 if (parsed_date < 0L) parsed_date = time(NULL);
329                 snprintf(buf, sizeof buf, "%ld", (long)parsed_date );
330                 if (msg->cm_fields['T'] == NULL)
331                         msg->cm_fields['T'] = strdup(buf);
332                 processed = 1;
333         }
334
335         else if (!strcasecmp(key, "From")) {
336                 process_rfc822_addr(value, user, node, name);
337                 lprintf(CTDL_DEBUG, "Converted to <%s@%s> (%s)\n", user, node, name);
338                 snprintf(addr, sizeof addr, "%s@%s", user, node);
339                 if (msg->cm_fields['A'] == NULL)
340                         msg->cm_fields['A'] = strdup(name);
341                 processed = 1;
342                 if (msg->cm_fields['F'] == NULL)
343                         msg->cm_fields['F'] = strdup(addr);
344                 processed = 1;
345         }
346
347         else if (!strcasecmp(key, "Subject")) {
348                 if (msg->cm_fields['U'] == NULL)
349                         msg->cm_fields['U'] = strdup(value);
350                 processed = 1;
351         }
352
353         else if (!strcasecmp(key, "To")) {
354                 if (msg->cm_fields['R'] == NULL)
355                         msg->cm_fields['R'] = strdup(value);
356                 processed = 1;
357         }
358
359         else if (!strcasecmp(key, "CC")) {
360                 if (msg->cm_fields['Y'] == NULL)
361                         msg->cm_fields['Y'] = strdup(value);
362                 processed = 1;
363         }
364
365         else if (!strcasecmp(key, "Message-ID")) {
366                 if (msg->cm_fields['I'] != NULL) {
367                         lprintf(CTDL_WARNING, "duplicate message id\n");
368                 }
369
370                 if (msg->cm_fields['I'] == NULL) {
371                         msg->cm_fields['I'] = strdup(value);
372
373                         /* Strip angle brackets */
374                         while (haschar(msg->cm_fields['I'], '<') > 0) {
375                                 strcpy(&msg->cm_fields['I'][0],
376                                         &msg->cm_fields['I'][1]);
377                         }
378                         for (i = 0; i<strlen(msg->cm_fields['I']); ++i)
379                                 if (msg->cm_fields['I'][i] == '>')
380                                         msg->cm_fields['I'][i] = 0;
381                 }
382
383                 processed = 1;
384         }
385
386         /* Clean up and move on. */
387         free(key);      /* Don't free 'value', it's actually the same buffer */
388         return(processed);
389 }
390
391
392 /*
393  * Convert an RFC822 message (headers + body) to a CtdlMessage structure.
394  * NOTE: the supplied buffer becomes part of the CtdlMessage structure, and
395  * will be deallocated when CtdlFreeMessage() is called.  Therefore, the
396  * supplied buffer should be DEREFERENCED.  It should not be freed or used
397  * again.
398  */
399 struct CtdlMessage *convert_internet_message(char *rfc822) {
400
401         struct CtdlMessage *msg;
402         int pos, beg, end, msglen;
403         int done;
404         char buf[SIZ];
405         int converted;
406
407         msg = malloc(sizeof(struct CtdlMessage));
408         if (msg == NULL) return msg;
409
410         memset(msg, 0, sizeof(struct CtdlMessage));
411         msg->cm_magic = CTDLMESSAGE_MAGIC;      /* self check */
412         msg->cm_anon_type = 0;                  /* never anonymous */
413         msg->cm_format_type = FMT_RFC822;       /* internet message */
414         msg->cm_fields['M'] = rfc822;
415
416         pos = 0;
417         done = 0;
418
419         while (!done) {
420
421                 /* Locate beginning and end of field, keeping in mind that
422                  * some fields might be multiline
423                  */
424                 beg = pos;
425                 end = (-1);
426
427                 msglen = strlen(rfc822);        
428                 while ( (end < 0) && (done == 0) ) {
429
430                         if ((rfc822[pos]=='\n')
431                            && (!isspace(rfc822[pos+1]))) {
432                                 end = pos;
433                         }
434
435                         /* done with headers? */
436                         if (   (rfc822[pos]=='\n')
437                            && ( (rfc822[pos+1]=='\n')
438                               ||(rfc822[pos+1]=='\r')) ) {
439                                 end = pos;
440                                 done = 1;
441                         }
442
443                         if (pos >= (msglen-1) ) {
444                                 end = pos;
445                                 done = 1;
446                         }
447
448                         ++pos;
449
450                 }
451
452                 /* At this point we have a field.  Are we interested in it? */
453                 converted = convert_field(msg, beg, end);
454
455                 /* Strip the field out of the RFC822 header if we used it */
456                 if (converted) {
457                         strcpy(&rfc822[beg], &rfc822[pos]);
458                         pos = beg;
459                 }
460
461                 /* If we've hit the end of the message, bail out */
462                 if (pos > strlen(rfc822)) done = 1;
463         }
464
465         /* Follow-up sanity checks... */
466
467         /* If there's no timestamp on this message, set it to now. */
468         if (msg->cm_fields['T'] == NULL) {
469                 snprintf(buf, sizeof buf, "%ld", (long)time(NULL));
470                 msg->cm_fields['T'] = strdup(buf);
471         }
472
473         return msg;
474 }
475
476
477
478 /*
479  * Look for a particular header field in an RFC822 message text.  If the
480  * requested field is found, it is unfolded (if necessary) and returned to
481  * the caller.  The field name is stripped out, leaving only its contents.
482  * The caller is responsible for freeing the returned buffer.  If the requested
483  * field is not present, or anything else goes wrong, it returns NULL.
484  */
485 char *rfc822_fetch_field(char *rfc822, char *fieldname) {
486         char *fieldbuf = NULL;
487         char *end_of_headers;
488         char *field_start;
489         char *ptr;
490         char *cont;
491         char fieldhdr[SIZ];
492
493         /* Should never happen, but sometimes we get stupid */
494         if (rfc822 == NULL) return(NULL);
495         if (fieldname == NULL) return(NULL);
496
497         snprintf(fieldhdr, sizeof fieldhdr, "%s:", fieldname);
498
499         /* Locate the end of the headers, so we don't run past that point */
500         end_of_headers = bmstrcasestr(rfc822, "\n\r\n");
501         if (end_of_headers == NULL) {
502                 end_of_headers = bmstrcasestr(rfc822, "\n\n");
503         }
504         if (end_of_headers == NULL) return (NULL);
505
506         field_start = bmstrcasestr(rfc822, fieldhdr);
507         if (field_start == NULL) return(NULL);
508         if (field_start > end_of_headers) return(NULL);
509
510         fieldbuf = malloc(SIZ);
511         strcpy(fieldbuf, "");
512
513         ptr = field_start;
514         ptr = memreadline(ptr, fieldbuf, SIZ-strlen(fieldbuf) );
515         while ( (isspace(ptr[0])) && (ptr < end_of_headers) ) {
516                 strcat(fieldbuf, " ");
517                 cont = &fieldbuf[strlen(fieldbuf)];
518                 ptr = memreadline(ptr, cont, SIZ-strlen(fieldbuf) );
519                 striplt(cont);
520         }
521
522         strcpy(fieldbuf, &fieldbuf[strlen(fieldhdr)]);
523         striplt(fieldbuf);
524
525         return(fieldbuf);
526 }
527
528
529
530 /*****************************************************************************
531  *                      DIRECTORY MANAGEMENT FUNCTIONS                       *
532  *****************************************************************************/
533
534 /*
535  * Generate the index key for an Internet e-mail address to be looked up
536  * in the database.
537  */
538 void directory_key(char *key, char *addr) {
539         int i;
540         int keylen = 0;
541
542         for (i=0; i<strlen(addr); ++i) {
543                 if (!isspace(addr[i])) {
544                         key[keylen++] = tolower(addr[i]);
545                 }
546         }
547         key[keylen++] = 0;
548
549         lprintf(CTDL_DEBUG, "Directory key is <%s>\n", key);
550 }
551
552
553
554 /* Return nonzero if the supplied address is in a domain we keep in
555  * the directory
556  */
557 int IsDirectory(char *addr) {
558         char domain[256];
559         int h;
560
561         extract_token(domain, addr, 1, '@', sizeof domain);
562         striplt(domain);
563
564         h = CtdlHostAlias(domain);
565
566         if ( (h == hostalias_localhost) || (h == hostalias_directory) ) {
567                 return(1);
568         }
569         else {
570                 return(0);
571         }
572 }
573
574
575 /*
576  * Initialize the directory database (erasing anything already there)
577  */
578 void CtdlDirectoryInit(void) {
579         cdb_trunc(CDB_DIRECTORY);
580 }
581
582
583 /*
584  * Add an Internet e-mail address to the directory for a user
585  */
586 void CtdlDirectoryAddUser(char *internet_addr, char *citadel_addr) {
587         char key[SIZ];
588
589         lprintf(CTDL_DEBUG, "Dir: %s --> %s\n",
590                 internet_addr, citadel_addr);
591         if (IsDirectory(internet_addr) == 0) return;
592
593         directory_key(key, internet_addr);
594
595         cdb_store(CDB_DIRECTORY, key, strlen(key),
596                 citadel_addr, strlen(citadel_addr)+1 );
597 }
598
599
600 /*
601  * Delete an Internet e-mail address from the directory.
602  *
603  * (NOTE: we don't actually use or need the citadel_addr variable; it's merely
604  * here because the callback API expects to be able to send it.)
605  */
606 void CtdlDirectoryDelUser(char *internet_addr, char *citadel_addr) {
607         char key[SIZ];
608
609         directory_key(key, internet_addr);
610         cdb_delete(CDB_DIRECTORY, key, strlen(key) );
611 }
612
613
614 /*
615  * Look up an Internet e-mail address in the directory.
616  * On success: returns 0, and Citadel address stored in 'target'
617  * On failure: returns nonzero
618  */
619 int CtdlDirectoryLookup(char *target, char *internet_addr, size_t targbuflen) {
620         struct cdbdata *cdbrec;
621         char key[SIZ];
622
623         /* Dump it in there unchanged, just for kicks */
624         safestrncpy(target, internet_addr, targbuflen);
625
626         /* Only do lookups for addresses with hostnames in them */
627         if (num_tokens(internet_addr, '@') != 2) return(-1);
628
629         /* Only do lookups for domains in the directory */
630         if (IsDirectory(internet_addr) == 0) return(-1);
631
632         directory_key(key, internet_addr);
633         cdbrec = cdb_fetch(CDB_DIRECTORY, key, strlen(key) );
634         if (cdbrec != NULL) {
635                 safestrncpy(target, cdbrec->ptr, targbuflen);
636                 cdb_free(cdbrec);
637                 return(0);
638         }
639
640         return(-1);
641 }
642
643
644 /*
645  * Harvest any email addresses that someone might want to have in their
646  * "collected addresses" book.
647  */
648 char *harvest_collected_addresses(struct CtdlMessage *msg) {
649         char *coll = NULL;
650         char addr[256];
651         char user[256], node[256], name[256];
652         int is_harvestable;
653         int i, j, h;
654         int field = 0;
655
656         if (msg == NULL) return(NULL);
657
658         is_harvestable = 1;
659         strcpy(addr, "");       
660         if (msg->cm_fields['A'] != NULL) {
661                 strcat(addr, msg->cm_fields['A']);
662         }
663         if (msg->cm_fields['F'] != NULL) {
664                 strcat(addr, " <");
665                 strcat(addr, msg->cm_fields['F']);
666                 strcat(addr, ">");
667                 if (IsDirectory(msg->cm_fields['F'])) {
668                         is_harvestable = 0;
669                 }
670         }
671
672         if (is_harvestable) {
673                 coll = strdup(addr);
674         }
675         else {
676                 coll = strdup("");
677         }
678
679         if (coll == NULL) return(NULL);
680
681         /* Scan both the R (To) and Y (CC) fields */
682         for (i = 0; i < 2; ++i) {
683                 if (i == 0) field = 'R' ;
684                 if (i == 1) field = 'Y' ;
685
686                 if (msg->cm_fields[field] != NULL) {
687                         for (j=0; j<num_tokens(msg->cm_fields[field], ','); ++j) {
688                                 extract_token(addr, msg->cm_fields[field], j, ',', sizeof addr);
689                                 process_rfc822_addr(addr, user, node, name);
690                                 h = CtdlHostAlias(node);
691                                 if ( (h != hostalias_localhost) && (h != hostalias_directory) ) {
692                                         coll = realloc(coll, strlen(coll) + strlen(addr) + 4);
693                                         if (coll == NULL) return(NULL);
694                                         if (strlen(coll) > 0) {
695                                                 strcat(coll, ",");
696                                         }
697                                         striplt(addr);
698                                         strcat(coll, addr);
699                                 }
700                         }
701                 }
702         }
703
704         if (strlen(coll) == 0) {
705                 free(coll);
706                 return(NULL);
707         }
708         return(coll);
709 }