* Renamed "dynloader" to "serv_extensions" globally. We don't want people
[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 (!strcasecmp(fqdn, config.c_fqdn)) return(hostalias_localhost);
77         if (!strcasecmp(fqdn, config.c_nodename)) return(hostalias_localhost);
78         if (inetcfg == NULL) return(hostalias_nomatch);
79
80         config_lines = num_tokens(inetcfg, '\n');
81         for (i=0; i<config_lines; ++i) {
82                 extract_token(buf, inetcfg, i, '\n');
83                 extract_token(host, buf, 0, '|');
84                 extract_token(type, buf, 1, '|');
85
86                 if ( (!strcasecmp(type, "localhost"))
87                    && (!strcasecmp(fqdn, host)))
88                         return(hostalias_localhost);
89
90                 if ( (!strcasecmp(type, "gatewaydomain"))
91                    && (!strcasecmp(&fqdn[strlen(fqdn)-strlen(host)], host)))
92                         return(hostalias_gatewaydomain);
93
94                 if ( (!strcasecmp(type, "directory"))
95                    && (!strcasecmp(&fqdn[strlen(fqdn)-strlen(host)], host)))
96                         return(hostalias_directory);
97
98         }
99
100         return(hostalias_nomatch);
101 }
102
103
104
105
106
107
108
109 /*
110  * Return 0 if a given string fuzzy-matches a Citadel user account
111  *
112  * FIXME ... this needs to be updated to handle aliases.
113  */
114 int fuzzy_match(struct usersupp *us, char *matchstring) {
115         int a;
116
117         if ( (!strncasecmp(matchstring, "cit", 3)) 
118            && (atol(&matchstring[3]) == us->usernum)) {
119                 return 0;
120         }
121
122
123         for (a=0; a<strlen(us->fullname); ++a) {
124                 if (!strncasecmp(&us->fullname[a],
125                    matchstring, strlen(matchstring))) {
126                         return 0;
127                 }
128         }
129         return -1;
130 }
131
132
133 /*
134  * Unfold a multi-line field into a single line, removing multi-whitespaces
135  */
136 void unfold_rfc822_field(char *field) {
137         int i;
138         int quote = 0;
139
140         striplt(field);         /* remove leading/trailing whitespace */
141
142         /* convert non-space whitespace to spaces, and remove double blanks */
143         for (i=0; i<strlen(field); ++i) {
144                 if (field[i]=='\"') quote = 1 - quote;
145                 if (!quote) {
146                         if (isspace(field[i])) field[i] = ' ';
147                         while (isspace(field[i]) && isspace(field[i+1])) {
148                                 strcpy(&field[i+1], &field[i+2]);
149                         }
150                 }
151         }
152 }
153
154
155
156 /*
157  * Split an RFC822-style address into userid, host, and full name
158  *
159  */
160 void process_rfc822_addr(const char *rfc822, char *user, char *node, char *name)
161 {
162         int a;
163
164         strcpy(user, "");
165         strcpy(node, config.c_fqdn);
166         strcpy(name, "");
167
168         /* extract full name - first, it's From minus <userid> */
169         strcpy(name, rfc822);
170         stripout(name, '<', '>');
171
172         /* strip anything to the left of a bang */
173         while ((strlen(name) > 0) && (haschar(name, '!') > 0))
174                 strcpy(name, &name[1]);
175
176         /* and anything to the right of a @ or % */
177         for (a = 0; a < strlen(name); ++a) {
178                 if (name[a] == '@')
179                         name[a] = 0;
180                 if (name[a] == '%')
181                         name[a] = 0;
182         }
183
184         /* but if there are parentheses, that changes the rules... */
185         if ((haschar(rfc822, '(') == 1) && (haschar(rfc822, ')') == 1)) {
186                 strcpy(name, rfc822);
187                 stripallbut(name, '(', ')');
188         }
189
190         /* but if there are a set of quotes, that supersedes everything */
191         if (haschar(rfc822, 34) == 2) {
192                 strcpy(name, rfc822);
193                 while ((strlen(name) > 0) && (name[0] != 34)) {
194                         strcpy(&name[0], &name[1]);
195                 }
196                 strcpy(&name[0], &name[1]);
197                 for (a = 0; a < strlen(name); ++a)
198                         if (name[a] == 34)
199                                 name[a] = 0;
200         }
201         /* extract user id */
202         strcpy(user, rfc822);
203
204         /* first get rid of anything in parens */
205         stripout(user, '(', ')');
206
207         /* if there's a set of angle brackets, strip it down to that */
208         if ((haschar(user, '<') == 1) && (haschar(user, '>') == 1)) {
209                 stripallbut(user, '<', '>');
210         }
211
212         /* strip anything to the left of a bang */
213         while ((strlen(user) > 0) && (haschar(user, '!') > 0))
214                 strcpy(user, &user[1]);
215
216         /* and anything to the right of a @ or % */
217         for (a = 0; a < strlen(user); ++a) {
218                 if (user[a] == '@')
219                         user[a] = 0;
220                 if (user[a] == '%')
221                         user[a] = 0;
222         }
223
224
225         /* extract node name */
226         strcpy(node, rfc822);
227
228         /* first get rid of anything in parens */
229         stripout(node, '(', ')');
230
231         /* if there's a set of angle brackets, strip it down to that */
232         if ((haschar(node, '<') == 1) && (haschar(node, '>') == 1)) {
233                 stripallbut(node, '<', '>');
234         }
235
236         /* If no node specified, tack ours on instead */
237         if (
238                 (haschar(node, '@')==0)
239                 && (haschar(node, '%')==0)
240                 && (haschar(node, '!')==0)
241         ) {
242                 strcpy(node, config.c_nodename);
243         }
244
245         else {
246
247                 /* strip anything to the left of a @ */
248                 while ((strlen(node) > 0) && (haschar(node, '@') > 0))
249                         strcpy(node, &node[1]);
250         
251                 /* strip anything to the left of a % */
252                 while ((strlen(node) > 0) && (haschar(node, '%') > 0))
253                         strcpy(node, &node[1]);
254         
255                 /* reduce multiple system bang paths to node!user */
256                 while ((strlen(node) > 0) && (haschar(node, '!') > 1))
257                         strcpy(node, &node[1]);
258         
259                 /* now get rid of the user portion of a node!user string */
260                 for (a = 0; a < strlen(node); ++a)
261                         if (node[a] == '!')
262                                 node[a] = 0;
263         }
264
265         /* strip leading and trailing spaces in all strings */
266         striplt(user);
267         striplt(node);
268         striplt(name);
269 }
270
271
272
273 /*
274  * convert_field() is a helper function for convert_internet_message().
275  * Given start/end positions for an rfc822 field, it converts it to a Citadel
276  * field if it wants to, and unfolds it if necessary.
277  *
278  * Returns 1 if the field was converted and inserted into the Citadel message
279  * structure, implying that the source field should be removed from the
280  * message text.
281  */
282 int convert_field(struct CtdlMessage *msg, int beg, int end) {
283         char *rfc822;
284         char *key, *value;
285         int i;
286         int colonpos = (-1);
287         int processed = 0;
288         char buf[SIZ];
289         char user[1024];
290         char node[1024];
291         char name[1024];
292         char addr[1024];
293         time_t parsed_date;
294
295         rfc822 = msg->cm_fields['M'];   /* M field contains rfc822 text */
296         for (i = end; i >= beg; --i) {
297                 if (rfc822[i] == ':') colonpos = i;
298         }
299
300         if (colonpos < 0) return(0);    /* no colon? not a valid header line */
301
302         key = mallok((end - beg) + 2);
303         safestrncpy(key, &rfc822[beg], (end-beg)+1);
304         key[colonpos - beg] = 0;
305         value = &key[(colonpos - beg) + 1];
306         unfold_rfc822_field(value);
307
308         /*
309          * Here's the big rfc822-to-citadel loop.
310          */
311
312         /* Date/time is converted into a unix timestamp.  If the conversion
313          * fails, we replace it with the time the message arrived locally.
314          */
315         if (!strcasecmp(key, "Date")) {
316                 parsed_date = parsedate(value);
317                 if (parsed_date < 0L) parsed_date = time(NULL);
318                 snprintf(buf, sizeof buf, "%ld", (long)parsed_date );
319                 if (msg->cm_fields['T'] == NULL)
320                         msg->cm_fields['T'] = strdoop(buf);
321                 processed = 1;
322         }
323
324         else if (!strcasecmp(key, "From")) {
325                 process_rfc822_addr(value, user, node, name);
326                 lprintf(9, "Converted to <%s@%s> (%s)\n", user, node, name);
327                 snprintf(addr, sizeof addr, "%s@%s", user, node);
328                 if (msg->cm_fields['A'] == NULL)
329                         msg->cm_fields['A'] = strdoop(name);
330                 processed = 1;
331                 if (msg->cm_fields['F'] == NULL)
332                         msg->cm_fields['F'] = strdoop(addr);
333                 processed = 1;
334         }
335
336         else if (!strcasecmp(key, "Subject")) {
337                 if (msg->cm_fields['U'] == NULL)
338                         msg->cm_fields['U'] = strdoop(value);
339                 processed = 1;
340         }
341
342         else if (!strcasecmp(key, "Message-ID")) {
343                 if (msg->cm_fields['I'] != NULL) {
344                         lprintf(5, "duplicate message id\n");
345                 }
346
347                 if (msg->cm_fields['I'] == NULL) {
348                         msg->cm_fields['I'] = strdoop(value);
349
350                         /* Strip angle brackets */
351                         while (haschar(msg->cm_fields['I'], '<') > 0) {
352                                 strcpy(&msg->cm_fields['I'][0],
353                                         &msg->cm_fields['I'][1]);
354                         }
355                         for (i = 0; i<strlen(msg->cm_fields['I']); ++i)
356                                 if (msg->cm_fields['I'][i] == '>')
357                                         msg->cm_fields['I'][i] = 0;
358                 }
359
360                 processed = 1;
361         }
362
363         /* Clean up and move on. */
364         phree(key);     /* Don't free 'value', it's actually the same buffer */
365         return(processed);
366 }
367
368
369 /*
370  * Convert an RFC822 message (headers + body) to a CtdlMessage structure.
371  * NOTE: the supplied buffer becomes part of the CtdlMessage structure, and
372  * will be deallocated when CtdlFreeMessage() is called.  Therefore, the
373  * supplied buffer should be DEREFERENCED.  It should not be freed or used
374  * again.
375  */
376 struct CtdlMessage *convert_internet_message(char *rfc822) {
377
378         struct CtdlMessage *msg;
379         int pos, beg, end, msglen;
380         int done;
381         char buf[SIZ];
382         int converted;
383
384         msg = mallok(sizeof(struct CtdlMessage));
385         if (msg == NULL) return msg;
386
387         memset(msg, 0, sizeof(struct CtdlMessage));
388         msg->cm_magic = CTDLMESSAGE_MAGIC;      /* self check */
389         msg->cm_anon_type = 0;                  /* never anonymous */
390         msg->cm_format_type = FMT_RFC822;       /* internet message */
391         msg->cm_fields['M'] = rfc822;
392
393         lprintf(9, "Unconverted RFC822 message length = %ld\n", (long)strlen(rfc822));
394         pos = 0;
395         done = 0;
396
397         while (!done) {
398
399                 /* Locate beginning and end of field, keeping in mind that
400                  * some fields might be multiline
401                  */
402                 beg = pos;
403                 end = (-1);
404
405                 msglen = strlen(rfc822);        
406                 while ( (end < 0) && (done == 0) ) {
407
408                         if ((rfc822[pos]=='\n')
409                            && (!isspace(rfc822[pos+1]))) {
410                                 end = pos;
411                         }
412
413                         /* done with headers? (commented out; see below)
414                         if (   ((rfc822[pos]=='\n')
415                               ||(rfc822[pos]=='\r') )
416                            && ( (rfc822[pos+1]=='\n')
417                               ||(rfc822[pos+1]=='\r')) ) {
418                                 end = pos;
419                                 done = 1;
420                         }
421                         */
422
423                         /* done with headers? (try this way instead) */
424                         if (   (rfc822[pos]=='\n')
425                            && ( (rfc822[pos+1]=='\n')
426                               ||(rfc822[pos+1]=='\r')) ) {
427                                 end = pos;
428                                 done = 1;
429                         }
430
431                         if (pos >= (msglen-1) ) {
432                                 end = pos;
433                                 done = 1;
434                         }
435
436                         ++pos;
437
438                 }
439
440                 /* At this point we have a field.  Are we interested in it? */
441                 converted = convert_field(msg, beg, end);
442
443                 /* Strip the field out of the RFC822 header if we used it */
444                 if (converted) {
445                         strcpy(&rfc822[beg], &rfc822[pos]);
446                         pos = beg;
447                 }
448
449                 /* If we've hit the end of the message, bail out */
450                 if (pos > strlen(rfc822)) done = 1;
451         }
452
453         /* Follow-up sanity checks... */
454
455         /* If there's no timestamp on this message, set it to now. */
456         if (msg->cm_fields['T'] == NULL) {
457                 snprintf(buf, sizeof buf, "%ld", (long)time(NULL));
458                 msg->cm_fields['T'] = strdoop(buf);
459         }
460
461         lprintf(9, "RFC822 length remaining after conversion = %ld\n",
462                 (long)strlen(rfc822));
463         return msg;
464 }
465
466
467
468 /*
469  * Look for a particular header field in an RFC822 message text.  If the
470  * requested field is found, it is unfolded (if necessary) and returned to
471  * the caller.  The field name is stripped out, leaving only its contents.
472  * The caller is responsible for freeing the returned buffer.  If the requested
473  * field is not present, or anything else goes wrong, it returns NULL.
474  */
475 char *rfc822_fetch_field(char *rfc822, char *fieldname) {
476         int pos = 0;
477         int beg, end;
478         int done = 0;
479         int colonpos, i;
480         char *fieldbuf = NULL;
481
482         /* Should never happen, but sometimes we get stupid */
483         if (rfc822 == NULL) return(NULL);
484         if (fieldname == NULL) return(NULL);
485
486         while (!done) {
487
488                 /* Locate beginning and end of field, keeping in mind that
489                  * some fields might be multiline
490                  */
491                 beg = pos;
492                 end = (-1);
493                 for (pos=beg; ((pos<=strlen(rfc822))&&(end<0)); ++pos) {
494                         if ((rfc822[pos]=='\n')
495                            && (!isspace(rfc822[pos+1]))) {
496                                 end = pos;
497                         }
498                         if ( (rfc822[pos]=='\n')        /* done w. headers? */
499                            && ( (rfc822[pos+1]=='\n')
500                               ||(rfc822[pos+1]=='\r'))) {
501                                 end = pos;
502                                 done = 1;
503                         }
504
505                 }
506
507                 /* At this point we have a field.  Is it The One? */
508                 if (end > beg) {
509                         fieldbuf = mallok((end-beg)+3);
510                         if (fieldbuf == NULL) return(NULL);
511                         safestrncpy(fieldbuf, &rfc822[beg], (end-beg)+1);
512                         unfold_rfc822_field(fieldbuf);
513                         colonpos = (-1);
514                         for (i = strlen(fieldbuf); i >= 0; --i) {
515                                 if (fieldbuf[i] == ':') colonpos = i;
516                         }
517                         if (colonpos > 0) {
518                                 fieldbuf[colonpos] = 0;
519                                 if (!strcasecmp(fieldbuf, fieldname)) {
520                                         strcpy(fieldbuf, &fieldbuf[colonpos+1]);
521                                         striplt(fieldbuf);
522                                         return(fieldbuf);
523                                 }
524                         }
525                         phree(fieldbuf);
526                 }
527
528                 /* If we've hit the end of the message, bail out */
529                 if (pos > strlen(rfc822)) done = 1;
530         }
531         return(NULL);
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(9, "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(9, "IsDirectory(%s)\n", domain);
572
573         if ( (h == hostalias_localhost) || (h == hostalias_directory) ) {
574                 lprintf(9, " ...yes\n");
575                 return(1);
576         }
577         else {
578                 lprintf(9, " ...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(9, "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         if (IsDirectory(internet_addr) == 0) return(-1);
633
634         directory_key(key, internet_addr);
635         cdbrec = cdb_fetch(CDB_DIRECTORY, key, strlen(key) );
636         if (cdbrec != NULL) {
637                 safestrncpy(target, cdbrec->ptr, SIZ);
638                 cdb_free(cdbrec);
639                 return(0);
640         }
641
642         return(-1);
643 }