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