xref: /openbsd-src/usr.sbin/smtpd/forward.c (revision 50b7afb2c2c0993b0894d4e34bf857cb13ed9c80)
1 /*	$OpenBSD: forward.c,v 1.35 2013/05/24 17:03:14 eric Exp $	*/
2 
3 /*
4  * Copyright (c) 2008 Gilles Chehade <gilles@poolp.org>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 #include <sys/types.h>
20 #include <sys/queue.h>
21 #include <sys/tree.h>
22 #include <sys/socket.h>
23 #include <sys/stat.h>
24 
25 #include <ctype.h>
26 #include <event.h>
27 #include <imsg.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <util.h>
32 #include <unistd.h>
33 
34 #include "smtpd.h"
35 #include "log.h"
36 
37 #define	MAX_FORWARD_SIZE	(4 * 1024)
38 #define	MAX_EXPAND_NODES	(100)
39 
40 int
41 forwards_get(int fd, struct expand *expand)
42 {
43 	FILE	       *fp = NULL;
44 	char	       *line = NULL;
45 	size_t		len;
46 	size_t		lineno;
47 	size_t		save;
48 	int		ret;
49 	struct stat	sb;
50 
51 	ret = -1;
52 	if (fstat(fd, &sb) == -1)
53 		goto end;
54 
55 	/* if it's empty just pretend that no expansion took place */
56 	if (sb.st_size == 0) {
57 		log_info("info: forward file is empty");
58 		ret = 0;
59 		goto end;
60 	}
61 
62 	/* over MAX_FORWARD_SIZE, temporarily fail */
63 	if (sb.st_size >= MAX_FORWARD_SIZE) {
64 		log_info("info: forward file exceeds max size");
65 		goto end;
66 	}
67 
68 	if ((fp = fdopen(fd, "r")) == NULL) {
69 		log_warn("warn: fdopen failure in forwards_get()");
70 		goto end;
71 	}
72 
73 	lineno = 0;
74 	save = expand->nb_nodes;
75 	while ((line = fparseln(fp, &len, &lineno, NULL, 0)) != NULL) {
76 		if (! expand_line(expand, line, 0)) {
77 			log_info("info: parse error in forward file");
78 			goto end;
79 		}
80 		if (expand->nb_nodes > MAX_EXPAND_NODES) {
81 			log_info("info: forward file expanded too many nodes");
82 			goto end;
83 		}
84 		free(line);
85 	}
86 
87 	ret = expand->nb_nodes > save ? 1 : 0;
88 
89 end:
90 	if (line)
91 		free(line);
92 	if (fp)
93 		fclose(fp);
94 	else
95 		close(fd);
96 	return ret;
97 }
98