Home | History | Annotate | Line # | Download | only in ftpd
ftpd.c revision 1.149
      1 /*	$NetBSD: ftpd.c,v 1.149 2003/01/22 04:33:35 lukem Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1997-2001 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.149 2003/01/22 04:33:35 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 #include <sys/mman.h>
    125 #include <sys/resource.h>
    126 
    127 #include <netinet/in.h>
    128 #include <netinet/in_systm.h>
    129 #include <netinet/ip.h>
    130 
    131 #define	FTP_NAMES
    132 #include <arpa/ftp.h>
    133 #include <arpa/inet.h>
    134 #include <arpa/telnet.h>
    135 
    136 #include <ctype.h>
    137 #include <dirent.h>
    138 #include <err.h>
    139 #include <errno.h>
    140 #include <fcntl.h>
    141 #include <fnmatch.h>
    142 #include <glob.h>
    143 #include <grp.h>
    144 #include <limits.h>
    145 #include <netdb.h>
    146 #include <pwd.h>
    147 #include <setjmp.h>
    148 #include <signal.h>
    149 #include <stdarg.h>
    150 #include <stdio.h>
    151 #include <stdlib.h>
    152 #include <string.h>
    153 #include <syslog.h>
    154 #include <time.h>
    155 #include <tzfile.h>
    156 #include <unistd.h>
    157 #include <util.h>
    158 #ifdef SUPPORT_UTMP
    159 #include <utmp.h>
    160 #endif
    161 #ifdef SUPPORT_UTMPX
    162 #include <utmpx.h>
    163 #endif
    164 #ifdef SKEY
    165 #include <skey.h>
    166 #endif
    167 #ifdef KERBEROS5
    168 #include <com_err.h>
    169 #include <krb5/krb5.h>
    170 #endif
    171 
    172 #define	GLOBAL
    173 #include "extern.h"
    174 #include "pathnames.h"
    175 #include "version.h"
    176 
    177 int	data;
    178 jmp_buf	urgcatch;
    179 int	sflag;
    180 int	stru;			/* avoid C keyword */
    181 int	mode;
    182 int	dataport;		/* use specific data port */
    183 int	dopidfile;		/* maintain pid file */
    184 int	doutmp;			/* update utmp file */
    185 int	dowtmp;			/* update wtmp file */
    186 int	doxferlog;		/* syslog wu-ftpd style xferlog entries */
    187 int	dropprivs;		/* if privileges should or have been dropped */
    188 int	mapped;			/* IPv4 connection on AF_INET6 socket */
    189 off_t	file_size;
    190 off_t	byte_count;
    191 static char ttyline[20];
    192 #ifdef SUPPORT_UTMP
    193 static struct utmp utmp;	/* for utmp */
    194 #endif
    195 #ifdef SUPPORT_UTMPX
    196 static struct utmpx utmpx;	/* for utmpx */
    197 #endif
    198 
    199 static const char *anondir = NULL;
    200 static const char *confdir = _DEFAULT_CONFDIR;
    201 
    202 #if defined(KERBEROS) || defined(KERBEROS5)
    203 int	has_ccache = 0;
    204 int	notickets = 1;
    205 char	*krbtkfile_env = NULL;
    206 char	*tty = ttyline;
    207 int	login_krb5_forwardable_tgt = 0;
    208 #endif
    209 
    210 int epsvall = 0;
    211 
    212 /*
    213  * Timeout intervals for retrying connections
    214  * to hosts that don't accept PORT cmds.  This
    215  * is a kludge, but given the problems with TCP...
    216  */
    217 #define	SWAITMAX	90	/* wait at most 90 seconds */
    218 #define	SWAITINT	5	/* interval between retries */
    219 
    220 int	swaitmax = SWAITMAX;
    221 int	swaitint = SWAITINT;
    222 
    223 enum send_status {
    224 	SS_SUCCESS,
    225 	SS_NO_TRANSFER,			/* no transfer made yet */
    226 	SS_FILE_ERROR,			/* file read error */
    227 	SS_DATA_ERROR			/* data send error */
    228 };
    229 
    230 static int	 bind_pasv_addr(void);
    231 static int	 checkuser(const char *, const char *, int, int, char **);
    232 static int	 checkaccess(const char *);
    233 static int	 checkpassword(const struct passwd *, const char *);
    234 static void	 end_login(void);
    235 static FILE	*getdatasock(const char *);
    236 static char	*gunique(const char *);
    237 static void	 login_utmp(const char *, const char *, const char *);
    238 static void	 logremotehost(struct sockinet *);
    239 static void	 lostconn(int);
    240 static void	 myoob(int);
    241 static int	 receive_data(FILE *, FILE *);
    242 static int	 send_data(FILE *, FILE *, const struct stat *, int);
    243 static struct passwd *sgetpwnam(const char *);
    244 static int	 write_data(int, char *, size_t, off_t *, struct timeval *,
    245 		     int);
    246 static enum send_status
    247 		 send_data_with_read(int, int, const struct stat *, int);
    248 static enum send_status
    249 		 send_data_with_mmap(int, int, const struct stat *, int);
    250 static void	 logrusage(const struct rusage *, const struct rusage *);
    251 static void	 logout_utmp(void);
    252 
    253 int	main(int, char *[]);
    254 
    255 #if defined(KERBEROS)
    256 int	klogin(struct passwd *, char *, char *, char *);
    257 void	kdestroy(void);
    258 #endif
    259 #if defined(KERBEROS5)
    260 int	k5login(struct passwd *, char *, char *, char *);
    261 void	k5destroy(void);
    262 #endif
    263 
    264 int
    265 main(int argc, char *argv[])
    266 {
    267 	int		addrlen, ch, on = 1, tos, keepalive;
    268 #ifdef KERBEROS5
    269 	krb5_error_code	kerror;
    270 #endif
    271 	char		*p;
    272 	long		l;
    273 
    274 	connections = 1;
    275 	debug = 0;
    276 	logging = 0;
    277 	pdata = -1;
    278 	sflag = 0;
    279 	dataport = 0;
    280 	dopidfile = 1;		/* default: DO use a pid file to count users */
    281 	doutmp = 0;		/* default: Do NOT log to utmp */
    282 	dowtmp = 1;		/* default: DO log to wtmp */
    283 	doxferlog = 0;		/* default: Do NOT syslog xferlog */
    284 	dropprivs = 0;
    285 	mapped = 0;
    286 	usedefault = 1;
    287 	emailaddr = NULL;
    288 	hostname[0] = '\0';
    289 	homedir[0] = '\0';
    290 	gidcount = 0;
    291 	is_oob = 0;
    292 	version = FTPD_VERSION;
    293 
    294 	/*
    295 	 * LOG_NDELAY sets up the logging connection immediately,
    296 	 * necessary for anonymous ftp's that chroot and can't do it later.
    297 	 */
    298 	openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
    299 
    300 	while ((ch = getopt(argc, argv, "a:c:C:de:h:HlP:qQrst:T:uUvV:wWX"))
    301 	    != -1) {
    302 		switch (ch) {
    303 		case 'a':
    304 			anondir = optarg;
    305 			break;
    306 
    307 		case 'c':
    308 			confdir = optarg;
    309 			break;
    310 
    311 		case 'C':
    312 			pw = sgetpwnam(optarg);
    313 			exit(checkaccess(optarg) ? 0 : 1);
    314 			/* NOTREACHED */
    315 
    316 		case 'd':
    317 		case 'v':		/* deprecated */
    318 			debug = 1;
    319 			break;
    320 
    321 		case 'e':
    322 			emailaddr = optarg;
    323 			break;
    324 
    325 		case 'h':
    326 			strlcpy(hostname, optarg, sizeof(hostname));
    327 			break;
    328 
    329 		case 'H':
    330 			if (gethostname(hostname, sizeof(hostname)) == -1)
    331 				hostname[0] = '\0';
    332 			hostname[sizeof(hostname) - 1] = '\0';
    333 			break;
    334 
    335 		case 'l':
    336 			logging++;	/* > 1 == extra logging */
    337 			break;
    338 
    339 		case 'P':
    340 			errno = 0;
    341 			p = NULL;
    342 			l = strtol(optarg, &p, 10);
    343 			if (errno || *optarg == '\0' || *p != '\0' ||
    344 			    l < IPPORT_RESERVED ||
    345 			    l > IPPORT_ANONMAX) {
    346 				syslog(LOG_WARNING, "Invalid dataport %s",
    347 				    optarg);
    348 				dataport = 0;
    349 			}
    350 			dataport = (int)l;
    351 			break;
    352 
    353 		case 'q':
    354 			dopidfile = 1;
    355 			break;
    356 
    357 		case 'Q':
    358 			dopidfile = 0;
    359 			break;
    360 
    361 		case 'r':
    362 			dropprivs = 1;
    363 			break;
    364 
    365 		case 's':
    366 			sflag = 1;
    367 			break;
    368 
    369 		case 't':
    370 		case 'T':
    371 			syslog(LOG_WARNING,
    372 			    "-%c has been deprecated in favour of ftpd.conf",
    373 			    ch);
    374 			break;
    375 
    376 		case 'u':
    377 			doutmp = 1;
    378 			break;
    379 
    380 		case 'U':
    381 			doutmp = 0;
    382 			break;
    383 
    384 		case 'V':
    385 			if (EMPTYSTR(optarg) || strcmp(optarg, "-") == 0)
    386 				version = NULL;
    387 			else
    388 				version = xstrdup(optarg);
    389 			break;
    390 
    391 		case 'w':
    392 			dowtmp = 1;
    393 			break;
    394 
    395 		case 'W':
    396 			dowtmp = 0;
    397 			break;
    398 
    399 		case 'X':
    400 			doxferlog = 1;
    401 			break;
    402 
    403 		default:
    404 			if (optopt == 'a' || optopt == 'C')
    405 				exit(1);
    406 			syslog(LOG_WARNING, "unknown flag -%c ignored", optopt);
    407 			break;
    408 		}
    409 	}
    410 	if (EMPTYSTR(confdir))
    411 		confdir = _DEFAULT_CONFDIR;
    412 
    413 	memset((char *)&his_addr, 0, sizeof(his_addr));
    414 	addrlen = sizeof(his_addr.si_su);
    415 	if (getpeername(0, (struct sockaddr *)&his_addr.si_su, &addrlen) < 0) {
    416 		syslog(LOG_ERR, "getpeername (%s): %m",argv[0]);
    417 		exit(1);
    418 	}
    419 	his_addr.su_len = addrlen;
    420 	memset((char *)&ctrl_addr, 0, sizeof(ctrl_addr));
    421 	addrlen = sizeof(ctrl_addr.si_su);
    422 	if (getsockname(0, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) {
    423 		syslog(LOG_ERR, "getsockname (%s): %m",argv[0]);
    424 		exit(1);
    425 	}
    426 	ctrl_addr.su_len = addrlen;
    427 #ifdef INET6
    428 	if (his_addr.su_family == AF_INET6
    429 	 && IN6_IS_ADDR_V4MAPPED(&his_addr.su_6addr)) {
    430 #if 1
    431 		/*
    432 		 * IPv4 control connection arrived to AF_INET6 socket.
    433 		 * I hate to do this, but this is the easiest solution.
    434 		 *
    435 		 * The assumption is untrue on SIIT environment.
    436 		 */
    437 		struct sockinet tmp_addr;
    438 		const int off = sizeof(struct in6_addr) - sizeof(struct in_addr);
    439 
    440 		tmp_addr = his_addr;
    441 		memset(&his_addr, 0, sizeof(his_addr));
    442 		his_addr.su_family = AF_INET;
    443 		his_addr.su_len = sizeof(his_addr.si_su.su_sin);
    444 		memcpy(&his_addr.su_addr, &tmp_addr.su_6addr.s6_addr[off],
    445 		    sizeof(his_addr.su_addr));
    446 		his_addr.su_port = tmp_addr.su_port;
    447 
    448 		tmp_addr = ctrl_addr;
    449 		memset(&ctrl_addr, 0, sizeof(ctrl_addr));
    450 		ctrl_addr.su_family = AF_INET;
    451 		ctrl_addr.su_len = sizeof(ctrl_addr.si_su.su_sin);
    452 		memcpy(&ctrl_addr.su_addr, &tmp_addr.su_6addr.s6_addr[off],
    453 		    sizeof(ctrl_addr.su_addr));
    454 		ctrl_addr.su_port = tmp_addr.su_port;
    455 #else
    456 		while (fgets(line, sizeof(line), fd) != NULL) {
    457 			if ((cp = strchr(line, '\n')) != NULL)
    458 				*cp = '\0';
    459 			reply(-530, "%s", line);
    460 		}
    461 		(void) fflush(stdout);
    462 		(void) fclose(fd);
    463 		reply(530,
    464 		    "Connection from IPv4 mapped address is not supported.");
    465 		exit(0);
    466 #endif
    467 
    468 		mapped = 1;
    469 	} else
    470 #endif /* INET6 */
    471 		mapped = 0;
    472 #ifdef IP_TOS
    473 	if (!mapped && his_addr.su_family == AF_INET) {
    474 		tos = IPTOS_LOWDELAY;
    475 		if (setsockopt(0, IPPROTO_IP, IP_TOS, (char *)&tos,
    476 			       sizeof(int)) < 0)
    477 			syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
    478 	}
    479 #endif
    480 	/* if the hostname hasn't been given, attempt to determine it */
    481 	if (hostname[0] == '\0') {
    482 		if (getnameinfo((struct sockaddr *)&ctrl_addr.si_su,
    483 		    ctrl_addr.su_len, hostname, sizeof(hostname), NULL, 0, 0)
    484 		    != 0)
    485 			(void)gethostname(hostname, sizeof(hostname));
    486 		hostname[sizeof(hostname) - 1] = '\0';
    487 	}
    488 
    489 	/* set this here so klogin can use it... */
    490 	(void)snprintf(ttyline, sizeof(ttyline), "ftp%d", getpid());
    491 
    492 	(void) freopen(_PATH_DEVNULL, "w", stderr);
    493 	(void) signal(SIGPIPE, lostconn);
    494 	(void) signal(SIGCHLD, SIG_IGN);
    495 	if (signal(SIGURG, myoob) == SIG_ERR)
    496 		syslog(LOG_WARNING, "signal: %m");
    497 
    498 	/* Try to handle urgent data inline */
    499 #ifdef SO_OOBINLINE
    500 	if (setsockopt(0, SOL_SOCKET, SO_OOBINLINE, (char *)&on, sizeof(on)) < 0)
    501 		syslog(LOG_WARNING, "setsockopt: %m");
    502 #endif
    503 	/* Set keepalives on the socket to detect dropped connections.  */
    504 #ifdef SO_KEEPALIVE
    505 	keepalive = 1;
    506 	if (setsockopt(0, SOL_SOCKET, SO_KEEPALIVE, (char *)&keepalive,
    507 	    sizeof(int)) < 0)
    508 		syslog(LOG_WARNING, "setsockopt (SO_KEEPALIVE): %m");
    509 #endif
    510 
    511 #ifdef	F_SETOWN
    512 	if (fcntl(fileno(stdin), F_SETOWN, getpid()) == -1)
    513 		syslog(LOG_WARNING, "fcntl F_SETOWN: %m");
    514 #endif
    515 	logremotehost(&his_addr);
    516 	/*
    517 	 * Set up default state
    518 	 */
    519 	data = -1;
    520 	type = TYPE_A;
    521 	form = FORM_N;
    522 	stru = STRU_F;
    523 	mode = MODE_S;
    524 	tmpline[0] = '\0';
    525 	hasyyerrored = 0;
    526 
    527 #ifdef KERBEROS5
    528 	kerror = krb5_init_context(&kcontext);
    529 	if (kerror) {
    530 		syslog(LOG_ERR, "%s when initializing Kerberos context",
    531 		    error_message(kerror));
    532 		exit(0);
    533 	}
    534 #endif /* KERBEROS5 */
    535 
    536 	init_curclass();
    537 	curclass.timeout = 300;		/* 5 minutes, as per login(1) */
    538 	curclass.type = CLASS_REAL;
    539 
    540 	/* If logins are disabled, print out the message. */
    541 	if (display_file(_PATH_NOLOGIN, 530)) {
    542 		reply(530, "System not available.");
    543 		exit(0);
    544 	}
    545 	(void)display_file(conffilename(_PATH_FTPWELCOME), 220);
    546 		/* reply(220,) must follow */
    547 	if (EMPTYSTR(version))
    548 		reply(220, "%s FTP server ready.", hostname);
    549 	else
    550 		reply(220, "%s FTP server (%s) ready.", hostname, version);
    551 
    552 	(void) setjmp(errcatch);
    553 	ftp_loop();
    554 	/* NOTREACHED */
    555 }
    556 
    557 static void
    558 lostconn(int signo)
    559 {
    560 
    561 	if (debug)
    562 		syslog(LOG_DEBUG, "lost connection");
    563 	dologout(1);
    564 }
    565 
    566 /*
    567  * Save the result of a getpwnam.  Used for USER command, since
    568  * the data returned must not be clobbered by any other command
    569  * (e.g., globbing).
    570  */
    571 static struct passwd *
    572 sgetpwnam(const char *name)
    573 {
    574 	static struct passwd save;
    575 	struct passwd *p;
    576 
    577 	if ((p = getpwnam(name)) == NULL)
    578 		return (p);
    579 	if (save.pw_name) {
    580 		free((char *)save.pw_name);
    581 		memset(save.pw_passwd, 0, strlen(save.pw_passwd));
    582 		free((char *)save.pw_passwd);
    583 		free((char *)save.pw_gecos);
    584 		free((char *)save.pw_dir);
    585 		free((char *)save.pw_shell);
    586 	}
    587 	save = *p;
    588 	save.pw_name = xstrdup(p->pw_name);
    589 	save.pw_passwd = xstrdup(p->pw_passwd);
    590 	save.pw_gecos = xstrdup(p->pw_gecos);
    591 	save.pw_dir = xstrdup(p->pw_dir);
    592 	save.pw_shell = xstrdup(p->pw_shell);
    593 	return (&save);
    594 }
    595 
    596 static int	login_attempts;	/* number of failed login attempts */
    597 static int	askpasswd;	/* had USER command, ask for PASSwd */
    598 static int	permitted;	/* USER permitted */
    599 static char	curname[LOGIN_NAME_MAX];	/* current USER name */
    600 
    601 /*
    602  * USER command.
    603  * Sets global passwd pointer pw if named account exists and is acceptable;
    604  * sets askpasswd if a PASS command is expected.  If logged in previously,
    605  * need to reset state.  If name is "ftp" or "anonymous", the name is not in
    606  * _PATH_FTPUSERS, and ftp account exists, set guest and pw, then just return.
    607  * If account doesn't exist, ask for passwd anyway.  Otherwise, check user
    608  * requesting login privileges.  Disallow anyone who does not have a standard
    609  * shell as returned by getusershell().  Disallow anyone mentioned in the file
    610  * _PATH_FTPUSERS to allow people such as root and uucp to be avoided.
    611  */
    612 void
    613 user(const char *name)
    614 {
    615 	char	*class;
    616 
    617 	class = NULL;
    618 	if (logged_in) {
    619 		switch (curclass.type) {
    620 		case CLASS_GUEST:
    621 			reply(530, "Can't change user from guest login.");
    622 			return;
    623 		case CLASS_CHROOT:
    624 			reply(530, "Can't change user from chroot user.");
    625 			return;
    626 		case CLASS_REAL:
    627 			if (dropprivs) {
    628 				reply(530, "Can't change user.");
    629 				return;
    630 			}
    631 			end_login();
    632 			break;
    633 		default:
    634 			abort();
    635 		}
    636 	}
    637 
    638 #if defined(KERBEROS)
    639 	kdestroy();
    640 #endif
    641 #if defined(KERBEROS5)
    642 	k5destroy();
    643 #endif
    644 
    645 	curclass.type = CLASS_REAL;
    646 	askpasswd = 0;
    647 	permitted = 0;
    648 
    649 	if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) {
    650 			/* need `pw' setup for checkaccess() and checkuser () */
    651 		if ((pw = sgetpwnam("ftp")) == NULL)
    652 			reply(530, "User %s unknown.", name);
    653 		else if (! checkaccess("ftp") || ! checkaccess("anonymous"))
    654 			reply(530, "User %s access denied.", name);
    655 		else {
    656 			curclass.type = CLASS_GUEST;
    657 			askpasswd = 1;
    658 			reply(331,
    659 			    "Guest login ok, type your name as password.");
    660 		}
    661 		if (!askpasswd) {
    662 			if (logging)
    663 				syslog(LOG_NOTICE,
    664 				    "ANONYMOUS FTP LOGIN REFUSED FROM %s",
    665 				    remotehost);
    666 			end_login();
    667 			goto cleanup_user;
    668 		}
    669 		name = "ftp";
    670 	} else
    671 		pw = sgetpwnam(name);
    672 
    673 	strlcpy(curname, name, sizeof(curname));
    674 
    675 			/* check user in /etc/ftpusers, and setup class */
    676 	permitted = checkuser(_PATH_FTPUSERS, curname, 1, 0, &class);
    677 
    678 			/* check user in /etc/ftpchroot */
    679 	if (checkuser(_PATH_FTPCHROOT, curname, 0, 0, NULL)) {
    680 		if (curclass.type == CLASS_GUEST) {
    681 			syslog(LOG_NOTICE,
    682 	    "Can't change guest user to chroot class; remove entry in %s",
    683 			    _PATH_FTPCHROOT);
    684 			exit(1);
    685 		}
    686 		curclass.type = CLASS_CHROOT;
    687 	}
    688 			/* determine default class */
    689 	if (class == NULL) {
    690 		switch (curclass.type) {
    691 		case CLASS_GUEST:
    692 			class = xstrdup("guest");
    693 			break;
    694 		case CLASS_CHROOT:
    695 			class = xstrdup("chroot");
    696 			break;
    697 		case CLASS_REAL:
    698 			class = xstrdup("real");
    699 			break;
    700 		default:
    701 			syslog(LOG_ERR, "unknown curclass.type %d; aborting",
    702 			    curclass.type);
    703 			abort();
    704 		}
    705 	}
    706 			/* parse ftpd.conf, setting up various parameters */
    707 	parse_conf(class);
    708 			/* if not guest user, check for valid shell */
    709 	if (pw == NULL)
    710 		permitted = 0;
    711 	else {
    712 		const char	*cp, *shell;
    713 
    714 		if ((shell = pw->pw_shell) == NULL || *shell == 0)
    715 			shell = _PATH_BSHELL;
    716 		while ((cp = getusershell()) != NULL)
    717 			if (strcmp(cp, shell) == 0)
    718 				break;
    719 		endusershell();
    720 		if (cp == NULL && curclass.type != CLASS_GUEST)
    721 			permitted = 0;
    722 	}
    723 
    724 			/* deny quickly (after USER not PASS) if requested */
    725 	if (CURCLASS_FLAGS_ISSET(denyquick) && !permitted) {
    726 		reply(530, "User %s may not use FTP.", curname);
    727 		if (logging)
    728 			syslog(LOG_NOTICE, "FTP LOGIN REFUSED FROM %s, %s",
    729 			    remotehost, curname);
    730 		end_login();
    731 		goto cleanup_user;
    732 	}
    733 
    734 			/* if haven't asked yet (i.e, not anon), ask now */
    735 	if (!askpasswd) {
    736 		askpasswd = 1;
    737 #ifdef SKEY
    738 		if (skey_haskey(curname) == 0) {
    739 			const char *myskey;
    740 
    741 			myskey = skey_keyinfo(curname);
    742 			reply(331, "Password [ %s ] required for %s.",
    743 			    myskey ? myskey : "error getting challenge",
    744 			    curname);
    745 		} else
    746 #endif
    747 			reply(331, "Password required for %s.", curname);
    748 	}
    749 
    750  cleanup_user:
    751 	/*
    752 	 * Delay before reading passwd after first failed
    753 	 * attempt to slow down passwd-guessing programs.
    754 	 */
    755 	if (login_attempts)
    756 		sleep((unsigned) login_attempts);
    757 
    758 	if (class)
    759 		free(class);
    760 }
    761 
    762 /*
    763  * Determine whether something is to happen (allow access, chroot)
    764  * for a user. Each line is a shell-style glob followed by
    765  * `yes' or `no'.
    766  *
    767  * For backward compatibility, `allow' and `deny' are synonymns
    768  * for `yes' and `no', respectively.
    769  *
    770  * Each glob is matched against the username in turn, and the first
    771  * match found is used. If no match is found, the result is the
    772  * argument `def'. If a match is found but without and explicit
    773  * `yes'/`no', the result is the opposite of def.
    774  *
    775  * If the file doesn't exist at all, the result is the argument
    776  * `nofile'
    777  *
    778  * Any line starting with `#' is considered a comment and ignored.
    779  *
    780  * Returns 0 if the user is denied, or 1 if they are allowed.
    781  *
    782  * NOTE: needs struct passwd *pw setup before use.
    783  */
    784 static int
    785 checkuser(const char *fname, const char *name, int def, int nofile,
    786 	    char **retclass)
    787 {
    788 	FILE	*fd;
    789 	int	 retval;
    790 	char	*word, *perm, *class, *buf, *p;
    791 	size_t	 len, line;
    792 
    793 	retval = def;
    794 	if (retclass != NULL)
    795 		*retclass = NULL;
    796 	if ((fd = fopen(conffilename(fname), "r")) == NULL)
    797 		return nofile;
    798 
    799 	line = 0;
    800 	for (;
    801 	    (buf = fparseln(fd, &len, &line, NULL, FPARSELN_UNESCCOMM |
    802 			    FPARSELN_UNESCCONT | FPARSELN_UNESCESC)) != NULL;
    803 	    free(buf), buf = NULL) {
    804 		word = perm = class = NULL;
    805 		p = buf;
    806 		if (len < 1)
    807 			continue;
    808 		if (p[len - 1] == '\n')
    809 			p[--len] = '\0';
    810 		if (EMPTYSTR(p))
    811 			continue;
    812 
    813 		NEXTWORD(p, word);
    814 		NEXTWORD(p, perm);
    815 		NEXTWORD(p, class);
    816 		if (EMPTYSTR(word))
    817 			continue;
    818 		if (!EMPTYSTR(class)) {
    819 			if (strcasecmp(class, "all") == 0 ||
    820 			    strcasecmp(class, "none") == 0) {
    821 				syslog(LOG_WARNING,
    822 		"%s line %d: illegal user-defined class `%s' - skipping entry",
    823 					    fname, (int)line, class);
    824 				continue;
    825 			}
    826 		}
    827 
    828 					/* have a host specifier */
    829 		if ((p = strchr(word, '@')) != NULL) {
    830 			unsigned long	net, mask, addr;
    831 			int		bits;
    832 
    833 			*p++ = '\0';
    834 					/* check against network or CIDR */
    835 			if (isdigit(*p) &&
    836 			    (bits = inet_net_pton(AF_INET, p,
    837 			    &net, sizeof(net))) != -1) {
    838 				net = ntohl(net);
    839 				mask = 0xffffffffU << (32 - bits);
    840 				addr = ntohl(his_addr.su_addr.s_addr);
    841 				if ((addr & mask) != net)
    842 					continue;
    843 
    844 					/* check against hostname glob */
    845 			} else if (fnmatch(p, remotehost, FNM_CASEFOLD) != 0)
    846 				continue;
    847 		}
    848 
    849 					/* have a group specifier */
    850 		if ((p = strchr(word, ':')) != NULL) {
    851 			gid_t	*groups, *ng;
    852 			int	 gsize, i, found;
    853 
    854 			if (pw == NULL)
    855 				continue;	/* no match for unknown user */
    856 			*p++ = '\0';
    857 			groups = NULL;
    858 			gsize = 16;
    859 			do {
    860 				ng = realloc(groups, gsize * sizeof(gid_t));
    861 				if (ng == NULL)
    862 					fatal(
    863 					    "Local resource failure: realloc");
    864 				groups = ng;
    865 			} while (getgrouplist(pw->pw_name, pw->pw_gid,
    866 						groups, &gsize) == -1);
    867 			found = 0;
    868 			for (i = 0; i < gsize; i++) {
    869 				struct group *g;
    870 
    871 				if ((g = getgrgid(groups[i])) == NULL)
    872 					continue;
    873 				if (fnmatch(p, g->gr_name, 0) == 0) {
    874 					found = 1;
    875 					break;
    876 				}
    877 			}
    878 			free(groups);
    879 			if (!found)
    880 				continue;
    881 		}
    882 
    883 					/* check against username glob */
    884 		if (fnmatch(word, name, 0) != 0)
    885 			continue;
    886 
    887 		if (perm != NULL &&
    888 		    ((strcasecmp(perm, "allow") == 0) ||
    889 		     (strcasecmp(perm, "yes") == 0)))
    890 			retval = 1;
    891 		else if (perm != NULL &&
    892 		    ((strcasecmp(perm, "deny") == 0) ||
    893 		     (strcasecmp(perm, "no") == 0)))
    894 			retval = 0;
    895 		else
    896 			retval = !def;
    897 		if (!EMPTYSTR(class) && retclass != NULL)
    898 			*retclass = xstrdup(class);
    899 		free(buf);
    900 		break;
    901 	}
    902 	(void) fclose(fd);
    903 	return (retval);
    904 }
    905 
    906 /*
    907  * Check if user is allowed by /etc/ftpusers
    908  * returns 1 for yes, 0 for no
    909  *
    910  * NOTE: needs struct passwd *pw setup (for checkuser())
    911  */
    912 static int
    913 checkaccess(const char *name)
    914 {
    915 
    916 	return (checkuser(_PATH_FTPUSERS, name, 1, 0, NULL));
    917 }
    918 
    919 static void
    920 login_utmp(const char *line, const char *name, const char *host)
    921 {
    922 #if defined(SUPPORT_UTMPX) || defined(SUPPORT_UTMP)
    923 	struct timeval tv;
    924 	(void)gettimeofday(&tv, NULL);
    925 #endif
    926 #ifdef SUPPORT_UTMPX
    927 	if (doutmp) {
    928 		(void)memset(&utmpx, 0, sizeof(utmpx));
    929 		utmpx.ut_tv = tv;
    930 		utmpx.ut_pid = getpid();
    931 		utmpx.ut_id[0] = 'f';
    932 		utmpx.ut_id[1] = 't';
    933 		utmpx.ut_id[2] = 'p';
    934 		utmpx.ut_id[3] = '*';
    935 		utmpx.ut_type = USER_PROCESS;
    936 		(void)strncpy(utmpx.ut_name, name, sizeof(utmpx.ut_name));
    937 		(void)strncpy(utmpx.ut_line, line, sizeof(utmpx.ut_line));
    938 		(void)strncpy(utmpx.ut_host, host, sizeof(utmpx.ut_host));
    939 		loginx(&utmpx);
    940 	}
    941 	if (dowtmp)
    942 		logwtmpx(line, name, host, 0, USER_PROCESS);
    943 #endif
    944 #ifdef SUPPORT_UTMP
    945 	if (doutmp) {
    946 		(void)memset(&utmp, 0, sizeof(utmp));
    947 		(void)time(&utmp.ut_time);
    948 		(void)strncpy(utmp.ut_name, name, sizeof(utmp.ut_name));
    949 		(void)strncpy(utmp.ut_line, line, sizeof(utmp.ut_line));
    950 		(void)strncpy(utmp.ut_host, host, sizeof(utmp.ut_host));
    951 		login(&utmp);
    952 	}
    953 	if (dowtmp)
    954 		logwtmp(line, name, host);
    955 #endif
    956 }
    957 
    958 static void
    959 logout_utmp(void)
    960 {
    961 	int okwtmp = dowtmp;
    962 	if (logged_in) {
    963 		if (doutmp) {
    964 #ifdef SUPPORT_UTMPX
    965 			okwtmp = logoutx(ttyline, 0, DEAD_PROCESS) & dowtmp;
    966 #endif
    967 #ifdef SUPPORT_UTMP
    968 			okwtmp = logout(ttyline) & dowtmp;
    969 #endif
    970 		}
    971 		if (okwtmp) {
    972 #ifdef SUPPORT_UTMPX
    973 			logwtmpx(ttyline, "", "", 0, DEAD_PROCESS);
    974 #endif
    975 #ifdef SUPPORT_UTMP
    976 			logwtmp(ttyline, "", "");
    977 #endif
    978 		}
    979 	}
    980 }
    981 
    982 /*
    983  * Terminate login as previous user (if any), resetting state;
    984  * used when USER command is given or login fails.
    985  */
    986 static void
    987 end_login(void)
    988 {
    989 	logout_utmp();
    990 	show_chdir_messages(-1);		/* flush chdir cache */
    991 	if (pw != NULL && pw->pw_passwd != NULL)
    992 		memset(pw->pw_passwd, 0, strlen(pw->pw_passwd));
    993 	pw = NULL;
    994 	logged_in = 0;
    995 	askpasswd = 0;
    996 	permitted = 0;
    997 	quietmessages = 0;
    998 	gidcount = 0;
    999 	curclass.type = CLASS_REAL;
   1000 	(void) seteuid((uid_t)0);
   1001 }
   1002 
   1003 void
   1004 pass(const char *passwd)
   1005 {
   1006 	int		 rval;
   1007 	char		 root[MAXPATHLEN];
   1008 
   1009 	if (logged_in || askpasswd == 0) {
   1010 		reply(503, "Login with USER first.");
   1011 		return;
   1012 	}
   1013 	askpasswd = 0;
   1014 	if (curclass.type != CLASS_GUEST) {
   1015 			/* "ftp" is the only account allowed with no password */
   1016 		if (pw == NULL) {
   1017 			rval = 1;	/* failure below */
   1018 			goto skip;
   1019 		}
   1020 #if defined(KERBEROS)
   1021 		if (klogin(pw, "", hostname, (char *)passwd) == 0) {
   1022 			rval = 0;
   1023 			goto skip;
   1024 		}
   1025 #endif
   1026 #if defined(KERBEROS5)
   1027 		if (k5login(pw, "", hostname, (char *)passwd) == 0) {
   1028 			rval = 0;
   1029 			goto skip;
   1030 		}
   1031 #endif
   1032 #ifdef SKEY
   1033 		if (skey_haskey(pw->pw_name) == 0) {
   1034 			char *p;
   1035 			int r;
   1036 
   1037 			p = xstrdup(passwd);
   1038 			r = skey_passcheck(pw->pw_name, p);
   1039 			free(p);
   1040 			if (r != -1) {
   1041 				rval = 0;
   1042 				goto skip;
   1043 			}
   1044 		}
   1045 #endif
   1046 		if (!sflag)
   1047 			rval = checkpassword(pw, passwd);
   1048 		else
   1049 			rval = 1;
   1050 
   1051  skip:
   1052 
   1053 			/*
   1054 			 * If rval > 0, the user failed the authentication check
   1055 			 * above.  If rval == 0, either Kerberos or local
   1056 			 * authentication succeeded.
   1057 			 */
   1058 		if (rval) {
   1059 			reply(530, "%s", rval == 2 ? "Password expired." :
   1060 			    "Login incorrect.");
   1061 			if (logging) {
   1062 				syslog(LOG_NOTICE,
   1063 				    "FTP LOGIN FAILED FROM %s", remotehost);
   1064 				syslog(LOG_AUTHPRIV | LOG_NOTICE,
   1065 				    "FTP LOGIN FAILED FROM %s, %s",
   1066 				    remotehost, curname);
   1067 			}
   1068 			pw = NULL;
   1069 			if (login_attempts++ >= 5) {
   1070 				syslog(LOG_NOTICE,
   1071 				    "repeated login failures from %s",
   1072 				    remotehost);
   1073 				exit(0);
   1074 			}
   1075 			return;
   1076 		}
   1077 	}
   1078 
   1079 			/* password ok; check if anything else prevents login */
   1080 	if (! permitted) {
   1081 		reply(530, "User %s may not use FTP.", pw->pw_name);
   1082 		if (logging)
   1083 			syslog(LOG_NOTICE, "FTP LOGIN REFUSED FROM %s, %s",
   1084 			    remotehost, pw->pw_name);
   1085 		goto bad;
   1086 	}
   1087 
   1088 	login_attempts = 0;		/* this time successful */
   1089 	if (setegid((gid_t)pw->pw_gid) < 0) {
   1090 		reply(550, "Can't set gid.");
   1091 		goto bad;
   1092 	}
   1093 	(void) initgroups(pw->pw_name, pw->pw_gid);
   1094 			/* cache groups for cmds.c::matchgroup() */
   1095 	gidcount = getgroups(sizeof(gidlist), gidlist);
   1096 
   1097 	/* open utmp/wtmp before chroot */
   1098 	login_utmp(ttyline, pw->pw_name, remotehost);
   1099 
   1100 	logged_in = 1;
   1101 
   1102 	connections = 1;
   1103 	if (dopidfile)
   1104 		count_users();
   1105 	if (curclass.limit != -1 && connections > curclass.limit) {
   1106 		if (! EMPTYSTR(curclass.limitfile))
   1107 			(void)display_file(conffilename(curclass.limitfile),
   1108 			    530);
   1109 		reply(530,
   1110 		    "User %s access denied, connection limit of " LLF
   1111 		    " reached.",
   1112 		    pw->pw_name, (LLT)curclass.limit);
   1113 		syslog(LOG_NOTICE,
   1114 		    "Maximum connection limit of " LLF
   1115 		    " for class %s reached, login refused for %s",
   1116 		    (LLT)curclass.limit, curclass.classname, pw->pw_name);
   1117 		goto bad;
   1118 	}
   1119 
   1120 	homedir[0] = '/';
   1121 	switch (curclass.type) {
   1122 	case CLASS_GUEST:
   1123 			/*
   1124 			 * We MUST do a chdir() after the chroot. Otherwise
   1125 			 * the old current directory will be accessible as "."
   1126 			 * outside the new root!
   1127 			 */
   1128 		format_path(root,
   1129 		    curclass.chroot ? curclass.chroot :
   1130 		    anondir ? anondir :
   1131 		    pw->pw_dir);
   1132 		format_path(homedir,
   1133 		    curclass.homedir ? curclass.homedir :
   1134 		    "/");
   1135 		if (EMPTYSTR(homedir))
   1136 			homedir[0] = '/';
   1137 		if (EMPTYSTR(root) || chroot(root) < 0) {
   1138 			syslog(LOG_NOTICE,
   1139 			    "GUEST user %s: can't chroot to %s: %m",
   1140 			    pw->pw_name, root);
   1141 			goto bad_guest;
   1142 		}
   1143 		if (chdir(homedir) < 0) {
   1144 			syslog(LOG_NOTICE,
   1145 			    "GUEST user %s: can't chdir to %s: %m",
   1146 			    pw->pw_name, homedir);
   1147  bad_guest:
   1148 			reply(550, "Can't set guest privileges.");
   1149 			goto bad;
   1150 		}
   1151 		break;
   1152 	case CLASS_CHROOT:
   1153 		format_path(root,
   1154 		    curclass.chroot ? curclass.chroot :
   1155 		    pw->pw_dir);
   1156 		format_path(homedir,
   1157 		    curclass.homedir ? curclass.homedir :
   1158 		    "/");
   1159 		if (EMPTYSTR(homedir))
   1160 			homedir[0] = '/';
   1161 		if (EMPTYSTR(root) || chroot(root) < 0) {
   1162 			syslog(LOG_NOTICE,
   1163 			    "CHROOT user %s: can't chroot to %s: %m",
   1164 			    pw->pw_name, root);
   1165 			goto bad_chroot;
   1166 		}
   1167 		if (chdir(homedir) < 0) {
   1168 			syslog(LOG_NOTICE,
   1169 			    "CHROOT user %s: can't chdir to %s: %m",
   1170 			    pw->pw_name, homedir);
   1171  bad_chroot:
   1172 			reply(550, "Can't change root.");
   1173 			goto bad;
   1174 		}
   1175 		break;
   1176 	case CLASS_REAL:
   1177 			/* only chroot REAL if explictly requested */
   1178 		if (! EMPTYSTR(curclass.chroot)) {
   1179 			format_path(root, curclass.chroot);
   1180 			if (EMPTYSTR(root) || chroot(root) < 0) {
   1181 				syslog(LOG_NOTICE,
   1182 				    "REAL user %s: can't chroot to %s: %m",
   1183 				    pw->pw_name, root);
   1184 				goto bad_chroot;
   1185 			}
   1186 		}
   1187 		format_path(homedir,
   1188 		    curclass.homedir ? curclass.homedir :
   1189 		    pw->pw_dir);
   1190 		if (EMPTYSTR(homedir) || chdir(homedir) < 0) {
   1191 			if (chdir("/") < 0) {
   1192 				syslog(LOG_NOTICE,
   1193 				    "REAL user %s: can't chdir to %s: %m",
   1194 				    pw->pw_name,
   1195 				    !EMPTYSTR(homedir) ?  homedir : "/");
   1196 				reply(530,
   1197 				    "User %s: can't change directory to %s.",
   1198 				    pw->pw_name,
   1199 				    !EMPTYSTR(homedir) ? homedir : "/");
   1200 				goto bad;
   1201 			} else {
   1202 				reply(-230,
   1203 				    "No directory! Logging in with home=/");
   1204 				homedir[0] = '/';
   1205 			}
   1206 		}
   1207 		break;
   1208 	}
   1209 	setlogin(pw->pw_name);
   1210 	if (dropprivs ||
   1211 	    (curclass.type != CLASS_REAL &&
   1212 	    ntohs(ctrl_addr.su_port) > IPPORT_RESERVED + 1)) {
   1213 		dropprivs++;
   1214 		if (setgid((gid_t)pw->pw_gid) < 0) {
   1215 			reply(550, "Can't set gid.");
   1216 			goto bad;
   1217 		}
   1218 		if (setuid((uid_t)pw->pw_uid) < 0) {
   1219 			reply(550, "Can't set uid.");
   1220 			goto bad;
   1221 		}
   1222 	} else {
   1223 		if (seteuid((uid_t)pw->pw_uid) < 0) {
   1224 			reply(550, "Can't set uid.");
   1225 			goto bad;
   1226 		}
   1227 	}
   1228 	setenv("HOME", homedir, 1);
   1229 
   1230 	if (curclass.type == CLASS_GUEST && passwd[0] == '-')
   1231 		quietmessages = 1;
   1232 
   1233 			/*
   1234 			 * Display a login message, if it exists.
   1235 			 * N.B. reply(230,) must follow the message.
   1236 			 */
   1237 	if (! EMPTYSTR(curclass.motd))
   1238 		(void)display_file(conffilename(curclass.motd), 230);
   1239 	show_chdir_messages(230);
   1240 	if (curclass.type == CLASS_GUEST) {
   1241 		char *p;
   1242 
   1243 		reply(230, "Guest login ok, access restrictions apply.");
   1244 #if HAVE_SETPROCTITLE
   1245 		snprintf(proctitle, sizeof(proctitle),
   1246 		    "%s: anonymous/%s", remotehost, passwd);
   1247 		setproctitle("%s", proctitle);
   1248 #endif /* HAVE_SETPROCTITLE */
   1249 		if (logging)
   1250 			syslog(LOG_INFO,
   1251 			"ANONYMOUS FTP LOGIN FROM %s, %s (class: %s, type: %s)",
   1252 			    remotehost, passwd,
   1253 			    curclass.classname, CURCLASSTYPE);
   1254 			/* store guest password reply into pw_passwd */
   1255 		REASSIGN(pw->pw_passwd, xstrdup(passwd));
   1256 		for (p = pw->pw_passwd; *p; p++)
   1257 			if (!isgraph(*p))
   1258 				*p = '_';
   1259 	} else {
   1260 		reply(230, "User %s logged in.", pw->pw_name);
   1261 #if HAVE_SETPROCTITLE
   1262 		snprintf(proctitle, sizeof(proctitle),
   1263 		    "%s: %s", remotehost, pw->pw_name);
   1264 		setproctitle("%s", proctitle);
   1265 #endif /* HAVE_SETPROCTITLE */
   1266 		if (logging)
   1267 			syslog(LOG_INFO,
   1268 			    "FTP LOGIN FROM %s as %s (class: %s, type: %s)",
   1269 			    remotehost, pw->pw_name,
   1270 			    curclass.classname, CURCLASSTYPE);
   1271 	}
   1272 	(void) umask(curclass.umask);
   1273 	return;
   1274 
   1275  bad:
   1276 			/* Forget all about it... */
   1277 	end_login();
   1278 }
   1279 
   1280 void
   1281 retrieve(char *argv[], const char *name)
   1282 {
   1283 	FILE *fin, *dout;
   1284 	struct stat st;
   1285 	int (*closefunc)(FILE *) = NULL;
   1286 	int dolog, sendrv, closerv, stderrfd, isconversion, isdata, isls;
   1287 	struct timeval start, finish, td, *tdp;
   1288 	struct rusage rusage_before, rusage_after;
   1289 	const char *dispname;
   1290 	char *error;
   1291 
   1292 	sendrv = closerv = stderrfd = -1;
   1293 	isconversion = isdata = isls = dolog = 0;
   1294 	tdp = NULL;
   1295 	dispname = name;
   1296 	fin = dout = NULL;
   1297 	error = NULL;
   1298 	if (argv == NULL) {		/* if not running a command ... */
   1299 		dolog = 1;
   1300 		isdata = 1;
   1301 		fin = fopen(name, "r");
   1302 		closefunc = fclose;
   1303 		if (fin == NULL)	/* doesn't exist?; try a conversion */
   1304 			argv = do_conversion(name);
   1305 		if (argv != NULL) {
   1306 			isconversion++;
   1307 			syslog(LOG_DEBUG, "get command: '%s' on '%s'",
   1308 			    argv[0], name);
   1309 		}
   1310 	}
   1311 	if (argv != NULL) {
   1312 		char temp[MAXPATHLEN];
   1313 
   1314 		if (strcmp(argv[0], INTERNAL_LS) == 0) {
   1315 			isls = 1;
   1316 			stderrfd = -1;
   1317 		} else {
   1318 			(void)snprintf(temp, sizeof(temp), "%s", TMPFILE);
   1319 			stderrfd = mkstemp(temp);
   1320 			if (stderrfd != -1)
   1321 				(void)unlink(temp);
   1322 		}
   1323 		dispname = argv[0];
   1324 		fin = ftpd_popen(argv, "r", stderrfd);
   1325 		closefunc = ftpd_pclose;
   1326 		st.st_size = -1;
   1327 		st.st_blksize = BUFSIZ;
   1328 	}
   1329 	if (fin == NULL) {
   1330 		if (errno != 0) {
   1331 			perror_reply(550, dispname);
   1332 			if (dolog)
   1333 				logxfer("get", -1, name, NULL, NULL,
   1334 				    strerror(errno));
   1335 		}
   1336 		goto cleanupretrieve;
   1337 	}
   1338 	byte_count = -1;
   1339 	if (argv == NULL
   1340 	    && (fstat(fileno(fin), &st) < 0 || !S_ISREG(st.st_mode))) {
   1341 		error = "Not a plain file";
   1342 		reply(550, "%s: %s.", dispname, error);
   1343 		goto done;
   1344 	}
   1345 	if (restart_point) {
   1346 		if (type == TYPE_A) {
   1347 			off_t i;
   1348 			int c;
   1349 
   1350 			for (i = 0; i < restart_point; i++) {
   1351 				if ((c=getc(fin)) == EOF) {
   1352 					error = strerror(errno);
   1353 					perror_reply(550, dispname);
   1354 					goto done;
   1355 				}
   1356 				if (c == '\n')
   1357 					i++;
   1358 			}
   1359 		} else if (lseek(fileno(fin), restart_point, SEEK_SET) < 0) {
   1360 			error = strerror(errno);
   1361 			perror_reply(550, dispname);
   1362 			goto done;
   1363 		}
   1364 	}
   1365 	dout = dataconn(dispname, st.st_size, "w");
   1366 	if (dout == NULL)
   1367 		goto done;
   1368 
   1369 	(void)getrusage(RUSAGE_SELF, &rusage_before);
   1370 	(void)gettimeofday(&start, NULL);
   1371 	sendrv = send_data(fin, dout, &st, isdata);
   1372 	(void)gettimeofday(&finish, NULL);
   1373 	(void)getrusage(RUSAGE_SELF, &rusage_after);
   1374 	closedataconn(dout);		/* close now to affect timing stats */
   1375 	timersub(&finish, &start, &td);
   1376 	tdp = &td;
   1377  done:
   1378 	if (dolog) {
   1379 		logxfer("get", byte_count, name, NULL, tdp, error);
   1380 		if (tdp != NULL)
   1381 			logrusage(&rusage_before, &rusage_after);
   1382 	}
   1383 	closerv = (*closefunc)(fin);
   1384 	if (sendrv == 0) {
   1385 		FILE *errf;
   1386 		struct stat sb;
   1387 
   1388 		if (!isls && argv != NULL && closerv != 0) {
   1389 			reply(-226,
   1390 			    "Command returned an exit status of %d",
   1391 			    closerv);
   1392 			if (isconversion)
   1393 				syslog(LOG_WARNING,
   1394 				    "retrieve command: '%s' returned %d",
   1395 				    argv[0], closerv);
   1396 		}
   1397 		if (!isls && argv != NULL && stderrfd != -1 &&
   1398 		    (fstat(stderrfd, &sb) == 0) && sb.st_size > 0 &&
   1399 		    ((errf = fdopen(stderrfd, "r")) != NULL)) {
   1400 			char *cp, line[LINE_MAX];
   1401 
   1402 			reply(-226, "Command error messages:");
   1403 			rewind(errf);
   1404 			while (fgets(line, sizeof(line), errf) != NULL) {
   1405 				if ((cp = strchr(line, '\n')) != NULL)
   1406 					*cp = '\0';
   1407 				reply(0, "  %s", line);
   1408 			}
   1409 			(void) fflush(stdout);
   1410 			(void) fclose(errf);
   1411 				/* a reply(226,) must follow */
   1412 		}
   1413 		reply(226, "Transfer complete.");
   1414 	}
   1415  cleanupretrieve:
   1416 	if (stderrfd != -1)
   1417 		(void)close(stderrfd);
   1418 	if (isconversion)
   1419 		free(argv);
   1420 }
   1421 
   1422 void
   1423 store(const char *name, const char *fmode, int unique)
   1424 {
   1425 	FILE *fout, *din;
   1426 	struct stat st;
   1427 	int (*closefunc)(FILE *);
   1428 	struct timeval start, finish, td, *tdp;
   1429 	char *desc, *error;
   1430 
   1431 	din = NULL;
   1432 	desc = (*fmode == 'w') ? "put" : "append";
   1433 	error = NULL;
   1434 	if (unique && stat(name, &st) == 0 &&
   1435 	    (name = gunique(name)) == NULL) {
   1436 		logxfer(desc, -1, name, NULL, NULL,
   1437 		    "cannot create unique file");
   1438 		goto cleanupstore;
   1439 	}
   1440 
   1441 	if (restart_point)
   1442 		fmode = "r+";
   1443 	fout = fopen(name, fmode);
   1444 	closefunc = fclose;
   1445 	tdp = NULL;
   1446 	if (fout == NULL) {
   1447 		perror_reply(553, name);
   1448 		logxfer(desc, -1, name, NULL, NULL, strerror(errno));
   1449 		goto cleanupstore;
   1450 	}
   1451 	byte_count = -1;
   1452 	if (restart_point) {
   1453 		if (type == TYPE_A) {
   1454 			off_t i;
   1455 			int c;
   1456 
   1457 			for (i = 0; i < restart_point; i++) {
   1458 				if ((c=getc(fout)) == EOF) {
   1459 					error = strerror(errno);
   1460 					perror_reply(550, name);
   1461 					goto done;
   1462 				}
   1463 				if (c == '\n')
   1464 					i++;
   1465 			}
   1466 			/*
   1467 			 * We must do this seek to "current" position
   1468 			 * because we are changing from reading to
   1469 			 * writing.
   1470 			 */
   1471 			if (fseek(fout, 0L, SEEK_CUR) < 0) {
   1472 				error = strerror(errno);
   1473 				perror_reply(550, name);
   1474 				goto done;
   1475 			}
   1476 		} else if (lseek(fileno(fout), restart_point, SEEK_SET) < 0) {
   1477 			error = strerror(errno);
   1478 			perror_reply(550, name);
   1479 			goto done;
   1480 		}
   1481 	}
   1482 	din = dataconn(name, (off_t)-1, "r");
   1483 	if (din == NULL)
   1484 		goto done;
   1485 	(void)gettimeofday(&start, NULL);
   1486 	if (receive_data(din, fout) == 0) {
   1487 		if (unique)
   1488 			reply(226, "Transfer complete (unique file name:%s).",
   1489 			    name);
   1490 		else
   1491 			reply(226, "Transfer complete.");
   1492 	}
   1493 	(void)gettimeofday(&finish, NULL);
   1494 	closedataconn(din);		/* close now to affect timing stats */
   1495 	timersub(&finish, &start, &td);
   1496 	tdp = &td;
   1497  done:
   1498 	logxfer(desc, byte_count, name, NULL, tdp, error);
   1499 	(*closefunc)(fout);
   1500  cleanupstore:
   1501 	;
   1502 }
   1503 
   1504 static FILE *
   1505 getdatasock(const char *fmode)
   1506 {
   1507 	int		on, s, t, tries;
   1508 	in_port_t	port;
   1509 
   1510 	on = 1;
   1511 	if (data >= 0)
   1512 		return (fdopen(data, fmode));
   1513 	if (! dropprivs)
   1514 		(void) seteuid((uid_t)0);
   1515 	s = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
   1516 	if (s < 0)
   1517 		goto bad;
   1518 	if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
   1519 	    (char *) &on, sizeof(on)) < 0)
   1520 		goto bad;
   1521 	if (setsockopt(s, SOL_SOCKET, SO_KEEPALIVE,
   1522 	    (char *) &on, sizeof(on)) < 0)
   1523 		goto bad;
   1524 			/* anchor socket to avoid multi-homing problems */
   1525 	data_source = ctrl_addr;
   1526 			/*
   1527 			 * By default source port for PORT connctions is
   1528 			 * ctrlport-1 (see RFC959 section 5.2).
   1529 			 * However, if privs have been dropped and that
   1530 			 * would be < IPPORT_RESERVED, use a random port
   1531 			 * instead.
   1532 			 */
   1533 	if (dataport)
   1534 		port = dataport;
   1535 	else
   1536 		port = ntohs(ctrl_addr.su_port) - 1;
   1537 	if (dropprivs && port < IPPORT_RESERVED)
   1538 		port = 0;		/* use random port */
   1539 	data_source.su_port = htons(port);
   1540 
   1541 	for (tries = 1; ; tries++) {
   1542 		if (bind(s, (struct sockaddr *)&data_source.si_su,
   1543 		    data_source.su_len) >= 0)
   1544 			break;
   1545 		if (errno != EADDRINUSE || tries > 10)
   1546 			goto bad;
   1547 		sleep(tries);
   1548 	}
   1549 	if (! dropprivs)
   1550 		(void) seteuid((uid_t)pw->pw_uid);
   1551 #ifdef IP_TOS
   1552 	if (!mapped && ctrl_addr.su_family == AF_INET) {
   1553 		on = IPTOS_THROUGHPUT;
   1554 		if (setsockopt(s, IPPROTO_IP, IP_TOS, (char *)&on,
   1555 			       sizeof(int)) < 0)
   1556 			syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
   1557 	}
   1558 #endif
   1559 	return (fdopen(s, fmode));
   1560  bad:
   1561 		/* Return the real value of errno (close may change it) */
   1562 	t = errno;
   1563 	if (! dropprivs)
   1564 		(void) seteuid((uid_t)pw->pw_uid);
   1565 	(void) close(s);
   1566 	errno = t;
   1567 	return (NULL);
   1568 }
   1569 
   1570 FILE *
   1571 dataconn(const char *name, off_t size, const char *fmode)
   1572 {
   1573 	char sizebuf[32];
   1574 	FILE *file;
   1575 	int retry = 0, tos, keepalive;
   1576 
   1577 	file_size = size;
   1578 	byte_count = 0;
   1579 	if (size != (off_t) -1)
   1580 		(void)snprintf(sizebuf, sizeof(sizebuf), " (" LLF " byte%s)",
   1581 		    (LLT)size, PLURAL(size));
   1582 	else
   1583 		sizebuf[0] = '\0';
   1584 	if (pdata >= 0) {
   1585 		struct sockinet from;
   1586 		int s, fromlen = sizeof(from.su_len);
   1587 
   1588 		(void) alarm(curclass.timeout);
   1589 		s = accept(pdata, (struct sockaddr *)&from.si_su, &fromlen);
   1590 		(void) alarm(0);
   1591 		if (s < 0) {
   1592 			reply(425, "Can't open data connection.");
   1593 			(void) close(pdata);
   1594 			pdata = -1;
   1595 			return (NULL);
   1596 		}
   1597 		(void) close(pdata);
   1598 		pdata = s;
   1599 		switch (from.su_family) {
   1600 		case AF_INET:
   1601 #ifdef IP_TOS
   1602 			if (!mapped) {
   1603 				tos = IPTOS_THROUGHPUT;
   1604 				(void) setsockopt(s, IPPROTO_IP, IP_TOS,
   1605 				    (char *)&tos, sizeof(int));
   1606 			}
   1607 			break;
   1608 #endif
   1609 		}
   1610 		/* Set keepalives on the socket to detect dropped conns. */
   1611 #ifdef SO_KEEPALIVE
   1612 		keepalive = 1;
   1613 		(void) setsockopt(s, SOL_SOCKET, SO_KEEPALIVE,
   1614 		    (char *)&keepalive, sizeof(int));
   1615 #endif
   1616 		reply(150, "Opening %s mode data connection for '%s'%s.",
   1617 		     type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
   1618 		return (fdopen(pdata, fmode));
   1619 	}
   1620 	if (data >= 0) {
   1621 		reply(125, "Using existing data connection for '%s'%s.",
   1622 		    name, sizebuf);
   1623 		usedefault = 1;
   1624 		return (fdopen(data, fmode));
   1625 	}
   1626 	if (usedefault)
   1627 		data_dest = his_addr;
   1628 	usedefault = 1;
   1629 	file = getdatasock(fmode);
   1630 	if (file == NULL) {
   1631 		char hbuf[NI_MAXHOST];
   1632 		char pbuf[NI_MAXSERV];
   1633 
   1634 		if (getnameinfo((struct sockaddr *)&data_source.si_su,
   1635 		    data_source.su_len, hbuf, sizeof(hbuf), pbuf, sizeof(pbuf),
   1636 		    NI_NUMERICHOST | NI_NUMERICSERV))
   1637 			strlcpy(hbuf, "?", sizeof(hbuf));
   1638 		reply(425, "Can't create data socket (%s,%s): %s.",
   1639 		      hbuf, pbuf, strerror(errno));
   1640 		return (NULL);
   1641 	}
   1642 	data = fileno(file);
   1643 	while (connect(data, (struct sockaddr *)&data_dest.si_su,
   1644 	    data_dest.su_len) < 0) {
   1645 		if (errno == EADDRINUSE && retry < swaitmax) {
   1646 			sleep((unsigned) swaitint);
   1647 			retry += swaitint;
   1648 			continue;
   1649 		}
   1650 		perror_reply(425, "Can't build data connection");
   1651 		(void) fclose(file);
   1652 		data = -1;
   1653 		return (NULL);
   1654 	}
   1655 	reply(150, "Opening %s mode data connection for '%s'%s.",
   1656 	     type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
   1657 	return (file);
   1658 }
   1659 
   1660 void
   1661 closedataconn(FILE *fd)
   1662 {
   1663 
   1664 	if (fd == NULL)
   1665 		return;
   1666 	(void)fclose(fd);
   1667 	data = -1;
   1668 	if (pdata >= 0)
   1669 		(void)close(pdata);
   1670 	pdata = -1;
   1671 }
   1672 
   1673 int
   1674 write_data(int fd, char *buf, size_t size, off_t *bufrem,
   1675     struct timeval *then, int isdata)
   1676 {
   1677 	struct timeval now, td;
   1678 	ssize_t c;
   1679 
   1680 	while (size > 0) {
   1681 		c = size;
   1682 		if (curclass.writesize) {
   1683 			if (curclass.writesize < c)
   1684 				c = curclass.writesize;
   1685 		}
   1686 		if (curclass.rateget) {
   1687 			if (*bufrem < c)
   1688 				c = *bufrem;
   1689 		}
   1690 		(void) alarm(curclass.timeout);
   1691 		c = write(fd, buf, c);
   1692 		if (c <= 0)
   1693 			return (1);
   1694 		buf += c;
   1695 		size -= c;
   1696 		byte_count += c;
   1697 		if (isdata) {
   1698 			total_data_out += c;
   1699 			total_data += c;
   1700 		}
   1701 		total_bytes_out += c;
   1702 		total_bytes += c;
   1703 		if (curclass.rateget) {
   1704 			*bufrem -= c;
   1705 			if (*bufrem == 0) {
   1706 				(void)gettimeofday(&now, NULL);
   1707 				timersub(&now, then, &td);
   1708 				if (td.tv_sec == 0) {
   1709 					usleep(1000000 - td.tv_usec);
   1710 					(void)gettimeofday(then, NULL);
   1711 				} else
   1712 					*then = now;
   1713 				*bufrem = curclass.rateget;
   1714 			}
   1715 		}
   1716 	}
   1717 	return (0);
   1718 }
   1719 
   1720 static enum send_status
   1721 send_data_with_read(int filefd, int netfd, const struct stat *st, int isdata)
   1722 {
   1723 	struct timeval then;
   1724 	off_t bufrem;
   1725 	size_t readsize;
   1726 	char *buf;
   1727 	int c, error;
   1728 
   1729 	if (curclass.readsize)
   1730 		readsize = curclass.readsize;
   1731 	else
   1732 		readsize = (size_t)st->st_blksize;
   1733 	if ((buf = malloc(readsize)) == NULL) {
   1734 		perror_reply(451, "Local resource failure: malloc");
   1735 		return (SS_NO_TRANSFER);
   1736 	}
   1737 
   1738 	if (curclass.rateget) {
   1739 		bufrem = curclass.rateget;
   1740 		(void)gettimeofday(&then, NULL);
   1741 	}
   1742 	while (1) {
   1743 		(void) alarm(curclass.timeout);
   1744 		c = read(filefd, buf, readsize);
   1745 		if (c == 0)
   1746 			error = SS_SUCCESS;
   1747 		else if (c < 0)
   1748 			error = SS_FILE_ERROR;
   1749 		else if (write_data(netfd, buf, c, &bufrem, &then, isdata))
   1750 			error = SS_DATA_ERROR;
   1751 		else
   1752 			continue;
   1753 
   1754 		free(buf);
   1755 		return (error);
   1756 	}
   1757 }
   1758 
   1759 static enum send_status
   1760 send_data_with_mmap(int filefd, int netfd, const struct stat *st, int isdata)
   1761 {
   1762 	struct timeval then;
   1763 	off_t bufrem, filesize, off, origoff;
   1764 	size_t mapsize, winsize;
   1765 	int error, sendbufsize, sendlowat;
   1766 	void *win;
   1767 
   1768 	if (curclass.sendbufsize) {
   1769 		sendbufsize = curclass.sendbufsize;
   1770 		if (setsockopt(netfd, SOL_SOCKET, SO_SNDBUF,
   1771 		    &sendbufsize, sizeof(int)) == -1)
   1772 			syslog(LOG_WARNING, "setsockopt(SO_SNDBUF, %d): %m",
   1773 			    sendbufsize);
   1774 	}
   1775 
   1776 	if (curclass.sendlowat) {
   1777 		sendlowat = curclass.sendlowat;
   1778 		if (setsockopt(netfd, SOL_SOCKET, SO_SNDLOWAT,
   1779 		    &sendlowat, sizeof(int)) == -1)
   1780 			syslog(LOG_WARNING, "setsockopt(SO_SNDLOWAT, %d): %m",
   1781 			    sendlowat);
   1782 	}
   1783 
   1784 	winsize = curclass.mmapsize;
   1785 	filesize = st->st_size;
   1786 	if (debug)
   1787 		syslog(LOG_INFO, "mmapsize = %ld, writesize = %ld",
   1788 		    (long)winsize, (long)curclass.writesize);
   1789 	if (winsize == 0)
   1790 		goto try_read;
   1791 
   1792 	off = lseek(filefd, (off_t)0, SEEK_CUR);
   1793 	if (off == -1)
   1794 		goto try_read;
   1795 
   1796 	origoff = off;
   1797 	if (curclass.rateget) {
   1798 		bufrem = curclass.rateget;
   1799 		(void)gettimeofday(&then, NULL);
   1800 	}
   1801 	while (1) {
   1802 		mapsize = MIN(filesize - off, winsize);
   1803 		if (mapsize == 0)
   1804 			break;
   1805 		win = mmap(NULL, mapsize, PROT_READ,
   1806 		    MAP_FILE|MAP_SHARED, filefd, off);
   1807 		if (win == MAP_FAILED) {
   1808 			if (off == origoff)
   1809 				goto try_read;
   1810 			return (SS_FILE_ERROR);
   1811 		}
   1812 		(void) madvise(win, mapsize, MADV_SEQUENTIAL);
   1813 		error = write_data(netfd, win, mapsize, &bufrem, &then,
   1814 		    isdata);
   1815 		(void) madvise(win, mapsize, MADV_DONTNEED);
   1816 		munmap(win, mapsize);
   1817 		if (error)
   1818 			return (SS_DATA_ERROR);
   1819 		off += mapsize;
   1820 	}
   1821 	return (SS_SUCCESS);
   1822 
   1823  try_read:
   1824 	return (send_data_with_read(filefd, netfd, st, isdata));
   1825 }
   1826 
   1827 /*
   1828  * Tranfer the contents of "instr" to "outstr" peer using the appropriate
   1829  * encapsulation of the data subject to Mode, Structure, and Type.
   1830  *
   1831  * NB: Form isn't handled.
   1832  */
   1833 static int
   1834 send_data(FILE *instr, FILE *outstr, const struct stat *st, int isdata)
   1835 {
   1836 	int	 c, filefd, netfd, rval;
   1837 
   1838 	transflag = 1;
   1839 	rval = -1;
   1840 	if (setjmp(urgcatch))
   1841 		goto cleanup_send_data;
   1842 
   1843 	switch (type) {
   1844 
   1845 	case TYPE_A:
   1846  /* XXXLUKEM: rate limit ascii send (get) */
   1847 		(void) alarm(curclass.timeout);
   1848 		while ((c = getc(instr)) != EOF) {
   1849 			byte_count++;
   1850 			if (c == '\n') {
   1851 				if (ferror(outstr))
   1852 					goto data_err;
   1853 				(void) putc('\r', outstr);
   1854 				if (isdata) {
   1855 					total_data_out++;
   1856 					total_data++;
   1857 				}
   1858 				total_bytes_out++;
   1859 				total_bytes++;
   1860 			}
   1861 			(void) putc(c, outstr);
   1862 			if (isdata) {
   1863 				total_data_out++;
   1864 				total_data++;
   1865 			}
   1866 			total_bytes_out++;
   1867 			total_bytes++;
   1868 			if ((byte_count % 4096) == 0)
   1869 				(void) alarm(curclass.timeout);
   1870 		}
   1871 		(void) alarm(0);
   1872 		fflush(outstr);
   1873 		if (ferror(instr))
   1874 			goto file_err;
   1875 		if (ferror(outstr))
   1876 			goto data_err;
   1877 		rval = 0;
   1878 		goto cleanup_send_data;
   1879 
   1880 	case TYPE_I:
   1881 	case TYPE_L:
   1882 		filefd = fileno(instr);
   1883 		netfd = fileno(outstr);
   1884 		switch (send_data_with_mmap(filefd, netfd, st, isdata)) {
   1885 
   1886 		case SS_SUCCESS:
   1887 			break;
   1888 
   1889 		case SS_NO_TRANSFER:
   1890 			goto cleanup_send_data;
   1891 
   1892 		case SS_FILE_ERROR:
   1893 			goto file_err;
   1894 
   1895 		case SS_DATA_ERROR:
   1896 			goto data_err;
   1897 		}
   1898 		rval = 0;
   1899 		goto cleanup_send_data;
   1900 
   1901 	default:
   1902 		reply(550, "Unimplemented TYPE %d in send_data", type);
   1903 		goto cleanup_send_data;
   1904 	}
   1905 
   1906  data_err:
   1907 	(void) alarm(0);
   1908 	perror_reply(426, "Data connection");
   1909 	goto cleanup_send_data;
   1910 
   1911  file_err:
   1912 	(void) alarm(0);
   1913 	perror_reply(551, "Error on input file");
   1914 		/* FALLTHROUGH */
   1915 
   1916  cleanup_send_data:
   1917 	(void) alarm(0);
   1918 	transflag = 0;
   1919 	if (isdata) {
   1920 		total_files_out++;
   1921 		total_files++;
   1922 	}
   1923 	total_xfers_out++;
   1924 	total_xfers++;
   1925 	return (rval);
   1926 }
   1927 
   1928 /*
   1929  * Transfer data from peer to "outstr" using the appropriate encapulation of
   1930  * the data subject to Mode, Structure, and Type.
   1931  *
   1932  * N.B.: Form isn't handled.
   1933  */
   1934 static int
   1935 receive_data(FILE *instr, FILE *outstr)
   1936 {
   1937 	int	c, bare_lfs, netfd, filefd, rval;
   1938 	off_t	byteswritten;
   1939 	char	buf[BUFSIZ];
   1940 #ifdef __GNUC__
   1941 	(void) &bare_lfs;
   1942 #endif
   1943 
   1944 	bare_lfs = 0;
   1945 	transflag = 1;
   1946 	rval = -1;
   1947 	byteswritten = 0;
   1948 	if (setjmp(urgcatch))
   1949 		goto cleanup_recv_data;
   1950 
   1951 #define FILESIZECHECK(x) \
   1952 			do { \
   1953 				if (curclass.maxfilesize != -1 && \
   1954 				    (x) > curclass.maxfilesize) { \
   1955 					errno = EFBIG; \
   1956 					goto file_err; \
   1957 				} \
   1958 			} while (0)
   1959 
   1960 	switch (type) {
   1961 
   1962 	case TYPE_I:
   1963 	case TYPE_L:
   1964 		netfd = fileno(instr);
   1965 		filefd = fileno(outstr);
   1966 		(void) alarm(curclass.timeout);
   1967 		if (curclass.rateput) {
   1968 			while (1) {
   1969 				int d;
   1970 				struct timeval then, now, td;
   1971 				off_t bufrem;
   1972 
   1973 				(void)gettimeofday(&then, NULL);
   1974 				errno = c = d = 0;
   1975 				for (bufrem = curclass.rateput; bufrem > 0; ) {
   1976 					if ((c = read(netfd, buf,
   1977 					    MIN(sizeof(buf), bufrem))) <= 0)
   1978 						goto recvdone;
   1979 					FILESIZECHECK(byte_count + c);
   1980 					if ((d = write(filefd, buf, c)) != c)
   1981 						goto file_err;
   1982 					(void) alarm(curclass.timeout);
   1983 					bufrem -= c;
   1984 					byte_count += c;
   1985 					total_data_in += c;
   1986 					total_data += c;
   1987 					total_bytes_in += c;
   1988 					total_bytes += c;
   1989 				}
   1990 				(void)gettimeofday(&now, NULL);
   1991 				timersub(&now, &then, &td);
   1992 				if (td.tv_sec == 0)
   1993 					usleep(1000000 - td.tv_usec);
   1994 			}
   1995 		} else {
   1996 			while ((c = read(netfd, buf, sizeof(buf))) > 0) {
   1997 				FILESIZECHECK(byte_count + c);
   1998 				if (write(filefd, buf, c) != c)
   1999 					goto file_err;
   2000 				(void) alarm(curclass.timeout);
   2001 				byte_count += c;
   2002 				total_data_in += c;
   2003 				total_data += c;
   2004 				total_bytes_in += c;
   2005 				total_bytes += c;
   2006 			}
   2007 		}
   2008  recvdone:
   2009 		if (c < 0)
   2010 			goto data_err;
   2011 		rval = 0;
   2012 		goto cleanup_recv_data;
   2013 
   2014 	case TYPE_E:
   2015 		reply(553, "TYPE E not implemented.");
   2016 		goto cleanup_recv_data;
   2017 
   2018 	case TYPE_A:
   2019 		(void) alarm(curclass.timeout);
   2020  /* XXXLUKEM: rate limit ascii receive (put) */
   2021 		while ((c = getc(instr)) != EOF) {
   2022 			byte_count++;
   2023 			total_data_in++;
   2024 			total_data++;
   2025 			total_bytes_in++;
   2026 			total_bytes++;
   2027 			if ((byte_count % 4096) == 0)
   2028 				(void) alarm(curclass.timeout);
   2029 			if (c == '\n')
   2030 				bare_lfs++;
   2031 			while (c == '\r') {
   2032 				if (ferror(outstr))
   2033 					goto data_err;
   2034 				if ((c = getc(instr)) != '\n') {
   2035 					byte_count++;
   2036 					total_data_in++;
   2037 					total_data++;
   2038 					total_bytes_in++;
   2039 					total_bytes++;
   2040 					if ((byte_count % 4096) == 0)
   2041 						(void) alarm(curclass.timeout);
   2042 					byteswritten++;
   2043 					FILESIZECHECK(byteswritten);
   2044 					(void) putc ('\r', outstr);
   2045 					if (c == '\0' || c == EOF)
   2046 						goto contin2;
   2047 				}
   2048 			}
   2049 			byteswritten++;
   2050 			FILESIZECHECK(byteswritten);
   2051 			(void) putc(c, outstr);
   2052  contin2:	;
   2053 		}
   2054 		(void) alarm(0);
   2055 		fflush(outstr);
   2056 		if (ferror(instr))
   2057 			goto data_err;
   2058 		if (ferror(outstr))
   2059 			goto file_err;
   2060 		if (bare_lfs) {
   2061 			reply(-226,
   2062 			    "WARNING! %d bare linefeeds received in ASCII mode",
   2063 			    bare_lfs);
   2064 			reply(0, "File may not have transferred correctly.");
   2065 		}
   2066 		rval = 0;
   2067 		goto cleanup_recv_data;
   2068 
   2069 	default:
   2070 		reply(550, "Unimplemented TYPE %d in receive_data", type);
   2071 		goto cleanup_recv_data;
   2072 	}
   2073 #undef FILESIZECHECK
   2074 
   2075  data_err:
   2076 	(void) alarm(0);
   2077 	perror_reply(426, "Data Connection");
   2078 	goto cleanup_recv_data;
   2079 
   2080  file_err:
   2081 	(void) alarm(0);
   2082 	perror_reply(452, "Error writing file");
   2083 	goto cleanup_recv_data;
   2084 
   2085  cleanup_recv_data:
   2086 	(void) alarm(0);
   2087 	transflag = 0;
   2088 	total_files_in++;
   2089 	total_files++;
   2090 	total_xfers_in++;
   2091 	total_xfers++;
   2092 	return (rval);
   2093 }
   2094 
   2095 void
   2096 statcmd(void)
   2097 {
   2098 	struct sockinet *su = NULL;
   2099 	static char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
   2100 	u_char *a, *p;
   2101 	int ispassive, af;
   2102 	off_t otbi, otbo, otb;
   2103 
   2104 	a = p = (u_char *)NULL;
   2105 
   2106 	reply(-211, "%s FTP server status:", hostname);
   2107 	reply(0, "Version: %s", EMPTYSTR(version) ? "<suppressed>" : version);
   2108 	hbuf[0] = '\0';
   2109 	if (!getnameinfo((struct sockaddr *)&his_addr.si_su, his_addr.su_len,
   2110 			hbuf, sizeof(hbuf), NULL, 0, NI_NUMERICHOST)
   2111 	    && strcmp(remotehost, hbuf) != 0)
   2112 		reply(0, "Connected to %s (%s)", remotehost, hbuf);
   2113 	else
   2114 		reply(0, "Connected to %s", remotehost);
   2115 
   2116 	if (logged_in) {
   2117 		if (curclass.type == CLASS_GUEST)
   2118 			reply(0, "Logged in anonymously");
   2119 		else
   2120 			reply(0, "Logged in as %s%s", pw->pw_name,
   2121 			    curclass.type == CLASS_CHROOT ? " (chroot)" : "");
   2122 	} else if (askpasswd)
   2123 		reply(0, "Waiting for password");
   2124 	else
   2125 		reply(0, "Waiting for user name");
   2126 	cprintf(stdout, "    TYPE: %s", typenames[type]);
   2127 	if (type == TYPE_A || type == TYPE_E)
   2128 		cprintf(stdout, ", FORM: %s", formnames[form]);
   2129 	if (type == TYPE_L) {
   2130 #if NBBY == 8
   2131 		cprintf(stdout, " %d", NBBY);
   2132 #else
   2133 			/* XXX: `bytesize' needs to be defined in this case */
   2134 		cprintf(stdout, " %d", bytesize);
   2135 #endif
   2136 	}
   2137 	cprintf(stdout, "; STRUcture: %s; transfer MODE: %s\r\n",
   2138 	    strunames[stru], modenames[mode]);
   2139 	ispassive = 0;
   2140 	if (data != -1) {
   2141 		reply(0, "Data connection open");
   2142 		su = NULL;
   2143 	} else if (pdata != -1) {
   2144 		reply(0, "in Passive mode");
   2145 		if (curclass.advertise.su_len != 0)
   2146 			su = &curclass.advertise;
   2147 		else
   2148 			su = &pasv_addr;
   2149 		ispassive = 1;
   2150 		goto printaddr;
   2151 	} else if (usedefault == 0) {
   2152 		if (epsvall) {
   2153 			reply(0, "EPSV only mode (EPSV ALL)");
   2154 			goto epsvonly;
   2155 		}
   2156 		su = (struct sockinet *)&data_dest;
   2157  printaddr:
   2158 							/* PASV/PORT */
   2159 		if (su->su_family == AF_INET) {
   2160 			a = (u_char *) &su->su_addr;
   2161 			p = (u_char *) &su->su_port;
   2162 #define UC(b) (((int) b) & 0xff)
   2163 			reply(0, "%s (%d,%d,%d,%d,%d,%d)",
   2164 				ispassive ? "PASV" : "PORT" ,
   2165 				UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
   2166 				UC(p[0]), UC(p[1]));
   2167 		}
   2168 
   2169 							/* LPSV/LPRT */
   2170 	    {
   2171 		int alen, i;
   2172 
   2173 		alen = 0;
   2174 		switch (su->su_family) {
   2175 		case AF_INET:
   2176 			a = (u_char *) &su->su_addr;
   2177 			p = (u_char *) &su->su_port;
   2178 			alen = sizeof(su->su_addr);
   2179 			af = 4;
   2180 			break;
   2181 #ifdef INET6
   2182 		case AF_INET6:
   2183 			a = (u_char *) &su->su_6addr;
   2184 			p = (u_char *) &su->su_port;
   2185 			alen = sizeof(su->su_6addr);
   2186 			af = 6;
   2187 			break;
   2188 #endif
   2189 		default:
   2190 			af = 0;
   2191 			break;
   2192 		}
   2193 		if (af) {
   2194 			cprintf(stdout, "    %s (%d,%d",
   2195 			    ispassive ? "LPSV" : "LPRT", af, alen);
   2196 			for (i = 0; i < alen; i++)
   2197 				cprintf(stdout, ",%d", UC(a[i]));
   2198 			cprintf(stdout, ",%d,%d,%d)\r\n",
   2199 			    2, UC(p[0]), UC(p[1]));
   2200 #undef UC
   2201 		}
   2202 	    }
   2203 
   2204 		/* EPRT/EPSV */
   2205  epsvonly:
   2206 		af = af2epsvproto(su->su_family);
   2207 		hbuf[0] = '\0';
   2208 		if (af > 0) {
   2209 			struct sockinet tmp;
   2210 
   2211 			tmp = *su;
   2212 #ifdef INET6
   2213 			if (tmp.su_family == AF_INET6)
   2214 				tmp.su_scope_id = 0;
   2215 #endif
   2216 			if (getnameinfo((struct sockaddr *)&tmp.si_su,
   2217 			    tmp.su_len, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf),
   2218 			    NI_NUMERICHOST | NI_NUMERICSERV) == 0)
   2219 				reply(0, "%s (|%d|%s|%s|)",
   2220 				    ispassive ? "EPSV" : "EPRT",
   2221 				    af, hbuf, sbuf);
   2222 		}
   2223 	} else
   2224 		reply(0, "No data connection");
   2225 
   2226 	if (logged_in) {
   2227 		reply(0,
   2228 		    "Data sent:        " LLF " byte%s in " LLF " file%s",
   2229 		    (LLT)total_data_out, PLURAL(total_data_out),
   2230 		    (LLT)total_files_out, PLURAL(total_files_out));
   2231 		reply(0,
   2232 		    "Data received:    " LLF " byte%s in " LLF " file%s",
   2233 		    (LLT)total_data_in, PLURAL(total_data_in),
   2234 		    (LLT)total_files_in, PLURAL(total_files_in));
   2235 		reply(0,
   2236 		    "Total data:       " LLF " byte%s in " LLF " file%s",
   2237 		    (LLT)total_data, PLURAL(total_data),
   2238 		    (LLT)total_files, PLURAL(total_files));
   2239 	}
   2240 	otbi = total_bytes_in;
   2241 	otbo = total_bytes_out;
   2242 	otb = total_bytes;
   2243 	reply(0, "Traffic sent:     " LLF " byte%s in " LLF " transfer%s",
   2244 	    (LLT)otbo, PLURAL(otbo),
   2245 	    (LLT)total_xfers_out, PLURAL(total_xfers_out));
   2246 	reply(0, "Traffic received: " LLF " byte%s in " LLF " transfer%s",
   2247 	    (LLT)otbi, PLURAL(otbi),
   2248 	    (LLT)total_xfers_in, PLURAL(total_xfers_in));
   2249 	reply(0, "Total traffic:    " LLF " byte%s in " LLF " transfer%s",
   2250 	    (LLT)otb, PLURAL(otb),
   2251 	    (LLT)total_xfers, PLURAL(total_xfers));
   2252 
   2253 	if (logged_in && !CURCLASS_FLAGS_ISSET(private)) {
   2254 		struct ftpconv *cp;
   2255 
   2256 		reply(0, "%s", "");
   2257 		reply(0, "Class: %s, type: %s",
   2258 		    curclass.classname, CURCLASSTYPE);
   2259 		reply(0, "Check PORT/LPRT commands: %sabled",
   2260 		    CURCLASS_FLAGS_ISSET(checkportcmd) ? "en" : "dis");
   2261 		if (! EMPTYSTR(curclass.display))
   2262 			reply(0, "Display file: %s", curclass.display);
   2263 		if (! EMPTYSTR(curclass.notify))
   2264 			reply(0, "Notify fileglob: %s", curclass.notify);
   2265 		reply(0, "Idle timeout: " LLF ", maximum timeout: " LLF,
   2266 		    (LLT)curclass.timeout, (LLT)curclass.maxtimeout);
   2267 		reply(0, "Current connections: %d", connections);
   2268 		if (curclass.limit == -1)
   2269 			reply(0, "Maximum connections: unlimited");
   2270 		else
   2271 			reply(0, "Maximum connections: " LLF,
   2272 			    (LLT)curclass.limit);
   2273 		if (curclass.limitfile)
   2274 			reply(0, "Connection limit exceeded message file: %s",
   2275 			    conffilename(curclass.limitfile));
   2276 		if (! EMPTYSTR(curclass.chroot))
   2277 			reply(0, "Chroot format: %s", curclass.chroot);
   2278 		reply(0, "Deny bad ftpusers(5) quickly: %sabled",
   2279 		    CURCLASS_FLAGS_ISSET(denyquick) ? "en" : "dis");
   2280 		if (! EMPTYSTR(curclass.homedir))
   2281 			reply(0, "Homedir format: %s", curclass.homedir);
   2282 		if (curclass.maxfilesize == -1)
   2283 			reply(0, "Maximum file size: unlimited");
   2284 		else
   2285 			reply(0, "Maximum file size: " LLF,
   2286 			    (LLT)curclass.maxfilesize);
   2287 		if (! EMPTYSTR(curclass.motd))
   2288 			reply(0, "MotD file: %s", conffilename(curclass.motd));
   2289 		reply(0,
   2290 	    "Modify commands (CHMOD, DELE, MKD, RMD, RNFR, UMASK): %sabled",
   2291 		    CURCLASS_FLAGS_ISSET(modify) ? "en" : "dis");
   2292 		reply(0, "Upload commands (APPE, STOR, STOU): %sabled",
   2293 		    CURCLASS_FLAGS_ISSET(upload) ? "en" : "dis");
   2294 		reply(0, "Sanitize file names: %sabled",
   2295 		    CURCLASS_FLAGS_ISSET(sanenames) ? "en" : "dis");
   2296 		reply(0, "PASV/LPSV/EPSV connections: %sabled",
   2297 		    CURCLASS_FLAGS_ISSET(passive) ? "en" : "dis");
   2298 		if (curclass.advertise.su_len != 0) {
   2299 			char buf[50];	/* big enough for IPv6 address */
   2300 			const char *bp;
   2301 
   2302 			bp = inet_ntop(curclass.advertise.su_family,
   2303 			    (void *)&curclass.advertise.su_addr,
   2304 			    buf, sizeof(buf));
   2305 			if (bp != NULL)
   2306 				reply(0, "PASV advertise address: %s", bp);
   2307 		}
   2308 		if (curclass.portmin && curclass.portmax)
   2309 			reply(0, "PASV port range: " LLF " - " LLF,
   2310 			    (LLT)curclass.portmin, (LLT)curclass.portmax);
   2311 		if (curclass.rateget)
   2312 			reply(0, "Rate get limit: " LLF " bytes/sec",
   2313 			    (LLT)curclass.rateget);
   2314 		else
   2315 			reply(0, "Rate get limit: disabled");
   2316 		if (curclass.rateput)
   2317 			reply(0, "Rate put limit: " LLF " bytes/sec",
   2318 			    (LLT)curclass.rateput);
   2319 		else
   2320 			reply(0, "Rate put limit: disabled");
   2321 		if (curclass.mmapsize)
   2322 			reply(0, "Mmap size: " LLF, (LLT)curclass.mmapsize);
   2323 		else
   2324 			reply(0, "Mmap size: disabled");
   2325 		if (curclass.readsize)
   2326 			reply(0, "Read size: " LLF, (LLT)curclass.readsize);
   2327 		else
   2328 			reply(0, "Read size: default");
   2329 		if (curclass.writesize)
   2330 			reply(0, "Write size: " LLF, (LLT)curclass.writesize);
   2331 		else
   2332 			reply(0, "Write size: default");
   2333 		if (curclass.sendbufsize)
   2334 			reply(0, "Send buffer size: " LLF,
   2335 			    (LLT)curclass.sendbufsize);
   2336 		else
   2337 			reply(0, "Send buffer size: default");
   2338 		if (curclass.sendlowat)
   2339 			reply(0, "Send low water mark: " LLF,
   2340 			    (LLT)curclass.sendlowat);
   2341 		else
   2342 			reply(0, "Send low water mark: default");
   2343 		reply(0, "Umask: %.04o", curclass.umask);
   2344 		for (cp = curclass.conversions; cp != NULL; cp=cp->next) {
   2345 			if (cp->suffix == NULL || cp->types == NULL ||
   2346 			    cp->command == NULL)
   2347 				continue;
   2348 			reply(0, "Conversion: %s [%s] disable: %s, command: %s",
   2349 			    cp->suffix, cp->types, cp->disable, cp->command);
   2350 		}
   2351 	}
   2352 
   2353 	reply(211, "End of status");
   2354 }
   2355 
   2356 void
   2357 fatal(const char *s)
   2358 {
   2359 
   2360 	reply(451, "Error in server: %s\n", s);
   2361 	reply(221, "Closing connection due to server error.");
   2362 	dologout(0);
   2363 	/* NOTREACHED */
   2364 }
   2365 
   2366 /*
   2367  * reply() --
   2368  *	depending on the value of n, display fmt with a trailing CRLF and
   2369  *	prefix of:
   2370  *	n < -1		prefix the message with abs(n) + "-"	(initial line)
   2371  *	n == 0		prefix the message with 4 spaces	(middle lines)
   2372  *	n >  0		prefix the message with n + " "		(final line)
   2373  */
   2374 void
   2375 reply(int n, const char *fmt, ...)
   2376 {
   2377 	off_t b;
   2378 	va_list ap;
   2379 
   2380 	va_start(ap, fmt);
   2381 	b = 0;
   2382 	if (n == 0)
   2383 		cprintf(stdout, "    ");
   2384 	else if (n < 0)
   2385 		cprintf(stdout, "%d-", -n);
   2386 	else
   2387 		cprintf(stdout, "%d ", n);
   2388 	b = vprintf(fmt, ap);
   2389 	va_end(ap);
   2390 	total_bytes += b;
   2391 	total_bytes_out += b;
   2392 	cprintf(stdout, "\r\n");
   2393 	(void)fflush(stdout);
   2394 	if (debug) {
   2395 		syslog(LOG_DEBUG, "<--- %d%c", abs(n), (n < 0) ? '-' : ' ');
   2396 		va_start(ap, fmt);
   2397 		vsyslog(LOG_DEBUG, fmt, ap);
   2398 		va_end(ap);
   2399 	}
   2400 }
   2401 
   2402 static void
   2403 logremotehost(struct sockinet *who)
   2404 {
   2405 
   2406 	if (getnameinfo((struct sockaddr *)&who->si_su,
   2407 	    who->su_len, remotehost, sizeof(remotehost), NULL, 0, 0))
   2408 		strlcpy(remotehost, "?", sizeof(remotehost));
   2409 
   2410 #if HAVE_SETPROCTITLE
   2411 	snprintf(proctitle, sizeof(proctitle), "%s: connected", remotehost);
   2412 	setproctitle("%s", proctitle);
   2413 #endif /* HAVE_SETPROCTITLE */
   2414 	if (logging)
   2415 		syslog(LOG_INFO, "connection from %s to %s",
   2416 		    remotehost, hostname);
   2417 }
   2418 
   2419 /*
   2420  * Record logout in wtmp file and exit with supplied status.
   2421  */
   2422 void
   2423 dologout(int status)
   2424 {
   2425 	/*
   2426 	* Prevent reception of SIGURG from resulting in a resumption
   2427 	* back to the main program loop.
   2428 	*/
   2429 	transflag = 0;
   2430 	logout_utmp();
   2431 	if (logged_in) {
   2432 #ifdef KERBEROS
   2433 		if (!notickets && krbtkfile_env)
   2434 			unlink(krbtkfile_env);
   2435 #endif
   2436 	}
   2437 	/* beware of flushing buffers after a SIGPIPE */
   2438 	_exit(status);
   2439 }
   2440 
   2441 void
   2442 abor(void)
   2443 {
   2444 
   2445 	tmpline[0] = '\0';
   2446 	is_oob = 0;
   2447 	reply(426, "Transfer aborted. Data connection closed.");
   2448 	reply(226, "Abort successful");
   2449 	longjmp(urgcatch, 1);
   2450 }
   2451 
   2452 void
   2453 statxfer(void)
   2454 {
   2455 
   2456 	tmpline[0] = '\0';
   2457 	is_oob = 0;
   2458 	if (file_size != (off_t) -1)
   2459 		reply(213,
   2460 		    "Status: " LLF " of " LLF " byte%s transferred",
   2461 		    (LLT)byte_count, (LLT)file_size,
   2462 		    PLURAL(byte_count));
   2463 	else
   2464 		reply(213, "Status: " LLF " byte%s transferred",
   2465 		    (LLT)byte_count, PLURAL(byte_count));
   2466 }
   2467 
   2468 static void
   2469 myoob(int signo)
   2470 {
   2471 	char *cp;
   2472 
   2473 	/* only process if transfer occurring */
   2474 	if (!transflag)
   2475 		return;
   2476 	cp = tmpline;
   2477 	if (getline(cp, sizeof(tmpline), stdin) == NULL) {
   2478 		reply(221, "You could at least say goodbye.");
   2479 		dologout(0);
   2480 	}
   2481 	is_oob = 1;
   2482 	ftp_handle_line(cp);
   2483 	is_oob = 0;
   2484 }
   2485 
   2486 static int
   2487 bind_pasv_addr(void)
   2488 {
   2489 	static int passiveport;
   2490 	int port, len;
   2491 
   2492 	len = pasv_addr.su_len;
   2493 	if (curclass.portmin == 0 && curclass.portmax == 0) {
   2494 		pasv_addr.su_port = 0;
   2495 		return (bind(pdata, (struct sockaddr *)&pasv_addr.si_su, len));
   2496 	}
   2497 
   2498 	if (passiveport == 0) {
   2499 		srand(getpid());
   2500 		passiveport = rand() % (curclass.portmax - curclass.portmin)
   2501 		    + curclass.portmin;
   2502 	}
   2503 
   2504 	port = passiveport;
   2505 	while (1) {
   2506 		port++;
   2507 		if (port > curclass.portmax)
   2508 			port = curclass.portmin;
   2509 		else if (port == passiveport) {
   2510 			errno = EAGAIN;
   2511 			return (-1);
   2512 		}
   2513 		pasv_addr.su_port = htons(port);
   2514 		if (bind(pdata, (struct sockaddr *)&pasv_addr.si_su, len) == 0)
   2515 			break;
   2516 		if (errno != EADDRINUSE)
   2517 			return (-1);
   2518 	}
   2519 	passiveport = port;
   2520 	return (0);
   2521 }
   2522 
   2523 /*
   2524  * Note: a response of 425 is not mentioned as a possible response to
   2525  *	the PASV command in RFC959. However, it has been blessed as
   2526  *	a legitimate response by Jon Postel in a telephone conversation
   2527  *	with Rick Adams on 25 Jan 89.
   2528  */
   2529 void
   2530 passive(void)
   2531 {
   2532 	int len;
   2533 	char *p, *a;
   2534 
   2535 	if (pdata >= 0)
   2536 		close(pdata);
   2537 	pdata = socket(AF_INET, SOCK_STREAM, 0);
   2538 	if (pdata < 0 || !logged_in) {
   2539 		perror_reply(425, "Can't open passive connection");
   2540 		return;
   2541 	}
   2542 	pasv_addr = ctrl_addr;
   2543 
   2544 	if (bind_pasv_addr() < 0)
   2545 		goto pasv_error;
   2546 	len = pasv_addr.su_len;
   2547 	if (getsockname(pdata, (struct sockaddr *) &pasv_addr.si_su, &len) < 0)
   2548 		goto pasv_error;
   2549 	pasv_addr.su_len = len;
   2550 	if (listen(pdata, 1) < 0)
   2551 		goto pasv_error;
   2552 	if (curclass.advertise.su_len != 0)
   2553 		a = (char *) &curclass.advertise.su_addr;
   2554 	else
   2555 		a = (char *) &pasv_addr.su_addr;
   2556 	p = (char *) &pasv_addr.su_port;
   2557 
   2558 #define UC(b) (((int) b) & 0xff)
   2559 
   2560 	reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
   2561 		UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
   2562 	return;
   2563 
   2564  pasv_error:
   2565 	(void) close(pdata);
   2566 	pdata = -1;
   2567 	perror_reply(425, "Can't open passive connection");
   2568 	return;
   2569 }
   2570 
   2571 /*
   2572  * convert protocol identifier to/from AF
   2573  */
   2574 int
   2575 lpsvproto2af(int proto)
   2576 {
   2577 
   2578 	switch (proto) {
   2579 	case 4:
   2580 		return AF_INET;
   2581 #ifdef INET6
   2582 	case 6:
   2583 		return AF_INET6;
   2584 #endif
   2585 	default:
   2586 		return -1;
   2587 	}
   2588 }
   2589 
   2590 int
   2591 af2lpsvproto(int af)
   2592 {
   2593 
   2594 	switch (af) {
   2595 	case AF_INET:
   2596 		return 4;
   2597 #ifdef INET6
   2598 	case AF_INET6:
   2599 		return 6;
   2600 #endif
   2601 	default:
   2602 		return -1;
   2603 	}
   2604 }
   2605 
   2606 int
   2607 epsvproto2af(int proto)
   2608 {
   2609 
   2610 	switch (proto) {
   2611 	case 1:
   2612 		return AF_INET;
   2613 #ifdef INET6
   2614 	case 2:
   2615 		return AF_INET6;
   2616 #endif
   2617 	default:
   2618 		return -1;
   2619 	}
   2620 }
   2621 
   2622 int
   2623 af2epsvproto(int af)
   2624 {
   2625 
   2626 	switch (af) {
   2627 	case AF_INET:
   2628 		return 1;
   2629 #ifdef INET6
   2630 	case AF_INET6:
   2631 		return 2;
   2632 #endif
   2633 	default:
   2634 		return -1;
   2635 	}
   2636 }
   2637 
   2638 /*
   2639  * 228 Entering Long Passive Mode (af, hal, h1, h2, h3,..., pal, p1, p2...)
   2640  * 229 Entering Extended Passive Mode (|||port|)
   2641  */
   2642 void
   2643 long_passive(char *cmd, int pf)
   2644 {
   2645 	int len;
   2646 	char *p, *a;
   2647 
   2648 	if (!logged_in) {
   2649 		syslog(LOG_NOTICE, "long passive but not logged in");
   2650 		reply(503, "Login with USER first.");
   2651 		return;
   2652 	}
   2653 
   2654 	if (pf != PF_UNSPEC && ctrl_addr.su_family != pf) {
   2655 		/*
   2656 		 * XXX: only EPRT/EPSV ready clients will understand this
   2657 		 */
   2658 		if (strcmp(cmd, "EPSV") != 0)
   2659 			reply(501, "Network protocol mismatch"); /*XXX*/
   2660 		else
   2661 			epsv_protounsupp("Network protocol mismatch");
   2662 
   2663 		return;
   2664 	}
   2665 
   2666 	if (pdata >= 0)
   2667 		close(pdata);
   2668 	pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
   2669 	if (pdata < 0) {
   2670 		perror_reply(425, "Can't open passive connection");
   2671 		return;
   2672 	}
   2673 	pasv_addr = ctrl_addr;
   2674 	if (bind_pasv_addr() < 0)
   2675 		goto pasv_error;
   2676 	len = pasv_addr.su_len;
   2677 	if (getsockname(pdata, (struct sockaddr *) &pasv_addr.si_su, &len) < 0)
   2678 		goto pasv_error;
   2679 	pasv_addr.su_len = len;
   2680 	if (listen(pdata, 1) < 0)
   2681 		goto pasv_error;
   2682 	p = (char *) &pasv_addr.su_port;
   2683 
   2684 #define UC(b) (((int) b) & 0xff)
   2685 
   2686 	if (strcmp(cmd, "LPSV") == 0) {
   2687 		struct sockinet *advert;
   2688 
   2689 		if (curclass.advertise.su_len != 0)
   2690 			advert = &curclass.advertise;
   2691 		else
   2692 			advert = &pasv_addr;
   2693 		switch (advert->su_family) {
   2694 		case AF_INET:
   2695 			a = (char *) &advert->su_addr;
   2696 			reply(228,
   2697     "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)",
   2698 				4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
   2699 				2, UC(p[0]), UC(p[1]));
   2700 			return;
   2701 #ifdef INET6
   2702 		case AF_INET6:
   2703 			a = (char *) &advert->su_6addr;
   2704 			reply(228,
   2705     "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)",
   2706 				6, 16,
   2707 				UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
   2708 				UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]),
   2709 				UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]),
   2710 				UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]),
   2711 				2, UC(p[0]), UC(p[1]));
   2712 			return;
   2713 #endif
   2714 		}
   2715 #undef UC
   2716 	} else if (strcmp(cmd, "EPSV") == 0) {
   2717 		switch (pasv_addr.su_family) {
   2718 		case AF_INET:
   2719 #ifdef INET6
   2720 		case AF_INET6:
   2721 #endif
   2722 			reply(229, "Entering Extended Passive Mode (|||%d|)",
   2723 			    ntohs(pasv_addr.su_port));
   2724 			return;
   2725 		}
   2726 	} else {
   2727 		/* more proper error code? */
   2728 	}
   2729 
   2730  pasv_error:
   2731 	(void) close(pdata);
   2732 	pdata = -1;
   2733 	perror_reply(425, "Can't open passive connection");
   2734 	return;
   2735 }
   2736 
   2737 int
   2738 extended_port(const char *arg)
   2739 {
   2740 	char *tmp = NULL;
   2741 	char *result[3];
   2742 	char *p, *q;
   2743 	char delim;
   2744 	struct addrinfo hints;
   2745 	struct addrinfo *res = NULL;
   2746 	int i;
   2747 	unsigned long proto;
   2748 
   2749 	tmp = xstrdup(arg);
   2750 	p = tmp;
   2751 	delim = p[0];
   2752 	p++;
   2753 	memset(result, 0, sizeof(result));
   2754 	for (i = 0; i < 3; i++) {
   2755 		q = strchr(p, delim);
   2756 		if (!q || *q != delim)
   2757 			goto parsefail;
   2758 		*q++ = '\0';
   2759 		result[i] = p;
   2760 		p = q;
   2761 	}
   2762 
   2763 			/* some more sanity checks */
   2764 	errno = 0;
   2765 	p = NULL;
   2766 	(void)strtoul(result[2], &p, 10);
   2767 	if (errno || !*result[2] || *p)
   2768 		goto parsefail;
   2769 	errno = 0;
   2770 	p = NULL;
   2771 	proto = strtoul(result[0], &p, 10);
   2772 	if (errno || !*result[0] || *p)
   2773 		goto protounsupp;
   2774 
   2775 	memset(&hints, 0, sizeof(hints));
   2776 	hints.ai_family = epsvproto2af((int)proto);
   2777 	if (hints.ai_family < 0)
   2778 		goto protounsupp;
   2779 	hints.ai_socktype = SOCK_STREAM;
   2780 	hints.ai_flags = AI_NUMERICHOST;
   2781 	if (getaddrinfo(result[1], result[2], &hints, &res))
   2782 		goto parsefail;
   2783 	if (res->ai_next)
   2784 		goto parsefail;
   2785 	if (sizeof(data_dest) < res->ai_addrlen)
   2786 		goto parsefail;
   2787 	memcpy(&data_dest.si_su, res->ai_addr, res->ai_addrlen);
   2788 	data_dest.su_len = res->ai_addrlen;
   2789 #ifdef INET6
   2790 	if (his_addr.su_family == AF_INET6 &&
   2791 	    data_dest.su_family == AF_INET6) {
   2792 			/* XXX: more sanity checks! */
   2793 		data_dest.su_scope_id = his_addr.su_scope_id;
   2794 	}
   2795 #endif
   2796 
   2797 	if (tmp != NULL)
   2798 		free(tmp);
   2799 	if (res)
   2800 		freeaddrinfo(res);
   2801 	return 0;
   2802 
   2803  parsefail:
   2804 	reply(500, "Invalid argument, rejected.");
   2805 	usedefault = 1;
   2806 	if (tmp != NULL)
   2807 		free(tmp);
   2808 	if (res)
   2809 		freeaddrinfo(res);
   2810 	return -1;
   2811 
   2812  protounsupp:
   2813 	epsv_protounsupp("Protocol not supported");
   2814 	usedefault = 1;
   2815 	if (tmp != NULL)
   2816 		free(tmp);
   2817 	if (res)
   2818 		freeaddrinfo(res);
   2819 	return -1;
   2820 }
   2821 
   2822 /*
   2823  * 522 Protocol not supported (proto,...)
   2824  * as we assume address family for control and data connections are the same,
   2825  * we do not return the list of address families we support - instead, we
   2826  * return the address family of the control connection.
   2827  */
   2828 void
   2829 epsv_protounsupp(const char *message)
   2830 {
   2831 	int proto;
   2832 
   2833 	proto = af2epsvproto(ctrl_addr.su_family);
   2834 	if (proto < 0)
   2835 		reply(501, "%s", message);	/* XXX */
   2836 	else
   2837 		reply(522, "%s, use (%d)", message, proto);
   2838 }
   2839 
   2840 /*
   2841  * Generate unique name for file with basename "local".
   2842  * The file named "local" is already known to exist.
   2843  * Generates failure reply on error.
   2844  *
   2845  * XXX:	this function should under go changes similar to
   2846  *	the mktemp(3)/mkstemp(3) changes.
   2847  */
   2848 static char *
   2849 gunique(const char *local)
   2850 {
   2851 	static char new[MAXPATHLEN];
   2852 	struct stat st;
   2853 	char *cp;
   2854 	int count;
   2855 
   2856 	cp = strrchr(local, '/');
   2857 	if (cp)
   2858 		*cp = '\0';
   2859 	if (stat(cp ? local : ".", &st) < 0) {
   2860 		perror_reply(553, cp ? local : ".");
   2861 		return (NULL);
   2862 	}
   2863 	if (cp)
   2864 		*cp = '/';
   2865 	for (count = 1; count < 100; count++) {
   2866 		(void)snprintf(new, sizeof(new) - 1, "%s.%d", local, count);
   2867 		if (stat(new, &st) < 0)
   2868 			return (new);
   2869 	}
   2870 	reply(452, "Unique file name cannot be created.");
   2871 	return (NULL);
   2872 }
   2873 
   2874 /*
   2875  * Format and send reply containing system error number.
   2876  */
   2877 void
   2878 perror_reply(int code, const char *string)
   2879 {
   2880 	int save_errno;
   2881 
   2882 	save_errno = errno;
   2883 	reply(code, "%s: %s.", string, strerror(errno));
   2884 	errno = save_errno;
   2885 }
   2886 
   2887 static char *onefile[] = {
   2888 	"",
   2889 	0
   2890 };
   2891 
   2892 void
   2893 send_file_list(const char *whichf)
   2894 {
   2895 	struct stat st;
   2896 	DIR *dirp = NULL;
   2897 	struct dirent *dir;
   2898 	FILE *dout = NULL;
   2899 	char **dirlist, *dirname, *notglob, *p;
   2900 	int simple = 0;
   2901 	int freeglob = 0;
   2902 	glob_t gl;
   2903 
   2904 #ifdef __GNUC__
   2905 	(void) &dout;
   2906 	(void) &dirlist;
   2907 	(void) &simple;
   2908 	(void) &freeglob;
   2909 #endif
   2910 
   2911 	p = NULL;
   2912 	if (strpbrk(whichf, "~{[*?") != NULL) {
   2913 		int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE|GLOB_LIMIT;
   2914 
   2915 		memset(&gl, 0, sizeof(gl));
   2916 		freeglob = 1;
   2917 		if (glob(whichf, flags, 0, &gl)) {
   2918 			reply(550, "not found");
   2919 			goto out;
   2920 		} else if (gl.gl_pathc == 0) {
   2921 			errno = ENOENT;
   2922 			perror_reply(550, whichf);
   2923 			goto out;
   2924 		}
   2925 		dirlist = gl.gl_pathv;
   2926 	} else {
   2927 		notglob = xstrdup(whichf);
   2928 		onefile[0] = notglob;
   2929 		dirlist = onefile;
   2930 		simple = 1;
   2931 	}
   2932 					/* XXX: } for vi sm */
   2933 
   2934 	if (setjmp(urgcatch)) {
   2935 		transflag = 0;
   2936 		goto out;
   2937 	}
   2938 	while ((dirname = *dirlist++) != NULL) {
   2939 		int trailingslash = 0;
   2940 
   2941 		if (stat(dirname, &st) < 0) {
   2942 			/*
   2943 			 * If user typed "ls -l", etc, and the client
   2944 			 * used NLST, do what the user meant.
   2945 			 */
   2946 			/* XXX: nuke this support? */
   2947 			if (dirname[0] == '-' && *dirlist == NULL &&
   2948 			    transflag == 0) {
   2949 				char *argv[] = { INTERNAL_LS, "", NULL };
   2950 
   2951 				argv[1] = dirname;
   2952 				retrieve(argv, dirname);
   2953 				goto out;
   2954 			}
   2955 			perror_reply(550, whichf);
   2956 			goto cleanup_send_file_list;
   2957 		}
   2958 
   2959 		if (S_ISREG(st.st_mode)) {
   2960 			/*
   2961 			 * XXXRFC:
   2962 			 *	should we follow RFC959 and not work
   2963 			 *	for non directories?
   2964 			 */
   2965 			if (dout == NULL) {
   2966 				dout = dataconn("file list", (off_t)-1, "w");
   2967 				if (dout == NULL)
   2968 					goto out;
   2969 				transflag++;
   2970 			}
   2971 			cprintf(dout, "%s%s\n", dirname,
   2972 			    type == TYPE_A ? "\r" : "");
   2973 			continue;
   2974 		} else if (!S_ISDIR(st.st_mode))
   2975 			continue;
   2976 
   2977 		if (dirname[strlen(dirname) - 1] == '/')
   2978 			trailingslash++;
   2979 
   2980 		if ((dirp = opendir(dirname)) == NULL)
   2981 			continue;
   2982 
   2983 		while ((dir = readdir(dirp)) != NULL) {
   2984 			char nbuf[MAXPATHLEN];
   2985 
   2986 			if (ISDOTDIR(dir->d_name) || ISDOTDOTDIR(dir->d_name))
   2987 				continue;
   2988 
   2989 			(void)snprintf(nbuf, sizeof(nbuf), "%s%s%s", dirname,
   2990 			    trailingslash ? "" : "/", dir->d_name);
   2991 
   2992 			/*
   2993 			 * We have to do a stat to ensure it's
   2994 			 * not a directory or special file.
   2995 			 */
   2996 			/*
   2997 			 * XXXRFC:
   2998 			 *	should we follow RFC959 and filter out
   2999 			 *	non files ?   lukem - NO!, or not until
   3000 			 *	our ftp client uses MLS{T,D} for completion.
   3001 			 */
   3002 			if (simple || (stat(nbuf, &st) == 0 &&
   3003 			    S_ISREG(st.st_mode))) {
   3004 				if (dout == NULL) {
   3005 					dout = dataconn("file list", (off_t)-1,
   3006 						"w");
   3007 					if (dout == NULL)
   3008 						goto out;
   3009 					transflag++;
   3010 				}
   3011 				p = nbuf;
   3012 				if (nbuf[0] == '.' && nbuf[1] == '/')
   3013 					p = &nbuf[2];
   3014 				cprintf(dout, "%s%s\n", p,
   3015 				    type == TYPE_A ? "\r" : "");
   3016 			}
   3017 		}
   3018 		(void) closedir(dirp);
   3019 	}
   3020 
   3021 	if (dout == NULL)
   3022 		reply(550, "No files found.");
   3023 	else if (ferror(dout) != 0)
   3024 		perror_reply(550, "Data connection");
   3025 	else
   3026 		reply(226, "Transfer complete.");
   3027 
   3028  cleanup_send_file_list:
   3029 	transflag = 0;
   3030 	closedataconn(dout);
   3031  out:
   3032 	total_xfers++;
   3033 	total_xfers_out++;
   3034 	if (notglob)
   3035 		free(notglob);
   3036 	if (freeglob)
   3037 		globfree(&gl);
   3038 }
   3039 
   3040 char *
   3041 conffilename(const char *s)
   3042 {
   3043 	static char filename[MAXPATHLEN];
   3044 
   3045 	if (*s == '/')
   3046 		strlcpy(filename, s, sizeof(filename));
   3047 	else
   3048 		(void)snprintf(filename, sizeof(filename), "%s/%s", confdir ,s);
   3049 	return (filename);
   3050 }
   3051 
   3052 /*
   3053  * logxfer --
   3054  *	if logging > 1, then based on the arguments, syslog a message:
   3055  *	 if bytes != -1		"<command> <file1> = <bytes> bytes"
   3056  *	 else if file2 != NULL	"<command> <file1> <file2>"
   3057  *	 else			"<command> <file1>"
   3058  *	if elapsed != NULL, append "in xxx.yyy seconds"
   3059  *	if error != NULL, append ": " + error
   3060  *
   3061  *	if doxferlog != 0, bytes != -1, and command is "get", "put",
   3062  *	or "append", syslog a wu-ftpd style xferlog entry
   3063  */
   3064 void
   3065 logxfer(const char *command, off_t bytes, const char *file1, const char *file2,
   3066     const struct timeval *elapsed, const char *error)
   3067 {
   3068 	char		 buf[MAXPATHLEN * 2 + 100], realfile[MAXPATHLEN];
   3069 	const char	*r1, *r2;
   3070 	char		 direction;
   3071 	size_t		 len;
   3072 	time_t		 now;
   3073 
   3074 	if (logging <=1 && !doxferlog)
   3075 		return;
   3076 
   3077 	r1 = r2 = NULL;
   3078 	if ((r1 = realpath(file1, realfile)) == NULL)
   3079 		r1 = file1;
   3080 	if (file2 != NULL)
   3081 		if ((r2 = realpath(file2, realfile)) == NULL)
   3082 			r2 = file2;
   3083 
   3084 		/*
   3085 		 * syslog command
   3086 		 */
   3087 	if (logging > 1) {
   3088 		len = snprintf(buf, sizeof(buf), "%s %s", command, r1);
   3089 		if (bytes != (off_t)-1)
   3090 			len += snprintf(buf + len, sizeof(buf) - len,
   3091 			    " = " LLF " byte%s", (LLT) bytes, PLURAL(bytes));
   3092 		else if (r2 != NULL)
   3093 			len += snprintf(buf + len, sizeof(buf) - len,
   3094 			    " %s", r2);
   3095 		if (elapsed != NULL)
   3096 			len += snprintf(buf + len, sizeof(buf) - len,
   3097 			    " in %ld.%.03d seconds", elapsed->tv_sec,
   3098 			    (int)(elapsed->tv_usec / 1000));
   3099 		if (error != NULL)
   3100 			len += snprintf(buf + len, sizeof(buf) - len,
   3101 			    ": %s", error);
   3102 		syslog(LOG_INFO, "%s", buf);
   3103 	}
   3104 
   3105 
   3106 		/*
   3107 		 * syslog wu-ftpd style log entry, prefixed with "xferlog: "
   3108 		 */
   3109 	if (!doxferlog || bytes == -1)
   3110 		return;
   3111 
   3112 	if (strcmp(command, "get") == 0)
   3113 		direction = 'o';
   3114 	else if (strcmp(command, "put") == 0 || strcmp(command, "append") == 0)
   3115 		direction = 'i';
   3116 	else
   3117 		return;
   3118 
   3119 	time(&now);
   3120 	syslog(LOG_INFO,
   3121 	    "xferlog%s: %.24s %ld %s " LLF " %s %c %s %c %c %s FTP 0 * %c",
   3122 
   3123 /*
   3124  * XXX: wu-ftpd puts (send) or (recv) in the syslog message, and removes
   3125  *	the full date.  This may be problematic for accurate log parsing,
   3126  *	given that syslog messages don't contain the full date.
   3127  */
   3128 #if 1		/* lukem's method; easier to convert to actual xferlog file */
   3129 	    "",
   3130 	    ctime(&now),
   3131 #else		/* wu-ftpd's syslog method, with an extra unneeded space */
   3132 	    (direction == 'i') ? " (recv)" : " (send)",
   3133 	    "",
   3134 #endif
   3135 	    elapsed == NULL ? 0 : elapsed->tv_sec + (elapsed->tv_usec > 0),
   3136 	    remotehost,
   3137 	    (LLT) bytes,
   3138 	    r1,
   3139 	    type == TYPE_A ? 'a' : 'b',
   3140 	    "_",		/* XXX: take conversions into account? */
   3141 	    direction,
   3142 
   3143 	    curclass.type == CLASS_GUEST ?  'a' :
   3144 	    curclass.type == CLASS_CHROOT ? 'g' :
   3145 	    curclass.type == CLASS_REAL ?   'r' : '?',
   3146 
   3147 	    curclass.type == CLASS_GUEST ? pw->pw_passwd : pw->pw_name,
   3148 	    error != NULL ? 'i' : 'c'
   3149 	    );
   3150 }
   3151 
   3152 /*
   3153  * Log the resource usage.
   3154  *
   3155  * XXX: more resource usage to logging?
   3156  */
   3157 void
   3158 logrusage(const struct rusage *rusage_before,
   3159     const struct rusage *rusage_after)
   3160 {
   3161 	struct timeval usrtime, systime;
   3162 
   3163 	if (logging <= 1)
   3164 		return;
   3165 
   3166 	timersub(&rusage_after->ru_utime, &rusage_before->ru_utime, &usrtime);
   3167 	timersub(&rusage_after->ru_stime, &rusage_before->ru_stime, &systime);
   3168 	syslog(LOG_INFO, "%ld.%.03du %ld.%.03ds %ld+%ldio %ldpf+%ldw",
   3169 	    usrtime.tv_sec, (int)(usrtime.tv_usec / 1000),
   3170 	    systime.tv_sec, (int)(systime.tv_usec / 1000),
   3171 	    rusage_after->ru_inblock - rusage_before->ru_inblock,
   3172 	    rusage_after->ru_oublock - rusage_before->ru_oublock,
   3173 	    rusage_after->ru_majflt - rusage_before->ru_majflt,
   3174 	    rusage_after->ru_nswap - rusage_before->ru_nswap);
   3175 }
   3176 
   3177 /*
   3178  * Determine if `password' is valid for user given in `pw'.
   3179  * Returns 2 if password expired, 1 if otherwise failed, 0 if ok
   3180  */
   3181 int
   3182 checkpassword(const struct passwd *pwent, const char *password)
   3183 {
   3184 	char	*orig, *new;
   3185 	time_t	 expire;
   3186 
   3187 	expire = 0;
   3188 	if (pwent == NULL)
   3189 		return 1;
   3190 
   3191 	orig = pwent->pw_passwd;	/* save existing password */
   3192 	expire = pwent->pw_expire;
   3193 
   3194 	if (orig[0] == '\0')		/* don't allow empty passwords */
   3195 		return 1;
   3196 
   3197 	new = crypt(password, orig);	/* encrypt given password */
   3198 	if (strcmp(new, orig) != 0)	/* compare */
   3199 		return 1;
   3200 
   3201 	if (expire && time(NULL) >= expire)
   3202 		return 2;		/* check if expired */
   3203 
   3204 	return 0;			/* OK! */
   3205 }
   3206 
   3207 char *
   3208 xstrdup(const char *s)
   3209 {
   3210 	char *new = strdup(s);
   3211 
   3212 	if (new == NULL)
   3213 		fatal("Local resource failure: malloc");
   3214 		/* NOTREACHED */
   3215 	return (new);
   3216 }
   3217 
   3218 /*
   3219  * As per fprintf(), but increment total_bytes and total_bytes_out,
   3220  * by the appropriate amount.
   3221  */
   3222 void
   3223 cprintf(FILE *fd, const char *fmt, ...)
   3224 {
   3225 	off_t b;
   3226 	va_list ap;
   3227 
   3228 	va_start(ap, fmt);
   3229 	b = vfprintf(fd, fmt, ap);
   3230 	va_end(ap);
   3231 	total_bytes += b;
   3232 	total_bytes_out += b;
   3233 }
   3234