* Got bounce messages working (mostly ... testers, please beat this up!)
[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 "internet_addressing.h"
31 #include "user_ops.h"
32 #include "room_ops.h"
33 #include "parsedate.h"
34
35
36 struct trynamebuf {
37         char buffer1[256];
38         char buffer2[256];
39 };
40
41 char *inetcfg = NULL;
42
43
44
45 /*
46  * Return nonzero if the supplied name is an alias for this host.
47  */
48 int CtdlHostAlias(char *fqdn) {
49         int config_lines;
50         int i;
51         char buf[256];
52         char host[256], type[256];
53
54         if (!strcasecmp(fqdn, config.c_fqdn)) return(hostalias_localhost);
55         if (!strcasecmp(fqdn, config.c_nodename)) return(hostalias_localhost);
56         if (inetcfg == NULL) return(hostalias_nomatch);
57
58         config_lines = num_tokens(inetcfg, '\n');
59         for (i=0; i<config_lines; ++i) {
60                 extract_token(buf, inetcfg, i, '\n');
61                 extract_token(host, buf, 0, '|');
62                 extract_token(type, buf, 1, '|');
63
64                 if ( (!strcasecmp(type, "localhost"))
65                    && (!strcasecmp(fqdn, host)))
66                         return(hostalias_localhost);
67
68                 if ( (!strcasecmp(type, "gatewaydomain"))
69                    && (!strcasecmp(&fqdn[strlen(fqdn)-strlen(host)], host)))
70                         return(hostalias_gatewaydomain);
71
72         }
73
74         return(hostalias_nomatch);
75 }
76
77
78
79
80
81
82
83 /*
84  * Return 0 if a given string fuzzy-matches a Citadel user account
85  *
86  * FIXME ... this needs to be updated to handle aliases.
87  */
88 int fuzzy_match(struct usersupp *us, char *matchstring) {
89         int a;
90
91         if ( (!strncasecmp(matchstring, "cit", 3)) 
92            && (atol(&matchstring[3]) == us->usernum)) {
93                 return 0;
94         }
95
96
97         for (a=0; a<strlen(us->fullname); ++a) {
98                 if (!strncasecmp(&us->fullname[a],
99                    matchstring, strlen(matchstring))) {
100                         return 0;
101                 }
102         }
103         return -1;
104 }
105
106
107 /*
108  * Unfold a multi-line field into a single line, removing multi-whitespaces
109  */
110 void unfold_rfc822_field(char *field) {
111         int i;
112         int quote = 0;
113
114         striplt(field);         /* remove leading/trailing whitespace */
115
116         /* convert non-space whitespace to spaces, and remove double blanks */
117         for (i=0; i<strlen(field); ++i) {
118                 if (field[i]=='\"') quote = 1 - quote;
119                 if (!quote) {
120                         if (isspace(field[i])) field[i] = ' ';
121                         while (isspace(field[i]) && isspace(field[i+1])) {
122                                 strcpy(&field[i+1], &field[i+2]);
123                         }
124                 }
125         }
126 }
127
128
129
130 /*
131  * Split an RFC822-style address into userid, host, and full name
132  * (Originally from citmail.c, and unchanged so far)
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         /* strip anything to the left of a @ */
245         while ((strlen(node) > 0) && (haschar(node, '@') > 0))
246                 strcpy(node, &node[1]);
247
248         /* strip anything to the left of a % */
249         while ((strlen(node) > 0) && (haschar(node, '%') > 0))
250                 strcpy(node, &node[1]);
251
252         /* reduce multiple system bang paths to node!user */
253         while ((strlen(node) > 0) && (haschar(node, '!') > 1))
254                 strcpy(node, &node[1]);
255
256         /* now get rid of the user portion of a node!user string */
257         for (a = 0; a < strlen(node); ++a)
258                 if (node[a] == '!')
259                         node[a] = 0;
260
261         /* strip leading and trailing spaces in all strings */
262         striplt(user);
263         striplt(node);
264         striplt(name);
265 }
266
267
268
269 /*
270  * Back end for convert_internet_address()
271  * (Compares an internet name [buffer1] and stores in [buffer2] if found)
272  */
273 void try_name(struct usersupp *us, void *data) {
274         struct trynamebuf *tnb;
275         tnb = (struct trynamebuf *)data;
276         
277         if (!strncasecmp(tnb->buffer1, "cit", 3))
278                 if (atol(&tnb->buffer1[3]) == us->usernum)
279                         strcpy(tnb->buffer2, us->fullname);
280
281         if (!collapsed_strcmp(tnb->buffer1, us->fullname)) 
282                         strcpy(tnb->buffer2, us->fullname);
283
284         if (us->uid != BBSUID)
285                 if (!strcasecmp(tnb->buffer1, getpwuid(us->uid)->pw_name))
286                         strcpy(tnb->buffer2, us->fullname);
287 }
288
289
290 /*
291  * Convert an Internet email address to a Citadel user/host combination
292  */
293 int convert_internet_address(char *destuser, char *desthost, char *source)
294 {
295         char user[256];
296         char node[256];
297         char name[256];
298         struct quickroom qrbuf;
299         int i;
300         int hostalias;
301         struct trynamebuf tnb;
302         char buf[256];
303
304         /* Split it up */
305         process_rfc822_addr(source, user, node, name);
306
307         /* Map the FQDN to a Citadel node name
308          */
309         hostalias =  CtdlHostAlias(node);
310         switch(hostalias) {
311                 case hostalias_localhost:
312                         strcpy(node, config.c_nodename);
313                         break;
314
315                 case hostalias_gatewaydomain:
316                         extract_token(buf, node, 0, '.');
317                         safestrncpy(node, buf, sizeof buf);
318         }
319
320         /* Now try to resolve the name
321          * FIXME ... do the multiple-addresses thing
322          */
323         if (!strcasecmp(node, config.c_nodename)) {
324                 /* Try all local rooms */
325                 if (!strncasecmp(user, "room_", 5)) {
326                         strcpy(name, &user[5]);
327                         for (i=0; i<strlen(name); ++i) 
328                                 if (name[i]=='_') name[i]=' ';
329                         if (getroom(&qrbuf, name) == 0) {
330                                 strcpy(destuser, qrbuf.QRname);
331                                 strcpy(desthost, config.c_nodename);
332                                 return rfc822_room_delivery;
333                         }
334                 }
335
336                 /* Try all local users */
337                 strcpy(destuser, user);
338                 strcpy(desthost, config.c_nodename);
339                 strcpy(tnb.buffer1, user);
340                 strcpy(tnb.buffer2, "");
341                 ForEachUser(try_name, &tnb);
342                 if (strlen(tnb.buffer2) == 0) return(rfc822_no_such_user);
343                 strcpy(destuser, tnb.buffer2);
344                 return(rfc822_address_locally_validated);
345         }
346
347         strcpy(destuser, user);
348         strcpy(desthost, node);
349         return(rfc822_address_invalid); /* unknown error */
350 }
351
352
353
354
355 /*
356  * convert_field() is a helper function for convert_internet_message().
357  * Given start/end positions for an rfc822 field, it converts it to a Citadel
358  * field if it wants to, and unfolds it if necessary.
359  *
360  * Returns 1 if the field was converted and inserted into the Citadel message
361  * structure, implying that the source field should be removed from the
362  * message text.
363  */
364 int convert_field(struct CtdlMessage *msg, int beg, int end) {
365         char *rfc822;
366         char *key, *value;
367         int i;
368         int colonpos = (-1);
369         int processed = 0;
370         char buf[256];
371         char user[1024];
372         char node[1024];
373         char name[1024];
374         char addr[1024];
375         time_t parsed_date;
376
377         rfc822 = msg->cm_fields['M'];   /* M field contains rfc822 text */
378         for (i = end; i >= beg; --i) {
379                 if (rfc822[i] == ':') colonpos = i;
380         }
381
382         if (colonpos < 0) return(0);    /* no colon? not a valid header line */
383
384         key = mallok((end - beg) + 2);
385         safestrncpy(key, &rfc822[beg], (end-beg)+1);
386         key[colonpos - beg] = 0;
387         value = &key[(colonpos - beg) + 1];
388         unfold_rfc822_field(value);
389
390         lprintf(9, "Key=<%s> Value=<%s>\n", key, value);
391
392         /*
393          * Here's the big rfc822-to-citadel loop.
394          */
395
396         /* Date/time is converted into a unix timestamp.  If the conversion
397          * fails, we replace it with the time the message arrived locally.
398          */
399         if (!strcasecmp(key, "Date")) {
400                 parsed_date = parsedate(value);
401                 if (parsed_date < 0L) parsed_date = time(NULL);
402                 lprintf(9, "Parsed date is %s",
403                         asctime(localtime(&parsed_date)));
404                 sprintf(buf, "%ld", parsed_date );
405                 if (msg->cm_fields['T'] == NULL)
406                         msg->cm_fields['T'] = strdoop(buf);
407                 processed = 1;
408         }
409
410         else if (!strcasecmp(key, "From")) {
411                 process_rfc822_addr(value, user, node, name);
412                 lprintf(9, "Converted to <%s@%s> (%s)\n", user, node, name);
413                 sprintf(addr, "%s@%s", user, node);
414                 if (msg->cm_fields['A'] == NULL)
415                         msg->cm_fields['A'] = strdoop(name);
416                 processed = 1;
417                 if (msg->cm_fields['F'] == NULL)
418                         msg->cm_fields['F'] = strdoop(addr);
419                 processed = 1;
420         }
421
422         else if (!strcasecmp(key, "Subject")) {
423                 if (msg->cm_fields['U'] == NULL)
424                         msg->cm_fields['U'] = strdoop(value);
425                 processed = 1;
426         }
427
428         /* Clean up and move on. */
429         phree(key);     /* Don't free 'value', it's actually the same buffer */
430         return(processed);
431 }
432
433
434 /*
435  * Convert an RFC822 message (headers + body) to a CtdlMessage structure.
436  */
437 struct CtdlMessage *convert_internet_message(char *rfc822) {
438
439         struct CtdlMessage *msg;
440         int pos, beg, end;
441         int done;
442         char buf[256];
443         int converted;
444
445         msg = mallok(sizeof(struct CtdlMessage));
446         if (msg == NULL) return msg;
447
448         memset(msg, 0, sizeof(struct CtdlMessage));
449         msg->cm_magic = CTDLMESSAGE_MAGIC;      /* self check */
450         msg->cm_anon_type = 0;                  /* never anonymous */
451         msg->cm_format_type = FMT_RFC822;       /* internet message */
452         msg->cm_fields['M'] = rfc822;
453
454         lprintf(9, "Unconverted RFC822 message length = %d\n", strlen(rfc822));
455         pos = 0;
456         done = 0;
457
458         while (!done) {
459
460                 /* Locate beginning and end of field, keeping in mind that
461                  * some fields might be multiline
462                  */
463                 beg = pos;
464                 end = (-1);
465                 for (pos=beg; ((pos<=strlen(rfc822))&&(end<0)); ++pos) {
466                         if ((rfc822[pos]=='\n')
467                            && (!isspace(rfc822[pos+1]))) {
468                                 end = pos;
469                         }
470                         if ( (rfc822[pos]=='\n')        /* done w. headers? */
471                            && ( (rfc822[pos+1]=='\n')
472                               ||(rfc822[pos+1]=='\r'))) {
473                                 end = pos;
474                                 done = 1;
475                         }
476
477                 }
478
479                 /* At this point we have a field.  Are we interested in it? */
480                 converted = convert_field(msg, beg, end);
481
482                 /* Strip the field out of the RFC822 header if we used it */
483                 if (converted) {
484                         strcpy(&rfc822[beg], &rfc822[pos]);
485                         pos = beg;
486                 }
487
488                 /* If we've hit the end of the message, bail out */
489                 if (pos > strlen(rfc822)) done = 1;
490         }
491
492         /* Follow-up sanity checks... */
493
494         /* If there's no timestamp on this message, set it to now. */
495         if (msg->cm_fields['T'] == NULL) {
496                 sprintf(buf, "%ld", time(NULL));
497                 msg->cm_fields['T'] = strdoop(buf);
498         }
499
500         lprintf(9, "RFC822 length remaining after conversion = %d\n",
501                 strlen(rfc822));
502         return msg;
503 }
504