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