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