Home | History | Annotate | Line # | Download | only in ftpd
ftpd.c revision 1.93
      1 /*	$NetBSD: ftpd.c,v 1.93 2000/06/14 13:44:24 lukem Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1997-2000 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. All advertising materials mentioning features or use of this software
     52  *    must display the following acknowledgement:
     53  *	This product includes software developed by the University of
     54  *	California, Berkeley and its contributors.
     55  * 4. Neither the name of the University nor the names of its contributors
     56  *    may be used to endorse or promote products derived from this software
     57  *    without specific prior written permission.
     58  *
     59  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     60  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     61  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     62  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     63  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     64  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     65  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     66  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     67  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     68  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     69  * SUCH DAMAGE.
     70  */
     71 
     72 /*
     73  * Copyright (C) 1997 and 1998 WIDE Project.
     74  * All rights reserved.
     75  *
     76  * Redistribution and use in source and binary forms, with or without
     77  * modification, are permitted provided that the following conditions
     78  * are met:
     79  * 1. Redistributions of source code must retain the above copyright
     80  *    notice, this list of conditions and the following disclaimer.
     81  * 2. Redistributions in binary form must reproduce the above copyright
     82  *    notice, this list of conditions and the following disclaimer in the
     83  *    documentation and/or other materials provided with the distribution.
     84  * 3. Neither the name of the project nor the names of its contributors
     85  *    may be used to endorse or promote products derived from this software
     86  *    without specific prior written permission.
     87  *
     88  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
     89  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     90  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     91  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
     92  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     93  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     94  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     95  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     96  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     97  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     98  * SUCH DAMAGE.
     99  */
    100 
    101 #include <sys/cdefs.h>
    102 #ifndef lint
    103 __COPYRIGHT(
    104 "@(#) Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994\n\
    105 	The Regents of the University of California.  All rights reserved.\n");
    106 #endif /* not lint */
    107 
    108 #ifndef lint
    109 #if 0
    110 static char sccsid[] = "@(#)ftpd.c	8.5 (Berkeley) 4/28/95";
    111 #else
    112 __RCSID("$NetBSD: ftpd.c,v 1.93 2000/06/14 13:44:24 lukem Exp $");
    113 #endif
    114 #endif /* not lint */
    115 
    116 /*
    117  * FTP server.
    118  */
    119 #include <sys/param.h>
    120 #include <sys/stat.h>
    121 #include <sys/ioctl.h>
    122 #include <sys/socket.h>
    123 #include <sys/wait.h>
    124 
    125 #include <netinet/in.h>
    126 #include <netinet/in_systm.h>
    127 #include <netinet/ip.h>
    128 
    129 #define	FTP_NAMES
    130 #include <arpa/ftp.h>
    131 #include <arpa/inet.h>
    132 #include <arpa/telnet.h>
    133 
    134 #include <ctype.h>
    135 #include <dirent.h>
    136 #include <err.h>
    137 #include <errno.h>
    138 #include <fcntl.h>
    139 #include <fnmatch.h>
    140 #include <glob.h>
    141 #include <grp.h>
    142 #include <limits.h>
    143 #include <netdb.h>
    144 #include <pwd.h>
    145 #include <setjmp.h>
    146 #include <signal.h>
    147 #include <stdarg.h>
    148 #include <stdio.h>
    149 #include <stdlib.h>
    150 #include <string.h>
    151 #include <syslog.h>
    152 #include <time.h>
    153 #include <unistd.h>
    154 #include <util.h>
    155 #include <utmp.h>
    156 #ifdef SKEY
    157 #include <skey.h>
    158 #endif
    159 #ifdef KERBEROS5
    160 #include <com_err.h>
    161 #include <krb5/krb5.h>
    162 #endif
    163 
    164 #define	GLOBAL
    165 #include "extern.h"
    166 #include "pathnames.h"
    167 #include "version.h"
    168 
    169 int	data;
    170 jmp_buf	urgcatch;
    171 struct	passwd *pw;
    172 int	sflag;
    173 int	stru;			/* avoid C keyword */
    174 int	mode;
    175 int	doutmp = 0;		/* update utmp file */
    176 int	mapped = 0;		/* IPv4 connection on AF_INET6 socket */
    177 off_t	file_size;
    178 off_t	byte_count;
    179 static char ttyline[20];
    180 static struct utmp utmp;	/* for utmp */
    181 
    182 static char *anondir = NULL;
    183 static char confdir[MAXPATHLEN];
    184 
    185 #if defined(KERBEROS) || defined(KERBEROS5)
    186 int	has_ccache = 0;
    187 int	notickets = 1;
    188 char	*krbtkfile_env = NULL;
    189 char	*tty = ttyline;
    190 int	login_krb5_forwardable_tgt = 0;
    191 #endif
    192 
    193 int epsvall = 0;
    194 
    195 /*
    196  * Timeout intervals for retrying connections
    197  * to hosts that don't accept PORT cmds.  This
    198  * is a kludge, but given the problems with TCP...
    199  */
    200 #define	SWAITMAX	90	/* wait at most 90 seconds */
    201 #define	SWAITINT	5	/* interval between retries */
    202 
    203 int	swaitmax = SWAITMAX;
    204 int	swaitint = SWAITINT;
    205 
    206 static int	 bind_pasv_addr(void);
    207 static int	 checkuser(const char *, const char *, int, int, char **);
    208 static int	 checkaccess(const char *);
    209 static void	 dolog(struct sockaddr *);
    210 static void	 end_login(void);
    211 static FILE	*getdatasock(const char *);
    212 static char	*gunique(const char *);
    213 static void	 lostconn(int);
    214 static void	 myoob(int);
    215 static int	 receive_data(FILE *, FILE *);
    216 static int	 send_data(FILE *, FILE *, off_t, int);
    217 static struct passwd *sgetpwnam(const char *);
    218 
    219 int	main(int, char *[]);
    220 
    221 #if defined(KERBEROS)
    222 int	klogin(struct passwd *, char *, char *, char *);
    223 void	kdestroy(void);
    224 #endif
    225 #if defined(KERBEROS5)
    226 int	k5login(struct passwd *, char *, char *, char *);
    227 void	k5destroy(void);
    228 #endif
    229 
    230 int
    231 main(int argc, char *argv[])
    232 {
    233 	int		addrlen, ch, on = 1, tos, keepalive;
    234 #ifdef KERBEROS5
    235 	krb5_error_code	kerror;
    236 #endif
    237 
    238 	connections = 1;
    239 	debug = 0;
    240 	logging = 0;
    241 	pdata = -1;
    242 	sflag = 0;
    243 	usedefault = 1;
    244 	(void)strcpy(confdir, _DEFAULT_CONFDIR);
    245 	hostname[0] = '\0';
    246 
    247 	while ((ch = getopt(argc, argv, "a:c:C:dh:lst:T:u:Uv")) != -1) {
    248 		switch (ch) {
    249 		case 'a':
    250 			anondir = optarg;
    251 			break;
    252 
    253 		case 'c':
    254 			(void)strlcpy(confdir, optarg, sizeof(confdir));
    255 			break;
    256 
    257 		case 'C':
    258 			pw = sgetpwnam(optarg);
    259 			exit(checkaccess(optarg) ? 0 : 1);
    260 			/* NOTREACHED */
    261 
    262 		case 'd':
    263 		case 'v':		/* deprecated */
    264 			debug = 1;
    265 			break;
    266 
    267 		case 'h':
    268 			strlcpy(hostname, optarg, sizeof(hostname));
    269 			break;
    270 
    271 		case 'l':
    272 			logging++;	/* > 1 == extra logging */
    273 			break;
    274 
    275 		case 's':
    276 			sflag = 1;
    277 			break;
    278 
    279 		case 't':
    280 		case 'T':
    281 		case 'u':
    282 			warnx("-%c has been deprecated in favour of ftpd.conf",
    283 			    ch);
    284 			break;
    285 
    286 		case 'U':
    287 			doutmp = 1;
    288 			break;
    289 
    290 		default:
    291 			if (optopt == 'a' || optopt == 'C')
    292 				exit(1);
    293 			warnx("unknown flag -%c ignored", optopt);
    294 			break;
    295 		}
    296 	}
    297 
    298 	/*
    299 	 * LOG_NDELAY sets up the logging connection immediately,
    300 	 * necessary for anonymous ftp's that chroot and can't do it later.
    301 	 */
    302 	openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
    303 	addrlen = sizeof(his_addr); /* xxx */
    304 	if (getpeername(0, (struct sockaddr *)&his_addr, &addrlen) < 0) {
    305 		syslog(LOG_ERR, "getpeername (%s): %m",argv[0]);
    306 		exit(1);
    307 	}
    308 	addrlen = sizeof(ctrl_addr);
    309 	if (getsockname(0, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) {
    310 		syslog(LOG_ERR, "getsockname (%s): %m",argv[0]);
    311 		exit(1);
    312 	}
    313 	if (his_addr.su_family == AF_INET6
    314 	 && IN6_IS_ADDR_V4MAPPED(&his_addr.su_sin6.sin6_addr)) {
    315 #if 1
    316 		/*
    317 		 * IPv4 control connection arrived to AF_INET6 socket.
    318 		 * I hate to do this, but this is the easiest solution.
    319 		 *
    320 		 * The assumption is untrue on SIIT environment.
    321 		 */
    322 		union sockunion tmp_addr;
    323 		const int off = sizeof(struct in6_addr) - sizeof(struct in_addr);
    324 
    325 		tmp_addr = his_addr;
    326 		memset(&his_addr, 0, sizeof(his_addr));
    327 		his_addr.su_sin.sin_family = AF_INET;
    328 		his_addr.su_sin.sin_len = sizeof(his_addr.su_sin);
    329 		memcpy(&his_addr.su_sin.sin_addr,
    330 			&tmp_addr.su_sin6.sin6_addr.s6_addr[off],
    331 			sizeof(his_addr.su_sin.sin_addr));
    332 		his_addr.su_sin.sin_port = tmp_addr.su_sin6.sin6_port;
    333 
    334 		tmp_addr = ctrl_addr;
    335 		memset(&ctrl_addr, 0, sizeof(ctrl_addr));
    336 		ctrl_addr.su_sin.sin_family = AF_INET;
    337 		ctrl_addr.su_sin.sin_len = sizeof(ctrl_addr.su_sin);
    338 		memcpy(&ctrl_addr.su_sin.sin_addr,
    339 			&tmp_addr.su_sin6.sin6_addr.s6_addr[off],
    340 			sizeof(ctrl_addr.su_sin.sin_addr));
    341 		ctrl_addr.su_sin.sin_port = tmp_addr.su_sin6.sin6_port;
    342 #else
    343 		while (fgets(line, sizeof(line), fd) != NULL) {
    344 			if ((cp = strchr(line, '\n')) != NULL)
    345 				*cp = '\0';
    346 			lreply(530, "%s", line);
    347 		}
    348 		(void) fflush(stdout);
    349 		(void) fclose(fd);
    350 		reply(530,
    351 			"Connection from IPv4 mapped address is not supported.");
    352 		exit(0);
    353 #endif
    354 
    355 		mapped = 1;
    356 	} else
    357 		mapped = 0;
    358 #ifdef IP_TOS
    359 	if (!mapped && his_addr.su_family == AF_INET) {
    360 		tos = IPTOS_LOWDELAY;
    361 		if (setsockopt(0, IPPROTO_IP, IP_TOS, (char *)&tos,
    362 			       sizeof(int)) < 0)
    363 			syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
    364 	}
    365 #endif
    366 	data_source.su_port = htons(ntohs(ctrl_addr.su_port) - 1);
    367 
    368 	/* if the hostname hasn't been given, attempt to determine it */
    369 	if (hostname[0] == '\0') {
    370 		if (getnameinfo((struct sockaddr *)&ctrl_addr, ctrl_addr.su_len,
    371 		    hostname, sizeof(hostname), NULL, 0, 0) != 0)
    372 			(void)gethostname(hostname, sizeof(hostname));
    373 		hostname[sizeof(hostname) - 1] = '\0';
    374 	}
    375 
    376 	/* set this here so klogin can use it... */
    377 	(void)snprintf(ttyline, sizeof(ttyline), "ftp%d", getpid());
    378 
    379 	(void) freopen(_PATH_DEVNULL, "w", stderr);
    380 	(void) signal(SIGPIPE, lostconn);
    381 	(void) signal(SIGCHLD, SIG_IGN);
    382 	if (signal(SIGURG, myoob) == SIG_ERR)
    383 		syslog(LOG_ERR, "signal: %m");
    384 
    385 	/* Try to handle urgent data inline */
    386 #ifdef SO_OOBINLINE
    387 	if (setsockopt(0, SOL_SOCKET, SO_OOBINLINE, (char *)&on, sizeof(on)) < 0)
    388 		syslog(LOG_ERR, "setsockopt: %m");
    389 #endif
    390 	/* Set keepalives on the socket to detect dropped connections.  */
    391 #ifdef SO_KEEPALIVE
    392 	keepalive = 1;
    393 	if (setsockopt(0, SOL_SOCKET, SO_KEEPALIVE, (char *)&keepalive,
    394 	    sizeof(int)) < 0)
    395 		syslog(LOG_WARNING, "setsockopt (SO_KEEPALIVE): %m");
    396 #endif
    397 
    398 #ifdef	F_SETOWN
    399 	if (fcntl(fileno(stdin), F_SETOWN, getpid()) == -1)
    400 		syslog(LOG_ERR, "fcntl F_SETOWN: %m");
    401 #endif
    402 	dolog((struct sockaddr *)&his_addr);
    403 	/*
    404 	 * Set up default state
    405 	 */
    406 	data = -1;
    407 	type = TYPE_A;
    408 	form = FORM_N;
    409 	stru = STRU_F;
    410 	mode = MODE_S;
    411 	tmpline[0] = '\0';
    412 	hasyyerrored = 0;
    413 
    414 #ifdef KERBEROS5
    415 	kerror = krb5_init_context(&kcontext);
    416 	if (kerror) {
    417 		syslog(LOG_NOTICE, "%s when initializing Kerberos context",
    418 		    error_message(kerror));
    419 		exit(0);
    420 	}
    421 #endif /* KERBEROS5 */
    422 
    423 	init_curclass();
    424 	curclass.timeout = 300;		/* 5 minutes, as per login(1) */
    425 	curclass.type = CLASS_REAL;
    426 
    427 	/* If logins are disabled, print out the message. */
    428 	if (format_file(_PATH_NOLOGIN, 530)) {
    429 		reply(530, "System not available.");
    430 		exit(0);
    431 	}
    432 	(void)format_file(conffilename(_PATH_FTPWELCOME), 220);
    433 		/* reply(220,) must follow */
    434 	reply(220, "%s FTP server (%s) ready.", hostname, FTPD_VERSION);
    435 
    436 	(void) setjmp(errcatch);
    437 	for (;;)
    438 		(void) yyparse();
    439 	/* NOTREACHED */
    440 }
    441 
    442 static void
    443 lostconn(int signo)
    444 {
    445 
    446 	if (debug)
    447 		syslog(LOG_DEBUG, "lost connection");
    448 	dologout(1);
    449 }
    450 
    451 /*
    452  * Save the result of a getpwnam.  Used for USER command, since
    453  * the data returned must not be clobbered by any other command
    454  * (e.g., globbing).
    455  */
    456 static struct passwd *
    457 sgetpwnam(const char *name)
    458 {
    459 	static struct passwd save;
    460 	struct passwd *p;
    461 
    462 	if ((p = getpwnam(name)) == NULL)
    463 		return (p);
    464 	if (save.pw_name) {
    465 		free((char *)save.pw_name);
    466 		memset(save.pw_passwd, 0, strlen(save.pw_passwd));
    467 		free((char *)save.pw_passwd);
    468 		free((char *)save.pw_gecos);
    469 		free((char *)save.pw_dir);
    470 		free((char *)save.pw_shell);
    471 	}
    472 	save = *p;
    473 	save.pw_name = xstrdup(p->pw_name);
    474 	save.pw_passwd = xstrdup(p->pw_passwd);
    475 	save.pw_gecos = xstrdup(p->pw_gecos);
    476 	save.pw_dir = xstrdup(p->pw_dir);
    477 	save.pw_shell = xstrdup(p->pw_shell);
    478 	return (&save);
    479 }
    480 
    481 static int	login_attempts;	/* number of failed login attempts */
    482 static int	askpasswd;	/* had user command, ask for passwd */
    483 static char	curname[10];	/* current USER name */
    484 
    485 /*
    486  * USER command.
    487  * Sets global passwd pointer pw if named account exists and is acceptable;
    488  * sets askpasswd if a PASS command is expected.  If logged in previously,
    489  * need to reset state.  If name is "ftp" or "anonymous", the name is not in
    490  * _PATH_FTPUSERS, and ftp account exists, set guest and pw, then just return.
    491  * If account doesn't exist, ask for passwd anyway.  Otherwise, check user
    492  * requesting login privileges.  Disallow anyone who does not have a standard
    493  * shell as returned by getusershell().  Disallow anyone mentioned in the file
    494  * _PATH_FTPUSERS to allow people such as root and uucp to be avoided.
    495  */
    496 void
    497 user(const char *name)
    498 {
    499 	if (logged_in) {
    500 		switch (curclass.type) {
    501 		case CLASS_GUEST:
    502 			reply(530, "Can't change user from guest login.");
    503 			return;
    504 		case CLASS_CHROOT:
    505 			reply(530, "Can't change user from chroot user.");
    506 			return;
    507 		case CLASS_REAL:
    508 			end_login();
    509 			break;
    510 		default:
    511 			abort();
    512 		}
    513 	}
    514 
    515 #if defined(KERBEROS)
    516 	kdestroy();
    517 #endif
    518 #if defined(KERBEROS5)
    519 	k5destroy();
    520 #endif
    521 
    522 	curclass.type = CLASS_REAL;
    523 	if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) {
    524 			/* need `pw' setup for checkaccess() and checkuser () */
    525 		if ((pw = sgetpwnam("ftp")) == NULL)
    526 			reply(530, "User %s unknown.", name);
    527 		else if (! checkaccess("ftp") || ! checkaccess("anonymous"))
    528 			reply(530, "User %s access denied.", name);
    529 		else {
    530 			curclass.type = CLASS_GUEST;
    531 			askpasswd = 1;
    532 			reply(331,
    533 			    "Guest login ok, type your name as password.");
    534 		}
    535 		if (!askpasswd && logging)
    536 			syslog(LOG_NOTICE,
    537 			    "ANONYMOUS FTP LOGIN REFUSED FROM %s", remotehost);
    538 		return;
    539 	}
    540 
    541 	pw = sgetpwnam(name);
    542 	if (logging)
    543 		strlcpy(curname, name, sizeof(curname));
    544 
    545 #ifdef SKEY
    546 	if (skey_haskey(name) == 0) {
    547 		char *myskey;
    548 
    549 		myskey = skey_keyinfo(name);
    550 		reply(331, "Password [%s] required for %s.",
    551 		    myskey ? myskey : "error getting challenge", name);
    552 	} else
    553 #endif
    554 		reply(331, "Password required for %s.", name);
    555 
    556 	askpasswd = 1;
    557 	/*
    558 	 * Delay before reading passwd after first failed
    559 	 * attempt to slow down passwd-guessing programs.
    560 	 */
    561 	if (login_attempts)
    562 		sleep((unsigned) login_attempts);
    563 }
    564 
    565 /*
    566  * Determine whether something is to happen (allow access, chroot)
    567  * for a user. Each line is a shell-style glob followed by
    568  * `yes' or `no'.
    569  *
    570  * For backward compatability, `allow' and `deny' are synonymns
    571  * for `yes' and `no', respectively.
    572  *
    573  * Each glob is matched against the username in turn, and the first
    574  * match found is used. If no match is found, the result is the
    575  * argument `def'. If a match is found but without and explicit
    576  * `yes'/`no', the result is the opposite of def.
    577  *
    578  * If the file doesn't exist at all, the result is the argument
    579  * `nofile'
    580  *
    581  * Any line starting with `#' is considered a comment and ignored.
    582  *
    583  * Returns 0 if the user is denied, or 1 if they are allowed.
    584  *
    585  * NOTE: needs struct passwd *pw setup before use.
    586  */
    587 int
    588 checkuser(const char *fname, const char *name, int def, int nofile,
    589 	    char **retclass)
    590 {
    591 	FILE	*fd;
    592 	int	 retval;
    593 	char	*glob, *perm, *class, *buf, *p;
    594 	size_t	 len, line;
    595 
    596 	retval = def;
    597 	if (retclass != NULL)
    598 		*retclass = NULL;
    599 	if ((fd = fopen(conffilename(fname), "r")) == NULL)
    600 		return nofile;
    601 
    602 	line = 0;
    603 	for (;
    604 	    (buf = fparseln(fd, &len, &line, NULL, FPARSELN_UNESCCOMM |
    605 	    		FPARSELN_UNESCCONT | FPARSELN_UNESCESC)) != NULL;
    606 	    free(buf), buf = NULL) {
    607 		glob = perm = class = NULL;
    608 		p = buf;
    609 		if (len < 1)
    610 			continue;
    611 		if (p[len - 1] == '\n')
    612 			p[--len] = '\0';
    613 		if (EMPTYSTR(p))
    614 			continue;
    615 
    616 		NEXTWORD(p, glob);
    617 		NEXTWORD(p, perm);
    618 		NEXTWORD(p, class);
    619 		if (EMPTYSTR(glob))
    620 			continue;
    621 		if (!EMPTYSTR(class)) {
    622 			if (strcasecmp(class, "all") == 0 ||
    623 			    strcasecmp(class, "none") == 0) {
    624 				syslog(LOG_WARNING,
    625 		"%s line %d: illegal user-defined class `%s' - skipping entry",
    626 					    fname, (int)line, class);
    627 				continue;
    628 			}
    629 		}
    630 
    631 					/* have a host specifier */
    632 		if ((p = strchr(glob, '@')) != NULL) {
    633 			u_int32_t	net, mask, addr;
    634 			int		bits;
    635 
    636 			*p++ = '\0';
    637 					/* check against network or CIDR */
    638 			if (isdigit(*p) &&
    639 			    (bits = inet_net_pton(AF_INET, p,
    640 			    &net, sizeof(net))) != -1) {
    641 				net = ntohl(net);
    642 				mask = 0xffffffffU << (32 - bits);
    643 				addr = ntohl(his_addr.su_sin.sin_addr.s_addr);
    644 				if ((addr & mask) != net)
    645 					continue;
    646 
    647 					/* check against hostname glob */
    648 			} else if (fnmatch(p, remotehost, 0) != 0)
    649 				continue;
    650 		}
    651 
    652 					/* have a group specifier */
    653 		if ((p = strchr(glob, ':')) != NULL) {
    654 			gid_t	*groups, *ng;
    655 			int	 gsize, i, found;
    656 
    657 			*p++ = '\0';
    658 			groups = NULL;
    659 			gsize = 16;
    660 			do {
    661 				ng = realloc(groups, gsize * sizeof(gid_t));
    662 				if (ng == NULL)
    663 					fatal(
    664 					    "Local resource failure: realloc");
    665 				groups = ng;
    666 			} while (getgrouplist(pw->pw_name, pw->pw_gid,
    667 						groups, &gsize) == -1);
    668 			found = 0;
    669 			for (i = 0; i < gsize; i++) {
    670 				struct group *g;
    671 
    672 				if ((g = getgrgid(groups[i])) == NULL)
    673 					continue;
    674 				if (fnmatch(p, g->gr_name, 0) == 0) {
    675 					found = 1;
    676 					break;
    677 				}
    678 			}
    679 			free(groups);
    680 			if (!found)
    681 				continue;
    682 		}
    683 
    684 					/* check against username glob */
    685 		if (fnmatch(glob, name, 0) != 0)
    686 			continue;
    687 
    688 		if (perm != NULL &&
    689 		    ((strcasecmp(perm, "allow") == 0) ||
    690 		     (strcasecmp(perm, "yes") == 0)))
    691 			retval = 1;
    692 		else if (perm != NULL &&
    693 		    ((strcasecmp(perm, "deny") == 0) ||
    694 		     (strcasecmp(perm, "no") == 0)))
    695 			retval = 0;
    696 		else
    697 			retval = !def;
    698 		if (!EMPTYSTR(class) && retclass != NULL)
    699 			*retclass = xstrdup(class);
    700 		free(buf);
    701 		break;
    702 	}
    703 	(void) fclose(fd);
    704 	return (retval);
    705 }
    706 
    707 /*
    708  * Check if user is allowed by /etc/ftpusers
    709  * returns 1 for yes, 0 for no
    710  *
    711  * NOTE: needs struct passwd *pw setup (for checkuser())
    712  */
    713 int
    714 checkaccess(const char *name)
    715 {
    716 
    717 	return (checkuser(_PATH_FTPUSERS, name, 1, 0, NULL));
    718 }
    719 
    720 /*
    721  * Terminate login as previous user, if any, resetting state;
    722  * used when USER command is given or login fails.
    723  */
    724 static void
    725 end_login(void)
    726 {
    727 
    728 	(void) seteuid((uid_t)0);
    729 	if (logged_in) {
    730 		logwtmp(ttyline, "", "");
    731 		if (doutmp)
    732 			logout(utmp.ut_line);
    733 	}
    734 	pw = NULL;
    735 	logged_in = 0;
    736 	quietmessages = 0;
    737 	curclass.type = CLASS_REAL;
    738 }
    739 
    740 void
    741 pass(const char *passwd)
    742 {
    743 	int		 rval;
    744 	const char	*cp, *shell, *home;
    745 	char		*class;
    746 
    747 	class = NULL;
    748 	if (logged_in || askpasswd == 0) {
    749 		reply(503, "Login with USER first.");
    750 		return;
    751 	}
    752 	askpasswd = 0;
    753 	if (curclass.type != CLASS_GUEST) {
    754 				/* "ftp" is only account allowed no password */
    755 		if (pw == NULL) {
    756 			rval = 1;	/* failure below */
    757 			goto skip;
    758 		}
    759 #if defined(KERBEROS)
    760 		if (klogin(pw, "", hostname, (char *)passwd) == 0) {
    761 			rval = 0;
    762 			goto skip;
    763 		}
    764 #endif
    765 #if defined(KERBEROS5)
    766 		if (k5login(pw, "", hostname, (char *)passwd) == 0) {
    767 			rval = 0;
    768 			goto skip;
    769 		}
    770 #endif
    771 #ifdef SKEY
    772 		if (skey_haskey(pw->pw_name) == 0) {
    773 			char *p;
    774 			int r;
    775 
    776 			p = xstrdup(passwd);
    777 			r = skey_passcheck(pw->pw_name, p);
    778 			free(p);
    779 			if (r != -1) {
    780 				rval = 0;
    781 				goto skip;
    782 			}
    783 		}
    784 #endif
    785 		if (!sflag && *pw->pw_passwd != '\0' &&
    786 		    !strcmp(crypt(passwd, pw->pw_passwd), pw->pw_passwd)) {
    787 			rval = 0;
    788 			goto skip;
    789 		}
    790 		rval = 1;
    791 
    792  skip:
    793 		if (pw != NULL && pw->pw_expire && time(NULL) >= pw->pw_expire)
    794 			rval = 2;
    795 		/*
    796 		 * If rval > 0, the user failed the authentication check
    797 		 * above.  If rval == 0, either Kerberos or local authentication
    798 		 * succeeded.
    799 		 */
    800 		if (rval) {
    801 			reply(530, rval == 2 ? "Password expired." :
    802 			    "Login incorrect.");
    803 			if (logging) {
    804 				syslog(LOG_NOTICE,
    805 				    "FTP LOGIN FAILED FROM %s", remotehost);
    806 				syslog(LOG_AUTHPRIV | LOG_NOTICE,
    807 				    "FTP LOGIN FAILED FROM %s, %s",
    808 				    remotehost, curname);
    809 			}
    810 			pw = NULL;
    811 			if (login_attempts++ >= 5) {
    812 				syslog(LOG_NOTICE,
    813 				    "repeated login failures from %s",
    814 				    remotehost);
    815 				exit(0);
    816 			}
    817 			return;
    818 		}
    819 	}
    820 
    821 	/* password was ok; see if anything else prevents login */
    822 	if (! checkuser(_PATH_FTPUSERS, pw->pw_name, 1, 0, &class)) {
    823 		reply(530, "User %s may not use FTP.", pw->pw_name);
    824 		if (logging)
    825 			syslog(LOG_NOTICE, "FTP LOGIN REFUSED FROM %s, %s",
    826 			    remotehost, pw->pw_name);
    827 		goto bad;
    828 	}
    829 	/* check for valid shell, if not guest user */
    830 	if ((shell = pw->pw_shell) == NULL || *shell == 0)
    831 		shell = _PATH_BSHELL;
    832 	while ((cp = getusershell()) != NULL)
    833 		if (strcmp(cp, shell) == 0)
    834 			break;
    835 	endusershell();
    836 	if (cp == NULL && curclass.type != CLASS_GUEST) {
    837 		reply(530, "User %s may not use FTP.", pw->pw_name);
    838 		if (logging)
    839 			syslog(LOG_NOTICE, "FTP LOGIN REFUSED FROM %s, %s",
    840 			    remotehost, pw->pw_name);
    841 		goto bad;
    842 	}
    843 
    844 	login_attempts = 0;		/* this time successful */
    845 	if (setegid((gid_t)pw->pw_gid) < 0) {
    846 		reply(550, "Can't set gid.");
    847 		goto bad;
    848 	}
    849 	(void) initgroups(pw->pw_name, pw->pw_gid);
    850 
    851 	/* open wtmp before chroot */
    852 	logwtmp(ttyline, pw->pw_name, remotehost);
    853 
    854 	/* open utmp before chroot */
    855 	if (doutmp) {
    856 		memset((void *)&utmp, 0, sizeof(utmp));
    857 		(void)time(&utmp.ut_time);
    858 		(void)strncpy(utmp.ut_name, pw->pw_name, sizeof(utmp.ut_name));
    859 		(void)strncpy(utmp.ut_host, remotehost, sizeof(utmp.ut_host));
    860 		(void)strncpy(utmp.ut_line, ttyline, sizeof(utmp.ut_line));
    861 		login(&utmp);
    862 	}
    863 
    864 	logged_in = 1;
    865 
    866 			/* check user in /etc/ftpchroot */
    867 	if (checkuser(_PATH_FTPCHROOT, pw->pw_name, 0, 0, NULL)) {
    868 		if (curclass.type == CLASS_GUEST) {
    869 			syslog(LOG_NOTICE,
    870 	    "Can't change guest user to chroot class; remove entry in %s",
    871 			    _PATH_FTPCHROOT);
    872 			exit(1);
    873 		}
    874 		curclass.type = CLASS_CHROOT;
    875 	}
    876 	if (class == NULL) {
    877 		switch (curclass.type) {
    878 		case CLASS_GUEST:
    879 			class = xstrdup("guest");
    880 			break;
    881 		case CLASS_CHROOT:
    882 			class = xstrdup("chroot");
    883 			break;
    884 		case CLASS_REAL:
    885 			class = xstrdup("real");
    886 			break;
    887 		default:
    888 			abort();
    889 		}
    890 	}
    891 
    892 	/* parse ftpd.conf, setting up various parameters */
    893 	parse_conf(class);
    894 	count_users();
    895 	if (curclass.limit != -1 && connections > curclass.limit) {
    896 		if (! EMPTYSTR(curclass.limitfile))
    897 			(void)format_file(conffilename(curclass.limitfile),530);
    898 		reply(530,
    899 		    "User %s access denied, connection limit of %d reached.",
    900 		    pw->pw_name, curclass.limit);
    901 		syslog(LOG_NOTICE,
    902 	"Maximum connection limit of %d for class %s reached, login refused",
    903 		    curclass.limit, curclass.classname);
    904 		goto bad;
    905 	}
    906 
    907 	home = "/";
    908 	switch (curclass.type) {
    909 	case CLASS_GUEST:
    910 		/*
    911 		 * We MUST do a chdir() after the chroot. Otherwise
    912 		 * the old current directory will be accessible as "."
    913 		 * outside the new root!
    914 		 */
    915 		if (chroot(anondir ? anondir : pw->pw_dir) < 0 ||
    916 		    chdir("/") < 0) {
    917 			reply(550, "Can't set guest privileges.");
    918 			goto bad;
    919 		}
    920 		break;
    921 	case CLASS_CHROOT:
    922 		if (chroot(pw->pw_dir) < 0 || chdir("/") < 0) {
    923 			reply(550, "Can't change root.");
    924 			goto bad;
    925 		}
    926 		break;
    927 	case CLASS_REAL:
    928 		if (chdir(pw->pw_dir) < 0) {
    929 			if (chdir("/") < 0) {
    930 				reply(530,
    931 				    "User %s: can't change directory to %s.",
    932 				    pw->pw_name, pw->pw_dir);
    933 				goto bad;
    934 			} else
    935 				lreply(230,
    936 				    "No directory! Logging in with home=/");
    937 		} else
    938 			home = pw->pw_dir;
    939 		break;
    940 	}
    941 	if (seteuid((uid_t)pw->pw_uid) < 0) {
    942 		reply(550, "Can't set uid.");
    943 		goto bad;
    944 	}
    945 	setenv("HOME", home, 1);
    946 
    947 	if (curclass.type == CLASS_GUEST && passwd[0] == '-')
    948 		quietmessages = 1;
    949 
    950 	/*
    951 	 * Display a login message, if it exists.
    952 	 * N.B. reply(230,) must follow the message.
    953 	 */
    954 	(void)format_file(conffilename(curclass.motd), 230);
    955 	show_chdir_messages(230);
    956 	if (curclass.type == CLASS_GUEST) {
    957 		reply(230, "Guest login ok, access restrictions apply.");
    958 #ifdef HASSETPROCTITLE
    959 		snprintf(proctitle, sizeof(proctitle),
    960 		    "%s: anonymous/%.*s", remotehost,
    961 		    (int) (sizeof(proctitle) - sizeof(remotehost) -
    962 		    sizeof(": anonymous/")), passwd);
    963 		setproctitle(proctitle);
    964 #endif /* HASSETPROCTITLE */
    965 		if (logging)
    966 			syslog(LOG_INFO,
    967 			"ANONYMOUS FTP LOGIN FROM %s, %s (class: %s, type: %s)",
    968 			    remotehost, passwd,
    969 			    curclass.classname, CURCLASSTYPE);
    970 	} else {
    971 		reply(230, "User %s logged in.", pw->pw_name);
    972 #ifdef HASSETPROCTITLE
    973 		snprintf(proctitle, sizeof(proctitle),
    974 		    "%s: %s", remotehost, pw->pw_name);
    975 		setproctitle(proctitle);
    976 #endif /* HASSETPROCTITLE */
    977 		if (logging)
    978 			syslog(LOG_INFO,
    979 			    "FTP LOGIN FROM %s as %s (class: %s, type: %s)",
    980 			    remotehost, pw->pw_name,
    981 			    curclass.classname, CURCLASSTYPE);
    982 	}
    983 	(void) umask(curclass.umask);
    984 	goto cleanuppass;
    985  bad:
    986 	/* Forget all about it... */
    987 	end_login();
    988  cleanuppass:
    989 	if (class)
    990 		free(class);
    991 }
    992 
    993 void
    994 retrieve(char *argv[], const char *name)
    995 {
    996 	FILE *fin = NULL, *dout;
    997 	struct stat st;
    998 	int (*closefunc)(FILE *) = NULL;
    999 	int log, sendrv, closerv, stderrfd, isconversion, isdata, isls;
   1000 	struct timeval start, finish, td, *tdp;
   1001 	const char *dispname;
   1002 
   1003 	sendrv = closerv = stderrfd = -1;
   1004 	isconversion = isdata = isls = log = 0;
   1005 	tdp = NULL;
   1006 	dispname = name;
   1007 	if (argv == NULL) {
   1008 		log = 1;
   1009 		isdata = 1;
   1010 		fin = fopen(name, "r");
   1011 		closefunc = fclose;
   1012 		if (fin == NULL)
   1013 			argv = do_conversion(name);
   1014 		if (argv != NULL) {
   1015 			isconversion++;
   1016 			syslog(LOG_INFO, "get command: '%s' on '%s'",
   1017 			    argv[0], name);
   1018 		}
   1019 	}
   1020 	if (argv != NULL) {
   1021 		char temp[MAXPATHLEN];
   1022 
   1023 		if (strcmp(argv[0], INTERNAL_LS) == 0) {
   1024 			isls = 1;
   1025 			stderrfd = -1;
   1026 		} else {
   1027 			(void)snprintf(temp, sizeof(temp), "%s", TMPFILE);
   1028 			stderrfd = mkstemp(temp);
   1029 			if (stderrfd != -1)
   1030 				(void)unlink(temp);
   1031 		}
   1032 		dispname = argv[0];
   1033 		fin = ftpd_popen(argv, "r", stderrfd);
   1034 		closefunc = ftpd_pclose;
   1035 		st.st_size = -1;
   1036 		st.st_blksize = BUFSIZ;
   1037 	}
   1038 	if (fin == NULL) {
   1039 		if (errno != 0) {
   1040 			perror_reply(550, dispname);
   1041 			if (log)
   1042 				logcmd("get", -1, name, NULL, NULL,
   1043 				    strerror(errno));
   1044 		}
   1045 		goto cleanupretrieve;
   1046 	}
   1047 	byte_count = -1;
   1048 	if (argv == NULL
   1049 	    && (fstat(fileno(fin), &st) < 0 || !S_ISREG(st.st_mode))) {
   1050 		reply(550, "%s: not a plain file.", dispname);
   1051 		goto done;
   1052 	}
   1053 	if (restart_point) {
   1054 		if (type == TYPE_A) {
   1055 			off_t i;
   1056 			int c;
   1057 
   1058 			for (i = 0; i < restart_point; i++) {
   1059 				if ((c=getc(fin)) == EOF) {
   1060 					perror_reply(550, dispname);
   1061 					goto done;
   1062 				}
   1063 				if (c == '\n')
   1064 					i++;
   1065 			}
   1066 		} else if (lseek(fileno(fin), restart_point, SEEK_SET) < 0) {
   1067 			perror_reply(550, dispname);
   1068 			goto done;
   1069 		}
   1070 	}
   1071 	dout = dataconn(dispname, st.st_size, "w");
   1072 	if (dout == NULL)
   1073 		goto done;
   1074 
   1075 	(void)gettimeofday(&start, NULL);
   1076 	sendrv = send_data(fin, dout, st.st_blksize, isdata);
   1077 	(void)gettimeofday(&finish, NULL);
   1078 	(void) fclose(dout);
   1079 	timersub(&finish, &start, &td);
   1080 	tdp = &td;
   1081 	data = -1;
   1082  done:
   1083 	if (log)
   1084 		logcmd("get", byte_count, name, NULL, tdp, NULL);
   1085 	closerv = (*closefunc)(fin);
   1086 	if (sendrv == 0) {
   1087 		FILE *err;
   1088 		struct stat sb;
   1089 
   1090 		if (!isls && argv != NULL && closerv != 0) {
   1091 			lreply(226,
   1092 			    "Command returned an exit status of %d",
   1093 			    closerv);
   1094 			if (isconversion)
   1095 				syslog(LOG_INFO,
   1096 				    "retrieve command: '%s' returned %d",
   1097 				    argv[0], closerv);
   1098 		}
   1099 		if (!isls && argv != NULL && stderrfd != -1 &&
   1100 		    (fstat(stderrfd, &sb) == 0) && sb.st_size > 0 &&
   1101 		    ((err = fdopen(stderrfd, "r")) != NULL)) {
   1102 			char *cp, line[LINE_MAX];
   1103 
   1104 			lreply(226, "Command error messages:");
   1105 			rewind(err);
   1106 			while (fgets(line, sizeof(line), err) != NULL) {
   1107 				if ((cp = strchr(line, '\n')) != NULL)
   1108 					*cp = '\0';
   1109 				lreply(0, "  %s", line);
   1110 			}
   1111 			(void) fflush(stdout);
   1112 			(void) fclose(err);
   1113 				/* a reply(226,) must follow */
   1114 		}
   1115 		reply(226, "Transfer complete.");
   1116 	}
   1117  cleanupretrieve:
   1118 	if (pdata >= 0)
   1119 		(void)close(pdata);
   1120 	pdata = -1;
   1121 	if (stderrfd != -1)
   1122 		(void)close(stderrfd);
   1123 	if (isconversion)
   1124 		free(argv);
   1125 }
   1126 
   1127 void
   1128 store(const char *name, const char *mode, int unique)
   1129 {
   1130 	FILE *fout, *din;
   1131 	struct stat st;
   1132 	int (*closefunc)(FILE *);
   1133 	struct timeval start, finish, td, *tdp;
   1134 	char *desc;
   1135 
   1136 	desc = (*mode == 'w') ? "put" : "append";
   1137 	if (unique && stat(name, &st) == 0 &&
   1138 	    (name = gunique(name)) == NULL) {
   1139 		logcmd(desc, -1, name, NULL, NULL, "cannot create unique file");
   1140 		goto cleanupstore;
   1141 	}
   1142 
   1143 	if (restart_point)
   1144 		mode = "r+";
   1145 	fout = fopen(name, mode);
   1146 	closefunc = fclose;
   1147 	tdp = NULL;
   1148 	if (fout == NULL) {
   1149 		perror_reply(553, name);
   1150 		logcmd(desc, -1, name, NULL, NULL, strerror(errno));
   1151 		goto cleanupstore;
   1152 	}
   1153 	byte_count = -1;
   1154 	if (restart_point) {
   1155 		if (type == TYPE_A) {
   1156 			off_t i;
   1157 			int c;
   1158 
   1159 			for (i = 0; i < restart_point; i++) {
   1160 				if ((c=getc(fout)) == EOF) {
   1161 					perror_reply(550, name);
   1162 					goto done;
   1163 				}
   1164 				if (c == '\n')
   1165 					i++;
   1166 			}
   1167 			/*
   1168 			 * We must do this seek to "current" position
   1169 			 * because we are changing from reading to
   1170 			 * writing.
   1171 			 */
   1172 			if (fseek(fout, 0L, SEEK_CUR) < 0) {
   1173 				perror_reply(550, name);
   1174 				goto done;
   1175 			}
   1176 		} else if (lseek(fileno(fout), restart_point, SEEK_SET) < 0) {
   1177 			perror_reply(550, name);
   1178 			goto done;
   1179 		}
   1180 	}
   1181 	din = dataconn(name, (off_t)-1, "r");
   1182 	if (din == NULL)
   1183 		goto done;
   1184 	(void)gettimeofday(&start, NULL);
   1185 	if (receive_data(din, fout) == 0) {
   1186 		if (unique)
   1187 			reply(226, "Transfer complete (unique file name:%s).",
   1188 			    name);
   1189 		else
   1190 			reply(226, "Transfer complete.");
   1191 	}
   1192 	(void)gettimeofday(&finish, NULL);
   1193 	(void) fclose(din);
   1194 	timersub(&finish, &start, &td);
   1195 	tdp = &td;
   1196 	data = -1;
   1197  done:
   1198 	logcmd(desc, byte_count, name, NULL, tdp, NULL);
   1199 	(*closefunc)(fout);
   1200  cleanupstore:
   1201 	if (pdata >= 0)
   1202 		(void)close(pdata);
   1203 	pdata = -1;
   1204 }
   1205 
   1206 static FILE *
   1207 getdatasock(const char *mode)
   1208 {
   1209 	int on = 1, s, t, tries;
   1210 
   1211 	if (data >= 0)
   1212 		return (fdopen(data, mode));
   1213 	(void) seteuid((uid_t)0);
   1214 	s = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
   1215 	if (s < 0)
   1216 		goto bad;
   1217 	if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
   1218 	    (char *) &on, sizeof(on)) < 0)
   1219 		goto bad;
   1220 	if (setsockopt(s, SOL_SOCKET, SO_KEEPALIVE,
   1221 	    (char *) &on, sizeof(on)) < 0)
   1222 		goto bad;
   1223 	/* anchor socket to avoid multi-homing problems */
   1224 	data_source = ctrl_addr;
   1225 	data_source.su_port = htons(20); /* ftp-data port */
   1226 	for (tries = 1; ; tries++) {
   1227 		if (bind(s, (struct sockaddr *)&data_source,
   1228 		    data_source.su_len) >= 0)
   1229 			break;
   1230 		if (errno != EADDRINUSE || tries > 10)
   1231 			goto bad;
   1232 		sleep(tries);
   1233 	}
   1234 	(void) seteuid((uid_t)pw->pw_uid);
   1235 #ifdef IP_TOS
   1236 	if (!mapped && ctrl_addr.su_family == AF_INET) {
   1237 		on = IPTOS_THROUGHPUT;
   1238 		if (setsockopt(s, IPPROTO_IP, IP_TOS, (char *)&on,
   1239 			       sizeof(int)) < 0)
   1240 			syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
   1241 	}
   1242 #endif
   1243 	return (fdopen(s, mode));
   1244  bad:
   1245 	/* Return the real value of errno (close may change it) */
   1246 	t = errno;
   1247 	(void) seteuid((uid_t)pw->pw_uid);
   1248 	(void) close(s);
   1249 	errno = t;
   1250 	return (NULL);
   1251 }
   1252 
   1253 FILE *
   1254 dataconn(const char *name, off_t size, const char *mode)
   1255 {
   1256 	char sizebuf[32];
   1257 	FILE *file;
   1258 	int retry = 0, tos, keepalive;
   1259 
   1260 	file_size = size;
   1261 	byte_count = 0;
   1262 	if (size != (off_t) -1)
   1263 		(void)snprintf(sizebuf, sizeof(sizebuf), " (%qd byte%s)",
   1264 		    (qdfmt_t)size, PLURAL(size));
   1265 	else
   1266 		sizebuf[0] = '\0';
   1267 	if (pdata >= 0) {
   1268 		union sockunion from;
   1269 		int s, fromlen = sizeof(from);
   1270 
   1271 		(void) alarm(curclass.timeout);
   1272 		s = accept(pdata, (struct sockaddr *)&from, &fromlen);
   1273 		(void) alarm(0);
   1274 		if (s < 0) {
   1275 			reply(425, "Can't open data connection.");
   1276 			(void) close(pdata);
   1277 			pdata = -1;
   1278 			return (NULL);
   1279 		}
   1280 		(void) close(pdata);
   1281 		pdata = s;
   1282 		switch (from.su_family) {
   1283 		case AF_INET:
   1284 #ifdef IP_TOS
   1285 			if (!mapped) {
   1286 				tos = IPTOS_THROUGHPUT;
   1287 				(void) setsockopt(s, IPPROTO_IP, IP_TOS,
   1288 				    (char *)&tos, sizeof(int));
   1289 			}
   1290 			break;
   1291 #endif
   1292 		}
   1293 		/* Set keepalives on the socket to detect dropped conns. */
   1294 #ifdef SO_KEEPALIVE
   1295 		keepalive = 1;
   1296 		(void) setsockopt(s, SOL_SOCKET, SO_KEEPALIVE,
   1297 		    (char *)&keepalive, sizeof(int));
   1298 #endif
   1299 		reply(150, "Opening %s mode data connection for '%s'%s.",
   1300 		     type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
   1301 		return (fdopen(pdata, mode));
   1302 	}
   1303 	if (data >= 0) {
   1304 		reply(125, "Using existing data connection for '%s'%s.",
   1305 		    name, sizebuf);
   1306 		usedefault = 1;
   1307 		return (fdopen(data, mode));
   1308 	}
   1309 	if (usedefault)
   1310 		data_dest = his_addr;
   1311 	usedefault = 1;
   1312 	file = getdatasock(mode);
   1313 	if (file == NULL) {
   1314 		char hbuf[INET6_ADDRSTRLEN];
   1315 		char pbuf[10];
   1316 		getnameinfo((struct sockaddr *)&data_source, data_source.su_len,
   1317 			hbuf, sizeof(hbuf), pbuf, sizeof(pbuf),
   1318 			NI_NUMERICHOST | NI_NUMERICSERV);
   1319 		reply(425, "Can't create data socket (%s,%s): %s.",
   1320 		      hbuf, pbuf, strerror(errno));
   1321 		return (NULL);
   1322 	}
   1323 	data = fileno(file);
   1324 	while (connect(data, (struct sockaddr *)&data_dest,
   1325 	    data_dest.su_len) < 0) {
   1326 		if (errno == EADDRINUSE && retry < swaitmax) {
   1327 			sleep((unsigned) swaitint);
   1328 			retry += swaitint;
   1329 			continue;
   1330 		}
   1331 		perror_reply(425, "Can't build data connection");
   1332 		(void) fclose(file);
   1333 		data = -1;
   1334 		return (NULL);
   1335 	}
   1336 	reply(150, "Opening %s mode data connection for '%s'%s.",
   1337 	     type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
   1338 	return (file);
   1339 }
   1340 
   1341 /*
   1342  * Tranfer the contents of "instr" to "outstr" peer using the appropriate
   1343  * encapsulation of the data subject * to Mode, Structure, and Type.
   1344  *
   1345  * NB: Form isn't handled.
   1346  */
   1347 static int
   1348 send_data(FILE *instr, FILE *outstr, off_t blksize, int isdata)
   1349 {
   1350 	int	 c, filefd, netfd, rval;
   1351 	char	*buf;
   1352 
   1353 	transflag = 1;
   1354 	rval = -1;
   1355 	buf = NULL;
   1356 	if (setjmp(urgcatch))
   1357 		goto cleanup_send_data;
   1358 
   1359 	switch (type) {
   1360 
   1361 	case TYPE_A:
   1362  /* XXXX: rate limit ascii send (get) */
   1363 		(void) alarm(curclass.timeout);
   1364 		while ((c = getc(instr)) != EOF) {
   1365 			byte_count++;
   1366 			if (c == '\n') {
   1367 				if (ferror(outstr))
   1368 					goto data_err;
   1369 				(void) putc('\r', outstr);
   1370 				if (isdata) {
   1371 					total_data_out++;
   1372 					total_data++;
   1373 				}
   1374 				total_bytes_out++;
   1375 				total_bytes++;
   1376 			}
   1377 			(void) putc(c, outstr);
   1378 			if (isdata) {
   1379 				total_data_out++;
   1380 				total_data++;
   1381 			}
   1382 			total_bytes_out++;
   1383 			total_bytes++;
   1384 			if ((byte_count % 4096) == 0)
   1385 				(void) alarm(curclass.timeout);
   1386 		}
   1387 		(void) alarm(0);
   1388 		fflush(outstr);
   1389 		if (ferror(instr))
   1390 			goto file_err;
   1391 		if (ferror(outstr))
   1392 			goto data_err;
   1393 		rval = 0;
   1394 		goto cleanup_send_data;
   1395 
   1396 	case TYPE_I:
   1397 	case TYPE_L:
   1398 		if ((buf = malloc((size_t)blksize)) == NULL) {
   1399 			perror_reply(451, "Local resource failure: malloc");
   1400 			goto cleanup_send_data;
   1401 		}
   1402 		filefd = fileno(instr);
   1403 		netfd = fileno(outstr);
   1404 		(void) alarm(curclass.timeout);
   1405 		if (curclass.rateget) {
   1406 			while (1) {
   1407 				int d;
   1408 				struct timeval then, now, td;
   1409 				off_t bufrem;
   1410 				char *bufp;
   1411 
   1412 				(void)gettimeofday(&then, NULL);
   1413 				errno = c = d = 0;
   1414 				bufrem = curclass.rateget;
   1415 				while (bufrem > 0) {
   1416 					if ((c = read(filefd, buf,
   1417 					    MIN(blksize, bufrem))) <= 0)
   1418 						goto senddone;
   1419 					(void) alarm(curclass.timeout);
   1420 					bufrem -= c;
   1421 					byte_count += c;
   1422 					if (isdata) {
   1423 						total_data_out += c;
   1424 						total_data += c;
   1425 					}
   1426 					total_bytes_out += c;
   1427 					total_bytes += c;
   1428 					for (bufp = buf; c > 0;
   1429 					    c -= d, bufp += d)
   1430 						if ((d =
   1431 						    write(netfd, bufp, c)) <= 0)
   1432 							break;
   1433 					if (d < 0)
   1434 						goto data_err;
   1435 				}
   1436 				(void)gettimeofday(&now, NULL);
   1437 				timersub(&now, &then, &td);
   1438 				if (td.tv_sec > 0)
   1439 					break;
   1440 				usleep(1000000 - td.tv_usec);
   1441 			}
   1442 		} else {
   1443 			while ((c = read(filefd, buf, (size_t)blksize)) > 0) {
   1444 				if (write(netfd, buf, c) != c)
   1445 					goto data_err;
   1446 				(void) alarm(curclass.timeout);
   1447 				byte_count += c;
   1448 				if (isdata) {
   1449 					total_data_out += c;
   1450 					total_data += c;
   1451 				}
   1452 				total_bytes_out += c;
   1453 				total_bytes += c;
   1454 			}
   1455 		}
   1456  senddone:
   1457 		if (c < 0)
   1458 			goto file_err;
   1459 		rval = 0;
   1460 		goto cleanup_send_data;
   1461 
   1462 	default:
   1463 		reply(550, "Unimplemented TYPE %d in send_data", type);
   1464 		goto cleanup_send_data;
   1465 	}
   1466 
   1467  data_err:
   1468 	(void) alarm(0);
   1469 	perror_reply(426, "Data connection");
   1470 	goto cleanup_send_data;
   1471 
   1472  file_err:
   1473 	(void) alarm(0);
   1474 	perror_reply(551, "Error on input file");
   1475 		/* FALLTHROUGH */
   1476 
   1477  cleanup_send_data:
   1478 	(void) alarm(0);
   1479 	transflag = 0;
   1480 	if (buf)
   1481 		free(buf);
   1482 	if (isdata) {
   1483 		total_files_out++;
   1484 		total_files++;
   1485 	}
   1486 	total_xfers_out++;
   1487 	total_xfers++;
   1488 	return (rval);
   1489 }
   1490 
   1491 /*
   1492  * Transfer data from peer to "outstr" using the appropriate encapulation of
   1493  * the data subject to Mode, Structure, and Type.
   1494  *
   1495  * N.B.: Form isn't handled.
   1496  */
   1497 static int
   1498 receive_data(FILE *instr, FILE *outstr)
   1499 {
   1500 	int	c, bare_lfs, netfd, filefd, rval;
   1501 	char	buf[BUFSIZ];
   1502 #ifdef __GNUC__
   1503 	(void) &bare_lfs;
   1504 #endif
   1505 
   1506 	bare_lfs = 0;
   1507 	transflag = 1;
   1508 	rval = -1;
   1509 	if (setjmp(urgcatch))
   1510 		goto cleanup_recv_data;
   1511 
   1512 	switch (type) {
   1513 
   1514 	case TYPE_I:
   1515 	case TYPE_L:
   1516 		netfd = fileno(instr);
   1517 		filefd = fileno(outstr);
   1518 		(void) alarm(curclass.timeout);
   1519 		if (curclass.rateput) {
   1520 			while (1) {
   1521 				int d;
   1522 				struct timeval then, now, td;
   1523 				off_t bufrem;
   1524 
   1525 				(void)gettimeofday(&then, NULL);
   1526 				errno = c = d = 0;
   1527 				for (bufrem = curclass.rateput; bufrem > 0; ) {
   1528 					if ((c = read(netfd, buf,
   1529 					    MIN(sizeof(buf), bufrem))) <= 0)
   1530 						goto recvdone;
   1531 					if ((d = write(filefd, buf, c)) != c)
   1532 						goto recvdone;
   1533 					(void) alarm(curclass.timeout);
   1534 					bufrem -= c;
   1535 					byte_count += c;
   1536 					total_data_in += c;
   1537 					total_data += c;
   1538 					total_bytes_in += c;
   1539 					total_bytes += c;
   1540 				}
   1541 				(void)gettimeofday(&now, NULL);
   1542 				timersub(&now, &then, &td);
   1543 				if (td.tv_sec > 0)
   1544 					break;
   1545 				usleep(1000000 - td.tv_usec);
   1546 			}
   1547 		} else {
   1548 			while ((c = read(netfd, buf, sizeof(buf))) > 0) {
   1549 				if (write(filefd, buf, c) != c)
   1550 					goto file_err;
   1551 				(void) alarm(curclass.timeout);
   1552 				byte_count += c;
   1553 				total_data_in += c;
   1554 				total_data += c;
   1555 				total_bytes_in += c;
   1556 				total_bytes += c;
   1557 			}
   1558 		}
   1559  recvdone:
   1560 		if (c < 0)
   1561 			goto data_err;
   1562 		rval = 0;
   1563 		goto cleanup_recv_data;
   1564 
   1565 	case TYPE_E:
   1566 		reply(553, "TYPE E not implemented.");
   1567 		goto cleanup_recv_data;
   1568 
   1569 	case TYPE_A:
   1570 		(void) alarm(curclass.timeout);
   1571  /* XXXX: rate limit ascii receive (put) */
   1572 		while ((c = getc(instr)) != EOF) {
   1573 			byte_count++;
   1574 			total_data_in++;
   1575 			total_data++;
   1576 			total_bytes_in++;
   1577 			total_bytes++;
   1578 			if ((byte_count % 4096) == 0)
   1579 				(void) alarm(curclass.timeout);
   1580 			if (c == '\n')
   1581 				bare_lfs++;
   1582 			while (c == '\r') {
   1583 				if (ferror(outstr))
   1584 					goto data_err;
   1585 				if ((c = getc(instr)) != '\n') {
   1586 					byte_count++;
   1587 					total_data_in++;
   1588 					total_data++;
   1589 					total_bytes_in++;
   1590 					total_bytes++;
   1591 					if ((byte_count % 4096) == 0)
   1592 						(void) alarm(curclass.timeout);
   1593 					(void) putc ('\r', outstr);
   1594 					if (c == '\0' || c == EOF)
   1595 						goto contin2;
   1596 				}
   1597 			}
   1598 			(void) putc(c, outstr);
   1599 	contin2:	;
   1600 		}
   1601 		(void) alarm(0);
   1602 		fflush(outstr);
   1603 		if (ferror(instr))
   1604 			goto data_err;
   1605 		if (ferror(outstr))
   1606 			goto file_err;
   1607 		if (bare_lfs) {
   1608 			lreply(226,
   1609 			    "WARNING! %d bare linefeeds received in ASCII mode",
   1610 			    bare_lfs);
   1611 			lreply(0, "File may not have transferred correctly.");
   1612 		}
   1613 		rval = 0;
   1614 		goto cleanup_recv_data;
   1615 
   1616 	default:
   1617 		reply(550, "Unimplemented TYPE %d in receive_data", type);
   1618 		goto cleanup_recv_data;
   1619 	}
   1620 
   1621  data_err:
   1622 	(void) alarm(0);
   1623 	perror_reply(426, "Data Connection");
   1624 	goto cleanup_recv_data;
   1625 
   1626  file_err:
   1627 	(void) alarm(0);
   1628 	perror_reply(452, "Error writing file");
   1629 	goto cleanup_recv_data;
   1630 
   1631  cleanup_recv_data:
   1632 	(void) alarm(0);
   1633 	transflag = 0;
   1634 	total_files_in++;
   1635 	total_files++;
   1636 	total_xfers_in++;
   1637 	total_xfers++;
   1638 	return (rval);
   1639 }
   1640 
   1641 void
   1642 statcmd(void)
   1643 {
   1644 	union sockunion *su = NULL;
   1645 	static char ntop_buf[INET6_ADDRSTRLEN];
   1646   	u_char *a, *p;
   1647 	int ispassive, af;
   1648 	off_t otbi, otbo, otb;
   1649 
   1650 	a = p = (u_char *)NULL;
   1651 
   1652 	lreply(211, "%s FTP server status:", hostname);
   1653 	lreply(0, "Version: %s", FTPD_VERSION);
   1654 	ntop_buf[0] = '\0';
   1655 	if (!getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
   1656 			ntop_buf, sizeof(ntop_buf), NULL, 0, NI_NUMERICHOST)
   1657 	    && strcmp(remotehost, ntop_buf) != 0) {
   1658 		lreply(0, "Connected to %s (%s)", remotehost, ntop_buf);
   1659 	} else
   1660 		lreply(0, "Connected to %s", remotehost);
   1661 	if (logged_in) {
   1662 		if (curclass.type == CLASS_GUEST)
   1663 			lreply(0, "Logged in anonymously");
   1664 		else
   1665 			lreply(0, "Logged in as %s%s", pw->pw_name,
   1666 			    curclass.type == CLASS_CHROOT ? " (chroot)" : "");
   1667 	} else if (askpasswd)
   1668 		lreply(0, "Waiting for password");
   1669 	else
   1670 		lreply(0, "Waiting for user name");
   1671 	lreply(-2, "    TYPE: %s", typenames[type]);
   1672 	if (type == TYPE_A || type == TYPE_E)
   1673 		lreply(-2, ", FORM: %s", formnames[form]);
   1674 	if (type == TYPE_L) {
   1675 #if NBBY == 8
   1676 		lreply(-2, " %d", NBBY);
   1677 #else
   1678 			/* XXX: `bytesize' needs to be defined in this case */
   1679 		lreply(-2, " %d", bytesize);
   1680 #endif
   1681 	}
   1682 	lreply(-1, "; STRUcture: %s; transfer MODE: %s",
   1683 	    strunames[stru], modenames[mode]);
   1684 	ispassive = 0;
   1685 	if (data != -1) {
   1686   		lreply(0, "Data connection open");
   1687 		su = NULL;
   1688 	} else if (pdata != -1) {
   1689 		lreply(0, "in Passive mode");
   1690 		su = (union sockunion *)&pasv_addr;
   1691 		ispassive = 1;
   1692 		goto printaddr;
   1693 	} else if (usedefault == 0) {
   1694 		if (epsvall) {
   1695 			lreply(0, "EPSV only mode (EPSV ALL)");
   1696 			goto epsvonly;
   1697 		}
   1698 		su = (union sockunion *)&data_dest;
   1699  printaddr:
   1700 							/* PASV/PORT */
   1701 		if (su->su_family == AF_INET) {
   1702 			a = (u_char *) &su->su_sin.sin_addr;
   1703 			p = (u_char *) &su->su_sin.sin_port;
   1704 #define UC(b) (((int) b) & 0xff)
   1705 			lreply(0, "%s (%d,%d,%d,%d,%d,%d)",
   1706 				ispassive ? "PASV" : "PORT" ,
   1707 				UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
   1708 				UC(p[0]), UC(p[1]));
   1709 		}
   1710 
   1711 /* XXXLUKEM this code doesn't look right; speak to itojun */
   1712 
   1713 							/* LPSV/LPRT */
   1714 	    {
   1715 		int alen, af, i;
   1716 
   1717 		alen = 0;
   1718 		switch (su->su_family) {
   1719 		case AF_INET:
   1720 			a = (u_char *) &su->su_sin.sin_addr;
   1721 			p = (u_char *) &su->su_sin.sin_port;
   1722 			alen = sizeof(su->su_sin.sin_addr);
   1723 			af = 4;
   1724 			break;
   1725 		case AF_INET6:
   1726 			a = (u_char *) &su->su_sin6.sin6_addr;
   1727 			p = (u_char *) &su->su_sin6.sin6_port;
   1728 			alen = sizeof(su->su_sin6.sin6_addr);
   1729 			af = 6;
   1730 			break;
   1731 		default:
   1732 			af = 0;
   1733 			break;
   1734 		}
   1735 		if (af) {
   1736 			lreply(-2, "    %s (%d,%d",
   1737 			    ispassive ? "LPSV" : "LPRT", af, alen);
   1738 			for (i = 0; i < alen; i++)
   1739 				lreply(-2, "%d,", UC(a[alen]));
   1740 			lreply(-1, "%d,%d,%d)", 2, UC(p[0]), UC(p[1]));
   1741 #undef UC
   1742 		}
   1743 	    }
   1744 
   1745 		/* EPRT/EPSV */
   1746  epsvonly:
   1747 		switch (su->su_family) {
   1748 		case AF_INET:
   1749 			af = 1;
   1750 			break;
   1751 		case AF_INET6:
   1752 			af = 2;
   1753 			break;
   1754 		default:
   1755 			af = 0;
   1756 			break;
   1757 		}
   1758 		if (af) {
   1759 			if (getnameinfo((struct sockaddr *)su, su->su_len,
   1760 				    ntop_buf, sizeof(ntop_buf), NULL, 0,
   1761 					NI_NUMERICHOST) == 0) {
   1762 				lreply(0, "%s (|%d|%s|%d|)",
   1763 				    ispassive ? "EPSV" : "EPRT",
   1764 				    af, ntop_buf, ntohs(su->su_port));
   1765 			}
   1766 		}
   1767 	} else
   1768 		lreply(0, "No data connection");
   1769 
   1770 	if (logged_in) {
   1771 		lreply(0, "Data sent:        %qd byte%s in %qd file%s",
   1772 		    (qdfmt_t)total_data_out, PLURAL(total_data_out),
   1773 		    (qdfmt_t)total_files_out, PLURAL(total_files_out));
   1774 		lreply(0, "Data received:    %qd byte%s in %qd file%s",
   1775 		    (qdfmt_t)total_data_in, PLURAL(total_data_in),
   1776 		    (qdfmt_t)total_files_in, PLURAL(total_files_in));
   1777 		lreply(0, "Total data:       %qd byte%s in %qd file%s",
   1778 		    (qdfmt_t)total_data, PLURAL(total_data),
   1779 		    (qdfmt_t)total_files, PLURAL(total_files));
   1780 	}
   1781 	otbi = total_bytes_in;
   1782 	otbo = total_bytes_out;
   1783 	otb = total_bytes;
   1784 	lreply(0, "Traffic sent:     %qd byte%s in %qd transfer%s",
   1785 	    (qdfmt_t)otbo, PLURAL(otbo),
   1786 	    (qdfmt_t)total_xfers_out, PLURAL(total_xfers_out));
   1787 	lreply(0, "Traffic received: %qd byte%s in %qd transfer%s",
   1788 	    (qdfmt_t)otbi, PLURAL(otbi),
   1789 	    (qdfmt_t)total_xfers_in, PLURAL(total_xfers_in));
   1790 	lreply(0, "Total traffic:    %qd byte%s in %qd transfer%s",
   1791 	    (qdfmt_t)otb, PLURAL(otb),
   1792 	    (qdfmt_t)total_xfers, PLURAL(total_xfers));
   1793 
   1794 	if (logged_in) {
   1795 		struct ftpconv *cp;
   1796 
   1797 		lreply(0, "");
   1798 		lreply(0, "Class: %s, type: %s",
   1799 		    curclass.classname, CURCLASSTYPE);
   1800 		lreply(0, "Check PORT/LPRT commands: %sabled",
   1801 		    curclass.checkportcmd ? "en" : "dis");
   1802 		if (curclass.display != NULL)
   1803 			lreply(0, "Display file: %s", curclass.display);
   1804 		if (curclass.notify != NULL)
   1805 			lreply(0, "Notify fileglob: %s", curclass.notify);
   1806 		lreply(0, "Idle timeout: %d, maximum timeout: %d",
   1807 		    curclass.timeout, curclass.maxtimeout);
   1808 		lreply(0, "Current connections: %d", connections);
   1809 		if (curclass.limit == -1)
   1810 			lreply(0, "Maximum connections: unlimited");
   1811 		else
   1812 			lreply(0, "Maximum connections: %d", curclass.limit);
   1813 		if (curclass.limitfile)
   1814 			lreply(0, "Connection limit exceeded file: %s",
   1815 			    curclass.limitfile);
   1816 		if (curclass.motd != NULL)
   1817 			lreply(0, "MotD file: %s", curclass.motd);
   1818 		lreply(0,
   1819 	    "Modify commands (CHMOD, DELE, MKD, RMD, RNFR, UMASK): %sabled",
   1820 		    curclass.modify ? "en" : "dis");
   1821 		lreply(0,
   1822 	    "Upload commands (APPE, STOR, STOU): %sabled",
   1823 		    curclass.upload ? "en" : "dis");
   1824 		if (curclass.portmin && curclass.portmax)
   1825 			lreply(0, "PASV port range: %d - %d",
   1826 			    curclass.portmin, curclass.portmax);
   1827 		if (curclass.rateget)
   1828 			lreply(0, "Rate get limit: %d bytes/sec",
   1829 			    curclass.rateget);
   1830 		else
   1831 			lreply(0, "Rate get limit: disabled");
   1832 		if (curclass.rateput)
   1833 			lreply(0, "Rate put limit: %d bytes/sec",
   1834 			    curclass.rateput);
   1835 		else
   1836 			lreply(0, "Rate put limit: disabled");
   1837 		lreply(0, "Umask: %.04o", curclass.umask);
   1838 		for (cp = curclass.conversions; cp != NULL; cp=cp->next) {
   1839 			if (cp->suffix == NULL || cp->types == NULL ||
   1840 			    cp->command == NULL)
   1841 				continue;
   1842 			lreply(0,
   1843 			    "Conversion: %s [%s] disable: %s, command: %s",
   1844 			    cp->suffix, cp->types, cp->disable, cp->command);
   1845 		}
   1846 	}
   1847 
   1848 	reply(211, "End of status");
   1849 }
   1850 
   1851 void
   1852 fatal(const char *s)
   1853 {
   1854 
   1855 	reply(451, "Error in server: %s\n", s);
   1856 	reply(221, "Closing connection due to server error.");
   1857 	dologout(0);
   1858 	/* NOTREACHED */
   1859 }
   1860 
   1861 /*
   1862  * reply() --
   1863  *	display the final line of a reply, with a trailing CRLF
   1864  *	i.e, n + " " + fmt + CRLF
   1865  */
   1866 void
   1867 reply(int n, const char *fmt, ...)
   1868 {
   1869 	off_t b;
   1870 	va_list ap;
   1871 
   1872 	va_start(ap, fmt);
   1873 	b = 0;
   1874 	b += printf("%d ", n);
   1875 	b += vprintf(fmt, ap);
   1876 	b += printf("\r\n");
   1877 	total_bytes += b;
   1878 	total_bytes_out += b;
   1879 	(void)fflush(stdout);
   1880 	if (debug) {
   1881 		syslog(LOG_DEBUG, "<--- %d ", n);
   1882 		vsyslog(LOG_DEBUG, fmt, ap);
   1883 	}
   1884 }
   1885 
   1886 /*
   1887  * lreply() --
   1888  *	depending on the value of n, display a line with a trailing CRLF:
   1889  *	n == -2		freeform text, but no trailing CRLF
   1890  *	n == -1		freeform text
   1891  *	n ==  0		prefix the message with 4 spaces
   1892  *	n  >  0		prefix the message with n + "-"
   1893  */
   1894 void
   1895 lreply(int n, const char *fmt, ...)
   1896 {
   1897 	off_t b;
   1898 	va_list ap;
   1899 
   1900 	va_start(ap, fmt);
   1901 	b = 0;
   1902 	switch (n) {
   1903 		case 0:
   1904 			b += printf("    ");
   1905 		case -1:
   1906 		case -2:
   1907 			break;
   1908 		default:
   1909 			b += printf("%d-", n);
   1910 			break;
   1911 	}
   1912 	b += vprintf(fmt, ap);
   1913 	if (n != -2)
   1914 		b += printf("\r\n");
   1915 	total_bytes += b;
   1916 	total_bytes_out += b;
   1917 	if (n != -2)
   1918 		(void)fflush(stdout);
   1919 	if (debug && n >= 0) {
   1920 		syslog(LOG_DEBUG, "<--- %d- ", n);
   1921 		vsyslog(LOG_DEBUG, fmt, ap);
   1922 	}
   1923 }
   1924 
   1925 static void
   1926 dolog(struct sockaddr *who)
   1927 {
   1928 	getnameinfo(who, who->sa_len, remotehost, sizeof(remotehost), NULL,0,0);
   1929 #ifdef HASSETPROCTITLE
   1930 	snprintf(proctitle, sizeof(proctitle), "%s: connected", remotehost);
   1931 	setproctitle(proctitle);
   1932 #endif /* HASSETPROCTITLE */
   1933 	if (logging)
   1934 		syslog(LOG_INFO, "connection from %s to %s",
   1935 		    remotehost, hostname);
   1936 }
   1937 
   1938 /*
   1939  * Record logout in wtmp file
   1940  * and exit with supplied status.
   1941  */
   1942 void
   1943 dologout(int status)
   1944 {
   1945 	/*
   1946 	* Prevent reception of SIGURG from resulting in a resumption
   1947 	* back to the main program loop.
   1948 	*/
   1949 	transflag = 0;
   1950 
   1951 	if (logged_in) {
   1952 		(void) seteuid((uid_t)0);
   1953 		logwtmp(ttyline, "", "");
   1954 		if (doutmp)
   1955 			logout(utmp.ut_line);
   1956 #ifdef KERBEROS
   1957 		if (!notickets && krbtkfile_env)
   1958 			unlink(krbtkfile_env);
   1959 #endif
   1960 	}
   1961 	/* beware of flushing buffers after a SIGPIPE */
   1962 	_exit(status);
   1963 }
   1964 
   1965 static void
   1966 myoob(int signo)
   1967 {
   1968 	char *cp;
   1969 
   1970 	/* only process if transfer occurring */
   1971 	if (!transflag)
   1972 		return;
   1973 	cp = tmpline;
   1974 	if (getline(cp, 7, stdin) == NULL) {
   1975 		reply(221, "You could at least say goodbye.");
   1976 		dologout(0);
   1977 	}
   1978 	if (strcasecmp(cp, "ABOR\r\n") == 0) {
   1979 		tmpline[0] = '\0';
   1980 		reply(426, "Transfer aborted. Data connection closed.");
   1981 		reply(226, "Abort successful");
   1982 		longjmp(urgcatch, 1);
   1983 	}
   1984 	if (strcasecmp(cp, "STAT\r\n") == 0) {
   1985 		tmpline[0] = '\0';
   1986 		if (file_size != (off_t) -1)
   1987 			reply(213, "Status: %qd of %qd byte%s transferred",
   1988 			    (qdfmt_t)byte_count, (qdfmt_t)file_size,
   1989 			    PLURAL(byte_count));
   1990 		else
   1991 			reply(213, "Status: %qd byte%s transferred",
   1992 			    (qdfmt_t)byte_count, PLURAL(byte_count));
   1993 	}
   1994 }
   1995 
   1996 static int
   1997 bind_pasv_addr(void)
   1998 {
   1999 	static int passiveport;
   2000 	int port, len;
   2001 
   2002 	len = pasv_addr.su_len;
   2003 	if (curclass.portmin == 0 && curclass.portmax == 0) {
   2004 		pasv_addr.su_port = 0;
   2005 		return (bind(pdata, (struct sockaddr *)&pasv_addr, len));
   2006 	}
   2007 
   2008 	if (passiveport == 0) {
   2009 		srand(getpid());
   2010 		passiveport = rand() % (curclass.portmax - curclass.portmin)
   2011 		    + curclass.portmin;
   2012 	}
   2013 
   2014 	port = passiveport;
   2015 	while (1) {
   2016 		port++;
   2017 		if (port > curclass.portmax)
   2018 			port = curclass.portmin;
   2019 		else if (port == passiveport) {
   2020 			errno = EAGAIN;
   2021 			return (-1);
   2022 		}
   2023 		pasv_addr.su_port = htons(port);
   2024 		if (bind(pdata, (struct sockaddr *)&pasv_addr, len) == 0)
   2025 			break;
   2026 		if (errno != EADDRINUSE)
   2027 			return (-1);
   2028 	}
   2029 	passiveport = port;
   2030 	return (0);
   2031 }
   2032 
   2033 /*
   2034  * Note: a response of 425 is not mentioned as a possible response to
   2035  *	the PASV command in RFC959. However, it has been blessed as
   2036  *	a legitimate response by Jon Postel in a telephone conversation
   2037  *	with Rick Adams on 25 Jan 89.
   2038  */
   2039 void
   2040 passive(void)
   2041 {
   2042 	int len;
   2043 	char *p, *a;
   2044 
   2045 	if (pdata >= 0)
   2046 		close(pdata);
   2047 	pdata = socket(AF_INET, SOCK_STREAM, 0);
   2048 	if (pdata < 0 || !logged_in) {
   2049 		perror_reply(425, "Can't open passive connection");
   2050 		return;
   2051 	}
   2052 	pasv_addr = ctrl_addr;
   2053 
   2054 	if (bind_pasv_addr() < 0)
   2055 		goto pasv_error;
   2056 	len = pasv_addr.su_len;
   2057 	if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
   2058 		goto pasv_error;
   2059 	if (listen(pdata, 1) < 0)
   2060 		goto pasv_error;
   2061 	a = (char *) &pasv_addr.su_sin.sin_addr;
   2062 	p = (char *) &pasv_addr.su_port;
   2063 
   2064 #define UC(b) (((int) b) & 0xff)
   2065 
   2066 	reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
   2067 		UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
   2068 	return;
   2069 
   2070  pasv_error:
   2071 	(void) close(pdata);
   2072 	pdata = -1;
   2073 	perror_reply(425, "Can't open passive connection");
   2074 	return;
   2075 }
   2076 
   2077 /*
   2078  * 228 Entering Long Passive Mode (af, hal, h1, h2, h3,..., pal, p1, p2...)
   2079  * 229 Entering Extended Passive Mode (|||port|)
   2080  */
   2081 void
   2082 long_passive(char *cmd, int pf)
   2083 {
   2084 	int len;
   2085 	char *p, *a;
   2086 
   2087 	if (!logged_in) {
   2088 		syslog(LOG_NOTICE, "long passive but not logged in");
   2089 		reply(503, "Login with USER first.");
   2090 		return;
   2091 	}
   2092 
   2093 	if (pf != PF_UNSPEC) {
   2094 		if (ctrl_addr.su_family != pf) {
   2095 			switch (ctrl_addr.su_family) {
   2096 			case AF_INET:
   2097 				pf = 1;
   2098 				break;
   2099 			case AF_INET6:
   2100 				pf = 2;
   2101 				break;
   2102 			default:
   2103 				pf = 0;
   2104 				break;
   2105 			}
   2106 			/*
   2107 			 * XXX
   2108 			 * only EPRT/EPSV ready clients will understand this
   2109 			 */
   2110 			if (strcmp(cmd, "EPSV") == 0 && pf) {
   2111 				reply(522, "Network protocol mismatch, "
   2112 					    "use (%d)", pf);
   2113 			} else
   2114 				reply(501, "Network protocol mismatch"); /*XXX*/
   2115 
   2116 			return;
   2117 		}
   2118 	}
   2119 
   2120 	if (pdata >= 0)
   2121 		close(pdata);
   2122 	pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
   2123 	if (pdata < 0) {
   2124 		perror_reply(425, "Can't open passive connection");
   2125 		return;
   2126 	}
   2127 	pasv_addr = ctrl_addr;
   2128 	if (bind_pasv_addr() < 0)
   2129 		goto pasv_error;
   2130 	len = pasv_addr.su_len;
   2131 	if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
   2132 		goto pasv_error;
   2133 	if (listen(pdata, 1) < 0)
   2134 		goto pasv_error;
   2135 	p = (char *) &pasv_addr.su_port;
   2136 
   2137 #define UC(b) (((int) b) & 0xff)
   2138 
   2139 	if (strcmp(cmd, "LPSV") == 0) {
   2140 		switch (pasv_addr.su_family) {
   2141 		case AF_INET:
   2142 			a = (char *) &pasv_addr.su_sin.sin_addr;
   2143 			reply(228, "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)",
   2144 				4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
   2145 				2, UC(p[0]), UC(p[1]));
   2146 			return;
   2147 		case AF_INET6:
   2148 			a = (char *) &pasv_addr.su_sin6.sin6_addr;
   2149 			reply(228, "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)",
   2150 				6, 16,
   2151 				UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
   2152 				UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]),
   2153 				UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]),
   2154 				UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]),
   2155 				2, UC(p[0]), UC(p[1]));
   2156 			return;
   2157 		}
   2158 #undef UC
   2159 	} else if (strcmp(cmd, "EPSV") == 0) {
   2160 		switch (pasv_addr.su_family) {
   2161 		case AF_INET:
   2162 		case AF_INET6:
   2163 			reply(229, "Entering Extended Passive Mode (|||%d|)",
   2164 			ntohs(pasv_addr.su_port));
   2165 			return;
   2166 		}
   2167 	} else {
   2168 		/* more proper error code? */
   2169 	}
   2170 
   2171  pasv_error:
   2172 	(void) close(pdata);
   2173 	pdata = -1;
   2174 	perror_reply(425, "Can't open passive connection");
   2175 	return;
   2176 }
   2177 
   2178 /*
   2179  * Generate unique name for file with basename "local".
   2180  * The file named "local" is already known to exist.
   2181  * Generates failure reply on error.
   2182  *
   2183  * XXX this function should under go changes similar to
   2184  * the mktemp(3)/mkstemp(3) changes.
   2185  */
   2186 static char *
   2187 gunique(const char *local)
   2188 {
   2189 	static char new[MAXPATHLEN];
   2190 	struct stat st;
   2191 	char *cp;
   2192 	int count;
   2193 
   2194 	cp = strrchr(local, '/');
   2195 	if (cp)
   2196 		*cp = '\0';
   2197 	if (stat(cp ? local : ".", &st) < 0) {
   2198 		perror_reply(553, cp ? local : ".");
   2199 		return (NULL);
   2200 	}
   2201 	if (cp)
   2202 		*cp = '/';
   2203 	for (count = 1; count < 100; count++) {
   2204 		(void)snprintf(new, sizeof(new) - 1, "%s.%d", local, count);
   2205 		if (stat(new, &st) < 0)
   2206 			return (new);
   2207 	}
   2208 	reply(452, "Unique file name cannot be created.");
   2209 	return (NULL);
   2210 }
   2211 
   2212 /*
   2213  * Format and send reply containing system error number.
   2214  */
   2215 void
   2216 perror_reply(int code, const char *string)
   2217 {
   2218 	int save_errno;
   2219 
   2220 	save_errno = errno;
   2221 	reply(code, "%s: %s.", string, strerror(errno));
   2222 	errno = save_errno;
   2223 }
   2224 
   2225 static char *onefile[] = {
   2226 	"",
   2227 	0
   2228 };
   2229 
   2230 void
   2231 send_file_list(const char *whichf)
   2232 {
   2233 	struct stat st;
   2234 	DIR *dirp = NULL;
   2235 	struct dirent *dir;
   2236 	FILE *dout = NULL;
   2237 	char **dirlist, *dirname, *p;
   2238 	int simple = 0;
   2239 	int freeglob = 0;
   2240 	glob_t gl;
   2241 	off_t b;
   2242 
   2243 #ifdef __GNUC__
   2244 	(void) &dout;
   2245 	(void) &dirlist;
   2246 	(void) &simple;
   2247 	(void) &freeglob;
   2248 #endif
   2249 
   2250 	p = NULL;
   2251 	if (strpbrk(whichf, "~{[*?") != NULL) {
   2252 		int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
   2253 
   2254 		memset(&gl, 0, sizeof(gl));
   2255 		freeglob = 1;
   2256 		if (glob(whichf, flags, 0, &gl)) {
   2257 			reply(550, "not found");
   2258 			goto out;
   2259 		} else if (gl.gl_pathc == 0) {
   2260 			errno = ENOENT;
   2261 			perror_reply(550, whichf);
   2262 			goto out;
   2263 		}
   2264 		dirlist = gl.gl_pathv;
   2265 	} else {
   2266 		p = xstrdup(whichf);
   2267 		onefile[0] = p;
   2268 		dirlist = onefile;
   2269 		simple = 1;
   2270 	}
   2271 					/* XXX: } for vi sm */
   2272 
   2273 	if (setjmp(urgcatch)) {
   2274 		transflag = 0;
   2275 		goto out;
   2276 	}
   2277 	while ((dirname = *dirlist++) != NULL) {
   2278 		int trailingslash = 0;
   2279 
   2280 		if (stat(dirname, &st) < 0) {
   2281 			/*
   2282 			 * If user typed "ls -l", etc, and the client
   2283 			 * used NLST, do what the user meant.
   2284 			 */
   2285 			/* XXX: nuke this support? */
   2286 			if (dirname[0] == '-' && *dirlist == NULL &&
   2287 			    transflag == 0) {
   2288 				char *argv[] = { INTERNAL_LS, "", NULL };
   2289 
   2290 				argv[1] = dirname;
   2291 				retrieve(argv, dirname);
   2292 				goto out;
   2293 			}
   2294 			perror_reply(550, whichf);
   2295 			if (dout != NULL) {
   2296 				(void) fclose(dout);
   2297 				transflag = 0;
   2298 				data = -1;
   2299 				if (pdata >= 0)
   2300 					(void)close(pdata);
   2301 				pdata = -1;
   2302 			}
   2303 			goto out;
   2304 		}
   2305 
   2306 		if (S_ISREG(st.st_mode)) {
   2307 			if (dout == NULL) {
   2308 				dout = dataconn("file list", (off_t)-1, "w");
   2309 				if (dout == NULL)
   2310 					goto out;
   2311 				transflag++;
   2312 			}
   2313 			b = fprintf(dout, "%s%s\n", dirname,
   2314 			    type == TYPE_A ? "\r" : "");
   2315 			total_bytes += b;
   2316 			total_bytes_out += b;
   2317 			byte_count += strlen(dirname) + 1;
   2318 			continue;
   2319 		} else if (!S_ISDIR(st.st_mode))
   2320 			continue;
   2321 
   2322 		if (dirname[strlen(dirname) - 1] == '/')
   2323 			trailingslash++;
   2324 
   2325 		if ((dirp = opendir(dirname)) == NULL)
   2326 			continue;
   2327 
   2328 		while ((dir = readdir(dirp)) != NULL) {
   2329 			char nbuf[MAXPATHLEN];
   2330 
   2331 			if (ISDOTDIR(dir->d_name) || ISDOTDOTDIR(dir->d_name))
   2332 				continue;
   2333 
   2334 			(void)snprintf(nbuf, sizeof(nbuf), "%s%s%s", dirname,
   2335 			    trailingslash ? "" : "/", dir->d_name);
   2336 
   2337 			/*
   2338 			 * We have to do a stat to ensure it's
   2339 			 * not a directory or special file.
   2340 			 */
   2341 			/* XXX: follow RFC959 and filter out non files ? */
   2342 			if (simple || (stat(nbuf, &st) == 0 &&
   2343 			    S_ISREG(st.st_mode))) {
   2344 				char *p;
   2345 
   2346 				if (dout == NULL) {
   2347 					dout = dataconn("file list", (off_t)-1,
   2348 						"w");
   2349 					if (dout == NULL)
   2350 						goto out;
   2351 					transflag++;
   2352 				}
   2353 				p = nbuf;
   2354 				if (nbuf[0] == '.' && nbuf[1] == '/')
   2355 					p = &nbuf[2];
   2356 				b = fprintf(dout, "%s%s\n", p,
   2357 				    type == TYPE_A ? "\r" : "");
   2358 				total_bytes += b;
   2359 				total_bytes_out += b;
   2360 				byte_count += strlen(nbuf) + 1;
   2361 			}
   2362 		}
   2363 		(void) closedir(dirp);
   2364 	}
   2365 
   2366 	if (dout == NULL)
   2367 		reply(550, "No files found.");
   2368 	else if (ferror(dout) != 0)
   2369 		perror_reply(550, "Data connection");
   2370 	else
   2371 		reply(226, "Transfer complete.");
   2372 
   2373 	transflag = 0;
   2374 	if (dout != NULL)
   2375 		(void) fclose(dout);
   2376 	else if (pdata >= 0)
   2377 		(void)close(pdata);
   2378 	data = -1;
   2379 	pdata = -1;
   2380  out:
   2381 	total_xfers++;
   2382 	total_xfers_out++;
   2383 	if (p)
   2384 		free(p);
   2385 	if (freeglob)
   2386 		globfree(&gl);
   2387 }
   2388 
   2389 char *
   2390 conffilename(const char *s)
   2391 {
   2392 	static char filename[MAXPATHLEN];
   2393 
   2394 	if (*s == '/')
   2395 		strlcpy(filename, s, sizeof(filename));
   2396 	else
   2397 		(void)snprintf(filename, sizeof(filename), "%s/%s", confdir ,s);
   2398 	return (filename);
   2399 }
   2400 
   2401 /*
   2402  * logcmd --
   2403  *	based on the arguments, syslog a message:
   2404  *	 if bytes != -1		"<command> <file1> = <bytes> bytes"
   2405  *	 else if file2 != NULL	"<command> <file1> <file2>"
   2406  *	 else			"<command> <file1>"
   2407  *	if elapsed != NULL, append "in xxx.yyy seconds"
   2408  *	if error != NULL, append ": " + error
   2409  */
   2410 void
   2411 logcmd(const char *command, off_t bytes, const char *file1, const char *file2,
   2412 	const struct timeval *elapsed, const char *error)
   2413 {
   2414 	char	buf[MAXPATHLEN * 2 + 100], realfile[MAXPATHLEN];
   2415 	const char *p;
   2416 	size_t	len;
   2417 
   2418 	if (logging <=1)
   2419 		return;
   2420 
   2421 	if ((p = realpath(file1, realfile)) == NULL) {
   2422 #if 0	/* XXX: too noisy */
   2423 		syslog(LOG_WARNING, "realpath `%s' failed: %s",
   2424 		    realfile, strerror(errno));
   2425 #endif
   2426 		p = file1;
   2427 	}
   2428 	len = snprintf(buf, sizeof(buf), "%s %s", command, p);
   2429 
   2430 	if (bytes != (off_t)-1) {
   2431 		len += snprintf(buf + len, sizeof(buf) - len,
   2432 		    " = %qd byte%s", (qdfmt_t) bytes, PLURAL(bytes));
   2433 	} else if (file2 != NULL) {
   2434 		if ((p = realpath(file2, realfile)) == NULL) {
   2435 #if 0	/* XXX: too noisy */
   2436 			syslog(LOG_WARNING, "realpath `%s' failed: %s",
   2437 			    realfile, strerror(errno));
   2438 #endif
   2439 			p = file2;
   2440 		}
   2441 		len += snprintf(buf + len, sizeof(buf) - len, " %s", p);
   2442 	}
   2443 
   2444 	if (elapsed != NULL) {
   2445 		len += snprintf(buf + len, sizeof(buf) - len,
   2446 		    " in %ld.%.03d seconds", elapsed->tv_sec,
   2447 		    (int)(elapsed->tv_usec / 1000));
   2448 	}
   2449 
   2450 	if (error != NULL)
   2451 		len += snprintf(buf + len, sizeof(buf) - len, ": %s", error);
   2452 
   2453 	syslog(LOG_INFO, "%s", buf);
   2454 }
   2455 
   2456 char *
   2457 xstrdup(const char *s)
   2458 {
   2459 	char *new = strdup(s);
   2460 
   2461 	if (new == NULL)
   2462 		fatal("Local resource failure: malloc");
   2463 		/* NOTREACHED */
   2464 	return (new);
   2465 }
   2466