* Silently refuse to add directory entries for Internet addresses already
[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 "dynloader.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
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[SIZ];
74         char host[SIZ], type[SIZ];
75
76         if (!strcasecmp(fqdn, config.c_fqdn)) return(hostalias_localhost);
77         if (!strcasecmp(fqdn, config.c_nodename)) return(hostalias_localhost);
78         if (inetcfg == NULL) return(hostalias_nomatch);
79
80         config_lines = num_tokens(inetcfg, '\n');
81         for (i=0; i<config_lines; ++i) {
82                 extract_token(buf, inetcfg, i, '\n');
83                 extract_token(host, buf, 0, '|');
84                 extract_token(type, buf, 1, '|');
85
86                 if ( (!strcasecmp(type, "localhost"))
87                    && (!strcasecmp(fqdn, host)))
88                         return(hostalias_localhost);
89
90                 if ( (!strcasecmp(type, "gatewaydomain"))
91                    && (!strcasecmp(&fqdn[strlen(fqdn)-strlen(host)], host)))
92                         return(hostalias_gatewaydomain);
93
94                 if ( (!strcasecmp(type, "directory"))
95                    && (!strcasecmp(&fqdn[strlen(fqdn)-strlen(host)], host)))
96                         return(hostalias_directory);
97
98         }
99
100         return(hostalias_nomatch);
101 }
102
103
104
105
106
107
108
109 /*
110  * Return 0 if a given string fuzzy-matches a Citadel user account
111  *
112  * FIXME ... this needs to be updated to handle aliases.
113  */
114 int fuzzy_match(struct usersupp *us, char *matchstring) {
115         int a;
116
117         if ( (!strncasecmp(matchstring, "cit", 3)) 
118            && (atol(&matchstring[3]) == us->usernum)) {
119                 return 0;
120         }
121
122
123         for (a=0; a<strlen(us->fullname); ++a) {
124                 if (!strncasecmp(&us->fullname[a],
125                    matchstring, strlen(matchstring))) {
126                         return 0;
127                 }
128         }
129         return -1;
130 }
131
132
133 /*
134  * Unfold a multi-line field into a single line, removing multi-whitespaces
135  */
136 void unfold_rfc822_field(char *field) {
137         int i;
138         int quote = 0;
139
140         striplt(field);         /* remove leading/trailing whitespace */
141
142         /* convert non-space whitespace to spaces, and remove double blanks */
143         for (i=0; i<strlen(field); ++i) {
144                 if (field[i]=='\"') quote = 1 - quote;
145                 if (!quote) {
146                         if (isspace(field[i])) field[i] = ' ';
147                         while (isspace(field[i]) && isspace(field[i+1])) {
148                                 strcpy(&field[i+1], &field[i+2]);
149                         }
150                 }
151         }
152 }
153
154
155
156 /*
157  * Split an RFC822-style address into userid, host, and full name
158  *
159  */
160 void process_rfc822_addr(char *rfc822, char *user, char *node, char *name)
161 {
162         int a;
163
164         strcpy(user, "");
165         strcpy(node, config.c_fqdn);
166         strcpy(name, "");
167
168         /* extract full name - first, it's From minus <userid> */
169         strcpy(name, rfc822);
170         stripout(name, '<', '>');
171
172         /* strip anything to the left of a bang */
173         while ((strlen(name) > 0) && (haschar(name, '!') > 0))
174                 strcpy(name, &name[1]);
175
176         /* and anything to the right of a @ or % */
177         for (a = 0; a < strlen(name); ++a) {
178                 if (name[a] == '@')
179                         name[a] = 0;
180                 if (name[a] == '%')
181                         name[a] = 0;
182         }
183
184         /* but if there are parentheses, that changes the rules... */
185         if ((haschar(rfc822, '(') == 1) && (haschar(rfc822, ')') == 1)) {
186                 strcpy(name, rfc822);
187                 stripallbut(name, '(', ')');
188         }
189
190         /* but if there are a set of quotes, that supersedes everything */
191         if (haschar(rfc822, 34) == 2) {
192                 strcpy(name, rfc822);
193                 while ((strlen(name) > 0) && (name[0] != 34)) {
194                         strcpy(&name[0], &name[1]);
195                 }
196                 strcpy(&name[0], &name[1]);
197                 for (a = 0; a < strlen(name); ++a)
198                         if (name[a] == 34)
199                                 name[a] = 0;
200         }
201         /* extract user id */
202         strcpy(user, rfc822);
203
204         /* first get rid of anything in parens */
205         stripout(user, '(', ')');
206
207         /* if there's a set of angle brackets, strip it down to that */
208         if ((haschar(user, '<') == 1) && (haschar(user, '>') == 1)) {
209                 stripallbut(user, '<', '>');
210         }
211
212         /* strip anything to the left of a bang */
213         while ((strlen(user) > 0) && (haschar(user, '!') > 0))
214                 strcpy(user, &user[1]);
215
216         /* and anything to the right of a @ or % */
217         for (a = 0; a < strlen(user); ++a) {
218                 if (user[a] == '@')
219                         user[a] = 0;
220                 if (user[a] == '%')
221                         user[a] = 0;
222         }
223
224
225         /* extract node name */
226         strcpy(node, rfc822);
227
228         /* first get rid of anything in parens */
229         stripout(node, '(', ')');
230
231         /* if there's a set of angle brackets, strip it down to that */
232         if ((haschar(node, '<') == 1) && (haschar(node, '>') == 1)) {
233                 stripallbut(node, '<', '>');
234         }
235
236         /* If no node specified, tack ours on instead */
237         if (
238                 (haschar(node, '@')==0)
239                 && (haschar(node, '%')==0)
240                 && (haschar(node, '!')==0)
241         ) {
242                 strcpy(node, config.c_nodename);
243         }
244
245         else {
246
247                 /* strip anything to the left of a @ */
248                 while ((strlen(node) > 0) && (haschar(node, '@') > 0))
249                         strcpy(node, &node[1]);
250         
251                 /* strip anything to the left of a % */
252                 while ((strlen(node) > 0) && (haschar(node, '%') > 0))
253                         strcpy(node, &node[1]);
254         
255                 /* reduce multiple system bang paths to node!user */
256                 while ((strlen(node) > 0) && (haschar(node, '!') > 1))
257                         strcpy(node, &node[1]);
258         
259                 /* now get rid of the user portion of a node!user string */
260                 for (a = 0; a < strlen(node); ++a)
261                         if (node[a] == '!')
262                                 node[a] = 0;
263         }
264
265         /* strip leading and trailing spaces in all strings */
266         striplt(user);
267         striplt(node);
268         striplt(name);
269 }
270
271
272
273 /*
274  * convert_field() is a helper function for convert_internet_message().
275  * Given start/end positions for an rfc822 field, it converts it to a Citadel
276  * field if it wants to, and unfolds it if necessary.
277  *
278  * Returns 1 if the field was converted and inserted into the Citadel message
279  * structure, implying that the source field should be removed from the
280  * message text.
281  */
282 int convert_field(struct CtdlMessage *msg, int beg, int end) {
283         char *rfc822;
284         char *key, *value;
285         int i;
286         int colonpos = (-1);
287         int processed = 0;
288         char buf[SIZ];
289         char user[1024];
290         char node[1024];
291         char name[1024];
292         char addr[1024];
293         time_t parsed_date;
294
295         rfc822 = msg->cm_fields['M'];   /* M field contains rfc822 text */
296         for (i = end; i >= beg; --i) {
297                 if (rfc822[i] == ':') colonpos = i;
298         }
299
300         if (colonpos < 0) return(0);    /* no colon? not a valid header line */
301
302         key = mallok((end - beg) + 2);
303         safestrncpy(key, &rfc822[beg], (end-beg)+1);
304         key[colonpos - beg] = 0;
305         value = &key[(colonpos - beg) + 1];
306         unfold_rfc822_field(value);
307
308         /*
309          * Here's the big rfc822-to-citadel loop.
310          */
311
312         /* Date/time is converted into a unix timestamp.  If the conversion
313          * fails, we replace it with the time the message arrived locally.
314          */
315         if (!strcasecmp(key, "Date")) {
316                 parsed_date = parsedate(value);
317                 if (parsed_date < 0L) parsed_date = time(NULL);
318                 snprintf(buf, sizeof buf, "%ld", (long)parsed_date );
319                 if (msg->cm_fields['T'] == NULL)
320                         msg->cm_fields['T'] = strdoop(buf);
321                 processed = 1;
322         }
323
324         else if (!strcasecmp(key, "From")) {
325                 process_rfc822_addr(value, user, node, name);
326                 lprintf(9, "Converted to <%s@%s> (%s)\n", user, node, name);
327                 snprintf(addr, sizeof addr, "%s@%s", user, node);
328                 if (msg->cm_fields['A'] == NULL)
329                         msg->cm_fields['A'] = strdoop(name);
330                 processed = 1;
331                 if (msg->cm_fields['F'] == NULL)
332                         msg->cm_fields['F'] = strdoop(addr);
333                 processed = 1;
334         }
335
336         else if (!strcasecmp(key, "Subject")) {
337                 if (msg->cm_fields['U'] == NULL)
338                         msg->cm_fields['U'] = strdoop(value);
339                 processed = 1;
340         }
341
342         else if (!strcasecmp(key, "Message-ID")) {
343                 if (msg->cm_fields['I'] != NULL) {
344                         lprintf(5, "duplicate message id\n");
345                 }
346
347                 if (msg->cm_fields['I'] == NULL) {
348                         msg->cm_fields['I'] = strdoop(value);
349
350                         /* Strip angle brackets */
351                         while (haschar(msg->cm_fields['I'], '<') > 0) {
352                                 strcpy(&msg->cm_fields['I'][0],
353                                         &msg->cm_fields['I'][1]);
354                         }
355                         for (i = 0; i<strlen(msg->cm_fields['I']); ++i)
356                                 if (msg->cm_fields['I'][i] == '>')
357                                         msg->cm_fields['I'][i] = 0;
358                 }
359
360                 processed = 1;
361         }
362
363         /* Clean up and move on. */
364         phree(key);     /* Don't free 'value', it's actually the same buffer */
365         return(processed);
366 }
367
368
369 /*
370  * Convert an RFC822 message (headers + body) to a CtdlMessage structure.
371  * NOTE: the supplied buffer becomes part of the CtdlMessage structure, and
372  * will be deallocated when CtdlFreeMessage() is called.  Therefore, the
373  * supplied buffer should be DEREFERENCED.  It should not be freed or used
374  * again.
375  */
376 struct CtdlMessage *convert_internet_message(char *rfc822) {
377
378         struct CtdlMessage *msg;
379         int pos, beg, end, msglen;
380         int done;
381         char buf[SIZ];
382         int converted;
383
384         msg = mallok(sizeof(struct CtdlMessage));
385         if (msg == NULL) return msg;
386
387         memset(msg, 0, sizeof(struct CtdlMessage));
388         msg->cm_magic = CTDLMESSAGE_MAGIC;      /* self check */
389         msg->cm_anon_type = 0;                  /* never anonymous */
390         msg->cm_format_type = FMT_RFC822;       /* internet message */
391         msg->cm_fields['M'] = rfc822;
392
393         lprintf(9, "Unconverted RFC822 message length = %ld\n", (long)strlen(rfc822));
394         pos = 0;
395         done = 0;
396
397         while (!done) {
398
399                 /* Locate beginning and end of field, keeping in mind that
400                  * some fields might be multiline
401                  */
402                 beg = pos;
403                 end = (-1);
404
405                 msglen = strlen(rfc822);        
406                 while ( (end < 0) && (done == 0) ) {
407
408                         if ((rfc822[pos]=='\n')
409                            && (!isspace(rfc822[pos+1]))) {
410                                 end = pos;
411                         }
412
413                         /* done with headers? */
414                         if (   ((rfc822[pos]=='\n')
415                               ||(rfc822[pos]=='\r') )
416                            && ( (rfc822[pos+1]=='\n')
417                               ||(rfc822[pos+1]=='\r')) ) {
418                                 end = pos;
419                                 done = 1;
420                         }
421
422                         if (pos >= (msglen-1) ) {
423                                 end = pos;
424                                 done = 1;
425                         }
426
427                         ++pos;
428
429                 }
430
431                 /* At this point we have a field.  Are we interested in it? */
432                 converted = convert_field(msg, beg, end);
433
434                 /* Strip the field out of the RFC822 header if we used it */
435                 if (converted) {
436                         strcpy(&rfc822[beg], &rfc822[pos]);
437                         pos = beg;
438                 }
439
440                 /* If we've hit the end of the message, bail out */
441                 if (pos > strlen(rfc822)) done = 1;
442         }
443
444         /* Follow-up sanity checks... */
445
446         /* If there's no timestamp on this message, set it to now. */
447         if (msg->cm_fields['T'] == NULL) {
448                 snprintf(buf, sizeof buf, "%ld", (long)time(NULL));
449                 msg->cm_fields['T'] = strdoop(buf);
450         }
451
452         lprintf(9, "RFC822 length remaining after conversion = %ld\n",
453                 (long)strlen(rfc822));
454         return msg;
455 }
456
457
458
459 /*
460  * Look for a particular header field in an RFC822 message text.  If the
461  * requested field is found, it is unfolded (if necessary) and returned to
462  * the caller.  The field name is stripped out, leaving only its contents.
463  * The caller is responsible for freeing the returned buffer.  If the requested
464  * field is not present, or anything else goes wrong, it returns NULL.
465  */
466 char *rfc822_fetch_field(char *rfc822, char *fieldname) {
467         int pos = 0;
468         int beg, end;
469         int done = 0;
470         int colonpos, i;
471         char *fieldbuf = NULL;
472
473         /* Should never happen, but sometimes we get stupid */
474         if (rfc822 == NULL) return(NULL);
475         if (fieldname == NULL) return(NULL);
476
477         while (!done) {
478
479                 /* Locate beginning and end of field, keeping in mind that
480                  * some fields might be multiline
481                  */
482                 beg = pos;
483                 end = (-1);
484                 for (pos=beg; ((pos<=strlen(rfc822))&&(end<0)); ++pos) {
485                         if ((rfc822[pos]=='\n')
486                            && (!isspace(rfc822[pos+1]))) {
487                                 end = pos;
488                         }
489                         if ( (rfc822[pos]=='\n')        /* done w. headers? */
490                            && ( (rfc822[pos+1]=='\n')
491                               ||(rfc822[pos+1]=='\r'))) {
492                                 end = pos;
493                                 done = 1;
494                         }
495
496                 }
497
498                 /* At this point we have a field.  Is it The One? */
499                 if (end > beg) {
500                         fieldbuf = mallok((end-beg)+3);
501                         if (fieldbuf == NULL) return(NULL);
502                         safestrncpy(fieldbuf, &rfc822[beg], (end-beg)+1);
503                         unfold_rfc822_field(fieldbuf);
504                         colonpos = (-1);
505                         for (i = strlen(fieldbuf); i >= 0; --i) {
506                                 if (fieldbuf[i] == ':') colonpos = i;
507                         }
508                         if (colonpos > 0) {
509                                 fieldbuf[colonpos] = 0;
510                                 if (!strcasecmp(fieldbuf, fieldname)) {
511                                         strcpy(fieldbuf, &fieldbuf[colonpos+1]);
512                                         striplt(fieldbuf);
513                                         return(fieldbuf);
514                                 }
515                         }
516                         phree(fieldbuf);
517                 }
518
519                 /* If we've hit the end of the message, bail out */
520                 if (pos > strlen(rfc822)) done = 1;
521         }
522         return(NULL);
523 }
524
525
526
527 /*****************************************************************************
528  *                      DIRECTORY MANAGEMENT FUNCTIONS                       *
529  *****************************************************************************/
530
531 /*
532  * Generate the index key for an Internet e-mail address to be looked up
533  * in the database.
534  */
535 void directory_key(char *key, char *addr) {
536         int i;
537         int keylen = 0;
538
539         for (i=0; i<strlen(addr); ++i) {
540                 if (!isspace(addr[i])) {
541                         key[keylen++] = tolower(addr[i]);
542                 }
543         }
544         key[keylen++] = 0;
545
546         lprintf(9, "Directory key is <%s>\n", key);
547 }
548
549
550
551 /* Return nonzero if the supplied address is in a domain we keep in
552  * the directory
553  */
554 int IsDirectory(char *addr) {
555         char domain[SIZ];
556         int h;
557
558         extract_token(domain, addr, 1, '@');
559         striplt(domain);
560
561         h = CtdlHostAlias(domain);
562         lprintf(9, "IsDirectory(%s)\n", domain);
563
564         if ( (h == hostalias_localhost) || (h == hostalias_directory) ) {
565                 lprintf(9, " ...yes\n");
566                 return(1);
567         }
568         else {
569                 lprintf(9, " ...no\n");
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(9, "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) {
620         struct cdbdata *cdbrec;
621         char key[SIZ];
622
623         lprintf(9, "CtdlDirectoryLookup(%s)\n", internet_addr);
624
625         if (IsDirectory(internet_addr) == 0) return(-1);
626
627         directory_key(key, internet_addr);
628         cdbrec = cdb_fetch(CDB_DIRECTORY, key, strlen(key) );
629         if (cdbrec != NULL) {
630                 safestrncpy(target, cdbrec->ptr, SIZ);
631                 cdb_free(cdbrec);
632                 lprintf(9, "Looked up as <%s>\n", target);
633                 return(0);
634         }
635
636         lprintf(9, "Lookup failed\n");
637         return(-1);
638 }