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