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