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