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