Home | History | Annotate | Line # | Download | only in ftp-proxy
ftp-proxy.c revision 1.3
      1 /*	$NetBSD: ftp-proxy.c,v 1.3 2009/07/13 19:05:39 roy Exp $ */
      2 /*	$OpenBSD: ftp-proxy.c,v 1.15 2007/08/15 15:18:02 camield Exp $ */
      3 
      4 /*
      5  * Copyright (c) 2004, 2005 Camiel Dobbelaar, <cd (at) sentia.nl>
      6  *
      7  * Permission to use, copy, modify, and distribute this software for any
      8  * purpose with or without fee is hereby granted, provided that the above
      9  * copyright notice and this permission notice appear in all copies.
     10  *
     11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
     12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
     13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
     14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
     15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
     16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
     17  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
     18  */
     19 
     20 #include <sys/queue.h>
     21 #include <sys/types.h>
     22 #include <sys/time.h>
     23 #include <sys/resource.h>
     24 #include <sys/socket.h>
     25 
     26 #include <net/if.h>
     27 #include <net/pfvar.h>
     28 #include <netinet/in.h>
     29 #include <arpa/inet.h>
     30 
     31 #include <err.h>
     32 #include <errno.h>
     33 #include <event.h>
     34 #include <fcntl.h>
     35 #include <netdb.h>
     36 #include <pwd.h>
     37 #include <signal.h>
     38 #include <stdarg.h>
     39 #include <stdio.h>
     40 #include <stdlib.h>
     41 #include <string.h>
     42 #include <syslog.h>
     43 #include <unistd.h>
     44 #include <vis.h>
     45 
     46 #include "filter.h"
     47 
     48 #if defined(__NetBSD__) && defined(WITH_IPF)
     49 #include "ipf.h"
     50 #endif /* __NetBSD__ && WITH_IPF */
     51 
     52 #define CONNECT_TIMEOUT	30
     53 #define MIN_PORT	1024
     54 #define MAX_LINE	500
     55 #define MAX_LOGLINE	300
     56 #define NTOP_BUFS	3
     57 #define TCP_BACKLOG	10
     58 
     59 #define CHROOT_DIR	"/var/chroot/ftp-proxy"
     60 #define NOPRIV_USER	"_proxy"
     61 
     62 /* pfctl standard NAT range. */
     63 #define PF_NAT_PROXY_PORT_LOW	50001
     64 #define PF_NAT_PROXY_PORT_HIGH	65535
     65 
     66 #ifndef sstosa
     67 #define	sstosa(ss)	((struct sockaddr *)(ss))
     68 #endif /* sstosa */
     69 
     70 #ifndef IPPORT_HIFIRSTAUTO
     71 #define IPPORT_HIFIRSTAUTO	IPPORT_ANONMIN
     72 #endif /* IPPORT_HIFIRSTAUTO */
     73 
     74 #ifndef IPPORT_HILASTAUTO
     75 #define IPPORT_HILASTAUTO	IPPORT_ANONMAX
     76 #endif /* IPPORT_HILASTAUTO */
     77 
     78 enum { CMD_NONE = 0, CMD_PORT, CMD_EPRT, CMD_PASV, CMD_EPSV };
     79 
     80 struct session {
     81 	u_int32_t		 id;
     82 	struct sockaddr_storage  client_ss;
     83 	struct sockaddr_storage  proxy_ss;
     84 	struct sockaddr_storage  server_ss;
     85 	struct sockaddr_storage  orig_server_ss;
     86 	struct bufferevent	*client_bufev;
     87 	struct bufferevent	*server_bufev;
     88 	int			 client_fd;
     89 	int			 server_fd;
     90 	char			 cbuf[MAX_LINE];
     91 	size_t			 cbuf_valid;
     92 	char			 sbuf[MAX_LINE];
     93 	size_t			 sbuf_valid;
     94 	int			 cmd;
     95 	u_int16_t		 port;
     96 	u_int16_t		 proxy_port;
     97 	LIST_ENTRY(session)	 entry;
     98 };
     99 
    100 LIST_HEAD(, session) sessions = LIST_HEAD_INITIALIZER(sessions);
    101 
    102 void	client_error(struct bufferevent *, short, void *);
    103 int	client_parse(struct session *s);
    104 int	client_parse_anon(struct session *s);
    105 int	client_parse_cmd(struct session *s);
    106 void	client_read(struct bufferevent *, void *);
    107 int	drop_privs(void);
    108 void	end_session(struct session *);
    109 int	exit_daemon(void);
    110 int	get_line(char *, size_t *);
    111 void	handle_connection(const int, short, void *);
    112 void	handle_signal(int, short, void *);
    113 struct session * init_session(void);
    114 void	logmsg(int, const char *, ...);
    115 u_int16_t parse_port(int);
    116 u_int16_t pick_proxy_port(void);
    117 void	proxy_reply(int, struct sockaddr *, u_int16_t);
    118 void	server_error(struct bufferevent *, short, void *);
    119 int	server_parse(struct session *s);
    120 int	allow_data_connection(struct session *s);
    121 void	server_read(struct bufferevent *, void *);
    122 const char *sock_ntop(struct sockaddr *);
    123 void	usage(void);
    124 
    125 char linebuf[MAX_LINE + 1];
    126 size_t linelen;
    127 
    128 char ntop_buf[NTOP_BUFS][INET6_ADDRSTRLEN];
    129 
    130 struct sockaddr_storage fixed_server_ss, fixed_proxy_ss;
    131 char *fixed_server, *fixed_server_port, *fixed_proxy, *listen_ip, *listen_port,
    132     *qname, *tagname;
    133 int anonymous_only, daemonize, id_count, ipv6_mode, loglevel, max_sessions,
    134     rfc_mode, session_count, timeout, verbose;
    135 extern char *__progname;
    136 
    137 #if defined(__NetBSD__) && defined(WITH_IPF)
    138 int ipf_enabled = 0;
    139 #endif /* __NetBSD__ && WITH_IPF */
    140 
    141 void
    142 client_error(struct bufferevent *bufev, short what, void *arg)
    143 {
    144 	struct session *s = arg;
    145 
    146 	if (what & EVBUFFER_EOF)
    147 		logmsg(LOG_INFO, "#%d client close", s->id);
    148 	else if (what == (EVBUFFER_ERROR | EVBUFFER_READ))
    149 		logmsg(LOG_ERR, "#%d client reset connection", s->id);
    150 	else if (what & EVBUFFER_TIMEOUT)
    151 		logmsg(LOG_ERR, "#%d client timeout", s->id);
    152 	else if (what & EVBUFFER_WRITE)
    153 		logmsg(LOG_ERR, "#%d client write error: %d", s->id, what);
    154 	else
    155 		logmsg(LOG_ERR, "#%d abnormal client error: %d", s->id, what);
    156 
    157 	end_session(s);
    158 }
    159 
    160 int
    161 client_parse(struct session *s)
    162 {
    163 	/* Reset any previous command. */
    164 	s->cmd = CMD_NONE;
    165 	s->port = 0;
    166 
    167 	/* Commands we are looking for are at least 4 chars long. */
    168 	if (linelen < 4)
    169 		return (1);
    170 
    171 	if (linebuf[0] == 'P' || linebuf[0] == 'p' ||
    172 	    linebuf[0] == 'E' || linebuf[0] == 'e') {
    173 		if (!client_parse_cmd(s))
    174 			return (0);
    175 
    176 		/*
    177 		 * Allow active mode connections immediately, instead of
    178 		 * waiting for a positive reply from the server.  Some
    179 		 * rare servers/proxies try to probe or setup the data
    180 		 * connection before an actual transfer request.
    181 		 */
    182 		if (s->cmd == CMD_PORT || s->cmd == CMD_EPRT)
    183 			return (allow_data_connection(s));
    184 	}
    185 
    186 	if (anonymous_only && (linebuf[0] == 'U' || linebuf[0] == 'u'))
    187 		return (client_parse_anon(s));
    188 
    189 	return (1);
    190 }
    191 
    192 int
    193 client_parse_anon(struct session *s)
    194 {
    195 	if (strcasecmp("USER ftp\r\n", linebuf) != 0 &&
    196 	    strcasecmp("USER anonymous\r\n", linebuf) != 0) {
    197 		snprintf(linebuf, sizeof linebuf,
    198 		    "500 Only anonymous FTP allowed\r\n");
    199 		logmsg(LOG_DEBUG, "#%d proxy: %s", s->id, linebuf);
    200 
    201 		/* Talk back to the client ourself. */
    202 		linelen = strlen(linebuf);
    203 		bufferevent_write(s->client_bufev, linebuf, linelen);
    204 
    205 		/* Clear buffer so it's not sent to the server. */
    206 		linebuf[0] = '\0';
    207 		linelen = 0;
    208 	}
    209 
    210 	return (1);
    211 }
    212 
    213 int
    214 client_parse_cmd(struct session *s)
    215 {
    216 	if (strncasecmp("PASV", linebuf, 4) == 0)
    217 		s->cmd = CMD_PASV;
    218 	else if (strncasecmp("PORT ", linebuf, 5) == 0)
    219 		s->cmd = CMD_PORT;
    220 	else if (strncasecmp("EPSV", linebuf, 4) == 0)
    221 		s->cmd = CMD_EPSV;
    222 	else if (strncasecmp("EPRT ", linebuf, 5) == 0)
    223 		s->cmd = CMD_EPRT;
    224 	else
    225 		return (1);
    226 
    227 	if (ipv6_mode && (s->cmd == CMD_PASV || s->cmd == CMD_PORT)) {
    228 		logmsg(LOG_CRIT, "PASV and PORT not allowed with IPv6");
    229 		return (0);
    230 	}
    231 
    232 	if (s->cmd == CMD_PORT || s->cmd == CMD_EPRT) {
    233 		s->port = parse_port(s->cmd);
    234 		if (s->port < MIN_PORT) {
    235 			logmsg(LOG_CRIT, "#%d bad port in '%s'", s->id,
    236 			    linebuf);
    237 			return (0);
    238 		}
    239 		s->proxy_port = pick_proxy_port();
    240 		proxy_reply(s->cmd, sstosa(&s->proxy_ss), s->proxy_port);
    241 		logmsg(LOG_DEBUG, "#%d proxy: %s", s->id, linebuf);
    242 	}
    243 
    244 	return (1);
    245 }
    246 
    247 void
    248 client_read(struct bufferevent *bufev, void *arg)
    249 {
    250 	struct session	*s = arg;
    251 	size_t		 buf_avail, nread;
    252 	int		 n;
    253 
    254 	do {
    255 		buf_avail = sizeof s->cbuf - s->cbuf_valid;
    256 		nread = bufferevent_read(bufev, s->cbuf + s->cbuf_valid,
    257 		    buf_avail);
    258 		s->cbuf_valid += nread;
    259 
    260 		while ((n = get_line(s->cbuf, &s->cbuf_valid)) > 0) {
    261 			logmsg(LOG_DEBUG, "#%d client: %s", s->id, linebuf);
    262 			if (!client_parse(s)) {
    263 				end_session(s);
    264 				return;
    265 			}
    266 			bufferevent_write(s->server_bufev, linebuf, linelen);
    267 		}
    268 
    269 		if (n == -1) {
    270 			logmsg(LOG_ERR, "#%d client command too long or not"
    271 			    " clean", s->id);
    272 			end_session(s);
    273 			return;
    274 		}
    275 	} while (nread == buf_avail);
    276 }
    277 
    278 int
    279 drop_privs(void)
    280 {
    281 	struct passwd *pw;
    282 
    283 	pw = getpwnam(NOPRIV_USER);
    284 	if (pw == NULL)
    285 		return (0);
    286 
    287 	tzset();
    288 #ifdef __NetBSD__
    289 	if (chroot(CHROOT_DIR) != 0 || chdir("/") != 0 ||
    290 	    setgroups(1, &pw->pw_gid) != 0 ||
    291 	    setgid(pw->pw_gid) != 0 ||
    292 	    setuid(pw->pw_uid) != 0)
    293 		return (0);
    294 #else
    295 	if (chroot(CHROOT_DIR) != 0 || chdir("/") != 0 ||
    296 	    setgroups(1, &pw->pw_gid) != 0 ||
    297 	    setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) != 0 ||
    298 	    setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) != 0)
    299 		return (0);
    300 #endif /* !__NetBSD__ */
    301 
    302 	return (1);
    303 }
    304 
    305 void
    306 end_session(struct session *s)
    307 {
    308 	int error;
    309 
    310 	logmsg(LOG_INFO, "#%d ending session", s->id);
    311 
    312 	if (s->client_fd != -1)
    313 		close(s->client_fd);
    314 	if (s->server_fd != -1)
    315 		close(s->server_fd);
    316 
    317 	if (s->client_bufev)
    318 		bufferevent_free(s->client_bufev);
    319 	if (s->server_bufev)
    320 		bufferevent_free(s->server_bufev);
    321 
    322 	/* Remove rulesets by commiting empty ones. */
    323 	error = 0;
    324 	if (prepare_commit(s->id) == -1)
    325 		error = errno;
    326 	else if (do_commit() == -1) {
    327 		error = errno;
    328 		do_rollback();
    329 	}
    330 	if (error)
    331 		logmsg(LOG_ERR, "#%d pf rule removal failed: %s", s->id,
    332 		    strerror(error));
    333 
    334 	LIST_REMOVE(s, entry);
    335 	free(s);
    336 	session_count--;
    337 }
    338 
    339 int
    340 exit_daemon(void)
    341 {
    342 	struct session *s, *next;
    343 
    344 	for (s = LIST_FIRST(&sessions); s != LIST_END(&sessions); s = next) {
    345 		next = LIST_NEXT(s, entry);
    346 		end_session(s);
    347 	}
    348 
    349 	if (daemonize)
    350 		closelog();
    351 
    352 	exit(0);
    353 
    354 	/* NOTREACHED */
    355 	return (-1);
    356 }
    357 
    358 int
    359 get_line(char *buf, size_t *valid)
    360 {
    361 	size_t i;
    362 
    363 	if (*valid > MAX_LINE)
    364 		return (-1);
    365 
    366 	/* Copy to linebuf while searching for a newline. */
    367 	for (i = 0; i < *valid; i++) {
    368 		linebuf[i] = buf[i];
    369 		if (buf[i] == '\0')
    370 			return (-1);
    371 		if (buf[i] == '\n')
    372 			break;
    373 	}
    374 
    375 	if (i == *valid) {
    376 		/* No newline found. */
    377 		linebuf[0] = '\0';
    378 		linelen = 0;
    379 		if (i < MAX_LINE)
    380 			return (0);
    381 		return (-1);
    382 	}
    383 
    384 	linelen = i + 1;
    385 	linebuf[linelen] = '\0';
    386 	*valid -= linelen;
    387 
    388 	/* Move leftovers to the start. */
    389 	if (*valid != 0)
    390 		bcopy(buf + linelen, buf, *valid);
    391 
    392 	return ((int)linelen);
    393 }
    394 
    395 void
    396 handle_connection(const int listen_fd, short event, void *ev)
    397 {
    398 	struct sockaddr_storage tmp_ss;
    399 	struct sockaddr *client_sa, *server_sa, *fixed_server_sa;
    400 	struct sockaddr *client_to_proxy_sa, *proxy_to_server_sa;
    401 	struct session *s;
    402 	socklen_t len;
    403 	int client_fd, fc, on;
    404 
    405 	/*
    406 	 * We _must_ accept the connection, otherwise libevent will keep
    407 	 * coming back, and we will chew up all CPU.
    408 	 */
    409 	client_sa = sstosa(&tmp_ss);
    410 	len = sizeof(struct sockaddr_storage);
    411 	if ((client_fd = accept(listen_fd, client_sa, &len)) < 0) {
    412 		logmsg(LOG_CRIT, "accept failed: %s", strerror(errno));
    413 		return;
    414 	}
    415 
    416 	/* Refuse connection if the maximum is reached. */
    417 	if (session_count >= max_sessions) {
    418 		logmsg(LOG_ERR, "client limit (%d) reached, refusing "
    419 		    "connection from %s", max_sessions, sock_ntop(client_sa));
    420 		close(client_fd);
    421 		return;
    422 	}
    423 
    424 	/* Allocate session and copy back the info from the accept(). */
    425 	s = init_session();
    426 	if (s == NULL) {
    427 		logmsg(LOG_CRIT, "init_session failed");
    428 		close(client_fd);
    429 		return;
    430 	}
    431 	s->client_fd = client_fd;
    432 	memcpy(sstosa(&s->client_ss), client_sa, client_sa->sa_len);
    433 
    434 	/* Cast it once, and be done with it. */
    435 	client_sa = sstosa(&s->client_ss);
    436 	server_sa = sstosa(&s->server_ss);
    437 	client_to_proxy_sa = sstosa(&tmp_ss);
    438 	proxy_to_server_sa = sstosa(&s->proxy_ss);
    439 	fixed_server_sa = sstosa(&fixed_server_ss);
    440 
    441 	/* Log id/client early to ease debugging. */
    442 	logmsg(LOG_DEBUG, "#%d accepted connection from %s", s->id,
    443 	    sock_ntop(client_sa));
    444 
    445 	/*
    446 	 * Find out the real server and port that the client wanted.
    447 	 */
    448 	len = sizeof(struct sockaddr_storage);
    449 	if ((getsockname(s->client_fd, client_to_proxy_sa, &len)) < 0) {
    450 		logmsg(LOG_CRIT, "#%d getsockname failed: %s", s->id,
    451 		    strerror(errno));
    452 		goto fail;
    453 	}
    454 	if (server_lookup(client_sa, client_to_proxy_sa, server_sa) != 0) {
    455 	    	logmsg(LOG_CRIT, "#%d server lookup failed (no rdr?)", s->id);
    456 		goto fail;
    457 	}
    458 	if (fixed_server) {
    459 		memcpy(sstosa(&s->orig_server_ss), server_sa,
    460 		    server_sa->sa_len);
    461 		memcpy(server_sa, fixed_server_sa, fixed_server_sa->sa_len);
    462 	}
    463 
    464 	/* XXX: check we are not connecting to ourself. */
    465 
    466 	/*
    467 	 * Setup socket and connect to server.
    468 	 */
    469 	if ((s->server_fd = socket(server_sa->sa_family, SOCK_STREAM,
    470 	    IPPROTO_TCP)) < 0) {
    471 		logmsg(LOG_CRIT, "#%d server socket failed: %s", s->id,
    472 		    strerror(errno));
    473 		goto fail;
    474 	}
    475 	if (fixed_proxy && bind(s->server_fd, sstosa(&fixed_proxy_ss),
    476 	    fixed_proxy_ss.ss_len) != 0) {
    477 		logmsg(LOG_CRIT, "#%d cannot bind fixed proxy address: %s",
    478 		    s->id, strerror(errno));
    479 		goto fail;
    480 	}
    481 
    482 	/* Use non-blocking connect(), see CONNECT_TIMEOUT below. */
    483 	if ((fc = fcntl(s->server_fd, F_GETFL)) == -1 ||
    484 	    fcntl(s->server_fd, F_SETFL, fc | O_NONBLOCK) == -1) {
    485 		logmsg(LOG_CRIT, "#%d cannot mark socket non-blocking: %s",
    486 		    s->id, strerror(errno));
    487 		goto fail;
    488 	}
    489 	if (connect(s->server_fd, server_sa, server_sa->sa_len) < 0 &&
    490 	    errno != EINPROGRESS) {
    491 		logmsg(LOG_CRIT, "#%d proxy cannot connect to server %s: %s",
    492 		    s->id, sock_ntop(server_sa), strerror(errno));
    493 		goto fail;
    494 	}
    495 
    496 	len = sizeof(struct sockaddr_storage);
    497 	if ((getsockname(s->server_fd, proxy_to_server_sa, &len)) < 0) {
    498 		logmsg(LOG_CRIT, "#%d getsockname failed: %s", s->id,
    499 		    strerror(errno));
    500 		goto fail;
    501 	}
    502 
    503 	logmsg(LOG_INFO, "#%d FTP session %d/%d started: client %s to server "
    504 	    "%s via proxy %s ", s->id, session_count, max_sessions,
    505 	    sock_ntop(client_sa), sock_ntop(server_sa),
    506 	    sock_ntop(proxy_to_server_sa));
    507 
    508 	/* Keepalive is nice, but don't care if it fails. */
    509 	on = 1;
    510 	setsockopt(s->client_fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&on,
    511 	    sizeof on);
    512 	setsockopt(s->server_fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&on,
    513 	    sizeof on);
    514 
    515 	/*
    516 	 * Setup buffered events.
    517 	 */
    518 	s->client_bufev = bufferevent_new(s->client_fd, &client_read, NULL,
    519 	    &client_error, s);
    520 	if (s->client_bufev == NULL) {
    521 		logmsg(LOG_CRIT, "#%d bufferevent_new client failed", s->id);
    522 		goto fail;
    523 	}
    524 	bufferevent_settimeout(s->client_bufev, timeout, 0);
    525 	bufferevent_enable(s->client_bufev, EV_READ | EV_TIMEOUT);
    526 
    527 	s->server_bufev = bufferevent_new(s->server_fd, &server_read, NULL,
    528 	    &server_error, s);
    529 	if (s->server_bufev == NULL) {
    530 		logmsg(LOG_CRIT, "#%d bufferevent_new server failed", s->id);
    531 		goto fail;
    532 	}
    533 	bufferevent_settimeout(s->server_bufev, CONNECT_TIMEOUT, 0);
    534 	bufferevent_enable(s->server_bufev, EV_READ | EV_TIMEOUT);
    535 
    536 	return;
    537 
    538  fail:
    539 	end_session(s);
    540 }
    541 
    542 void
    543 handle_signal(int sig, short event, void *arg)
    544 {
    545 	/*
    546 	 * Signal handler rules don't apply, libevent decouples for us.
    547 	 */
    548 
    549 	logmsg(LOG_ERR, "%s exiting on signal %d", __progname, sig);
    550 
    551 	exit_daemon();
    552 }
    553 
    554 
    555 struct session *
    556 init_session(void)
    557 {
    558 	struct session *s;
    559 
    560 	s = calloc(1, sizeof(struct session));
    561 	if (s == NULL)
    562 		return (NULL);
    563 
    564 	s->id = id_count++;
    565 	s->client_fd = -1;
    566 	s->server_fd = -1;
    567 	s->cbuf[0] = '\0';
    568 	s->cbuf_valid = 0;
    569 	s->sbuf[0] = '\0';
    570 	s->sbuf_valid = 0;
    571 	s->client_bufev = NULL;
    572 	s->server_bufev = NULL;
    573 	s->cmd = CMD_NONE;
    574 	s->port = 0;
    575 
    576 	LIST_INSERT_HEAD(&sessions, s, entry);
    577 	session_count++;
    578 
    579 	return (s);
    580 }
    581 
    582 void
    583 logmsg(int pri, const char *message, ...)
    584 {
    585 	va_list	ap;
    586 
    587 	if (pri > loglevel)
    588 		return;
    589 
    590 	va_start(ap, message);
    591 
    592 	if (daemonize)
    593 		/* syslog does its own vissing. */
    594 		vsyslog(pri, message, ap);
    595 	else {
    596 		char buf[MAX_LOGLINE];
    597 		char visbuf[2 * MAX_LOGLINE];
    598 
    599 		/* We don't care about truncation. */
    600 		vsnprintf(buf, sizeof buf, message, ap);
    601 #ifdef __NetBSD__
    602 		size_t len = strlen(buf);
    603 		if (len > sizeof visbuf) {
    604 			len = sizeof visbuf;
    605 		}
    606 		strvisx(visbuf, buf, len, VIS_CSTYLE | VIS_NL);
    607 #else
    608 		strnvis(visbuf, buf, sizeof visbuf, VIS_CSTYLE | VIS_NL);
    609 #endif /* !__NetBSD__ */
    610 		fprintf(stderr, "%s\n", visbuf);
    611 	}
    612 
    613 	va_end(ap);
    614 }
    615 
    616 int
    617 main(int argc, char *argv[])
    618 {
    619 	struct rlimit rlp;
    620 	struct addrinfo hints, *res;
    621 	struct event ev, ev_sighup, ev_sigint, ev_sigterm;
    622 	int ch, error, listenfd, on;
    623 	const char *errstr = NULL; /* XXX gcc */
    624 
    625 	/* Defaults. */
    626 	anonymous_only	= 0;
    627 	daemonize	= 1;
    628 	fixed_proxy	= NULL;
    629 	fixed_server	= NULL;
    630 	fixed_server_port = "21";
    631 	ipv6_mode	= 0;
    632 	listen_ip	= NULL;
    633 	listen_port	= "8021";
    634 	loglevel	= LOG_NOTICE;
    635 	max_sessions	= 100;
    636 	qname		= NULL;
    637 	rfc_mode	= 0;
    638 	tagname		= NULL;
    639 	timeout		= 24 * 3600;
    640 	verbose		= 0;
    641 
    642 	/* Other initialization. */
    643 	id_count	= 1;
    644 	session_count	= 0;
    645 
    646 #if defined(__NetBSD__) && defined(WITH_IPF)
    647 	while ((ch = getopt(argc, argv, "6Aa:b:D:di:m:P:p:q:R:rT:t:v")) != -1) {
    648 #else
    649 	while ((ch = getopt(argc, argv, "6Aa:b:D:dm:P:p:q:R:rT:t:v")) != -1) {
    650 #endif /* __NetBSD__ && WITH_IPF */
    651 		switch (ch) {
    652 		case '6':
    653 			ipv6_mode = 1;
    654 			break;
    655 		case 'A':
    656 			anonymous_only = 1;
    657 			break;
    658 		case 'a':
    659 			fixed_proxy = optarg;
    660 			break;
    661 		case 'b':
    662 			listen_ip = optarg;
    663 			break;
    664 		case 'D':
    665 			loglevel = strtonum(optarg, LOG_EMERG, LOG_DEBUG,
    666 			    &errstr);
    667 			if (errstr)
    668 				errx(1, "loglevel %s", errstr);
    669 			break;
    670 		case 'd':
    671 			daemonize = 0;
    672 			break;
    673 #if defined(__NetBSD__) && defined(WITH_IPF)
    674 		case 'i':
    675 			ipf_enabled = 1;
    676 			netif = optarg;
    677 			break;
    678 #endif /* __NetBSD__ && WITH_IPF */
    679 		case 'm':
    680 			max_sessions = strtonum(optarg, 1, 500, &errstr);
    681 			if (errstr)
    682 				errx(1, "max sessions %s", errstr);
    683 			break;
    684 		case 'P':
    685 			fixed_server_port = optarg;
    686 			break;
    687 		case 'p':
    688 			listen_port = optarg;
    689 			break;
    690 		case 'q':
    691 			if (strlen(optarg) >= PF_QNAME_SIZE)
    692 				errx(1, "queuename too long");
    693 			qname = optarg;
    694 			break;
    695 		case 'R':
    696 			fixed_server = optarg;
    697 			break;
    698 		case 'r':
    699 			rfc_mode = 1;
    700 			break;
    701 		case 'T':
    702 			if (strlen(optarg) >= PF_TAG_NAME_SIZE)
    703 				errx(1, "tagname too long");
    704 			tagname = optarg;
    705 			break;
    706 		case 't':
    707 			timeout = strtonum(optarg, 0, 86400, &errstr);
    708 			if (errstr)
    709 				errx(1, "timeout %s", errstr);
    710 			break;
    711 		case 'v':
    712 			verbose++;
    713 			if (verbose > 2)
    714 				usage();
    715 			break;
    716 		default:
    717 			usage();
    718 		}
    719 	}
    720 
    721 	if (listen_ip == NULL)
    722 		listen_ip = ipv6_mode ? "::1" : "127.0.0.1";
    723 
    724 	/* Check for root to save the user from cryptic failure messages. */
    725 	if (getuid() != 0)
    726 		errx(1, "needs to start as root");
    727 
    728 	/* Raise max. open files limit to satisfy max. sessions. */
    729 	rlp.rlim_cur = rlp.rlim_max = (2 * max_sessions) + 10;
    730 	if (setrlimit(RLIMIT_NOFILE, &rlp) == -1)
    731 		err(1, "setrlimit");
    732 
    733 	if (fixed_proxy) {
    734 		memset(&hints, 0, sizeof hints);
    735 		hints.ai_flags = AI_NUMERICHOST;
    736 		hints.ai_family = ipv6_mode ? AF_INET6 : AF_INET;
    737 		hints.ai_socktype = SOCK_STREAM;
    738 		error = getaddrinfo(fixed_proxy, NULL, &hints, &res);
    739 		if (error)
    740 			errx(1, "getaddrinfo fixed proxy address failed: %s",
    741 			    gai_strerror(error));
    742 		memcpy(&fixed_proxy_ss, res->ai_addr, res->ai_addrlen);
    743 		logmsg(LOG_INFO, "using %s to connect to servers",
    744 		    sock_ntop(sstosa(&fixed_proxy_ss)));
    745 		freeaddrinfo(res);
    746 	}
    747 
    748 	if (fixed_server) {
    749 		memset(&hints, 0, sizeof hints);
    750 		hints.ai_family = ipv6_mode ? AF_INET6 : AF_INET;
    751 		hints.ai_socktype = SOCK_STREAM;
    752 		error = getaddrinfo(fixed_server, fixed_server_port, &hints,
    753 		    &res);
    754 		if (error)
    755 			errx(1, "getaddrinfo fixed server address failed: %s",
    756 			    gai_strerror(error));
    757 		memcpy(&fixed_server_ss, res->ai_addr, res->ai_addrlen);
    758 		logmsg(LOG_INFO, "using fixed server %s",
    759 		    sock_ntop(sstosa(&fixed_server_ss)));
    760 		freeaddrinfo(res);
    761 	}
    762 
    763 	/* Setup listener. */
    764 	memset(&hints, 0, sizeof hints);
    765 	hints.ai_flags = AI_NUMERICHOST | AI_PASSIVE;
    766 	hints.ai_family = ipv6_mode ? AF_INET6 : AF_INET;
    767 	hints.ai_socktype = SOCK_STREAM;
    768 	error = getaddrinfo(listen_ip, listen_port, &hints, &res);
    769 	if (error)
    770 		errx(1, "getaddrinfo listen address failed: %s",
    771 		    gai_strerror(error));
    772 	if ((listenfd = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP)) == -1)
    773 		errx(1, "socket failed");
    774 	on = 1;
    775 	if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, (void *)&on,
    776 	    sizeof on) != 0)
    777 		err(1, "setsockopt failed");
    778 	if (bind(listenfd, (struct sockaddr *)res->ai_addr,
    779 	    (socklen_t)res->ai_addrlen) != 0)
    780 	    	err(1, "bind failed");
    781 	if (listen(listenfd, TCP_BACKLOG) != 0)
    782 		err(1, "listen failed");
    783 	freeaddrinfo(res);
    784 
    785 	/* Initialize pf. */
    786 	init_filter(qname, tagname, verbose);
    787 
    788 	if (daemonize) {
    789 		if (daemon(0, 0) == -1)
    790 			err(1, "cannot daemonize");
    791 		openlog(__progname, LOG_PID | LOG_NDELAY, LOG_DAEMON);
    792 	}
    793 
    794 	/* Use logmsg for output from here on. */
    795 
    796 	if (!drop_privs()) {
    797 		logmsg(LOG_ERR, "cannot drop privileges: %s", strerror(errno));
    798 		exit(1);
    799 	}
    800 
    801 	event_init();
    802 
    803 	/* Setup signal handler. */
    804 	signal(SIGPIPE, SIG_IGN);
    805 	signal_set(&ev_sighup, SIGHUP, handle_signal, NULL);
    806 	signal_set(&ev_sigint, SIGINT, handle_signal, NULL);
    807 	signal_set(&ev_sigterm, SIGTERM, handle_signal, NULL);
    808 	signal_add(&ev_sighup, NULL);
    809 	signal_add(&ev_sigint, NULL);
    810 	signal_add(&ev_sigterm, NULL);
    811 
    812 	event_set(&ev, listenfd, EV_READ | EV_PERSIST, handle_connection, &ev);
    813 	event_add(&ev, NULL);
    814 
    815 	logmsg(LOG_NOTICE, "listening on %s port %s", listen_ip, listen_port);
    816 
    817 	/*  Vroom, vroom.  */
    818 	event_dispatch();
    819 
    820 	logmsg(LOG_ERR, "event_dispatch error: %s", strerror(errno));
    821 	exit_daemon();
    822 
    823 	/* NOTREACHED */
    824 	return (1);
    825 }
    826 
    827 u_int16_t
    828 parse_port(int mode)
    829 {
    830 	unsigned int	 port, v[6];
    831 	int		 n;
    832 	char		*p;
    833 
    834 	/* Find the last space or left-parenthesis. */
    835 	for (p = linebuf + linelen; p > linebuf; p--)
    836 		if (*p == ' ' || *p == '(')
    837 			break;
    838 	if (p == linebuf)
    839 		return (0);
    840 
    841 	switch (mode) {
    842 	case CMD_PORT:
    843 		n = sscanf(p, " %u,%u,%u,%u,%u,%u", &v[0], &v[1], &v[2],
    844 		    &v[3], &v[4], &v[5]);
    845 		if (n == 6 && v[0] < 256 && v[1] < 256 && v[2] < 256 &&
    846 		    v[3] < 256 && v[4] < 256 && v[5] < 256)
    847 			return ((v[4] << 8) | v[5]);
    848 		break;
    849 	case CMD_PASV:
    850 		n = sscanf(p, "(%u,%u,%u,%u,%u,%u)", &v[0], &v[1], &v[2],
    851 		    &v[3], &v[4], &v[5]);
    852 		if (n == 6 && v[0] < 256 && v[1] < 256 && v[2] < 256 &&
    853 		    v[3] < 256 && v[4] < 256 && v[5] < 256)
    854 			return ((v[4] << 8) | v[5]);
    855 		break;
    856 	case CMD_EPSV:
    857 		n = sscanf(p, "(|||%u|)", &port);
    858 		if (n == 1 && port < 65536)
    859 			return (port);
    860 		break;
    861 	case CMD_EPRT:
    862 		n = sscanf(p, " |1|%u.%u.%u.%u|%u|", &v[0], &v[1], &v[2],
    863 		    &v[3], &port);
    864 		if (n == 5 && v[0] < 256 && v[1] < 256 && v[2] < 256 &&
    865 		    v[3] < 256 && port < 65536)
    866 			return (port);
    867 		n = sscanf(p, " |2|%*[a-fA-F0-9:]|%u|", &port);
    868 		if (n == 1 && port < 65536)
    869 			return (port);
    870 		break;
    871 	default:
    872 		return (0);
    873 	}
    874 
    875 	return (0);
    876 }
    877 
    878 u_int16_t
    879 pick_proxy_port(void)
    880 {
    881 	/* Random should be good enough for avoiding port collisions. */
    882 	return (IPPORT_HIFIRSTAUTO + (arc4random() %
    883 	    (IPPORT_HILASTAUTO - IPPORT_HIFIRSTAUTO)));
    884 }
    885 
    886 void
    887 proxy_reply(int cmd, struct sockaddr *sa, u_int16_t port)
    888 {
    889 	int i, r = -1;
    890 
    891 	switch (cmd) {
    892 	case CMD_PORT:
    893 		r = snprintf(linebuf, sizeof linebuf,
    894 		    "PORT %s,%u,%u\r\n", sock_ntop(sa), port / 256,
    895 		    port % 256);
    896 		break;
    897 	case CMD_PASV:
    898 		r = snprintf(linebuf, sizeof linebuf,
    899 		    "227 Entering Passive Mode (%s,%u,%u)\r\n", sock_ntop(sa),
    900 		        port / 256, port % 256);
    901 		break;
    902 	case CMD_EPRT:
    903 		if (sa->sa_family == AF_INET)
    904 			r = snprintf(linebuf, sizeof linebuf,
    905 			    "EPRT |1|%s|%u|\r\n", sock_ntop(sa), port);
    906 		else if (sa->sa_family == AF_INET6)
    907 			r = snprintf(linebuf, sizeof linebuf,
    908 			    "EPRT |2|%s|%u|\r\n", sock_ntop(sa), port);
    909 		break;
    910 	case CMD_EPSV:
    911 		r = snprintf(linebuf, sizeof linebuf,
    912 		    "229 Entering Extended Passive Mode (|||%u|)\r\n", port);
    913 		break;
    914 	}
    915 
    916 	if (r < 0 || r >= sizeof linebuf) {
    917 		logmsg(LOG_ERR, "proxy_reply failed: %d", r);
    918 		linebuf[0] = '\0';
    919 		linelen = 0;
    920 		return;
    921 	}
    922 	linelen = (size_t)r;
    923 
    924 	if (cmd == CMD_PORT || cmd == CMD_PASV) {
    925 		/* Replace dots in IP address with commas. */
    926 		for (i = 0; i < linelen; i++)
    927 			if (linebuf[i] == '.')
    928 				linebuf[i] = ',';
    929 	}
    930 }
    931 
    932 void
    933 server_error(struct bufferevent *bufev, short what, void *arg)
    934 {
    935 	struct session *s = arg;
    936 
    937 	if (what & EVBUFFER_EOF)
    938 		logmsg(LOG_INFO, "#%d server close", s->id);
    939 	else if (what == (EVBUFFER_ERROR | EVBUFFER_READ))
    940 		logmsg(LOG_ERR, "#%d server refused connection", s->id);
    941 	else if (what & EVBUFFER_WRITE)
    942 		logmsg(LOG_ERR, "#%d server write error: %d", s->id, what);
    943 	else if (what & EVBUFFER_TIMEOUT)
    944 		logmsg(LOG_NOTICE, "#%d server timeout", s->id);
    945 	else
    946 		logmsg(LOG_ERR, "#%d abnormal server error: %d", s->id, what);
    947 
    948 	end_session(s);
    949 }
    950 
    951 int
    952 server_parse(struct session *s)
    953 {
    954 	if (s->cmd == CMD_NONE || linelen < 4 || linebuf[0] != '2')
    955 		goto out;
    956 
    957 	if ((s->cmd == CMD_PASV && strncmp("227 ", linebuf, 4) == 0) ||
    958 	    (s->cmd == CMD_EPSV && strncmp("229 ", linebuf, 4) == 0))
    959 		return (allow_data_connection(s));
    960 
    961  out:
    962 	s->cmd = CMD_NONE;
    963 	s->port = 0;
    964 
    965 	return (1);
    966 }
    967 
    968 int
    969 allow_data_connection(struct session *s)
    970 {
    971 	struct sockaddr *client_sa, *orig_sa, *proxy_sa, *server_sa;
    972 	int prepared = 0;
    973 
    974 	/*
    975 	 * The pf rules below do quite some NAT rewriting, to keep up
    976 	 * appearances.  Points to keep in mind:
    977 	 * 1)  The client must think it's talking to the real server,
    978 	 *     for both control and data connections.  Transparently.
    979 	 * 2)  The server must think that the proxy is the client.
    980 	 * 3)  Source and destination ports are rewritten to minimize
    981 	 *     port collisions, to aid security (some systems pick weak
    982 	 *     ports) or to satisfy RFC requirements (source port 20).
    983 	 */
    984 
    985 	/* Cast this once, to make code below it more readable. */
    986 	client_sa = sstosa(&s->client_ss);
    987 	server_sa = sstosa(&s->server_ss);
    988 	proxy_sa = sstosa(&s->proxy_ss);
    989 	if (fixed_server)
    990 		/* Fixed server: data connections must appear to come
    991 		   from / go to the original server, not the fixed one. */
    992 		orig_sa = sstosa(&s->orig_server_ss);
    993 	else
    994 		/* Server not fixed: orig_server == server. */
    995 		orig_sa = sstosa(&s->server_ss);
    996 
    997 	/* Passive modes. */
    998 	if (s->cmd == CMD_PASV || s->cmd == CMD_EPSV) {
    999 		s->port = parse_port(s->cmd);
   1000 		if (s->port < MIN_PORT) {
   1001 			logmsg(LOG_CRIT, "#%d bad port in '%s'", s->id,
   1002 			    linebuf);
   1003 			return (0);
   1004 		}
   1005 		s->proxy_port = pick_proxy_port();
   1006 		logmsg(LOG_INFO, "#%d passive: client to server port %d"
   1007 		    " via port %d", s->id, s->port, s->proxy_port);
   1008 
   1009 		if (prepare_commit(s->id) == -1)
   1010 			goto fail;
   1011 		prepared = 1;
   1012 
   1013 		proxy_reply(s->cmd, orig_sa, s->proxy_port);
   1014 		logmsg(LOG_DEBUG, "#%d proxy: %s", s->id, linebuf);
   1015 
   1016 		/* rdr from $client to $orig_server port $proxy_port -> $server
   1017 		    port $port */
   1018 		if (add_rdr(s->id, client_sa, orig_sa, s->proxy_port,
   1019 		    server_sa, s->port) == -1)
   1020 			goto fail;
   1021 
   1022 		/* nat from $client to $server port $port -> $proxy */
   1023 		if (add_nat(s->id, client_sa, server_sa, s->port, proxy_sa,
   1024 		    PF_NAT_PROXY_PORT_LOW, PF_NAT_PROXY_PORT_HIGH) == -1)
   1025 			goto fail;
   1026 
   1027 		/* pass in from $client to $server port $port */
   1028 		if (add_filter(s->id, PF_IN, client_sa, server_sa,
   1029 		    s->port) == -1)
   1030 			goto fail;
   1031 
   1032 		/* pass out from $proxy to $server port $port */
   1033 		if (add_filter(s->id, PF_OUT, proxy_sa, server_sa,
   1034 		    s->port) == -1)
   1035 			goto fail;
   1036 	}
   1037 
   1038 	/* Active modes. */
   1039 	if (s->cmd == CMD_PORT || s->cmd == CMD_EPRT) {
   1040 		logmsg(LOG_INFO, "#%d active: server to client port %d"
   1041 		    " via port %d", s->id, s->port, s->proxy_port);
   1042 
   1043 		if (prepare_commit(s->id) == -1)
   1044 			goto fail;
   1045 		prepared = 1;
   1046 
   1047 		/* rdr from $server to $proxy port $proxy_port -> $client port
   1048 		    $port */
   1049 		if (add_rdr(s->id, server_sa, proxy_sa, s->proxy_port,
   1050 		    client_sa, s->port) == -1)
   1051 			goto fail;
   1052 
   1053 		/* nat from $server to $client port $port -> $orig_server port
   1054 		    $natport */
   1055 		if (rfc_mode && s->cmd == CMD_PORT) {
   1056 			/* Rewrite sourceport to RFC mandated 20. */
   1057 			if (add_nat(s->id, server_sa, client_sa, s->port,
   1058 			    orig_sa, 20, 20) == -1)
   1059 				goto fail;
   1060 		} else {
   1061 			/* Let pf pick a source port from the standard range. */
   1062 			if (add_nat(s->id, server_sa, client_sa, s->port,
   1063 			    orig_sa, PF_NAT_PROXY_PORT_LOW,
   1064 			    PF_NAT_PROXY_PORT_HIGH) == -1)
   1065 			    	goto fail;
   1066 		}
   1067 
   1068 		/* pass in from $server to $client port $port */
   1069 		if (add_filter(s->id, PF_IN, server_sa, client_sa, s->port) ==
   1070 		    -1)
   1071 			goto fail;
   1072 
   1073 		/* pass out from $orig_server to $client port $port */
   1074 		if (add_filter(s->id, PF_OUT, orig_sa, client_sa, s->port) ==
   1075 		    -1)
   1076 			goto fail;
   1077 	}
   1078 
   1079 	/* Commit rules if they were prepared. */
   1080 	if (prepared && (do_commit() == -1)) {
   1081 		if (errno != EBUSY)
   1082 			goto fail;
   1083 		/* One more try if busy. */
   1084 		usleep(5000);
   1085 		if (do_commit() == -1)
   1086 			goto fail;
   1087 	}
   1088 
   1089 	s->cmd = CMD_NONE;
   1090 	s->port = 0;
   1091 
   1092 	return (1);
   1093 
   1094  fail:
   1095 	logmsg(LOG_CRIT, "#%d pf operation failed: %s", s->id, strerror(errno));
   1096 	if (prepared)
   1097 		do_rollback();
   1098 	return (0);
   1099 }
   1100 
   1101 void
   1102 server_read(struct bufferevent *bufev, void *arg)
   1103 {
   1104 	struct session	*s = arg;
   1105 	size_t		 buf_avail, nread;
   1106 	int		 n;
   1107 
   1108 	bufferevent_settimeout(bufev, timeout, 0);
   1109 
   1110 	do {
   1111 		buf_avail = sizeof s->sbuf - s->sbuf_valid;
   1112 		nread = bufferevent_read(bufev, s->sbuf + s->sbuf_valid,
   1113 		    buf_avail);
   1114 		s->sbuf_valid += nread;
   1115 
   1116 		while ((n = get_line(s->sbuf, &s->sbuf_valid)) > 0) {
   1117 			logmsg(LOG_DEBUG, "#%d server: %s", s->id, linebuf);
   1118 			if (!server_parse(s)) {
   1119 				end_session(s);
   1120 				return;
   1121 			}
   1122 			bufferevent_write(s->client_bufev, linebuf, linelen);
   1123 		}
   1124 
   1125 		if (n == -1) {
   1126 			logmsg(LOG_ERR, "#%d server reply too long or not"
   1127 			    " clean", s->id);
   1128 			end_session(s);
   1129 			return;
   1130 		}
   1131 	} while (nread == buf_avail);
   1132 }
   1133 
   1134 const char *
   1135 sock_ntop(struct sockaddr *sa)
   1136 {
   1137 	static int n = 0;
   1138 
   1139 	/* Cycle to next buffer. */
   1140 	n = (n + 1) % NTOP_BUFS;
   1141 	ntop_buf[n][0] = '\0';
   1142 
   1143 	if (sa->sa_family == AF_INET) {
   1144 		struct sockaddr_in *sin = (struct sockaddr_in *)sa;
   1145 
   1146 		return (inet_ntop(AF_INET, &sin->sin_addr, ntop_buf[n],
   1147 		    sizeof ntop_buf[0]));
   1148 	}
   1149 
   1150 	if (sa->sa_family == AF_INET6) {
   1151 		struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sa;
   1152 
   1153 		return (inet_ntop(AF_INET6, &sin6->sin6_addr, ntop_buf[n],
   1154 		    sizeof ntop_buf[0]));
   1155 	}
   1156 
   1157 	return (NULL);
   1158 }
   1159 
   1160 void
   1161 usage(void)
   1162 {
   1163 	fprintf(stderr, "usage: %s [-6Adrv] [-a address] [-b address]"
   1164 	    " [-D level] [-m maxsessions]\n                 [-P port]"
   1165 #if defined(__NetBSD__) && defined(WITH_IPF)
   1166 	    " [-i netif]"
   1167 #endif /* __NetBSD__ && WITH_IPF */
   1168 	    " [-p port] [-q queue] [-R address] [-T tag] [-t timeout]\n",
   1169 	    __progname);
   1170 
   1171 	exit(1);
   1172 }
   1173