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