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