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