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