Home | History | Annotate | Line # | Download | only in ftpd
ftpd.c revision 1.6
      1 /*
      2  * Copyright (c) 1985, 1988, 1990 Regents of the University of California.
      3  * All rights reserved.
      4  *
      5  * Redistribution and use in source and binary forms, with or without
      6  * modification, are permitted provided that the following conditions
      7  * are met:
      8  * 1. Redistributions of source code must retain the above copyright
      9  *    notice, this list of conditions and the following disclaimer.
     10  * 2. Redistributions in binary form must reproduce the above copyright
     11  *    notice, this list of conditions and the following disclaimer in the
     12  *    documentation and/or other materials provided with the distribution.
     13  * 3. All advertising materials mentioning features or use of this software
     14  *    must display the following acknowledgement:
     15  *	This product includes software developed by the University of
     16  *	California, Berkeley and its contributors.
     17  * 4. Neither the name of the University nor the names of its contributors
     18  *    may be used to endorse or promote products derived from this software
     19  *    without specific prior written permission.
     20  *
     21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     31  * SUCH DAMAGE.
     32  */
     33 
     34 #ifndef lint
     35 char copyright[] =
     36 "@(#) Copyright (c) 1985, 1988, 1990 Regents of the University of California.\n\
     37  All rights reserved.\n";
     38 #endif /* not lint */
     39 
     40 #ifndef lint
     41 /*static char sccsid[] = "from: @(#)ftpd.c	5.40 (Berkeley) 7/2/91";*/
     42 static char rcsid[] = "$Id: ftpd.c,v 1.6 1994/04/14 03:15:41 cgd Exp $";
     43 #endif /* not lint */
     44 
     45 /*
     46  * FTP server.
     47  */
     48 #include <sys/param.h>
     49 #include <sys/stat.h>
     50 #include <sys/ioctl.h>
     51 #include <sys/socket.h>
     52 #include <sys/wait.h>
     53 
     54 #include <netinet/in.h>
     55 #include <netinet/in_systm.h>
     56 #include <netinet/ip.h>
     57 
     58 #define	FTP_NAMES
     59 #include <arpa/ftp.h>
     60 #include <arpa/inet.h>
     61 #include <arpa/telnet.h>
     62 
     63 #include <signal.h>
     64 #include <dirent.h>
     65 #include <fcntl.h>
     66 #include <time.h>
     67 #include <pwd.h>
     68 #include <setjmp.h>
     69 #include <netdb.h>
     70 #include <errno.h>
     71 #include <syslog.h>
     72 #include <varargs.h>
     73 #include <unistd.h>
     74 #include <stdio.h>
     75 #include <ctype.h>
     76 #include <stdlib.h>
     77 #include <string.h>
     78 #include "pathnames.h"
     79 
     80 /*
     81  * File containing login names
     82  * NOT to be used on this machine.
     83  * Commonly used to disallow uucp.
     84  */
     85 extern	int errno;
     86 extern	char *crypt();
     87 extern	char version[];
     88 extern	char *home;		/* pointer to home directory for glob */
     89 extern	FILE *ftpd_popen(), *fopen(), *freopen();
     90 extern	int  ftpd_pclose(), fclose();
     91 extern	char *getline();
     92 extern	char cbuf[];
     93 extern	off_t restart_point;
     94 
     95 struct	sockaddr_in ctrl_addr;
     96 struct	sockaddr_in data_source;
     97 struct	sockaddr_in data_dest;
     98 struct	sockaddr_in his_addr;
     99 struct	sockaddr_in pasv_addr;
    100 
    101 int	data;
    102 jmp_buf	errcatch, urgcatch;
    103 int	logged_in;
    104 struct	passwd *pw;
    105 int	debug;
    106 int	timeout = 900;    /* timeout after 15 minutes of inactivity */
    107 int	maxtimeout = 7200;/* don't allow idle time to be set beyond 2 hours */
    108 int	logging;
    109 int	guest;
    110 int	dochroot;
    111 int	type;
    112 int	form;
    113 int	stru;			/* avoid C keyword */
    114 int	mode;
    115 int	usedefault = 1;		/* for data transfers */
    116 int	pdata = -1;		/* for passive mode */
    117 int	transflag;
    118 off_t	file_size;
    119 off_t	byte_count;
    120 #if !defined(CMASK) || CMASK == 0
    121 #undef CMASK
    122 #define CMASK 027
    123 #endif
    124 int	defumask = CMASK;		/* default umask value */
    125 char	tmpline[7];
    126 char	hostname[MAXHOSTNAMELEN];
    127 char	remotehost[MAXHOSTNAMELEN];
    128 
    129 #if defined(KERBEROS)
    130 int notickets = 1;
    131 char *krbtkfile_env = NULL;
    132 #endif
    133 
    134 /*
    135  * Timeout intervals for retrying connections
    136  * to hosts that don't accept PORT cmds.  This
    137  * is a kludge, but given the problems with TCP...
    138  */
    139 #define	SWAITMAX	90	/* wait at most 90 seconds */
    140 #define	SWAITINT	5	/* interval between retries */
    141 
    142 int	swaitmax = SWAITMAX;
    143 int	swaitint = SWAITINT;
    144 
    145 void	lostconn(), myoob();
    146 FILE	*getdatasock(), *dataconn();
    147 
    148 #ifdef HASSETPROCTITLE
    149 char	proctitle[BUFSIZ];	/* initial part of title */
    150 #endif /* HASSETPROCTITLE */
    151 
    152 main(argc, argv, envp)
    153 	int argc;
    154 	char *argv[];
    155 	char **envp;
    156 {
    157 	int addrlen, on = 1, tos;
    158 	char *cp;
    159 
    160 	/*
    161 	 * LOG_NDELAY sets up the logging connection immediately,
    162 	 * necessary for anonymous ftp's that chroot and can't do it later.
    163 	 */
    164 	openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_DAEMON);
    165 	addrlen = sizeof (his_addr);
    166 	if (getpeername(0, (struct sockaddr *)&his_addr, &addrlen) < 0) {
    167 		syslog(LOG_ERR, "getpeername (%s): %m",argv[0]);
    168 		exit(1);
    169 	}
    170 	addrlen = sizeof (ctrl_addr);
    171 	if (getsockname(0, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) {
    172 		syslog(LOG_ERR, "getsockname (%s): %m",argv[0]);
    173 		exit(1);
    174 	}
    175 #ifdef IP_TOS
    176 	tos = IPTOS_LOWDELAY;
    177 	if (setsockopt(0, IPPROTO_IP, IP_TOS, (char *)&tos, sizeof(int)) < 0)
    178 		syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
    179 #endif
    180 	data_source.sin_port = htons(ntohs(ctrl_addr.sin_port) - 1);
    181 	debug = 0;
    182 
    183 	argc--, argv++;
    184 	while (argc > 0 && *argv[0] == '-') {
    185 		for (cp = &argv[0][1]; *cp; cp++) switch (*cp) {
    186 
    187 		case 'v':
    188 			debug = 1;
    189 			break;
    190 
    191 		case 'd':
    192 			debug = 1;
    193 			break;
    194 
    195 		case 'l':
    196 			logging = 1;
    197 			break;
    198 
    199 		case 't':
    200 			timeout = atoi(++cp);
    201 			if (maxtimeout < timeout)
    202 				maxtimeout = timeout;
    203 			goto nextopt;
    204 
    205 		case 'T':
    206 			maxtimeout = atoi(++cp);
    207 			if (timeout > maxtimeout)
    208 				timeout = maxtimeout;
    209 			goto nextopt;
    210 
    211 		case 'u':
    212 		    {
    213 			int val = 0;
    214 
    215 			while (*++cp && *cp >= '0' && *cp <= '9')
    216 				val = val*8 + *cp - '0';
    217 			if (*cp)
    218 				fprintf(stderr, "ftpd: Bad value for -u\n");
    219 			else
    220 				defumask = val;
    221 			goto nextopt;
    222 		    }
    223 
    224 		default:
    225 			fprintf(stderr, "ftpd: Unknown flag -%c ignored.\n",
    226 			     *cp);
    227 			break;
    228 		}
    229 nextopt:
    230 		argc--, argv++;
    231 	}
    232 	(void) freopen(_PATH_DEVNULL, "w", stderr);
    233 	(void) signal(SIGPIPE, lostconn);
    234 	(void) signal(SIGCHLD, SIG_IGN);
    235 	if ((int)signal(SIGURG, myoob) < 0)
    236 		syslog(LOG_ERR, "signal: %m");
    237 
    238 	/* Try to handle urgent data inline */
    239 #ifdef SO_OOBINLINE
    240 	if (setsockopt(0, SOL_SOCKET, SO_OOBINLINE, (char *)&on, sizeof(on)) < 0)
    241 		syslog(LOG_ERR, "setsockopt: %m");
    242 #endif
    243 
    244 #ifdef	F_SETOWN
    245 	if (fcntl(fileno(stdin), F_SETOWN, getpid()) == -1)
    246 		syslog(LOG_ERR, "fcntl F_SETOWN: %m");
    247 #endif
    248 	dolog(&his_addr);
    249 	/*
    250 	 * Set up default state
    251 	 */
    252 	data = -1;
    253 	type = TYPE_A;
    254 	form = FORM_N;
    255 	stru = STRU_F;
    256 	mode = MODE_S;
    257 	tmpline[0] = '\0';
    258 	(void) gethostname(hostname, sizeof (hostname));
    259 	reply(220, "%s FTP server (%s) ready.", hostname, version);
    260 	(void) setjmp(errcatch);
    261 	for (;;)
    262 		(void) yyparse();
    263 	/* NOTREACHED */
    264 }
    265 
    266 void
    267 lostconn()
    268 {
    269 	if (debug)
    270 		syslog(LOG_DEBUG, "lost connection");
    271 	dologout(-1);
    272 }
    273 
    274 static char ttyline[20];
    275 
    276 /*
    277  * Helper function for sgetpwnam().
    278  */
    279 char *
    280 sgetsave(s)
    281 	char *s;
    282 {
    283 	char *new = malloc((unsigned) strlen(s) + 1);
    284 
    285 	if (new == NULL) {
    286 		perror_reply(421, "Local resource failure: malloc");
    287 		dologout(1);
    288 		/* NOTREACHED */
    289 	}
    290 	(void) strcpy(new, s);
    291 	return (new);
    292 }
    293 
    294 /*
    295  * Save the result of a getpwnam.  Used for USER command, since
    296  * the data returned must not be clobbered by any other command
    297  * (e.g., globbing).
    298  */
    299 struct passwd *
    300 sgetpwnam(name)
    301 	char *name;
    302 {
    303 	static struct passwd save;
    304 	register struct passwd *p;
    305 	char *sgetsave();
    306 
    307 	if ((p = getpwnam(name)) == NULL)
    308 		return (p);
    309 	if (save.pw_name) {
    310 		free(save.pw_name);
    311 		free(save.pw_passwd);
    312 		free(save.pw_gecos);
    313 		free(save.pw_dir);
    314 		free(save.pw_shell);
    315 	}
    316 	save = *p;
    317 	save.pw_name = sgetsave(p->pw_name);
    318 	save.pw_passwd = sgetsave(p->pw_passwd);
    319 	save.pw_gecos = sgetsave(p->pw_gecos);
    320 	save.pw_dir = sgetsave(p->pw_dir);
    321 	save.pw_shell = sgetsave(p->pw_shell);
    322 	return (&save);
    323 }
    324 
    325 int login_attempts;		/* number of failed login attempts */
    326 int askpasswd;			/* had user command, ask for passwd */
    327 
    328 /*
    329  * USER command.
    330  * Sets global passwd pointer pw if named account exists and is acceptable;
    331  * sets askpasswd if a PASS command is expected.  If logged in previously,
    332  * need to reset state.  If name is "ftp" or "anonymous", the name is not in
    333  * _PATH_FTPUSERS, and ftp account exists, set guest and pw, then just return.
    334  * If account doesn't exist, ask for passwd anyway.  Otherwise, check user
    335  * requesting login privileges.  Disallow anyone who does not have a standard
    336  * shell as returned by getusershell().  Disallow anyone mentioned in the file
    337  * _PATH_FTPUSERS to allow people such as root and uucp to be avoided.
    338  */
    339 user(name)
    340 	char *name;
    341 {
    342 	register char *cp;
    343 	char *shell;
    344 	char *getusershell();
    345 
    346 	if (logged_in) {
    347 		if (guest) {
    348 			reply(530, "Can't change user from guest login.");
    349 			return;
    350 		} else if (dochroot) {
    351 			reply(530, "Can't change user from chroot user.");
    352 			return;
    353 		}
    354 		end_login();
    355 	}
    356 
    357 	guest = 0;
    358 	if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) {
    359 		if (checkuser(_PATH_FTPUSERS, "ftp") ||
    360 		    checkuser(_PATH_FTPUSERS, "anonymous"))
    361 			reply(530, "User %s access denied.", name);
    362 		else if ((pw = sgetpwnam("ftp")) != NULL) {
    363 			guest = 1;
    364 			askpasswd = 1;
    365 			reply(331, "Guest login ok, send ident as password.");
    366 		} else
    367 			reply(530, "User %s unknown.", name);
    368 		return;
    369 	}
    370 	if (pw = sgetpwnam(name)) {
    371 		if ((shell = pw->pw_shell) == NULL || *shell == 0)
    372 			shell = _PATH_BSHELL;
    373 		while ((cp = getusershell()) != NULL)
    374 			if (strcmp(cp, shell) == 0)
    375 				break;
    376 		endusershell();
    377 		if (cp == NULL || checkuser(_PATH_FTPUSERS, name)) {
    378 			reply(530, "User %s access denied.", name);
    379 			if (logging)
    380 				syslog(LOG_NOTICE,
    381 				    "FTP LOGIN REFUSED FROM %s, %s",
    382 				    remotehost, name);
    383 			pw = (struct passwd *) NULL;
    384 			return;
    385 		}
    386 	}
    387 	reply(331, "Password required for %s.", name);
    388 	askpasswd = 1;
    389 	/*
    390 	 * Delay before reading passwd after first failed
    391 	 * attempt to slow down passwd-guessing programs.
    392 	 */
    393 	if (login_attempts)
    394 		sleep((unsigned) login_attempts);
    395 }
    396 
    397 /*
    398  * Check if a user is in the file "fname"
    399  */
    400 checkuser(fname, name)
    401 	char *fname;
    402 	char *name;
    403 {
    404 	register FILE *fd;
    405 	register char *p;
    406 	char line[BUFSIZ];
    407 
    408 	if ((fd = fopen(fname, "r")) != NULL) {
    409 		while (fgets(line, sizeof(line), fd) != NULL)
    410 			if ((p = index(line, '\n')) != NULL) {
    411 				*p = '\0';
    412 				if (line[0] == '#')
    413 					continue;
    414 				if (strcmp(line, name) == 0)
    415 					return (1);
    416 			}
    417 		(void) fclose(fd);
    418 	}
    419 	return (0);
    420 }
    421 
    422 /*
    423  * Terminate login as previous user, if any, resetting state;
    424  * used when USER command is given or login fails.
    425  */
    426 end_login()
    427 {
    428 
    429 	(void) seteuid((uid_t)0);
    430 	if (logged_in)
    431 		logwtmp(ttyline, "", "");
    432 	pw = NULL;
    433 	logged_in = 0;
    434 	guest = 0;
    435 	dochroot = 0;
    436 }
    437 
    438 pass(passwd)
    439 	char *passwd;
    440 {
    441 	int rval;
    442 
    443 	if (logged_in || askpasswd == 0) {
    444 		reply(503, "Login with USER first.");
    445 		return;
    446 	}
    447 	askpasswd = 0;
    448 	if (!guest) {		/* "ftp" is only account allowed no password */
    449 		if (pw == NULL)
    450 			rval = 1;  /* failure below */
    451 		else
    452 #if defined(KERBEROS)
    453 			rval = klogin(pw, "", hostname, passwd);
    454 			if (rval == 1)
    455 #endif
    456 				/* the strcmp does not catch null passwords! */
    457 				if (pw == NULL || *pw->pw_passwd == '\0')
    458 					rval = 1;   /* failure */
    459 		else
    460 					rval = strcmp(crypt(passwd, (pw ? pw->pw_passwd : "xx")),
    461 						      pw->pw_passwd);
    462 
    463 		/*
    464 		 * If rval == 1, the user failed the authentication check
    465 		 * above.  If rval == 0, either Kerberos or local authentication
    466 		 * succeeded.
    467 		 */
    468 		if (rval) {
    469 			reply(530, "Login incorrect.");
    470 			pw = NULL;
    471 			if (login_attempts++ >= 5) {
    472 				syslog(LOG_NOTICE,
    473 				    "repeated login failures from %s",
    474 				    remotehost);
    475 				exit(0);
    476 			}
    477 			return;
    478 		}
    479 	}
    480 	login_attempts = 0;		/* this time successful */
    481 	(void) setegid((gid_t)pw->pw_gid);
    482 	(void) initgroups(pw->pw_name, pw->pw_gid);
    483 
    484 	/* open wtmp before chroot */
    485 	(void)sprintf(ttyline, "ftp%d", getpid());
    486 	logwtmp(ttyline, pw->pw_name, remotehost);
    487 	logged_in = 1;
    488 
    489 	dochroot = checkuser(_PATH_FTPCHROOT, pw->pw_name);
    490 	if (guest) {
    491 		/*
    492 		 * We MUST do a chdir() after the chroot. Otherwise
    493 		 * the old current directory will be accessible as "."
    494 		 * outside the new root!
    495 		 */
    496 		if (chroot(pw->pw_dir) < 0 || chdir("/") < 0) {
    497 			reply(550, "Can't set guest privileges.");
    498 			goto bad;
    499 		}
    500 	} else if (dochroot) {
    501 		if (chroot(pw->pw_dir) < 0 || chdir("/") < 0) {
    502 			reply(550, "Can't change root.");
    503 			goto bad;
    504 		}
    505 	} else if (chdir(pw->pw_dir) < 0) {
    506 		if (chdir("/") < 0) {
    507 			reply(530, "User %s: can't change directory to %s.",
    508 			    pw->pw_name, pw->pw_dir);
    509 			goto bad;
    510 		} else
    511 			lreply(230, "No directory! Logging in with home=/");
    512 	}
    513 	if (seteuid((uid_t)pw->pw_uid) < 0) {
    514 		reply(550, "Can't set uid.");
    515 		goto bad;
    516 	}
    517 	if (guest) {
    518 		reply(230, "Guest login ok, access restrictions apply.");
    519 #ifdef HASSETPROCTITLE
    520 		sprintf(proctitle, "%s: anonymous/%.*s", remotehost,
    521 		    sizeof(proctitle) - sizeof(remotehost) -
    522 		    sizeof(": anonymous/"), passwd);
    523 		setproctitle(proctitle);
    524 #endif /* HASSETPROCTITLE */
    525 		if (logging)
    526 			syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s, %s",
    527 			    remotehost, passwd);
    528 	} else {
    529 		reply(230, "User %s logged in.", pw->pw_name);
    530 #ifdef HASSETPROCTITLE
    531 		sprintf(proctitle, "%s: %s", remotehost, pw->pw_name);
    532 		setproctitle(proctitle);
    533 #endif /* HASSETPROCTITLE */
    534 		if (logging)
    535 			syslog(LOG_INFO, "FTP LOGIN FROM %s, %s",
    536 			    remotehost, pw->pw_name);
    537 	}
    538 	home = pw->pw_dir;		/* home dir for globbing */
    539 	(void) umask(defumask);
    540 	return;
    541 bad:
    542 	/* Forget all about it... */
    543 	end_login();
    544 }
    545 
    546 retrieve(cmd, name)
    547 	char *cmd, *name;
    548 {
    549 	FILE *fin, *dout;
    550 	struct stat st;
    551 	int (*closefunc)();
    552 
    553 	if (cmd == 0) {
    554 		fin = fopen(name, "r"), closefunc = fclose;
    555 		st.st_size = 0;
    556 	} else {
    557 		char line[BUFSIZ];
    558 
    559 		(void) sprintf(line, cmd, name), name = line;
    560 		fin = ftpd_popen(line, "r"), closefunc = ftpd_pclose;
    561 		st.st_size = -1;
    562 		st.st_blksize = BUFSIZ;
    563 	}
    564 	if (fin == NULL) {
    565 		if (errno != 0)
    566 			perror_reply(550, name);
    567 		return;
    568 	}
    569 	if (cmd == 0 &&
    570 	    (fstat(fileno(fin), &st) < 0 || (st.st_mode&S_IFMT) != S_IFREG)) {
    571 		reply(550, "%s: not a plain file.", name);
    572 		goto done;
    573 	}
    574 	if (restart_point) {
    575 		if (type == TYPE_A) {
    576 			register int i, n, c;
    577 
    578 			n = restart_point;
    579 			i = 0;
    580 			while (i++ < n) {
    581 				if ((c=getc(fin)) == EOF) {
    582 					perror_reply(550, name);
    583 					goto done;
    584 				}
    585 				if (c == '\n')
    586 					i++;
    587 			}
    588 		} else if (lseek(fileno(fin), restart_point, L_SET) < 0) {
    589 			perror_reply(550, name);
    590 			goto done;
    591 		}
    592 	}
    593 	dout = dataconn(name, st.st_size, "w");
    594 	if (dout == NULL)
    595 		goto done;
    596 	send_data(fin, dout, st.st_blksize);
    597 	(void) fclose(dout);
    598 	data = -1;
    599 	pdata = -1;
    600 done:
    601 	(*closefunc)(fin);
    602 }
    603 
    604 store(name, mode, unique)
    605 	char *name, *mode;
    606 	int unique;
    607 {
    608 	FILE *fout, *din;
    609 	struct stat st;
    610 	int (*closefunc)();
    611 	char *gunique();
    612 
    613 	if (unique && stat(name, &st) == 0 &&
    614 	    (name = gunique(name)) == NULL)
    615 		return;
    616 
    617 	if (restart_point)
    618 		mode = "r+w";
    619 	fout = fopen(name, mode);
    620 	closefunc = fclose;
    621 	if (fout == NULL) {
    622 		perror_reply(553, name);
    623 		return;
    624 	}
    625 	if (restart_point) {
    626 		if (type == TYPE_A) {
    627 			register int i, n, c;
    628 
    629 			n = restart_point;
    630 			i = 0;
    631 			while (i++ < n) {
    632 				if ((c=getc(fout)) == EOF) {
    633 					perror_reply(550, name);
    634 					goto done;
    635 				}
    636 				if (c == '\n')
    637 					i++;
    638 			}
    639 			/*
    640 			 * We must do this seek to "current" position
    641 			 * because we are changing from reading to
    642 			 * writing.
    643 			 */
    644 			if (fseek(fout, 0L, L_INCR) < 0) {
    645 				perror_reply(550, name);
    646 				goto done;
    647 			}
    648 		} else if (lseek(fileno(fout), restart_point, L_SET) < 0) {
    649 			perror_reply(550, name);
    650 			goto done;
    651 		}
    652 	}
    653 	din = dataconn(name, (off_t)-1, "r");
    654 	if (din == NULL)
    655 		goto done;
    656 	if (receive_data(din, fout) == 0) {
    657 		if (unique)
    658 			reply(226, "Transfer complete (unique file name:%s).",
    659 			    name);
    660 		else
    661 			reply(226, "Transfer complete.");
    662 	}
    663 	(void) fclose(din);
    664 	data = -1;
    665 	pdata = -1;
    666 done:
    667 	(*closefunc)(fout);
    668 }
    669 
    670 FILE *
    671 getdatasock(mode)
    672 	char *mode;
    673 {
    674 	int s, on = 1, tries;
    675 
    676 	if (data >= 0)
    677 		return (fdopen(data, mode));
    678 	(void) seteuid((uid_t)0);
    679 	s = socket(AF_INET, SOCK_STREAM, 0);
    680 	if (s < 0)
    681 		goto bad;
    682 	if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
    683 	    (char *) &on, sizeof (on)) < 0)
    684 		goto bad;
    685 	/* anchor socket to avoid multi-homing problems */
    686 	data_source.sin_family = AF_INET;
    687 	data_source.sin_addr = ctrl_addr.sin_addr;
    688 	for (tries = 1; ; tries++) {
    689 		if (bind(s, (struct sockaddr *)&data_source,
    690 		    sizeof (data_source)) >= 0)
    691 			break;
    692 		if (errno != EADDRINUSE || tries > 10)
    693 			goto bad;
    694 		sleep(tries);
    695 	}
    696 	(void) seteuid((uid_t)pw->pw_uid);
    697 #ifdef IP_TOS
    698 	on = IPTOS_THROUGHPUT;
    699 	if (setsockopt(s, IPPROTO_IP, IP_TOS, (char *)&on, sizeof(int)) < 0)
    700 		syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
    701 #endif
    702 	return (fdopen(s, mode));
    703 bad:
    704 	(void) seteuid((uid_t)pw->pw_uid);
    705 	(void) close(s);
    706 	return (NULL);
    707 }
    708 
    709 FILE *
    710 dataconn(name, size, mode)
    711 	char *name;
    712 	off_t size;
    713 	char *mode;
    714 {
    715 	char sizebuf[32];
    716 	FILE *file;
    717 	int retry = 0, tos;
    718 
    719 	file_size = size;
    720 	byte_count = 0;
    721 	if (size != (off_t) -1)
    722 		(void) sprintf (sizebuf, " (%ld bytes)", size);
    723 	else
    724 		(void) strcpy(sizebuf, "");
    725 	if (pdata >= 0) {
    726 		struct sockaddr_in from;
    727 		int s, fromlen = sizeof(from);
    728 
    729 		s = accept(pdata, (struct sockaddr *)&from, &fromlen);
    730 		if (s < 0) {
    731 			reply(425, "Can't open data connection.");
    732 			(void) close(pdata);
    733 			pdata = -1;
    734 			return(NULL);
    735 		}
    736 		(void) close(pdata);
    737 		pdata = s;
    738 #ifdef IP_TOS
    739 		tos = IPTOS_LOWDELAY;
    740 		(void) setsockopt(s, IPPROTO_IP, IP_TOS, (char *)&tos,
    741 		    sizeof(int));
    742 #endif
    743 		reply(150, "Opening %s mode data connection for %s%s.",
    744 		     type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
    745 		return(fdopen(pdata, mode));
    746 	}
    747 	if (data >= 0) {
    748 		reply(125, "Using existing data connection for %s%s.",
    749 		    name, sizebuf);
    750 		usedefault = 1;
    751 		return (fdopen(data, mode));
    752 	}
    753 	if (usedefault)
    754 		data_dest = his_addr;
    755 	usedefault = 1;
    756 	file = getdatasock(mode);
    757 	if (file == NULL) {
    758 		reply(425, "Can't create data socket (%s,%d): %s.",
    759 		    inet_ntoa(data_source.sin_addr),
    760 		    ntohs(data_source.sin_port), strerror(errno));
    761 		return (NULL);
    762 	}
    763 	data = fileno(file);
    764 	while (connect(data, (struct sockaddr *)&data_dest,
    765 	    sizeof (data_dest)) < 0) {
    766 		if (errno == EADDRINUSE && retry < swaitmax) {
    767 			sleep((unsigned) swaitint);
    768 			retry += swaitint;
    769 			continue;
    770 		}
    771 		perror_reply(425, "Can't build data connection");
    772 		(void) fclose(file);
    773 		data = -1;
    774 		return (NULL);
    775 	}
    776 	reply(150, "Opening %s mode data connection for %s%s.",
    777 	     type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
    778 	return (file);
    779 }
    780 
    781 /*
    782  * Tranfer the contents of "instr" to
    783  * "outstr" peer using the appropriate
    784  * encapsulation of the data subject
    785  * to Mode, Structure, and Type.
    786  *
    787  * NB: Form isn't handled.
    788  */
    789 send_data(instr, outstr, blksize)
    790 	FILE *instr, *outstr;
    791 	off_t blksize;
    792 {
    793 	register int c, cnt;
    794 	register char *buf;
    795 	int netfd, filefd;
    796 
    797 	transflag++;
    798 	if (setjmp(urgcatch)) {
    799 		transflag = 0;
    800 		return;
    801 	}
    802 	switch (type) {
    803 
    804 	case TYPE_A:
    805 		while ((c = getc(instr)) != EOF) {
    806 			byte_count++;
    807 			if (c == '\n') {
    808 				if (ferror(outstr))
    809 					goto data_err;
    810 				(void) putc('\r', outstr);
    811 			}
    812 			(void) putc(c, outstr);
    813 		}
    814 		fflush(outstr);
    815 		transflag = 0;
    816 		if (ferror(instr))
    817 			goto file_err;
    818 		if (ferror(outstr))
    819 			goto data_err;
    820 		reply(226, "Transfer complete.");
    821 		return;
    822 
    823 	case TYPE_I:
    824 	case TYPE_L:
    825 		if ((buf = malloc((u_int)blksize)) == NULL) {
    826 			transflag = 0;
    827 			perror_reply(451, "Local resource failure: malloc");
    828 			return;
    829 		}
    830 		netfd = fileno(outstr);
    831 		filefd = fileno(instr);
    832 		while ((cnt = read(filefd, buf, (u_int)blksize)) > 0 &&
    833 		    write(netfd, buf, cnt) == cnt)
    834 			byte_count += cnt;
    835 		transflag = 0;
    836 		(void)free(buf);
    837 		if (cnt != 0) {
    838 			if (cnt < 0)
    839 				goto file_err;
    840 			goto data_err;
    841 		}
    842 		reply(226, "Transfer complete.");
    843 		return;
    844 	default:
    845 		transflag = 0;
    846 		reply(550, "Unimplemented TYPE %d in send_data", type);
    847 		return;
    848 	}
    849 
    850 data_err:
    851 	transflag = 0;
    852 	perror_reply(426, "Data connection");
    853 	return;
    854 
    855 file_err:
    856 	transflag = 0;
    857 	perror_reply(551, "Error on input file");
    858 }
    859 
    860 /*
    861  * Transfer data from peer to
    862  * "outstr" using the appropriate
    863  * encapulation of the data subject
    864  * to Mode, Structure, and Type.
    865  *
    866  * N.B.: Form isn't handled.
    867  */
    868 receive_data(instr, outstr)
    869 	FILE *instr, *outstr;
    870 {
    871 	register int c;
    872 	int cnt, bare_lfs = 0;
    873 	char buf[BUFSIZ];
    874 
    875 	transflag++;
    876 	if (setjmp(urgcatch)) {
    877 		transflag = 0;
    878 		return (-1);
    879 	}
    880 	switch (type) {
    881 
    882 	case TYPE_I:
    883 	case TYPE_L:
    884 		while ((cnt = read(fileno(instr), buf, sizeof buf)) > 0) {
    885 			if (write(fileno(outstr), buf, cnt) != cnt)
    886 				goto file_err;
    887 			byte_count += cnt;
    888 		}
    889 		if (cnt < 0)
    890 			goto data_err;
    891 		transflag = 0;
    892 		return (0);
    893 
    894 	case TYPE_E:
    895 		reply(553, "TYPE E not implemented.");
    896 		transflag = 0;
    897 		return (-1);
    898 
    899 	case TYPE_A:
    900 		while ((c = getc(instr)) != EOF) {
    901 			byte_count++;
    902 			if (c == '\n')
    903 				bare_lfs++;
    904 			while (c == '\r') {
    905 				if (ferror(outstr))
    906 					goto data_err;
    907 				if ((c = getc(instr)) != '\n') {
    908 					(void) putc ('\r', outstr);
    909 					if (c == '\0' || c == EOF)
    910 						goto contin2;
    911 				}
    912 			}
    913 			(void) putc(c, outstr);
    914 	contin2:	;
    915 		}
    916 		fflush(outstr);
    917 		if (ferror(instr))
    918 			goto data_err;
    919 		if (ferror(outstr))
    920 			goto file_err;
    921 		transflag = 0;
    922 		if (bare_lfs) {
    923 			lreply(230, "WARNING! %d bare linefeeds received in ASCII mode", bare_lfs);
    924 			printf("   File may not have transferred correctly.\r\n");
    925 		}
    926 		return (0);
    927 	default:
    928 		reply(550, "Unimplemented TYPE %d in receive_data", type);
    929 		transflag = 0;
    930 		return (-1);
    931 	}
    932 
    933 data_err:
    934 	transflag = 0;
    935 	perror_reply(426, "Data Connection");
    936 	return (-1);
    937 
    938 file_err:
    939 	transflag = 0;
    940 	perror_reply(452, "Error writing file");
    941 	return (-1);
    942 }
    943 
    944 statfilecmd(filename)
    945 	char *filename;
    946 {
    947 	char line[BUFSIZ];
    948 	FILE *fin;
    949 	int c;
    950 
    951 	(void) sprintf(line, "/bin/ls -lgA %s", filename);
    952 	fin = ftpd_popen(line, "r");
    953 	lreply(211, "status of %s:", filename);
    954 	while ((c = getc(fin)) != EOF) {
    955 		if (c == '\n') {
    956 			if (ferror(stdout)){
    957 				perror_reply(421, "control connection");
    958 				(void) ftpd_pclose(fin);
    959 				dologout(1);
    960 				/* NOTREACHED */
    961 			}
    962 			if (ferror(fin)) {
    963 				perror_reply(551, filename);
    964 				(void) ftpd_pclose(fin);
    965 				return;
    966 			}
    967 			(void) putc('\r', stdout);
    968 		}
    969 		(void) putc(c, stdout);
    970 	}
    971 	(void) ftpd_pclose(fin);
    972 	reply(211, "End of Status");
    973 }
    974 
    975 statcmd()
    976 {
    977 	struct sockaddr_in *sin;
    978 	u_char *a, *p;
    979 
    980 	lreply(211, "%s FTP server status:", hostname, version);
    981 	printf("     %s\r\n", version);
    982 	printf("     Connected to %s", remotehost);
    983 	if (!isdigit(remotehost[0]))
    984 		printf(" (%s)", inet_ntoa(his_addr.sin_addr));
    985 	printf("\r\n");
    986 	if (logged_in) {
    987 		if (guest)
    988 			printf("     Logged in anonymously\r\n");
    989 		else
    990 			printf("     Logged in as %s\r\n", pw->pw_name);
    991 	} else if (askpasswd)
    992 		printf("     Waiting for password\r\n");
    993 	else
    994 		printf("     Waiting for user name\r\n");
    995 	printf("     TYPE: %s", typenames[type]);
    996 	if (type == TYPE_A || type == TYPE_E)
    997 		printf(", FORM: %s", formnames[form]);
    998 	if (type == TYPE_L)
    999 #if NBBY == 8
   1000 		printf(" %d", NBBY);
   1001 #else
   1002 		printf(" %d", bytesize);	/* need definition! */
   1003 #endif
   1004 	printf("; STRUcture: %s; transfer MODE: %s\r\n",
   1005 	    strunames[stru], modenames[mode]);
   1006 	if (data != -1)
   1007 		printf("     Data connection open\r\n");
   1008 	else if (pdata != -1) {
   1009 		printf("     in Passive mode");
   1010 		sin = &pasv_addr;
   1011 		goto printaddr;
   1012 	} else if (usedefault == 0) {
   1013 		printf("     PORT");
   1014 		sin = &data_dest;
   1015 printaddr:
   1016 		a = (u_char *) &sin->sin_addr;
   1017 		p = (u_char *) &sin->sin_port;
   1018 #define UC(b) (((int) b) & 0xff)
   1019 		printf(" (%d,%d,%d,%d,%d,%d)\r\n", UC(a[0]),
   1020 			UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
   1021 #undef UC
   1022 	} else
   1023 		printf("     No data connection\r\n");
   1024 	reply(211, "End of status");
   1025 }
   1026 
   1027 fatal(s)
   1028 	char *s;
   1029 {
   1030 	reply(451, "Error in server: %s\n", s);
   1031 	reply(221, "Closing connection due to server error.");
   1032 	dologout(0);
   1033 	/* NOTREACHED */
   1034 }
   1035 
   1036 /* VARARGS2 */
   1037 reply(n, fmt, p0, p1, p2, p3, p4, p5)
   1038 	int n;
   1039 	char *fmt;
   1040 {
   1041 	printf("%d ", n);
   1042 	printf(fmt, p0, p1, p2, p3, p4, p5);
   1043 	printf("\r\n");
   1044 	(void)fflush(stdout);
   1045 	if (debug) {
   1046 		syslog(LOG_DEBUG, "<--- %d ", n);
   1047 		syslog(LOG_DEBUG, fmt, p0, p1, p2, p3, p4, p5);
   1048 }
   1049 }
   1050 
   1051 /* VARARGS2 */
   1052 lreply(n, fmt, p0, p1, p2, p3, p4, p5)
   1053 	int n;
   1054 	char *fmt;
   1055 {
   1056 	printf("%d- ", n);
   1057 	printf(fmt, p0, p1, p2, p3, p4, p5);
   1058 	printf("\r\n");
   1059 	(void)fflush(stdout);
   1060 	if (debug) {
   1061 		syslog(LOG_DEBUG, "<--- %d- ", n);
   1062 		syslog(LOG_DEBUG, fmt, p0, p1, p2, p3, p4, p5);
   1063 	}
   1064 }
   1065 
   1066 ack(s)
   1067 	char *s;
   1068 {
   1069 	reply(250, "%s command successful.", s);
   1070 }
   1071 
   1072 nack(s)
   1073 	char *s;
   1074 {
   1075 	reply(502, "%s command not implemented.", s);
   1076 }
   1077 
   1078 /* ARGSUSED */
   1079 yyerror(s)
   1080 	char *s;
   1081 {
   1082 	char *cp;
   1083 
   1084 	if (cp = index(cbuf,'\n'))
   1085 		*cp = '\0';
   1086 	reply(500, "'%s': command not understood.", cbuf);
   1087 }
   1088 
   1089 delete(name)
   1090 	char *name;
   1091 {
   1092 	struct stat st;
   1093 
   1094 	if (stat(name, &st) < 0) {
   1095 		perror_reply(550, name);
   1096 		return;
   1097 	}
   1098 	if ((st.st_mode&S_IFMT) == S_IFDIR) {
   1099 		if (rmdir(name) < 0) {
   1100 			perror_reply(550, name);
   1101 			return;
   1102 		}
   1103 		goto done;
   1104 	}
   1105 	if (unlink(name) < 0) {
   1106 		perror_reply(550, name);
   1107 		return;
   1108 	}
   1109 done:
   1110 	ack("DELE");
   1111 }
   1112 
   1113 cwd(path)
   1114 	char *path;
   1115 {
   1116 	if (chdir(path) < 0)
   1117 		perror_reply(550, path);
   1118 	else
   1119 		ack("CWD");
   1120 }
   1121 
   1122 makedir(name)
   1123 	char *name;
   1124 {
   1125 	if (mkdir(name, 0777) < 0)
   1126 		perror_reply(550, name);
   1127 	else
   1128 		reply(257, "MKD command successful.");
   1129 }
   1130 
   1131 removedir(name)
   1132 	char *name;
   1133 {
   1134 	if (rmdir(name) < 0)
   1135 		perror_reply(550, name);
   1136 	else
   1137 		ack("RMD");
   1138 }
   1139 
   1140 pwd()
   1141 {
   1142 	char path[MAXPATHLEN + 1];
   1143 	extern char *getwd();
   1144 
   1145 	if (getwd(path) == (char *)NULL)
   1146 		reply(550, "%s.", path);
   1147 	else
   1148 		reply(257, "\"%s\" is current directory.", path);
   1149 }
   1150 
   1151 char *
   1152 renamefrom(name)
   1153 	char *name;
   1154 {
   1155 	struct stat st;
   1156 
   1157 	if (stat(name, &st) < 0) {
   1158 		perror_reply(550, name);
   1159 		return ((char *)0);
   1160 	}
   1161 	reply(350, "File exists, ready for destination name");
   1162 	return (name);
   1163 }
   1164 
   1165 renamecmd(from, to)
   1166 	char *from, *to;
   1167 {
   1168 	if (rename(from, to) < 0)
   1169 		perror_reply(550, "rename");
   1170 	else
   1171 		ack("RNTO");
   1172 }
   1173 
   1174 dolog(sin)
   1175 	struct sockaddr_in *sin;
   1176 {
   1177 	struct hostent *hp = gethostbyaddr((char *)&sin->sin_addr,
   1178 		sizeof (struct in_addr), AF_INET);
   1179 	time_t t, time();
   1180 	extern char *ctime();
   1181 
   1182 	if (hp)
   1183 		(void) strncpy(remotehost, hp->h_name, sizeof (remotehost));
   1184 	else
   1185 		(void) strncpy(remotehost, inet_ntoa(sin->sin_addr),
   1186 		    sizeof (remotehost));
   1187 #ifdef HASSETPROCTITLE
   1188 	sprintf(proctitle, "%s: connected", remotehost);
   1189 	setproctitle(proctitle);
   1190 #endif /* HASSETPROCTITLE */
   1191 
   1192 	if (logging) {
   1193 		t = time((time_t *) 0);
   1194 		syslog(LOG_INFO, "connection from %s at %s",
   1195 		    remotehost, ctime(&t));
   1196 	}
   1197 }
   1198 
   1199 /*
   1200  * Record logout in wtmp file
   1201  * and exit with supplied status.
   1202  */
   1203 dologout(status)
   1204 	int status;
   1205 {
   1206 	if (logged_in) {
   1207 		(void) seteuid((uid_t)0);
   1208 		logwtmp(ttyline, "", "");
   1209 #if defined(KERBEROS)
   1210 		if (!notickets && krbtkfile_env)
   1211 			unlink(krbtkfile_env);
   1212 #endif
   1213 	}
   1214 	/* beware of flushing buffers after a SIGPIPE */
   1215 	_exit(status);
   1216 }
   1217 
   1218 void
   1219 myoob()
   1220 {
   1221 	char *cp;
   1222 
   1223 	/* only process if transfer occurring */
   1224 	if (!transflag)
   1225 		return;
   1226 	cp = tmpline;
   1227 	if (getline(cp, 7, stdin) == NULL) {
   1228 		reply(221, "You could at least say goodbye.");
   1229 		dologout(0);
   1230 	}
   1231 	upper(cp);
   1232 	if (strcmp(cp, "ABOR\r\n") == 0) {
   1233 		tmpline[0] = '\0';
   1234 		reply(426, "Transfer aborted. Data connection closed.");
   1235 		reply(226, "Abort successful");
   1236 		longjmp(urgcatch, 1);
   1237 	}
   1238 	if (strcmp(cp, "STAT\r\n") == 0) {
   1239 		if (file_size != (off_t) -1)
   1240 			reply(213, "Status: %lu of %lu bytes transferred",
   1241 			    byte_count, file_size);
   1242 		else
   1243 			reply(213, "Status: %lu bytes transferred", byte_count);
   1244 	}
   1245 }
   1246 
   1247 /*
   1248  * Note: a response of 425 is not mentioned as a possible response to
   1249  * 	the PASV command in RFC959. However, it has been blessed as
   1250  * 	a legitimate response by Jon Postel in a telephone conversation
   1251  *	with Rick Adams on 25 Jan 89.
   1252  */
   1253 passive()
   1254 {
   1255 	int len;
   1256 	register char *p, *a;
   1257 
   1258 	pdata = socket(AF_INET, SOCK_STREAM, 0);
   1259 	if (pdata < 0) {
   1260 		perror_reply(425, "Can't open passive connection");
   1261 		return;
   1262 	}
   1263 	pasv_addr = ctrl_addr;
   1264 	pasv_addr.sin_port = 0;
   1265 	(void) seteuid((uid_t)0);
   1266 	if (bind(pdata, (struct sockaddr *)&pasv_addr, sizeof(pasv_addr)) < 0) {
   1267 		(void) seteuid((uid_t)pw->pw_uid);
   1268 		goto pasv_error;
   1269 	}
   1270 	(void) seteuid((uid_t)pw->pw_uid);
   1271 	len = sizeof(pasv_addr);
   1272 	if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
   1273 		goto pasv_error;
   1274 	if (listen(pdata, 1) < 0)
   1275 		goto pasv_error;
   1276 	a = (char *) &pasv_addr.sin_addr;
   1277 	p = (char *) &pasv_addr.sin_port;
   1278 
   1279 #define UC(b) (((int) b) & 0xff)
   1280 
   1281 	reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
   1282 		UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
   1283 	return;
   1284 
   1285 pasv_error:
   1286 	(void) close(pdata);
   1287 	pdata = -1;
   1288 	perror_reply(425, "Can't open passive connection");
   1289 	return;
   1290 }
   1291 
   1292 /*
   1293  * Generate unique name for file with basename "local".
   1294  * The file named "local" is already known to exist.
   1295  * Generates failure reply on error.
   1296  */
   1297 char *
   1298 gunique(local)
   1299 	char *local;
   1300 {
   1301 	static char new[MAXPATHLEN];
   1302 	struct stat st;
   1303 	char *cp = rindex(local, '/');
   1304 	int count = 0;
   1305 
   1306 	if (cp)
   1307 		*cp = '\0';
   1308 	if (stat(cp ? local : ".", &st) < 0) {
   1309 		perror_reply(553, cp ? local : ".");
   1310 		return((char *) 0);
   1311 	}
   1312 	if (cp)
   1313 		*cp = '/';
   1314 	(void) strcpy(new, local);
   1315 	cp = new + strlen(new);
   1316 	*cp++ = '.';
   1317 	for (count = 1; count < 100; count++) {
   1318 		(void) sprintf(cp, "%d", count);
   1319 		if (stat(new, &st) < 0)
   1320 			return(new);
   1321 	}
   1322 	reply(452, "Unique file name cannot be created.");
   1323 	return((char *) 0);
   1324 }
   1325 
   1326 /*
   1327  * Format and send reply containing system error number.
   1328  */
   1329 perror_reply(code, string)
   1330 	int code;
   1331 	char *string;
   1332 {
   1333 	reply(code, "%s: %s.", string, strerror(errno));
   1334 }
   1335 
   1336 static char *onefile[] = {
   1337 	"",
   1338 	0
   1339 };
   1340 
   1341 send_file_list(whichfiles)
   1342 	char *whichfiles;
   1343 {
   1344 	struct stat st;
   1345 	DIR *dirp = NULL;
   1346 	struct dirent *dir;
   1347 	FILE *dout = NULL;
   1348 	register char **dirlist, *dirname;
   1349 	int simple = 0;
   1350 	char *strpbrk();
   1351 
   1352 	if (strpbrk(whichfiles, "~{[*?") != NULL) {
   1353 		extern char **ftpglob(), *globerr;
   1354 
   1355 		globerr = NULL;
   1356 		dirlist = ftpglob(whichfiles);
   1357 		if (globerr != NULL) {
   1358 			reply(550, globerr);
   1359 			return;
   1360 		} else if (dirlist == NULL) {
   1361 			errno = ENOENT;
   1362 			perror_reply(550, whichfiles);
   1363 			return;
   1364 		}
   1365 	} else {
   1366 		onefile[0] = whichfiles;
   1367 		dirlist = onefile;
   1368 		simple = 1;
   1369 	}
   1370 
   1371 	if (setjmp(urgcatch)) {
   1372 		transflag = 0;
   1373 		return;
   1374 	}
   1375 	while (dirname = *dirlist++) {
   1376 		if (stat(dirname, &st) < 0) {
   1377 			/*
   1378 			 * If user typed "ls -l", etc, and the client
   1379 			 * used NLST, do what the user meant.
   1380 			 */
   1381 			if (dirname[0] == '-' && *dirlist == NULL &&
   1382 			    transflag == 0) {
   1383 				retrieve("/bin/ls %s", dirname);
   1384 				return;
   1385 			}
   1386 			perror_reply(550, whichfiles);
   1387 			if (dout != NULL) {
   1388 				(void) fclose(dout);
   1389 				transflag = 0;
   1390 				data = -1;
   1391 				pdata = -1;
   1392 			}
   1393 			return;
   1394 		}
   1395 
   1396 		if ((st.st_mode&S_IFMT) == S_IFREG) {
   1397 			if (dout == NULL) {
   1398 				dout = dataconn("file list", (off_t)-1, "w");
   1399 				if (dout == NULL)
   1400 					return;
   1401 				transflag++;
   1402 			}
   1403 			fprintf(dout, "%s%s\n", dirname,
   1404 				type == TYPE_A ? "\r" : "");
   1405 			byte_count += strlen(dirname) + 1;
   1406 			continue;
   1407 		} else if ((st.st_mode&S_IFMT) != S_IFDIR)
   1408 			continue;
   1409 
   1410 		if ((dirp = opendir(dirname)) == NULL)
   1411 			continue;
   1412 
   1413 		while ((dir = readdir(dirp)) != NULL) {
   1414 			char nbuf[MAXPATHLEN];
   1415 
   1416 			if (dir->d_name[0] == '.' && dir->d_namlen == 1)
   1417 				continue;
   1418 			if (dir->d_name[0] == '.' && dir->d_name[1] == '.' &&
   1419 			    dir->d_namlen == 2)
   1420 				continue;
   1421 
   1422 			sprintf(nbuf, "%s/%s", dirname, dir->d_name);
   1423 
   1424 			/*
   1425 			 * We have to do a stat to insure it's
   1426 			 * not a directory or special file.
   1427 			 */
   1428 			if (simple || (stat(nbuf, &st) == 0 &&
   1429 			    (st.st_mode&S_IFMT) == S_IFREG)) {
   1430 				if (dout == NULL) {
   1431 					dout = dataconn("file list", (off_t)-1,
   1432 						"w");
   1433 					if (dout == NULL)
   1434 						return;
   1435 					transflag++;
   1436 				}
   1437 				if (nbuf[0] == '.' && nbuf[1] == '/')
   1438 					fprintf(dout, "%s%s\n", &nbuf[2],
   1439 						type == TYPE_A ? "\r" : "");
   1440 				else
   1441 					fprintf(dout, "%s%s\n", nbuf,
   1442 						type == TYPE_A ? "\r" : "");
   1443 				byte_count += strlen(nbuf) + 1;
   1444 			}
   1445 		}
   1446 		(void) closedir(dirp);
   1447 	}
   1448 
   1449 	if (dout == NULL)
   1450 		reply(550, "No files found.");
   1451 	else if (ferror(dout) != 0)
   1452 		perror_reply(550, "Data connection");
   1453 	else
   1454 		reply(226, "Transfer complete.");
   1455 
   1456 	transflag = 0;
   1457 	if (dout != NULL)
   1458 		(void) fclose(dout);
   1459 	data = -1;
   1460 	pdata = -1;
   1461 }
   1462