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