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