Home | History | Annotate | Line # | Download | only in ftpd
ftpd.c revision 1.164.2.1.4.4
      1 /*	$NetBSD: ftpd.c,v 1.164.2.1.4.4 2008/09/18 19:16:54 bouyer Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1997-2004 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Luke Mewburn.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  * 3. All advertising materials mentioning features or use of this software
     19  *    must display the following acknowledgement:
     20  *        This product includes software developed by the NetBSD
     21  *        Foundation, Inc. and its contributors.
     22  * 4. Neither the name of The NetBSD Foundation nor the names of its
     23  *    contributors may be used to endorse or promote products derived
     24  *    from this software without specific prior written permission.
     25  *
     26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     36  * POSSIBILITY OF SUCH DAMAGE.
     37  */
     38 
     39 /*
     40  * Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994
     41  *	The Regents of the University of California.  All rights reserved.
     42  *
     43  * Redistribution and use in source and binary forms, with or without
     44  * modification, are permitted provided that the following conditions
     45  * are met:
     46  * 1. Redistributions of source code must retain the above copyright
     47  *    notice, this list of conditions and the following disclaimer.
     48  * 2. Redistributions in binary form must reproduce the above copyright
     49  *    notice, this list of conditions and the following disclaimer in the
     50  *    documentation and/or other materials provided with the distribution.
     51  * 3. Neither the name of the University nor the names of its contributors
     52  *    may be used to endorse or promote products derived from this software
     53  *    without specific prior written permission.
     54  *
     55  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     56  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     57  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     58  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     59  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     60  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     61  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     62  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     63  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     64  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     65  * SUCH DAMAGE.
     66  */
     67 
     68 /*
     69  * Copyright (C) 1997 and 1998 WIDE Project.
     70  * All rights reserved.
     71  *
     72  * Redistribution and use in source and binary forms, with or without
     73  * modification, are permitted provided that the following conditions
     74  * are met:
     75  * 1. Redistributions of source code must retain the above copyright
     76  *    notice, this list of conditions and the following disclaimer.
     77  * 2. Redistributions in binary form must reproduce the above copyright
     78  *    notice, this list of conditions and the following disclaimer in the
     79  *    documentation and/or other materials provided with the distribution.
     80  * 3. Neither the name of the project nor the names of its contributors
     81  *    may be used to endorse or promote products derived from this software
     82  *    without specific prior written permission.
     83  *
     84  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
     85  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     86  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     87  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
     88  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     89  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     90  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     91  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     92  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     93  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     94  * SUCH DAMAGE.
     95  */
     96 
     97 #include <sys/cdefs.h>
     98 #ifndef lint
     99 __COPYRIGHT(
    100 "@(#) Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994\n\
    101 	The Regents of the University of California.  All rights reserved.\n");
    102 #endif /* not lint */
    103 
    104 #ifndef lint
    105 #if 0
    106 static char sccsid[] = "@(#)ftpd.c	8.5 (Berkeley) 4/28/95";
    107 #else
    108 __RCSID("$NetBSD: ftpd.c,v 1.164.2.1.4.4 2008/09/18 19:16:54 bouyer Exp $");
    109 #endif
    110 #endif /* not lint */
    111 
    112 /*
    113  * FTP server.
    114  */
    115 #include <sys/param.h>
    116 #include <sys/stat.h>
    117 #include <sys/ioctl.h>
    118 #include <sys/socket.h>
    119 #include <sys/wait.h>
    120 #include <sys/mman.h>
    121 #include <sys/resource.h>
    122 
    123 #include <netinet/in.h>
    124 #include <netinet/in_systm.h>
    125 #include <netinet/ip.h>
    126 
    127 #define	FTP_NAMES
    128 #include <arpa/ftp.h>
    129 #include <arpa/inet.h>
    130 #include <arpa/telnet.h>
    131 
    132 #include <ctype.h>
    133 #include <dirent.h>
    134 #include <err.h>
    135 #include <errno.h>
    136 #include <fcntl.h>
    137 #include <fnmatch.h>
    138 #include <glob.h>
    139 #include <grp.h>
    140 #include <limits.h>
    141 #include <netdb.h>
    142 #include <pwd.h>
    143 #include <signal.h>
    144 #include <stdarg.h>
    145 #include <stdio.h>
    146 #include <stdlib.h>
    147 #include <string.h>
    148 #include <syslog.h>
    149 #include <time.h>
    150 #include <tzfile.h>
    151 #include <unistd.h>
    152 #include <util.h>
    153 #ifdef SUPPORT_UTMP
    154 #include <utmp.h>
    155 #endif
    156 #ifdef SUPPORT_UTMPX
    157 #include <utmpx.h>
    158 #endif
    159 #ifdef SKEY
    160 #include <skey.h>
    161 #endif
    162 #ifdef KERBEROS5
    163 #include <com_err.h>
    164 #include <krb5/krb5.h>
    165 #endif
    166 
    167 #ifdef	LOGIN_CAP
    168 #include <login_cap.h>
    169 #endif
    170 
    171 #ifdef USE_PAM
    172 #include <security/pam_appl.h>
    173 #endif
    174 
    175 #define	GLOBAL
    176 #include "extern.h"
    177 #include "pathnames.h"
    178 #include "version.h"
    179 
    180 volatile sig_atomic_t	transflag;
    181 volatile sig_atomic_t	urgflag;
    182 
    183 int	data;
    184 int	sflag;
    185 int	stru;			/* avoid C keyword */
    186 int	mode;
    187 int	dataport;		/* use specific data port */
    188 int	dopidfile;		/* maintain pid file */
    189 int	doutmp;			/* update utmp file */
    190 int	dowtmp;			/* update wtmp file */
    191 int	doxferlog;		/* syslog/write wu-ftpd style xferlog entries */
    192 int	xferlogfd;		/* fd to write wu-ftpd xferlog entries to */
    193 int	dropprivs;		/* if privileges should or have been dropped */
    194 int	mapped;			/* IPv4 connection on AF_INET6 socket */
    195 off_t	file_size;
    196 off_t	byte_count;
    197 static char ttyline[20];
    198 
    199 #ifdef USE_PAM
    200 static int	auth_pam(struct passwd **, const char *);
    201 pam_handle_t	*pamh = NULL;
    202 #endif
    203 
    204 #ifdef SUPPORT_UTMP
    205 static struct utmp utmp;	/* for utmp */
    206 #endif
    207 #ifdef SUPPORT_UTMPX
    208 static struct utmpx utmpx;	/* for utmpx */
    209 #endif
    210 
    211 static const char *anondir = NULL;
    212 static const char *confdir = _DEFAULT_CONFDIR;
    213 
    214 static char	*curname;		/* current USER name */
    215 static size_t	curname_len;		/* length of curname (include NUL) */
    216 
    217 #if defined(KERBEROS) || defined(KERBEROS5)
    218 int	has_ccache = 0;
    219 int	notickets = 1;
    220 char	*krbtkfile_env = NULL;
    221 char	*tty = ttyline;
    222 int	login_krb5_forwardable_tgt = 0;
    223 #endif
    224 
    225 int epsvall = 0;
    226 
    227 /*
    228  * Timeout intervals for retrying connections
    229  * to hosts that don't accept PORT cmds.  This
    230  * is a kludge, but given the problems with TCP...
    231  */
    232 #define	SWAITMAX	90	/* wait at most 90 seconds */
    233 #define	SWAITINT	5	/* interval between retries */
    234 
    235 int	swaitmax = SWAITMAX;
    236 int	swaitint = SWAITINT;
    237 
    238 enum send_status {
    239 	SS_SUCCESS,
    240 	SS_ABORTED,			/* transfer aborted */
    241 	SS_NO_TRANSFER,			/* no transfer made yet */
    242 	SS_FILE_ERROR,			/* file read error */
    243 	SS_DATA_ERROR			/* data send error */
    244 };
    245 
    246 static int	 bind_pasv_addr(void);
    247 static int	 checkuser(const char *, const char *, int, int, char **);
    248 static int	 checkaccess(const char *);
    249 static int	 checkpassword(const struct passwd *, const char *);
    250 static void	 end_login(void);
    251 static FILE	*getdatasock(const char *);
    252 static char	*gunique(const char *);
    253 static void	 login_utmp(const char *, const char *, const char *,
    254 		     struct sockinet *);
    255 static void	 logremotehost(struct sockinet *);
    256 static void	 lostconn(int);
    257 static void	 toolong(int);
    258 static void	 sigquit(int);
    259 static void	 sigurg(int);
    260 static int	 handleoobcmd(void);
    261 static int	 receive_data(FILE *, FILE *);
    262 static int	 send_data(FILE *, FILE *, const struct stat *, int);
    263 static struct passwd *sgetpwnam(const char *);
    264 static int	 write_data(int, char *, size_t, off_t *, struct timeval *,
    265 		     int);
    266 static enum send_status
    267 		 send_data_with_read(int, int, const struct stat *, int);
    268 static enum send_status
    269 		 send_data_with_mmap(int, int, const struct stat *, int);
    270 static void	 logrusage(const struct rusage *, const struct rusage *);
    271 static void	 logout_utmp(void);
    272 
    273 int	main(int, char *[]);
    274 
    275 #if defined(KERBEROS)
    276 int	klogin(struct passwd *, char *, char *, char *);
    277 void	kdestroy(void);
    278 #endif
    279 #if defined(KERBEROS5)
    280 int	k5login(struct passwd *, char *, char *, char *);
    281 void	k5destroy(void);
    282 #endif
    283 
    284 int
    285 main(int argc, char *argv[])
    286 {
    287 	int		addrlen, ch, on = 1, tos, keepalive;
    288 #ifdef KERBEROS5
    289 	krb5_error_code	kerror;
    290 #endif
    291 	char		*p;
    292 	const char	*xferlogname = NULL;
    293 	long		l;
    294 	struct sigaction sa;
    295 
    296 	connections = 1;
    297 	debug = 0;
    298 	logging = 0;
    299 	pdata = -1;
    300 	sflag = 0;
    301 	dataport = 0;
    302 	dopidfile = 1;		/* default: DO use a pid file to count users */
    303 	doutmp = 0;		/* default: Do NOT log to utmp */
    304 	dowtmp = 1;		/* default: DO log to wtmp */
    305 	doxferlog = 0;		/* default: Do NOT syslog xferlog */
    306 	xferlogfd = -1;		/* default: Do NOT write xferlog file */
    307 	dropprivs = 0;
    308 	mapped = 0;
    309 	usedefault = 1;
    310 	emailaddr = NULL;
    311 	hostname[0] = '\0';
    312 	homedir[0] = '\0';
    313 	gidcount = 0;
    314 	is_oob = 0;
    315 	version = FTPD_VERSION;
    316 
    317 	/*
    318 	 * LOG_NDELAY sets up the logging connection immediately,
    319 	 * necessary for anonymous ftp's that chroot and can't do it later.
    320 	 */
    321 	openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
    322 
    323 	while ((ch = getopt(argc, argv, "a:c:C:de:h:HlL:P:qQrst:T:uUvV:wWX"))
    324 	    != -1) {
    325 		switch (ch) {
    326 		case 'a':
    327 			anondir = optarg;
    328 			break;
    329 
    330 		case 'c':
    331 			confdir = optarg;
    332 			break;
    333 
    334 		case 'C':
    335 			pw = sgetpwnam(optarg);
    336 			exit(checkaccess(optarg) ? 0 : 1);
    337 			/* NOTREACHED */
    338 
    339 		case 'd':
    340 		case 'v':		/* deprecated */
    341 			debug = 1;
    342 			break;
    343 
    344 		case 'e':
    345 			emailaddr = optarg;
    346 			break;
    347 
    348 		case 'h':
    349 			strlcpy(hostname, optarg, sizeof(hostname));
    350 			break;
    351 
    352 		case 'H':
    353 			if (gethostname(hostname, sizeof(hostname)) == -1)
    354 				hostname[0] = '\0';
    355 			hostname[sizeof(hostname) - 1] = '\0';
    356 			break;
    357 
    358 		case 'l':
    359 			logging++;	/* > 1 == extra logging */
    360 			break;
    361 
    362 		case 'L':
    363 			xferlogname = optarg;
    364 			break;
    365 
    366 		case 'P':
    367 			errno = 0;
    368 			p = NULL;
    369 			l = strtol(optarg, &p, 10);
    370 			if (errno || *optarg == '\0' || *p != '\0' ||
    371 			    l < IPPORT_RESERVED ||
    372 			    l > IPPORT_ANONMAX) {
    373 				syslog(LOG_WARNING, "Invalid dataport %s",
    374 				    optarg);
    375 				dataport = 0;
    376 			}
    377 			dataport = (int)l;
    378 			break;
    379 
    380 		case 'q':
    381 			dopidfile = 1;
    382 			break;
    383 
    384 		case 'Q':
    385 			dopidfile = 0;
    386 			break;
    387 
    388 		case 'r':
    389 			dropprivs = 1;
    390 			break;
    391 
    392 		case 's':
    393 			sflag = 1;
    394 			break;
    395 
    396 		case 't':
    397 		case 'T':
    398 			syslog(LOG_WARNING,
    399 			    "-%c has been deprecated in favour of ftpd.conf",
    400 			    ch);
    401 			break;
    402 
    403 		case 'u':
    404 			doutmp = 1;
    405 			break;
    406 
    407 		case 'U':
    408 			doutmp = 0;
    409 			break;
    410 
    411 		case 'V':
    412 			if (EMPTYSTR(optarg) || strcmp(optarg, "-") == 0)
    413 				version = NULL;
    414 			else
    415 				version = xstrdup(optarg);
    416 			break;
    417 
    418 		case 'w':
    419 			dowtmp = 1;
    420 			break;
    421 
    422 		case 'W':
    423 			dowtmp = 0;
    424 			break;
    425 
    426 		case 'X':
    427 			doxferlog |= 1;
    428 			break;
    429 
    430 		default:
    431 			if (optopt == 'a' || optopt == 'C')
    432 				exit(1);
    433 			syslog(LOG_WARNING, "unknown flag -%c ignored", optopt);
    434 			break;
    435 		}
    436 	}
    437 	if (EMPTYSTR(confdir))
    438 		confdir = _DEFAULT_CONFDIR;
    439 
    440 	errno = 0;
    441 	l = sysconf(_SC_LOGIN_NAME_MAX);
    442 	if (l == -1 && errno != 0) {
    443 		syslog(LOG_ERR, "sysconf _SC_LOGIN_NAME_MAX: %m");
    444 		exit(1);
    445 	} else if (l <= 0) {
    446 		syslog(LOG_WARNING, "using conservative LOGIN_NAME_MAX value");
    447 		curname_len = _POSIX_LOGIN_NAME_MAX;
    448 	} else
    449 		curname_len = (size_t)l;
    450 	curname = malloc(curname_len);
    451 	if (curname == NULL) {
    452 		syslog(LOG_ERR, "malloc: %m");
    453 		exit(1);
    454 	}
    455 	curname[0] = '\0';
    456 
    457 	memset((char *)&his_addr, 0, sizeof(his_addr));
    458 	addrlen = sizeof(his_addr.si_su);
    459 	if (getpeername(0, (struct sockaddr *)&his_addr.si_su, &addrlen) < 0) {
    460 		syslog(LOG_ERR, "getpeername (%s): %m",argv[0]);
    461 		exit(1);
    462 	}
    463 	his_addr.su_len = addrlen;
    464 	memset((char *)&ctrl_addr, 0, sizeof(ctrl_addr));
    465 	addrlen = sizeof(ctrl_addr.si_su);
    466 	if (getsockname(0, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) {
    467 		syslog(LOG_ERR, "getsockname (%s): %m",argv[0]);
    468 		exit(1);
    469 	}
    470 	ctrl_addr.su_len = addrlen;
    471 #ifdef INET6
    472 	if (his_addr.su_family == AF_INET6
    473 	 && IN6_IS_ADDR_V4MAPPED(&his_addr.su_6addr)) {
    474 #if 1
    475 		/*
    476 		 * IPv4 control connection arrived to AF_INET6 socket.
    477 		 * I hate to do this, but this is the easiest solution.
    478 		 *
    479 		 * The assumption is untrue on SIIT environment.
    480 		 */
    481 		struct sockinet tmp_addr;
    482 		const int off = sizeof(struct in6_addr) - sizeof(struct in_addr);
    483 
    484 		tmp_addr = his_addr;
    485 		memset(&his_addr, 0, sizeof(his_addr));
    486 		his_addr.su_family = AF_INET;
    487 		his_addr.su_len = sizeof(his_addr.si_su.su_sin);
    488 		memcpy(&his_addr.su_addr, &tmp_addr.su_6addr.s6_addr[off],
    489 		    sizeof(his_addr.su_addr));
    490 		his_addr.su_port = tmp_addr.su_port;
    491 
    492 		tmp_addr = ctrl_addr;
    493 		memset(&ctrl_addr, 0, sizeof(ctrl_addr));
    494 		ctrl_addr.su_family = AF_INET;
    495 		ctrl_addr.su_len = sizeof(ctrl_addr.si_su.su_sin);
    496 		memcpy(&ctrl_addr.su_addr, &tmp_addr.su_6addr.s6_addr[off],
    497 		    sizeof(ctrl_addr.su_addr));
    498 		ctrl_addr.su_port = tmp_addr.su_port;
    499 #else
    500 		while (fgets(line, sizeof(line), fd) != NULL) {
    501 			if ((cp = strchr(line, '\n')) != NULL)
    502 				*cp = '\0';
    503 			reply(-530, "%s", line);
    504 		}
    505 		(void) fflush(stdout);
    506 		(void) fclose(fd);
    507 		reply(530,
    508 		    "Connection from IPv4 mapped address is not supported.");
    509 		exit(0);
    510 #endif
    511 
    512 		mapped = 1;
    513 	} else
    514 #endif /* INET6 */
    515 		mapped = 0;
    516 #ifdef IP_TOS
    517 	if (!mapped && his_addr.su_family == AF_INET) {
    518 		tos = IPTOS_LOWDELAY;
    519 		if (setsockopt(0, IPPROTO_IP, IP_TOS, (char *)&tos,
    520 			       sizeof(int)) < 0)
    521 			syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
    522 	}
    523 #endif
    524 	/* if the hostname hasn't been given, attempt to determine it */
    525 	if (hostname[0] == '\0') {
    526 		if (getnameinfo((struct sockaddr *)&ctrl_addr.si_su,
    527 		    ctrl_addr.su_len, hostname, sizeof(hostname), NULL, 0, 0)
    528 		    != 0)
    529 			(void)gethostname(hostname, sizeof(hostname));
    530 		hostname[sizeof(hostname) - 1] = '\0';
    531 	}
    532 
    533 	/* set this here so klogin can use it... */
    534 	(void)snprintf(ttyline, sizeof(ttyline), "ftp%d", getpid());
    535 
    536 	(void) freopen(_PATH_DEVNULL, "w", stderr);
    537 
    538 	memset(&sa, 0, sizeof(sa));
    539 	sa.sa_handler = SIG_DFL;
    540 	sa.sa_flags = SA_RESTART;
    541 	sigemptyset(&sa.sa_mask);
    542 	(void) sigaction(SIGCHLD, &sa, NULL);
    543 
    544 	sa.sa_handler = sigquit;
    545 	sa.sa_flags = SA_RESTART;
    546 	sigfillset(&sa.sa_mask);	/* block all sigs in these handlers */
    547 	(void) sigaction(SIGHUP, &sa, NULL);
    548 	(void) sigaction(SIGINT, &sa, NULL);
    549 	(void) sigaction(SIGQUIT, &sa, NULL);
    550 	(void) sigaction(SIGTERM, &sa, NULL);
    551 	sa.sa_handler = lostconn;
    552 	(void) sigaction(SIGPIPE, &sa, NULL);
    553 	sa.sa_handler = toolong;
    554 	(void) sigaction(SIGALRM, &sa, NULL);
    555 	sa.sa_handler = sigurg;
    556 	(void) sigaction(SIGURG, &sa, NULL);
    557 
    558 	/* Try to handle urgent data inline */
    559 #ifdef SO_OOBINLINE
    560 	if (setsockopt(0, SOL_SOCKET, SO_OOBINLINE, (char *)&on, sizeof(on)) < 0)
    561 		syslog(LOG_WARNING, "setsockopt: %m");
    562 #endif
    563 	/* Set keepalives on the socket to detect dropped connections.  */
    564 #ifdef SO_KEEPALIVE
    565 	keepalive = 1;
    566 	if (setsockopt(0, SOL_SOCKET, SO_KEEPALIVE, (char *)&keepalive,
    567 	    sizeof(int)) < 0)
    568 		syslog(LOG_WARNING, "setsockopt (SO_KEEPALIVE): %m");
    569 #endif
    570 
    571 #ifdef	F_SETOWN
    572 	if (fcntl(fileno(stdin), F_SETOWN, getpid()) == -1)
    573 		syslog(LOG_WARNING, "fcntl F_SETOWN: %m");
    574 #endif
    575 	logremotehost(&his_addr);
    576 	/*
    577 	 * Set up default state
    578 	 */
    579 	data = -1;
    580 	type = TYPE_A;
    581 	form = FORM_N;
    582 	stru = STRU_F;
    583 	mode = MODE_S;
    584 	tmpline[0] = '\0';
    585 	hasyyerrored = 0;
    586 
    587 #ifdef KERBEROS5
    588 	kerror = krb5_init_context(&kcontext);
    589 	if (kerror) {
    590 		syslog(LOG_ERR, "%s when initializing Kerberos context",
    591 		    error_message(kerror));
    592 		exit(0);
    593 	}
    594 #endif /* KERBEROS5 */
    595 
    596 	init_curclass();
    597 	curclass.timeout = 300;		/* 5 minutes, as per login(1) */
    598 	curclass.type = CLASS_REAL;
    599 
    600 	/* If logins are disabled, print out the message. */
    601 	if (display_file(_PATH_NOLOGIN, 530)) {
    602 		reply(530, "System not available.");
    603 		exit(0);
    604 	}
    605 	(void)display_file(conffilename(_NAME_FTPWELCOME), 220);
    606 		/* reply(220,) must follow */
    607 	if (EMPTYSTR(version))
    608 		reply(220, "%s FTP server ready.", hostname);
    609 	else
    610 		reply(220, "%s FTP server (%s) ready.", hostname, version);
    611 
    612 	if (xferlogname != NULL) {
    613 		xferlogfd = open(xferlogname, O_WRONLY | O_APPEND | O_CREAT,
    614 		    0660);
    615 		if (xferlogfd == -1)
    616 			syslog(LOG_WARNING, "open xferlog `%s': %m",
    617 			    xferlogname);
    618 		else
    619 			doxferlog |= 2;
    620 	}
    621 
    622 	ftp_loop();
    623 	/* NOTREACHED */
    624 }
    625 
    626 static void
    627 lostconn(int signo)
    628 {
    629 
    630 	if (debug)
    631 		syslog(LOG_DEBUG, "lost connection");
    632 	dologout(1);
    633 }
    634 
    635 static void
    636 toolong(int signo)
    637 {
    638 
    639 		/* XXXSIGRACE */
    640 	reply(421,
    641 	    "Timeout (" LLF " seconds): closing control connection.",
    642 	    (LLT)curclass.timeout);
    643 	if (logging)
    644 		syslog(LOG_INFO, "User %s timed out after " LLF " seconds",
    645 		    (pw ? pw->pw_name : "unknown"), (LLT)curclass.timeout);
    646 	dologout(1);
    647 }
    648 
    649 static void
    650 sigquit(int signo)
    651 {
    652 
    653 	if (debug)
    654 		syslog(LOG_DEBUG, "got signal %d", signo);
    655 	dologout(1);
    656 }
    657 
    658 static void
    659 sigurg(int signo)
    660 {
    661 
    662 	urgflag = 1;
    663 }
    664 
    665 
    666 /*
    667  * Save the result of a getpwnam.  Used for USER command, since
    668  * the data returned must not be clobbered by any other command
    669  * (e.g., globbing).
    670  */
    671 static struct passwd *
    672 sgetpwnam(const char *name)
    673 {
    674 	static struct passwd save;
    675 	struct passwd *p;
    676 
    677 	if ((p = getpwnam(name)) == NULL)
    678 		return (p);
    679 	if (save.pw_name) {
    680 		free((char *)save.pw_name);
    681 		memset(save.pw_passwd, 0, strlen(save.pw_passwd));
    682 		free((char *)save.pw_passwd);
    683 		free((char *)save.pw_gecos);
    684 		free((char *)save.pw_dir);
    685 		free((char *)save.pw_shell);
    686 	}
    687 	save = *p;
    688 	save.pw_name = xstrdup(p->pw_name);
    689 	save.pw_passwd = xstrdup(p->pw_passwd);
    690 	save.pw_gecos = xstrdup(p->pw_gecos);
    691 	save.pw_dir = xstrdup(p->pw_dir);
    692 	save.pw_shell = xstrdup(p->pw_shell);
    693 	return (&save);
    694 }
    695 
    696 static int	login_attempts;	/* number of failed login attempts */
    697 static int	askpasswd;	/* had USER command, ask for PASSwd */
    698 static int	permitted;	/* USER permitted */
    699 
    700 /*
    701  * USER command.
    702  * Sets global passwd pointer pw if named account exists and is acceptable;
    703  * sets askpasswd if a PASS command is expected.  If logged in previously,
    704  * need to reset state.  If name is "ftp" or "anonymous", the name is not in
    705  * _NAME_FTPUSERS, and ftp account exists, set guest and pw, then just return.
    706  * If account doesn't exist, ask for passwd anyway.  Otherwise, check user
    707  * requesting login privileges.  Disallow anyone who does not have a standard
    708  * shell as returned by getusershell().  Disallow anyone mentioned in the file
    709  * _NAME_FTPUSERS to allow people such as root and uucp to be avoided.
    710  */
    711 void
    712 user(const char *name)
    713 {
    714 	char	*class;
    715 #ifdef	LOGIN_CAP
    716 	login_cap_t *lc = NULL;
    717 #endif
    718 
    719 	class = NULL;
    720 	if (logged_in) {
    721 		switch (curclass.type) {
    722 		case CLASS_GUEST:
    723 			reply(530, "Can't change user from guest login.");
    724 			return;
    725 		case CLASS_CHROOT:
    726 			reply(530, "Can't change user from chroot user.");
    727 			return;
    728 		case CLASS_REAL:
    729 			if (dropprivs) {
    730 				reply(530, "Can't change user.");
    731 				return;
    732 			}
    733 			end_login();
    734 			break;
    735 		default:
    736 			abort();
    737 		}
    738 	}
    739 
    740 #if defined(KERBEROS)
    741 	kdestroy();
    742 #endif
    743 #if defined(KERBEROS5)
    744 	k5destroy();
    745 #endif
    746 
    747 	curclass.type = CLASS_REAL;
    748 	askpasswd = 0;
    749 	permitted = 0;
    750 
    751 	if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) {
    752 			/* need `pw' setup for checkaccess() and checkuser () */
    753 		if ((pw = sgetpwnam("ftp")) == NULL)
    754 			reply(530, "User %s unknown.", name);
    755 		else if (! checkaccess("ftp") || ! checkaccess("anonymous"))
    756 			reply(530, "User %s access denied.", name);
    757 		else {
    758 			curclass.type = CLASS_GUEST;
    759 			askpasswd = 1;
    760 			reply(331,
    761 			    "Guest login ok, type your name as password.");
    762 		}
    763 		if (!askpasswd) {
    764 			if (logging)
    765 				syslog(LOG_NOTICE,
    766 				    "ANONYMOUS FTP LOGIN REFUSED FROM %s",
    767 				    remotehost);
    768 			end_login();
    769 			goto cleanup_user;
    770 		}
    771 		name = "ftp";
    772 	} else
    773 		pw = sgetpwnam(name);
    774 
    775 	strlcpy(curname, name, curname_len);
    776 
    777 			/* check user in /etc/ftpusers, and setup class */
    778 	permitted = checkuser(_NAME_FTPUSERS, curname, 1, 0, &class);
    779 
    780 			/* check user in /etc/ftpchroot */
    781 	lc = login_getpwclass(pw);
    782 	if (checkuser(_NAME_FTPCHROOT, curname, 0, 0, NULL)
    783 #ifdef	LOGIN_CAP	/* Allow login.conf configuration as well */
    784 	    || login_getcapbool(lc, "ftp-chroot", 0)
    785 #endif
    786 	) {
    787 		if (curclass.type == CLASS_GUEST) {
    788 			syslog(LOG_NOTICE,
    789 	    "Can't change guest user to chroot class; remove entry in %s",
    790 			    _NAME_FTPCHROOT);
    791 			exit(1);
    792 		}
    793 		curclass.type = CLASS_CHROOT;
    794 	}
    795 			/* determine default class */
    796 	if (class == NULL) {
    797 		switch (curclass.type) {
    798 		case CLASS_GUEST:
    799 			class = xstrdup("guest");
    800 			break;
    801 		case CLASS_CHROOT:
    802 			class = xstrdup("chroot");
    803 			break;
    804 		case CLASS_REAL:
    805 			class = xstrdup("real");
    806 			break;
    807 		default:
    808 			syslog(LOG_ERR, "unknown curclass.type %d; aborting",
    809 			    curclass.type);
    810 			abort();
    811 		}
    812 	}
    813 			/* parse ftpd.conf, setting up various parameters */
    814 	parse_conf(class);
    815 			/* if not guest user, check for valid shell */
    816 	if (pw == NULL)
    817 		permitted = 0;
    818 	else {
    819 		const char	*cp, *shell;
    820 
    821 		if ((shell = pw->pw_shell) == NULL || *shell == 0)
    822 			shell = _PATH_BSHELL;
    823 		while ((cp = getusershell()) != NULL)
    824 			if (strcmp(cp, shell) == 0)
    825 				break;
    826 		endusershell();
    827 		if (cp == NULL && curclass.type != CLASS_GUEST)
    828 			permitted = 0;
    829 	}
    830 
    831 			/* deny quickly (after USER not PASS) if requested */
    832 	if (CURCLASS_FLAGS_ISSET(denyquick) && !permitted) {
    833 		reply(530, "User %s may not use FTP.", curname);
    834 		if (logging)
    835 			syslog(LOG_NOTICE, "FTP LOGIN REFUSED FROM %s, %s",
    836 			    remotehost, curname);
    837 		end_login();
    838 		goto cleanup_user;
    839 	}
    840 
    841 			/* if haven't asked yet (i.e, not anon), ask now */
    842 	if (!askpasswd) {
    843 		askpasswd = 1;
    844 #ifdef SKEY
    845 		if (skey_haskey(curname) == 0) {
    846 			const char *myskey;
    847 
    848 			myskey = skey_keyinfo(curname);
    849 			reply(331, "Password [ %s ] required for %s.",
    850 			    myskey ? myskey : "error getting challenge",
    851 			    curname);
    852 		} else
    853 #endif
    854 			reply(331, "Password required for %s.", curname);
    855 	}
    856 
    857  cleanup_user:
    858 #ifdef LOGIN_CAP
    859 	login_close(lc);
    860 #endif
    861 	/*
    862 	 * Delay before reading passwd after first failed
    863 	 * attempt to slow down passwd-guessing programs.
    864 	 */
    865 	if (login_attempts)
    866 		sleep((unsigned) login_attempts);
    867 
    868 	if (class)
    869 		free(class);
    870 }
    871 
    872 /*
    873  * Determine whether something is to happen (allow access, chroot)
    874  * for a user. Each line is a shell-style glob followed by
    875  * `yes' or `no'.
    876  *
    877  * For backward compatibility, `allow' and `deny' are synonymns
    878  * for `yes' and `no', respectively.
    879  *
    880  * Each glob is matched against the username in turn, and the first
    881  * match found is used. If no match is found, the result is the
    882  * argument `def'. If a match is found but without and explicit
    883  * `yes'/`no', the result is the opposite of def.
    884  *
    885  * If the file doesn't exist at all, the result is the argument
    886  * `nofile'
    887  *
    888  * Any line starting with `#' is considered a comment and ignored.
    889  *
    890  * Returns 0 if the user is denied, or 1 if they are allowed.
    891  *
    892  * NOTE: needs struct passwd *pw setup before use.
    893  */
    894 static int
    895 checkuser(const char *fname, const char *name, int def, int nofile,
    896 	    char **retclass)
    897 {
    898 	FILE	*fd;
    899 	int	 retval;
    900 	char	*word, *perm, *class, *buf, *p;
    901 	size_t	 len, line;
    902 
    903 	retval = def;
    904 	if (retclass != NULL)
    905 		*retclass = NULL;
    906 	if ((fd = fopen(conffilename(fname), "r")) == NULL)
    907 		return nofile;
    908 
    909 	line = 0;
    910 	for (;
    911 	    (buf = fparseln(fd, &len, &line, NULL, FPARSELN_UNESCCOMM |
    912 			    FPARSELN_UNESCCONT | FPARSELN_UNESCESC)) != NULL;
    913 	    free(buf), buf = NULL) {
    914 		word = perm = class = NULL;
    915 		p = buf;
    916 		if (len < 1)
    917 			continue;
    918 		if (p[len - 1] == '\n')
    919 			p[--len] = '\0';
    920 		if (EMPTYSTR(p))
    921 			continue;
    922 
    923 		NEXTWORD(p, word);
    924 		NEXTWORD(p, perm);
    925 		NEXTWORD(p, class);
    926 		if (EMPTYSTR(word))
    927 			continue;
    928 		if (!EMPTYSTR(class)) {
    929 			if (strcasecmp(class, "all") == 0 ||
    930 			    strcasecmp(class, "none") == 0) {
    931 				syslog(LOG_WARNING,
    932 		"%s line %d: illegal user-defined class `%s' - skipping entry",
    933 					    fname, (int)line, class);
    934 				continue;
    935 			}
    936 		}
    937 
    938 					/* have a host specifier */
    939 		if ((p = strchr(word, '@')) != NULL) {
    940 			unsigned long	net, mask, addr;
    941 			int		bits;
    942 
    943 			*p++ = '\0';
    944 					/* check against network or CIDR */
    945 			if (isdigit((unsigned char)*p) &&
    946 			    (bits = inet_net_pton(AF_INET, p,
    947 			    &net, sizeof(net))) != -1) {
    948 				net = ntohl(net);
    949 				mask = 0xffffffffU << (32 - bits);
    950 				addr = ntohl(his_addr.su_addr.s_addr);
    951 				if ((addr & mask) != net)
    952 					continue;
    953 
    954 					/* check against hostname glob */
    955 			} else if (fnmatch(p, remotehost, FNM_CASEFOLD) != 0)
    956 				continue;
    957 		}
    958 
    959 					/* have a group specifier */
    960 		if ((p = strchr(word, ':')) != NULL) {
    961 			gid_t	*groups, *ng;
    962 			int	 gsize, i, found;
    963 
    964 			if (pw == NULL)
    965 				continue;	/* no match for unknown user */
    966 			*p++ = '\0';
    967 			groups = NULL;
    968 			gsize = 16;
    969 			do {
    970 				ng = realloc(groups, gsize * sizeof(gid_t));
    971 				if (ng == NULL)
    972 					fatal(
    973 					    "Local resource failure: realloc");
    974 				groups = ng;
    975 			} while (getgrouplist(pw->pw_name, pw->pw_gid,
    976 						groups, &gsize) == -1);
    977 			found = 0;
    978 			for (i = 0; i < gsize; i++) {
    979 				struct group *g;
    980 
    981 				if ((g = getgrgid(groups[i])) == NULL)
    982 					continue;
    983 				if (fnmatch(p, g->gr_name, 0) == 0) {
    984 					found = 1;
    985 					break;
    986 				}
    987 			}
    988 			free(groups);
    989 			if (!found)
    990 				continue;
    991 		}
    992 
    993 					/* check against username glob */
    994 		if (fnmatch(word, name, 0) != 0)
    995 			continue;
    996 
    997 		if (perm != NULL &&
    998 		    ((strcasecmp(perm, "allow") == 0) ||
    999 		     (strcasecmp(perm, "yes") == 0)))
   1000 			retval = 1;
   1001 		else if (perm != NULL &&
   1002 		    ((strcasecmp(perm, "deny") == 0) ||
   1003 		     (strcasecmp(perm, "no") == 0)))
   1004 			retval = 0;
   1005 		else
   1006 			retval = !def;
   1007 		if (!EMPTYSTR(class) && retclass != NULL)
   1008 			*retclass = xstrdup(class);
   1009 		free(buf);
   1010 		break;
   1011 	}
   1012 	(void) fclose(fd);
   1013 	return (retval);
   1014 }
   1015 
   1016 /*
   1017  * Check if user is allowed by /etc/ftpusers
   1018  * returns 1 for yes, 0 for no
   1019  *
   1020  * NOTE: needs struct passwd *pw setup (for checkuser())
   1021  */
   1022 static int
   1023 checkaccess(const char *name)
   1024 {
   1025 
   1026 	return (checkuser(_NAME_FTPUSERS, name, 1, 0, NULL));
   1027 }
   1028 
   1029 static void
   1030 login_utmp(const char *line, const char *name, const char *host,
   1031     struct sockinet *haddr)
   1032 {
   1033 #if defined(SUPPORT_UTMPX) || defined(SUPPORT_UTMP)
   1034 	struct timeval tv;
   1035 	(void)gettimeofday(&tv, NULL);
   1036 #endif
   1037 #ifdef SUPPORT_UTMPX
   1038 	if (doutmp) {
   1039 		(void)memset(&utmpx, 0, sizeof(utmpx));
   1040 		utmpx.ut_tv = tv;
   1041 		utmpx.ut_pid = getpid();
   1042 		utmpx.ut_id[0] = 'f';
   1043 		utmpx.ut_id[1] = 't';
   1044 		utmpx.ut_id[2] = 'p';
   1045 		utmpx.ut_id[3] = '*';
   1046 		utmpx.ut_type = USER_PROCESS;
   1047 		(void)strncpy(utmpx.ut_name, name, sizeof(utmpx.ut_name));
   1048 		(void)strncpy(utmpx.ut_line, line, sizeof(utmpx.ut_line));
   1049 		(void)strncpy(utmpx.ut_host, host, sizeof(utmpx.ut_host));
   1050 		(void)memcpy(&utmpx.ut_ss, &haddr->si_su, haddr->su_len);
   1051 		ftpd_loginx(&utmpx);
   1052 	}
   1053 	if (dowtmp)
   1054 		ftpd_logwtmpx(line, name, host, haddr, 0, USER_PROCESS);
   1055 #endif
   1056 #ifdef SUPPORT_UTMP
   1057 	if (doutmp) {
   1058 		(void)memset(&utmp, 0, sizeof(utmp));
   1059 		(void)time(&utmp.ut_time);
   1060 		(void)strncpy(utmp.ut_name, name, sizeof(utmp.ut_name));
   1061 		(void)strncpy(utmp.ut_line, line, sizeof(utmp.ut_line));
   1062 		(void)strncpy(utmp.ut_host, host, sizeof(utmp.ut_host));
   1063 		ftpd_login(&utmp);
   1064 	}
   1065 	if (dowtmp)
   1066 		ftpd_logwtmp(line, name, host);
   1067 #endif
   1068 }
   1069 
   1070 static void
   1071 logout_utmp(void)
   1072 {
   1073 	int okwtmp = dowtmp;
   1074 	if (logged_in) {
   1075 		if (doutmp) {
   1076 #ifdef SUPPORT_UTMPX
   1077 			okwtmp = logoutx(ttyline, 0, DEAD_PROCESS) & dowtmp;
   1078 #endif
   1079 #ifdef SUPPORT_UTMP
   1080 			okwtmp = ftpd_logout(ttyline) & dowtmp;
   1081 #endif
   1082 		}
   1083 		if (okwtmp) {
   1084 #ifdef SUPPORT_UTMPX
   1085 			ftpd_logwtmpx(ttyline, "", "", NULL, 0,
   1086 			    DEAD_PROCESS);
   1087 #endif
   1088 #ifdef SUPPORT_UTMP
   1089 			ftpd_logwtmp(ttyline, "", "");
   1090 #endif
   1091 		}
   1092 	}
   1093 }
   1094 
   1095 /*
   1096  * Terminate login as previous user (if any), resetting state;
   1097  * used when USER command is given or login fails.
   1098  */
   1099 static void
   1100 end_login(void)
   1101 {
   1102 #ifdef USE_PAM
   1103 	int e;
   1104 #endif
   1105 	logout_utmp();
   1106 	show_chdir_messages(-1);		/* flush chdir cache */
   1107 	if (pw != NULL && pw->pw_passwd != NULL)
   1108 		memset(pw->pw_passwd, 0, strlen(pw->pw_passwd));
   1109 	pw = NULL;
   1110 	logged_in = 0;
   1111 	askpasswd = 0;
   1112 	permitted = 0;
   1113 	quietmessages = 0;
   1114 	gidcount = 0;
   1115 	curclass.type = CLASS_REAL;
   1116 	(void) seteuid((uid_t)0);
   1117 #ifdef	LOGIN_CAP
   1118 	setusercontext(NULL, getpwuid(0), 0,
   1119 		       LOGIN_SETPRIORITY|LOGIN_SETRESOURCES|LOGIN_SETUMASK);
   1120 #endif
   1121 #ifdef USE_PAM
   1122 	if (pamh) {
   1123 		if ((e = pam_setcred(pamh, PAM_DELETE_CRED)) != PAM_SUCCESS)
   1124 			syslog(LOG_ERR, "pam_setcred: %s",
   1125 			    pam_strerror(pamh, e));
   1126 		if ((e = pam_close_session(pamh,0)) != PAM_SUCCESS)
   1127 			syslog(LOG_ERR, "pam_close_session: %s",
   1128 			    pam_strerror(pamh, e));
   1129 		if ((e = pam_end(pamh, e)) != PAM_SUCCESS)
   1130 			syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
   1131 		pamh = NULL;
   1132 	}
   1133 #endif
   1134 }
   1135 
   1136 void
   1137 pass(const char *passwd)
   1138 {
   1139 	int		 rval;
   1140 	char		 root[MAXPATHLEN];
   1141 #ifdef	LOGIN_CAP
   1142 	login_cap_t *lc = NULL;
   1143 #endif
   1144 #ifdef USE_PAM
   1145 	int e;
   1146 #endif
   1147 	if (logged_in || askpasswd == 0) {
   1148 		reply(503, "Login with USER first.");
   1149 		return;
   1150 	}
   1151 	askpasswd = 0;
   1152 	if (curclass.type != CLASS_GUEST) {
   1153 			/* "ftp" is the only account allowed with no password */
   1154 		if (pw == NULL) {
   1155 			rval = 1;	/* failure below */
   1156 			goto skip;
   1157 		}
   1158 #ifdef USE_PAM
   1159 		rval = auth_pam(&pw, passwd);
   1160 #ifdef notdef
   1161 		/* If PAM fails, we proceed with other authentications */
   1162 		if (rval >= 0) {
   1163 			goto skip;
   1164 		}
   1165 #else
   1166 		/* If PAM fails, that's it */
   1167 		goto skip;
   1168 #endif
   1169 #endif
   1170 #if defined(KERBEROS)
   1171 		if (klogin(pw, "", hostname, (char *)passwd) == 0) {
   1172 			rval = 0;
   1173 			goto skip;
   1174 		}
   1175 #endif
   1176 #if defined(KERBEROS5)
   1177 		if (k5login(pw, "", hostname, (char *)passwd) == 0) {
   1178 			rval = 0;
   1179 			goto skip;
   1180 		}
   1181 #endif
   1182 #ifdef SKEY
   1183 		if (skey_haskey(pw->pw_name) == 0) {
   1184 			char *p;
   1185 			int r;
   1186 
   1187 			p = xstrdup(passwd);
   1188 			r = skey_passcheck(pw->pw_name, p);
   1189 			free(p);
   1190 			if (r != -1) {
   1191 				rval = 0;
   1192 				goto skip;
   1193 			}
   1194 		}
   1195 #endif
   1196 		if (!sflag)
   1197 			rval = checkpassword(pw, passwd);
   1198 		else
   1199 			rval = 1;
   1200 
   1201  skip:
   1202 
   1203 			/*
   1204 			 * If rval > 0, the user failed the authentication check
   1205 			 * above.  If rval == 0, either Kerberos or local
   1206 			 * authentication succeeded.
   1207 			 */
   1208 		if (rval) {
   1209 			reply(530, "%s", rval == 2 ? "Password expired." :
   1210 			    "Login incorrect.");
   1211 			if (logging) {
   1212 				syslog(LOG_NOTICE,
   1213 				    "FTP LOGIN FAILED FROM %s", remotehost);
   1214 				syslog(LOG_AUTHPRIV | LOG_NOTICE,
   1215 				    "FTP LOGIN FAILED FROM %s, %s",
   1216 				    remotehost, curname);
   1217 			}
   1218 			pw = NULL;
   1219 			if (login_attempts++ >= 5) {
   1220 				syslog(LOG_NOTICE,
   1221 				    "repeated login failures from %s",
   1222 				    remotehost);
   1223 				exit(0);
   1224 			}
   1225 			return;
   1226 		}
   1227 	}
   1228 
   1229 			/* password ok; check if anything else prevents login */
   1230 	if (! permitted) {
   1231 		reply(530, "User %s may not use FTP.", pw->pw_name);
   1232 		if (logging)
   1233 			syslog(LOG_NOTICE, "FTP LOGIN REFUSED FROM %s, %s",
   1234 			    remotehost, pw->pw_name);
   1235 		goto bad;
   1236 	}
   1237 
   1238 	login_attempts = 0;		/* this time successful */
   1239 	if (setegid((gid_t)pw->pw_gid) < 0) {
   1240 		reply(550, "Can't set gid.");
   1241 		goto bad;
   1242 	}
   1243 #ifdef	LOGIN_CAP
   1244 	if ((lc = login_getpwclass(pw)) != NULL) {
   1245 #ifdef notyet
   1246 		char	remote_ip[NI_MAXHOST];
   1247 
   1248 		if (getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
   1249 			remote_ip, sizeof(remote_ip) - 1, NULL, 0,
   1250 			NI_NUMERICHOST))
   1251 				*remote_ip = 0;
   1252 		remote_ip[sizeof(remote_ip) - 1] = 0;
   1253 		if (!auth_hostok(lc, remotehost, remote_ip)) {
   1254 			syslog(LOG_INFO|LOG_AUTH,
   1255 			    "FTP LOGIN FAILED (HOST) as %s: permission denied.",
   1256 			    pw->pw_name);
   1257 			reply(530, "Permission denied.");
   1258 			pw = NULL;
   1259 			return;
   1260 		}
   1261 		if (!auth_timeok(lc, time(NULL))) {
   1262 			reply(530, "Login not available right now.");
   1263 			pw = NULL;
   1264 			return;
   1265 		}
   1266 #endif
   1267 	}
   1268 	setsid();
   1269 	setusercontext(lc, pw, 0,
   1270 		LOGIN_SETLOGIN|LOGIN_SETGROUP|LOGIN_SETPRIORITY|
   1271 		LOGIN_SETRESOURCES|LOGIN_SETUMASK);
   1272 #else
   1273 	(void) initgroups(pw->pw_name, pw->pw_gid);
   1274 			/* cache groups for cmds.c::matchgroup() */
   1275 #endif
   1276 #ifdef USE_PAM
   1277 	if (pamh) {
   1278 		if ((e = pam_open_session(pamh, 0)) != PAM_SUCCESS) {
   1279 			syslog(LOG_ERR, "pam_open_session: %s",
   1280 			    pam_strerror(pamh, e));
   1281 		} else if ((e = pam_setcred(pamh, PAM_ESTABLISH_CRED))
   1282 		    != PAM_SUCCESS) {
   1283 			syslog(LOG_ERR, "pam_setcred: %s",
   1284 			    pam_strerror(pamh, e));
   1285 		}
   1286 	}
   1287 #endif
   1288 	gidcount = getgroups(0, NULL);
   1289 	if (gidlist)
   1290 		free(gidlist);
   1291 	gidlist = malloc(gidcount * sizeof *gidlist);
   1292 	gidcount = getgroups(gidcount, gidlist);
   1293 
   1294 	/* open utmp/wtmp before chroot */
   1295 	login_utmp(ttyline, pw->pw_name, remotehost, &his_addr);
   1296 
   1297 	logged_in = 1;
   1298 
   1299 	connections = 1;
   1300 	if (dopidfile)
   1301 		count_users();
   1302 	if (curclass.limit != -1 && connections > curclass.limit) {
   1303 		if (! EMPTYSTR(curclass.limitfile))
   1304 			(void)display_file(conffilename(curclass.limitfile),
   1305 			    530);
   1306 		reply(530,
   1307 		    "User %s access denied, connection limit of " LLF
   1308 		    " reached.",
   1309 		    pw->pw_name, (LLT)curclass.limit);
   1310 		syslog(LOG_NOTICE,
   1311 		    "Maximum connection limit of " LLF
   1312 		    " for class %s reached, login refused for %s",
   1313 		    (LLT)curclass.limit, curclass.classname, pw->pw_name);
   1314 		goto bad;
   1315 	}
   1316 
   1317 	homedir[0] = '/';
   1318 	switch (curclass.type) {
   1319 	case CLASS_GUEST:
   1320 			/*
   1321 			 * We MUST do a chdir() after the chroot. Otherwise
   1322 			 * the old current directory will be accessible as "."
   1323 			 * outside the new root!
   1324 			 */
   1325 		format_path(root,
   1326 		    curclass.chroot ? curclass.chroot :
   1327 		    anondir ? anondir :
   1328 		    pw->pw_dir);
   1329 		format_path(homedir,
   1330 		    curclass.homedir ? curclass.homedir :
   1331 		    "/");
   1332 		if (EMPTYSTR(homedir))
   1333 			homedir[0] = '/';
   1334 		if (EMPTYSTR(root) || chroot(root) < 0) {
   1335 			syslog(LOG_NOTICE,
   1336 			    "GUEST user %s: can't chroot to %s: %m",
   1337 			    pw->pw_name, root);
   1338 			goto bad_guest;
   1339 		}
   1340 		if (chdir(homedir) < 0) {
   1341 			syslog(LOG_NOTICE,
   1342 			    "GUEST user %s: can't chdir to %s: %m",
   1343 			    pw->pw_name, homedir);
   1344  bad_guest:
   1345 			reply(550, "Can't set guest privileges.");
   1346 			goto bad;
   1347 		}
   1348 		break;
   1349 	case CLASS_CHROOT:
   1350 		format_path(root,
   1351 		    curclass.chroot ? curclass.chroot :
   1352 		    pw->pw_dir);
   1353 		format_path(homedir,
   1354 		    curclass.homedir ? curclass.homedir :
   1355 		    "/");
   1356 		if (EMPTYSTR(homedir))
   1357 			homedir[0] = '/';
   1358 		if (EMPTYSTR(root) || chroot(root) < 0) {
   1359 			syslog(LOG_NOTICE,
   1360 			    "CHROOT user %s: can't chroot to %s: %m",
   1361 			    pw->pw_name, root);
   1362 			goto bad_chroot;
   1363 		}
   1364 		if (chdir(homedir) < 0) {
   1365 			syslog(LOG_NOTICE,
   1366 			    "CHROOT user %s: can't chdir to %s: %m",
   1367 			    pw->pw_name, homedir);
   1368  bad_chroot:
   1369 			reply(550, "Can't change root.");
   1370 			goto bad;
   1371 		}
   1372 		break;
   1373 	case CLASS_REAL:
   1374 			/* only chroot REAL if explictly requested */
   1375 		if (! EMPTYSTR(curclass.chroot)) {
   1376 			format_path(root, curclass.chroot);
   1377 			if (EMPTYSTR(root) || chroot(root) < 0) {
   1378 				syslog(LOG_NOTICE,
   1379 				    "REAL user %s: can't chroot to %s: %m",
   1380 				    pw->pw_name, root);
   1381 				goto bad_chroot;
   1382 			}
   1383 		}
   1384 		format_path(homedir,
   1385 		    curclass.homedir ? curclass.homedir :
   1386 		    pw->pw_dir);
   1387 		if (EMPTYSTR(homedir) || chdir(homedir) < 0) {
   1388 			if (chdir("/") < 0) {
   1389 				syslog(LOG_NOTICE,
   1390 				    "REAL user %s: can't chdir to %s: %m",
   1391 				    pw->pw_name,
   1392 				    !EMPTYSTR(homedir) ?  homedir : "/");
   1393 				reply(530,
   1394 				    "User %s: can't change directory to %s.",
   1395 				    pw->pw_name,
   1396 				    !EMPTYSTR(homedir) ? homedir : "/");
   1397 				goto bad;
   1398 			} else {
   1399 				reply(-230,
   1400 				    "No directory! Logging in with home=/");
   1401 				homedir[0] = '/';
   1402 			}
   1403 		}
   1404 		break;
   1405 	}
   1406 #ifndef LOGIN_CAP
   1407 	setsid();
   1408 	setlogin(pw->pw_name);
   1409 #endif
   1410 	if (dropprivs ||
   1411 	    (curclass.type != CLASS_REAL &&
   1412 	    ntohs(ctrl_addr.su_port) > IPPORT_RESERVED + 1)) {
   1413 		dropprivs++;
   1414 		if (setgid((gid_t)pw->pw_gid) < 0) {
   1415 			reply(550, "Can't set gid.");
   1416 			goto bad;
   1417 		}
   1418 		if (setuid((uid_t)pw->pw_uid) < 0) {
   1419 			reply(550, "Can't set uid.");
   1420 			goto bad;
   1421 		}
   1422 	} else {
   1423 		if (seteuid((uid_t)pw->pw_uid) < 0) {
   1424 			reply(550, "Can't set uid.");
   1425 			goto bad;
   1426 		}
   1427 	}
   1428 	setenv("HOME", homedir, 1);
   1429 
   1430 	if (curclass.type == CLASS_GUEST && passwd[0] == '-')
   1431 		quietmessages = 1;
   1432 
   1433 			/*
   1434 			 * Display a login message, if it exists.
   1435 			 * N.B. reply(230,) must follow the message.
   1436 			 */
   1437 	if (! EMPTYSTR(curclass.motd))
   1438 		(void)display_file(conffilename(curclass.motd), 230);
   1439 	show_chdir_messages(230);
   1440 	if (curclass.type == CLASS_GUEST) {
   1441 		char *p;
   1442 
   1443 		reply(230, "Guest login ok, access restrictions apply.");
   1444 #if HAVE_SETPROCTITLE
   1445 		snprintf(proctitle, sizeof(proctitle),
   1446 		    "%s: anonymous/%s", remotehost, passwd);
   1447 		setproctitle("%s", proctitle);
   1448 #endif /* HAVE_SETPROCTITLE */
   1449 		if (logging)
   1450 			syslog(LOG_INFO,
   1451 			"ANONYMOUS FTP LOGIN FROM %s, %s (class: %s, type: %s)",
   1452 			    remotehost, passwd,
   1453 			    curclass.classname, CURCLASSTYPE);
   1454 			/* store guest password reply into pw_passwd */
   1455 		REASSIGN(pw->pw_passwd, xstrdup(passwd));
   1456 		for (p = pw->pw_passwd; *p; p++)
   1457 			if (!isgraph((unsigned char)*p))
   1458 				*p = '_';
   1459 	} else {
   1460 		reply(230, "User %s logged in.", pw->pw_name);
   1461 #if HAVE_SETPROCTITLE
   1462 		snprintf(proctitle, sizeof(proctitle),
   1463 		    "%s: %s", remotehost, pw->pw_name);
   1464 		setproctitle("%s", proctitle);
   1465 #endif /* HAVE_SETPROCTITLE */
   1466 		if (logging)
   1467 			syslog(LOG_INFO,
   1468 			    "FTP LOGIN FROM %s as %s (class: %s, type: %s)",
   1469 			    remotehost, pw->pw_name,
   1470 			    curclass.classname, CURCLASSTYPE);
   1471 	}
   1472 	(void) umask(curclass.umask);
   1473 #ifdef	LOGIN_CAP
   1474 	login_close(lc);
   1475 #endif
   1476 	return;
   1477 
   1478  bad:
   1479 #ifdef	LOGIN_CAP
   1480 	login_close(lc);
   1481 #endif
   1482 			/* Forget all about it... */
   1483 	end_login();
   1484 }
   1485 
   1486 void
   1487 retrieve(char *argv[], const char *name)
   1488 {
   1489 	FILE *fin, *dout;
   1490 	struct stat st;
   1491 	int (*closefunc)(FILE *) = NULL;
   1492 	int dolog, sendrv, closerv, stderrfd, isconversion, isdata, isls;
   1493 	struct timeval start, finish, td, *tdp;
   1494 	struct rusage rusage_before, rusage_after;
   1495 	const char *dispname;
   1496 	char *error;
   1497 
   1498 	sendrv = closerv = stderrfd = -1;
   1499 	isconversion = isdata = isls = dolog = 0;
   1500 	tdp = NULL;
   1501 	dispname = name;
   1502 	fin = dout = NULL;
   1503 	error = NULL;
   1504 	if (argv == NULL) {		/* if not running a command ... */
   1505 		dolog = 1;
   1506 		isdata = 1;
   1507 		fin = fopen(name, "r");
   1508 		closefunc = fclose;
   1509 		if (fin == NULL)	/* doesn't exist?; try a conversion */
   1510 			argv = do_conversion(name);
   1511 		if (argv != NULL) {
   1512 			isconversion++;
   1513 			syslog(LOG_DEBUG, "get command: '%s' on '%s'",
   1514 			    argv[0], name);
   1515 		}
   1516 	}
   1517 	if (argv != NULL) {
   1518 		char temp[MAXPATHLEN];
   1519 
   1520 		if (strcmp(argv[0], INTERNAL_LS) == 0) {
   1521 			isls = 1;
   1522 			stderrfd = -1;
   1523 		} else {
   1524 			(void)snprintf(temp, sizeof(temp), "%s", TMPFILE);
   1525 			stderrfd = mkstemp(temp);
   1526 			if (stderrfd != -1)
   1527 				(void)unlink(temp);
   1528 		}
   1529 		dispname = argv[0];
   1530 		fin = ftpd_popen(argv, "r", stderrfd);
   1531 		closefunc = ftpd_pclose;
   1532 		st.st_size = -1;
   1533 		st.st_blksize = BUFSIZ;
   1534 	}
   1535 	if (fin == NULL) {
   1536 		if (errno != 0) {
   1537 			perror_reply(550, dispname);
   1538 			if (dolog)
   1539 				logxfer("get", -1, name, NULL, NULL,
   1540 				    strerror(errno));
   1541 		}
   1542 		goto cleanupretrieve;
   1543 	}
   1544 	byte_count = -1;
   1545 	if (argv == NULL
   1546 	    && (fstat(fileno(fin), &st) < 0 || !S_ISREG(st.st_mode))) {
   1547 		error = "Not a plain file";
   1548 		reply(550, "%s: %s.", dispname, error);
   1549 		goto done;
   1550 	}
   1551 	if (restart_point) {
   1552 		if (type == TYPE_A) {
   1553 			off_t i;
   1554 			int c;
   1555 
   1556 			for (i = 0; i < restart_point; i++) {
   1557 				if ((c=getc(fin)) == EOF) {
   1558 					error = strerror(errno);
   1559 					perror_reply(550, dispname);
   1560 					goto done;
   1561 				}
   1562 				if (c == '\n')
   1563 					i++;
   1564 			}
   1565 		} else if (lseek(fileno(fin), restart_point, SEEK_SET) < 0) {
   1566 			error = strerror(errno);
   1567 			perror_reply(550, dispname);
   1568 			goto done;
   1569 		}
   1570 	}
   1571 	dout = dataconn(dispname, st.st_size, "w");
   1572 	if (dout == NULL)
   1573 		goto done;
   1574 
   1575 	(void)getrusage(RUSAGE_SELF, &rusage_before);
   1576 	(void)gettimeofday(&start, NULL);
   1577 	sendrv = send_data(fin, dout, &st, isdata);
   1578 	(void)gettimeofday(&finish, NULL);
   1579 	(void)getrusage(RUSAGE_SELF, &rusage_after);
   1580 	closedataconn(dout);		/* close now to affect timing stats */
   1581 	timersub(&finish, &start, &td);
   1582 	tdp = &td;
   1583  done:
   1584 	if (dolog) {
   1585 		logxfer("get", byte_count, name, NULL, tdp, error);
   1586 		if (tdp != NULL)
   1587 			logrusage(&rusage_before, &rusage_after);
   1588 	}
   1589 	closerv = (*closefunc)(fin);
   1590 	if (sendrv == 0) {
   1591 		FILE *errf;
   1592 		struct stat sb;
   1593 
   1594 		if (!isls && argv != NULL && closerv != 0) {
   1595 			reply(-226,
   1596 			    "Command returned an exit status of %d",
   1597 			    closerv);
   1598 			if (isconversion)
   1599 				syslog(LOG_WARNING,
   1600 				    "retrieve command: '%s' returned %d",
   1601 				    argv[0], closerv);
   1602 		}
   1603 		if (!isls && argv != NULL && stderrfd != -1 &&
   1604 		    (fstat(stderrfd, &sb) == 0) && sb.st_size > 0 &&
   1605 		    ((errf = fdopen(stderrfd, "r")) != NULL)) {
   1606 			char *cp, line[LINE_MAX];
   1607 
   1608 			reply(-226, "Command error messages:");
   1609 			rewind(errf);
   1610 			while (fgets(line, sizeof(line), errf) != NULL) {
   1611 				if ((cp = strchr(line, '\n')) != NULL)
   1612 					*cp = '\0';
   1613 				reply(0, "  %s", line);
   1614 			}
   1615 			(void) fflush(stdout);
   1616 			(void) fclose(errf);
   1617 				/* a reply(226,) must follow */
   1618 		}
   1619 		reply(226, "Transfer complete.");
   1620 	}
   1621  cleanupretrieve:
   1622 	if (stderrfd != -1)
   1623 		(void)close(stderrfd);
   1624 	if (isconversion)
   1625 		free(argv);
   1626 }
   1627 
   1628 void
   1629 store(const char *name, const char *fmode, int unique)
   1630 {
   1631 	FILE *fout, *din;
   1632 	struct stat st;
   1633 	int (*closefunc)(FILE *);
   1634 	struct timeval start, finish, td, *tdp;
   1635 	char *desc, *error;
   1636 
   1637 	din = NULL;
   1638 	desc = (*fmode == 'w') ? "put" : "append";
   1639 	error = NULL;
   1640 	if (unique && stat(name, &st) == 0 &&
   1641 	    (name = gunique(name)) == NULL) {
   1642 		logxfer(desc, -1, name, NULL, NULL,
   1643 		    "cannot create unique file");
   1644 		goto cleanupstore;
   1645 	}
   1646 
   1647 	if (restart_point)
   1648 		fmode = "r+";
   1649 	fout = fopen(name, fmode);
   1650 	closefunc = fclose;
   1651 	tdp = NULL;
   1652 	if (fout == NULL) {
   1653 		perror_reply(553, name);
   1654 		logxfer(desc, -1, name, NULL, NULL, strerror(errno));
   1655 		goto cleanupstore;
   1656 	}
   1657 	byte_count = -1;
   1658 	if (restart_point) {
   1659 		if (type == TYPE_A) {
   1660 			off_t i;
   1661 			int c;
   1662 
   1663 			for (i = 0; i < restart_point; i++) {
   1664 				if ((c=getc(fout)) == EOF) {
   1665 					error = strerror(errno);
   1666 					perror_reply(550, name);
   1667 					goto done;
   1668 				}
   1669 				if (c == '\n')
   1670 					i++;
   1671 			}
   1672 			/*
   1673 			 * We must do this seek to "current" position
   1674 			 * because we are changing from reading to
   1675 			 * writing.
   1676 			 */
   1677 			if (fseek(fout, 0L, SEEK_CUR) < 0) {
   1678 				error = strerror(errno);
   1679 				perror_reply(550, name);
   1680 				goto done;
   1681 			}
   1682 		} else if (lseek(fileno(fout), restart_point, SEEK_SET) < 0) {
   1683 			error = strerror(errno);
   1684 			perror_reply(550, name);
   1685 			goto done;
   1686 		}
   1687 	}
   1688 	din = dataconn(name, (off_t)-1, "r");
   1689 	if (din == NULL)
   1690 		goto done;
   1691 	(void)gettimeofday(&start, NULL);
   1692 	if (receive_data(din, fout) == 0) {
   1693 		if (unique)
   1694 			reply(226, "Transfer complete (unique file name:%s).",
   1695 			    name);
   1696 		else
   1697 			reply(226, "Transfer complete.");
   1698 	}
   1699 	(void)gettimeofday(&finish, NULL);
   1700 	closedataconn(din);		/* close now to affect timing stats */
   1701 	timersub(&finish, &start, &td);
   1702 	tdp = &td;
   1703  done:
   1704 	logxfer(desc, byte_count, name, NULL, tdp, error);
   1705 	(*closefunc)(fout);
   1706  cleanupstore:
   1707 	;
   1708 }
   1709 
   1710 static FILE *
   1711 getdatasock(const char *fmode)
   1712 {
   1713 	int		on, s, t, tries;
   1714 	in_port_t	port;
   1715 
   1716 	on = 1;
   1717 	if (data >= 0)
   1718 		return (fdopen(data, fmode));
   1719 	if (! dropprivs)
   1720 		(void) seteuid((uid_t)0);
   1721 	s = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
   1722 	if (s < 0)
   1723 		goto bad;
   1724 	if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
   1725 	    (char *) &on, sizeof(on)) < 0)
   1726 		goto bad;
   1727 	if (setsockopt(s, SOL_SOCKET, SO_KEEPALIVE,
   1728 	    (char *) &on, sizeof(on)) < 0)
   1729 		goto bad;
   1730 			/* anchor socket to avoid multi-homing problems */
   1731 	data_source = ctrl_addr;
   1732 			/*
   1733 			 * By default source port for PORT connctions is
   1734 			 * ctrlport-1 (see RFC959 section 5.2).
   1735 			 * However, if privs have been dropped and that
   1736 			 * would be < IPPORT_RESERVED, use a random port
   1737 			 * instead.
   1738 			 */
   1739 	if (dataport)
   1740 		port = dataport;
   1741 	else
   1742 		port = ntohs(ctrl_addr.su_port) - 1;
   1743 	if (dropprivs && port < IPPORT_RESERVED)
   1744 		port = 0;		/* use random port */
   1745 	data_source.su_port = htons(port);
   1746 
   1747 	for (tries = 1; ; tries++) {
   1748 		if (bind(s, (struct sockaddr *)&data_source.si_su,
   1749 		    data_source.su_len) >= 0)
   1750 			break;
   1751 		if (errno != EADDRINUSE || tries > 10)
   1752 			goto bad;
   1753 		sleep(tries);
   1754 	}
   1755 	if (! dropprivs)
   1756 		(void) seteuid((uid_t)pw->pw_uid);
   1757 #ifdef IP_TOS
   1758 	if (!mapped && ctrl_addr.su_family == AF_INET) {
   1759 		on = IPTOS_THROUGHPUT;
   1760 		if (setsockopt(s, IPPROTO_IP, IP_TOS, (char *)&on,
   1761 			       sizeof(int)) < 0)
   1762 			syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
   1763 	}
   1764 #endif
   1765 	return (fdopen(s, fmode));
   1766  bad:
   1767 		/* Return the real value of errno (close may change it) */
   1768 	t = errno;
   1769 	if (! dropprivs)
   1770 		(void) seteuid((uid_t)pw->pw_uid);
   1771 	(void) close(s);
   1772 	errno = t;
   1773 	return (NULL);
   1774 }
   1775 
   1776 FILE *
   1777 dataconn(const char *name, off_t size, const char *fmode)
   1778 {
   1779 	char sizebuf[32];
   1780 	FILE *file;
   1781 	int retry, tos, keepalive, conerrno;
   1782 
   1783 	file_size = size;
   1784 	byte_count = 0;
   1785 	if (size != (off_t) -1)
   1786 		(void)snprintf(sizebuf, sizeof(sizebuf), " (" LLF " byte%s)",
   1787 		    (LLT)size, PLURAL(size));
   1788 	else
   1789 		sizebuf[0] = '\0';
   1790 	if (pdata >= 0) {
   1791 		struct sockinet from;
   1792 		int s, fromlen = sizeof(from.su_len);
   1793 
   1794 		(void) alarm(curclass.timeout);
   1795 		s = accept(pdata, (struct sockaddr *)&from.si_su, &fromlen);
   1796 		(void) alarm(0);
   1797 		if (s < 0) {
   1798 			reply(425, "Can't open data connection.");
   1799 			(void) close(pdata);
   1800 			pdata = -1;
   1801 			return (NULL);
   1802 		}
   1803 		(void) close(pdata);
   1804 		pdata = s;
   1805 		switch (from.su_family) {
   1806 		case AF_INET:
   1807 #ifdef IP_TOS
   1808 			if (!mapped) {
   1809 				tos = IPTOS_THROUGHPUT;
   1810 				(void) setsockopt(s, IPPROTO_IP, IP_TOS,
   1811 				    (char *)&tos, sizeof(int));
   1812 			}
   1813 			break;
   1814 #endif
   1815 		}
   1816 		/* Set keepalives on the socket to detect dropped conns. */
   1817 #ifdef SO_KEEPALIVE
   1818 		keepalive = 1;
   1819 		(void) setsockopt(s, SOL_SOCKET, SO_KEEPALIVE,
   1820 		    (char *)&keepalive, sizeof(int));
   1821 #endif
   1822 		reply(150, "Opening %s mode data connection for '%s'%s.",
   1823 		     type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
   1824 		return (fdopen(pdata, fmode));
   1825 	}
   1826 	if (data >= 0) {
   1827 		reply(125, "Using existing data connection for '%s'%s.",
   1828 		    name, sizebuf);
   1829 		usedefault = 1;
   1830 		return (fdopen(data, fmode));
   1831 	}
   1832 	if (usedefault)
   1833 		data_dest = his_addr;
   1834 	usedefault = 1;
   1835 	retry = conerrno = 0;
   1836 	do {
   1837 		file = getdatasock(fmode);
   1838 		if (file == NULL) {
   1839 			char hbuf[NI_MAXHOST];
   1840 			char pbuf[NI_MAXSERV];
   1841 
   1842 			if (getnameinfo((struct sockaddr *)&data_source.si_su,
   1843 			    data_source.su_len, hbuf, sizeof(hbuf), pbuf,
   1844 			    sizeof(pbuf), NI_NUMERICHOST | NI_NUMERICSERV))
   1845 				strlcpy(hbuf, "?", sizeof(hbuf));
   1846 			reply(425, "Can't create data socket (%s,%s): %s.",
   1847 			      hbuf, pbuf, strerror(errno));
   1848 			return (NULL);
   1849 		}
   1850 		data = fileno(file);
   1851 		conerrno = 0;
   1852 		if (connect(data, (struct sockaddr *)&data_dest.si_su,
   1853 		    data_dest.su_len) == 0)
   1854 			break;
   1855 		conerrno = errno;
   1856 		(void) fclose(file);
   1857 		file = NULL;
   1858 		data = -1;
   1859 		if (conerrno == EADDRINUSE) {
   1860 			sleep((unsigned) swaitint);
   1861 			retry += swaitint;
   1862 		} else {
   1863 			break;
   1864 		}
   1865 	} while (retry <= swaitmax);
   1866 	if (conerrno != 0) {
   1867 		perror_reply(425, "Can't build data connection");
   1868 		return (NULL);
   1869 	}
   1870 	reply(150, "Opening %s mode data connection for '%s'%s.",
   1871 	     type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
   1872 	return (file);
   1873 }
   1874 
   1875 void
   1876 closedataconn(FILE *fd)
   1877 {
   1878 
   1879 	if (fd == NULL)
   1880 		return;
   1881 	(void)fclose(fd);
   1882 	data = -1;
   1883 	if (pdata >= 0)
   1884 		(void)close(pdata);
   1885 	pdata = -1;
   1886 }
   1887 
   1888 int
   1889 write_data(int fd, char *buf, size_t size, off_t *bufrem,
   1890     struct timeval *then, int isdata)
   1891 {
   1892 	struct timeval now, td;
   1893 	ssize_t c;
   1894 
   1895 	while (size > 0) {
   1896 		c = size;
   1897 		if (curclass.writesize) {
   1898 			if (curclass.writesize < c)
   1899 				c = curclass.writesize;
   1900 		}
   1901 		if (curclass.rateget) {
   1902 			if (*bufrem < c)
   1903 				c = *bufrem;
   1904 		}
   1905 		(void) alarm(curclass.timeout);
   1906 		c = write(fd, buf, c);
   1907 		if (c <= 0)
   1908 			return (1);
   1909 		buf += c;
   1910 		size -= c;
   1911 		byte_count += c;
   1912 		if (isdata) {
   1913 			total_data_out += c;
   1914 			total_data += c;
   1915 		}
   1916 		total_bytes_out += c;
   1917 		total_bytes += c;
   1918 		if (curclass.rateget) {
   1919 			*bufrem -= c;
   1920 			if (*bufrem == 0) {
   1921 				(void)gettimeofday(&now, NULL);
   1922 				timersub(&now, then, &td);
   1923 				if (td.tv_sec == 0) {
   1924 					usleep(1000000 - td.tv_usec);
   1925 					(void)gettimeofday(then, NULL);
   1926 				} else
   1927 					*then = now;
   1928 				*bufrem = curclass.rateget;
   1929 			}
   1930 		}
   1931 	}
   1932 	return (0);
   1933 }
   1934 
   1935 static enum send_status
   1936 send_data_with_read(int filefd, int netfd, const struct stat *st, int isdata)
   1937 {
   1938 	struct timeval then;
   1939 	off_t bufrem;
   1940 	size_t readsize;
   1941 	char *buf;
   1942 	int c, error;
   1943 
   1944 	if (curclass.readsize)
   1945 		readsize = curclass.readsize;
   1946 	else
   1947 		readsize = (size_t)st->st_blksize;
   1948 	if ((buf = malloc(readsize)) == NULL) {
   1949 		perror_reply(451, "Local resource failure: malloc");
   1950 		return (SS_NO_TRANSFER);
   1951 	}
   1952 
   1953 	if (curclass.rateget) {
   1954 		bufrem = curclass.rateget;
   1955 		(void)gettimeofday(&then, NULL);
   1956 	}
   1957 	while (1) {
   1958 		(void) alarm(curclass.timeout);
   1959 		c = read(filefd, buf, readsize);
   1960 		if (c == 0)
   1961 			error = SS_SUCCESS;
   1962 		else if (c < 0)
   1963 			error = SS_FILE_ERROR;
   1964 		else if (write_data(netfd, buf, c, &bufrem, &then, isdata))
   1965 			error = SS_DATA_ERROR;
   1966 		else if (urgflag && handleoobcmd())
   1967 			error = SS_ABORTED;
   1968 		else
   1969 			continue;
   1970 
   1971 		free(buf);
   1972 		return (error);
   1973 	}
   1974 }
   1975 
   1976 static enum send_status
   1977 send_data_with_mmap(int filefd, int netfd, const struct stat *st, int isdata)
   1978 {
   1979 	struct timeval then;
   1980 	off_t bufrem, filesize, off, origoff;
   1981 	size_t mapsize, winsize;
   1982 	int error, sendbufsize, sendlowat;
   1983 	void *win;
   1984 
   1985 	if (curclass.sendbufsize) {
   1986 		sendbufsize = curclass.sendbufsize;
   1987 		if (setsockopt(netfd, SOL_SOCKET, SO_SNDBUF,
   1988 		    &sendbufsize, sizeof(int)) == -1)
   1989 			syslog(LOG_WARNING, "setsockopt(SO_SNDBUF, %d): %m",
   1990 			    sendbufsize);
   1991 	}
   1992 
   1993 	if (curclass.sendlowat) {
   1994 		sendlowat = curclass.sendlowat;
   1995 		if (setsockopt(netfd, SOL_SOCKET, SO_SNDLOWAT,
   1996 		    &sendlowat, sizeof(int)) == -1)
   1997 			syslog(LOG_WARNING, "setsockopt(SO_SNDLOWAT, %d): %m",
   1998 			    sendlowat);
   1999 	}
   2000 
   2001 	winsize = curclass.mmapsize;
   2002 	filesize = st->st_size;
   2003 	if (debug)
   2004 		syslog(LOG_INFO, "mmapsize = %ld, writesize = %ld",
   2005 		    (long)winsize, (long)curclass.writesize);
   2006 	if (winsize == 0)
   2007 		goto try_read;
   2008 
   2009 	off = lseek(filefd, (off_t)0, SEEK_CUR);
   2010 	if (off == -1)
   2011 		goto try_read;
   2012 
   2013 	origoff = off;
   2014 	if (curclass.rateget) {
   2015 		bufrem = curclass.rateget;
   2016 		(void)gettimeofday(&then, NULL);
   2017 	}
   2018 	while (1) {
   2019 		mapsize = MIN(filesize - off, winsize);
   2020 		if (mapsize == 0)
   2021 			break;
   2022 		win = mmap(NULL, mapsize, PROT_READ,
   2023 		    MAP_FILE|MAP_SHARED, filefd, off);
   2024 		if (win == MAP_FAILED) {
   2025 			if (off == origoff)
   2026 				goto try_read;
   2027 			return (SS_FILE_ERROR);
   2028 		}
   2029 		(void) madvise(win, mapsize, MADV_SEQUENTIAL);
   2030 		error = write_data(netfd, win, mapsize, &bufrem, &then,
   2031 		    isdata);
   2032 		(void) madvise(win, mapsize, MADV_DONTNEED);
   2033 		munmap(win, mapsize);
   2034 		if (urgflag && handleoobcmd())
   2035 			return (SS_ABORTED);
   2036 		if (error)
   2037 			return (SS_DATA_ERROR);
   2038 		off += mapsize;
   2039 	}
   2040 	return (SS_SUCCESS);
   2041 
   2042  try_read:
   2043 	return (send_data_with_read(filefd, netfd, st, isdata));
   2044 }
   2045 
   2046 /*
   2047  * Tranfer the contents of "instr" to "outstr" peer using the appropriate
   2048  * encapsulation of the data subject to Mode, Structure, and Type.
   2049  *
   2050  * NB: Form isn't handled.
   2051  */
   2052 static int
   2053 send_data(FILE *instr, FILE *outstr, const struct stat *st, int isdata)
   2054 {
   2055 	int	 c, filefd, netfd, rval;
   2056 
   2057 	urgflag = 0;
   2058 	transflag = 1;
   2059 	rval = -1;
   2060 
   2061 	switch (type) {
   2062 
   2063 	case TYPE_A:
   2064  /* XXXLUKEM: rate limit ascii send (get) */
   2065 		(void) alarm(curclass.timeout);
   2066 		while ((c = getc(instr)) != EOF) {
   2067 			if (urgflag && handleoobcmd())
   2068 				goto cleanup_send_data;
   2069 			byte_count++;
   2070 			if (c == '\n') {
   2071 				if (ferror(outstr))
   2072 					goto data_err;
   2073 				(void) putc('\r', outstr);
   2074 				if (isdata) {
   2075 					total_data_out++;
   2076 					total_data++;
   2077 				}
   2078 				total_bytes_out++;
   2079 				total_bytes++;
   2080 			}
   2081 			(void) putc(c, outstr);
   2082 			if (isdata) {
   2083 				total_data_out++;
   2084 				total_data++;
   2085 			}
   2086 			total_bytes_out++;
   2087 			total_bytes++;
   2088 			if ((byte_count % 4096) == 0)
   2089 				(void) alarm(curclass.timeout);
   2090 		}
   2091 		(void) alarm(0);
   2092 		fflush(outstr);
   2093 		if (ferror(instr))
   2094 			goto file_err;
   2095 		if (ferror(outstr))
   2096 			goto data_err;
   2097 		rval = 0;
   2098 		goto cleanup_send_data;
   2099 
   2100 	case TYPE_I:
   2101 	case TYPE_L:
   2102 		filefd = fileno(instr);
   2103 		netfd = fileno(outstr);
   2104 		switch (send_data_with_mmap(filefd, netfd, st, isdata)) {
   2105 
   2106 		case SS_SUCCESS:
   2107 			break;
   2108 
   2109 		case SS_ABORTED:
   2110 		case SS_NO_TRANSFER:
   2111 			goto cleanup_send_data;
   2112 
   2113 		case SS_FILE_ERROR:
   2114 			goto file_err;
   2115 
   2116 		case SS_DATA_ERROR:
   2117 			goto data_err;
   2118 		}
   2119 		rval = 0;
   2120 		goto cleanup_send_data;
   2121 
   2122 	default:
   2123 		reply(550, "Unimplemented TYPE %d in send_data", type);
   2124 		goto cleanup_send_data;
   2125 	}
   2126 
   2127  data_err:
   2128 	(void) alarm(0);
   2129 	perror_reply(426, "Data connection");
   2130 	goto cleanup_send_data;
   2131 
   2132  file_err:
   2133 	(void) alarm(0);
   2134 	perror_reply(551, "Error on input file");
   2135 	goto cleanup_send_data;
   2136 
   2137  cleanup_send_data:
   2138 	(void) alarm(0);
   2139 	transflag = 0;
   2140 	urgflag = 0;
   2141 	if (isdata) {
   2142 		total_files_out++;
   2143 		total_files++;
   2144 	}
   2145 	total_xfers_out++;
   2146 	total_xfers++;
   2147 	return (rval);
   2148 }
   2149 
   2150 /*
   2151  * Transfer data from peer to "outstr" using the appropriate encapulation of
   2152  * the data subject to Mode, Structure, and Type.
   2153  *
   2154  * N.B.: Form isn't handled.
   2155  */
   2156 static int
   2157 receive_data(FILE *instr, FILE *outstr)
   2158 {
   2159 	int	c, bare_lfs, netfd, filefd, rval;
   2160 	off_t	byteswritten;
   2161 	char	buf[BUFSIZ];
   2162 	struct sigaction sa, sa_saved;
   2163 #ifdef __GNUC__
   2164 	(void) &bare_lfs;
   2165 #endif
   2166 
   2167 	memset(&sa, 0, sizeof(sa));
   2168 	sigfillset(&sa.sa_mask);
   2169 	sa.sa_flags = SA_RESTART;
   2170 	sa.sa_handler = lostconn;
   2171 	(void) sigaction(SIGALRM, &sa, &sa_saved);
   2172 
   2173 	bare_lfs = 0;
   2174 	urgflag = 0;
   2175 	transflag = 1;
   2176 	rval = -1;
   2177 	byteswritten = 0;
   2178 
   2179 #define FILESIZECHECK(x) \
   2180 			do { \
   2181 				if (curclass.maxfilesize != -1 && \
   2182 				    (x) > curclass.maxfilesize) { \
   2183 					errno = EFBIG; \
   2184 					goto file_err; \
   2185 				} \
   2186 			} while (0)
   2187 
   2188 	switch (type) {
   2189 
   2190 	case TYPE_I:
   2191 	case TYPE_L:
   2192 		netfd = fileno(instr);
   2193 		filefd = fileno(outstr);
   2194 		(void) alarm(curclass.timeout);
   2195 		if (curclass.rateput) {
   2196 			while (1) {
   2197 				int d;
   2198 				struct timeval then, now, td;
   2199 				off_t bufrem;
   2200 
   2201 				(void)gettimeofday(&then, NULL);
   2202 				errno = c = d = 0;
   2203 				for (bufrem = curclass.rateput; bufrem > 0; ) {
   2204 					if ((c = read(netfd, buf,
   2205 					    MIN(sizeof(buf), bufrem))) <= 0)
   2206 						goto recvdone;
   2207 					if (urgflag && handleoobcmd())
   2208 						goto cleanup_recv_data;
   2209 					FILESIZECHECK(byte_count + c);
   2210 					if ((d = write(filefd, buf, c)) != c)
   2211 						goto file_err;
   2212 					(void) alarm(curclass.timeout);
   2213 					bufrem -= c;
   2214 					byte_count += c;
   2215 					total_data_in += c;
   2216 					total_data += c;
   2217 					total_bytes_in += c;
   2218 					total_bytes += c;
   2219 				}
   2220 				(void)gettimeofday(&now, NULL);
   2221 				timersub(&now, &then, &td);
   2222 				if (td.tv_sec == 0)
   2223 					usleep(1000000 - td.tv_usec);
   2224 			}
   2225 		} else {
   2226 			while ((c = read(netfd, buf, sizeof(buf))) > 0) {
   2227 				if (urgflag && handleoobcmd())
   2228 					goto cleanup_recv_data;
   2229 				FILESIZECHECK(byte_count + c);
   2230 				if (write(filefd, buf, c) != c)
   2231 					goto file_err;
   2232 				(void) alarm(curclass.timeout);
   2233 				byte_count += c;
   2234 				total_data_in += c;
   2235 				total_data += c;
   2236 				total_bytes_in += c;
   2237 				total_bytes += c;
   2238 			}
   2239 		}
   2240  recvdone:
   2241 		if (c < 0)
   2242 			goto data_err;
   2243 		rval = 0;
   2244 		goto cleanup_recv_data;
   2245 
   2246 	case TYPE_E:
   2247 		reply(553, "TYPE E not implemented.");
   2248 		goto cleanup_recv_data;
   2249 
   2250 	case TYPE_A:
   2251 		(void) alarm(curclass.timeout);
   2252  /* XXXLUKEM: rate limit ascii receive (put) */
   2253 		while ((c = getc(instr)) != EOF) {
   2254 			if (urgflag && handleoobcmd())
   2255 				goto cleanup_recv_data;
   2256 			byte_count++;
   2257 			total_data_in++;
   2258 			total_data++;
   2259 			total_bytes_in++;
   2260 			total_bytes++;
   2261 			if ((byte_count % 4096) == 0)
   2262 				(void) alarm(curclass.timeout);
   2263 			if (c == '\n')
   2264 				bare_lfs++;
   2265 			while (c == '\r') {
   2266 				if (ferror(outstr))
   2267 					goto data_err;
   2268 				if ((c = getc(instr)) != '\n') {
   2269 					byte_count++;
   2270 					total_data_in++;
   2271 					total_data++;
   2272 					total_bytes_in++;
   2273 					total_bytes++;
   2274 					if ((byte_count % 4096) == 0)
   2275 						(void) alarm(curclass.timeout);
   2276 					byteswritten++;
   2277 					FILESIZECHECK(byteswritten);
   2278 					(void) putc ('\r', outstr);
   2279 					if (c == '\0' || c == EOF)
   2280 						goto contin2;
   2281 				}
   2282 			}
   2283 			byteswritten++;
   2284 			FILESIZECHECK(byteswritten);
   2285 			(void) putc(c, outstr);
   2286  contin2:	;
   2287 		}
   2288 		(void) alarm(0);
   2289 		fflush(outstr);
   2290 		if (ferror(instr))
   2291 			goto data_err;
   2292 		if (ferror(outstr))
   2293 			goto file_err;
   2294 		if (bare_lfs) {
   2295 			reply(-226,
   2296 			    "WARNING! %d bare linefeeds received in ASCII mode",
   2297 			    bare_lfs);
   2298 			reply(0, "File may not have transferred correctly.");
   2299 		}
   2300 		rval = 0;
   2301 		goto cleanup_recv_data;
   2302 
   2303 	default:
   2304 		reply(550, "Unimplemented TYPE %d in receive_data", type);
   2305 		goto cleanup_recv_data;
   2306 	}
   2307 #undef FILESIZECHECK
   2308 
   2309  data_err:
   2310 	(void) alarm(0);
   2311 	perror_reply(426, "Data Connection");
   2312 	goto cleanup_recv_data;
   2313 
   2314  file_err:
   2315 	(void) alarm(0);
   2316 	perror_reply(452, "Error writing file");
   2317 	goto cleanup_recv_data;
   2318 
   2319  cleanup_recv_data:
   2320 	(void) alarm(0);
   2321 	(void) sigaction(SIGALRM, &sa_saved, NULL);
   2322 	transflag = 0;
   2323 	urgflag = 0;
   2324 	total_files_in++;
   2325 	total_files++;
   2326 	total_xfers_in++;
   2327 	total_xfers++;
   2328 	return (rval);
   2329 }
   2330 
   2331 void
   2332 statcmd(void)
   2333 {
   2334 	struct sockinet *su = NULL;
   2335 	static char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
   2336 	u_char *a, *p;
   2337 	int ispassive, af;
   2338 	off_t otbi, otbo, otb;
   2339 
   2340 	a = p = (u_char *)NULL;
   2341 
   2342 	reply(-211, "%s FTP server status:", hostname);
   2343 	reply(0, "Version: %s", EMPTYSTR(version) ? "<suppressed>" : version);
   2344 	hbuf[0] = '\0';
   2345 	if (!getnameinfo((struct sockaddr *)&his_addr.si_su, his_addr.su_len,
   2346 			hbuf, sizeof(hbuf), NULL, 0, NI_NUMERICHOST)
   2347 	    && strcmp(remotehost, hbuf) != 0)
   2348 		reply(0, "Connected to %s (%s)", remotehost, hbuf);
   2349 	else
   2350 		reply(0, "Connected to %s", remotehost);
   2351 
   2352 	if (logged_in) {
   2353 		if (curclass.type == CLASS_GUEST)
   2354 			reply(0, "Logged in anonymously");
   2355 		else
   2356 			reply(0, "Logged in as %s%s", pw->pw_name,
   2357 			    curclass.type == CLASS_CHROOT ? " (chroot)" : "");
   2358 	} else if (askpasswd)
   2359 		reply(0, "Waiting for password");
   2360 	else
   2361 		reply(0, "Waiting for user name");
   2362 	cprintf(stdout, "    TYPE: %s", typenames[type]);
   2363 	if (type == TYPE_A || type == TYPE_E)
   2364 		cprintf(stdout, ", FORM: %s", formnames[form]);
   2365 	if (type == TYPE_L) {
   2366 #if NBBY == 8
   2367 		cprintf(stdout, " %d", NBBY);
   2368 #else
   2369 			/* XXX: `bytesize' needs to be defined in this case */
   2370 		cprintf(stdout, " %d", bytesize);
   2371 #endif
   2372 	}
   2373 	cprintf(stdout, "; STRUcture: %s; transfer MODE: %s\r\n",
   2374 	    strunames[stru], modenames[mode]);
   2375 	ispassive = 0;
   2376 	if (data != -1) {
   2377 		reply(0, "Data connection open");
   2378 		su = NULL;
   2379 	} else if (pdata != -1) {
   2380 		reply(0, "in Passive mode");
   2381 		if (curclass.advertise.su_len != 0)
   2382 			su = &curclass.advertise;
   2383 		else
   2384 			su = &pasv_addr;
   2385 		ispassive = 1;
   2386 		goto printaddr;
   2387 	} else if (usedefault == 0) {
   2388 		su = (struct sockinet *)&data_dest;
   2389 
   2390 		if (epsvall) {
   2391 			reply(0, "EPSV only mode (EPSV ALL)");
   2392 			goto epsvonly;
   2393 		}
   2394  printaddr:
   2395 							/* PASV/PORT */
   2396 		if (su->su_family == AF_INET) {
   2397 			a = (u_char *) &su->su_addr;
   2398 			p = (u_char *) &su->su_port;
   2399 #define UC(b) (((int) b) & 0xff)
   2400 			reply(0, "%s (%d,%d,%d,%d,%d,%d)",
   2401 				ispassive ? "PASV" : "PORT" ,
   2402 				UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
   2403 				UC(p[0]), UC(p[1]));
   2404 		}
   2405 
   2406 							/* LPSV/LPRT */
   2407 	    {
   2408 		int alen, i;
   2409 
   2410 		alen = 0;
   2411 		switch (su->su_family) {
   2412 		case AF_INET:
   2413 			a = (u_char *) &su->su_addr;
   2414 			p = (u_char *) &su->su_port;
   2415 			alen = sizeof(su->su_addr);
   2416 			af = 4;
   2417 			break;
   2418 #ifdef INET6
   2419 		case AF_INET6:
   2420 			a = (u_char *) &su->su_6addr;
   2421 			p = (u_char *) &su->su_port;
   2422 			alen = sizeof(su->su_6addr);
   2423 			af = 6;
   2424 			break;
   2425 #endif
   2426 		default:
   2427 			af = 0;
   2428 			break;
   2429 		}
   2430 		if (af) {
   2431 			cprintf(stdout, "    %s (%d,%d",
   2432 			    ispassive ? "LPSV" : "LPRT", af, alen);
   2433 			for (i = 0; i < alen; i++)
   2434 				cprintf(stdout, ",%d", UC(a[i]));
   2435 			cprintf(stdout, ",%d,%d,%d)\r\n",
   2436 			    2, UC(p[0]), UC(p[1]));
   2437 #undef UC
   2438 		}
   2439 	    }
   2440 
   2441 		/* EPRT/EPSV */
   2442  epsvonly:
   2443 		af = af2epsvproto(su->su_family);
   2444 		hbuf[0] = '\0';
   2445 		if (af > 0) {
   2446 			struct sockinet tmp;
   2447 
   2448 			tmp = *su;
   2449 #ifdef INET6
   2450 			if (tmp.su_family == AF_INET6)
   2451 				tmp.su_scope_id = 0;
   2452 #endif
   2453 			if (getnameinfo((struct sockaddr *)&tmp.si_su,
   2454 			    tmp.su_len, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf),
   2455 			    NI_NUMERICHOST | NI_NUMERICSERV) == 0)
   2456 				reply(0, "%s (|%d|%s|%s|)",
   2457 				    ispassive ? "EPSV" : "EPRT",
   2458 				    af, hbuf, sbuf);
   2459 		}
   2460 	} else
   2461 		reply(0, "No data connection");
   2462 
   2463 	if (logged_in) {
   2464 		reply(0,
   2465 		    "Data sent:        " LLF " byte%s in " LLF " file%s",
   2466 		    (LLT)total_data_out, PLURAL(total_data_out),
   2467 		    (LLT)total_files_out, PLURAL(total_files_out));
   2468 		reply(0,
   2469 		    "Data received:    " LLF " byte%s in " LLF " file%s",
   2470 		    (LLT)total_data_in, PLURAL(total_data_in),
   2471 		    (LLT)total_files_in, PLURAL(total_files_in));
   2472 		reply(0,
   2473 		    "Total data:       " LLF " byte%s in " LLF " file%s",
   2474 		    (LLT)total_data, PLURAL(total_data),
   2475 		    (LLT)total_files, PLURAL(total_files));
   2476 	}
   2477 	otbi = total_bytes_in;
   2478 	otbo = total_bytes_out;
   2479 	otb = total_bytes;
   2480 	reply(0, "Traffic sent:     " LLF " byte%s in " LLF " transfer%s",
   2481 	    (LLT)otbo, PLURAL(otbo),
   2482 	    (LLT)total_xfers_out, PLURAL(total_xfers_out));
   2483 	reply(0, "Traffic received: " LLF " byte%s in " LLF " transfer%s",
   2484 	    (LLT)otbi, PLURAL(otbi),
   2485 	    (LLT)total_xfers_in, PLURAL(total_xfers_in));
   2486 	reply(0, "Total traffic:    " LLF " byte%s in " LLF " transfer%s",
   2487 	    (LLT)otb, PLURAL(otb),
   2488 	    (LLT)total_xfers, PLURAL(total_xfers));
   2489 
   2490 	if (logged_in && !CURCLASS_FLAGS_ISSET(private)) {
   2491 		struct ftpconv *cp;
   2492 
   2493 		reply(0, "%s", "");
   2494 		reply(0, "Class: %s, type: %s",
   2495 		    curclass.classname, CURCLASSTYPE);
   2496 		reply(0, "Check PORT/LPRT commands: %sabled",
   2497 		    CURCLASS_FLAGS_ISSET(checkportcmd) ? "en" : "dis");
   2498 		if (! EMPTYSTR(curclass.display))
   2499 			reply(0, "Display file: %s", curclass.display);
   2500 		if (! EMPTYSTR(curclass.notify))
   2501 			reply(0, "Notify fileglob: %s", curclass.notify);
   2502 		reply(0, "Idle timeout: " LLF ", maximum timeout: " LLF,
   2503 		    (LLT)curclass.timeout, (LLT)curclass.maxtimeout);
   2504 		reply(0, "Current connections: %d", connections);
   2505 		if (curclass.limit == -1)
   2506 			reply(0, "Maximum connections: unlimited");
   2507 		else
   2508 			reply(0, "Maximum connections: " LLF,
   2509 			    (LLT)curclass.limit);
   2510 		if (curclass.limitfile)
   2511 			reply(0, "Connection limit exceeded message file: %s",
   2512 			    conffilename(curclass.limitfile));
   2513 		if (! EMPTYSTR(curclass.chroot))
   2514 			reply(0, "Chroot format: %s", curclass.chroot);
   2515 		reply(0, "Deny bad ftpusers(5) quickly: %sabled",
   2516 		    CURCLASS_FLAGS_ISSET(denyquick) ? "en" : "dis");
   2517 		if (! EMPTYSTR(curclass.homedir))
   2518 			reply(0, "Homedir format: %s", curclass.homedir);
   2519 		if (curclass.maxfilesize == -1)
   2520 			reply(0, "Maximum file size: unlimited");
   2521 		else
   2522 			reply(0, "Maximum file size: " LLF,
   2523 			    (LLT)curclass.maxfilesize);
   2524 		if (! EMPTYSTR(curclass.motd))
   2525 			reply(0, "MotD file: %s", conffilename(curclass.motd));
   2526 		reply(0,
   2527 	    "Modify commands (CHMOD, DELE, MKD, RMD, RNFR, UMASK): %sabled",
   2528 		    CURCLASS_FLAGS_ISSET(modify) ? "en" : "dis");
   2529 		reply(0, "Upload commands (APPE, STOR, STOU): %sabled",
   2530 		    CURCLASS_FLAGS_ISSET(upload) ? "en" : "dis");
   2531 		reply(0, "Sanitize file names: %sabled",
   2532 		    CURCLASS_FLAGS_ISSET(sanenames) ? "en" : "dis");
   2533 		reply(0, "PASV/LPSV/EPSV connections: %sabled",
   2534 		    CURCLASS_FLAGS_ISSET(passive) ? "en" : "dis");
   2535 		if (curclass.advertise.su_len != 0) {
   2536 			char buf[50];	/* big enough for IPv6 address */
   2537 			const char *bp;
   2538 
   2539 			bp = inet_ntop(curclass.advertise.su_family,
   2540 			    (void *)&curclass.advertise.su_addr,
   2541 			    buf, sizeof(buf));
   2542 			if (bp != NULL)
   2543 				reply(0, "PASV advertise address: %s", bp);
   2544 		}
   2545 		if (curclass.portmin && curclass.portmax)
   2546 			reply(0, "PASV port range: " LLF " - " LLF,
   2547 			    (LLT)curclass.portmin, (LLT)curclass.portmax);
   2548 		if (curclass.rateget)
   2549 			reply(0, "Rate get limit: " LLF " bytes/sec",
   2550 			    (LLT)curclass.rateget);
   2551 		else
   2552 			reply(0, "Rate get limit: disabled");
   2553 		if (curclass.rateput)
   2554 			reply(0, "Rate put limit: " LLF " bytes/sec",
   2555 			    (LLT)curclass.rateput);
   2556 		else
   2557 			reply(0, "Rate put limit: disabled");
   2558 		if (curclass.mmapsize)
   2559 			reply(0, "Mmap size: " LLF, (LLT)curclass.mmapsize);
   2560 		else
   2561 			reply(0, "Mmap size: disabled");
   2562 		if (curclass.readsize)
   2563 			reply(0, "Read size: " LLF, (LLT)curclass.readsize);
   2564 		else
   2565 			reply(0, "Read size: default");
   2566 		if (curclass.writesize)
   2567 			reply(0, "Write size: " LLF, (LLT)curclass.writesize);
   2568 		else
   2569 			reply(0, "Write size: default");
   2570 		if (curclass.sendbufsize)
   2571 			reply(0, "Send buffer size: " LLF,
   2572 			    (LLT)curclass.sendbufsize);
   2573 		else
   2574 			reply(0, "Send buffer size: default");
   2575 		if (curclass.sendlowat)
   2576 			reply(0, "Send low water mark: " LLF,
   2577 			    (LLT)curclass.sendlowat);
   2578 		else
   2579 			reply(0, "Send low water mark: default");
   2580 		reply(0, "Umask: %.04o", curclass.umask);
   2581 		for (cp = curclass.conversions; cp != NULL; cp=cp->next) {
   2582 			if (cp->suffix == NULL || cp->types == NULL ||
   2583 			    cp->command == NULL)
   2584 				continue;
   2585 			reply(0, "Conversion: %s [%s] disable: %s, command: %s",
   2586 			    cp->suffix, cp->types, cp->disable, cp->command);
   2587 		}
   2588 	}
   2589 
   2590 	reply(211, "End of status");
   2591 }
   2592 
   2593 void
   2594 fatal(const char *s)
   2595 {
   2596 
   2597 	reply(451, "Error in server: %s\n", s);
   2598 	reply(221, "Closing connection due to server error.");
   2599 	dologout(0);
   2600 	/* NOTREACHED */
   2601 }
   2602 
   2603 /*
   2604  * reply() --
   2605  *	depending on the value of n, display fmt with a trailing CRLF and
   2606  *	prefix of:
   2607  *	n < -1		prefix the message with abs(n) + "-"	(initial line)
   2608  *	n == 0		prefix the message with 4 spaces	(middle lines)
   2609  *	n >  0		prefix the message with n + " "		(final line)
   2610  */
   2611 void
   2612 reply(int n, const char *fmt, ...)
   2613 {
   2614 	char	msg[MAXPATHLEN * 2 + 100];
   2615 	size_t	b;
   2616 	va_list	ap;
   2617 
   2618 	b = 0;
   2619 	if (n == 0)
   2620 		b = snprintf(msg, sizeof(msg), "    ");
   2621 	else if (n < 0)
   2622 		b = snprintf(msg, sizeof(msg), "%d-", -n);
   2623 	else
   2624 		b = snprintf(msg, sizeof(msg), "%d ", n);
   2625 	va_start(ap, fmt);
   2626 	vsnprintf(msg + b, sizeof(msg) - b, fmt, ap);
   2627 	va_end(ap);
   2628 	cprintf(stdout, "%s\r\n", msg);
   2629 	(void)fflush(stdout);
   2630 	if (debug)
   2631 		syslog(LOG_DEBUG, "<--- %s", msg);
   2632 }
   2633 
   2634 static void
   2635 logremotehost(struct sockinet *who)
   2636 {
   2637 
   2638 	if (getnameinfo((struct sockaddr *)&who->si_su,
   2639 	    who->su_len, remotehost, sizeof(remotehost), NULL, 0, 0))
   2640 		strlcpy(remotehost, "?", sizeof(remotehost));
   2641 
   2642 #if HAVE_SETPROCTITLE
   2643 	snprintf(proctitle, sizeof(proctitle), "%s: connected", remotehost);
   2644 	setproctitle("%s", proctitle);
   2645 #endif /* HAVE_SETPROCTITLE */
   2646 	if (logging)
   2647 		syslog(LOG_INFO, "connection from %s to %s",
   2648 		    remotehost, hostname);
   2649 }
   2650 
   2651 /*
   2652  * Record logout in wtmp file and exit with supplied status.
   2653  * NOTE: because this is called from signal handlers it cannot
   2654  *       use stdio (or call other functions that use stdio).
   2655  */
   2656 void
   2657 dologout(int status)
   2658 {
   2659 	/*
   2660 	* Prevent reception of SIGURG from resulting in a resumption
   2661 	* back to the main program loop.
   2662 	*/
   2663 	transflag = 0;
   2664 	logout_utmp();
   2665 	if (logged_in) {
   2666 #ifdef KERBEROS
   2667 		if (!notickets && krbtkfile_env)
   2668 			unlink(krbtkfile_env);
   2669 #endif
   2670 	}
   2671 	/* beware of flushing buffers after a SIGPIPE */
   2672 	if (xferlogfd != -1)
   2673 		close(xferlogfd);
   2674 	_exit(status);
   2675 }
   2676 
   2677 void
   2678 abor(void)
   2679 {
   2680 
   2681 	if (!transflag)
   2682 		return;
   2683 	tmpline[0] = '\0';
   2684 	is_oob = 0;
   2685 	reply(426, "Transfer aborted. Data connection closed.");
   2686 	reply(226, "Abort successful");
   2687 	transflag = 0;		/* flag that the transfer has aborted */
   2688 }
   2689 
   2690 void
   2691 statxfer(void)
   2692 {
   2693 
   2694 	if (!transflag)
   2695 		return;
   2696 	tmpline[0] = '\0';
   2697 	is_oob = 0;
   2698 	if (file_size != (off_t) -1)
   2699 		reply(213,
   2700 		    "Status: " LLF " of " LLF " byte%s transferred",
   2701 		    (LLT)byte_count, (LLT)file_size,
   2702 		    PLURAL(byte_count));
   2703 	else
   2704 		reply(213, "Status: " LLF " byte%s transferred",
   2705 		    (LLT)byte_count, PLURAL(byte_count));
   2706 }
   2707 
   2708 /*
   2709  * Call when urgflag != 0 to handle Out Of Band commands.
   2710  * Returns non zero if the OOB command aborted the transfer
   2711  * by setting transflag to 0. (c.f., "ABOR").
   2712  */
   2713 static int
   2714 handleoobcmd()
   2715 {
   2716 	char *cp;
   2717 
   2718 	if (!urgflag)
   2719 		return (0);
   2720 	urgflag = 0;
   2721 	/* only process if transfer occurring */
   2722 	if (!transflag)
   2723 		return (0);
   2724 	cp = tmpline;
   2725 	if (getline(cp, sizeof(tmpline), stdin) == NULL) {
   2726 		reply(221, "You could at least say goodbye.");
   2727 		dologout(0);
   2728 	}
   2729 		/*
   2730 		 * Manually parse OOB commands, because we can't
   2731 		 * recursively call the yacc parser...
   2732 		 */
   2733 	if (strcasecmp(cp, "ABOR\r\n") == 0) {
   2734 		abor();
   2735 	} else if (strcasecmp(cp, "STAT\r\n") == 0) {
   2736 		statxfer();
   2737 	} else {
   2738 		/* XXX: error with "500 unknown command" ? */
   2739 	}
   2740 	return (transflag == 0);
   2741 }
   2742 
   2743 static int
   2744 bind_pasv_addr(void)
   2745 {
   2746 	static int passiveport;
   2747 	int port, len;
   2748 
   2749 	len = pasv_addr.su_len;
   2750 	if (curclass.portmin == 0 && curclass.portmax == 0) {
   2751 		pasv_addr.su_port = 0;
   2752 		return (bind(pdata, (struct sockaddr *)&pasv_addr.si_su, len));
   2753 	}
   2754 
   2755 	if (passiveport == 0) {
   2756 		srand(getpid());
   2757 		passiveport = rand() % (curclass.portmax - curclass.portmin)
   2758 		    + curclass.portmin;
   2759 	}
   2760 
   2761 	port = passiveport;
   2762 	while (1) {
   2763 		port++;
   2764 		if (port > curclass.portmax)
   2765 			port = curclass.portmin;
   2766 		else if (port == passiveport) {
   2767 			errno = EAGAIN;
   2768 			return (-1);
   2769 		}
   2770 		pasv_addr.su_port = htons(port);
   2771 		if (bind(pdata, (struct sockaddr *)&pasv_addr.si_su, len) == 0)
   2772 			break;
   2773 		if (errno != EADDRINUSE)
   2774 			return (-1);
   2775 	}
   2776 	passiveport = port;
   2777 	return (0);
   2778 }
   2779 
   2780 /*
   2781  * Note: a response of 425 is not mentioned as a possible response to
   2782  *	the PASV command in RFC959. However, it has been blessed as
   2783  *	a legitimate response by Jon Postel in a telephone conversation
   2784  *	with Rick Adams on 25 Jan 89.
   2785  */
   2786 void
   2787 passive(void)
   2788 {
   2789 	int len;
   2790 	char *p, *a;
   2791 
   2792 	if (pdata >= 0)
   2793 		close(pdata);
   2794 	pdata = socket(AF_INET, SOCK_STREAM, 0);
   2795 	if (pdata < 0 || !logged_in) {
   2796 		perror_reply(425, "Can't open passive connection");
   2797 		return;
   2798 	}
   2799 	pasv_addr = ctrl_addr;
   2800 
   2801 	if (bind_pasv_addr() < 0)
   2802 		goto pasv_error;
   2803 	len = pasv_addr.su_len;
   2804 	if (getsockname(pdata, (struct sockaddr *) &pasv_addr.si_su, &len) < 0)
   2805 		goto pasv_error;
   2806 	pasv_addr.su_len = len;
   2807 	if (listen(pdata, 1) < 0)
   2808 		goto pasv_error;
   2809 	if (curclass.advertise.su_len != 0)
   2810 		a = (char *) &curclass.advertise.su_addr;
   2811 	else
   2812 		a = (char *) &pasv_addr.su_addr;
   2813 	p = (char *) &pasv_addr.su_port;
   2814 
   2815 #define UC(b) (((int) b) & 0xff)
   2816 
   2817 	reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
   2818 		UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
   2819 	return;
   2820 
   2821  pasv_error:
   2822 	(void) close(pdata);
   2823 	pdata = -1;
   2824 	perror_reply(425, "Can't open passive connection");
   2825 	return;
   2826 }
   2827 
   2828 /*
   2829  * convert protocol identifier to/from AF
   2830  */
   2831 int
   2832 lpsvproto2af(int proto)
   2833 {
   2834 
   2835 	switch (proto) {
   2836 	case 4:
   2837 		return AF_INET;
   2838 #ifdef INET6
   2839 	case 6:
   2840 		return AF_INET6;
   2841 #endif
   2842 	default:
   2843 		return -1;
   2844 	}
   2845 }
   2846 
   2847 int
   2848 af2lpsvproto(int af)
   2849 {
   2850 
   2851 	switch (af) {
   2852 	case AF_INET:
   2853 		return 4;
   2854 #ifdef INET6
   2855 	case AF_INET6:
   2856 		return 6;
   2857 #endif
   2858 	default:
   2859 		return -1;
   2860 	}
   2861 }
   2862 
   2863 int
   2864 epsvproto2af(int proto)
   2865 {
   2866 
   2867 	switch (proto) {
   2868 	case 1:
   2869 		return AF_INET;
   2870 #ifdef INET6
   2871 	case 2:
   2872 		return AF_INET6;
   2873 #endif
   2874 	default:
   2875 		return -1;
   2876 	}
   2877 }
   2878 
   2879 int
   2880 af2epsvproto(int af)
   2881 {
   2882 
   2883 	switch (af) {
   2884 	case AF_INET:
   2885 		return 1;
   2886 #ifdef INET6
   2887 	case AF_INET6:
   2888 		return 2;
   2889 #endif
   2890 	default:
   2891 		return -1;
   2892 	}
   2893 }
   2894 
   2895 /*
   2896  * 228 Entering Long Passive Mode (af, hal, h1, h2, h3,..., pal, p1, p2...)
   2897  * 229 Entering Extended Passive Mode (|||port|)
   2898  */
   2899 void
   2900 long_passive(char *cmd, int pf)
   2901 {
   2902 	int len;
   2903 	char *p, *a;
   2904 
   2905 	if (!logged_in) {
   2906 		syslog(LOG_NOTICE, "long passive but not logged in");
   2907 		reply(503, "Login with USER first.");
   2908 		return;
   2909 	}
   2910 
   2911 	if (pf != PF_UNSPEC && ctrl_addr.su_family != pf) {
   2912 		/*
   2913 		 * XXX: only EPRT/EPSV ready clients will understand this
   2914 		 */
   2915 		if (strcmp(cmd, "EPSV") != 0)
   2916 			reply(501, "Network protocol mismatch"); /*XXX*/
   2917 		else
   2918 			epsv_protounsupp("Network protocol mismatch");
   2919 
   2920 		return;
   2921 	}
   2922 
   2923 	if (pdata >= 0)
   2924 		close(pdata);
   2925 	pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
   2926 	if (pdata < 0) {
   2927 		perror_reply(425, "Can't open passive connection");
   2928 		return;
   2929 	}
   2930 	pasv_addr = ctrl_addr;
   2931 	if (bind_pasv_addr() < 0)
   2932 		goto pasv_error;
   2933 	len = pasv_addr.su_len;
   2934 	if (getsockname(pdata, (struct sockaddr *) &pasv_addr.si_su, &len) < 0)
   2935 		goto pasv_error;
   2936 	pasv_addr.su_len = len;
   2937 	if (listen(pdata, 1) < 0)
   2938 		goto pasv_error;
   2939 	p = (char *) &pasv_addr.su_port;
   2940 
   2941 #define UC(b) (((int) b) & 0xff)
   2942 
   2943 	if (strcmp(cmd, "LPSV") == 0) {
   2944 		struct sockinet *advert;
   2945 
   2946 		if (curclass.advertise.su_len != 0)
   2947 			advert = &curclass.advertise;
   2948 		else
   2949 			advert = &pasv_addr;
   2950 		switch (advert->su_family) {
   2951 		case AF_INET:
   2952 			a = (char *) &advert->su_addr;
   2953 			reply(228,
   2954     "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)",
   2955 				4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
   2956 				2, UC(p[0]), UC(p[1]));
   2957 			return;
   2958 #ifdef INET6
   2959 		case AF_INET6:
   2960 			a = (char *) &advert->su_6addr;
   2961 			reply(228,
   2962     "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)",
   2963 				6, 16,
   2964 				UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
   2965 				UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]),
   2966 				UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]),
   2967 				UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]),
   2968 				2, UC(p[0]), UC(p[1]));
   2969 			return;
   2970 #endif
   2971 		}
   2972 #undef UC
   2973 	} else if (strcmp(cmd, "EPSV") == 0) {
   2974 		switch (pasv_addr.su_family) {
   2975 		case AF_INET:
   2976 #ifdef INET6
   2977 		case AF_INET6:
   2978 #endif
   2979 			reply(229, "Entering Extended Passive Mode (|||%d|)",
   2980 			    ntohs(pasv_addr.su_port));
   2981 			return;
   2982 		}
   2983 	} else {
   2984 		/* more proper error code? */
   2985 	}
   2986 
   2987  pasv_error:
   2988 	(void) close(pdata);
   2989 	pdata = -1;
   2990 	perror_reply(425, "Can't open passive connection");
   2991 	return;
   2992 }
   2993 
   2994 int
   2995 extended_port(const char *arg)
   2996 {
   2997 	char *tmp = NULL;
   2998 	char *result[3];
   2999 	char *p, *q;
   3000 	char delim;
   3001 	struct addrinfo hints;
   3002 	struct addrinfo *res = NULL;
   3003 	int i;
   3004 	unsigned long proto;
   3005 
   3006 	tmp = xstrdup(arg);
   3007 	p = tmp;
   3008 	delim = p[0];
   3009 	p++;
   3010 	memset(result, 0, sizeof(result));
   3011 	for (i = 0; i < 3; i++) {
   3012 		q = strchr(p, delim);
   3013 		if (!q || *q != delim)
   3014 			goto parsefail;
   3015 		*q++ = '\0';
   3016 		result[i] = p;
   3017 		p = q;
   3018 	}
   3019 
   3020 			/* some more sanity checks */
   3021 	errno = 0;
   3022 	p = NULL;
   3023 	(void)strtoul(result[2], &p, 10);
   3024 	if (errno || !*result[2] || *p)
   3025 		goto parsefail;
   3026 	errno = 0;
   3027 	p = NULL;
   3028 	proto = strtoul(result[0], &p, 10);
   3029 	if (errno || !*result[0] || *p)
   3030 		goto protounsupp;
   3031 
   3032 	memset(&hints, 0, sizeof(hints));
   3033 	hints.ai_family = epsvproto2af((int)proto);
   3034 	if (hints.ai_family < 0)
   3035 		goto protounsupp;
   3036 	hints.ai_socktype = SOCK_STREAM;
   3037 	hints.ai_flags = AI_NUMERICHOST;
   3038 	if (getaddrinfo(result[1], result[2], &hints, &res))
   3039 		goto parsefail;
   3040 	if (res->ai_next)
   3041 		goto parsefail;
   3042 	if (sizeof(data_dest) < res->ai_addrlen)
   3043 		goto parsefail;
   3044 	memcpy(&data_dest.si_su, res->ai_addr, res->ai_addrlen);
   3045 	data_dest.su_len = res->ai_addrlen;
   3046 #ifdef INET6
   3047 	if (his_addr.su_family == AF_INET6 &&
   3048 	    data_dest.su_family == AF_INET6) {
   3049 			/* XXX: more sanity checks! */
   3050 		data_dest.su_scope_id = his_addr.su_scope_id;
   3051 	}
   3052 #endif
   3053 
   3054 	if (tmp != NULL)
   3055 		free(tmp);
   3056 	if (res)
   3057 		freeaddrinfo(res);
   3058 	return 0;
   3059 
   3060  parsefail:
   3061 	reply(500, "Invalid argument, rejected.");
   3062 	usedefault = 1;
   3063 	if (tmp != NULL)
   3064 		free(tmp);
   3065 	if (res)
   3066 		freeaddrinfo(res);
   3067 	return -1;
   3068 
   3069  protounsupp:
   3070 	epsv_protounsupp("Protocol not supported");
   3071 	usedefault = 1;
   3072 	if (tmp != NULL)
   3073 		free(tmp);
   3074 	if (res)
   3075 		freeaddrinfo(res);
   3076 	return -1;
   3077 }
   3078 
   3079 /*
   3080  * 522 Protocol not supported (proto,...)
   3081  * as we assume address family for control and data connections are the same,
   3082  * we do not return the list of address families we support - instead, we
   3083  * return the address family of the control connection.
   3084  */
   3085 void
   3086 epsv_protounsupp(const char *message)
   3087 {
   3088 	int proto;
   3089 
   3090 	proto = af2epsvproto(ctrl_addr.su_family);
   3091 	if (proto < 0)
   3092 		reply(501, "%s", message);	/* XXX */
   3093 	else
   3094 		reply(522, "%s, use (%d)", message, proto);
   3095 }
   3096 
   3097 /*
   3098  * Generate unique name for file with basename "local".
   3099  * The file named "local" is already known to exist.
   3100  * Generates failure reply on error.
   3101  *
   3102  * XXX:	this function should under go changes similar to
   3103  *	the mktemp(3)/mkstemp(3) changes.
   3104  */
   3105 static char *
   3106 gunique(const char *local)
   3107 {
   3108 	static char new[MAXPATHLEN];
   3109 	struct stat st;
   3110 	char *cp;
   3111 	int count;
   3112 
   3113 	cp = strrchr(local, '/');
   3114 	if (cp)
   3115 		*cp = '\0';
   3116 	if (stat(cp ? local : ".", &st) < 0) {
   3117 		perror_reply(553, cp ? local : ".");
   3118 		return (NULL);
   3119 	}
   3120 	if (cp)
   3121 		*cp = '/';
   3122 	for (count = 1; count < 100; count++) {
   3123 		(void)snprintf(new, sizeof(new) - 1, "%s.%d", local, count);
   3124 		if (stat(new, &st) < 0)
   3125 			return (new);
   3126 	}
   3127 	reply(452, "Unique file name cannot be created.");
   3128 	return (NULL);
   3129 }
   3130 
   3131 /*
   3132  * Format and send reply containing system error number.
   3133  */
   3134 void
   3135 perror_reply(int code, const char *string)
   3136 {
   3137 	int save_errno;
   3138 
   3139 	save_errno = errno;
   3140 	reply(code, "%s: %s.", string, strerror(errno));
   3141 	errno = save_errno;
   3142 }
   3143 
   3144 static char *onefile[] = {
   3145 	"",
   3146 	0
   3147 };
   3148 
   3149 void
   3150 send_file_list(const char *whichf)
   3151 {
   3152 	struct stat st;
   3153 	DIR *dirp = NULL;
   3154 	struct dirent *dir;
   3155 	FILE *dout = NULL;
   3156 	char **dirlist, *dirname, *p;
   3157 	char *notglob = NULL;
   3158 	int simple = 0;
   3159 	int freeglob = 0;
   3160 	glob_t gl;
   3161 
   3162 #ifdef __GNUC__
   3163 	(void) &dout;
   3164 	(void) &dirlist;
   3165 	(void) &simple;
   3166 	(void) &freeglob;
   3167 #endif
   3168 	urgflag = 0;
   3169 
   3170 	p = NULL;
   3171 	if (strpbrk(whichf, "~{[*?") != NULL) {
   3172 		int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE|GLOB_LIMIT;
   3173 
   3174 		memset(&gl, 0, sizeof(gl));
   3175 		freeglob = 1;
   3176 		if (glob(whichf, flags, 0, &gl)) {
   3177 			reply(450, "Not found");
   3178 			goto cleanup_send_file_list;
   3179 		} else if (gl.gl_pathc == 0) {
   3180 			errno = ENOENT;
   3181 			perror_reply(450, whichf);
   3182 			goto cleanup_send_file_list;
   3183 		}
   3184 		dirlist = gl.gl_pathv;
   3185 	} else {
   3186 		notglob = xstrdup(whichf);
   3187 		onefile[0] = notglob;
   3188 		dirlist = onefile;
   3189 		simple = 1;
   3190 	}
   3191 					/* XXX: } for vi sm */
   3192 
   3193 	while ((dirname = *dirlist++) != NULL) {
   3194 		int trailingslash = 0;
   3195 
   3196 		if (stat(dirname, &st) < 0) {
   3197 			/*
   3198 			 * If user typed "ls -l", etc, and the client
   3199 			 * used NLST, do what the user meant.
   3200 			 */
   3201 			/* XXX: nuke this support? */
   3202 			if (dirname[0] == '-' && *dirlist == NULL &&
   3203 			    transflag == 0) {
   3204 				char *argv[] = { INTERNAL_LS, "", NULL };
   3205 
   3206 				argv[1] = dirname;
   3207 				retrieve(argv, dirname);
   3208 				goto cleanup_send_file_list;
   3209 			}
   3210 			perror_reply(450, whichf);
   3211 			goto cleanup_send_file_list;
   3212 		}
   3213 
   3214 		if (S_ISREG(st.st_mode)) {
   3215 			/*
   3216 			 * XXXRFC:
   3217 			 *	should we follow RFC959 and not work
   3218 			 *	for non directories?
   3219 			 */
   3220 			if (dout == NULL) {
   3221 				dout = dataconn("file list", (off_t)-1, "w");
   3222 				if (dout == NULL)
   3223 					goto cleanup_send_file_list;
   3224 				transflag = 1;
   3225 			}
   3226 			cprintf(dout, "%s%s\n", dirname,
   3227 			    type == TYPE_A ? "\r" : "");
   3228 			continue;
   3229 		} else if (!S_ISDIR(st.st_mode))
   3230 			continue;
   3231 
   3232 		if (dirname[strlen(dirname) - 1] == '/')
   3233 			trailingslash++;
   3234 
   3235 		if ((dirp = opendir(dirname)) == NULL)
   3236 			continue;
   3237 
   3238 		while ((dir = readdir(dirp)) != NULL) {
   3239 			char nbuf[MAXPATHLEN];
   3240 
   3241 			if (urgflag && handleoobcmd())
   3242 				goto cleanup_send_file_list;
   3243 
   3244 			if (ISDOTDIR(dir->d_name) || ISDOTDOTDIR(dir->d_name))
   3245 				continue;
   3246 
   3247 			(void)snprintf(nbuf, sizeof(nbuf), "%s%s%s", dirname,
   3248 			    trailingslash ? "" : "/", dir->d_name);
   3249 
   3250 			/*
   3251 			 * We have to do a stat to ensure it's
   3252 			 * not a directory or special file.
   3253 			 */
   3254 			/*
   3255 			 * XXXRFC:
   3256 			 *	should we follow RFC959 and filter out
   3257 			 *	non files ?   lukem - NO!, or not until
   3258 			 *	our ftp client uses MLS{T,D} for completion.
   3259 			 */
   3260 			if (simple || (stat(nbuf, &st) == 0 &&
   3261 			    S_ISREG(st.st_mode))) {
   3262 				if (dout == NULL) {
   3263 					dout = dataconn("file list", (off_t)-1,
   3264 						"w");
   3265 					if (dout == NULL)
   3266 						goto cleanup_send_file_list;
   3267 					transflag = 1;
   3268 				}
   3269 				p = nbuf;
   3270 				if (nbuf[0] == '.' && nbuf[1] == '/')
   3271 					p = &nbuf[2];
   3272 				cprintf(dout, "%s%s\n", p,
   3273 				    type == TYPE_A ? "\r" : "");
   3274 			}
   3275 		}
   3276 		(void) closedir(dirp);
   3277 	}
   3278 
   3279 	if (dout == NULL)
   3280 		reply(450, "No files found.");
   3281 	else if (ferror(dout) != 0)
   3282 		perror_reply(451, "Data connection");
   3283 	else
   3284 		reply(226, "Transfer complete.");
   3285 
   3286  cleanup_send_file_list:
   3287 	closedataconn(dout);
   3288 	transflag = 0;
   3289 	urgflag = 0;
   3290 	total_xfers++;
   3291 	total_xfers_out++;
   3292 	if (notglob)
   3293 		free(notglob);
   3294 	if (freeglob)
   3295 		globfree(&gl);
   3296 }
   3297 
   3298 char *
   3299 conffilename(const char *s)
   3300 {
   3301 	static char filename[MAXPATHLEN];
   3302 
   3303 	if (*s == '/')
   3304 		strlcpy(filename, s, sizeof(filename));
   3305 	else
   3306 		(void)snprintf(filename, sizeof(filename), "%s/%s", confdir ,s);
   3307 	return (filename);
   3308 }
   3309 
   3310 /*
   3311  * logxfer --
   3312  *	if logging > 1, then based on the arguments, syslog a message:
   3313  *	 if bytes != -1		"<command> <file1> = <bytes> bytes"
   3314  *	 else if file2 != NULL	"<command> <file1> <file2>"
   3315  *	 else			"<command> <file1>"
   3316  *	if elapsed != NULL, append "in xxx.yyy seconds"
   3317  *	if error != NULL, append ": " + error
   3318  *
   3319  *	if doxferlog != 0, bytes != -1, and command is "get", "put",
   3320  *	or "append", syslog and/or write a wu-ftpd style xferlog entry
   3321  */
   3322 void
   3323 logxfer(const char *command, off_t bytes, const char *file1, const char *file2,
   3324     const struct timeval *elapsed, const char *error)
   3325 {
   3326 	char		 buf[MAXPATHLEN * 2 + 100];
   3327 	char		 realfile1[MAXPATHLEN], realfile2[MAXPATHLEN];
   3328 	const char	*r1, *r2;
   3329 	char		 direction;
   3330 	size_t		 len;
   3331 	time_t		 now;
   3332 
   3333 	if (logging <=1 && !doxferlog)
   3334 		return;
   3335 
   3336 	r1 = r2 = NULL;
   3337 	if ((r1 = realpath(file1, realfile1)) == NULL)
   3338 		r1 = file1;
   3339 	if (file2 != NULL)
   3340 		if ((r2 = realpath(file2, realfile2)) == NULL)
   3341 			r2 = file2;
   3342 
   3343 		/*
   3344 		 * syslog command
   3345 		 */
   3346 	if (logging > 1) {
   3347 		len = snprintf(buf, sizeof(buf), "%s %s", command, r1);
   3348 		if (bytes != (off_t)-1)
   3349 			len += snprintf(buf + len, sizeof(buf) - len,
   3350 			    " = " LLF " byte%s", (LLT) bytes, PLURAL(bytes));
   3351 		else if (r2 != NULL)
   3352 			len += snprintf(buf + len, sizeof(buf) - len,
   3353 			    " %s", r2);
   3354 		if (elapsed != NULL)
   3355 			len += snprintf(buf + len, sizeof(buf) - len,
   3356 			    " in %ld.%.03d seconds", elapsed->tv_sec,
   3357 			    (int)(elapsed->tv_usec / 1000));
   3358 		if (error != NULL)
   3359 			len += snprintf(buf + len, sizeof(buf) - len,
   3360 			    ": %s", error);
   3361 		syslog(LOG_INFO, "%s", buf);
   3362 	}
   3363 
   3364 		/*
   3365 		 * syslog wu-ftpd style log entry, prefixed with "xferlog: "
   3366 		 */
   3367 	if (!doxferlog || bytes == -1)
   3368 		return;
   3369 
   3370 	if (strcmp(command, "get") == 0)
   3371 		direction = 'o';
   3372 	else if (strcmp(command, "put") == 0 || strcmp(command, "append") == 0)
   3373 		direction = 'i';
   3374 	else
   3375 		return;
   3376 
   3377 	time(&now);
   3378 	len = snprintf(buf, sizeof(buf),
   3379 	    "%.24s %ld %s " LLF " %s %c %s %c %c %s FTP 0 * %c\n",
   3380 
   3381 /*
   3382  * XXX: wu-ftpd puts ' (send)' or ' (recv)' in the syslog message, and removes
   3383  *	the full date.  This may be problematic for accurate log parsing,
   3384  *	given that syslog messages don't contain the full date.
   3385  */
   3386 	    ctime(&now),
   3387 	    elapsed == NULL ? 0 : elapsed->tv_sec + (elapsed->tv_usec > 0),
   3388 	    remotehost,
   3389 	    (LLT) bytes,
   3390 	    r1,
   3391 	    type == TYPE_A ? 'a' : 'b',
   3392 	    "_",		/* XXX: take conversions into account? */
   3393 	    direction,
   3394 
   3395 	    curclass.type == CLASS_GUEST ?  'a' :
   3396 	    curclass.type == CLASS_CHROOT ? 'g' :
   3397 	    curclass.type == CLASS_REAL ?   'r' : '?',
   3398 
   3399 	    curclass.type == CLASS_GUEST ? pw->pw_passwd : pw->pw_name,
   3400 	    error != NULL ? 'i' : 'c'
   3401 	    );
   3402 
   3403 	if ((doxferlog & 2) && xferlogfd != -1)
   3404 		write(xferlogfd, buf, len);
   3405 	if ((doxferlog & 1)) {
   3406 		buf[len-1] = '\n';	/* strip \n from syslog message */
   3407 		syslog(LOG_INFO, "xferlog: %s", buf);
   3408 	}
   3409 }
   3410 
   3411 /*
   3412  * Log the resource usage.
   3413  *
   3414  * XXX: more resource usage to logging?
   3415  */
   3416 void
   3417 logrusage(const struct rusage *rusage_before,
   3418     const struct rusage *rusage_after)
   3419 {
   3420 	struct timeval usrtime, systime;
   3421 
   3422 	if (logging <= 1)
   3423 		return;
   3424 
   3425 	timersub(&rusage_after->ru_utime, &rusage_before->ru_utime, &usrtime);
   3426 	timersub(&rusage_after->ru_stime, &rusage_before->ru_stime, &systime);
   3427 	syslog(LOG_INFO, "%ld.%.03du %ld.%.03ds %ld+%ldio %ldpf+%ldw",
   3428 	    usrtime.tv_sec, (int)(usrtime.tv_usec / 1000),
   3429 	    systime.tv_sec, (int)(systime.tv_usec / 1000),
   3430 	    rusage_after->ru_inblock - rusage_before->ru_inblock,
   3431 	    rusage_after->ru_oublock - rusage_before->ru_oublock,
   3432 	    rusage_after->ru_majflt - rusage_before->ru_majflt,
   3433 	    rusage_after->ru_nswap - rusage_before->ru_nswap);
   3434 }
   3435 
   3436 /*
   3437  * Determine if `password' is valid for user given in `pw'.
   3438  * Returns 2 if password expired, 1 if otherwise failed, 0 if ok
   3439  */
   3440 int
   3441 checkpassword(const struct passwd *pwent, const char *password)
   3442 {
   3443 	char	*orig, *new;
   3444 	time_t	 change, expire, now;
   3445 
   3446 	change = expire = 0;
   3447 	if (pwent == NULL)
   3448 		return 1;
   3449 
   3450 	time(&now);
   3451 	orig = pwent->pw_passwd;	/* save existing password */
   3452 	expire = pwent->pw_expire;
   3453 	change = (pwent->pw_change == _PASSWORD_CHGNOW)? now : pwent->pw_change;
   3454 
   3455 	if (orig[0] == '\0')		/* don't allow empty passwords */
   3456 		return 1;
   3457 
   3458 	new = crypt(password, orig);	/* encrypt given password */
   3459 	if (strcmp(new, orig) != 0)	/* compare */
   3460 		return 1;
   3461 
   3462 	if ((expire && now >= expire) || (change && now >= change))
   3463 		return 2;		/* check if expired */
   3464 
   3465 	return 0;			/* OK! */
   3466 }
   3467 
   3468 char *
   3469 xstrdup(const char *s)
   3470 {
   3471 	char *new = strdup(s);
   3472 
   3473 	if (new == NULL)
   3474 		fatal("Local resource failure: malloc");
   3475 		/* NOTREACHED */
   3476 	return (new);
   3477 }
   3478 
   3479 /*
   3480  * As per fprintf(), but increment total_bytes and total_bytes_out,
   3481  * by the appropriate amount.
   3482  */
   3483 void
   3484 cprintf(FILE *fd, const char *fmt, ...)
   3485 {
   3486 	off_t b;
   3487 	va_list ap;
   3488 
   3489 	va_start(ap, fmt);
   3490 	b = vfprintf(fd, fmt, ap);
   3491 	va_end(ap);
   3492 	total_bytes += b;
   3493 	total_bytes_out += b;
   3494 }
   3495 
   3496 #ifdef USE_PAM
   3497 /*
   3498  * the following code is stolen from imap-uw PAM authentication module and
   3499  * login.c
   3500  */
   3501 #define COPY_STRING(s) (s ? strdup(s) : NULL)
   3502 
   3503 struct cred_t {
   3504 	const char *uname;		/* user name */
   3505 	const char *pass;		/* password */
   3506 };
   3507 typedef struct cred_t cred_t;
   3508 
   3509 static int
   3510 auth_conv(int num_msg, const struct pam_message **msg,
   3511     struct pam_response **resp, void *appdata)
   3512 {
   3513 	int i;
   3514 	cred_t *cred = (cred_t *) appdata;
   3515 	struct pam_response *myreply;
   3516 
   3517 	myreply = calloc(num_msg, sizeof *myreply);
   3518 	if (myreply == NULL)
   3519 		return PAM_BUF_ERR;
   3520 
   3521 	for (i = 0; i < num_msg; i++) {
   3522 		switch (msg[i]->msg_style) {
   3523 		case PAM_PROMPT_ECHO_ON:	/* assume want user name */
   3524 			myreply[i].resp_retcode = PAM_SUCCESS;
   3525 			myreply[i].resp = COPY_STRING(cred->uname);
   3526 			/* PAM frees resp. */
   3527 			break;
   3528 		case PAM_PROMPT_ECHO_OFF:	/* assume want password */
   3529 			myreply[i].resp_retcode = PAM_SUCCESS;
   3530 			myreply[i].resp = COPY_STRING(cred->pass);
   3531 			/* PAM frees resp. */
   3532 			break;
   3533 		case PAM_TEXT_INFO:
   3534 		case PAM_ERROR_MSG:
   3535 			myreply[i].resp_retcode = PAM_SUCCESS;
   3536 			myreply[i].resp = NULL;
   3537 			break;
   3538 		default:			/* unknown message style */
   3539 			free(myreply);
   3540 			return PAM_CONV_ERR;
   3541 		}
   3542 	}
   3543 
   3544 	*resp = myreply;
   3545 	return PAM_SUCCESS;
   3546 }
   3547 
   3548 /*
   3549  * Attempt to authenticate the user using PAM.  Returns 0 if the user is
   3550  * authenticated, or 1 if not authenticated.  If some sort of PAM system
   3551  * error occurs (e.g., the "/etc/pam.conf" file is missing) then this
   3552  * function returns -1.  This can be used as an indication that we should
   3553  * fall back to a different authentication mechanism.
   3554  */
   3555 static int
   3556 auth_pam(struct passwd **ppw, const char *pwstr)
   3557 {
   3558 	const char *tmpl_user;
   3559 	const void *item;
   3560 	int rval;
   3561 	int e;
   3562 	cred_t auth_cred = { (*ppw)->pw_name, pwstr };
   3563 	struct pam_conv conv = { &auth_conv, &auth_cred };
   3564 
   3565 	e = pam_start("ftpd", (*ppw)->pw_name, &conv, &pamh);
   3566 	if (e != PAM_SUCCESS) {
   3567 		/*
   3568 		 * In OpenPAM, it's OK to pass NULL to pam_strerror()
   3569 		 * if context creation has failed in the first place.
   3570 		 */
   3571 		syslog(LOG_ERR, "pam_start: %s", pam_strerror(NULL, e));
   3572 		return -1;
   3573 	}
   3574 
   3575 	e = pam_set_item(pamh, PAM_RHOST, remotehost);
   3576 	if (e != PAM_SUCCESS) {
   3577 		syslog(LOG_ERR, "pam_set_item(PAM_RHOST): %s",
   3578 			pam_strerror(pamh, e));
   3579 		if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
   3580 			syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
   3581 		}
   3582 		pamh = NULL;
   3583 		return -1;
   3584 	}
   3585 
   3586 	e = pam_authenticate(pamh, 0);
   3587 	switch (e) {
   3588 	case PAM_SUCCESS:
   3589 		/*
   3590 		 * With PAM we support the concept of a "template"
   3591 		 * user.  The user enters a login name which is
   3592 		 * authenticated by PAM, usually via a remote service
   3593 		 * such as RADIUS or TACACS+.  If authentication
   3594 		 * succeeds, a different but related "template" name
   3595 		 * is used for setting the credentials, shell, and
   3596 		 * home directory.  The name the user enters need only
   3597 		 * exist on the remote authentication server, but the
   3598 		 * template name must be present in the local password
   3599 		 * database.
   3600 		 *
   3601 		 * This is supported by two various mechanisms in the
   3602 		 * individual modules.  However, from the application's
   3603 		 * point of view, the template user is always passed
   3604 		 * back as a changed value of the PAM_USER item.
   3605 		 */
   3606 		if ((e = pam_get_item(pamh, PAM_USER, &item)) ==
   3607 		    PAM_SUCCESS) {
   3608 			tmpl_user = (const char *) item;
   3609 			if (strcmp((*ppw)->pw_name, tmpl_user) != 0)
   3610 				*ppw = sgetpwnam(tmpl_user);
   3611 		} else
   3612 			syslog(LOG_ERR, "Couldn't get PAM_USER: %s",
   3613 			    pam_strerror(pamh, e));
   3614 		rval = 0;
   3615 		break;
   3616 
   3617 	case PAM_AUTH_ERR:
   3618 	case PAM_USER_UNKNOWN:
   3619 	case PAM_MAXTRIES:
   3620 		rval = 1;
   3621 		break;
   3622 
   3623 	default:
   3624 		syslog(LOG_ERR, "pam_authenticate: %s", pam_strerror(pamh, e));
   3625 		rval = -1;
   3626 		break;
   3627 	}
   3628 
   3629 	if (rval == 0) {
   3630 		e = pam_acct_mgmt(pamh, 0);
   3631 		if (e != PAM_SUCCESS) {
   3632 			syslog(LOG_ERR, "pam_acct_mgmt: %s",
   3633 						pam_strerror(pamh, e));
   3634 			rval = 1;
   3635 		}
   3636 	}
   3637 
   3638 	if (rval != 0) {
   3639 		if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
   3640 			syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
   3641 		}
   3642 		pamh = NULL;
   3643 	}
   3644 	return rval;
   3645 }
   3646 
   3647 #endif /* USE_PAM */
   3648