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