* Finished most of the work for the Global Address Book.
[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  * Back end for convert_internet_address()
275  * (Compares an internet name [buffer1] and stores in [buffer2] if found)
276  */
277 void try_name(struct usersupp *us, void *data) {
278         struct passwd *pw;
279         struct trynamebuf *tnb;
280         tnb = (struct trynamebuf *)data;
281
282         if (!strncasecmp(tnb->buffer1, "cit", 3))
283                 if (atol(&tnb->buffer1[3]) == us->usernum)
284                         strcpy(tnb->buffer2, us->fullname);
285
286         if (!collapsed_strcmp(tnb->buffer1, us->fullname)) 
287                         strcpy(tnb->buffer2, us->fullname);
288
289         if (us->uid != BBSUID) {
290                 pw = getpwuid(us->uid);
291                 if (pw != NULL) {
292                         if (!strcasecmp(tnb->buffer1, pw->pw_name)) {
293                                 strcpy(tnb->buffer2, us->fullname);
294                         }
295                 }
296         }
297 }
298
299
300 /*
301  * Convert an Internet email address to a Citadel user/host combination
302  */
303 int convert_internet_address(char *destuser, char *desthost, char *source)
304 {
305         char user[SIZ];
306         char node[SIZ];
307         char name[SIZ];
308         struct quickroom qrbuf;
309         int i;
310         int hostalias;
311         struct trynamebuf tnb;
312         char buf[SIZ];
313         int passes = 0;
314         char sourcealias[1024];
315
316         safestrncpy(sourcealias, source, sizeof(sourcealias) );
317         alias(sourcealias);
318
319 REALIAS:
320         /* Split it up */
321         process_rfc822_addr(sourcealias, user, node, name);
322         lprintf(9, "process_rfc822_addr() converted to <%s@%s> (%s)\n",
323                 user, node, name);
324
325         /* Map the FQDN to a Citadel node name
326          */
327         hostalias =  CtdlHostAlias(node);
328         switch(hostalias) {
329                 case hostalias_localhost:
330                         strcpy(node, config.c_nodename);
331                         break;
332
333                 case hostalias_gatewaydomain:
334                         extract_token(buf, node, 0, '.');
335                         safestrncpy(node, buf, sizeof buf);
336         }
337
338         /* Now try to resolve the name
339          * FIXME ... do the multiple-addresses thing
340          */
341         if (!strcasecmp(node, config.c_nodename)) {
342
343
344                 /* First, see if we hit an alias.  Don't do this more than
345                  * a few times, in case we accidentally hit an alias loop
346                  */
347                 strcpy(sourcealias, user);
348                 alias(user);
349                 if ( (strcasecmp(user, sourcealias)) && (++passes < 3) )
350                         goto REALIAS;
351
352                 /* Try all local rooms */
353                 if (!strncasecmp(user, "room_", 5)) {
354                         strcpy(name, &user[5]);
355                         for (i=0; i<strlen(name); ++i) 
356                                 if (name[i]=='_') name[i]=' ';
357                         if (getroom(&qrbuf, name) == 0) {
358                                 strcpy(destuser, qrbuf.QRname);
359                                 strcpy(desthost, config.c_nodename);
360                                 return rfc822_room_delivery;
361                         }
362                 }
363
364                 /* Try all local users */
365                 strcpy(destuser, user);
366                 strcpy(desthost, config.c_nodename);
367                 strcpy(tnb.buffer1, user);
368                 strcpy(tnb.buffer2, "");
369                 ForEachUser(try_name, &tnb);
370                 if (strlen(tnb.buffer2) == 0) return(rfc822_no_such_user);
371                 strcpy(destuser, tnb.buffer2);
372                 return(rfc822_address_locally_validated);
373         }
374
375         strcpy(destuser, user);
376         strcpy(desthost, node);
377         if (hostalias == hostalias_gatewaydomain)
378                 return(rfc822_address_on_citadel_network);
379         return(rfc822_address_nonlocal);
380 }
381
382
383
384
385 /*
386  * convert_field() is a helper function for convert_internet_message().
387  * Given start/end positions for an rfc822 field, it converts it to a Citadel
388  * field if it wants to, and unfolds it if necessary.
389  *
390  * Returns 1 if the field was converted and inserted into the Citadel message
391  * structure, implying that the source field should be removed from the
392  * message text.
393  */
394 int convert_field(struct CtdlMessage *msg, int beg, int end) {
395         char *rfc822;
396         char *key, *value;
397         int i;
398         int colonpos = (-1);
399         int processed = 0;
400         char buf[SIZ];
401         char user[1024];
402         char node[1024];
403         char name[1024];
404         char addr[1024];
405         time_t parsed_date;
406
407         rfc822 = msg->cm_fields['M'];   /* M field contains rfc822 text */
408         for (i = end; i >= beg; --i) {
409                 if (rfc822[i] == ':') colonpos = i;
410         }
411
412         if (colonpos < 0) return(0);    /* no colon? not a valid header line */
413
414         key = mallok((end - beg) + 2);
415         safestrncpy(key, &rfc822[beg], (end-beg)+1);
416         key[colonpos - beg] = 0;
417         value = &key[(colonpos - beg) + 1];
418         unfold_rfc822_field(value);
419
420         /*
421          * Here's the big rfc822-to-citadel loop.
422          */
423
424         /* Date/time is converted into a unix timestamp.  If the conversion
425          * fails, we replace it with the time the message arrived locally.
426          */
427         if (!strcasecmp(key, "Date")) {
428                 parsed_date = parsedate(value);
429                 if (parsed_date < 0L) parsed_date = time(NULL);
430                 snprintf(buf, sizeof buf, "%ld", (long)parsed_date );
431                 if (msg->cm_fields['T'] == NULL)
432                         msg->cm_fields['T'] = strdoop(buf);
433                 processed = 1;
434         }
435
436         else if (!strcasecmp(key, "From")) {
437                 process_rfc822_addr(value, user, node, name);
438                 lprintf(9, "Converted to <%s@%s> (%s)\n", user, node, name);
439                 snprintf(addr, sizeof addr, "%s@%s", user, node);
440                 if (msg->cm_fields['A'] == NULL)
441                         msg->cm_fields['A'] = strdoop(name);
442                 processed = 1;
443                 if (msg->cm_fields['F'] == NULL)
444                         msg->cm_fields['F'] = strdoop(addr);
445                 processed = 1;
446         }
447
448         else if (!strcasecmp(key, "Subject")) {
449                 if (msg->cm_fields['U'] == NULL)
450                         msg->cm_fields['U'] = strdoop(value);
451                 processed = 1;
452         }
453
454         else if (!strcasecmp(key, "Message-ID")) {
455                 if (msg->cm_fields['I'] != NULL) {
456                         lprintf(5, "duplicate message id\n");
457                 }
458
459                 if (msg->cm_fields['I'] == NULL) {
460                         msg->cm_fields['I'] = strdoop(value);
461
462                         /* Strip angle brackets */
463                         while (haschar(msg->cm_fields['I'], '<') > 0) {
464                                 strcpy(&msg->cm_fields['I'][0],
465                                         &msg->cm_fields['I'][1]);
466                         }
467                         for (i = 0; i<strlen(msg->cm_fields['I']); ++i)
468                                 if (msg->cm_fields['I'][i] == '>')
469                                         msg->cm_fields['I'][i] = 0;
470                 }
471
472                 processed = 1;
473         }
474
475         /* Clean up and move on. */
476         phree(key);     /* Don't free 'value', it's actually the same buffer */
477         return(processed);
478 }
479
480
481 /*
482  * Convert an RFC822 message (headers + body) to a CtdlMessage structure.
483  * NOTE: the supplied buffer becomes part of the CtdlMessage structure, and
484  * will be deallocated when CtdlFreeMessage() is called.  Therefore, the
485  * supplied buffer should be DEREFERENCED.  It should not be freed or used
486  * again.
487  */
488 struct CtdlMessage *convert_internet_message(char *rfc822) {
489
490         struct CtdlMessage *msg;
491         int pos, beg, end, msglen;
492         int done;
493         char buf[SIZ];
494         int converted;
495
496         msg = mallok(sizeof(struct CtdlMessage));
497         if (msg == NULL) return msg;
498
499         memset(msg, 0, sizeof(struct CtdlMessage));
500         msg->cm_magic = CTDLMESSAGE_MAGIC;      /* self check */
501         msg->cm_anon_type = 0;                  /* never anonymous */
502         msg->cm_format_type = FMT_RFC822;       /* internet message */
503         msg->cm_fields['M'] = rfc822;
504
505         lprintf(9, "Unconverted RFC822 message length = %ld\n", (long)strlen(rfc822));
506         pos = 0;
507         done = 0;
508
509         while (!done) {
510
511                 /* Locate beginning and end of field, keeping in mind that
512                  * some fields might be multiline
513                  */
514                 beg = pos;
515                 end = (-1);
516
517                 msglen = strlen(rfc822);        
518                 while ( (end < 0) && (done == 0) ) {
519
520                         if ((rfc822[pos]=='\n')
521                            && (!isspace(rfc822[pos+1]))) {
522                                 end = pos;
523                         }
524
525                         /* done with headers? */
526                         if (   ((rfc822[pos]=='\n')
527                               ||(rfc822[pos]=='\r') )
528                            && ( (rfc822[pos+1]=='\n')
529                               ||(rfc822[pos+1]=='\r')) ) {
530                                 end = pos;
531                                 done = 1;
532                         }
533
534                         if (pos >= (msglen-1) ) {
535                                 end = pos;
536                                 done = 1;
537                         }
538
539                         ++pos;
540
541                 }
542
543                 /* At this point we have a field.  Are we interested in it? */
544                 converted = convert_field(msg, beg, end);
545
546                 /* Strip the field out of the RFC822 header if we used it */
547                 if (converted) {
548                         strcpy(&rfc822[beg], &rfc822[pos]);
549                         pos = beg;
550                 }
551
552                 /* If we've hit the end of the message, bail out */
553                 if (pos > strlen(rfc822)) done = 1;
554         }
555
556         /* Follow-up sanity checks... */
557
558         /* If there's no timestamp on this message, set it to now. */
559         if (msg->cm_fields['T'] == NULL) {
560                 snprintf(buf, sizeof buf, "%ld", (long)time(NULL));
561                 msg->cm_fields['T'] = strdoop(buf);
562         }
563
564         lprintf(9, "RFC822 length remaining after conversion = %ld\n",
565                 (long)strlen(rfc822));
566         return msg;
567 }
568
569
570
571 /*
572  * Look for a particular header field in an RFC822 message text.  If the
573  * requested field is found, it is unfolded (if necessary) and returned to
574  * the caller.  The field name is stripped out, leaving only its contents.
575  * The caller is responsible for freeing the returned buffer.  If the requested
576  * field is not present, or anything else goes wrong, it returns NULL.
577  */
578 char *rfc822_fetch_field(char *rfc822, char *fieldname) {
579         int pos = 0;
580         int beg, end;
581         int done = 0;
582         int colonpos, i;
583         char *fieldbuf = NULL;
584
585         /* Should never happen, but sometimes we get stupid */
586         if (rfc822 == NULL) return(NULL);
587         if (fieldname == NULL) return(NULL);
588
589         while (!done) {
590
591                 /* Locate beginning and end of field, keeping in mind that
592                  * some fields might be multiline
593                  */
594                 beg = pos;
595                 end = (-1);
596                 for (pos=beg; ((pos<=strlen(rfc822))&&(end<0)); ++pos) {
597                         if ((rfc822[pos]=='\n')
598                            && (!isspace(rfc822[pos+1]))) {
599                                 end = pos;
600                         }
601                         if ( (rfc822[pos]=='\n')        /* done w. headers? */
602                            && ( (rfc822[pos+1]=='\n')
603                               ||(rfc822[pos+1]=='\r'))) {
604                                 end = pos;
605                                 done = 1;
606                         }
607
608                 }
609
610                 /* At this point we have a field.  Is it The One? */
611                 if (end > beg) {
612                         fieldbuf = mallok((end-beg)+3);
613                         if (fieldbuf == NULL) return(NULL);
614                         safestrncpy(fieldbuf, &rfc822[beg], (end-beg)+1);
615                         unfold_rfc822_field(fieldbuf);
616                         colonpos = (-1);
617                         for (i = strlen(fieldbuf); i >= 0; --i) {
618                                 if (fieldbuf[i] == ':') colonpos = i;
619                         }
620                         if (colonpos > 0) {
621                                 fieldbuf[colonpos] = 0;
622                                 if (!strcasecmp(fieldbuf, fieldname)) {
623                                         strcpy(fieldbuf, &fieldbuf[colonpos+1]);
624                                         striplt(fieldbuf);
625                                         return(fieldbuf);
626                                 }
627                         }
628                         phree(fieldbuf);
629                 }
630
631                 /* If we've hit the end of the message, bail out */
632                 if (pos > strlen(rfc822)) done = 1;
633         }
634         return(NULL);
635 }
636
637
638
639 /*****************************************************************************
640  *                      DIRECTORY MANAGEMENT FUNCTIONS                       *
641  *****************************************************************************/
642
643 /*
644  * Generate the index key for an Internet e-mail address to be looked up
645  * in the database.
646  */
647 void directory_key(char *key, char *addr) {
648         int i;
649         int keylen = 0;
650
651         for (i=0; i<strlen(addr); ++i) {
652                 if (!isspace(addr[i])) {
653                         key[keylen++] = tolower(addr[i]);
654                 }
655         }
656         key[keylen++] = 0;
657
658         lprintf(9, "Directory key is <%s>\n", key);
659 }
660
661
662
663 /* Return nonzero if the supplied address is in a domain we keep in
664  * the directory
665  */
666 int IsDirectory(char *addr) {
667         char domain[SIZ];
668         int h;
669
670         extract_token(domain, addr, 1, '@');
671         striplt(domain);
672
673         h = CtdlHostAlias(domain);
674         lprintf(9, "IsDirectory(%s)\n", domain);
675
676         if ( (h == hostalias_localhost) || (h == hostalias_directory) ) {
677                 lprintf(9, " ...yes\n");
678                 return(1);
679         }
680         else {
681                 lprintf(9, " ...no\n");
682                 return(0);
683         }
684 }
685
686
687 /*
688  * Initialize the directory database (erasing anything already there)
689  */
690 void CtdlDirectoryInit(void) {
691         /* FIXME ... write this */
692 }
693
694
695 /*
696  * Add an Internet e-mail address to the directory for a user
697  */
698 void CtdlDirectoryAddUser(char *internet_addr, char *citadel_addr) {
699         char key[SIZ];
700
701         lprintf(9, "Dir: %s --> %s\n",
702                 internet_addr, citadel_addr);
703         if (IsDirectory(internet_addr) == 0) return;
704
705         directory_key(key, internet_addr);
706
707         cdb_store(CDB_DIRECTORY, key, strlen(key),
708                 citadel_addr, strlen(citadel_addr)+1 );
709 }
710
711
712 /*
713  * Delete an Internet e-mail address from the directory
714  */
715 void CtdlDirectoryDelUser(char *internet_addr) {
716         char key[SIZ];
717
718         directory_key(key, internet_addr);
719         cdb_delete(CDB_DIRECTORY, key, strlen(key) );
720 }
721
722
723 /*
724  * Look up an Internet e-mail address in the directory.
725  * On success: returns 0, and Citadel address stored in 'target'
726  * On failure: returns nonzero
727  */
728 int CtdlDirectoryLookup(char *target, char *internet_addr) {
729         struct cdbdata *cdbrec;
730         char key[SIZ];
731
732         lprintf(9, "CtdlDirectoryLookup(%s)\n", internet_addr);
733
734         if (IsDirectory(internet_addr) == 0) return(-1);
735
736         directory_key(key, internet_addr);
737         cdbrec = cdb_fetch(CDB_DIRECTORY, key, strlen(key) );
738         if (cdbrec != NULL) {
739                 safestrncpy(target, cdbrec->ptr, SIZ);
740                 cdb_free(cdbrec);
741                 lprintf(9, "Looked up as <%s>\n", target);
742                 return(0);
743         }
744
745         lprintf(9, "Lookup failed\n");
746         return(-1);
747 }