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