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