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