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