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