* Properly handle all aliases specified in network/mail.aliases for incoming
[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 #include <sys/time.h>
19 #include <sys/wait.h>
20 #include <string.h>
21 #include <limits.h>
22 #include "citadel.h"
23 #include "server.h"
24 #include <time.h>
25 #include "sysdep_decls.h"
26 #include "citserver.h"
27 #include "support.h"
28 #include "config.h"
29 #include "tools.h"
30 #include "msgbase.h"
31 #include "internet_addressing.h"
32 #include "user_ops.h"
33 #include "room_ops.h"
34 #include "parsedate.h"
35
36
37 struct trynamebuf {
38         char buffer1[256];
39         char buffer2[256];
40 };
41
42 char *inetcfg = NULL;
43
44
45
46 /*
47  * Return nonzero if the supplied name is an alias for this host.
48  */
49 int CtdlHostAlias(char *fqdn) {
50         int config_lines;
51         int i;
52         char buf[256];
53         char host[256], type[256];
54
55         if (!strcasecmp(fqdn, config.c_fqdn)) return(hostalias_localhost);
56         if (!strcasecmp(fqdn, config.c_nodename)) return(hostalias_localhost);
57         if (inetcfg == NULL) return(hostalias_nomatch);
58
59         config_lines = num_tokens(inetcfg, '\n');
60         for (i=0; i<config_lines; ++i) {
61                 extract_token(buf, inetcfg, i, '\n');
62                 extract_token(host, buf, 0, '|');
63                 extract_token(type, buf, 1, '|');
64
65                 if ( (!strcasecmp(type, "localhost"))
66                    && (!strcasecmp(fqdn, host)))
67                         return(hostalias_localhost);
68
69                 if ( (!strcasecmp(type, "gatewaydomain"))
70                    && (!strcasecmp(&fqdn[strlen(fqdn)-strlen(host)], host)))
71                         return(hostalias_gatewaydomain);
72
73         }
74
75         return(hostalias_nomatch);
76 }
77
78
79
80
81
82
83
84 /*
85  * Return 0 if a given string fuzzy-matches a Citadel user account
86  *
87  * FIXME ... this needs to be updated to handle aliases.
88  */
89 int fuzzy_match(struct usersupp *us, char *matchstring) {
90         int a;
91
92         if ( (!strncasecmp(matchstring, "cit", 3)) 
93            && (atol(&matchstring[3]) == us->usernum)) {
94                 return 0;
95         }
96
97
98         for (a=0; a<strlen(us->fullname); ++a) {
99                 if (!strncasecmp(&us->fullname[a],
100                    matchstring, strlen(matchstring))) {
101                         return 0;
102                 }
103         }
104         return -1;
105 }
106
107
108 /*
109  * Unfold a multi-line field into a single line, removing multi-whitespaces
110  */
111 void unfold_rfc822_field(char *field) {
112         int i;
113         int quote = 0;
114
115         striplt(field);         /* remove leading/trailing whitespace */
116
117         /* convert non-space whitespace to spaces, and remove double blanks */
118         for (i=0; i<strlen(field); ++i) {
119                 if (field[i]=='\"') quote = 1 - quote;
120                 if (!quote) {
121                         if (isspace(field[i])) field[i] = ' ';
122                         while (isspace(field[i]) && isspace(field[i+1])) {
123                                 strcpy(&field[i+1], &field[i+2]);
124                         }
125                 }
126         }
127 }
128
129
130
131 /*
132  * Split an RFC822-style address into userid, host, and full name
133  *
134  */
135 void process_rfc822_addr(char *rfc822, char *user, char *node, char *name)
136 {
137         int a;
138
139         strcpy(user, "");
140         strcpy(node, config.c_fqdn);
141         strcpy(name, "");
142
143         /* extract full name - first, it's From minus <userid> */
144         strcpy(name, rfc822);
145         for (a = 0; a < strlen(name); ++a) {
146                 if (name[a] == '<') {
147                         do {
148                                 strcpy(&name[a], &name[a + 1]);
149                         } while ((strlen(name) > 0) && (name[a] != '>'));
150                         strcpy(&name[a], &name[a + 1]);
151                 }
152         }
153         /* strip anything to the left of a bang */
154         while ((strlen(name) > 0) && (haschar(name, '!') > 0))
155                 strcpy(name, &name[1]);
156
157         /* and anything to the right of a @ or % */
158         for (a = 0; a < strlen(name); ++a) {
159                 if (name[a] == '@')
160                         name[a] = 0;
161                 if (name[a] == '%')
162                         name[a] = 0;
163         }
164
165         /* but if there are parentheses, that changes the rules... */
166         if ((haschar(rfc822, '(') == 1) && (haschar(rfc822, ')') == 1)) {
167                 strcpy(name, rfc822);
168                 while ((strlen(name) > 0) && (name[0] != '(')) {
169                         strcpy(&name[0], &name[1]);
170                 }
171                 strcpy(&name[0], &name[1]);
172                 for (a = 0; a < strlen(name); ++a) {
173                         if (name[a] == ')') {
174                                 name[a] = 0;
175                         }
176                 }
177         }
178         /* but if there are a set of quotes, that supersedes everything */
179         if (haschar(rfc822, 34) == 2) {
180                 strcpy(name, rfc822);
181                 while ((strlen(name) > 0) && (name[0] != 34)) {
182                         strcpy(&name[0], &name[1]);
183                 }
184                 strcpy(&name[0], &name[1]);
185                 for (a = 0; a < strlen(name); ++a)
186                         if (name[a] == 34)
187                                 name[a] = 0;
188         }
189         /* extract user id */
190         strcpy(user, rfc822);
191
192         /* first get rid of anything in parens */
193         for (a = 0; a < strlen(user); ++a)
194                 if (user[a] == '(') {
195                         do {
196                                 strcpy(&user[a], &user[a + 1]);
197                         } while ((strlen(user) > 0) && (user[a] != ')'));
198                         strcpy(&user[a], &user[a + 1]);
199                 }
200         /* if there's a set of angle brackets, strip it down to that */
201         if ((haschar(user, '<') == 1) && (haschar(user, '>') == 1)) {
202                 while ((strlen(user) > 0) && (user[0] != '<')) {
203                         strcpy(&user[0], &user[1]);
204                 }
205                 strcpy(&user[0], &user[1]);
206                 for (a = 0; a < strlen(user); ++a)
207                         if (user[a] == '>')
208                                 user[a] = 0;
209         }
210         /* strip anything to the left of a bang */
211         while ((strlen(user) > 0) && (haschar(user, '!') > 0))
212                 strcpy(user, &user[1]);
213
214         /* and anything to the right of a @ or % */
215         for (a = 0; a < strlen(user); ++a) {
216                 if (user[a] == '@')
217                         user[a] = 0;
218                 if (user[a] == '%')
219                         user[a] = 0;
220         }
221
222
223         /* extract node name */
224         strcpy(node, rfc822);
225
226         /* first get rid of anything in parens */
227         for (a = 0; a < strlen(node); ++a)
228                 if (node[a] == '(') {
229                         do {
230                                 strcpy(&node[a], &node[a + 1]);
231                         } while ((strlen(node) > 0) && (node[a] != ')'));
232                         strcpy(&node[a], &node[a + 1]);
233                 }
234         /* if there's a set of angle brackets, strip it down to that */
235         if ((haschar(node, '<') == 1) && (haschar(node, '>') == 1)) {
236                 while ((strlen(node) > 0) && (node[0] != '<')) {
237                         strcpy(&node[0], &node[1]);
238                 }
239                 strcpy(&node[0], &node[1]);
240                 for (a = 0; a < strlen(node); ++a)
241                         if (node[a] == '>')
242                                 node[a] = 0;
243         }
244
245         /* If no node specified, tack ours on instead */
246         if (
247                 (haschar(node, '@')==0)
248                 && (haschar(node, '%')==0)
249                 && (haschar(node, '!')==0)
250         ) {
251                 strcpy(node, config.c_nodename);
252         }
253
254         else {
255
256                 /* strip anything to the left of a @ */
257                 while ((strlen(node) > 0) && (haschar(node, '@') > 0))
258                         strcpy(node, &node[1]);
259         
260                 /* strip anything to the left of a % */
261                 while ((strlen(node) > 0) && (haschar(node, '%') > 0))
262                         strcpy(node, &node[1]);
263         
264                 /* reduce multiple system bang paths to node!user */
265                 while ((strlen(node) > 0) && (haschar(node, '!') > 1))
266                         strcpy(node, &node[1]);
267         
268                 /* now get rid of the user portion of a node!user string */
269                 for (a = 0; a < strlen(node); ++a)
270                         if (node[a] == '!')
271                                 node[a] = 0;
272         }
273
274         /* strip leading and trailing spaces in all strings */
275         striplt(user);
276         striplt(node);
277         striplt(name);
278 }
279
280
281
282 /*
283  * Back end for convert_internet_address()
284  * (Compares an internet name [buffer1] and stores in [buffer2] if found)
285  */
286 void try_name(struct usersupp *us, void *data) {
287         struct trynamebuf *tnb;
288         tnb = (struct trynamebuf *)data;
289         
290         if (!strncasecmp(tnb->buffer1, "cit", 3))
291                 if (atol(&tnb->buffer1[3]) == us->usernum)
292                         strcpy(tnb->buffer2, us->fullname);
293
294         if (!collapsed_strcmp(tnb->buffer1, us->fullname)) 
295                         strcpy(tnb->buffer2, us->fullname);
296
297         if (us->uid != BBSUID)
298                 if (!strcasecmp(tnb->buffer1, getpwuid(us->uid)->pw_name))
299                         strcpy(tnb->buffer2, us->fullname);
300 }
301
302
303 /*
304  * Convert an Internet email address to a Citadel user/host combination
305  */
306 int convert_internet_address(char *destuser, char *desthost, char *source)
307 {
308         char user[256];
309         char node[256];
310         char name[256];
311         struct quickroom qrbuf;
312         int i;
313         int hostalias;
314         struct trynamebuf tnb;
315         char buf[256];
316         int passes = 0;
317         char sourcealias[1024];
318
319         safestrncpy(sourcealias, source, sizeof(sourcealias) );
320
321 REALIAS:
322         /* Split it up */
323         process_rfc822_addr(sourcealias, user, node, name);
324         lprintf(9, "process_rfc822_addr() converted to <%s@%s> (%s)\n",
325                 user, node, name);
326
327         /* Map the FQDN to a Citadel node name
328          */
329         hostalias =  CtdlHostAlias(node);
330         switch(hostalias) {
331                 case hostalias_localhost:
332                         strcpy(node, config.c_nodename);
333                         break;
334
335                 case hostalias_gatewaydomain:
336                         extract_token(buf, node, 0, '.');
337                         safestrncpy(node, buf, sizeof buf);
338         }
339
340         /* Now try to resolve the name
341          * FIXME ... do the multiple-addresses thing
342          */
343         if (!strcasecmp(node, config.c_nodename)) {
344
345
346                 /* First, see if we hit an alias.  Don't do this more than
347                  * a few times, in case we accidentally hit an alias loop
348                  */
349                 strcpy(sourcealias, user);
350                 alias(user);
351                 if ( (strcasecmp(user, sourcealias)) && (++passes < 3) )
352                         goto REALIAS;
353
354                 /* Try all local rooms */
355                 if (!strncasecmp(user, "room_", 5)) {
356                         strcpy(name, &user[5]);
357                         for (i=0; i<strlen(name); ++i) 
358                                 if (name[i]=='_') name[i]=' ';
359                         if (getroom(&qrbuf, name) == 0) {
360                                 strcpy(destuser, qrbuf.QRname);
361                                 strcpy(desthost, config.c_nodename);
362                                 return rfc822_room_delivery;
363                         }
364                 }
365
366                 /* Try all local users */
367                 strcpy(destuser, user);
368                 strcpy(desthost, config.c_nodename);
369                 strcpy(tnb.buffer1, user);
370                 strcpy(tnb.buffer2, "");
371                 ForEachUser(try_name, &tnb);
372                 if (strlen(tnb.buffer2) == 0) return(rfc822_no_such_user);
373                 strcpy(destuser, tnb.buffer2);
374                 return(rfc822_address_locally_validated);
375         }
376
377         strcpy(destuser, user);
378         strcpy(desthost, node);
379         return(rfc822_address_invalid); /* unknown error */
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[256];
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         lprintf(9, "Key=<%s> Value=<%s>\n", key, value);
421
422         /*
423          * Here's the big rfc822-to-citadel loop.
424          */
425
426         /* Date/time is converted into a unix timestamp.  If the conversion
427          * fails, we replace it with the time the message arrived locally.
428          */
429         if (!strcasecmp(key, "Date")) {
430                 parsed_date = parsedate(value);
431                 if (parsed_date < 0L) parsed_date = time(NULL);
432                 lprintf(9, "Parsed date is %s",
433                         asctime(localtime(&parsed_date)));
434                 sprintf(buf, "%ld", parsed_date );
435                 if (msg->cm_fields['T'] == NULL)
436                         msg->cm_fields['T'] = strdoop(buf);
437                 processed = 1;
438         }
439
440         else if (!strcasecmp(key, "From")) {
441                 process_rfc822_addr(value, user, node, name);
442                 lprintf(9, "Converted to <%s@%s> (%s)\n", user, node, name);
443                 sprintf(addr, "%s@%s", user, node);
444                 if (msg->cm_fields['A'] == NULL)
445                         msg->cm_fields['A'] = strdoop(name);
446                 processed = 1;
447                 if (msg->cm_fields['F'] == NULL)
448                         msg->cm_fields['F'] = strdoop(addr);
449                 processed = 1;
450         }
451
452         else if (!strcasecmp(key, "Subject")) {
453                 if (msg->cm_fields['U'] == NULL)
454                         msg->cm_fields['U'] = strdoop(value);
455                 processed = 1;
456         }
457
458         /* Clean up and move on. */
459         phree(key);     /* Don't free 'value', it's actually the same buffer */
460         return(processed);
461 }
462
463
464 /*
465  * Convert an RFC822 message (headers + body) to a CtdlMessage structure.
466  */
467 struct CtdlMessage *convert_internet_message(char *rfc822) {
468
469         struct CtdlMessage *msg;
470         int pos, beg, end;
471         int done;
472         char buf[256];
473         int converted;
474
475         msg = mallok(sizeof(struct CtdlMessage));
476         if (msg == NULL) return msg;
477
478         memset(msg, 0, sizeof(struct CtdlMessage));
479         msg->cm_magic = CTDLMESSAGE_MAGIC;      /* self check */
480         msg->cm_anon_type = 0;                  /* never anonymous */
481         msg->cm_format_type = FMT_RFC822;       /* internet message */
482         msg->cm_fields['M'] = rfc822;
483
484         lprintf(9, "Unconverted RFC822 message length = %d\n", strlen(rfc822));
485         pos = 0;
486         done = 0;
487
488         while (!done) {
489
490                 /* Locate beginning and end of field, keeping in mind that
491                  * some fields might be multiline
492                  */
493                 beg = pos;
494                 end = (-1);
495                 for (pos=beg; ((pos<=strlen(rfc822))&&(end<0)); ++pos) {
496                         if ((rfc822[pos]=='\n')
497                            && (!isspace(rfc822[pos+1]))) {
498                                 end = pos;
499                         }
500                         if ( (rfc822[pos]=='\n')        /* done w. headers? */
501                            && ( (rfc822[pos+1]=='\n')
502                               ||(rfc822[pos+1]=='\r'))) {
503                                 end = pos;
504                                 done = 1;
505                         }
506
507                 }
508
509                 /* At this point we have a field.  Are we interested in it? */
510                 converted = convert_field(msg, beg, end);
511
512                 /* Strip the field out of the RFC822 header if we used it */
513                 if (converted) {
514                         strcpy(&rfc822[beg], &rfc822[pos]);
515                         pos = beg;
516                 }
517
518                 /* If we've hit the end of the message, bail out */
519                 if (pos > strlen(rfc822)) done = 1;
520         }
521
522         /* Follow-up sanity checks... */
523
524         /* If there's no timestamp on this message, set it to now. */
525         if (msg->cm_fields['T'] == NULL) {
526                 sprintf(buf, "%ld", time(NULL));
527                 msg->cm_fields['T'] = strdoop(buf);
528         }
529
530         lprintf(9, "RFC822 length remaining after conversion = %d\n",
531                 strlen(rfc822));
532         return msg;
533 }
534