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