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