ftpd.c revision 1.97
1/*	$OpenBSD: ftpd.c,v 1.97 2001/05/29 21:35:16 millert Exp $	*/
2/*	$NetBSD: ftpd.c,v 1.15 1995/06/03 22:46:47 mycroft Exp $	*/
3
4/*
5 * Copyright (C) 1997 and 1998 WIDE Project.
6 * 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. Neither the name of the project nor the names of its contributors
17 *    may be used to endorse or promote products derived from this software
18 *    without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
31 */
32
33/*
34 * Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994
35 *	The Regents of the University of California.  All rights reserved.
36 *
37 * Redistribution and use in source and binary forms, with or without
38 * modification, are permitted provided that the following conditions
39 * are met:
40 * 1. Redistributions of source code must retain the above copyright
41 *    notice, this list of conditions and the following disclaimer.
42 * 2. Redistributions in binary form must reproduce the above copyright
43 *    notice, this list of conditions and the following disclaimer in the
44 *    documentation and/or other materials provided with the distribution.
45 * 3. All advertising materials mentioning features or use of this software
46 *    must display the following acknowledgement:
47 *	This product includes software developed by the University of
48 *	California, Berkeley and its contributors.
49 * 4. Neither the name of the University nor the names of its contributors
50 *    may be used to endorse or promote products derived from this software
51 *    without specific prior written permission.
52 *
53 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
54 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
55 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
56 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
57 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
58 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
59 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
60 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
61 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
62 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
63 * SUCH DAMAGE.
64 */
65
66#ifndef lint
67static char copyright[] =
68"@(#) Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994\n\
69	The Regents of the University of California.  All rights reserved.\n";
70#endif /* not lint */
71
72#ifndef lint
73#if 0
74static char sccsid[] = "@(#)ftpd.c	8.4 (Berkeley) 4/16/94";
75#else
76static char rcsid[] = "$OpenBSD: ftpd.c,v 1.97 2001/05/29 21:35:16 millert Exp $";
77#endif
78#endif /* not lint */
79
80/*
81 * FTP server.
82 */
83#include <sys/param.h>
84#include <sys/stat.h>
85#include <sys/ioctl.h>
86#include <sys/socket.h>
87#include <sys/wait.h>
88#include <sys/mman.h>
89
90#include <netinet/in.h>
91#include <netinet/in_systm.h>
92#include <netinet/ip.h>
93#include <netinet/tcp.h>
94
95#define	FTP_NAMES
96#include <arpa/ftp.h>
97#include <arpa/inet.h>
98#include <arpa/telnet.h>
99
100#include <ctype.h>
101#include <dirent.h>
102#include <err.h>
103#include <errno.h>
104#include <fcntl.h>
105#include <glob.h>
106#include <limits.h>
107#include <login_cap.h>
108#include <netdb.h>
109#include <pwd.h>
110#include <setjmp.h>
111#include <signal.h>
112#include <stdio.h>
113#include <stdlib.h>
114#include <string.h>
115#include <syslog.h>
116#include <time.h>
117#include <vis.h>
118#include <unistd.h>
119#include <util.h>
120#include <utmp.h>
121#include <bsd_auth.h>
122
123#if defined(TCPWRAPPERS)
124#include <tcpd.h>
125#endif	/* TCPWRAPPERS */
126
127#include "pathnames.h"
128#include "extern.h"
129
130#ifdef __STDC__
131#include <stdarg.h>
132#else
133#include <varargs.h>
134#endif
135
136static char version[] = "Version 6.5/OpenBSD";
137
138extern	off_t restart_point;
139extern	char cbuf[];
140
141union sockunion server_addr;
142union sockunion ctrl_addr;
143union sockunion data_source;
144union sockunion data_dest;
145union sockunion his_addr;
146union sockunion pasv_addr;
147
148sigset_t allsigs;
149
150int	daemon_mode = 0;
151int	data;
152jmp_buf	errcatch, urgcatch;
153int	logged_in;
154struct	passwd *pw;
155int	debug = 0;
156int	timeout = 900;    /* timeout after 15 minutes of inactivity */
157int	maxtimeout = 7200;/* don't allow idle time to be set beyond 2 hours */
158int	logging;
159int	high_data_ports = 0;
160int	anon_only = 0;
161int	multihome = 0;
162int	guest;
163int	stats;
164int	statfd = -1;
165int	portcheck = 1;
166int	dochroot;
167int	type;
168int	form;
169int	stru;			/* avoid C keyword */
170int	mode;
171int	doutmp = 0;		/* update utmp file */
172int	usedefault = 1;		/* for data transfers */
173int	pdata = -1;		/* for passive mode */
174int	family = AF_INET;
175sig_atomic_t transflag;
176off_t	file_size;
177off_t	byte_count;
178#if !defined(CMASK) || CMASK == 0
179#undef CMASK
180#define CMASK 022
181#endif
182int	defumask = CMASK;		/* default umask value */
183int	umaskchange = 1;		/* allow user to change umask value. */
184char	tmpline[7];
185char	hostname[MAXHOSTNAMELEN];
186char	remotehost[MAXHOSTNAMELEN];
187char	dhostname[MAXHOSTNAMELEN];
188char	*guestpw;
189static char ttyline[20];
190char	*tty = ttyline;		/* for klogin */
191static struct utmp utmp;	/* for utmp */
192static	login_cap_t *lc;
193static	auth_session_t *as;
194
195#if defined(TCPWRAPPERS)
196int	allow_severity = LOG_INFO;
197int	deny_severity = LOG_NOTICE;
198#endif	/* TCPWRAPPERS */
199
200char	*ident = NULL;
201
202
203int epsvall = 0;
204
205/*
206 * Timeout intervals for retrying connections
207 * to hosts that don't accept PORT cmds.  This
208 * is a kludge, but given the problems with TCP...
209 */
210#define	SWAITMAX	90	/* wait at most 90 seconds */
211#define	SWAITINT	5	/* interval between retries */
212
213int	swaitmax = SWAITMAX;
214int	swaitint = SWAITINT;
215
216#ifdef HASSETPROCTITLE
217char	proctitle[BUFSIZ];	/* initial part of title */
218#endif /* HASSETPROCTITLE */
219
220#define LOGCMD(cmd, file) \
221	if (logging > 1) \
222	    syslog(LOG_INFO,"%s %s%s", cmd, \
223		*(file) == '/' ? "" : curdir(), file);
224#define LOGCMD2(cmd, file1, file2) \
225	 if (logging > 1) \
226	    syslog(LOG_INFO,"%s %s%s %s%s", cmd, \
227		*(file1) == '/' ? "" : curdir(), file1, \
228		*(file2) == '/' ? "" : curdir(), file2);
229#define LOGBYTES(cmd, file, cnt) \
230	if (logging > 1) { \
231		if (cnt == (off_t)-1) \
232		    syslog(LOG_INFO,"%s %s%s", cmd, \
233			*(file) == '/' ? "" : curdir(), file); \
234		else \
235		    syslog(LOG_INFO, "%s %s%s = %qd bytes", \
236			cmd, (*(file) == '/') ? "" : curdir(), file, cnt); \
237	}
238
239static void	 ack __P((char *));
240static void	 myoob __P((int));
241static int	 checkuser __P((char *, char *));
242static FILE	*dataconn __P((char *, off_t, char *));
243static void	 dolog __P((struct sockaddr *));
244static char	*copy_dir __P((char *, struct passwd *));
245static char	*curdir __P((void));
246static void	 end_login __P((void));
247static FILE	*getdatasock __P((char *));
248static int	guniquefd __P((char *, char **));
249static void	 lostconn __P((int));
250static void	 sigquit __P((int));
251static int	 receive_data __P((FILE *, FILE *));
252static void	 replydirname __P((const char *, const char *));
253static void	 send_data __P((FILE *, FILE *, off_t, off_t, int));
254static struct passwd *
255		 sgetpwnam __P((char *));
256static void	 reapchild __P((int));
257static int	 check_host __P((struct sockaddr *));
258static void	 usage __P((void));
259
260void	 logxfer __P((char *, off_t, time_t));
261
262static char *
263curdir()
264{
265	static char path[MAXPATHLEN+1];	/* path + '/' */
266
267	if (getcwd(path, sizeof(path)-1) == NULL)
268		return ("");
269	if (path[1] != '\0')		/* special case for root dir. */
270		strcat(path, "/");
271	/* For guest account, skip / since it's chrooted */
272	return (guest ? path+1 : path);
273}
274
275char *argstr = "AdDhlMSt:T:u:UvP46";
276
277static void
278usage()
279{
280	syslog(LOG_ERR,
281	    "usage: ftpd [-AdDhlMSUv] [-t timeout] [-T maxtimeout] [-u mask]");
282	exit(2);
283}
284
285int
286main(argc, argv, envp)
287	int argc;
288	char *argv[];
289	char **envp;
290{
291	int addrlen, ch, on = 1, tos;
292	char *cp, line[LINE_MAX];
293	FILE *fp;
294	struct hostent *hp;
295
296	tzset();		/* in case no timezone database in ~ftp */
297	sigfillset(&allsigs);	/* used to block signals while root */
298
299	while ((ch = getopt(argc, argv, argstr)) != -1) {
300		switch (ch) {
301		case 'A':
302			anon_only = 1;
303			break;
304
305		case 'd':
306			debug = 1;
307			break;
308
309		case 'D':
310			daemon_mode = 1;
311			break;
312
313		case 'P':
314			portcheck = 0;
315			break;
316
317		case 'h':
318			high_data_ports = 1;
319			break;
320
321		case 'l':
322			logging++;	/* > 1 == extra logging */
323			break;
324
325		case 'M':
326			multihome = 1;
327			break;
328
329		case 'S':
330			stats = 1;
331			break;
332
333		case 't':
334			timeout = atoi(optarg);
335			if (maxtimeout < timeout)
336				maxtimeout = timeout;
337			break;
338
339		case 'T':
340			maxtimeout = atoi(optarg);
341			if (timeout > maxtimeout)
342				timeout = maxtimeout;
343			break;
344
345		case 'u':
346		    {
347			long val = 0;
348			char *p;
349			umaskchange = 0;
350
351			val = strtol(optarg, &p, 8);
352			if (*p != '\0' || val < 0 || (val & ~ACCESSPERMS)) {
353				syslog(LOG_ERR,
354				    "ftpd: %s is a bad value for -u, aborting..",
355				    optarg);
356				exit(2);
357			} else
358				defumask = val;
359			break;
360		    }
361
362		case 'U':
363			doutmp = 1;
364			break;
365
366		case 'v':
367			debug = 1;
368			break;
369
370		case '4':
371			family = AF_INET;
372			break;
373
374		case '6':
375			family = AF_INET6;
376			break;
377
378		default:
379			usage();
380			break;
381		}
382	}
383
384	(void) freopen(_PATH_DEVNULL, "w", stderr);
385
386	/*
387	 * LOG_NDELAY sets up the logging connection immediately,
388	 * necessary for anonymous ftp's that chroot and can't do it later.
389	 */
390	openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
391
392	if (daemon_mode) {
393		int ctl_sock, fd;
394		struct servent *sv;
395
396		/*
397		 * Detach from parent.
398		 */
399		if (daemon(1, 1) < 0) {
400			syslog(LOG_ERR, "failed to become a daemon");
401			exit(1);
402		}
403		(void) signal(SIGCHLD, reapchild);
404		/*
405		 * Get port number for ftp/tcp.
406		 */
407		sv = getservbyname("ftp", "tcp");
408		if (sv == NULL) {
409			syslog(LOG_ERR, "getservbyname for ftp failed");
410			exit(1);
411		}
412		/*
413		 * Open a socket, bind it to the FTP port, and start
414		 * listening.
415		 */
416		ctl_sock = socket(family, SOCK_STREAM, 0);
417		if (ctl_sock < 0) {
418			syslog(LOG_ERR, "control socket: %m");
419			exit(1);
420		}
421		if (setsockopt(ctl_sock, SOL_SOCKET, SO_REUSEADDR,
422		    (char *)&on, sizeof(on)) < 0)
423			syslog(LOG_ERR, "control setsockopt: %m");
424		memset(&server_addr, 0, sizeof(server_addr));
425		server_addr.su_sin.sin_family = family;
426		switch (family) {
427		case AF_INET:
428			server_addr.su_len = sizeof(struct sockaddr_in);
429			server_addr.su_sin.sin_port = sv->s_port;
430			break;
431		case AF_INET6:
432			server_addr.su_len = sizeof(struct sockaddr_in6);
433			server_addr.su_sin6.sin6_port = sv->s_port;
434			break;
435		}
436		if (bind(ctl_sock, (struct sockaddr *)&server_addr,
437			 server_addr.su_len)) {
438			syslog(LOG_ERR, "control bind: %m");
439			exit(1);
440		}
441		if (listen(ctl_sock, 32) < 0) {
442			syslog(LOG_ERR, "control listen: %m");
443			exit(1);
444		}
445		/* Stash pid in pidfile */
446		if ((fp = fopen(_PATH_FTPDPID, "w")) == NULL)
447			syslog(LOG_ERR, "can't open %s: %m", _PATH_FTPDPID);
448		else {
449			fprintf(fp, "%d\n", getpid());
450			fchmod(fileno(fp), S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
451			fclose(fp);
452		}
453		/*
454		 * Loop forever accepting connection requests and forking off
455		 * children to handle them.
456		 */
457		while (1) {
458			addrlen = sizeof(his_addr);
459			fd = accept(ctl_sock, (struct sockaddr *)&his_addr,
460				    &addrlen);
461			if (fork() == 0) {
462				/* child */
463				(void) dup2(fd, 0);
464				(void) dup2(fd, 1);
465				close(ctl_sock);
466				break;
467			}
468			close(fd);
469		}
470
471#if defined(TCPWRAPPERS)
472		/* ..in the child. */
473		if (!check_host((struct sockaddr *)&his_addr))
474			exit(1);
475#endif	/* TCPWRAPPERS */
476	} else {
477		addrlen = sizeof(his_addr);
478		if (getpeername(0, (struct sockaddr *)&his_addr,
479				&addrlen) < 0) {
480			/* syslog(LOG_ERR, "getpeername (%s): %m", argv[0]); */
481			exit(1);
482		}
483	}
484
485	/* set this here so klogin can use it... */
486	(void)snprintf(ttyline, sizeof(ttyline), "ftp%d", getpid());
487
488	(void) signal(SIGHUP, sigquit);
489	(void) signal(SIGINT, sigquit);
490	(void) signal(SIGQUIT, sigquit);
491	(void) signal(SIGTERM, sigquit);
492	(void) signal(SIGPIPE, lostconn);
493	(void) signal(SIGCHLD, SIG_IGN);
494	if (signal(SIGURG, myoob) == SIG_ERR)
495		syslog(LOG_ERR, "signal: %m");
496
497	addrlen = sizeof(ctrl_addr);
498	if (getsockname(0, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) {
499		syslog(LOG_ERR, "getsockname (%s): %m", argv[0]);
500		exit(1);
501	}
502	if (his_addr.su_family == AF_INET6
503	 && IN6_IS_ADDR_V4MAPPED(&his_addr.su_sin6.sin6_addr)) {
504#if 1
505		/*
506		 * IPv4 control connection arrived to AF_INET6 socket.
507		 * I hate to do this, but this is the easiest solution.
508		 */
509		union sockunion tmp_addr;
510		const int off = sizeof(struct in6_addr) - sizeof(struct in_addr);
511
512		tmp_addr = his_addr;
513		memset(&his_addr, 0, sizeof(his_addr));
514		his_addr.su_sin.sin_family = AF_INET;
515		his_addr.su_sin.sin_len = sizeof(his_addr.su_sin);
516		memcpy(&his_addr.su_sin.sin_addr,
517		    &tmp_addr.su_sin6.sin6_addr.s6_addr[off],
518		    sizeof(his_addr.su_sin.sin_addr));
519		his_addr.su_sin.sin_port = tmp_addr.su_sin6.sin6_port;
520
521		tmp_addr = ctrl_addr;
522		memset(&ctrl_addr, 0, sizeof(ctrl_addr));
523		ctrl_addr.su_sin.sin_family = AF_INET;
524		ctrl_addr.su_sin.sin_len = sizeof(ctrl_addr.su_sin);
525		memcpy(&ctrl_addr.su_sin.sin_addr,
526		    &tmp_addr.su_sin6.sin6_addr.s6_addr[off],
527		    sizeof(ctrl_addr.su_sin.sin_addr));
528		ctrl_addr.su_sin.sin_port = tmp_addr.su_sin6.sin6_port;
529#else
530		while (fgets(line, sizeof(line), fd) != NULL) {
531			if ((cp = strchr(line, '\n')) != NULL)
532				*cp = '\0';
533			lreply(530, "%s", line);
534		}
535		(void) fflush(stdout);
536		(void) fclose(fd);
537		reply(530,
538			"Connection from IPv4 mapped address is not supported.");
539		exit(0);
540#endif
541	}
542#ifdef IP_TOS
543	if (his_addr.su_family == AF_INET) {
544		tos = IPTOS_LOWDELAY;
545		if (setsockopt(0, IPPROTO_IP, IP_TOS, (char *)&tos,
546		    sizeof(int)) < 0)
547			syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
548	}
549#endif
550	data_source.su_port = htons(ntohs(ctrl_addr.su_port) - 1);
551
552	/* Try to handle urgent data inline */
553#ifdef SO_OOBINLINE
554	if (setsockopt(0, SOL_SOCKET, SO_OOBINLINE, (char *)&on, sizeof(on)) < 0)
555		syslog(LOG_ERR, "setsockopt: %m");
556#endif
557
558#ifdef	F_SETOWN
559	if (fcntl(fileno(stdin), F_SETOWN, getpid()) == -1)
560		syslog(LOG_ERR, "fcntl F_SETOWN: %m");
561#endif
562	dolog((struct sockaddr *)&his_addr);
563	/*
564	 * Set up default state
565	 */
566	data = -1;
567	type = TYPE_A;
568	form = FORM_N;
569	stru = STRU_F;
570	mode = MODE_S;
571	tmpline[0] = '\0';
572
573	/* If logins are disabled, print out the message. */
574	if ((fp = fopen(_PATH_NOLOGIN, "r")) != NULL) {
575		while (fgets(line, sizeof(line), fp) != NULL) {
576			if ((cp = strchr(line, '\n')) != NULL)
577				*cp = '\0';
578			lreply(530, "%s", line);
579		}
580		(void) fflush(stdout);
581		(void) fclose(fp);
582		reply(530, "System not available.");
583		exit(0);
584	}
585	if ((fp = fopen(_PATH_FTPWELCOME, "r")) != NULL) {
586		while (fgets(line, sizeof(line), fp) != NULL) {
587			if ((cp = strchr(line, '\n')) != NULL)
588				*cp = '\0';
589			lreply(220, "%s", line);
590		}
591		(void) fflush(stdout);
592		(void) fclose(fp);
593		/* reply(220,) must follow */
594	}
595	(void) gethostname(hostname, sizeof(hostname));
596
597	/* Make sure hostname is fully qualified. */
598	hp = gethostbyname(hostname);
599	if (hp != NULL)
600		strcpy(hostname, hp->h_name);
601
602	if (multihome) {
603		getnameinfo((struct sockaddr *)&ctrl_addr, ctrl_addr.su_len,
604		    dhostname, sizeof(dhostname), NULL, 0, 0);
605	}
606
607	reply(220, "%s FTP server (%s) ready.",
608	    (multihome ? dhostname : hostname), version);
609	(void) setjmp(errcatch);
610	for (;;)
611		(void) yyparse();
612	/* NOTREACHED */
613}
614
615/*
616 * Signal handlers.
617 */
618
619static void
620lostconn(signo)
621	int signo;
622{
623
624	sigprocmask(SIG_BLOCK, &allsigs, NULL);
625	if (debug)
626		syslog(LOG_DEBUG, "lost connection");
627	dologout(1);
628}
629
630static void
631sigquit(signo)
632	int signo;
633{
634
635	sigprocmask(SIG_BLOCK, &allsigs, NULL);
636	syslog(LOG_ERR, "got signal %s", sys_signame[signo]);
637	dologout(1);
638}
639
640/*
641 * Save the result of a getpwnam.  Used for USER command, since
642 * the data returned must not be clobbered by any other command
643 * (e.g., globbing).
644 */
645static struct passwd *
646sgetpwnam(name)
647	char *name;
648{
649	static struct passwd *save;
650	struct passwd *pw;
651
652	if ((pw = getpwnam(name)) == NULL)
653		return (pw);
654	if (save) {
655		memset(save->pw_passwd, 0, strlen(save->pw_passwd));
656		free(save);
657	}
658	save = pw_dup(pw);
659	if (save == NULL) {
660		perror_reply(421, "Local resource failure: malloc");
661		dologout(1);
662		/* NOTREACHED */
663	}
664	return (save);
665}
666
667static int login_attempts;	/* number of failed login attempts */
668static int askpasswd;		/* had user command, ask for passwd */
669static char curname[MAXLOGNAME];	/* current USER name */
670
671/*
672 * USER command.
673 * Sets global passwd pointer pw if named account exists and is acceptable;
674 * sets askpasswd if a PASS command is expected.  If logged in previously,
675 * need to reset state.  If name is "ftp" or "anonymous", the name is not in
676 * _PATH_FTPUSERS, and ftp account exists, set guest and pw, then just return.
677 * If account doesn't exist, ask for passwd anyway.  Otherwise, check user
678 * requesting login privileges.  Disallow anyone who does not have a standard
679 * shell as returned by getusershell().  Disallow anyone mentioned in the file
680 * _PATH_FTPUSERS to allow people such as root and uucp to be avoided.
681 */
682void
683user(name)
684	char *name;
685{
686	char *cp, *shell, *style;
687	char *class = NULL;
688
689	if (logged_in) {
690		if (guest) {
691			reply(530, "Can't change user from guest login.");
692			return;
693		} else if (dochroot) {
694			reply(530, "Can't change user from chroot user.");
695			return;
696		}
697		login_close(lc);
698		lc = NULL;
699		if (as) {
700			auth_close(as);
701			as = NULL;
702		}
703		end_login();
704	}
705
706	if ((style = strchr(name, ':')) != NULL)
707		*style++ = 0;
708
709	guest = 0;
710	if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) {
711		if (checkuser(_PATH_FTPUSERS, "ftp") ||
712		    checkuser(_PATH_FTPUSERS, "anonymous"))
713			reply(530, "User %s access denied.", name);
714		else if ((pw = sgetpwnam("ftp")) != NULL) {
715			guest = 1;
716			askpasswd = 1;
717			lc = login_getclass(pw->pw_class);
718			reply(331,
719			"Guest login ok, send your email address as password.");
720		} else
721			reply(530, "User %s unknown.", name);
722		if (!askpasswd && logging)
723			syslog(LOG_NOTICE,
724			    "ANONYMOUS FTP LOGIN REFUSED FROM %s", remotehost);
725		return;
726	}
727
728	shell = _PATH_BSHELL;
729	if ((pw = sgetpwnam(name))) {
730		class = pw->pw_class;
731		if (pw->pw_shell != NULL && *pw->pw_shell != '\0')
732			shell = pw->pw_shell;
733		while ((cp = getusershell()) != NULL)
734			if (strcmp(cp, shell) == 0)
735				break;
736		shell = cp;
737		endusershell();
738	}
739
740	/* Get login class; if invalid style treat like unknown user. */
741	lc = login_getclass(class);
742	if (lc && (style = login_getstyle(lc, style, "auth-ftp")) == NULL) {
743		login_close(lc);
744		lc = NULL;
745		pw = NULL;
746	}
747
748	/* Do pre-authentication setup. */
749	if (lc && ((as = auth_open()) == NULL ||
750	    auth_setitem(as, AUTHV_STYLE, style) < 0 ||
751	    auth_setitem(as, AUTHV_NAME, name) < 0 ||
752	    auth_setitem(as, AUTHV_CLASS, class)) < 0) {
753		if (as) {
754			auth_close(as);
755			as = NULL;
756		}
757		login_close(lc);
758		lc = NULL;
759		reply(421, "Local resource failure");
760		return;
761	}
762	if (logging)
763		strlcpy(curname, name, sizeof(curname));
764
765	dochroot = (lc && login_getcapbool(lc, "ftp-chroot", 0)) ||
766	    checkuser(_PATH_FTPCHROOT, name);
767	if (anon_only && !dochroot) {
768		reply(530, "Sorry, only anonymous ftp allowed.");
769		return;
770	}
771	if (pw) {
772		if ((!shell && !dochroot) || checkuser(_PATH_FTPUSERS, name)) {
773			reply(530, "User %s access denied.", name);
774			if (logging)
775				syslog(LOG_NOTICE,
776				    "FTP LOGIN REFUSED FROM %s, %s",
777				    remotehost, name);
778			pw = NULL;
779			return;
780		}
781	}
782
783	if (as != NULL && (cp = auth_challenge(as)) != NULL)
784		reply(331, cp);
785	else
786		reply(331, "Password required for %s.", name);
787
788	askpasswd = 1;
789	/*
790	 * Delay before reading passwd after first failed
791	 * attempt to slow down passwd-guessing programs.
792	 */
793	if (login_attempts)
794		sleep((unsigned) login_attempts);
795}
796
797/*
798 * Check if a user is in the file "fname"
799 */
800static int
801checkuser(fname, name)
802	char *fname;
803	char *name;
804{
805	FILE *fp;
806	int found = 0;
807	char *p, line[BUFSIZ];
808
809	if ((fp = fopen(fname, "r")) != NULL) {
810		while (fgets(line, sizeof(line), fp) != NULL)
811			if ((p = strchr(line, '\n')) != NULL) {
812				*p = '\0';
813				if (line[0] == '#')
814					continue;
815				if (strcmp(line, name) == 0) {
816					found = 1;
817					break;
818				}
819			}
820		(void) fclose(fp);
821	}
822	return (found);
823}
824
825/*
826 * Terminate login as previous user, if any, resetting state;
827 * used when USER command is given or login fails.
828 */
829static void
830end_login()
831{
832
833	sigprocmask (SIG_BLOCK, &allsigs, NULL);
834	(void) seteuid((uid_t)0);
835	if (logged_in) {
836		ftpdlogwtmp(ttyline, "", "");
837		if (doutmp)
838			logout(utmp.ut_line);
839	}
840	pw = NULL;
841	/* umask is restored in ftpcmd.y */
842	setusercontext(NULL, getpwuid(0), (uid_t)0,
843	    LOGIN_SETPRIORITY|LOGIN_SETRESOURCES);
844	logged_in = 0;
845	guest = 0;
846	dochroot = 0;
847}
848
849void
850pass(passwd)
851	char *passwd;
852{
853	int authok, flags;
854	FILE *fp;
855	static char homedir[MAXPATHLEN];
856	char *dir, rootdir[MAXPATHLEN];
857
858	if (logged_in || askpasswd == 0) {
859		reply(503, "Login with USER first.");
860		return;
861	}
862	askpasswd = 0;
863	if (!guest) {		/* "ftp" is only account allowed no password */
864		authok = 0;
865		if (pw == NULL) {
866			useconds_t us;
867
868			/* Sleep between 1 and 3 seconds to emulate a crypt. */
869			us = arc4random() % 3000000;
870			usleep(us);
871		} else {
872			authok = auth_userresponse(as, passwd, 0);
873			auth_close(as);
874			as = NULL;
875		}
876		if (authok == 0) {
877			reply(530, "Login incorrect.");
878			if (logging)
879				syslog(LOG_NOTICE,
880				    "FTP LOGIN FAILED FROM %s, %s",
881				    remotehost, curname);
882			pw = NULL;
883			if (login_attempts++ >= 5) {
884				syslog(LOG_NOTICE,
885				    "repeated login failures from %s",
886				    remotehost);
887				exit(0);
888			}
889			return;
890		}
891	} else if (lc != NULL) {
892		/* Save anonymous' password. */
893		guestpw = strdup(passwd);
894		if (guestpw == (char *)NULL)
895			fatal("Out of memory");
896
897		if ((as = auth_open()) == NULL)
898			fatal("Out of memory");
899		auth_setoption(as, "FTPD_HOST",
900		    multihome ? dhostname : hostname);
901		authok = auth_approval(as, lc, pw->pw_name, "ftp");
902		auth_close(as);
903		as = NULL;
904		if (authok == 0) {
905			syslog(LOG_INFO|LOG_AUTH,
906			    "FTP LOGIN FAILED (HOST) as %s: approval failure.",
907			    pw->pw_name);
908			reply(530, "Approval failure.\n");
909			exit(0);
910		}
911	} else {
912		syslog(LOG_INFO|LOG_AUTH,
913		    "FTP LOGIN CLASS %s MISSING for %s: approval failure.",
914		    pw->pw_class, pw->pw_name);
915		reply(530, "Permission denied.\n");
916		exit(0);
917	}
918	login_attempts = 0;		/* this time successful */
919	if (setegid((gid_t)pw->pw_gid) < 0) {
920		reply(550, "Can't set gid.");
921		return;
922	}
923	/* set umask via setusercontext() unless -u flag was given. */
924	flags = LOGIN_SETGROUP|LOGIN_SETPRIORITY|LOGIN_SETRESOURCES;
925	if (umaskchange)
926		flags |= LOGIN_SETUMASK;
927	else
928		(void) umask(defumask);
929	setusercontext(lc, pw, (uid_t)0, flags);
930
931	/* open wtmp before chroot */
932	ftpdlogwtmp(ttyline, pw->pw_name, remotehost);
933
934	/* open utmp before chroot */
935	if (doutmp) {
936		memset((void *)&utmp, 0, sizeof(utmp));
937		(void)time(&utmp.ut_time);
938		(void)strncpy(utmp.ut_name, pw->pw_name, sizeof(utmp.ut_name));
939		(void)strncpy(utmp.ut_host, remotehost, sizeof(utmp.ut_host));
940		(void)strncpy(utmp.ut_line, ttyline, sizeof(utmp.ut_line));
941		login(&utmp);
942	}
943
944	/* open stats file before chroot */
945	if (guest && (stats == 1) && (statfd < 0))
946		if ((statfd = open(_PATH_FTPDSTATFILE, O_WRONLY|O_APPEND)) < 0)
947			stats = 0;
948
949	logged_in = 1;
950
951	if ((dir = login_getcapstr(lc, "ftp-dir", NULL, NULL))) {
952		char *newdir;
953
954		newdir = copy_dir(dir, pw);
955		if (newdir == NULL) {
956			perror_reply(421, "Local resource failure: malloc");
957			dologout(1);
958			/* NOTREACHED */
959		}
960		free(pw->pw_dir);
961		pw->pw_dir = newdir;
962	}
963	if (guest || dochroot) {
964		if (multihome && guest) {
965			struct stat ts;
966
967			/* Compute root directory. */
968			snprintf(rootdir, sizeof(rootdir), "%s/%s",
969				  pw->pw_dir, dhostname);
970			if (stat(rootdir, &ts) < 0) {
971				snprintf(rootdir, sizeof(rootdir), "%s/%s",
972					  pw->pw_dir, hostname);
973			}
974		} else
975			strcpy(rootdir, pw->pw_dir);
976	}
977	if (guest) {
978		/*
979		 * We MUST do a chdir() after the chroot. Otherwise
980		 * the old current directory will be accessible as "."
981		 * outside the new root!
982		 */
983		if (chroot(rootdir) < 0 || chdir("/") < 0) {
984			reply(550, "Can't set guest privileges.");
985			goto bad;
986		}
987		strcpy(pw->pw_dir, "/");
988		if (setenv("HOME", "/", 1) == -1) {
989			reply(550, "Can't setup environment.");
990			goto bad;
991		}
992	} else if (dochroot) {
993		if (chroot(rootdir) < 0 || chdir("/") < 0) {
994			reply(550, "Can't change root.");
995			goto bad;
996		}
997		strcpy(pw->pw_dir, "/");
998		if (setenv("HOME", "/", 1) == -1) {
999			reply(550, "Can't setup environment.");
1000			goto bad;
1001		}
1002	} else if (chdir(pw->pw_dir) < 0) {
1003		if (chdir("/") < 0) {
1004			reply(530, "User %s: can't change directory to %s.",
1005			    pw->pw_name, pw->pw_dir);
1006			goto bad;
1007		} else
1008			lreply(230, "No directory! Logging in with home=/");
1009	}
1010	if (seteuid((uid_t)pw->pw_uid) < 0) {
1011		reply(550, "Can't set uid.");
1012		goto bad;
1013	}
1014	sigprocmask(SIG_UNBLOCK, &allsigs, NULL);
1015
1016	/*
1017	 * Set home directory so that use of ~ (tilde) works correctly.
1018	 */
1019	if (getcwd(homedir, MAXPATHLEN) != NULL) {
1020		if (setenv("HOME", homedir, 1) == -1) {
1021			reply(550, "Can't setup environment.");
1022			goto bad;
1023		}
1024	}
1025
1026	/*
1027	 * Display a login message, if it exists.
1028	 * N.B. reply(230,) must follow the message.
1029	 */
1030	if ((fp = fopen(_PATH_FTPLOGINMESG, "r")) != NULL) {
1031		char *cp, line[LINE_MAX];
1032
1033		while (fgets(line, sizeof(line), fp) != NULL) {
1034			if ((cp = strchr(line, '\n')) != NULL)
1035				*cp = '\0';
1036			lreply(230, "%s", line);
1037		}
1038		(void) fflush(stdout);
1039		(void) fclose(fp);
1040	}
1041	if (guest) {
1042		if (ident != NULL)
1043			free(ident);
1044		ident = strdup(passwd);
1045		if (ident == NULL)
1046			fatal("Ran out of memory.");
1047		reply(230, "Guest login ok, access restrictions apply.");
1048#ifdef HASSETPROCTITLE
1049		snprintf(proctitle, sizeof(proctitle),
1050		    "%s: anonymous/%.*s", remotehost,
1051		    (int)(sizeof(proctitle) - sizeof(remotehost) -
1052		    sizeof(": anonymous/")), passwd);
1053		setproctitle("%s", proctitle);
1054#endif /* HASSETPROCTITLE */
1055		if (logging)
1056			syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s, %s",
1057			    remotehost, passwd);
1058	} else {
1059		reply(230, "User %s logged in.", pw->pw_name);
1060#ifdef HASSETPROCTITLE
1061		snprintf(proctitle, sizeof(proctitle),
1062		    "%s: %s", remotehost, pw->pw_name);
1063		setproctitle("%s", proctitle);
1064#endif /* HASSETPROCTITLE */
1065		if (logging)
1066			syslog(LOG_INFO, "FTP LOGIN FROM %s as %s",
1067			    remotehost, pw->pw_name);
1068	}
1069	login_close(lc);
1070	lc = NULL;
1071	return;
1072bad:
1073	/* Forget all about it... */
1074	login_close(lc);
1075	lc = NULL;
1076	end_login();
1077}
1078
1079void
1080retrieve(cmd, name)
1081	char *cmd, *name;
1082{
1083	FILE *fin, *dout;
1084	struct stat st;
1085	int (*closefunc) __P((FILE *));
1086	time_t start;
1087
1088	if (cmd == 0) {
1089		fin = fopen(name, "r"), closefunc = fclose;
1090		st.st_size = 0;
1091	} else {
1092		char line[BUFSIZ];
1093
1094		(void) snprintf(line, sizeof(line), cmd, name);
1095		name = line;
1096		fin = ftpd_popen(line, "r"), closefunc = ftpd_pclose;
1097		st.st_size = -1;
1098		st.st_blksize = BUFSIZ;
1099	}
1100	if (fin == NULL) {
1101		if (errno != 0) {
1102			perror_reply(550, name);
1103			if (cmd == 0) {
1104				LOGCMD("get", name);
1105			}
1106		}
1107		return;
1108	}
1109	byte_count = -1;
1110	if (cmd == 0 && (fstat(fileno(fin), &st) < 0 || !S_ISREG(st.st_mode))) {
1111		reply(550, "%s: not a plain file.", name);
1112		goto done;
1113	}
1114	if (restart_point) {
1115		if (type == TYPE_A) {
1116			off_t i, n;
1117			int c;
1118
1119			n = restart_point;
1120			i = 0;
1121			while (i++ < n) {
1122				if ((c=getc(fin)) == EOF) {
1123					perror_reply(550, name);
1124					goto done;
1125				}
1126				if (c == '\n')
1127					i++;
1128			}
1129		} else if (lseek(fileno(fin), restart_point, SEEK_SET) < 0) {
1130			perror_reply(550, name);
1131			goto done;
1132		}
1133	}
1134	dout = dataconn(name, st.st_size, "w");
1135	if (dout == NULL)
1136		goto done;
1137	time(&start);
1138	send_data(fin, dout, st.st_blksize, st.st_size,
1139		  (restart_point == 0 && cmd == 0 && S_ISREG(st.st_mode)));
1140	if ((cmd == 0) && stats)
1141		logxfer(name, byte_count, start);
1142	(void) fclose(dout);
1143	data = -1;
1144done:
1145	if (pdata >= 0)
1146		(void) close(pdata);
1147	pdata = -1;
1148	if (cmd == 0)
1149		LOGBYTES("get", name, byte_count);
1150	(*closefunc)(fin);
1151}
1152
1153void
1154store(name, mode, unique)
1155	char *name, *mode;
1156	int unique;
1157{
1158	FILE *fout, *din;
1159	int (*closefunc) __P((FILE *));
1160	struct stat st;
1161	int fd;
1162
1163	if (restart_point && *mode != 'a')
1164		mode = "r+";
1165
1166	if (unique && stat(name, &st) == 0) {
1167		char *nam;
1168
1169		fd = guniquefd(name, &nam);
1170		if (fd == -1) {
1171			LOGCMD(*mode == 'w' ? "put" : "append", name);
1172			return;
1173		}
1174		name = nam;
1175		fout = fdopen(fd, mode);
1176	} else
1177		fout = fopen(name, mode);
1178
1179	closefunc = fclose;
1180	if (fout == NULL) {
1181		perror_reply(553, name);
1182		LOGCMD(*mode == 'w' ? "put" : "append", name);
1183		return;
1184	}
1185	byte_count = -1;
1186	if (restart_point) {
1187		if (type == TYPE_A) {
1188			off_t i, n;
1189			int c;
1190
1191			n = restart_point;
1192			i = 0;
1193			while (i++ < n) {
1194				if ((c=getc(fout)) == EOF) {
1195					perror_reply(550, name);
1196					goto done;
1197				}
1198				if (c == '\n')
1199					i++;
1200			}
1201			/*
1202			 * We must do this seek to "current" position
1203			 * because we are changing from reading to
1204			 * writing.
1205			 */
1206			if (fseek(fout, 0L, SEEK_CUR) < 0) {
1207				perror_reply(550, name);
1208				goto done;
1209			}
1210		} else if (lseek(fileno(fout), restart_point, SEEK_SET) < 0) {
1211			perror_reply(550, name);
1212			goto done;
1213		}
1214	}
1215	din = dataconn(name, (off_t)-1, "r");
1216	if (din == NULL)
1217		goto done;
1218	if (receive_data(din, fout) == 0) {
1219		if (unique)
1220			reply(226, "Transfer complete (unique file name:%s).",
1221			    name);
1222		else
1223			reply(226, "Transfer complete.");
1224	}
1225	(void) fclose(din);
1226	data = -1;
1227	pdata = -1;
1228done:
1229	LOGBYTES(*mode == 'w' ? "put" : "append", name, byte_count);
1230	(*closefunc)(fout);
1231}
1232
1233static FILE *
1234getdatasock(mode)
1235	char *mode;
1236{
1237	int on = 1, s, t, tries;
1238
1239	if (data >= 0)
1240		return (fdopen(data, mode));
1241	sigprocmask (SIG_BLOCK, &allsigs, NULL);
1242	(void) seteuid((uid_t)0);
1243	s = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
1244	if (s < 0)
1245		goto bad;
1246	if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
1247	    (char *) &on, sizeof(on)) < 0)
1248		goto bad;
1249	/* anchor socket to avoid multi-homing problems */
1250	data_source = ctrl_addr;
1251	data_source.su_port = htons(20); /* ftp-data port */
1252	for (tries = 1; ; tries++) {
1253		if (bind(s, (struct sockaddr *)&data_source,
1254		    data_source.su_len) >= 0)
1255			break;
1256		if (errno != EADDRINUSE || tries > 10)
1257			goto bad;
1258		sleep(tries);
1259	}
1260	(void) seteuid((uid_t)pw->pw_uid);
1261	sigprocmask (SIG_UNBLOCK, &allsigs, NULL);
1262
1263#ifdef IP_TOS
1264	if (ctrl_addr.su_family == AF_INET) {
1265		on = IPTOS_THROUGHPUT;
1266		if (setsockopt(s, IPPROTO_IP, IP_TOS, (char *)&on,
1267		    sizeof(int)) < 0)
1268			syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
1269	}
1270#endif
1271#ifdef TCP_NOPUSH
1272	/*
1273	 * Turn off push flag to keep sender TCP from sending short packets
1274	 * at the boundaries of each write().  Should probably do a SO_SNDBUF
1275	 * to set the send buffer size as well, but that may not be desirable
1276	 * in heavy-load situations.
1277	 */
1278	on = 1;
1279	if (setsockopt(s, IPPROTO_TCP, TCP_NOPUSH, (char *)&on, sizeof(on)) < 0)
1280		syslog(LOG_WARNING, "setsockopt (TCP_NOPUSH): %m");
1281#endif
1282#ifdef SO_SNDBUF
1283	on = 65536;
1284	if (setsockopt(s, SOL_SOCKET, SO_SNDBUF, (char *)&on, sizeof(on)) < 0)
1285		syslog(LOG_WARNING, "setsockopt (SO_SNDBUF): %m");
1286#endif
1287
1288	return (fdopen(s, mode));
1289bad:
1290	/* Return the real value of errno (close may change it) */
1291	t = errno;
1292	(void) seteuid((uid_t)pw->pw_uid);
1293	sigprocmask (SIG_UNBLOCK, &allsigs, NULL);
1294	(void) close(s);
1295	errno = t;
1296	return (NULL);
1297}
1298
1299static FILE *
1300dataconn(name, size, mode)
1301	char *name;
1302	off_t size;
1303	char *mode;
1304{
1305	char sizebuf[32];
1306	FILE *file;
1307	int retry = 0;
1308	in_port_t *p;
1309	char *fa, *ha;
1310	int alen;
1311
1312	file_size = size;
1313	byte_count = 0;
1314	if (size != (off_t) -1) {
1315		(void) snprintf(sizebuf, sizeof(sizebuf), " (%qd bytes)",
1316				size);
1317	} else
1318		sizebuf[0] = '\0';
1319	if (pdata >= 0) {
1320		union sockunion from;
1321		int s, fromlen = sizeof(from);
1322
1323		signal (SIGALRM, toolong);
1324		(void) alarm ((unsigned) timeout);
1325		s = accept(pdata, (struct sockaddr *)&from, &fromlen);
1326		(void) alarm (0);
1327		if (s < 0) {
1328			reply(425, "Can't open data connection.");
1329			(void) close(pdata);
1330			pdata = -1;
1331			return (NULL);
1332		}
1333		switch (from.su_family) {
1334		case AF_INET:
1335			p = (in_port_t *)&from.su_sin.sin_port;
1336			fa = (u_char *)&from.su_sin.sin_addr;
1337			ha = (u_char *)&his_addr.su_sin.sin_addr;
1338			alen = sizeof(struct in_addr);
1339			break;
1340		case AF_INET6:
1341			p = (in_port_t *)&from.su_sin6.sin6_port;
1342			fa = (u_char *)&from.su_sin6.sin6_addr;
1343			ha = (u_char *)&his_addr.su_sin6.sin6_addr;
1344			alen = sizeof(struct in6_addr);
1345			break;
1346		default:
1347			perror_reply(425, "Can't build data connection");
1348			(void) close(pdata);
1349			(void) close(s);
1350			pdata = -1;
1351			return (NULL);
1352		}
1353		if (from.su_family != his_addr.su_family ||
1354		    ntohs(*p) < IPPORT_RESERVED) {
1355			perror_reply(425, "Can't build data connection");
1356			(void) close(pdata);
1357			(void) close(s);
1358			pdata = -1;
1359			return (NULL);
1360		}
1361		if (portcheck && memcmp(fa, ha, alen) != 0) {
1362			perror_reply(435, "Can't build data connection");
1363			(void) close(pdata);
1364			(void) close(s);
1365			pdata = -1;
1366			return (NULL);
1367		}
1368		(void) close(pdata);
1369		pdata = s;
1370		reply(150, "Opening %s mode data connection for '%s'%s.",
1371		    type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1372		return (fdopen(pdata, mode));
1373	}
1374	if (data >= 0) {
1375		reply(125, "Using existing data connection for '%s'%s.",
1376		    name, sizebuf);
1377		usedefault = 1;
1378		return (fdopen(data, mode));
1379	}
1380	if (usedefault)
1381		data_dest = his_addr;
1382	usedefault = 1;
1383	file = getdatasock(mode);
1384	if (file == NULL) {
1385		char hbuf[MAXHOSTNAMELEN], pbuf[10];
1386
1387		getnameinfo((struct sockaddr *)&data_source, data_source.su_len,
1388		    hbuf, sizeof(hbuf), pbuf, sizeof(pbuf),
1389		    NI_NUMERICHOST | NI_NUMERICSERV);
1390		reply(425, "Can't create data socket (%s,%s): %s.",
1391		    hbuf, pbuf, strerror(errno));
1392		return (NULL);
1393	}
1394	data = fileno(file);
1395
1396	/*
1397	 * attempt to connect to reserved port on client machine;
1398	 * this looks like an attack
1399	 */
1400	switch (data_dest.su_family) {
1401	case AF_INET:
1402		p = (in_port_t *)&data_dest.su_sin.sin_port;
1403		fa = (u_char *)&data_dest.su_sin.sin_addr;
1404		ha = (u_char *)&his_addr.su_sin.sin_addr;
1405		alen = sizeof(struct in_addr);
1406		break;
1407	case AF_INET6:
1408		p = (in_port_t *)&data_dest.su_sin6.sin6_port;
1409		fa = (u_char *)&data_dest.su_sin6.sin6_addr;
1410		ha = (u_char *)&his_addr.su_sin6.sin6_addr;
1411		alen = sizeof(struct in6_addr);
1412		break;
1413	default:
1414		perror_reply(425, "Can't build data connection");
1415		(void) fclose(file);
1416		pdata = -1;
1417		return (NULL);
1418	}
1419	if (data_dest.su_family != his_addr.su_family ||
1420	    ntohs(*p) < IPPORT_RESERVED || ntohs(*p) == 2049) {	/* XXX */
1421		perror_reply(425, "Can't build data connection");
1422		(void) fclose(file);
1423		data = -1;
1424		return NULL;
1425	}
1426	if (portcheck && memcmp(fa, ha, alen) != 0) {
1427		perror_reply(435, "Can't build data connection");
1428		(void) fclose(file);
1429		data = -1;
1430		return NULL;
1431	}
1432	while (connect(data, (struct sockaddr *)&data_dest,
1433	    data_dest.su_len) < 0) {
1434		if (errno == EADDRINUSE && retry < swaitmax) {
1435			sleep((unsigned) swaitint);
1436			retry += swaitint;
1437			continue;
1438		}
1439		perror_reply(425, "Can't build data connection");
1440		(void) fclose(file);
1441		data = -1;
1442		return (NULL);
1443	}
1444	reply(150, "Opening %s mode data connection for '%s'%s.",
1445	    type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1446	return (file);
1447}
1448
1449/*
1450 * Tranfer the contents of "instr" to "outstr" peer using the appropriate
1451 * encapsulation of the data subject to Mode, Structure, and Type.
1452 *
1453 * NB: Form isn't handled.
1454 */
1455static void
1456send_data(instr, outstr, blksize, filesize, isreg)
1457	FILE *instr, *outstr;
1458	off_t blksize;
1459	off_t filesize;
1460	int isreg;
1461{
1462	int c, cnt, filefd, netfd;
1463	char *buf, *bp;
1464	size_t len;
1465
1466	transflag++;
1467	if (setjmp(urgcatch)) {
1468		transflag = 0;
1469		return;
1470	}
1471	switch (type) {
1472
1473	case TYPE_A:
1474		while ((c = getc(instr)) != EOF) {
1475			byte_count++;
1476			if (c == '\n') {
1477				if (ferror(outstr))
1478					goto data_err;
1479				(void) putc('\r', outstr);
1480			}
1481			(void) putc(c, outstr);
1482		}
1483		fflush(outstr);
1484		transflag = 0;
1485		if (ferror(instr))
1486			goto file_err;
1487		if (ferror(outstr))
1488			goto data_err;
1489		reply(226, "Transfer complete.");
1490		return;
1491
1492	case TYPE_I:
1493	case TYPE_L:
1494		/*
1495		 * isreg is only set if we are not doing restart and we
1496		 * are sending a regular file
1497		 */
1498		netfd = fileno(outstr);
1499		filefd = fileno(instr);
1500
1501		if (isreg && filesize < (off_t)16 * 1024 * 1024) {
1502			buf = mmap(0, filesize, PROT_READ, MAP_SHARED, filefd,
1503				   (off_t)0);
1504			if (buf == MAP_FAILED) {
1505				syslog(LOG_WARNING, "mmap(%lu): %m",
1506				    (unsigned long)filesize);
1507				goto oldway;
1508			}
1509			bp = buf;
1510			len = filesize;
1511			do {
1512				cnt = write(netfd, bp, len);
1513				len -= cnt;
1514				bp += cnt;
1515				if (cnt > 0) byte_count += cnt;
1516			} while(cnt > 0 && len > 0);
1517
1518			transflag = 0;
1519			munmap(buf, (size_t)filesize);
1520			if (cnt < 0)
1521				goto data_err;
1522			reply(226, "Transfer complete.");
1523			return;
1524		}
1525
1526oldway:
1527		if ((buf = malloc((u_int)blksize)) == NULL) {
1528			transflag = 0;
1529			perror_reply(451, "Local resource failure: malloc");
1530			return;
1531		}
1532
1533		while ((cnt = read(filefd, buf, (u_int)blksize)) > 0 &&
1534		    write(netfd, buf, cnt) == cnt)
1535			byte_count += cnt;
1536		transflag = 0;
1537		(void)free(buf);
1538		if (cnt != 0) {
1539			if (cnt < 0)
1540				goto file_err;
1541			goto data_err;
1542		}
1543		reply(226, "Transfer complete.");
1544		return;
1545	default:
1546		transflag = 0;
1547		reply(550, "Unimplemented TYPE %d in send_data", type);
1548		return;
1549	}
1550
1551data_err:
1552	transflag = 0;
1553	perror_reply(426, "Data connection");
1554	return;
1555
1556file_err:
1557	transflag = 0;
1558	perror_reply(551, "Error on input file");
1559}
1560
1561/*
1562 * Transfer data from peer to "outstr" using the appropriate encapulation of
1563 * the data subject to Mode, Structure, and Type.
1564 *
1565 * N.B.: Form isn't handled.
1566 */
1567static int
1568receive_data(instr, outstr)
1569	FILE *instr, *outstr;
1570{
1571	int c;
1572	int cnt, bare_lfs = 0;
1573	char buf[BUFSIZ];
1574
1575	transflag++;
1576	if (setjmp(urgcatch)) {
1577		transflag = 0;
1578		return (-1);
1579	}
1580	switch (type) {
1581
1582	case TYPE_I:
1583	case TYPE_L:
1584		signal (SIGALRM, lostconn);
1585
1586		do {
1587			(void) alarm ((unsigned) timeout);
1588			cnt = read(fileno(instr), buf, sizeof(buf));
1589			(void) alarm (0);
1590
1591			if (cnt > 0) {
1592				if (write(fileno(outstr), buf, cnt) != cnt)
1593					goto file_err;
1594				byte_count += cnt;
1595			}
1596		} while (cnt > 0);
1597		if (cnt < 0)
1598			goto data_err;
1599		transflag = 0;
1600		return (0);
1601
1602	case TYPE_E:
1603		reply(553, "TYPE E not implemented.");
1604		transflag = 0;
1605		return (-1);
1606
1607	case TYPE_A:
1608		while ((c = getc(instr)) != EOF) {
1609			byte_count++;
1610			if (c == '\n')
1611				bare_lfs++;
1612			while (c == '\r') {
1613				if (ferror(outstr))
1614					goto data_err;
1615				if ((c = getc(instr)) != '\n') {
1616					(void) putc ('\r', outstr);
1617					if (c == '\0' || c == EOF)
1618						goto contin2;
1619				}
1620			}
1621			(void) putc(c, outstr);
1622	contin2:	;
1623		}
1624		fflush(outstr);
1625		if (ferror(instr))
1626			goto data_err;
1627		if (ferror(outstr))
1628			goto file_err;
1629		transflag = 0;
1630		if (bare_lfs) {
1631			lreply(226,
1632			    "WARNING! %d bare linefeeds received in ASCII mode",
1633			    bare_lfs);
1634			printf("   File may not have transferred correctly.\r\n");
1635		}
1636		return (0);
1637	default:
1638		reply(550, "Unimplemented TYPE %d in receive_data", type);
1639		transflag = 0;
1640		return (-1);
1641	}
1642
1643data_err:
1644	transflag = 0;
1645	perror_reply(426, "Data Connection");
1646	return (-1);
1647
1648file_err:
1649	transflag = 0;
1650	perror_reply(452, "Error writing file");
1651	return (-1);
1652}
1653
1654void
1655statfilecmd(filename)
1656	char *filename;
1657{
1658	FILE *fin;
1659	int c;
1660	int atstart;
1661	char line[LINE_MAX];
1662
1663	(void)snprintf(line, sizeof(line), "/bin/ls -lgA %s", filename);
1664	fin = ftpd_popen(line, "r");
1665	lreply(211, "status of %s:", filename);
1666	atstart = 1;
1667	while ((c = getc(fin)) != EOF) {
1668		if (c == '\n') {
1669			if (ferror(stdout)){
1670				perror_reply(421, "control connection");
1671				(void) ftpd_pclose(fin);
1672				dologout(1);
1673				/* NOTREACHED */
1674			}
1675			if (ferror(fin)) {
1676				perror_reply(551, filename);
1677				(void) ftpd_pclose(fin);
1678				return;
1679			}
1680			(void) putc('\r', stdout);
1681		}
1682		if (atstart && isdigit(c))
1683			(void) putc(' ', stdout);
1684		(void) putc(c, stdout);
1685		atstart = (c == '\n');
1686	}
1687	(void) ftpd_pclose(fin);
1688	reply(211, "End of Status");
1689}
1690
1691void
1692statcmd()
1693{
1694	union sockunion *su;
1695	u_char *a, *p;
1696	char hbuf[MAXHOSTNAMELEN];
1697	int ispassive;
1698
1699	lreply(211, "%s FTP server status:", hostname, version);
1700	printf("     %s\r\n", version);
1701	getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
1702	    hbuf, sizeof(hbuf), NULL, 0, NI_NUMERICHOST);
1703	printf("     Connected to %s", remotehost);
1704	if (strcmp(remotehost, hbuf) != 0)
1705		printf(" (%s)", hbuf);
1706	printf("\r\n");
1707	if (logged_in) {
1708		if (guest)
1709			printf("     Logged in anonymously\r\n");
1710		else
1711			printf("     Logged in as %s\r\n", pw->pw_name);
1712	} else if (askpasswd)
1713		printf("     Waiting for password\r\n");
1714	else
1715		printf("     Waiting for user name\r\n");
1716	printf("     TYPE: %s", typenames[type]);
1717	if (type == TYPE_A || type == TYPE_E)
1718		printf(", FORM: %s", formnames[form]);
1719	if (type == TYPE_L)
1720#if NBBY == 8
1721		printf(" %d", NBBY);
1722#else
1723		printf(" %d", bytesize);	/* need definition! */
1724#endif
1725	printf("; STRUcture: %s; transfer MODE: %s\r\n",
1726	    strunames[stru], modenames[mode]);
1727	ispassive = 0;
1728	if (data != -1)
1729		printf("     Data connection open\r\n");
1730	else if (pdata != -1) {
1731		printf("     in Passive mode\r\n");
1732		su = (union sockunion *)&pasv_addr;
1733		ispassive++;
1734		goto printaddr;
1735	} else if (usedefault == 0) {
1736		su = (union sockunion *)&data_dest;
1737printaddr:
1738		/* PASV/PORT */
1739		if (su->su_family == AF_INET) {
1740			if (ispassive)
1741				printf("211- PASV ");
1742			else
1743				printf("211- PORT ");
1744			a = (u_char *) &su->su_sin.sin_addr;
1745			p = (u_char *) &su->su_sin.sin_port;
1746			printf("(%u,%u,%u,%u,%u,%u)\r\n",
1747			    a[0], a[1], a[2], a[3],
1748			    p[0], p[1]);
1749		}
1750
1751		/* LPSV/LPRT */
1752	    {
1753		int alen, af, i;
1754
1755		alen = 0;
1756		switch (su->su_family) {
1757		case AF_INET:
1758			a = (u_char *) &su->su_sin.sin_addr;
1759			p = (u_char *) &su->su_sin.sin_port;
1760			alen = sizeof(su->su_sin.sin_addr);
1761			af = 4;
1762			break;
1763		case AF_INET6:
1764			a = (u_char *) &su->su_sin6.sin6_addr;
1765			p = (u_char *) &su->su_sin6.sin6_port;
1766			alen = sizeof(su->su_sin6.sin6_addr);
1767			af = 6;
1768			break;
1769		default:
1770			af = 0;
1771			break;
1772		}
1773		if (af) {
1774			if (ispassive)
1775				printf("211- LPSV ");
1776			else
1777				printf("211- LPRT ");
1778			printf("(%u,%u", af, alen);
1779			for (i = 0; i < alen; i++)
1780				printf(",%u", a[i]);
1781			printf(",%u,%u,%u)\r\n", 2, p[0], p[1]);
1782		}
1783	    }
1784
1785		/* EPRT/EPSV */
1786epsvonly:
1787	    {
1788		u_char af;
1789
1790		switch (su->su_family) {
1791		case AF_INET:
1792			af = 1;
1793			break;
1794		case AF_INET6:
1795			af = 2;
1796			break;
1797		default:
1798			af = 0;
1799			break;
1800		}
1801		if (af) {
1802			char hbuf[MAXHOSTNAMELEN], pbuf[10];
1803			if (getnameinfo((struct sockaddr *)su, su->su_len,
1804			    hbuf, sizeof(hbuf), pbuf, sizeof(pbuf),
1805			    NI_NUMERICHOST) == 0) {
1806				if (ispassive)
1807					printf("211- EPSV ");
1808				else
1809					printf("211- EPRT ");
1810				printf("(|%u|%s|%s|)\r\n",
1811					af, hbuf, pbuf);
1812			}
1813		}
1814	    }
1815	} else
1816		printf("     No data connection\r\n");
1817	reply(211, "End of status");
1818}
1819
1820void
1821fatal(s)
1822	char *s;
1823{
1824
1825	reply(451, "Error in server: %s\n", s);
1826	reply(221, "Closing connection due to server error.");
1827	dologout(0);
1828	/* NOTREACHED */
1829}
1830
1831void
1832#ifdef __STDC__
1833reply(int n, const char *fmt, ...)
1834#else
1835reply(n, fmt, va_alist)
1836	int n;
1837	char *fmt;
1838	va_dcl
1839#endif
1840{
1841	char *buf, *p, *next;
1842	va_list ap;
1843#ifdef __STDC__
1844	va_start(ap, fmt);
1845#else
1846	va_start(ap);
1847#endif
1848	if (vasprintf(&buf, fmt, ap) == -1 || buf == NULL) {
1849		printf("412 Local resource failure: malloc\r\n");
1850		fflush(stdout);
1851		dologout(1);
1852	}
1853	next = buf;
1854	while ((p = strsep(&next, "\n\r"))) {
1855		printf("%d%s %s\r\n", n, (next != '\0') ? "-" : "", p);
1856		if (debug)
1857			syslog(LOG_DEBUG, "<--- %d%s %s", n,
1858			    (next != '\0') ? "-" : "", p);
1859	}
1860	(void)fflush(stdout);
1861	free(buf);
1862}
1863
1864void
1865#ifdef __STDC__
1866lreply(int n, const char *fmt, ...)
1867#else
1868lreply(n, fmt, va_alist)
1869	int n;
1870	char *fmt;
1871	va_dcl
1872#endif
1873{
1874	va_list ap;
1875#ifdef __STDC__
1876	va_start(ap, fmt);
1877#else
1878	va_start(ap);
1879#endif
1880	(void)printf("%d- ", n);
1881	(void)vprintf(fmt, ap);
1882	(void)printf("\r\n");
1883	(void)fflush(stdout);
1884	if (debug) {
1885		syslog(LOG_DEBUG, "<--- %d- ", n);
1886		vsyslog(LOG_DEBUG, fmt, ap);
1887	}
1888}
1889
1890static void
1891ack(s)
1892	char *s;
1893{
1894
1895	reply(250, "%s command successful.", s);
1896}
1897
1898void
1899nack(s)
1900	char *s;
1901{
1902
1903	reply(502, "%s command not implemented.", s);
1904}
1905
1906/* ARGSUSED */
1907void
1908yyerror(s)
1909	char *s;
1910{
1911	char *cp;
1912
1913	if ((cp = strchr(cbuf,'\n')))
1914		*cp = '\0';
1915	reply(500, "'%s': command not understood.", cbuf);
1916}
1917
1918void
1919delete(name)
1920	char *name;
1921{
1922	struct stat st;
1923
1924	LOGCMD("delete", name);
1925	if (stat(name, &st) < 0) {
1926		perror_reply(550, name);
1927		return;
1928	}
1929	if ((st.st_mode&S_IFMT) == S_IFDIR) {
1930		if (rmdir(name) < 0) {
1931			perror_reply(550, name);
1932			return;
1933		}
1934		goto done;
1935	}
1936	if (unlink(name) < 0) {
1937		perror_reply(550, name);
1938		return;
1939	}
1940done:
1941	ack("DELE");
1942}
1943
1944void
1945cwd(path)
1946	char *path;
1947{
1948	FILE *message;
1949
1950	if (chdir(path) < 0)
1951		perror_reply(550, path);
1952	else {
1953		if ((message = fopen(_PATH_CWDMESG, "r")) != NULL) {
1954			char *cp, line[LINE_MAX];
1955
1956			while (fgets(line, sizeof(line), message) != NULL) {
1957				if ((cp = strchr(line, '\n')) != NULL)
1958					*cp = '\0';
1959				lreply(250, "%s", line);
1960			}
1961			(void) fflush(stdout);
1962			(void) fclose(message);
1963		}
1964		ack("CWD");
1965	}
1966}
1967
1968void
1969replydirname(name, message)
1970	const char *name, *message;
1971{
1972	char *p, *ep;
1973	char npath[MAXPATHLEN * 2];
1974
1975	p = npath;
1976	ep = &npath[sizeof(npath) - 1];
1977	while (*name) {
1978		if (*name == '"') {
1979			if (ep - p < 2)
1980				break;
1981			*p++ = *name++;
1982			*p++ = '"';
1983		} else {
1984			if (ep - p < 1)
1985				break;
1986			*p++ = *name++;
1987		}
1988	}
1989	*p = '\0';
1990	reply(257, "\"%s\" %s", npath, message);
1991}
1992
1993void
1994makedir(name)
1995	char *name;
1996{
1997
1998	LOGCMD("mkdir", name);
1999	if (mkdir(name, 0777) < 0)
2000		perror_reply(550, name);
2001	else
2002		replydirname(name, "directory created.");
2003}
2004
2005void
2006removedir(name)
2007	char *name;
2008{
2009
2010	LOGCMD("rmdir", name);
2011	if (rmdir(name) < 0)
2012		perror_reply(550, name);
2013	else
2014		ack("RMD");
2015}
2016
2017void
2018pwd()
2019{
2020	char path[MAXPATHLEN];
2021
2022	if (getcwd(path, sizeof(path)) == NULL)
2023		reply(550, "Can't get current directory: %s.", strerror(errno));
2024	else
2025		replydirname(path, "is current directory.");
2026}
2027
2028char *
2029renamefrom(name)
2030	char *name;
2031{
2032	struct stat st;
2033
2034	if (stat(name, &st) < 0) {
2035		perror_reply(550, name);
2036		return ((char *)0);
2037	}
2038	reply(350, "File exists, ready for destination name");
2039	return (name);
2040}
2041
2042void
2043renamecmd(from, to)
2044	char *from, *to;
2045{
2046
2047	LOGCMD2("rename", from, to);
2048	if (rename(from, to) < 0)
2049		perror_reply(550, "rename");
2050	else
2051		ack("RNTO");
2052}
2053
2054static void
2055dolog(sa)
2056	struct sockaddr *sa;
2057{
2058	char hbuf[sizeof(remotehost)];
2059
2060	getnameinfo(sa, sa->sa_len, hbuf, sizeof(hbuf), NULL, 0, 0);
2061	(void) strlcpy(remotehost, hbuf, sizeof(remotehost));
2062
2063#ifdef HASSETPROCTITLE
2064	snprintf(proctitle, sizeof(proctitle), "%s: connected", remotehost);
2065	setproctitle("%s", proctitle);
2066#endif /* HASSETPROCTITLE */
2067
2068	if (logging)
2069		syslog(LOG_INFO, "connection from %s", remotehost);
2070}
2071
2072/*
2073 * Record logout in wtmp file
2074 * and exit with supplied status.
2075 */
2076void
2077dologout(status)
2078	int status;
2079{
2080
2081	transflag = 0;
2082
2083	if (logged_in) {
2084		sigprocmask(SIG_BLOCK, &allsigs, NULL);
2085		(void) seteuid((uid_t)0);
2086		ftpdlogwtmp(ttyline, "", "");
2087		if (doutmp)
2088			logout(utmp.ut_line);
2089	}
2090	/* beware of flushing buffers after a SIGPIPE */
2091	_exit(status);
2092}
2093
2094static void
2095myoob(signo)
2096	int signo;
2097{
2098	char *cp;
2099	int save_errno = errno;
2100
2101	/* only process if transfer occurring */
2102	if (!transflag)
2103		return;
2104	cp = tmpline;
2105	if (getline(cp, 7, stdin) == NULL) {
2106		reply(221, "You could at least say goodbye.");
2107		dologout(0);
2108	}
2109	upper(cp);
2110	if (strcmp(cp, "ABOR\r\n") == 0) {
2111		tmpline[0] = '\0';
2112		reply(426, "Transfer aborted. Data connection closed.");
2113		reply(226, "Abort successful");
2114		longjmp(urgcatch, 1);
2115	}
2116	if (strcmp(cp, "STAT\r\n") == 0) {
2117		tmpline[0] = '\0';
2118		if (file_size != (off_t) -1)
2119			reply(213, "Status: %qd of %qd bytes transferred",
2120			    byte_count, file_size);
2121		else
2122			reply(213, "Status: %qd bytes transferred", byte_count);
2123	}
2124	errno = save_errno;
2125}
2126
2127/*
2128 * Note: a response of 425 is not mentioned as a possible response to
2129 *	the PASV command in RFC959. However, it has been blessed as
2130 *	a legitimate response by Jon Postel in a telephone conversation
2131 *	with Rick Adams on 25 Jan 89.
2132 */
2133void
2134passive()
2135{
2136	int len, on;
2137	u_char *p, *a;
2138
2139	if (pw == NULL) {
2140		reply(530, "Please login with USER and PASS");
2141		return;
2142	}
2143	if (pdata >= 0)
2144		close(pdata);
2145	/*
2146	 * XXX
2147	 * At this point, it would be nice to have an algorithm that
2148	 * inserted a growing delay in an attack scenario.  Such a thing
2149	 * would look like continual passive sockets being opened, but
2150	 * nothing serious being done with them.  They're not used to
2151	 * move data; the entire attempt is just to use tcp FIN_WAIT
2152	 * resources.
2153	 */
2154	pdata = socket(AF_INET, SOCK_STREAM, 0);
2155	if (pdata < 0) {
2156		perror_reply(425, "Can't open passive connection");
2157		return;
2158	}
2159
2160#ifdef IP_PORTRANGE
2161	on = high_data_ports ? IP_PORTRANGE_HIGH : IP_PORTRANGE_DEFAULT;
2162	if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2163	    (char *)&on, sizeof(on)) < 0)
2164		goto pasv_error;
2165#endif
2166
2167	pasv_addr = ctrl_addr;
2168	pasv_addr.su_sin.sin_port = 0;
2169	if (bind(pdata, (struct sockaddr *)&pasv_addr,
2170		 pasv_addr.su_len) < 0)
2171		goto pasv_error;
2172
2173	len = sizeof(pasv_addr);
2174	if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2175		goto pasv_error;
2176	if (listen(pdata, 1) < 0)
2177		goto pasv_error;
2178	a = (u_char *) &pasv_addr.su_sin.sin_addr;
2179	p = (u_char *) &pasv_addr.su_sin.sin_port;
2180
2181	reply(227, "Entering Passive Mode (%u,%u,%u,%u,%u,%u)", a[0],
2182	    a[1], a[2], a[3], p[0], p[1]);
2183	return;
2184
2185pasv_error:
2186	(void) seteuid((uid_t)pw->pw_uid);
2187	(void) close(pdata);
2188	pdata = -1;
2189	perror_reply(425, "Can't open passive connection");
2190	return;
2191}
2192
2193/*
2194 * convert protocol identifier to/from AF
2195 */
2196int
2197lpsvproto2af(int proto)
2198{
2199
2200	switch (proto) {
2201	case 4:	return AF_INET;
2202#ifdef INET6
2203	case 6:	return AF_INET6;
2204#endif
2205	default: return -1;
2206	}
2207}
2208
2209int
2210af2lpsvproto(int af)
2211{
2212
2213	switch (af) {
2214	case AF_INET:	return 4;
2215#ifdef INET6
2216	case AF_INET6:	return 6;
2217#endif
2218	default:	return -1;
2219	}
2220}
2221
2222int
2223epsvproto2af(int proto)
2224{
2225
2226	switch (proto) {
2227	case 1:	return AF_INET;
2228#ifdef INET6
2229	case 2:	return AF_INET6;
2230#endif
2231	default: return -1;
2232	}
2233}
2234
2235int
2236af2epsvproto(int af)
2237{
2238
2239	switch (af) {
2240	case AF_INET:	return 1;
2241#ifdef INET6
2242	case AF_INET6:	return 2;
2243#endif
2244	default:	return -1;
2245	}
2246}
2247
2248/*
2249 * 228 Entering Long Passive Mode (af, hal, h1, h2, h3,..., pal, p1, p2...)
2250 * 229 Entering Extended Passive Mode (|||port|)
2251 */
2252void
2253long_passive(char *cmd, int pf)
2254{
2255	int len, on;
2256	register u_char *p, *a;
2257
2258	if (!logged_in) {
2259		syslog(LOG_NOTICE, "long passive but not logged in");
2260		reply(503, "Login with USER first.");
2261		return;
2262	}
2263
2264	if (pf != PF_UNSPEC && ctrl_addr.su_family != pf) {
2265		/*
2266		 * XXX
2267		 * only EPRT/EPSV ready clients will understand this
2268		 */
2269		if (strcmp(cmd, "EPSV") != 0)
2270			reply(501, "Network protocol mismatch"); /*XXX*/
2271		else
2272			epsv_protounsupp("Network protocol mismatch");
2273
2274		return;
2275	}
2276
2277	if (pdata >= 0)
2278		close(pdata);
2279	/*
2280	 * XXX
2281	 * At this point, it would be nice to have an algorithm that
2282	 * inserted a growing delay in an attack scenario.  Such a thing
2283	 * would look like continual passive sockets being opened, but
2284	 * nothing serious being done with them.  They not used to move
2285	 * data; the entire attempt is just to use tcp FIN_WAIT
2286	 * resources.
2287	 */
2288	pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2289	if (pdata < 0) {
2290		perror_reply(425, "Can't open passive connection");
2291		return;
2292	}
2293
2294	switch (ctrl_addr.su_family) {
2295	case AF_INET:
2296#ifdef IP_PORTRANGE
2297		on = high_data_ports ? IP_PORTRANGE_HIGH : IP_PORTRANGE_DEFAULT;
2298		if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2299		    (char *)&on, sizeof(on)) < 0)
2300			goto pasv_error;
2301#endif
2302		break;
2303	case AF_INET6:
2304#ifdef IPV6_PORTRANGE
2305		on = high_data_ports ? IPV6_PORTRANGE_HIGH
2306				     : IPV6_PORTRANGE_DEFAULT;
2307		if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2308		    (char *)&on, sizeof(on)) < 0)
2309			goto pasv_error;
2310#endif
2311		break;
2312	}
2313
2314	pasv_addr = ctrl_addr;
2315	pasv_addr.su_port = 0;
2316	(void) seteuid((uid_t) 0);
2317	if (bind(pdata, (struct sockaddr *) &pasv_addr, pasv_addr.su_len) < 0) {
2318		(void) seteuid((uid_t) pw->pw_uid);
2319		goto pasv_error;
2320	}
2321	(void) seteuid((uid_t) pw->pw_uid);
2322	len = pasv_addr.su_len;
2323	if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2324		goto pasv_error;
2325	if (listen(pdata, 1) < 0)
2326		goto pasv_error;
2327	p = (u_char *) &pasv_addr.su_port;
2328
2329	if (strcmp(cmd, "LPSV") == 0) {
2330		switch (pasv_addr.su_family) {
2331		case AF_INET:
2332			a = (u_char *) &pasv_addr.su_sin.sin_addr;
2333			reply(228,
2334			    "Entering Long Passive Mode (%u,%u,%u,%u,%u,%u,%u,%u,%u)",
2335			    4, 4, a[0], a[1], a[2], a[3], 2, p[0], p[1]);
2336			return;
2337		case AF_INET6:
2338			a = (char *) &pasv_addr.su_sin6.sin6_addr;
2339			reply(228,
2340			    "Entering Long Passive Mode (%u,%u,%u,%u,%u,%u,"
2341			    "%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u)",
2342				6, 16, a[0], a[1], a[2], a[3], a[4],
2343				a[5], a[6], a[7], a[8], a[9], a[10],
2344				a[11], a[12], a[13], a[14], a[15],
2345				2, p[0], p[1]);
2346			return;
2347		}
2348	} else if (strcmp(cmd, "EPSV") == 0) {
2349		switch (pasv_addr.su_family) {
2350		case AF_INET:
2351		case AF_INET6:
2352			reply(229, "Entering Extended Passive Mode (|||%u|)",
2353			    ntohs(pasv_addr.su_port));
2354			return;
2355		}
2356	} else {
2357		/* more proper error code? */
2358	}
2359
2360  pasv_error:
2361	(void) close(pdata);
2362	pdata = -1;
2363	perror_reply(425, "Can't open passive connection");
2364	return;
2365}
2366
2367/*
2368 * EPRT |proto|addr|port|
2369 */
2370int
2371extended_port(const char *arg)
2372{
2373	char *tmp = NULL;
2374	char *result[3];
2375	char *p, *q;
2376	char delim;
2377	struct addrinfo hints;
2378	struct addrinfo *res = NULL;
2379	int i;
2380	unsigned long proto;
2381
2382	if (epsvall) {
2383		reply(501, "EPRT disallowed after EPSV ALL");
2384		return -1;
2385	}
2386
2387	usedefault = 0;
2388	if (pdata >= 0) {
2389		(void) close(pdata);
2390		pdata = -1;
2391	}
2392
2393	tmp = strdup(arg);
2394	if (!tmp) {
2395		fatal("not enough core.");
2396		/*NOTREACHED*/
2397	}
2398	p = tmp;
2399	delim = p[0];
2400	p++;
2401	memset(result, 0, sizeof(result));
2402	for (i = 0; i < 3; i++) {
2403		q = strchr(p, delim);
2404		if (!q || *q != delim)
2405			goto parsefail;
2406		*q++ = '\0';
2407		result[i] = p;
2408		p = q;
2409	}
2410
2411	/* some more sanity check */
2412	p = NULL;
2413	(void)strtoul(result[2], &p, 10);
2414	if (!*result[2] || *p)
2415		goto protounsupp;
2416	p = NULL;
2417	proto = strtoul(result[0], &p, 10);
2418	if (!*result[0] || *p)
2419		goto protounsupp;
2420
2421	memset(&hints, 0, sizeof(hints));
2422	hints.ai_family = epsvproto2af((int)proto);
2423	if (hints.ai_family < 0)
2424		goto protounsupp;
2425	hints.ai_socktype = SOCK_STREAM;
2426	hints.ai_flags = AI_NUMERICHOST;	/*no DNS*/
2427	if (getaddrinfo(result[1], result[2], &hints, &res))
2428		goto parsefail;
2429	if (res->ai_next)
2430		goto parsefail;
2431	if (sizeof(data_dest) < res->ai_addrlen)
2432		goto parsefail;
2433	memcpy(&data_dest, res->ai_addr, res->ai_addrlen);
2434	if (his_addr.su_family == AF_INET6 &&
2435	    data_dest.su_family == AF_INET6) {
2436		/* XXX more sanity checks! */
2437		data_dest.su_sin6.sin6_scope_id =
2438		    his_addr.su_sin6.sin6_scope_id;
2439	}
2440	if (pdata >= 0) {
2441		(void) close(pdata);
2442		pdata = -1;
2443	}
2444	reply(200, "EPRT command successful.");
2445
2446	if (tmp)
2447		free(tmp);
2448	if (res)
2449		freeaddrinfo(res);
2450	return 0;
2451
2452parsefail:
2453	reply(500, "Invalid argument, rejected.");
2454	usedefault = 1;
2455	if (tmp)
2456		free(tmp);
2457	if (res)
2458		freeaddrinfo(res);
2459	return -1;
2460
2461protounsupp:
2462	epsv_protounsupp("Protocol not supported");
2463	usedefault = 1;
2464	if (tmp)
2465		free(tmp);
2466	if (res)
2467		freeaddrinfo(res);
2468	return -1;
2469}
2470
2471/*
2472 * 522 Protocol not supported (proto,...)
2473 * as we assume address family for control and data connections are the same,
2474 * we do not return the list of address families we support - instead, we
2475 * return the address family of the control connection.
2476 */
2477void
2478epsv_protounsupp(const char *message)
2479{
2480	int proto;
2481
2482	proto = af2epsvproto(ctrl_addr.su_family);
2483	if (proto < 0)
2484		reply(501, "%s", message);	/*XXX*/
2485	else
2486		reply(522, "%s, use (%d)", message, proto);
2487}
2488
2489/*
2490 * Generate unique name for file with basename "local".
2491 * The file named "local" is already known to exist.
2492 * Generates failure reply on error.
2493 */
2494static int
2495guniquefd(local, nam)
2496	char *local;
2497	char **nam;
2498{
2499	static char new[MAXPATHLEN];
2500	struct stat st;
2501	int count, len, fd;
2502	char *cp;
2503
2504	cp = strrchr(local, '/');
2505	if (cp)
2506		*cp = '\0';
2507	if (stat(cp ? local : ".", &st) < 0) {
2508		perror_reply(553, cp ? local : ".");
2509		return (-1);
2510	}
2511	if (cp)
2512		*cp = '/';
2513	(void) strlcpy(new, local, sizeof(new));
2514	len = strlen(new);
2515	if (len+2+1 >= sizeof(new)-1)
2516		return (-1);
2517	cp = new + len;
2518	*cp++ = '.';
2519	for (count = 1; count < 100; count++) {
2520		(void)snprintf(cp, sizeof(new) - (cp - new), "%d", count);
2521		fd = open(new, O_RDWR|O_CREAT|O_EXCL, 0666);
2522		if (fd == -1)
2523			continue;
2524		if (nam)
2525			*nam = new;
2526		return (fd);
2527	}
2528	reply(452, "Unique file name cannot be created.");
2529	return (-1);
2530}
2531
2532/*
2533 * Format and send reply containing system error number.
2534 */
2535void
2536perror_reply(code, string)
2537	int code;
2538	char *string;
2539{
2540
2541	reply(code, "%s: %s.", string, strerror(errno));
2542}
2543
2544static char *onefile[] = {
2545	"",
2546	0
2547};
2548
2549void
2550send_file_list(whichf)
2551	char *whichf;
2552{
2553	struct stat st;
2554	DIR *dirp = NULL;
2555	struct dirent *dir;
2556	FILE *dout = NULL;
2557	char **dirlist, *dirname;
2558	int simple = 0;
2559	int freeglob = 0;
2560	glob_t gl;
2561
2562	if (strpbrk(whichf, "~{[*?") != NULL) {
2563		memset(&gl, 0, sizeof(gl));
2564		freeglob = 1;
2565		if (glob(whichf,
2566		    GLOB_BRACE|GLOB_NOCHECK|GLOB_QUOTE|GLOB_TILDE|GLOB_LIMIT,
2567		    0, &gl)) {
2568			reply(550, "not found");
2569			goto out;
2570		} else if (gl.gl_pathc == 0) {
2571			errno = ENOENT;
2572			perror_reply(550, whichf);
2573			goto out;
2574		}
2575		dirlist = gl.gl_pathv;
2576	} else {
2577		onefile[0] = whichf;
2578		dirlist = onefile;
2579		simple = 1;
2580	}
2581
2582	if (setjmp(urgcatch)) {
2583		transflag = 0;
2584		goto out;
2585	}
2586	while ((dirname = *dirlist++)) {
2587		if (stat(dirname, &st) < 0) {
2588			/*
2589			 * If user typed "ls -l", etc, and the client
2590			 * used NLST, do what the user meant.
2591			 */
2592			if (dirname[0] == '-' && *dirlist == NULL &&
2593			    transflag == 0) {
2594				retrieve("/bin/ls %s", dirname);
2595				goto out;
2596			}
2597			perror_reply(550, whichf);
2598			if (dout != NULL) {
2599				(void) fclose(dout);
2600				transflag = 0;
2601				data = -1;
2602				pdata = -1;
2603			}
2604			goto out;
2605		}
2606
2607		if (S_ISREG(st.st_mode)) {
2608			if (dout == NULL) {
2609				dout = dataconn("file list", (off_t)-1, "w");
2610				if (dout == NULL)
2611					goto out;
2612				transflag++;
2613			}
2614			fprintf(dout, "%s%s\n", dirname,
2615				type == TYPE_A ? "\r" : "");
2616			byte_count += strlen(dirname) + 1;
2617			continue;
2618		} else if (!S_ISDIR(st.st_mode))
2619			continue;
2620
2621		if ((dirp = opendir(dirname)) == NULL)
2622			continue;
2623
2624		while ((dir = readdir(dirp)) != NULL) {
2625			char nbuf[MAXPATHLEN];
2626
2627			if (dir->d_name[0] == '.' && dir->d_namlen == 1)
2628				continue;
2629			if (dir->d_name[0] == '.' && dir->d_name[1] == '.' &&
2630			    dir->d_namlen == 2)
2631				continue;
2632
2633			snprintf(nbuf, sizeof(nbuf), "%s/%s", dirname,
2634				 dir->d_name);
2635
2636			/*
2637			 * We have to do a stat to insure it's
2638			 * not a directory or special file.
2639			 */
2640			if (simple || (stat(nbuf, &st) == 0 &&
2641			    S_ISREG(st.st_mode))) {
2642				if (dout == NULL) {
2643					dout = dataconn("file list", (off_t)-1,
2644						"w");
2645					if (dout == NULL)
2646						goto out;
2647					transflag++;
2648				}
2649				if (nbuf[0] == '.' && nbuf[1] == '/')
2650					fprintf(dout, "%s%s\n", &nbuf[2],
2651						type == TYPE_A ? "\r" : "");
2652				else
2653					fprintf(dout, "%s%s\n", nbuf,
2654						type == TYPE_A ? "\r" : "");
2655				byte_count += strlen(nbuf) + 1;
2656			}
2657		}
2658		(void) closedir(dirp);
2659	}
2660
2661	if (dout == NULL)
2662		reply(550, "No files found.");
2663	else if (ferror(dout) != 0)
2664		perror_reply(550, "Data connection");
2665	else
2666		reply(226, "Transfer complete.");
2667
2668	transflag = 0;
2669	if (dout != NULL)
2670		(void) fclose(dout);
2671	else {
2672		if (pdata >= 0)
2673			close(pdata);
2674	}
2675	data = -1;
2676	pdata = -1;
2677out:
2678	if (freeglob) {
2679		freeglob = 0;
2680		globfree(&gl);
2681	}
2682}
2683
2684static void
2685reapchild(signo)
2686	int signo;
2687{
2688	int save_errno = errno;
2689
2690	while (wait3(NULL, WNOHANG, NULL) > 0)
2691		;
2692	errno = save_errno;
2693}
2694
2695void
2696logxfer(name, size, start)
2697	char *name;
2698	off_t size;
2699	time_t start;
2700{
2701	char buf[400 + MAXHOSTNAMELEN*4 + MAXPATHLEN*4];
2702	char dir[MAXPATHLEN], path[MAXPATHLEN], rpath[MAXPATHLEN];
2703	char vremotehost[MAXHOSTNAMELEN*4], vpath[MAXPATHLEN*4];
2704	char *vpw;
2705	time_t now;
2706
2707	if ((statfd >= 0) && (getcwd(dir, sizeof(dir)) != NULL)) {
2708		time(&now);
2709
2710		vpw = (char *)malloc(strlen((guest) ? guestpw : pw->pw_name)*4+1);
2711		if (vpw == NULL)
2712			return;
2713
2714		snprintf(path, sizeof(path), "%s/%s", dir, name);
2715		if (realpath(path, rpath) == NULL)
2716			strlcpy(rpath, path, sizeof(rpath));
2717		strvis(vpath, rpath, VIS_SAFE|VIS_NOSLASH);
2718
2719		strvis(vremotehost, remotehost, VIS_SAFE|VIS_NOSLASH);
2720		strvis(vpw, (guest) ? guestpw : pw->pw_name, VIS_SAFE|VIS_NOSLASH);
2721
2722		snprintf(buf, sizeof(buf),
2723		    "%.24s %d %s %qd %s %c %s %c %c %s ftp %d %s %s\n",
2724		    ctime(&now), now - start + (now == start),
2725		    vremotehost, (long long) size, vpath,
2726		    ((type == TYPE_A) ? 'a' : 'b'), "*" /* none yet */,
2727		    'o', ((guest) ? 'a' : 'r'),
2728		    vpw, 0 /* none yet */,
2729		    ((guest) ? "*" : pw->pw_name), dhostname);
2730		write(statfd, buf, strlen(buf));
2731		free(vpw);
2732	}
2733}
2734
2735#if defined(TCPWRAPPERS)
2736static int
2737check_host(sa)
2738	struct sockaddr *sa;
2739{
2740	struct sockaddr_in *sin;
2741	struct hostent *hp;
2742	char *addr;
2743
2744	if (sa->sa_family != AF_INET)
2745		return 1;	/*XXX*/
2746
2747	sin = (struct sockaddr_in *)sa;
2748	hp = gethostbyaddr((char *)&sin->sin_addr,
2749	    sizeof(struct in_addr), AF_INET);
2750	addr = inet_ntoa(sin->sin_addr);
2751	if (hp) {
2752		if (!hosts_ctl("ftpd", hp->h_name, addr, STRING_UNKNOWN)) {
2753			syslog(LOG_NOTICE, "tcpwrappers rejected: %s [%s]",
2754			    hp->h_name, addr);
2755			return (0);
2756		}
2757	} else {
2758		if (!hosts_ctl("ftpd", STRING_UNKNOWN, addr, STRING_UNKNOWN)) {
2759			syslog(LOG_NOTICE, "tcpwrappers rejected: [%s]", addr);
2760			return (0);
2761		}
2762	}
2763	return (1);
2764}
2765#endif	/* TCPWRAPPERS */
2766
2767/*
2768 * Allocate space and return a copy of the specified dir.
2769 * If 'dir' begins with a tilde (~), expand it.
2770 */
2771char *
2772copy_dir(dir, pw)
2773	char *dir;
2774	struct passwd *pw;
2775{
2776	char *cp;
2777	char *newdir;
2778	char *user = NULL;
2779	size_t dirsiz;
2780
2781	/* Nothing to expand */
2782	if (dir[0] !=  '~')
2783		return (strdup(dir));
2784
2785	/* "dir" is of form ~user/some/dir, lookup user. */
2786	if (dir[1] != '/' && dir[1] != '\0') {
2787		if ((cp = strchr(dir + 1, '/')) == NULL)
2788		    cp = dir + strlen(dir);
2789		if ((user = malloc(cp - dir)) == NULL)
2790			return (NULL);
2791		strlcpy(user, dir + 1, cp - dir);
2792
2793		/* Only do lookup if it is a different user. */
2794		if (strcmp(user, pw->pw_name) != 0) {
2795			if ((pw = getpwnam(user)) == NULL) {
2796				/* No such user, interpret literally */
2797				free(user);
2798				return(strdup(dir));
2799			}
2800		}
2801	}
2802
2803	/*
2804	 * If there is no directory separator (/) then it is just pw_dir.
2805	 * Otherwise, replace ~foo with  pw_dir.
2806	 */
2807	if ((cp = strchr(dir + 1, '/')) == NULL) {
2808		newdir = strdup(pw->pw_dir);
2809	} else {
2810		dirsiz = strlen(cp) + strlen(pw->pw_dir) + 1;
2811		if ((newdir = malloc(dirsiz)) == NULL)
2812			return (NULL);
2813		strcpy(newdir, pw->pw_dir);
2814		strcat(newdir, cp);
2815	}
2816
2817	if (user)
2818		free(user);
2819	return(newdir);
2820}
2821