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