* Realized that there was lots of similarly broken code in
[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
149         strcpy(user, "");
150         strcpy(node, config.c_fqdn);
151         strcpy(name, "");
152
153         /* extract full name - first, it's From minus <userid> */
154         strcpy(name, rfc822);
155         stripout(name, '<', '>');
156
157         /* strip anything to the left of a bang */
158         while ((strlen(name) > 0) && (haschar(name, '!') > 0))
159                 strcpy(name, &name[1]);
160
161         /* and anything to the right of a @ or % */
162         for (a = 0; a < strlen(name); ++a) {
163                 if (name[a] == '@')
164                         name[a] = 0;
165                 if (name[a] == '%')
166                         name[a] = 0;
167         }
168
169         /* but if there are parentheses, that changes the rules... */
170         if ((haschar(rfc822, '(') == 1) && (haschar(rfc822, ')') == 1)) {
171                 strcpy(name, rfc822);
172                 stripallbut(name, '(', ')');
173         }
174
175         /* but if there are a set of quotes, that supersedes everything */
176         if (haschar(rfc822, 34) == 2) {
177                 strcpy(name, rfc822);
178                 while ((strlen(name) > 0) && (name[0] != 34)) {
179                         strcpy(&name[0], &name[1]);
180                 }
181                 strcpy(&name[0], &name[1]);
182                 for (a = 0; a < strlen(name); ++a)
183                         if (name[a] == 34)
184                                 name[a] = 0;
185         }
186         /* extract user id */
187         strcpy(user, rfc822);
188
189         /* first get rid of anything in parens */
190         stripout(user, '(', ')');
191
192         /* if there's a set of angle brackets, strip it down to that */
193         if ((haschar(user, '<') == 1) && (haschar(user, '>') == 1)) {
194                 stripallbut(user, '<', '>');
195         }
196
197         /* strip anything to the left of a bang */
198         while ((strlen(user) > 0) && (haschar(user, '!') > 0))
199                 strcpy(user, &user[1]);
200
201         /* and anything to the right of a @ or % */
202         for (a = 0; a < strlen(user); ++a) {
203                 if (user[a] == '@')
204                         user[a] = 0;
205                 if (user[a] == '%')
206                         user[a] = 0;
207         }
208
209
210         /* extract node name */
211         strcpy(node, rfc822);
212
213         /* first get rid of anything in parens */
214         stripout(node, '(', ')');
215
216         /* if there's a set of angle brackets, strip it down to that */
217         if ((haschar(node, '<') == 1) && (haschar(node, '>') == 1)) {
218                 stripallbut(node, '<', '>');
219         }
220
221         /* If no node specified, tack ours on instead */
222         if (
223                 (haschar(node, '@')==0)
224                 && (haschar(node, '%')==0)
225                 && (haschar(node, '!')==0)
226         ) {
227                 strcpy(node, config.c_nodename);
228         }
229
230         else {
231
232                 /* strip anything to the left of a @ */
233                 while ((strlen(node) > 0) && (haschar(node, '@') > 0))
234                         strcpy(node, &node[1]);
235         
236                 /* strip anything to the left of a % */
237                 while ((strlen(node) > 0) && (haschar(node, '%') > 0))
238                         strcpy(node, &node[1]);
239         
240                 /* reduce multiple system bang paths to node!user */
241                 while ((strlen(node) > 0) && (haschar(node, '!') > 1))
242                         strcpy(node, &node[1]);
243         
244                 /* now get rid of the user portion of a node!user string */
245                 for (a = 0; a < strlen(node); ++a)
246                         if (node[a] == '!')
247                                 node[a] = 0;
248         }
249
250         /* strip leading and trailing spaces in all strings */
251         striplt(user);
252         striplt(node);
253         striplt(name);
254 }
255
256
257
258 /*
259  * Back end for convert_internet_address()
260  * (Compares an internet name [buffer1] and stores in [buffer2] if found)
261  */
262 void try_name(struct usersupp *us, void *data) {
263         struct passwd *pw;
264         struct trynamebuf *tnb;
265         tnb = (struct trynamebuf *)data;
266
267         if (!strncasecmp(tnb->buffer1, "cit", 3))
268                 if (atol(&tnb->buffer1[3]) == us->usernum)
269                         strcpy(tnb->buffer2, us->fullname);
270
271         if (!collapsed_strcmp(tnb->buffer1, us->fullname)) 
272                         strcpy(tnb->buffer2, us->fullname);
273
274         if (us->uid != BBSUID) {
275                 pw = getpwuid(us->uid);
276                 if (pw != NULL) {
277                         if (!strcasecmp(tnb->buffer1, pw->pw_name)) {
278                                 strcpy(tnb->buffer2, us->fullname);
279                         }
280                 }
281         }
282 }
283
284
285 /*
286  * Convert an Internet email address to a Citadel user/host combination
287  */
288 int convert_internet_address(char *destuser, char *desthost, char *source)
289 {
290         char user[SIZ];
291         char node[SIZ];
292         char name[SIZ];
293         struct quickroom qrbuf;
294         int i;
295         int hostalias;
296         struct trynamebuf tnb;
297         char buf[SIZ];
298         int passes = 0;
299         char sourcealias[1024];
300
301         safestrncpy(sourcealias, source, sizeof(sourcealias) );
302         alias(sourcealias);
303
304 REALIAS:
305         /* Split it up */
306         process_rfc822_addr(sourcealias, user, node, name);
307         lprintf(9, "process_rfc822_addr() converted to <%s@%s> (%s)\n",
308                 user, node, name);
309
310         /* Map the FQDN to a Citadel node name
311          */
312         hostalias =  CtdlHostAlias(node);
313         switch(hostalias) {
314                 case hostalias_localhost:
315                         strcpy(node, config.c_nodename);
316                         break;
317
318                 case hostalias_gatewaydomain:
319                         extract_token(buf, node, 0, '.');
320                         safestrncpy(node, buf, sizeof buf);
321         }
322
323         /* Now try to resolve the name
324          * FIXME ... do the multiple-addresses thing
325          */
326         if (!strcasecmp(node, config.c_nodename)) {
327
328
329                 /* First, see if we hit an alias.  Don't do this more than
330                  * a few times, in case we accidentally hit an alias loop
331                  */
332                 strcpy(sourcealias, user);
333                 alias(user);
334                 if ( (strcasecmp(user, sourcealias)) && (++passes < 3) )
335                         goto REALIAS;
336
337                 /* Try all local rooms */
338                 if (!strncasecmp(user, "room_", 5)) {
339                         strcpy(name, &user[5]);
340                         for (i=0; i<strlen(name); ++i) 
341                                 if (name[i]=='_') name[i]=' ';
342                         if (getroom(&qrbuf, name) == 0) {
343                                 strcpy(destuser, qrbuf.QRname);
344                                 strcpy(desthost, config.c_nodename);
345                                 return rfc822_room_delivery;
346                         }
347                 }
348
349                 /* Try all local users */
350                 strcpy(destuser, user);
351                 strcpy(desthost, config.c_nodename);
352                 strcpy(tnb.buffer1, user);
353                 strcpy(tnb.buffer2, "");
354                 ForEachUser(try_name, &tnb);
355                 if (strlen(tnb.buffer2) == 0) return(rfc822_no_such_user);
356                 strcpy(destuser, tnb.buffer2);
357                 return(rfc822_address_locally_validated);
358         }
359
360         strcpy(destuser, user);
361         strcpy(desthost, node);
362         if (hostalias == hostalias_gatewaydomain)
363                 return(rfc822_address_on_citadel_network);
364         return(rfc822_address_nonlocal);
365 }
366
367
368
369
370 /*
371  * convert_field() is a helper function for convert_internet_message().
372  * Given start/end positions for an rfc822 field, it converts it to a Citadel
373  * field if it wants to, and unfolds it if necessary.
374  *
375  * Returns 1 if the field was converted and inserted into the Citadel message
376  * structure, implying that the source field should be removed from the
377  * message text.
378  */
379 int convert_field(struct CtdlMessage *msg, int beg, int end) {
380         char *rfc822;
381         char *key, *value;
382         int i;
383         int colonpos = (-1);
384         int processed = 0;
385         char buf[SIZ];
386         char user[1024];
387         char node[1024];
388         char name[1024];
389         char addr[1024];
390         time_t parsed_date;
391
392         rfc822 = msg->cm_fields['M'];   /* M field contains rfc822 text */
393         for (i = end; i >= beg; --i) {
394                 if (rfc822[i] == ':') colonpos = i;
395         }
396
397         if (colonpos < 0) return(0);    /* no colon? not a valid header line */
398
399         key = mallok((end - beg) + 2);
400         safestrncpy(key, &rfc822[beg], (end-beg)+1);
401         key[colonpos - beg] = 0;
402         value = &key[(colonpos - beg) + 1];
403         unfold_rfc822_field(value);
404
405         /*
406          * Here's the big rfc822-to-citadel loop.
407          */
408
409         /* Date/time is converted into a unix timestamp.  If the conversion
410          * fails, we replace it with the time the message arrived locally.
411          */
412         if (!strcasecmp(key, "Date")) {
413                 parsed_date = parsedate(value);
414                 if (parsed_date < 0L) parsed_date = time(NULL);
415                 snprintf(buf, sizeof buf, "%ld", parsed_date );
416                 if (msg->cm_fields['T'] == NULL)
417                         msg->cm_fields['T'] = strdoop(buf);
418                 processed = 1;
419         }
420
421         else if (!strcasecmp(key, "From")) {
422                 process_rfc822_addr(value, user, node, name);
423                 lprintf(9, "Converted to <%s@%s> (%s)\n", user, node, name);
424                 snprintf(addr, sizeof addr, "%s@%s", user, node);
425                 if (msg->cm_fields['A'] == NULL)
426                         msg->cm_fields['A'] = strdoop(name);
427                 processed = 1;
428                 if (msg->cm_fields['F'] == NULL)
429                         msg->cm_fields['F'] = strdoop(addr);
430                 processed = 1;
431         }
432
433         else if (!strcasecmp(key, "Subject")) {
434                 if (msg->cm_fields['U'] == NULL)
435                         msg->cm_fields['U'] = strdoop(value);
436                 processed = 1;
437         }
438
439         else if (!strcasecmp(key, "Message-ID")) {
440                 if (msg->cm_fields['I'] != NULL) {
441                         lprintf(5, "duplicate message id\n");
442                 }
443
444                 if (msg->cm_fields['I'] == NULL) {
445                         msg->cm_fields['I'] = strdoop(value);
446
447                         /* Strip angle brackets */
448                         while (haschar(msg->cm_fields['I'], '<') > 0) {
449                                 strcpy(&msg->cm_fields['I'][0],
450                                         &msg->cm_fields['I'][1]);
451                         }
452                         for (i = 0; i<strlen(msg->cm_fields['I']); ++i)
453                                 if (msg->cm_fields['I'][i] == '>')
454                                         msg->cm_fields['I'][i] = 0;
455                 }
456
457                 processed = 1;
458         }
459
460         /* Clean up and move on. */
461         phree(key);     /* Don't free 'value', it's actually the same buffer */
462         return(processed);
463 }
464
465
466 /*
467  * Convert an RFC822 message (headers + body) to a CtdlMessage structure.
468  * NOTE: the supplied buffer becomes part of the CtdlMessage structure, and
469  * will be deallocated when CtdlFreeMessage() is called.  Therefore, the
470  * supplied buffer should be DEREFERENCED.  It should not be freed or used
471  * again.
472  */
473 struct CtdlMessage *convert_internet_message(char *rfc822) {
474
475         struct CtdlMessage *msg;
476         int pos, beg, end, msglen;
477         int done;
478         char buf[SIZ];
479         int converted;
480
481         msg = mallok(sizeof(struct CtdlMessage));
482         if (msg == NULL) return msg;
483
484         memset(msg, 0, sizeof(struct CtdlMessage));
485         msg->cm_magic = CTDLMESSAGE_MAGIC;      /* self check */
486         msg->cm_anon_type = 0;                  /* never anonymous */
487         msg->cm_format_type = FMT_RFC822;       /* internet message */
488         msg->cm_fields['M'] = rfc822;
489
490         lprintf(9, "Unconverted RFC822 message length = %d\n", strlen(rfc822));
491         pos = 0;
492         done = 0;
493
494         while (!done) {
495
496                 /* Locate beginning and end of field, keeping in mind that
497                  * some fields might be multiline
498                  */
499                 beg = pos;
500                 end = (-1);
501
502                 msglen = strlen(rfc822);        
503                 while ( (end < 0) && (done == 0) ) {
504
505                         if ((rfc822[pos]=='\n')
506                            && (!isspace(rfc822[pos+1]))) {
507                                 end = pos;
508                         }
509
510                         /* done with headers? */
511                         if (   ((rfc822[pos]=='\n')
512                               ||(rfc822[pos]=='\r') )
513                            && ( (rfc822[pos+1]=='\n')
514                               ||(rfc822[pos+1]=='\r')) ) {
515                                 end = pos;
516                                 done = 1;
517                         }
518
519                         if (pos >= (msglen-1) ) {
520                                 end = pos;
521                                 done = 1;
522                         }
523
524                         ++pos;
525
526                 }
527
528                 /* At this point we have a field.  Are we interested in it? */
529                 converted = convert_field(msg, beg, end);
530
531                 /* Strip the field out of the RFC822 header if we used it */
532                 if (converted) {
533                         strcpy(&rfc822[beg], &rfc822[pos]);
534                         pos = beg;
535                 }
536
537                 /* If we've hit the end of the message, bail out */
538                 if (pos > strlen(rfc822)) done = 1;
539         }
540
541         /* Follow-up sanity checks... */
542
543         /* If there's no timestamp on this message, set it to now. */
544         if (msg->cm_fields['T'] == NULL) {
545                 snprintf(buf, sizeof buf, "%ld", time(NULL));
546                 msg->cm_fields['T'] = strdoop(buf);
547         }
548
549         lprintf(9, "RFC822 length remaining after conversion = %d\n",
550                 strlen(rfc822));
551         return msg;
552 }
553
554
555
556 /*
557  * Look for a particular header field in an RFC822 message text.  If the
558  * requested field is found, it is unfolded (if necessary) and returned to
559  * the caller.  The field name is stripped out, leaving only its contents.
560  * The caller is responsible for freeing the returned buffer.  If the requested
561  * field is not present, or anything else goes wrong, it returns NULL.
562  */
563 char *rfc822_fetch_field(char *rfc822, char *fieldname) {
564         int pos = 0;
565         int beg, end;
566         int done = 0;
567         int colonpos, i;
568         char *fieldbuf = NULL;
569
570         /* Should never happen, but sometimes we get stupid */
571         if (rfc822 == NULL) return(NULL);
572         if (fieldname == NULL) return(NULL);
573
574         while (!done) {
575
576                 /* Locate beginning and end of field, keeping in mind that
577                  * some fields might be multiline
578                  */
579                 beg = pos;
580                 end = (-1);
581                 for (pos=beg; ((pos<=strlen(rfc822))&&(end<0)); ++pos) {
582                         if ((rfc822[pos]=='\n')
583                            && (!isspace(rfc822[pos+1]))) {
584                                 end = pos;
585                         }
586                         if ( (rfc822[pos]=='\n')        /* done w. headers? */
587                            && ( (rfc822[pos+1]=='\n')
588                               ||(rfc822[pos+1]=='\r'))) {
589                                 end = pos;
590                                 done = 1;
591                         }
592
593                 }
594
595                 /* At this point we have a field.  Is it The One? */
596                 if (end > beg) {
597                         fieldbuf = mallok((end-beg)+3);
598                         if (fieldbuf == NULL) return(NULL);
599                         safestrncpy(fieldbuf, &rfc822[beg], (end-beg)+1);
600                         unfold_rfc822_field(fieldbuf);
601                         colonpos = (-1);
602                         for (i = strlen(fieldbuf); i >= 0; --i) {
603                                 if (fieldbuf[i] == ':') colonpos = i;
604                         }
605                         if (colonpos > 0) {
606                                 fieldbuf[colonpos] = 0;
607                                 if (!strcasecmp(fieldbuf, fieldname)) {
608                                         strcpy(fieldbuf, &fieldbuf[colonpos+1]);
609                                         striplt(fieldbuf);
610                                         return(fieldbuf);
611                                 }
612                         }
613                         phree(fieldbuf);
614                 }
615
616                 /* If we've hit the end of the message, bail out */
617                 if (pos > strlen(rfc822)) done = 1;
618         }
619         return(NULL);
620 }