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