/*
 * Copyright (c) 1985, 1988 Regents of the University of California.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms are permitted
 * provided that the above copyright notice and this paragraph are
 * duplicated in all such forms and that any documentation,
 * advertising materials, and other materials related to such
 * distribution and use acknowledge that the software was developed
 * by the University of California, Berkeley.  The name of the
 * University may not be used to endorse or promote products derived
 * from this software without specific prior written permission.
 */

#ifndef lint
char copyright[] =
"@(#) Copyright (c) 1985, 1988 Regents of the University of California.\n\
 All rights reserved.\n";
#endif not lint

#ifndef lint
static	char sccsid[] = "@(#)ftpd.c 1.1 90/03/23 SMI"; /* from UCB 5.20 12/7/88 */
#endif not lint

/*
 * FTP server.
 */
#include <sys/param.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/file.h>
#include <sys/wait.h>

#include <netinet/in.h>

#include <arpa/ftp.h>
#include <arpa/inet.h>
#include <arpa/telnet.h>

#include <stdio.h>
#include <signal.h>
#include <pwd.h>
#include <setjmp.h>
#include <netdb.h>
#include <errno.h>
#include <strings.h>
#include <syslog.h>
#include <varargs.h>

#include <assert.h>

#include "tmp/libpq-fs.h"

/*
 * File containing login names
 * NOT to be used on this machine.
 * Commonly used to disallow uucp.
 */
#define	FTPUSERS	"/etc/ftpusers"

extern	int errno;
extern	char *sys_errlist[];
extern	int sys_nerr;
extern	char *crypt();
extern	char version[];
extern	char *home;		/* pointer to home directory for glob */
extern	FILE *ftpd_popen(), *fopen(), *freopen();
extern	int  ftpd_pclose(), fclose();
extern	char *getline();
extern	char cbuf[];

struct	sockaddr_in ctrl_addr;
struct	sockaddr_in data_source;
struct	sockaddr_in data_dest;
struct	sockaddr_in his_addr;

int	data;
jmp_buf	errcatch, urgcatch;
int	logged_in;
struct	passwd *pw;
int	debug;
int	timeout = 900;    /* timeout after 15 minutes of inactivity */
int	logging;
int	guest;
int	type;
int	formxxx; /* rename to avoid conflict with pq library */
int	stru;			/* avoid C keyword */
int	mode;
int	usedefault = 1;		/* for data transfers */
int	pdata = -1;		/* for passive mode */
int	transflag;
int	socksize = 24 * 1024;	/* larger socket window size for data */
char	tmpline[7];
char	hostname[MAXHOSTNAMELEN];
char	remotehost[MAXHOSTNAMELEN];
char	buf[BUFSIZ*8];		/* larger buffer to speed up binary xfers */

/*
 * Timeout intervals for retrying connections
 * to hosts that don't accept PORT cmds.  This
 * is a kludge, but given the problems with TCP...
 */
#define	SWAITMAX	90	/* wait at most 90 seconds */
#define	SWAITINT	5	/* interval between retries */

int	swaitmax = SWAITMAX;
int	swaitint = SWAITINT;

int	lostconn();
int	myoob();
FILE	*getdatasock(), *dataconn();

main(argc, argv)
	int argc;
	char *argv[];
{
	int addrlen, on = 1;
	char *cp;


	openlog("ftpd", LOG_PID/*, LOG_DAEMON*/);
	addrlen = sizeof (his_addr);
	if (getpeername(0, (struct sockaddr *)&his_addr, &addrlen) < 0) {
		syslog(LOG_ERR, "getpeername (%s): %m",argv[0]);
		exit(1);
	}
	addrlen = sizeof (ctrl_addr);
	if (getsockname(0, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) {
		syslog(LOG_ERR, "getsockname (%s): %m",argv[0]);
		exit(1);
	}
	data_source.sin_port = htons(ntohs(ctrl_addr.sin_port) - 1);
	debug = 0;
	argc--, argv++;
	while (argc > 0 && *argv[0] == '-') {
		for (cp = &argv[0][1]; *cp; cp++) switch (*cp) {

		case 'v':
			debug = 1;
			break;

		case 'd':
			debug = 1;
			break;

		case 'l':
			logging = 1;
			break;

		case 't':
			timeout = atoi(++cp);
			goto nextopt;
			break;

		default:
			fprintf(stderr, "ftpd: Unknown flag -%c ignored.\n",
			     *cp);
			break;
		}
nextopt:
		argc--, argv++;
	}
	(void) freopen("/dev/null", "w", stderr);
	(void) signal(SIGPIPE, lostconn);
	(void) signal(SIGCHLD, SIG_IGN);
	if (signal(SIGURG, myoob) == BADSIG)
		syslog(LOG_ERR, "signal: %m");
	/* handle urgent data inline */
#ifdef SO_OOBINLINE
	if (setsockopt(0, SOL_SOCKET, SO_OOBINLINE, (char *)&on, sizeof(on)) < 0)
		syslog(LOG_ERR, "setsockopt: %m");
#endif
	if (fcntl(fileno(stdin), F_SETOWN, getpid()) == -1)
		syslog(LOG_ERR, "fcntl F_SETOWN: %m");
	dolog(&his_addr);
	/* do telnet option negotiation here */
	/*
	 * Set up default state
	 */
	data = -1;
	type = TYPE_A;
	formxxx = FORM_N;
	stru = STRU_F;
	mode = MODE_S;
	tmpline[0] = '\0';
	(void) gethostname(hostname, sizeof (hostname));
	reply(220, "%s FTP server (%s) ready.", hostname, version);
	(void) setjmp(errcatch);
	for (;;)
		(void) yyparse();
}

lostconn()
{

	if (debug)
		syslog(LOG_DEBUG, "lost connection");
	dologout(-1);
}

static char ttyline[20];

/*
 * Helper function for sgetpwnam().
 */
char *
sgetsave(s)
	char *s;
{
	char *malloc();
	char *newx = malloc((unsigned) strlen(s) + 1);
	
	if (newx == NULL) {
		reply(553, "Local resource failure: malloc");
		dologout(1);
	}
	(void) strcpy(newx, s);
	return (newx);
}

/*
 * Save the result of a getpwnam.  Used for USER command, since
 * the data returned must not be clobbered by any other command
 * (e.g., globbing).
 */
struct passwd *
sgetpwnam(name)
	char *name;
{
	static struct passwd save;
	register struct passwd *p;
	char *sgetsave();

	if ((p = getpwnam(name)) == NULL)
		return (p);
	if (save.pw_name) {
		free(save.pw_name);
		free(save.pw_passwd);
		free(save.pw_comment);
		free(save.pw_gecos);
		free(save.pw_dir);
		free(save.pw_shell);
	}
	save = *p;
	save.pw_name = sgetsave(p->pw_name);
	save.pw_passwd = sgetsave(p->pw_passwd);
	save.pw_comment = sgetsave(p->pw_comment);
	save.pw_gecos = sgetsave(p->pw_gecos);
	save.pw_dir = sgetsave(p->pw_dir);
	save.pw_shell = sgetsave(p->pw_shell);
	return (&save);
}

int login_attempts;		/* number of failed login attempts */
int askpasswd;			/* had user command, ask for passwd */

/*
 * USER command.
 * Sets global passwd pointer pw if named account exists
 * and is acceptable; sets askpasswd if a PASS command is
 * expected. If logged in previously, need to reset state.
 * If name is "ftp" or "anonymous" and ftp account exists,
 * set guest and pw, then just return.
 * If account doesn't exist, ask for passwd anyway.
 * Otherwise, check user requesting login privileges.
 * Disallow anyone who does not have a standard
 * shell returned by getusershell() (/etc/shells).
 * Disallow anyone mentioned in the file FTPUSERS
 * to allow people such as root and uucp to be avoided.
 */
/* don't suppport /etc/shells yet */
char *getusershell() { return "/bin/csh"; }
endusershell() { }

user(name)
	char *name;
{
	register char *cp;
	FILE *fd;
	char *shell;
	char line[BUFSIZ], *index(), *getusershell();

	if (logged_in) {
		if (guest) {
			reply(530, "Can't change user from guest login.");
			return;
		}
		end_login();
	}

	guest = 0;
	if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) {
		if ((pw = sgetpwnam("ftp")) != NULL) {
			guest = 1;
			askpasswd = 1;
			reply(331, "Guest login ok, send ident as password.");
		} else
			reply(530, "User %s unknown.", name);
		return;
	}
	if (pw = sgetpwnam(name)) {
#if 0
		if ((shell = pw->pw_shell) == NULL || *shell == 0)
			shell = "/bin/sh";
		while ((cp = getusershell()) != NULL)
			if (strcmp(cp, shell) == 0)
				break;
		endusershell();
		if (cp == NULL) {
			reply(530, "User %s access denied.", name);
			pw = (struct passwd *) NULL;
			return;
		}
#endif
		if ((fd = fopen(FTPUSERS, "r")) != NULL) {
		    while (fgets(line, sizeof (line), fd) != NULL) {
			if ((cp = index(line, '\n')) != NULL)
				*cp = '\0';
			if (strcmp(line, name) == 0) {
				reply(530, "User %s access denied.", name);
				pw = (struct passwd *) NULL;
				return;
			}
		    }
		}
		(void) fclose(fd);
	}
	reply(331, "Password required for %s.", name);
	askpasswd = 1;
	/*
	 * Delay before reading passwd after first failed
	 * attempt to slow down passwd-guessing programs.
	 */
	if (login_attempts)
		sleep((unsigned) login_attempts);
}

/*
 * Terminate login as previous user, if any, resetting state;
 * used when USER command is given or login fails.
 */
end_login()
{

	(void) seteuid((uid_t)0);
	if (logged_in)
		logwtmp(ttyline, "", "");
	pw = NULL;
	logged_in = 0;
	guest = 0;
}

pass(passwd)
	char *passwd;
{
	char *xpasswd, *salt;
	static char USER[256];

	if (logged_in || askpasswd == 0) {
		reply(503, "Login with USER first.");
		return;
	}
	askpasswd = 0;
	if (!guest) {		/* "ftp" is only account allowed no password */
		if (pw == NULL)
			salt = "xx";
		else
			salt = pw->pw_passwd;
		xpasswd = crypt(passwd, salt);
		/* The strcmp does not catch null passwords! */
		if (pw == NULL || *pw->pw_passwd == '\0' ||
		    strcmp(xpasswd, pw->pw_passwd)) {
			reply(530, "Login incorrect.");
			pw = NULL;
			if (login_attempts++ >= 5) {
				syslog(LOG_ERR,
				    "repeated login failures from %s",
				    remotehost);
				exit(0);
			}
			return;
		}
	}
	login_attempts = 0;		/* this time successful */
	(void) setegid((gid_t)pw->pw_gid);
	(void) initgroups(pw->pw_name, pw->pw_gid);
	if (chdir(pw->pw_dir)) {
		if (chdir("/")) {
			reply(550, "User %s: can't change directory to %s.",
				pw->pw_name, pw->pw_dir);
			goto bad;
		}
	}

	/* open wtmp before chroot */
	(void)sprintf(ttyline, "ftp%d", getpid());
	logwtmp(ttyline, pw->pw_name, remotehost);
	logged_in = 1;

	if (guest && chroot(pw->pw_dir) < 0) {
		reply(550, "Can't set guest privileges.");
		goto bad;
	}
	if (seteuid((uid_t)pw->pw_uid) < 0) {
		reply(550, "Can't set uid.");
		goto bad;
	}
	if (guest)
		reply(230, "-Guest login ok, access restrictions apply.");
	else
		reply(230, "-User %s logged in.", pw->pw_name);
	home = pw->pw_dir;		/* home dir for globbing */
	reply(230,"Setting PQ db to %s",pw->pw_name);
	sprintf(USER,"USER=%s",pw->pw_name);
	putenv(USER);
	PQsetdb(pw->pw_name);
	return;
bad:
	/* Forget all about it... */
	end_login();
}

/*
 * return a printable type string
 */
char *print_type(t)
{
	switch (t)
	{
	  case TYPE_A:	return("ASCII ");
	  case TYPE_L:
	  case TYPE_I:	return("Binary ");
	}
	return("");
}

retrieve(cmd, name)
	char *cmd, *name;
{
	FILE *fin, *dout;
	struct pgstat st;
	int (*closefunc)(), tmp;
	void (*oldpipe)();	/* Hold value of SIGPIPE during close */

	if (cmd == 0) {
		fin = (FILE *)p_open(name, O_RDONLY); closefunc = p_close;
/*	    reply(200, "got %d as fd.", fin);*/
	} else {
		char line[BUFSIZ];

		(void) sprintf(line, cmd, name), name = line;
		fin = ftpd_popen(line, "r"), closefunc = ftpd_pclose;
	}
	if ((cmd != 0 && fin == NULL) || (cmd == 0 && ((int )fin) < 0)) {
		if (errno != 0)
			perror_reply(550, name);
		return;
	}
	st.st_size = 0;
	if (cmd == 0 &&
	    (p_stat(name, &st) < 0 || (st.st_mode&S_IFMT) != S_IFREG)) {
		reply(550, "%s: not a plain file.", name);
		goto done;
	}
	dout = dataconn(name, st.st_size, "w");
	if (dout == NULL)
		goto done;
	if ((tmp = send_data(fin, dout,cmd)) > 0 || ferror(dout) > 0) {
		perror_reply(550, name);
	}
	else if (tmp == 0) {
		reply(226, "%sTransfer complete.", print_type(type));
	}
	/*
	 * If the transfer failed because the data connection got aborted,
	 * then the fclose may cause a SIGPIPE trying to flush the buffers
	 * and abort the whole session.  Ignore SIGPIPEs during the fclose.
	 */
	oldpipe = signal(SIGPIPE, SIG_IGN);
	(void) fclose(dout);
	data = -1;
	pdata = -1;
	signal(SIGPIPE, oldpipe);
done:
	(*closefunc)(fin);
}

store(name, mode, unique)
	char *name, *mode;
	int unique;
{
	int fout;
	FILE *din;
	int (*closefunc)(), tmp;
	char *gunique();

	{
		struct pgstat st;

		if (unique && p_stat(name, &st) == 0 &&
		    (name = gunique(name)) == NULL)
			return;
		fout = p_open(name, mode), closefunc = p_close;
	}
	if (fout < NULL) {
		perror_reply(553, name);
		return;
	}
	din = dataconn(name, (off_t)-1, "r");
	if (din == NULL)
		goto done;
	if ((tmp = receive_data(din, fout)) > 0 || p_ferror(fout) > 0)
		perror_reply(552, name);
	else if (tmp == 0) {
		if (p_ferror(fout) > 0)
			perror_reply(552, name);
		else if (unique)
			reply(226, "Transfer complete (unique file name:%s).",
			    name);
		else
			reply(226, "%sTransfer complete.", print_type(type));
	}
	(void) fclose(din);
	data = -1;
	pdata = -1;
done:
	(*closefunc)(fout);
}

FILE *
getdatasock(mode)
	char *mode;
{
	int s, on = 1;

	if (data >= 0)
		return (fdopen(data, mode));
	s = socket(AF_INET, SOCK_STREAM, 0);
	if (s < 0)
		return (NULL);
	(void) seteuid((uid_t)0);
	if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *) &on, sizeof (on)) < 0)
		goto bad;
	/* anchor socket to avoid multi-homing problems */
	data_source.sin_family = AF_INET;
	data_source.sin_addr = ctrl_addr.sin_addr;
	if (bind(s, (struct sockaddr *)&data_source, sizeof (data_source)) < 0)
		goto bad;
	(void) seteuid((uid_t)pw->pw_uid);
	return (fdopen(s, mode));
bad:
	(void) seteuid((uid_t)pw->pw_uid);
	(void) close(s);
	return (NULL);
}

FILE *
dataconn(name, size, mode)
	char *name;
	off_t size;
	char *mode;
{
	char sizebuf[32];
	FILE *file;
	int retry = 0;

	if (size != (off_t) -1)
		(void) sprintf (sizebuf, " (%ld bytes)", size);
	else
		(void) strcpy(sizebuf, "");
	if (pdata >= 0) {
		struct sockaddr_in from;
		int s, fromlen = sizeof(from);

		s = accept(pdata, (struct sockaddr *)&from, &fromlen);
		if (s < 0) {
			reply(425, "Can't open data connection.");
			(void) close(pdata);
			pdata = -1;
			return(NULL);
		}
		(void) close(pdata);
		pdata = s;
		reply(150, "%sdata connection for %s (%s,%d)%s.",
		     print_type(type),
		     name, inet_ntoa(from.sin_addr),
		     ntohs(from.sin_port), sizebuf);
		return(fdopen(pdata, mode));
	}
	if (data >= 0) {
		reply(125, "Using existing %sdata connection for %s%s.",
		    print_type(type),
		    name, sizebuf);
		usedefault = 1;
		return (fdopen(data, mode));
	}
	if (usedefault)
		data_dest = his_addr;
	usedefault = 1;
	file = getdatasock(mode);
	if (file == NULL) {
		reply(425, "Can't create data socket (%s,%d): %s.",
		    inet_ntoa(data_source.sin_addr),
		    ntohs(data_source.sin_port),
		    errno < sys_nerr ? sys_errlist[errno] : "unknown error");
		return (NULL);
	}
	data = fileno(file);
	(void) setsockopt(data, SOL_SOCKET, SO_SNDBUF, (char *)&socksize, 
				sizeof (socksize));
	(void) setsockopt(data, SOL_SOCKET, SO_RCVBUF, (char *)&socksize, 
				sizeof (socksize));
	while (connect(data, &data_dest, sizeof (data_dest)) < 0) {
		if (errno == EADDRINUSE && retry < swaitmax) {
			sleep((unsigned) swaitint);
			retry += swaitint;
			continue;
		}
		perror_reply(425, "Can't build data connection");
		(void) fclose(file);
		data = -1;
		return (NULL);
	}
	reply(150, "%sdata connection for %s (%s,%d)%s.",
	    print_type(type),
	    name, inet_ntoa(data_dest.sin_addr),
	    ntohs(data_dest.sin_port), sizebuf);
	return (file);
}

/*
 * Envelope for 'send_data_body'.  Allow data connections to fail without
 * terminating the daemon, but SIGPIPE is set to be ignored so that if
 * one occurs on the data channel we'll just catch the error return on
 * the write rather than causing the whole session to abort.
 */
/* Change instream to a file descriptor because we don't support buffered
 * i/o in the postgres lib yet...
 */
send_data(instr, outstr,cmd)
	int instr;		/* Data being sent */
	FILE *outstr;		/* Connection being transmitted upon */
{
	int value;		/* Return value from send_data_body */
	void (*oldpipe)();	/* Old handler for SIGPIPE */

	oldpipe = signal(SIGPIPE, SIG_IGN);
	value = send_data_body(instr, outstr,cmd);
	signal(SIGPIPE, oldpipe);
	return (value);	
}

/*
 * Tranfer the contents of "instr" to
 * "outstr" peer using the appropriate
 * encapulation of the date subject
 * to Mode, Structure, and Type.
 *
 * NB: Form isn't handled.
 */
send_data_body(instr, outstr,cmd)
     int instr;
     FILE  *outstr;
     int cmd; /* ==0 if instr is binary file. !0 if instr is a FILE  */
{
	register int c;
	int netfd, filefd, cnt;

	transflag++;
	if (setjmp(urgcatch)) {
		transflag = 0;
		return(-1);
	}
	switch (type) {
	    /* Ascii mode will not work until buffered i/o works ...*/
	case TYPE_A:
	    assert(cmd != 0);
		while ((c = getc((FILE *)instr)) != EOF) {
			if (c == '\n') {
				if (ferror (outstr)) {
					transflag = 0;
					return (1);
				}
				(void) putc('\r', outstr);
			}
			(void) putc(c, outstr);
		}
		transflag = 0;
		if (ferror ((FILE *)instr) || ferror (outstr)) {
			return (1);
		}
		return (0);
	case TYPE_I:
	case TYPE_L:
		netfd = fileno(outstr);
		filefd = instr;

		while ((cnt = p_read(filefd, buf, sizeof (buf))) > 0) {
			if (write(netfd, buf, cnt) < 0) {
				transflag = 0;
				return (1);
			}
		}
		transflag = 0;
		return (cnt < 0);
	}
	reply(550, "Unimplemented TYPE %d in send_data", type);
	transflag = 0;
	return (-1);
}

/*
 * Transfer data from peer to
 * "outstr" using the appropriate
 * encapulation of the data subject
 * to Mode, Structure, and Type.
 *
 * N.B.: Form isn't handled.
 */
receive_data(instr, outstr)
	FILE *instr;
     int outstr;
{
	register int c;
	int cnt;
	char bigbuf[256*1024];
	int bigbufused = 0;


	transflag++;
	if (setjmp(urgcatch)) {
		transflag = 0;
		return(-1);
	}
	switch (type) {

	case TYPE_I:
	case TYPE_L:
		while ((cnt = read(fileno(instr), buf, sizeof buf)) > 0) {
			if (bigbufused + cnt >= sizeof(bigbuf)) {
				if (p_write(outstr, bigbuf, bigbufused) < 0) {
					transflag = 0;
					return (1);
				}
				bigbufused = 0;
			}
			bcopy(buf,bigbuf+bigbufused,cnt);
			bigbufused += cnt;
		}
		if (bigbufused > 0) {
			if (p_write(outstr, bigbuf, bigbufused) < 0) {
				transflag = 0;
				return (1);
			}
		}
		transflag = 0;
		return (cnt < 0);

	case TYPE_E:
		reply(553, "TYPE E not implemented.");
		transflag = 0;
		return (-1);
#if 0
/* no ascii until buffered i/o support */
	case TYPE_A:
		while ((c = getc(instr)) != EOF) {
			while (c == '\r') {
				if (ferror (outstr)) {
					transflag = 0;
					return (1);
				}
				if ((c = getc(instr)) != '\n')
					(void) putc ('\r', outstr);
			}
			(void) putc (c, outstr);
		}
		transflag = 0;
		if (ferror (instr) || ferror (outstr))
			return (1);
		return (0);
#endif
	}
	transflag = 0;
	fatal("Unknown type in receive_data.");
	/*NOTREACHED*/
}

fatal(s)
	char *s;
{
	reply(451, "Error in server: %s\n", s);
	reply(221, "Closing connection due to server error.");
	dologout(0);
}

/*VARARGS2*/
reply(n, s, va_alist)
	int n;
	char *s;
	va_dcl
{
	va_list ap;

	va_start(ap);
	printf("%d", n);
	if (s[0] != '-') printf(" ");
	_doprnt(s, ap, stdout);
	printf("\r\n");
	(void) fflush(stdout);
	if (debug) {
		syslog(LOG_DEBUG, "<--- %d ", n);
/*		vsyslog(LOG_DEBUG, s, ap);*/
	}
	va_end(ap);
}

/*VARARGS2*/
lreply(n, s, va_alist)
	int n;
	char *s;
	va_dcl
{
	va_list ap;

	va_start(ap);
	printf("%d-", n);
	_doprnt(s, ap, stdout);
	printf("\r\n");
	(void) fflush(stdout);
	if (debug) {
		syslog(LOG_DEBUG, "<--- %d- ", n);
/*		vsyslog(LOG_DEBUG, s, ap);*/
	}
	va_end(ap);
}

ack(s)
	char *s;
{
	reply(250, "%s command successful.", s);
}

nack(s)
	char *s;
{
	reply(502, "%s command not implemented.", s);
}

/* ARGSUSED */
yyerror(s)
	char *s;
{
	char *cp;

	cp = index(cbuf,'\n');
	*cp = '\0';
	reply(500, "'%s': command not understood.",cbuf);
}

deletex(name)
	char *name;
{
	struct pgstat st;

	if (p_stat(name, &st) < 0) {
		perror_reply(550, name);
		return;
	}
	if ((st.st_mode&S_IFMT) == S_IFDIR) {
		if (p_rmdir(name) < 0) {
			perror_reply(550, name);
			return;
		}
		goto done;
	}
	if (p_unlink(name) < 0) {
		perror_reply(550, name);
		return;
	}
done:
	ack("DELE");
}

cwd(path)
	char *path;
{

	if (p_chdir(path) < 0) {
		perror_reply(550, path);
		return;
	}
	ack("CWD");
}

makedir(name)
	char *name;
{
	if (p_mkdir(name, 0777) < 0)
		perror_reply(550, name);
	else
		reply(257, "MKD command successful.");
}

removedir(name)
	char *name;
{

	if (p_rmdir(name) < 0) {
		perror_reply(550, name);
		return;
	}
	ack("RMD");
}

pwd()
{
	char path[MAXPATHLEN + 1];
	extern char *p_getwd();

	if (p_getwd(path) == (char *)NULL) {
		reply(550, "%s.", path);
		return;
	}
	reply(257, "\"%s\" is current directory.", path);
}

char *
renamefrom(name)
	char *name;
{
	struct pgstat st;

	if (p_stat(name, &st) < 0) {
		perror_reply(550, name);
		return ((char *)0);
	}
	reply(350, "File exists, ready for destination name");
	return (name);
}

renamecmd(from, to)
	char *from, *to;
{

	if (p_rename(from, to) < 0) {
		perror_reply(550, "rename");
		return;
	}
	ack("RNTO");
}

dolog(sin)
	struct sockaddr_in *sin;
{
	struct hostent *hp = gethostbyaddr((char *)&sin->sin_addr,
		sizeof (struct in_addr), AF_INET);
	time_t t, time();
	extern char *ctime();

	if (hp)
		(void) strncpy(remotehost, hp->h_name, sizeof (remotehost));
	else
		(void) strncpy(remotehost, inet_ntoa(sin->sin_addr),
		    sizeof (remotehost));
	if (!logging)
		return;
	t = time((time_t *) 0);
	syslog(LOG_INFO, "connection from %s at %s",
	    remotehost, ctime(&t));
}

/*
 * Record logout in wtmp file
 * and exit with supplied status.
 */
dologout(status)
	int status;
{
	if (logged_in) {
		(void) seteuid((uid_t)0);
		logwtmp(ttyline, "", "");
		PQfinish();
	}
	/* beware of flushing buffers after a SIGPIPE */
	_exit(status);
}

myoob()
{
	char *cp;

	/* only process if transfer occurring */
	if (!transflag)
		return;
	cp = tmpline;
	if (getline(cp, 7, stdin) == NULL) {
		reply(221, "You could at least say goodbye.");
		dologout(0);
	}
	upper(cp);
	if (strcmp(cp, "ABOR\r\n"))
		return;
	tmpline[0] = '\0';
	reply(426,"Transfer aborted. Data connection closed.");
	reply(226,"Abort successful");
	longjmp(urgcatch, 1);
}

/*
 * Note: The 530 reply codes could be 4xx codes, except nothing is
 * given in the state tables except 421 which implies an exit.  (RFC959)
 */
passive()
{
	int len;
	struct sockaddr_in tmp;
	register char *p, *a;

	pdata = socket(AF_INET, SOCK_STREAM, 0);
	if (pdata < 0) {
		reply(530, "Can't open passive connection");
		return;
	}
	tmp = ctrl_addr;
	tmp.sin_port = 0;
	(void) seteuid((uid_t)0);
	if (bind(pdata, (struct sockaddr *) &tmp, sizeof(tmp)) < 0) {
		(void) seteuid((uid_t)pw->pw_uid);
		(void) close(pdata);
		pdata = -1;
		reply(530, "Can't open passive connection");
		return;
	}
	(void) seteuid((uid_t)pw->pw_uid);
	len = sizeof(tmp);
	if (getsockname(pdata, (struct sockaddr *) &tmp, &len) < 0) {
		(void) close(pdata);
		pdata = -1;
		reply(530, "Can't open passive connection");
		return;
	}
	if (listen(pdata, 1) < 0) {
		(void) close(pdata);
		pdata = -1;
		reply(530, "Can't open passive connection");
		return;
	}
	a = (char *) &tmp.sin_addr;
	p = (char *) &tmp.sin_port;

#define UC(b) (((int) b) & 0xff)

	reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
		UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
}

/*
 * Generate unique name for file with basename "local".
 * The file named "local" is already known to exist.
 * Generates failure reply on error.
 */
char *
gunique(local)
	char *local;
{
	static char newx[MAXPATHLEN];
	struct pgstat st;
	char *cp = rindex(local, '/');
	int d, count=0;

	if (cp)
		*cp = '\0';
	d = stat(cp ? local : ".", &st);
	if (cp)
		*cp = '/';
	if (d < 0) {
		perror_reply(553, local);
		return((char *) 0);
	}
	(void) strcpy(newx, local);
	cp = newx + strlen(newx);
	*cp++ = '.';
	for (count = 1; count < 100; count++) {
		(void) sprintf(cp, "%d", count);
		if (stat(newx, &st) < 0)
			return(newx);
	}
	reply(452, "Unique file name cannot be created.");
	return((char *) 0);
}

/*
 * Format and send reply containing system error number.
 */
perror_reply(code, string)
	int code;
	char *string;
{

	if (errno < sys_nerr)
		reply(code, "%s: %s.", string, sys_errlist[errno]);
	else
		reply(code, "%s: unknown error %d.", string, errno);
}
