* internet_addressing.c: fixed a bug in process_rfc822_addr() that caused the
[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
19 #if TIME_WITH_SYS_TIME
20 # include <sys/time.h>
21 # include <time.h>
22 #else
23 # if HAVE_SYS_TIME_H
24 #  include <sys/time.h>
25 # else
26 #  include <time.h>
27 # endif
28 #endif
29
30 #include <sys/wait.h>
31 #include <string.h>
32 #include <limits.h>
33 #include "citadel.h"
34 #include "server.h"
35 #include "sysdep_decls.h"
36 #include "citserver.h"
37 #include "support.h"
38 #include "config.h"
39 #include "tools.h"
40 #include "msgbase.h"
41 #include "internet_addressing.h"
42 #include "user_ops.h"
43 #include "room_ops.h"
44 #include "parsedate.h"
45
46
47 struct trynamebuf {
48         char buffer1[SIZ];
49         char buffer2[SIZ];
50 };
51
52 char *inetcfg = NULL;
53
54
55
56 /*
57  * Return nonzero if the supplied name is an alias for this host.
58  */
59 int CtdlHostAlias(char *fqdn) {
60         int config_lines;
61         int i;
62         char buf[SIZ];
63         char host[SIZ], type[SIZ];
64
65         if (!strcasecmp(fqdn, config.c_fqdn)) return(hostalias_localhost);
66         if (!strcasecmp(fqdn, config.c_nodename)) return(hostalias_localhost);
67         if (inetcfg == NULL) return(hostalias_nomatch);
68
69         config_lines = num_tokens(inetcfg, '\n');
70         for (i=0; i<config_lines; ++i) {
71                 extract_token(buf, inetcfg, i, '\n');
72                 extract_token(host, buf, 0, '|');
73                 extract_token(type, buf, 1, '|');
74
75                 if ( (!strcasecmp(type, "localhost"))
76                    && (!strcasecmp(fqdn, host)))
77                         return(hostalias_localhost);
78
79                 if ( (!strcasecmp(type, "gatewaydomain"))
80                    && (!strcasecmp(&fqdn[strlen(fqdn)-strlen(host)], host)))
81                         return(hostalias_gatewaydomain);
82
83         }
84
85         return(hostalias_nomatch);
86 }
87
88
89
90
91
92
93
94 /*
95  * Return 0 if a given string fuzzy-matches a Citadel user account
96  *
97  * FIXME ... this needs to be updated to handle aliases.
98  */
99 int fuzzy_match(struct usersupp *us, char *matchstring) {
100         int a;
101
102         if ( (!strncasecmp(matchstring, "cit", 3)) 
103            && (atol(&matchstring[3]) == us->usernum)) {
104                 return 0;
105         }
106
107
108         for (a=0; a<strlen(us->fullname); ++a) {
109                 if (!strncasecmp(&us->fullname[a],
110                    matchstring, strlen(matchstring))) {
111                         return 0;
112                 }
113         }
114         return -1;
115 }
116
117
118 /*
119  * Unfold a multi-line field into a single line, removing multi-whitespaces
120  */
121 void unfold_rfc822_field(char *field) {
122         int i;
123         int quote = 0;
124
125         striplt(field);         /* remove leading/trailing whitespace */
126
127         /* convert non-space whitespace to spaces, and remove double blanks */
128         for (i=0; i<strlen(field); ++i) {
129                 if (field[i]=='\"') quote = 1 - quote;
130                 if (!quote) {
131                         if (isspace(field[i])) field[i] = ' ';
132                         while (isspace(field[i]) && isspace(field[i+1])) {
133                                 strcpy(&field[i+1], &field[i+2]);
134                         }
135                 }
136         }
137 }
138
139
140
141 /*
142  * Split an RFC822-style address into userid, host, and full name
143  *
144  */
145 void process_rfc822_addr(char *rfc822, char *user, char *node, char *name)
146 {
147         int a;
148         int lb, rb;
149
150         strcpy(user, "");
151         strcpy(node, config.c_fqdn);
152         strcpy(name, "");
153
154         /* extract full name - first, it's From minus <userid> */
155         strcpy(name, rfc822);
156         lb = (-1);
157         rb = (-1);
158         for (a = 0; a < strlen(name); ++a) {
159                 if (name[a] == '<') lb = a;
160                 if (name[a] == '>') rb = a;
161         }
162         if ( (lb > 0) && (rb > lb) ) {
163                 strcpy(&name[lb - 1], &name[rb + 1]);
164         }
165
166         /* strip anything to the left of a bang */
167         while ((strlen(name) > 0) && (haschar(name, '!') > 0))
168                 strcpy(name, &name[1]);
169
170         /* and anything to the right of a @ or % */
171         for (a = 0; a < strlen(name); ++a) {
172                 if (name[a] == '@')
173                         name[a] = 0;
174                 if (name[a] == '%')
175                         name[a] = 0;
176         }
177
178         /* but if there are parentheses, that changes the rules... */
179         if ((haschar(rfc822, '(') == 1) && (haschar(rfc822, ')') == 1)) {
180                 strcpy(name, rfc822);
181                 while ((strlen(name) > 0) && (name[0] != '(')) {
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] == ')') {
187                                 name[a] = 0;
188                         }
189                 }
190         }
191         /* but if there are a set of quotes, that supersedes everything */
192         if (haschar(rfc822, 34) == 2) {
193                 strcpy(name, rfc822);
194                 while ((strlen(name) > 0) && (name[0] != 34)) {
195                         strcpy(&name[0], &name[1]);
196                 }
197                 strcpy(&name[0], &name[1]);
198                 for (a = 0; a < strlen(name); ++a)
199                         if (name[a] == 34)
200                                 name[a] = 0;
201         }
202         /* extract user id */
203         strcpy(user, rfc822);
204
205         /* first get rid of anything in parens */
206         for (a = 0; a < strlen(user); ++a)
207                 if (user[a] == '(') {
208                         do {
209                                 strcpy(&user[a], &user[a + 1]);
210                         } while ((strlen(user) > 0) && (user[a] != ')'));
211                         strcpy(&user[a], &user[a + 1]);
212                 }
213         /* if there's a set of angle brackets, strip it down to that */
214         if ((haschar(user, '<') == 1) && (haschar(user, '>') == 1)) {
215                 while ((strlen(user) > 0) && (user[0] != '<')) {
216                         strcpy(&user[0], &user[1]);
217                 }
218                 strcpy(&user[0], &user[1]);
219                 for (a = 0; a < strlen(user); ++a)
220                         if (user[a] == '>')
221                                 user[a] = 0;
222         }
223         /* strip anything to the left of a bang */
224         while ((strlen(user) > 0) && (haschar(user, '!') > 0))
225                 strcpy(user, &user[1]);
226
227         /* and anything to the right of a @ or % */
228         for (a = 0; a < strlen(user); ++a) {
229                 if (user[a] == '@')
230                         user[a] = 0;
231                 if (user[a] == '%')
232                         user[a] = 0;
233         }
234
235
236         /* extract node name */
237         strcpy(node, rfc822);
238
239         /* first get rid of anything in parens */
240         for (a = 0; a < strlen(node); ++a)
241                 if (node[a] == '(') {
242                         do {
243                                 strcpy(&node[a], &node[a + 1]);
244                         } while ((strlen(node) > 0) && (node[a] != ')'));
245                         strcpy(&node[a], &node[a + 1]);
246                 }
247         /* if there's a set of angle brackets, strip it down to that */
248         if ((haschar(node, '<') == 1) && (haschar(node, '>') == 1)) {
249                 while ((strlen(node) > 0) && (node[0] != '<')) {
250                         strcpy(&node[0], &node[1]);
251                 }
252                 strcpy(&node[0], &node[1]);
253                 for (a = 0; a < strlen(node); ++a)
254                         if (node[a] == '>')
255                                 node[a] = 0;
256         }
257
258         /* If no node specified, tack ours on instead */
259         if (
260                 (haschar(node, '@')==0)
261                 && (haschar(node, '%')==0)
262                 && (haschar(node, '!')==0)
263         ) {
264                 strcpy(node, config.c_nodename);
265         }
266
267         else {
268
269                 /* strip anything to the left of a @ */
270                 while ((strlen(node) > 0) && (haschar(node, '@') > 0))
271                         strcpy(node, &node[1]);
272         
273                 /* strip anything to the left of a % */
274                 while ((strlen(node) > 0) && (haschar(node, '%') > 0))
275                         strcpy(node, &node[1]);
276         
277                 /* reduce multiple system bang paths to node!user */
278                 while ((strlen(node) > 0) && (haschar(node, '!') > 1))
279                         strcpy(node, &node[1]);
280         
281                 /* now get rid of the user portion of a node!user string */
282                 for (a = 0; a < strlen(node); ++a)
283                         if (node[a] == '!')
284                                 node[a] = 0;
285         }
286
287         /* strip leading and trailing spaces in all strings */
288         striplt(user);
289         striplt(node);
290         striplt(name);
291 }
292
293
294
295 /*
296  * Back end for convert_internet_address()
297  * (Compares an internet name [buffer1] and stores in [buffer2] if found)
298  */
299 void try_name(struct usersupp *us, void *data) {
300         struct passwd *pw;
301         struct trynamebuf *tnb;
302         tnb = (struct trynamebuf *)data;
303
304         if (!strncasecmp(tnb->buffer1, "cit", 3))
305                 if (atol(&tnb->buffer1[3]) == us->usernum)
306                         strcpy(tnb->buffer2, us->fullname);
307
308         if (!collapsed_strcmp(tnb->buffer1, us->fullname)) 
309                         strcpy(tnb->buffer2, us->fullname);
310
311         if (us->uid != BBSUID) {
312                 pw = getpwuid(us->uid);
313                 if (pw != NULL) {
314                         if (!strcasecmp(tnb->buffer1, pw->pw_name)) {
315                                 strcpy(tnb->buffer2, us->fullname);
316                         }
317                 }
318         }
319 }
320
321
322 /*
323  * Convert an Internet email address to a Citadel user/host combination
324  */
325 int convert_internet_address(char *destuser, char *desthost, char *source)
326 {
327         char user[SIZ];
328         char node[SIZ];
329         char name[SIZ];
330         struct quickroom qrbuf;
331         int i;
332         int hostalias;
333         struct trynamebuf tnb;
334         char buf[SIZ];
335         int passes = 0;
336         char sourcealias[1024];
337
338         safestrncpy(sourcealias, source, sizeof(sourcealias) );
339         alias(sourcealias);
340
341 REALIAS:
342         /* Split it up */
343         process_rfc822_addr(sourcealias, user, node, name);
344         lprintf(9, "process_rfc822_addr() converted to <%s@%s> (%s)\n",
345                 user, node, name);
346
347         /* Map the FQDN to a Citadel node name
348          */
349         hostalias =  CtdlHostAlias(node);
350         switch(hostalias) {
351                 case hostalias_localhost:
352                         strcpy(node, config.c_nodename);
353                         break;
354
355                 case hostalias_gatewaydomain:
356                         extract_token(buf, node, 0, '.');
357                         safestrncpy(node, buf, sizeof buf);
358         }
359
360         /* Now try to resolve the name
361          * FIXME ... do the multiple-addresses thing
362          */
363         if (!strcasecmp(node, config.c_nodename)) {
364
365
366                 /* First, see if we hit an alias.  Don't do this more than
367                  * a few times, in case we accidentally hit an alias loop
368                  */
369                 strcpy(sourcealias, user);
370                 alias(user);
371                 if ( (strcasecmp(user, sourcealias)) && (++passes < 3) )
372                         goto REALIAS;
373
374                 /* Try all local rooms */
375                 if (!strncasecmp(user, "room_", 5)) {
376                         strcpy(name, &user[5]);
377                         for (i=0; i<strlen(name); ++i) 
378                                 if (name[i]=='_') name[i]=' ';
379                         if (getroom(&qrbuf, name) == 0) {
380                                 strcpy(destuser, qrbuf.QRname);
381                                 strcpy(desthost, config.c_nodename);
382                                 return rfc822_room_delivery;
383                         }
384                 }
385
386                 /* Try all local users */
387                 strcpy(destuser, user);
388                 strcpy(desthost, config.c_nodename);
389                 strcpy(tnb.buffer1, user);
390                 strcpy(tnb.buffer2, "");
391                 ForEachUser(try_name, &tnb);
392                 if (strlen(tnb.buffer2) == 0) return(rfc822_no_such_user);
393                 strcpy(destuser, tnb.buffer2);
394                 return(rfc822_address_locally_validated);
395         }
396
397         strcpy(destuser, user);
398         strcpy(desthost, node);
399         if (hostalias == hostalias_gatewaydomain)
400                 return(rfc822_address_on_citadel_network);
401         return(rfc822_address_nonlocal);
402 }
403
404
405
406
407 /*
408  * convert_field() is a helper function for convert_internet_message().
409  * Given start/end positions for an rfc822 field, it converts it to a Citadel
410  * field if it wants to, and unfolds it if necessary.
411  *
412  * Returns 1 if the field was converted and inserted into the Citadel message
413  * structure, implying that the source field should be removed from the
414  * message text.
415  */
416 int convert_field(struct CtdlMessage *msg, int beg, int end) {
417         char *rfc822;
418         char *key, *value;
419         int i;
420         int colonpos = (-1);
421         int processed = 0;
422         char buf[SIZ];
423         char user[1024];
424         char node[1024];
425         char name[1024];
426         char addr[1024];
427         time_t parsed_date;
428
429         rfc822 = msg->cm_fields['M'];   /* M field contains rfc822 text */
430         for (i = end; i >= beg; --i) {
431                 if (rfc822[i] == ':') colonpos = i;
432         }
433
434         if (colonpos < 0) return(0);    /* no colon? not a valid header line */
435
436         key = mallok((end - beg) + 2);
437         safestrncpy(key, &rfc822[beg], (end-beg)+1);
438         key[colonpos - beg] = 0;
439         value = &key[(colonpos - beg) + 1];
440         unfold_rfc822_field(value);
441
442         /*
443          * Here's the big rfc822-to-citadel loop.
444          */
445
446         /* Date/time is converted into a unix timestamp.  If the conversion
447          * fails, we replace it with the time the message arrived locally.
448          */
449         if (!strcasecmp(key, "Date")) {
450                 parsed_date = parsedate(value);
451                 if (parsed_date < 0L) parsed_date = time(NULL);
452                 snprintf(buf, sizeof buf, "%ld", parsed_date );
453                 if (msg->cm_fields['T'] == NULL)
454                         msg->cm_fields['T'] = strdoop(buf);
455                 processed = 1;
456         }
457
458         else if (!strcasecmp(key, "From")) {
459                 process_rfc822_addr(value, user, node, name);
460                 lprintf(9, "Converted to <%s@%s> (%s)\n", user, node, name);
461                 snprintf(addr, sizeof addr, "%s@%s", user, node);
462                 if (msg->cm_fields['A'] == NULL)
463                         msg->cm_fields['A'] = strdoop(name);
464                 processed = 1;
465                 if (msg->cm_fields['F'] == NULL)
466                         msg->cm_fields['F'] = strdoop(addr);
467                 processed = 1;
468         }
469
470         else if (!strcasecmp(key, "Subject")) {
471                 if (msg->cm_fields['U'] == NULL)
472                         msg->cm_fields['U'] = strdoop(value);
473                 processed = 1;
474         }
475
476         else if (!strcasecmp(key, "Message-ID")) {
477                 if (msg->cm_fields['I'] != NULL) {
478                         lprintf(5, "duplicate message id\n");
479                 }
480
481                 if (msg->cm_fields['I'] == NULL) {
482                         msg->cm_fields['I'] = strdoop(value);
483
484                         /* Strip angle brackets */
485                         while (haschar(msg->cm_fields['I'], '<') > 0) {
486                                 strcpy(&msg->cm_fields['I'][0],
487                                         &msg->cm_fields['I'][1]);
488                         }
489                         for (i = 0; i<strlen(msg->cm_fields['I']); ++i)
490                                 if (msg->cm_fields['I'][i] == '>')
491                                         msg->cm_fields['I'][i] = 0;
492                 }
493
494                 processed = 1;
495         }
496
497         /* Clean up and move on. */
498         phree(key);     /* Don't free 'value', it's actually the same buffer */
499         return(processed);
500 }
501
502
503 /*
504  * Convert an RFC822 message (headers + body) to a CtdlMessage structure.
505  * NOTE: the supplied buffer becomes part of the CtdlMessage structure, and
506  * will be deallocated when CtdlFreeMessage() is called.  Therefore, the
507  * supplied buffer should be DEREFERENCED.  It should not be freed or used
508  * again.
509  */
510 struct CtdlMessage *convert_internet_message(char *rfc822) {
511
512         struct CtdlMessage *msg;
513         int pos, beg, end, msglen;
514         int done;
515         char buf[SIZ];
516         int converted;
517
518         msg = mallok(sizeof(struct CtdlMessage));
519         if (msg == NULL) return msg;
520
521         memset(msg, 0, sizeof(struct CtdlMessage));
522         msg->cm_magic = CTDLMESSAGE_MAGIC;      /* self check */
523         msg->cm_anon_type = 0;                  /* never anonymous */
524         msg->cm_format_type = FMT_RFC822;       /* internet message */
525         msg->cm_fields['M'] = rfc822;
526
527         lprintf(9, "Unconverted RFC822 message length = %d\n", strlen(rfc822));
528         pos = 0;
529         done = 0;
530
531         while (!done) {
532
533                 /* Locate beginning and end of field, keeping in mind that
534                  * some fields might be multiline
535                  */
536                 beg = pos;
537                 end = (-1);
538
539                 msglen = strlen(rfc822);        
540                 while ( (end < 0) && (done == 0) ) {
541
542                         if ((rfc822[pos]=='\n')
543                            && (!isspace(rfc822[pos+1]))) {
544                                 end = pos;
545                         }
546
547                         /* done with headers? */
548                         if (   ((rfc822[pos]=='\n')
549                               ||(rfc822[pos]=='\r') )
550                            && ( (rfc822[pos+1]=='\n')
551                               ||(rfc822[pos+1]=='\r')) ) {
552                                 end = pos;
553                                 done = 1;
554                         }
555
556                         if (pos >= (msglen-1) ) {
557                                 end = pos;
558                                 done = 1;
559                         }
560
561                         ++pos;
562
563                 }
564
565                 /* At this point we have a field.  Are we interested in it? */
566                 converted = convert_field(msg, beg, end);
567
568                 /* Strip the field out of the RFC822 header if we used it */
569                 if (converted) {
570                         strcpy(&rfc822[beg], &rfc822[pos]);
571                         pos = beg;
572                 }
573
574                 /* If we've hit the end of the message, bail out */
575                 if (pos > strlen(rfc822)) done = 1;
576         }
577
578         /* Follow-up sanity checks... */
579
580         /* If there's no timestamp on this message, set it to now. */
581         if (msg->cm_fields['T'] == NULL) {
582                 snprintf(buf, sizeof buf, "%ld", time(NULL));
583                 msg->cm_fields['T'] = strdoop(buf);
584         }
585
586         lprintf(9, "RFC822 length remaining after conversion = %d\n",
587                 strlen(rfc822));
588         return msg;
589 }
590
591
592
593 /*
594  * Look for a particular header field in an RFC822 message text.  If the
595  * requested field is found, it is unfolded (if necessary) and returned to
596  * the caller.  The field name is stripped out, leaving only its contents.
597  * The caller is responsible for freeing the returned buffer.  If the requested
598  * field is not present, or anything else goes wrong, it returns NULL.
599  */
600 char *rfc822_fetch_field(char *rfc822, char *fieldname) {
601         int pos = 0;
602         int beg, end;
603         int done = 0;
604         int colonpos, i;
605         char *fieldbuf = NULL;
606
607         /* Should never happen, but sometimes we get stupid */
608         if (rfc822 == NULL) return(NULL);
609         if (fieldname == NULL) return(NULL);
610
611         while (!done) {
612
613                 /* Locate beginning and end of field, keeping in mind that
614                  * some fields might be multiline
615                  */
616                 beg = pos;
617                 end = (-1);
618                 for (pos=beg; ((pos<=strlen(rfc822))&&(end<0)); ++pos) {
619                         if ((rfc822[pos]=='\n')
620                            && (!isspace(rfc822[pos+1]))) {
621                                 end = pos;
622                         }
623                         if ( (rfc822[pos]=='\n')        /* done w. headers? */
624                            && ( (rfc822[pos+1]=='\n')
625                               ||(rfc822[pos+1]=='\r'))) {
626                                 end = pos;
627                                 done = 1;
628                         }
629
630                 }
631
632                 /* At this point we have a field.  Is it The One? */
633                 if (end > beg) {
634                         fieldbuf = mallok((end-beg)+3);
635                         if (fieldbuf == NULL) return(NULL);
636                         safestrncpy(fieldbuf, &rfc822[beg], (end-beg)+1);
637                         unfold_rfc822_field(fieldbuf);
638                         colonpos = (-1);
639                         for (i = strlen(fieldbuf); i >= 0; --i) {
640                                 if (fieldbuf[i] == ':') colonpos = i;
641                         }
642                         if (colonpos > 0) {
643                                 fieldbuf[colonpos] = 0;
644                                 if (!strcasecmp(fieldbuf, fieldname)) {
645                                         strcpy(fieldbuf, &fieldbuf[colonpos+1]);
646                                         striplt(fieldbuf);
647                                         return(fieldbuf);
648                                 }
649                         }
650                         phree(fieldbuf);
651                 }
652
653                 /* If we've hit the end of the message, bail out */
654                 if (pos > strlen(rfc822)) done = 1;
655         }
656         return(NULL);
657 }