* Holy war on strlen: use IsEmptyStr where apropriate.
[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 #include "database.h"
46
47
48 #ifndef HAVE_SNPRINTF
49 #include "snprintf.h"
50 #endif
51
52
53 struct trynamebuf {
54         char buffer1[SIZ];
55         char buffer2[SIZ];
56 };
57
58 char *inetcfg = NULL;
59 struct spamstrings_t *spamstrings = NULL;
60
61
62 /*
63  * Return nonzero if the supplied name is an alias for this host.
64  */
65 int CtdlHostAlias(char *fqdn) {
66         int config_lines;
67         int i;
68         char buf[256];
69         char host[256], type[256];
70
71         if (fqdn == NULL) return(hostalias_nomatch);
72         if (IsEmptyStr(fqdn)) return(hostalias_nomatch);
73         if (!strcasecmp(fqdn, "localhost")) return(hostalias_localhost);
74         if (!strcasecmp(fqdn, config.c_fqdn)) return(hostalias_localhost);
75         if (!strcasecmp(fqdn, config.c_nodename)) return(hostalias_localhost);
76         if (inetcfg == NULL) return(hostalias_nomatch);
77
78         config_lines = num_tokens(inetcfg, '\n');
79         for (i=0; i<config_lines; ++i) {
80                 extract_token(buf, inetcfg, i, '\n', sizeof buf);
81                 extract_token(host, buf, 0, '|', sizeof host);
82                 extract_token(type, buf, 1, '|', sizeof type);
83
84                 if ( (!strcasecmp(type, "localhost"))
85                    && (!strcasecmp(fqdn, host)))
86                         return(hostalias_localhost);
87
88                 if ( (!strcasecmp(type, "gatewaydomain"))
89                    && (!strcasecmp(&fqdn[strlen(fqdn)-strlen(host)], host)))
90                         return(hostalias_gatewaydomain);
91
92                 if ( (!strcasecmp(type, "directory"))
93                    && (!strcasecmp(&fqdn[strlen(fqdn)-strlen(host)], host)))
94                         return(hostalias_directory);
95
96                 if ( (!strcasecmp(type, "masqdomain"))
97                    && (!strcasecmp(&fqdn[strlen(fqdn)-strlen(host)], host)))
98                         return(hostalias_masq);
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         if (rfc822 == NULL) return;
171
172         /* extract full name - first, it's From minus <userid> */
173         strcpy(name, rfc822);
174         stripout(name, '<', '>');
175
176         /* strip anything to the left of a bang */
177         while ((!IsEmptyStr(name)) && (haschar(name, '!') > 0))
178                 strcpy(name, &name[1]);
179
180         /* and anything to the right of a @ or % */
181         for (a = 0; a < strlen(name); ++a) {
182                 if (name[a] == '@')
183                         name[a] = 0;
184                 if (name[a] == '%')
185                         name[a] = 0;
186         }
187
188         /* but if there are parentheses, that changes the rules... */
189         if ((haschar(rfc822, '(') == 1) && (haschar(rfc822, ')') == 1)) {
190                 strcpy(name, rfc822);
191                 stripallbut(name, '(', ')');
192         }
193
194         /* but if there are a set of quotes, that supersedes everything */
195         if (haschar(rfc822, 34) == 2) {
196                 strcpy(name, rfc822);
197                 while ((!IsEmptyStr(name)) && (name[0] != 34)) {
198                         strcpy(&name[0], &name[1]);
199                 }
200                 strcpy(&name[0], &name[1]);
201                 for (a = 0; a < strlen(name); ++a)
202                         if (name[a] == 34)
203                                 name[a] = 0;
204         }
205         /* extract user id */
206         strcpy(user, rfc822);
207
208         /* first get rid of anything in parens */
209         stripout(user, '(', ')');
210
211         /* if there's a set of angle brackets, strip it down to that */
212         if ((haschar(user, '<') == 1) && (haschar(user, '>') == 1)) {
213                 stripallbut(user, '<', '>');
214         }
215
216         /* strip anything to the left of a bang */
217         while ((!IsEmptyStr(user)) && (haschar(user, '!') > 0))
218                 strcpy(user, &user[1]);
219
220         /* and anything to the right of a @ or % */
221         for (a = 0; a < strlen(user); ++a) {
222                 if (user[a] == '@')
223                         user[a] = 0;
224                 if (user[a] == '%')
225                         user[a] = 0;
226         }
227
228
229         /* extract node name */
230         strcpy(node, rfc822);
231
232         /* first get rid of anything in parens */
233         stripout(node, '(', ')');
234
235         /* if there's a set of angle brackets, strip it down to that */
236         if ((haschar(node, '<') == 1) && (haschar(node, '>') == 1)) {
237                 stripallbut(node, '<', '>');
238         }
239
240         /* If no node specified, tack ours on instead */
241         if (
242                 (haschar(node, '@')==0)
243                 && (haschar(node, '%')==0)
244                 && (haschar(node, '!')==0)
245         ) {
246                 strcpy(node, config.c_nodename);
247         }
248
249         else {
250
251                 /* strip anything to the left of a @ */
252                 while ((!IsEmptyStr(node)) && (haschar(node, '@') > 0))
253                         strcpy(node, &node[1]);
254         
255                 /* strip anything to the left of a % */
256                 while ((!IsEmptyStr(node)) && (haschar(node, '%') > 0))
257                         strcpy(node, &node[1]);
258         
259                 /* reduce multiple system bang paths to node!user */
260                 while ((!IsEmptyStr(node)) && (haschar(node, '!') > 1))
261                         strcpy(node, &node[1]);
262         
263                 /* now get rid of the user portion of a node!user string */
264                 for (a = 0; a < strlen(node); ++a)
265                         if (node[a] == '!')
266                                 node[a] = 0;
267         }
268
269         /* strip leading and trailing spaces in all strings */
270         striplt(user);
271         striplt(node);
272         striplt(name);
273
274         /* If we processed a string that had the address in angle brackets
275          * but no name outside the brackets, we now have an empty name.  In
276          * this case, use the user portion of the address as the name.
277          */
278         if ((IsEmptyStr(name)) && (!IsEmptyStr(user))) {
279                 strcpy(name, user);
280         }
281 }
282
283
284
285 /*
286  * convert_field() is a helper function for convert_internet_message().
287  * Given start/end positions for an rfc822 field, it converts it to a Citadel
288  * field if it wants to, and unfolds it if necessary.
289  *
290  * Returns 1 if the field was converted and inserted into the Citadel message
291  * structure, implying that the source field should be removed from the
292  * message text.
293  */
294 int convert_field(struct CtdlMessage *msg, int beg, int end) {
295         char *rfc822;
296         char *key, *value;
297         int i;
298         int colonpos = (-1);
299         int processed = 0;
300         char buf[SIZ];
301         char user[1024];
302         char node[1024];
303         char name[1024];
304         char addr[1024];
305         time_t parsed_date;
306
307         rfc822 = msg->cm_fields['M'];   /* M field contains rfc822 text */
308         for (i = end; i >= beg; --i) {
309                 if (rfc822[i] == ':') colonpos = i;
310         }
311
312         if (colonpos < 0) return(0);    /* no colon? not a valid header line */
313
314         key = malloc((end - beg) + 2);
315         safestrncpy(key, &rfc822[beg], (end-beg)+1);
316         key[colonpos - beg] = 0;
317         value = &key[(colonpos - beg) + 1];
318         unfold_rfc822_field(value);
319
320         /*
321          * Here's the big rfc822-to-citadel loop.
322          */
323
324         /* Date/time is converted into a unix timestamp.  If the conversion
325          * fails, we replace it with the time the message arrived locally.
326          */
327         if (!strcasecmp(key, "Date")) {
328                 parsed_date = parsedate(value);
329                 if (parsed_date < 0L) parsed_date = time(NULL);
330                 snprintf(buf, sizeof buf, "%ld", (long)parsed_date );
331                 if (msg->cm_fields['T'] == NULL)
332                         msg->cm_fields['T'] = strdup(buf);
333                 processed = 1;
334         }
335
336         else if (!strcasecmp(key, "From")) {
337                 process_rfc822_addr(value, user, node, name);
338                 lprintf(CTDL_DEBUG, "Converted to <%s@%s> (%s)\n", user, node, name);
339                 snprintf(addr, sizeof addr, "%s@%s", user, node);
340                 if (msg->cm_fields['A'] == NULL)
341                         msg->cm_fields['A'] = strdup(name);
342                 processed = 1;
343                 if (msg->cm_fields['F'] == NULL)
344                         msg->cm_fields['F'] = strdup(addr);
345                 processed = 1;
346         }
347
348         else if (!strcasecmp(key, "Subject")) {
349                 if (msg->cm_fields['U'] == NULL)
350                         msg->cm_fields['U'] = strdup(value);
351                 processed = 1;
352         }
353
354         else if (!strcasecmp(key, "To")) {
355                 if (msg->cm_fields['R'] == NULL)
356                         msg->cm_fields['R'] = strdup(value);
357                 processed = 1;
358         }
359
360         else if (!strcasecmp(key, "CC")) {
361                 if (msg->cm_fields['Y'] == NULL)
362                         msg->cm_fields['Y'] = strdup(value);
363                 processed = 1;
364         }
365
366         else if (!strcasecmp(key, "Message-ID")) {
367                 if (msg->cm_fields['I'] != NULL) {
368                         lprintf(CTDL_WARNING, "duplicate message id\n");
369                 }
370
371                 if (msg->cm_fields['I'] == NULL) {
372                         msg->cm_fields['I'] = strdup(value);
373
374                         /* Strip angle brackets */
375                         while (haschar(msg->cm_fields['I'], '<') > 0) {
376                                 strcpy(&msg->cm_fields['I'][0],
377                                         &msg->cm_fields['I'][1]);
378                         }
379                         for (i = 0; i<strlen(msg->cm_fields['I']); ++i)
380                                 if (msg->cm_fields['I'][i] == '>')
381                                         msg->cm_fields['I'][i] = 0;
382                 }
383
384                 processed = 1;
385         }
386
387         else if (!strcasecmp(key, "Return-Path")) {
388                 if (msg->cm_fields['P'] == NULL)
389                         msg->cm_fields['P'] = strdup(value);
390                 processed = 1;
391         }
392
393         else if (!strcasecmp(key, "Envelope-To")) {
394                 if (msg->cm_fields['V'] == NULL)
395                         msg->cm_fields['V'] = strdup(value);
396                 processed = 1;
397         }
398
399         /* Clean up and move on. */
400         free(key);      /* Don't free 'value', it's actually the same buffer */
401         return(processed);
402 }
403
404
405 /*
406  * Convert an RFC822 message (headers + body) to a CtdlMessage structure.
407  * NOTE: the supplied buffer becomes part of the CtdlMessage structure, and
408  * will be deallocated when CtdlFreeMessage() is called.  Therefore, the
409  * supplied buffer should be DEREFERENCED.  It should not be freed or used
410  * again.
411  */
412 struct CtdlMessage *convert_internet_message(char *rfc822) {
413
414         struct CtdlMessage *msg;
415         int pos, beg, end, msglen;
416         int done;
417         char buf[SIZ];
418         int converted;
419
420         msg = malloc(sizeof(struct CtdlMessage));
421         if (msg == NULL) return msg;
422
423         memset(msg, 0, sizeof(struct CtdlMessage));
424         msg->cm_magic = CTDLMESSAGE_MAGIC;      /* self check */
425         msg->cm_anon_type = 0;                  /* never anonymous */
426         msg->cm_format_type = FMT_RFC822;       /* internet message */
427         msg->cm_fields['M'] = rfc822;
428
429         pos = 0;
430         done = 0;
431
432         while (!done) {
433
434                 /* Locate beginning and end of field, keeping in mind that
435                  * some fields might be multiline
436                  */
437                 beg = pos;
438                 end = (-1);
439
440                 msglen = strlen(rfc822);        
441                 while ( (end < 0) && (done == 0) ) {
442
443                         if ((rfc822[pos]=='\n')
444                            && (!isspace(rfc822[pos+1]))) {
445                                 end = pos;
446                         }
447
448                         /* done with headers? */
449                         if (   (rfc822[pos]=='\n')
450                            && ( (rfc822[pos+1]=='\n')
451                               ||(rfc822[pos+1]=='\r')) ) {
452                                 end = pos;
453                                 done = 1;
454                         }
455
456                         if (pos >= (msglen-1) ) {
457                                 end = pos;
458                                 done = 1;
459                         }
460
461                         ++pos;
462
463                 }
464
465                 /* At this point we have a field.  Are we interested in it? */
466                 converted = convert_field(msg, beg, end);
467
468                 /* Strip the field out of the RFC822 header if we used it */
469                 if (converted) {
470                         strcpy(&rfc822[beg], &rfc822[pos]);
471                         pos = beg;
472                 }
473
474                 /* If we've hit the end of the message, bail out */
475                 if (pos > strlen(rfc822)) done = 1;
476         }
477
478         /* Follow-up sanity checks... */
479
480         /* If there's no timestamp on this message, set it to now. */
481         if (msg->cm_fields['T'] == NULL) {
482                 snprintf(buf, sizeof buf, "%ld", (long)time(NULL));
483                 msg->cm_fields['T'] = strdup(buf);
484         }
485
486         return msg;
487 }
488
489
490
491 /*
492  * Look for a particular header field in an RFC822 message text.  If the
493  * requested field is found, it is unfolded (if necessary) and returned to
494  * the caller.  The field name is stripped out, leaving only its contents.
495  * The caller is responsible for freeing the returned buffer.  If the requested
496  * field is not present, or anything else goes wrong, it returns NULL.
497  */
498 char *rfc822_fetch_field(char *rfc822, char *fieldname) {
499         char *fieldbuf = NULL;
500         char *end_of_headers;
501         char *field_start;
502         char *ptr;
503         char *cont;
504         char fieldhdr[SIZ];
505
506         /* Should never happen, but sometimes we get stupid */
507         if (rfc822 == NULL) return(NULL);
508         if (fieldname == NULL) return(NULL);
509
510         snprintf(fieldhdr, sizeof fieldhdr, "%s:", fieldname);
511
512         /* Locate the end of the headers, so we don't run past that point */
513         end_of_headers = bmstrcasestr(rfc822, "\n\r\n");
514         if (end_of_headers == NULL) {
515                 end_of_headers = bmstrcasestr(rfc822, "\n\n");
516         }
517         if (end_of_headers == NULL) return (NULL);
518
519         field_start = bmstrcasestr(rfc822, fieldhdr);
520         if (field_start == NULL) return(NULL);
521         if (field_start > end_of_headers) return(NULL);
522
523         fieldbuf = malloc(SIZ);
524         strcpy(fieldbuf, "");
525
526         ptr = field_start;
527         ptr = memreadline(ptr, fieldbuf, SIZ-strlen(fieldbuf) );
528         while ( (isspace(ptr[0])) && (ptr < end_of_headers) ) {
529                 strcat(fieldbuf, " ");
530                 cont = &fieldbuf[strlen(fieldbuf)];
531                 ptr = memreadline(ptr, cont, SIZ-strlen(fieldbuf) );
532                 striplt(cont);
533         }
534
535         strcpy(fieldbuf, &fieldbuf[strlen(fieldhdr)]);
536         striplt(fieldbuf);
537
538         return(fieldbuf);
539 }
540
541
542
543 /*****************************************************************************
544  *                      DIRECTORY MANAGEMENT FUNCTIONS                       *
545  *****************************************************************************/
546
547 /*
548  * Generate the index key for an Internet e-mail address to be looked up
549  * in the database.
550  */
551 void directory_key(char *key, char *addr) {
552         int i;
553         int keylen = 0;
554
555         for (i=0; i<strlen(addr); ++i) {
556                 if (!isspace(addr[i])) {
557                         key[keylen++] = tolower(addr[i]);
558                 }
559         }
560         key[keylen++] = 0;
561
562         lprintf(CTDL_DEBUG, "Directory key is <%s>\n", key);
563 }
564
565
566
567 /* Return nonzero if the supplied address is in a domain we keep in
568  * the directory
569  */
570 int IsDirectory(char *addr, int allow_masq_domains) {
571         char domain[256];
572         int h;
573
574         extract_token(domain, addr, 1, '@', sizeof domain);
575         striplt(domain);
576
577         h = CtdlHostAlias(domain);
578
579         if ( (h == hostalias_masq) && allow_masq_domains)
580                 return(1);
581         
582         if ( (h == hostalias_localhost) || (h == hostalias_directory) ) {
583                 return(1);
584         }
585         else {
586                 return(0);
587         }
588 }
589
590
591 /*
592  * Initialize the directory database (erasing anything already there)
593  */
594 void CtdlDirectoryInit(void) {
595         cdb_trunc(CDB_DIRECTORY);
596 }
597
598
599 /*
600  * Add an Internet e-mail address to the directory for a user
601  */
602 void CtdlDirectoryAddUser(char *internet_addr, char *citadel_addr) {
603         char key[SIZ];
604
605         lprintf(CTDL_DEBUG, "Dir: %s --> %s\n",
606                 internet_addr, citadel_addr);
607         if (IsDirectory(internet_addr, 0) == 0) return;
608
609         directory_key(key, internet_addr);
610
611         cdb_store(CDB_DIRECTORY, key, strlen(key),
612                 citadel_addr, strlen(citadel_addr)+1 );
613 }
614
615
616 /*
617  * Delete an Internet e-mail address from the directory.
618  *
619  * (NOTE: we don't actually use or need the citadel_addr variable; it's merely
620  * here because the callback API expects to be able to send it.)
621  */
622 void CtdlDirectoryDelUser(char *internet_addr, char *citadel_addr) {
623         char key[SIZ];
624
625         directory_key(key, internet_addr);
626         cdb_delete(CDB_DIRECTORY, key, strlen(key) );
627 }
628
629
630 /*
631  * Look up an Internet e-mail address in the directory.
632  * On success: returns 0, and Citadel address stored in 'target'
633  * On failure: returns nonzero
634  */
635 int CtdlDirectoryLookup(char *target, char *internet_addr, size_t targbuflen) {
636         struct cdbdata *cdbrec;
637         char key[SIZ];
638
639         /* Dump it in there unchanged, just for kicks */
640         safestrncpy(target, internet_addr, targbuflen);
641
642         /* Only do lookups for addresses with hostnames in them */
643         if (num_tokens(internet_addr, '@') != 2) return(-1);
644
645         /* Only do lookups for domains in the directory */
646         if (IsDirectory(internet_addr, 0) == 0) return(-1);
647
648         directory_key(key, internet_addr);
649         cdbrec = cdb_fetch(CDB_DIRECTORY, key, strlen(key) );
650         if (cdbrec != NULL) {
651                 safestrncpy(target, cdbrec->ptr, targbuflen);
652                 cdb_free(cdbrec);
653                 return(0);
654         }
655
656         return(-1);
657 }
658
659
660 /*
661  * Harvest any email addresses that someone might want to have in their
662  * "collected addresses" book.
663  */
664 char *harvest_collected_addresses(struct CtdlMessage *msg) {
665         char *coll = NULL;
666         char addr[256];
667         char user[256], node[256], name[256];
668         int is_harvestable;
669         int i, j, h;
670         int field = 0;
671
672         if (msg == NULL) return(NULL);
673
674         is_harvestable = 1;
675         strcpy(addr, "");       
676         if (msg->cm_fields['A'] != NULL) {
677                 strcat(addr, msg->cm_fields['A']);
678         }
679         if (msg->cm_fields['F'] != NULL) {
680                 strcat(addr, " <");
681                 strcat(addr, msg->cm_fields['F']);
682                 strcat(addr, ">");
683                 if (IsDirectory(msg->cm_fields['F'], 0)) {
684                         is_harvestable = 0;
685                 }
686         }
687
688         if (is_harvestable) {
689                 coll = strdup(addr);
690         }
691         else {
692                 coll = strdup("");
693         }
694
695         if (coll == NULL) return(NULL);
696
697         /* Scan both the R (To) and Y (CC) fields */
698         for (i = 0; i < 2; ++i) {
699                 if (i == 0) field = 'R' ;
700                 if (i == 1) field = 'Y' ;
701
702                 if (msg->cm_fields[field] != NULL) {
703                         for (j=0; j<num_tokens(msg->cm_fields[field], ','); ++j) {
704                                 extract_token(addr, msg->cm_fields[field], j, ',', sizeof addr);
705                                 process_rfc822_addr(addr, user, node, name);
706                                 h = CtdlHostAlias(node);
707                                 if ( (h != hostalias_localhost) && (h != hostalias_directory) ) {
708                                         coll = realloc(coll, strlen(coll) + strlen(addr) + 4);
709                                         if (coll == NULL) return(NULL);
710                                         if (!IsEmptyStr(coll)) {
711                                                 strcat(coll, ",");
712                                         }
713                                         striplt(addr);
714                                         strcat(coll, addr);
715                                 }
716                         }
717                 }
718         }
719
720         if (IsEmptyStr(coll)) {
721                 free(coll);
722                 return(NULL);
723         }
724         return(coll);
725 }