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