* Implemented the 'getsubaddress' callback, but then realized
[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         if (rfc822 == NULL) return;
168
169         /* extract full name - first, it's From minus <userid> */
170         strcpy(name, rfc822);
171         stripout(name, '<', '>');
172
173         /* strip anything to the left of a bang */
174         while ((strlen(name) > 0) && (haschar(name, '!') > 0))
175                 strcpy(name, &name[1]);
176
177         /* and anything to the right of a @ or % */
178         for (a = 0; a < strlen(name); ++a) {
179                 if (name[a] == '@')
180                         name[a] = 0;
181                 if (name[a] == '%')
182                         name[a] = 0;
183         }
184
185         /* but if there are parentheses, that changes the rules... */
186         if ((haschar(rfc822, '(') == 1) && (haschar(rfc822, ')') == 1)) {
187                 strcpy(name, rfc822);
188                 stripallbut(name, '(', ')');
189         }
190
191         /* but if there are a set of quotes, that supersedes everything */
192         if (haschar(rfc822, 34) == 2) {
193                 strcpy(name, rfc822);
194                 while ((strlen(name) > 0) && (name[0] != 34)) {
195                         strcpy(&name[0], &name[1]);
196                 }
197                 strcpy(&name[0], &name[1]);
198                 for (a = 0; a < strlen(name); ++a)
199                         if (name[a] == 34)
200                                 name[a] = 0;
201         }
202         /* extract user id */
203         strcpy(user, rfc822);
204
205         /* first get rid of anything in parens */
206         stripout(user, '(', ')');
207
208         /* if there's a set of angle brackets, strip it down to that */
209         if ((haschar(user, '<') == 1) && (haschar(user, '>') == 1)) {
210                 stripallbut(user, '<', '>');
211         }
212
213         /* strip anything to the left of a bang */
214         while ((strlen(user) > 0) && (haschar(user, '!') > 0))
215                 strcpy(user, &user[1]);
216
217         /* and anything to the right of a @ or % */
218         for (a = 0; a < strlen(user); ++a) {
219                 if (user[a] == '@')
220                         user[a] = 0;
221                 if (user[a] == '%')
222                         user[a] = 0;
223         }
224
225
226         /* extract node name */
227         strcpy(node, rfc822);
228
229         /* first get rid of anything in parens */
230         stripout(node, '(', ')');
231
232         /* if there's a set of angle brackets, strip it down to that */
233         if ((haschar(node, '<') == 1) && (haschar(node, '>') == 1)) {
234                 stripallbut(node, '<', '>');
235         }
236
237         /* If no node specified, tack ours on instead */
238         if (
239                 (haschar(node, '@')==0)
240                 && (haschar(node, '%')==0)
241                 && (haschar(node, '!')==0)
242         ) {
243                 strcpy(node, config.c_nodename);
244         }
245
246         else {
247
248                 /* strip anything to the left of a @ */
249                 while ((strlen(node) > 0) && (haschar(node, '@') > 0))
250                         strcpy(node, &node[1]);
251         
252                 /* strip anything to the left of a % */
253                 while ((strlen(node) > 0) && (haschar(node, '%') > 0))
254                         strcpy(node, &node[1]);
255         
256                 /* reduce multiple system bang paths to node!user */
257                 while ((strlen(node) > 0) && (haschar(node, '!') > 1))
258                         strcpy(node, &node[1]);
259         
260                 /* now get rid of the user portion of a node!user string */
261                 for (a = 0; a < strlen(node); ++a)
262                         if (node[a] == '!')
263                                 node[a] = 0;
264         }
265
266         /* strip leading and trailing spaces in all strings */
267         striplt(user);
268         striplt(node);
269         striplt(name);
270
271         /* If we processed a string that had the address in angle brackets
272          * but no name outside the brackets, we now have an empty name.  In
273          * this case, use the user portion of the address as the name.
274          */
275         if ((strlen(name) == 0) && (strlen(user) > 0)) {
276                 strcpy(name, user);
277         }
278 }
279
280
281
282 /*
283  * convert_field() is a helper function for convert_internet_message().
284  * Given start/end positions for an rfc822 field, it converts it to a Citadel
285  * field if it wants to, and unfolds it if necessary.
286  *
287  * Returns 1 if the field was converted and inserted into the Citadel message
288  * structure, implying that the source field should be removed from the
289  * message text.
290  */
291 int convert_field(struct CtdlMessage *msg, int beg, int end) {
292         char *rfc822;
293         char *key, *value;
294         int i;
295         int colonpos = (-1);
296         int processed = 0;
297         char buf[SIZ];
298         char user[1024];
299         char node[1024];
300         char name[1024];
301         char addr[1024];
302         time_t parsed_date;
303
304         rfc822 = msg->cm_fields['M'];   /* M field contains rfc822 text */
305         for (i = end; i >= beg; --i) {
306                 if (rfc822[i] == ':') colonpos = i;
307         }
308
309         if (colonpos < 0) return(0);    /* no colon? not a valid header line */
310
311         key = malloc((end - beg) + 2);
312         safestrncpy(key, &rfc822[beg], (end-beg)+1);
313         key[colonpos - beg] = 0;
314         value = &key[(colonpos - beg) + 1];
315         unfold_rfc822_field(value);
316
317         /*
318          * Here's the big rfc822-to-citadel loop.
319          */
320
321         /* Date/time is converted into a unix timestamp.  If the conversion
322          * fails, we replace it with the time the message arrived locally.
323          */
324         if (!strcasecmp(key, "Date")) {
325                 parsed_date = parsedate(value);
326                 if (parsed_date < 0L) parsed_date = time(NULL);
327                 snprintf(buf, sizeof buf, "%ld", (long)parsed_date );
328                 if (msg->cm_fields['T'] == NULL)
329                         msg->cm_fields['T'] = strdup(buf);
330                 processed = 1;
331         }
332
333         else if (!strcasecmp(key, "From")) {
334                 process_rfc822_addr(value, user, node, name);
335                 lprintf(CTDL_DEBUG, "Converted to <%s@%s> (%s)\n", user, node, name);
336                 snprintf(addr, sizeof addr, "%s@%s", user, node);
337                 if (msg->cm_fields['A'] == NULL)
338                         msg->cm_fields['A'] = strdup(name);
339                 processed = 1;
340                 if (msg->cm_fields['F'] == NULL)
341                         msg->cm_fields['F'] = strdup(addr);
342                 processed = 1;
343         }
344
345         else if (!strcasecmp(key, "Subject")) {
346                 if (msg->cm_fields['U'] == NULL)
347                         msg->cm_fields['U'] = strdup(value);
348                 processed = 1;
349         }
350
351         else if (!strcasecmp(key, "To")) {
352                 if (msg->cm_fields['R'] == NULL)
353                         msg->cm_fields['R'] = strdup(value);
354                 processed = 1;
355         }
356
357         else if (!strcasecmp(key, "CC")) {
358                 if (msg->cm_fields['Y'] == NULL)
359                         msg->cm_fields['Y'] = strdup(value);
360                 processed = 1;
361         }
362
363         else if (!strcasecmp(key, "Message-ID")) {
364                 if (msg->cm_fields['I'] != NULL) {
365                         lprintf(CTDL_WARNING, "duplicate message id\n");
366                 }
367
368                 if (msg->cm_fields['I'] == NULL) {
369                         msg->cm_fields['I'] = strdup(value);
370
371                         /* Strip angle brackets */
372                         while (haschar(msg->cm_fields['I'], '<') > 0) {
373                                 strcpy(&msg->cm_fields['I'][0],
374                                         &msg->cm_fields['I'][1]);
375                         }
376                         for (i = 0; i<strlen(msg->cm_fields['I']); ++i)
377                                 if (msg->cm_fields['I'][i] == '>')
378                                         msg->cm_fields['I'][i] = 0;
379                 }
380
381                 processed = 1;
382         }
383
384         /* Clean up and move on. */
385         free(key);      /* Don't free 'value', it's actually the same buffer */
386         return(processed);
387 }
388
389
390 /*
391  * Convert an RFC822 message (headers + body) to a CtdlMessage structure.
392  * NOTE: the supplied buffer becomes part of the CtdlMessage structure, and
393  * will be deallocated when CtdlFreeMessage() is called.  Therefore, the
394  * supplied buffer should be DEREFERENCED.  It should not be freed or used
395  * again.
396  */
397 struct CtdlMessage *convert_internet_message(char *rfc822) {
398
399         struct CtdlMessage *msg;
400         int pos, beg, end, msglen;
401         int done;
402         char buf[SIZ];
403         int converted;
404
405         msg = malloc(sizeof(struct CtdlMessage));
406         if (msg == NULL) return msg;
407
408         memset(msg, 0, sizeof(struct CtdlMessage));
409         msg->cm_magic = CTDLMESSAGE_MAGIC;      /* self check */
410         msg->cm_anon_type = 0;                  /* never anonymous */
411         msg->cm_format_type = FMT_RFC822;       /* internet message */
412         msg->cm_fields['M'] = rfc822;
413
414         pos = 0;
415         done = 0;
416
417         while (!done) {
418
419                 /* Locate beginning and end of field, keeping in mind that
420                  * some fields might be multiline
421                  */
422                 beg = pos;
423                 end = (-1);
424
425                 msglen = strlen(rfc822);        
426                 while ( (end < 0) && (done == 0) ) {
427
428                         if ((rfc822[pos]=='\n')
429                            && (!isspace(rfc822[pos+1]))) {
430                                 end = pos;
431                         }
432
433                         /* done with headers? */
434                         if (   (rfc822[pos]=='\n')
435                            && ( (rfc822[pos+1]=='\n')
436                               ||(rfc822[pos+1]=='\r')) ) {
437                                 end = pos;
438                                 done = 1;
439                         }
440
441                         if (pos >= (msglen-1) ) {
442                                 end = pos;
443                                 done = 1;
444                         }
445
446                         ++pos;
447
448                 }
449
450                 /* At this point we have a field.  Are we interested in it? */
451                 converted = convert_field(msg, beg, end);
452
453                 /* Strip the field out of the RFC822 header if we used it */
454                 if (converted) {
455                         strcpy(&rfc822[beg], &rfc822[pos]);
456                         pos = beg;
457                 }
458
459                 /* If we've hit the end of the message, bail out */
460                 if (pos > strlen(rfc822)) done = 1;
461         }
462
463         /* Follow-up sanity checks... */
464
465         /* If there's no timestamp on this message, set it to now. */
466         if (msg->cm_fields['T'] == NULL) {
467                 snprintf(buf, sizeof buf, "%ld", (long)time(NULL));
468                 msg->cm_fields['T'] = strdup(buf);
469         }
470
471         return msg;
472 }
473
474
475
476 /*
477  * Look for a particular header field in an RFC822 message text.  If the
478  * requested field is found, it is unfolded (if necessary) and returned to
479  * the caller.  The field name is stripped out, leaving only its contents.
480  * The caller is responsible for freeing the returned buffer.  If the requested
481  * field is not present, or anything else goes wrong, it returns NULL.
482  */
483 char *rfc822_fetch_field(char *rfc822, char *fieldname) {
484         char *fieldbuf = NULL;
485         char *end_of_headers;
486         char *field_start;
487         char *ptr;
488         char *cont;
489         char fieldhdr[SIZ];
490
491         /* Should never happen, but sometimes we get stupid */
492         if (rfc822 == NULL) return(NULL);
493         if (fieldname == NULL) return(NULL);
494
495         snprintf(fieldhdr, sizeof fieldhdr, "%s:", fieldname);
496
497         /* Locate the end of the headers, so we don't run past that point */
498         end_of_headers = bmstrcasestr(rfc822, "\n\r\n");
499         if (end_of_headers == NULL) {
500                 end_of_headers = bmstrcasestr(rfc822, "\n\n");
501         }
502         if (end_of_headers == NULL) return (NULL);
503
504         field_start = bmstrcasestr(rfc822, fieldhdr);
505         if (field_start == NULL) return(NULL);
506         if (field_start > end_of_headers) return(NULL);
507
508         fieldbuf = malloc(SIZ);
509         strcpy(fieldbuf, "");
510
511         ptr = field_start;
512         ptr = memreadline(ptr, fieldbuf, SIZ-strlen(fieldbuf) );
513         while ( (isspace(ptr[0])) && (ptr < end_of_headers) ) {
514                 strcat(fieldbuf, " ");
515                 cont = &fieldbuf[strlen(fieldbuf)];
516                 ptr = memreadline(ptr, cont, SIZ-strlen(fieldbuf) );
517                 striplt(cont);
518         }
519
520         strcpy(fieldbuf, &fieldbuf[strlen(fieldhdr)]);
521         striplt(fieldbuf);
522
523         return(fieldbuf);
524 }
525
526
527
528 /*****************************************************************************
529  *                      DIRECTORY MANAGEMENT FUNCTIONS                       *
530  *****************************************************************************/
531
532 /*
533  * Generate the index key for an Internet e-mail address to be looked up
534  * in the database.
535  */
536 void directory_key(char *key, char *addr) {
537         int i;
538         int keylen = 0;
539
540         for (i=0; i<strlen(addr); ++i) {
541                 if (!isspace(addr[i])) {
542                         key[keylen++] = tolower(addr[i]);
543                 }
544         }
545         key[keylen++] = 0;
546
547         lprintf(CTDL_DEBUG, "Directory key is <%s>\n", key);
548 }
549
550
551
552 /* Return nonzero if the supplied address is in a domain we keep in
553  * the directory
554  */
555 int IsDirectory(char *addr) {
556         char domain[256];
557         int h;
558
559         extract_token(domain, addr, 1, '@', sizeof domain);
560         striplt(domain);
561
562         h = CtdlHostAlias(domain);
563
564         if ( (h == hostalias_localhost) || (h == hostalias_directory) ) {
565                 return(1);
566         }
567         else {
568                 return(0);
569         }
570 }
571
572
573 /*
574  * Initialize the directory database (erasing anything already there)
575  */
576 void CtdlDirectoryInit(void) {
577         cdb_trunc(CDB_DIRECTORY);
578 }
579
580
581 /*
582  * Add an Internet e-mail address to the directory for a user
583  */
584 void CtdlDirectoryAddUser(char *internet_addr, char *citadel_addr) {
585         char key[SIZ];
586
587         lprintf(CTDL_DEBUG, "Dir: %s --> %s\n",
588                 internet_addr, citadel_addr);
589         if (IsDirectory(internet_addr) == 0) return;
590
591         directory_key(key, internet_addr);
592
593         cdb_store(CDB_DIRECTORY, key, strlen(key),
594                 citadel_addr, strlen(citadel_addr)+1 );
595 }
596
597
598 /*
599  * Delete an Internet e-mail address from the directory.
600  *
601  * (NOTE: we don't actually use or need the citadel_addr variable; it's merely
602  * here because the callback API expects to be able to send it.)
603  */
604 void CtdlDirectoryDelUser(char *internet_addr, char *citadel_addr) {
605         char key[SIZ];
606
607         directory_key(key, internet_addr);
608         cdb_delete(CDB_DIRECTORY, key, strlen(key) );
609 }
610
611
612 /*
613  * Look up an Internet e-mail address in the directory.
614  * On success: returns 0, and Citadel address stored in 'target'
615  * On failure: returns nonzero
616  */
617 int CtdlDirectoryLookup(char *target, char *internet_addr, size_t targbuflen) {
618         struct cdbdata *cdbrec;
619         char key[SIZ];
620
621         /* Dump it in there unchanged, just for kicks */
622         safestrncpy(target, internet_addr, targbuflen);
623
624         /* Only do lookups for addresses with hostnames in them */
625         if (num_tokens(internet_addr, '@') != 2) return(-1);
626
627         /* Only do lookups for domains in the directory */
628         if (IsDirectory(internet_addr) == 0) return(-1);
629
630         directory_key(key, internet_addr);
631         cdbrec = cdb_fetch(CDB_DIRECTORY, key, strlen(key) );
632         if (cdbrec != NULL) {
633                 safestrncpy(target, cdbrec->ptr, targbuflen);
634                 cdb_free(cdbrec);
635                 return(0);
636         }
637
638         return(-1);
639 }
640
641
642 /*
643  * Harvest any email addresses that someone might want to have in their
644  * "collected addresses" book.
645  */
646 char *harvest_collected_addresses(struct CtdlMessage *msg) {
647         char *coll = NULL;
648         char addr[256];
649         char user[256], node[256], name[256];
650         int is_harvestable;
651         int i, j, h;
652         int field = 0;
653
654         if (msg == NULL) return(NULL);
655
656         is_harvestable = 1;
657         strcpy(addr, "");       
658         if (msg->cm_fields['A'] != NULL) {
659                 strcat(addr, msg->cm_fields['A']);
660         }
661         if (msg->cm_fields['F'] != NULL) {
662                 strcat(addr, " <");
663                 strcat(addr, msg->cm_fields['F']);
664                 strcat(addr, ">");
665                 if (IsDirectory(msg->cm_fields['F'])) {
666                         is_harvestable = 0;
667                 }
668         }
669
670         if (is_harvestable) {
671                 coll = strdup(addr);
672         }
673         else {
674                 coll = strdup("");
675         }
676
677         if (coll == NULL) return(NULL);
678
679         /* Scan both the R (To) and Y (CC) fields */
680         for (i = 0; i < 2; ++i) {
681                 if (i == 0) field = 'R' ;
682                 if (i == 1) field = 'Y' ;
683
684                 if (msg->cm_fields[field] != NULL) {
685                         for (j=0; j<num_tokens(msg->cm_fields[field], ','); ++j) {
686                                 extract_token(addr, msg->cm_fields[field], j, ',', sizeof addr);
687                                 process_rfc822_addr(addr, user, node, name);
688                                 h = CtdlHostAlias(node);
689                                 if ( (h != hostalias_localhost) && (h != hostalias_directory) ) {
690                                         coll = realloc(coll, strlen(coll) + strlen(addr) + 4);
691                                         if (coll == NULL) return(NULL);
692                                         if (strlen(coll) > 0) {
693                                                 strcat(coll, ",");
694                                         }
695                                         striplt(addr);
696                                         strcat(coll, addr);
697                                 }
698                         }
699                 }
700         }
701
702         if (strlen(coll) == 0) {
703                 free(coll);
704                 return(NULL);
705         }
706         return(coll);
707 }