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