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