* Fixed acceptance of inbound SMTP messages relaying to other Citadel nodes
[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         }
380         return(rfc822_address_nonlocal);
381 }
382
383
384
385
386 /*
387  * convert_field() is a helper function for convert_internet_message().
388  * Given start/end positions for an rfc822 field, it converts it to a Citadel
389  * field if it wants to, and unfolds it if necessary.
390  *
391  * Returns 1 if the field was converted and inserted into the Citadel message
392  * structure, implying that the source field should be removed from the
393  * message text.
394  */
395 int convert_field(struct CtdlMessage *msg, int beg, int end) {
396         char *rfc822;
397         char *key, *value;
398         int i;
399         int colonpos = (-1);
400         int processed = 0;
401         char buf[SIZ];
402         char user[1024];
403         char node[1024];
404         char name[1024];
405         char addr[1024];
406         time_t parsed_date;
407
408         rfc822 = msg->cm_fields['M'];   /* M field contains rfc822 text */
409         for (i = end; i >= beg; --i) {
410                 if (rfc822[i] == ':') colonpos = i;
411         }
412
413         if (colonpos < 0) return(0);    /* no colon? not a valid header line */
414
415         key = mallok((end - beg) + 2);
416         safestrncpy(key, &rfc822[beg], (end-beg)+1);
417         key[colonpos - beg] = 0;
418         value = &key[(colonpos - beg) + 1];
419         unfold_rfc822_field(value);
420
421         /*
422          * Here's the big rfc822-to-citadel loop.
423          */
424
425         /* Date/time is converted into a unix timestamp.  If the conversion
426          * fails, we replace it with the time the message arrived locally.
427          */
428         if (!strcasecmp(key, "Date")) {
429                 parsed_date = parsedate(value);
430                 if (parsed_date < 0L) parsed_date = time(NULL);
431                 snprintf(buf, sizeof buf, "%ld", (long)parsed_date );
432                 if (msg->cm_fields['T'] == NULL)
433                         msg->cm_fields['T'] = strdoop(buf);
434                 processed = 1;
435         }
436
437         else if (!strcasecmp(key, "From")) {
438                 process_rfc822_addr(value, user, node, name);
439                 lprintf(9, "Converted to <%s@%s> (%s)\n", user, node, name);
440                 snprintf(addr, sizeof addr, "%s@%s", user, node);
441                 if (msg->cm_fields['A'] == NULL)
442                         msg->cm_fields['A'] = strdoop(name);
443                 processed = 1;
444                 if (msg->cm_fields['F'] == NULL)
445                         msg->cm_fields['F'] = strdoop(addr);
446                 processed = 1;
447         }
448
449         else if (!strcasecmp(key, "Subject")) {
450                 if (msg->cm_fields['U'] == NULL)
451                         msg->cm_fields['U'] = strdoop(value);
452                 processed = 1;
453         }
454
455         else if (!strcasecmp(key, "Message-ID")) {
456                 if (msg->cm_fields['I'] != NULL) {
457                         lprintf(5, "duplicate message id\n");
458                 }
459
460                 if (msg->cm_fields['I'] == NULL) {
461                         msg->cm_fields['I'] = strdoop(value);
462
463                         /* Strip angle brackets */
464                         while (haschar(msg->cm_fields['I'], '<') > 0) {
465                                 strcpy(&msg->cm_fields['I'][0],
466                                         &msg->cm_fields['I'][1]);
467                         }
468                         for (i = 0; i<strlen(msg->cm_fields['I']); ++i)
469                                 if (msg->cm_fields['I'][i] == '>')
470                                         msg->cm_fields['I'][i] = 0;
471                 }
472
473                 processed = 1;
474         }
475
476         /* Clean up and move on. */
477         phree(key);     /* Don't free 'value', it's actually the same buffer */
478         return(processed);
479 }
480
481
482 /*
483  * Convert an RFC822 message (headers + body) to a CtdlMessage structure.
484  * NOTE: the supplied buffer becomes part of the CtdlMessage structure, and
485  * will be deallocated when CtdlFreeMessage() is called.  Therefore, the
486  * supplied buffer should be DEREFERENCED.  It should not be freed or used
487  * again.
488  */
489 struct CtdlMessage *convert_internet_message(char *rfc822) {
490
491         struct CtdlMessage *msg;
492         int pos, beg, end, msglen;
493         int done;
494         char buf[SIZ];
495         int converted;
496
497         msg = mallok(sizeof(struct CtdlMessage));
498         if (msg == NULL) return msg;
499
500         memset(msg, 0, sizeof(struct CtdlMessage));
501         msg->cm_magic = CTDLMESSAGE_MAGIC;      /* self check */
502         msg->cm_anon_type = 0;                  /* never anonymous */
503         msg->cm_format_type = FMT_RFC822;       /* internet message */
504         msg->cm_fields['M'] = rfc822;
505
506         lprintf(9, "Unconverted RFC822 message length = %ld\n", (long)strlen(rfc822));
507         pos = 0;
508         done = 0;
509
510         while (!done) {
511
512                 /* Locate beginning and end of field, keeping in mind that
513                  * some fields might be multiline
514                  */
515                 beg = pos;
516                 end = (-1);
517
518                 msglen = strlen(rfc822);        
519                 while ( (end < 0) && (done == 0) ) {
520
521                         if ((rfc822[pos]=='\n')
522                            && (!isspace(rfc822[pos+1]))) {
523                                 end = pos;
524                         }
525
526                         /* done with headers? */
527                         if (   ((rfc822[pos]=='\n')
528                               ||(rfc822[pos]=='\r') )
529                            && ( (rfc822[pos+1]=='\n')
530                               ||(rfc822[pos+1]=='\r')) ) {
531                                 end = pos;
532                                 done = 1;
533                         }
534
535                         if (pos >= (msglen-1) ) {
536                                 end = pos;
537                                 done = 1;
538                         }
539
540                         ++pos;
541
542                 }
543
544                 /* At this point we have a field.  Are we interested in it? */
545                 converted = convert_field(msg, beg, end);
546
547                 /* Strip the field out of the RFC822 header if we used it */
548                 if (converted) {
549                         strcpy(&rfc822[beg], &rfc822[pos]);
550                         pos = beg;
551                 }
552
553                 /* If we've hit the end of the message, bail out */
554                 if (pos > strlen(rfc822)) done = 1;
555         }
556
557         /* Follow-up sanity checks... */
558
559         /* If there's no timestamp on this message, set it to now. */
560         if (msg->cm_fields['T'] == NULL) {
561                 snprintf(buf, sizeof buf, "%ld", (long)time(NULL));
562                 msg->cm_fields['T'] = strdoop(buf);
563         }
564
565         lprintf(9, "RFC822 length remaining after conversion = %ld\n",
566                 (long)strlen(rfc822));
567         return msg;
568 }
569
570
571
572 /*
573  * Look for a particular header field in an RFC822 message text.  If the
574  * requested field is found, it is unfolded (if necessary) and returned to
575  * the caller.  The field name is stripped out, leaving only its contents.
576  * The caller is responsible for freeing the returned buffer.  If the requested
577  * field is not present, or anything else goes wrong, it returns NULL.
578  */
579 char *rfc822_fetch_field(char *rfc822, char *fieldname) {
580         int pos = 0;
581         int beg, end;
582         int done = 0;
583         int colonpos, i;
584         char *fieldbuf = NULL;
585
586         /* Should never happen, but sometimes we get stupid */
587         if (rfc822 == NULL) return(NULL);
588         if (fieldname == NULL) return(NULL);
589
590         while (!done) {
591
592                 /* Locate beginning and end of field, keeping in mind that
593                  * some fields might be multiline
594                  */
595                 beg = pos;
596                 end = (-1);
597                 for (pos=beg; ((pos<=strlen(rfc822))&&(end<0)); ++pos) {
598                         if ((rfc822[pos]=='\n')
599                            && (!isspace(rfc822[pos+1]))) {
600                                 end = pos;
601                         }
602                         if ( (rfc822[pos]=='\n')        /* done w. headers? */
603                            && ( (rfc822[pos+1]=='\n')
604                               ||(rfc822[pos+1]=='\r'))) {
605                                 end = pos;
606                                 done = 1;
607                         }
608
609                 }
610
611                 /* At this point we have a field.  Is it The One? */
612                 if (end > beg) {
613                         fieldbuf = mallok((end-beg)+3);
614                         if (fieldbuf == NULL) return(NULL);
615                         safestrncpy(fieldbuf, &rfc822[beg], (end-beg)+1);
616                         unfold_rfc822_field(fieldbuf);
617                         colonpos = (-1);
618                         for (i = strlen(fieldbuf); i >= 0; --i) {
619                                 if (fieldbuf[i] == ':') colonpos = i;
620                         }
621                         if (colonpos > 0) {
622                                 fieldbuf[colonpos] = 0;
623                                 if (!strcasecmp(fieldbuf, fieldname)) {
624                                         strcpy(fieldbuf, &fieldbuf[colonpos+1]);
625                                         striplt(fieldbuf);
626                                         return(fieldbuf);
627                                 }
628                         }
629                         phree(fieldbuf);
630                 }
631
632                 /* If we've hit the end of the message, bail out */
633                 if (pos > strlen(rfc822)) done = 1;
634         }
635         return(NULL);
636 }
637
638
639
640 /*****************************************************************************
641  *                      DIRECTORY MANAGEMENT FUNCTIONS                       *
642  *****************************************************************************/
643
644 /*
645  * Generate the index key for an Internet e-mail address to be looked up
646  * in the database.
647  */
648 void directory_key(char *key, char *addr) {
649         int i;
650         int keylen = 0;
651
652         for (i=0; i<strlen(addr); ++i) {
653                 if (!isspace(addr[i])) {
654                         key[keylen++] = tolower(addr[i]);
655                 }
656         }
657         key[keylen++] = 0;
658
659         lprintf(9, "Directory key is <%s>\n", key);
660 }
661
662
663
664 /* Return nonzero if the supplied address is in a domain we keep in
665  * the directory
666  */
667 int IsDirectory(char *addr) {
668         char domain[SIZ];
669         int h;
670
671         extract_token(domain, addr, 1, '@');
672         striplt(domain);
673
674         h = CtdlHostAlias(domain);
675         lprintf(9, "IsDirectory(%s)\n", domain);
676
677         if ( (h == hostalias_localhost) || (h == hostalias_directory) ) {
678                 lprintf(9, " ...yes\n");
679                 return(1);
680         }
681         else {
682                 lprintf(9, " ...no\n");
683                 return(0);
684         }
685 }
686
687
688 /*
689  * Initialize the directory database (erasing anything already there)
690  */
691 void CtdlDirectoryInit(void) {
692         /* FIXME ... write this */
693 }
694
695
696 /*
697  * Add an Internet e-mail address to the directory for a user
698  */
699 void CtdlDirectoryAddUser(char *internet_addr, char *citadel_addr) {
700         char key[SIZ];
701
702         lprintf(9, "Dir: %s --> %s\n",
703                 internet_addr, citadel_addr);
704         if (IsDirectory(internet_addr) == 0) return;
705
706         directory_key(key, internet_addr);
707
708         cdb_store(CDB_DIRECTORY, key, strlen(key),
709                 citadel_addr, strlen(citadel_addr)+1 );
710 }
711
712
713 /*
714  * Delete an Internet e-mail address from the directory
715  */
716 void CtdlDirectoryDelUser(char *internet_addr) {
717         char key[SIZ];
718
719         directory_key(key, internet_addr);
720         cdb_delete(CDB_DIRECTORY, key, strlen(key) );
721 }
722
723
724 /*
725  * Look up an Internet e-mail address in the directory.
726  * On success: returns 0, and Citadel address stored in 'target'
727  * On failure: returns nonzero
728  */
729 int CtdlDirectoryLookup(char *target, char *internet_addr) {
730         struct cdbdata *cdbrec;
731         char key[SIZ];
732
733         lprintf(9, "CtdlDirectoryLookup(%s)\n", internet_addr);
734
735         if (IsDirectory(internet_addr) == 0) return(-1);
736
737         directory_key(key, internet_addr);
738         cdbrec = cdb_fetch(CDB_DIRECTORY, key, strlen(key) );
739         if (cdbrec != NULL) {
740                 safestrncpy(target, cdbrec->ptr, SIZ);
741                 cdb_free(cdbrec);
742                 lprintf(9, "Looked up as <%s>\n", target);
743                 return(0);
744         }
745
746         lprintf(9, "Lookup failed\n");
747         return(-1);
748 }