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