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