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