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