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