ftpd.c revision 1.100
1/*	$OpenBSD: ftpd.c,v 1.100 2001/06/25 16:24:27 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.100 2001/06/25 16:24:27 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	    auth_setitem(as, "login", "yes") < 0)) {
754	    auth_setitem(as, "notickets", "yes") < 0)) {
755		if (as) {
756			auth_close(as);
757			as = NULL;
758		}
759		login_close(lc);
760		lc = NULL;
761		reply(421, "Local resource failure");
762		return;
763	}
764	if (logging)
765		strlcpy(curname, name, sizeof(curname));
766
767	dochroot = (lc && login_getcapbool(lc, "ftp-chroot", 0)) ||
768	    checkuser(_PATH_FTPCHROOT, name);
769	if (anon_only && !dochroot) {
770		reply(530, "Sorry, only anonymous ftp allowed.");
771		return;
772	}
773	if (pw) {
774		if ((!shell && !dochroot) || checkuser(_PATH_FTPUSERS, name)) {
775			reply(530, "User %s access denied.", name);
776			if (logging)
777				syslog(LOG_NOTICE,
778				    "FTP LOGIN REFUSED FROM %s, %s",
779				    remotehost, name);
780			pw = NULL;
781			return;
782		}
783	}
784
785	if (as != NULL && (cp = auth_challenge(as)) != NULL)
786		reply(331, cp);
787	else
788		reply(331, "Password required for %s.", name);
789
790	askpasswd = 1;
791	/*
792	 * Delay before reading passwd after first failed
793	 * attempt to slow down passwd-guessing programs.
794	 */
795	if (login_attempts)
796		sleep((unsigned) login_attempts);
797}
798
799/*
800 * Check if a user is in the file "fname"
801 */
802static int
803checkuser(fname, name)
804	char *fname;
805	char *name;
806{
807	FILE *fp;
808	int found = 0;
809	char *p, line[BUFSIZ];
810
811	if ((fp = fopen(fname, "r")) != NULL) {
812		while (fgets(line, sizeof(line), fp) != NULL)
813			if ((p = strchr(line, '\n')) != NULL) {
814				*p = '\0';
815				if (line[0] == '#')
816					continue;
817				if (strcmp(line, name) == 0) {
818					found = 1;
819					break;
820				}
821			}
822		(void) fclose(fp);
823	}
824	return (found);
825}
826
827/*
828 * Terminate login as previous user, if any, resetting state;
829 * used when USER command is given or login fails.
830 */
831static void
832end_login()
833{
834
835	sigprocmask (SIG_BLOCK, &allsigs, NULL);
836	(void) seteuid((uid_t)0);
837	if (logged_in) {
838		ftpdlogwtmp(ttyline, "", "");
839		if (doutmp)
840			logout(utmp.ut_line);
841	}
842	pw = NULL;
843	/* umask is restored in ftpcmd.y */
844	setusercontext(NULL, getpwuid(0), (uid_t)0,
845	    LOGIN_SETPRIORITY|LOGIN_SETRESOURCES);
846	logged_in = 0;
847	guest = 0;
848	dochroot = 0;
849}
850
851void
852pass(passwd)
853	char *passwd;
854{
855	int authok, flags;
856	FILE *fp;
857	static char homedir[MAXPATHLEN];
858	char *dir, rootdir[MAXPATHLEN];
859
860	if (logged_in || askpasswd == 0) {
861		reply(503, "Login with USER first.");
862		return;
863	}
864	askpasswd = 0;
865	if (!guest) {		/* "ftp" is only account allowed no password */
866		authok = 0;
867		if (pw == NULL) {
868			useconds_t us;
869
870			/* Sleep between 1 and 3 seconds to emulate a crypt. */
871			us = arc4random() % 3000000;
872			usleep(us);
873		} else {
874			authok = auth_userresponse(as, passwd, 0);
875			auth_close(as);
876			as = NULL;
877		}
878		if (authok == 0) {
879			reply(530, "Login incorrect.");
880			if (logging)
881				syslog(LOG_NOTICE,
882				    "FTP LOGIN FAILED FROM %s, %s",
883				    remotehost, curname);
884			pw = NULL;
885			if (login_attempts++ >= 5) {
886				syslog(LOG_NOTICE,
887				    "repeated login failures from %s",
888				    remotehost);
889				exit(0);
890			}
891			return;
892		}
893	} else if (lc != NULL) {
894		/* Save anonymous' password. */
895		guestpw = strdup(passwd);
896		if (guestpw == (char *)NULL)
897			fatal("Out of memory");
898
899		if ((as = auth_open()) == NULL)
900			fatal("Out of memory");
901		auth_setoption(as, "FTPD_HOST",
902		    multihome ? dhostname : hostname);
903		authok = auth_approval(as, lc, pw->pw_name, "ftp");
904		auth_close(as);
905		as = NULL;
906		if (authok == 0) {
907			syslog(LOG_INFO|LOG_AUTH,
908			    "FTP LOGIN FAILED (HOST) as %s: approval failure.",
909			    pw->pw_name);
910			reply(530, "Approval failure.\n");
911			exit(0);
912		}
913	} else {
914		syslog(LOG_INFO|LOG_AUTH,
915		    "FTP LOGIN CLASS %s MISSING for %s: approval failure.",
916		    pw->pw_class, pw->pw_name);
917		reply(530, "Permission denied.\n");
918		exit(0);
919	}
920	login_attempts = 0;		/* this time successful */
921	if (setegid((gid_t)pw->pw_gid) < 0) {
922		reply(550, "Can't set gid.");
923		return;
924	}
925	/* set umask via setusercontext() unless -u flag was given. */
926	flags = LOGIN_SETGROUP|LOGIN_SETPRIORITY|LOGIN_SETRESOURCES;
927	if (umaskchange)
928		flags |= LOGIN_SETUMASK;
929	else
930		(void) umask(defumask);
931	setusercontext(lc, pw, (uid_t)0, flags);
932
933	/* open wtmp before chroot */
934	ftpdlogwtmp(ttyline, pw->pw_name, remotehost);
935
936	/* open utmp before chroot */
937	if (doutmp) {
938		memset((void *)&utmp, 0, sizeof(utmp));
939		(void)time(&utmp.ut_time);
940		(void)strncpy(utmp.ut_name, pw->pw_name, sizeof(utmp.ut_name));
941		(void)strncpy(utmp.ut_host, remotehost, sizeof(utmp.ut_host));
942		(void)strncpy(utmp.ut_line, ttyline, sizeof(utmp.ut_line));
943		login(&utmp);
944	}
945
946	/* open stats file before chroot */
947	if (guest && (stats == 1) && (statfd < 0))
948		if ((statfd = open(_PATH_FTPDSTATFILE, O_WRONLY|O_APPEND)) < 0)
949			stats = 0;
950
951	logged_in = 1;
952
953	if ((dir = login_getcapstr(lc, "ftp-dir", NULL, NULL))) {
954		char *newdir;
955
956		newdir = copy_dir(dir, pw);
957		if (newdir == NULL) {
958			perror_reply(421, "Local resource failure: malloc");
959			dologout(1);
960			/* NOTREACHED */
961		}
962		free(pw->pw_dir);
963		pw->pw_dir = newdir;
964	}
965	if (guest || dochroot) {
966		if (multihome && guest) {
967			struct stat ts;
968
969			/* Compute root directory. */
970			snprintf(rootdir, sizeof(rootdir), "%s/%s",
971				  pw->pw_dir, dhostname);
972			if (stat(rootdir, &ts) < 0) {
973				snprintf(rootdir, sizeof(rootdir), "%s/%s",
974					  pw->pw_dir, hostname);
975			}
976		} else
977			strcpy(rootdir, pw->pw_dir);
978	}
979	if (guest) {
980		/*
981		 * We MUST do a chdir() after the chroot. Otherwise
982		 * the old current directory will be accessible as "."
983		 * outside the new root!
984		 */
985		if (chroot(rootdir) < 0 || chdir("/") < 0) {
986			reply(550, "Can't set guest privileges.");
987			goto bad;
988		}
989		strcpy(pw->pw_dir, "/");
990		if (setenv("HOME", "/", 1) == -1) {
991			reply(550, "Can't setup environment.");
992			goto bad;
993		}
994	} else if (dochroot) {
995		if (chroot(rootdir) < 0 || chdir("/") < 0) {
996			reply(550, "Can't change root.");
997			goto bad;
998		}
999		strcpy(pw->pw_dir, "/");
1000		if (setenv("HOME", "/", 1) == -1) {
1001			reply(550, "Can't setup environment.");
1002			goto bad;
1003		}
1004	} else if (chdir(pw->pw_dir) < 0) {
1005		if (chdir("/") < 0) {
1006			reply(530, "User %s: can't change directory to %s.",
1007			    pw->pw_name, pw->pw_dir);
1008			goto bad;
1009		} else
1010			lreply(230, "No directory! Logging in with home=/");
1011	}
1012	if (seteuid((uid_t)pw->pw_uid) < 0) {
1013		reply(550, "Can't set uid.");
1014		goto bad;
1015	}
1016	sigprocmask(SIG_UNBLOCK, &allsigs, NULL);
1017
1018	/*
1019	 * Set home directory so that use of ~ (tilde) works correctly.
1020	 */
1021	if (getcwd(homedir, MAXPATHLEN) != NULL) {
1022		if (setenv("HOME", homedir, 1) == -1) {
1023			reply(550, "Can't setup environment.");
1024			goto bad;
1025		}
1026	}
1027
1028	/*
1029	 * Display a login message, if it exists.
1030	 * N.B. reply(230,) must follow the message.
1031	 */
1032	if ((fp = fopen(_PATH_FTPLOGINMESG, "r")) != NULL) {
1033		char *cp, line[LINE_MAX];
1034
1035		while (fgets(line, sizeof(line), fp) != NULL) {
1036			if ((cp = strchr(line, '\n')) != NULL)
1037				*cp = '\0';
1038			lreply(230, "%s", line);
1039		}
1040		(void) fflush(stdout);
1041		(void) fclose(fp);
1042	}
1043	if (guest) {
1044		if (ident != NULL)
1045			free(ident);
1046		ident = strdup(passwd);
1047		if (ident == NULL)
1048			fatal("Ran out of memory.");
1049		reply(230, "Guest login ok, access restrictions apply.");
1050#ifdef HASSETPROCTITLE
1051		snprintf(proctitle, sizeof(proctitle),
1052		    "%s: anonymous/%.*s", remotehost,
1053		    (int)(sizeof(proctitle) - sizeof(remotehost) -
1054		    sizeof(": anonymous/")), passwd);
1055		setproctitle("%s", proctitle);
1056#endif /* HASSETPROCTITLE */
1057		if (logging)
1058			syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s, %s",
1059			    remotehost, passwd);
1060	} else {
1061		reply(230, "User %s logged in.", pw->pw_name);
1062#ifdef HASSETPROCTITLE
1063		snprintf(proctitle, sizeof(proctitle),
1064		    "%s: %s", remotehost, pw->pw_name);
1065		setproctitle("%s", proctitle);
1066#endif /* HASSETPROCTITLE */
1067		if (logging)
1068			syslog(LOG_INFO, "FTP LOGIN FROM %s as %s",
1069			    remotehost, pw->pw_name);
1070	}
1071	login_close(lc);
1072	lc = NULL;
1073	return;
1074bad:
1075	/* Forget all about it... */
1076	login_close(lc);
1077	lc = NULL;
1078	end_login();
1079}
1080
1081void
1082retrieve(cmd, name)
1083	char *cmd, *name;
1084{
1085	FILE *fin, *dout;
1086	struct stat st;
1087	int (*closefunc) __P((FILE *));
1088	time_t start;
1089
1090	if (cmd == 0) {
1091		fin = fopen(name, "r"), closefunc = fclose;
1092		st.st_size = 0;
1093	} else {
1094		char line[BUFSIZ];
1095
1096		(void) snprintf(line, sizeof(line), cmd, name);
1097		name = line;
1098		fin = ftpd_popen(line, "r"), closefunc = ftpd_pclose;
1099		st.st_size = -1;
1100		st.st_blksize = BUFSIZ;
1101	}
1102	if (fin == NULL) {
1103		if (errno != 0) {
1104			perror_reply(550, name);
1105			if (cmd == 0) {
1106				LOGCMD("get", name);
1107			}
1108		}
1109		return;
1110	}
1111	byte_count = -1;
1112	if (cmd == 0 && (fstat(fileno(fin), &st) < 0 || !S_ISREG(st.st_mode))) {
1113		reply(550, "%s: not a plain file.", name);
1114		goto done;
1115	}
1116	if (restart_point) {
1117		if (type == TYPE_A) {
1118			off_t i, n;
1119			int c;
1120
1121			n = restart_point;
1122			i = 0;
1123			while (i++ < n) {
1124				if ((c=getc(fin)) == EOF) {
1125					perror_reply(550, name);
1126					goto done;
1127				}
1128				if (c == '\n')
1129					i++;
1130			}
1131		} else if (lseek(fileno(fin), restart_point, SEEK_SET) < 0) {
1132			perror_reply(550, name);
1133			goto done;
1134		}
1135	}
1136	dout = dataconn(name, st.st_size, "w");
1137	if (dout == NULL)
1138		goto done;
1139	time(&start);
1140	send_data(fin, dout, st.st_blksize, st.st_size,
1141		  (restart_point == 0 && cmd == 0 && S_ISREG(st.st_mode)));
1142	if ((cmd == 0) && stats)
1143		logxfer(name, byte_count, start);
1144	(void) fclose(dout);
1145	data = -1;
1146done:
1147	if (pdata >= 0)
1148		(void) close(pdata);
1149	pdata = -1;
1150	if (cmd == 0)
1151		LOGBYTES("get", name, byte_count);
1152	(*closefunc)(fin);
1153}
1154
1155void
1156store(name, mode, unique)
1157	char *name, *mode;
1158	int unique;
1159{
1160	FILE *fout, *din;
1161	int (*closefunc) __P((FILE *));
1162	struct stat st;
1163	int fd;
1164
1165	if (restart_point && *mode != 'a')
1166		mode = "r+";
1167
1168	if (unique && stat(name, &st) == 0) {
1169		char *nam;
1170
1171		fd = guniquefd(name, &nam);
1172		if (fd == -1) {
1173			LOGCMD(*mode == 'w' ? "put" : "append", name);
1174			return;
1175		}
1176		name = nam;
1177		fout = fdopen(fd, mode);
1178	} else
1179		fout = fopen(name, mode);
1180
1181	closefunc = fclose;
1182	if (fout == NULL) {
1183		perror_reply(553, name);
1184		LOGCMD(*mode == 'w' ? "put" : "append", name);
1185		return;
1186	}
1187	byte_count = -1;
1188	if (restart_point) {
1189		if (type == TYPE_A) {
1190			off_t i, n;
1191			int c;
1192
1193			n = restart_point;
1194			i = 0;
1195			while (i++ < n) {
1196				if ((c=getc(fout)) == EOF) {
1197					perror_reply(550, name);
1198					goto done;
1199				}
1200				if (c == '\n')
1201					i++;
1202			}
1203			/*
1204			 * We must do this seek to "current" position
1205			 * because we are changing from reading to
1206			 * writing.
1207			 */
1208			if (fseek(fout, 0L, SEEK_CUR) < 0) {
1209				perror_reply(550, name);
1210				goto done;
1211			}
1212		} else if (lseek(fileno(fout), restart_point, SEEK_SET) < 0) {
1213			perror_reply(550, name);
1214			goto done;
1215		}
1216	}
1217	din = dataconn(name, (off_t)-1, "r");
1218	if (din == NULL)
1219		goto done;
1220	if (receive_data(din, fout) == 0) {
1221		if (unique)
1222			reply(226, "Transfer complete (unique file name:%s).",
1223			    name);
1224		else
1225			reply(226, "Transfer complete.");
1226	}
1227	(void) fclose(din);
1228	data = -1;
1229	pdata = -1;
1230done:
1231	LOGBYTES(*mode == 'w' ? "put" : "append", name, byte_count);
1232	(*closefunc)(fout);
1233}
1234
1235static FILE *
1236getdatasock(mode)
1237	char *mode;
1238{
1239	int on = 1, s, t, tries;
1240
1241	if (data >= 0)
1242		return (fdopen(data, mode));
1243	sigprocmask (SIG_BLOCK, &allsigs, NULL);
1244	(void) seteuid((uid_t)0);
1245	s = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
1246	if (s < 0)
1247		goto bad;
1248	if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
1249	    (char *) &on, sizeof(on)) < 0)
1250		goto bad;
1251	/* anchor socket to avoid multi-homing problems */
1252	data_source = ctrl_addr;
1253	data_source.su_port = htons(20); /* ftp-data port */
1254	for (tries = 1; ; tries++) {
1255		if (bind(s, (struct sockaddr *)&data_source,
1256		    data_source.su_len) >= 0)
1257			break;
1258		if (errno != EADDRINUSE || tries > 10)
1259			goto bad;
1260		sleep(tries);
1261	}
1262	(void) seteuid((uid_t)pw->pw_uid);
1263	sigprocmask (SIG_UNBLOCK, &allsigs, NULL);
1264
1265#ifdef IP_TOS
1266	if (ctrl_addr.su_family == AF_INET) {
1267		on = IPTOS_THROUGHPUT;
1268		if (setsockopt(s, IPPROTO_IP, IP_TOS, (char *)&on,
1269		    sizeof(int)) < 0)
1270			syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
1271	}
1272#endif
1273#ifdef TCP_NOPUSH
1274	/*
1275	 * Turn off push flag to keep sender TCP from sending short packets
1276	 * at the boundaries of each write().  Should probably do a SO_SNDBUF
1277	 * to set the send buffer size as well, but that may not be desirable
1278	 * in heavy-load situations.
1279	 */
1280	on = 1;
1281	if (setsockopt(s, IPPROTO_TCP, TCP_NOPUSH, (char *)&on, sizeof(on)) < 0)
1282		syslog(LOG_WARNING, "setsockopt (TCP_NOPUSH): %m");
1283#endif
1284#ifdef SO_SNDBUF
1285	on = 65536;
1286	if (setsockopt(s, SOL_SOCKET, SO_SNDBUF, (char *)&on, sizeof(on)) < 0)
1287		syslog(LOG_WARNING, "setsockopt (SO_SNDBUF): %m");
1288#endif
1289
1290	return (fdopen(s, mode));
1291bad:
1292	/* Return the real value of errno (close may change it) */
1293	t = errno;
1294	(void) seteuid((uid_t)pw->pw_uid);
1295	sigprocmask (SIG_UNBLOCK, &allsigs, NULL);
1296	(void) close(s);
1297	errno = t;
1298	return (NULL);
1299}
1300
1301static FILE *
1302dataconn(name, size, mode)
1303	char *name;
1304	off_t size;
1305	char *mode;
1306{
1307	char sizebuf[32];
1308	FILE *file;
1309	int retry = 0;
1310	in_port_t *p;
1311	char *fa, *ha;
1312	int alen;
1313
1314	file_size = size;
1315	byte_count = 0;
1316	if (size != (off_t) -1) {
1317		(void) snprintf(sizebuf, sizeof(sizebuf), " (%qd bytes)",
1318				size);
1319	} else
1320		sizebuf[0] = '\0';
1321	if (pdata >= 0) {
1322		union sockunion from;
1323		int s, fromlen = sizeof(from);
1324
1325		signal (SIGALRM, toolong);
1326		(void) alarm ((unsigned) timeout);
1327		s = accept(pdata, (struct sockaddr *)&from, &fromlen);
1328		(void) alarm (0);
1329		if (s < 0) {
1330			reply(425, "Can't open data connection.");
1331			(void) close(pdata);
1332			pdata = -1;
1333			return (NULL);
1334		}
1335		switch (from.su_family) {
1336		case AF_INET:
1337			p = (in_port_t *)&from.su_sin.sin_port;
1338			fa = (u_char *)&from.su_sin.sin_addr;
1339			ha = (u_char *)&his_addr.su_sin.sin_addr;
1340			alen = sizeof(struct in_addr);
1341			break;
1342		case AF_INET6:
1343			p = (in_port_t *)&from.su_sin6.sin6_port;
1344			fa = (u_char *)&from.su_sin6.sin6_addr;
1345			ha = (u_char *)&his_addr.su_sin6.sin6_addr;
1346			alen = sizeof(struct in6_addr);
1347			break;
1348		default:
1349			perror_reply(425, "Can't build data connection");
1350			(void) close(pdata);
1351			(void) close(s);
1352			pdata = -1;
1353			return (NULL);
1354		}
1355		if (from.su_family != his_addr.su_family ||
1356		    ntohs(*p) < IPPORT_RESERVED) {
1357			perror_reply(425, "Can't build data connection");
1358			(void) close(pdata);
1359			(void) close(s);
1360			pdata = -1;
1361			return (NULL);
1362		}
1363		if (portcheck && memcmp(fa, ha, alen) != 0) {
1364			perror_reply(435, "Can't build data connection");
1365			(void) close(pdata);
1366			(void) close(s);
1367			pdata = -1;
1368			return (NULL);
1369		}
1370		(void) close(pdata);
1371		pdata = s;
1372		reply(150, "Opening %s mode data connection for '%s'%s.",
1373		    type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1374		return (fdopen(pdata, mode));
1375	}
1376	if (data >= 0) {
1377		reply(125, "Using existing data connection for '%s'%s.",
1378		    name, sizebuf);
1379		usedefault = 1;
1380		return (fdopen(data, mode));
1381	}
1382	if (usedefault)
1383		data_dest = his_addr;
1384	usedefault = 1;
1385	file = getdatasock(mode);
1386	if (file == NULL) {
1387		char hbuf[MAXHOSTNAMELEN], pbuf[10];
1388
1389		getnameinfo((struct sockaddr *)&data_source, data_source.su_len,
1390		    hbuf, sizeof(hbuf), pbuf, sizeof(pbuf),
1391		    NI_NUMERICHOST | NI_NUMERICSERV);
1392		reply(425, "Can't create data socket (%s,%s): %s.",
1393		    hbuf, pbuf, strerror(errno));
1394		return (NULL);
1395	}
1396	data = fileno(file);
1397
1398	/*
1399	 * attempt to connect to reserved port on client machine;
1400	 * this looks like an attack
1401	 */
1402	switch (data_dest.su_family) {
1403	case AF_INET:
1404		p = (in_port_t *)&data_dest.su_sin.sin_port;
1405		fa = (u_char *)&data_dest.su_sin.sin_addr;
1406		ha = (u_char *)&his_addr.su_sin.sin_addr;
1407		alen = sizeof(struct in_addr);
1408		break;
1409	case AF_INET6:
1410		p = (in_port_t *)&data_dest.su_sin6.sin6_port;
1411		fa = (u_char *)&data_dest.su_sin6.sin6_addr;
1412		ha = (u_char *)&his_addr.su_sin6.sin6_addr;
1413		alen = sizeof(struct in6_addr);
1414		break;
1415	default:
1416		perror_reply(425, "Can't build data connection");
1417		(void) fclose(file);
1418		pdata = -1;
1419		return (NULL);
1420	}
1421	if (data_dest.su_family != his_addr.su_family ||
1422	    ntohs(*p) < IPPORT_RESERVED || ntohs(*p) == 2049) {	/* XXX */
1423		perror_reply(425, "Can't build data connection");
1424		(void) fclose(file);
1425		data = -1;
1426		return NULL;
1427	}
1428	if (portcheck && memcmp(fa, ha, alen) != 0) {
1429		perror_reply(435, "Can't build data connection");
1430		(void) fclose(file);
1431		data = -1;
1432		return NULL;
1433	}
1434	while (connect(data, (struct sockaddr *)&data_dest,
1435	    data_dest.su_len) < 0) {
1436		if (errno == EADDRINUSE && retry < swaitmax) {
1437			sleep((unsigned) swaitint);
1438			retry += swaitint;
1439			continue;
1440		}
1441		perror_reply(425, "Can't build data connection");
1442		(void) fclose(file);
1443		data = -1;
1444		return (NULL);
1445	}
1446	reply(150, "Opening %s mode data connection for '%s'%s.",
1447	    type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1448	return (file);
1449}
1450
1451/*
1452 * Tranfer the contents of "instr" to "outstr" peer using the appropriate
1453 * encapsulation of the data subject to Mode, Structure, and Type.
1454 *
1455 * NB: Form isn't handled.
1456 */
1457static void
1458send_data(instr, outstr, blksize, filesize, isreg)
1459	FILE *instr, *outstr;
1460	off_t blksize;
1461	off_t filesize;
1462	int isreg;
1463{
1464	int c, cnt, filefd, netfd;
1465	char *buf, *bp;
1466	size_t len;
1467
1468	transflag++;
1469	if (setjmp(urgcatch)) {
1470		transflag = 0;
1471		return;
1472	}
1473	switch (type) {
1474
1475	case TYPE_A:
1476		while ((c = getc(instr)) != EOF) {
1477			byte_count++;
1478			if (c == '\n') {
1479				if (ferror(outstr))
1480					goto data_err;
1481				(void) putc('\r', outstr);
1482			}
1483			(void) putc(c, outstr);
1484		}
1485		fflush(outstr);
1486		transflag = 0;
1487		if (ferror(instr))
1488			goto file_err;
1489		if (ferror(outstr))
1490			goto data_err;
1491		reply(226, "Transfer complete.");
1492		return;
1493
1494	case TYPE_I:
1495	case TYPE_L:
1496		/*
1497		 * isreg is only set if we are not doing restart and we
1498		 * are sending a regular file
1499		 */
1500		netfd = fileno(outstr);
1501		filefd = fileno(instr);
1502
1503		if (isreg && filesize < (off_t)16 * 1024 * 1024) {
1504			buf = mmap(0, filesize, PROT_READ, MAP_SHARED, filefd,
1505				   (off_t)0);
1506			if (buf == MAP_FAILED) {
1507				syslog(LOG_WARNING, "mmap(%lu): %m",
1508				    (unsigned long)filesize);
1509				goto oldway;
1510			}
1511			bp = buf;
1512			len = filesize;
1513			do {
1514				cnt = write(netfd, bp, len);
1515				len -= cnt;
1516				bp += cnt;
1517				if (cnt > 0) byte_count += cnt;
1518			} while(cnt > 0 && len > 0);
1519
1520			transflag = 0;
1521			munmap(buf, (size_t)filesize);
1522			if (cnt < 0)
1523				goto data_err;
1524			reply(226, "Transfer complete.");
1525			return;
1526		}
1527
1528oldway:
1529		if ((buf = malloc((u_int)blksize)) == NULL) {
1530			transflag = 0;
1531			perror_reply(451, "Local resource failure: malloc");
1532			return;
1533		}
1534
1535		while ((cnt = read(filefd, buf, (u_int)blksize)) > 0 &&
1536		    write(netfd, buf, cnt) == cnt)
1537			byte_count += cnt;
1538		transflag = 0;
1539		(void)free(buf);
1540		if (cnt != 0) {
1541			if (cnt < 0)
1542				goto file_err;
1543			goto data_err;
1544		}
1545		reply(226, "Transfer complete.");
1546		return;
1547	default:
1548		transflag = 0;
1549		reply(550, "Unimplemented TYPE %d in send_data", type);
1550		return;
1551	}
1552
1553data_err:
1554	transflag = 0;
1555	perror_reply(426, "Data connection");
1556	return;
1557
1558file_err:
1559	transflag = 0;
1560	perror_reply(551, "Error on input file");
1561}
1562
1563/*
1564 * Transfer data from peer to "outstr" using the appropriate encapulation of
1565 * the data subject to Mode, Structure, and Type.
1566 *
1567 * N.B.: Form isn't handled.
1568 */
1569static int
1570receive_data(instr, outstr)
1571	FILE *instr, *outstr;
1572{
1573	int c;
1574	int cnt, bare_lfs = 0;
1575	char buf[BUFSIZ];
1576
1577	transflag++;
1578	if (setjmp(urgcatch)) {
1579		transflag = 0;
1580		return (-1);
1581	}
1582	switch (type) {
1583
1584	case TYPE_I:
1585	case TYPE_L:
1586		signal (SIGALRM, lostconn);
1587
1588		do {
1589			(void) alarm ((unsigned) timeout);
1590			cnt = read(fileno(instr), buf, sizeof(buf));
1591			(void) alarm (0);
1592
1593			if (cnt > 0) {
1594				if (write(fileno(outstr), buf, cnt) != cnt)
1595					goto file_err;
1596				byte_count += cnt;
1597			}
1598		} while (cnt > 0);
1599		if (cnt < 0)
1600			goto data_err;
1601		transflag = 0;
1602		return (0);
1603
1604	case TYPE_E:
1605		reply(553, "TYPE E not implemented.");
1606		transflag = 0;
1607		return (-1);
1608
1609	case TYPE_A:
1610		while ((c = getc(instr)) != EOF) {
1611			byte_count++;
1612			if (c == '\n')
1613				bare_lfs++;
1614			while (c == '\r') {
1615				if (ferror(outstr))
1616					goto data_err;
1617				if ((c = getc(instr)) != '\n') {
1618					(void) putc ('\r', outstr);
1619					if (c == '\0' || c == EOF)
1620						goto contin2;
1621				}
1622			}
1623			(void) putc(c, outstr);
1624	contin2:	;
1625		}
1626		fflush(outstr);
1627		if (ferror(instr))
1628			goto data_err;
1629		if (ferror(outstr))
1630			goto file_err;
1631		transflag = 0;
1632		if (bare_lfs) {
1633			lreply(226,
1634			    "WARNING! %d bare linefeeds received in ASCII mode",
1635			    bare_lfs);
1636			printf("   File may not have transferred correctly.\r\n");
1637		}
1638		return (0);
1639	default:
1640		reply(550, "Unimplemented TYPE %d in receive_data", type);
1641		transflag = 0;
1642		return (-1);
1643	}
1644
1645data_err:
1646	transflag = 0;
1647	perror_reply(426, "Data Connection");
1648	return (-1);
1649
1650file_err:
1651	transflag = 0;
1652	perror_reply(452, "Error writing file");
1653	return (-1);
1654}
1655
1656void
1657statfilecmd(filename)
1658	char *filename;
1659{
1660	FILE *fin;
1661	int c;
1662	int atstart;
1663	char line[LINE_MAX];
1664
1665	(void)snprintf(line, sizeof(line), "/bin/ls -lgA %s", filename);
1666	fin = ftpd_popen(line, "r");
1667	lreply(211, "status of %s:", filename);
1668	atstart = 1;
1669	while ((c = getc(fin)) != EOF) {
1670		if (c == '\n') {
1671			if (ferror(stdout)){
1672				perror_reply(421, "control connection");
1673				(void) ftpd_pclose(fin);
1674				dologout(1);
1675				/* NOTREACHED */
1676			}
1677			if (ferror(fin)) {
1678				perror_reply(551, filename);
1679				(void) ftpd_pclose(fin);
1680				return;
1681			}
1682			(void) putc('\r', stdout);
1683		}
1684		if (atstart && isdigit(c))
1685			(void) putc(' ', stdout);
1686		(void) putc(c, stdout);
1687		atstart = (c == '\n');
1688	}
1689	(void) ftpd_pclose(fin);
1690	reply(211, "End of Status");
1691}
1692
1693void
1694statcmd()
1695{
1696	union sockunion *su;
1697	u_char *a, *p;
1698	char hbuf[MAXHOSTNAMELEN];
1699	int ispassive;
1700
1701	lreply(211, "%s FTP server status:", hostname, version);
1702	printf("     %s\r\n", version);
1703	getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
1704	    hbuf, sizeof(hbuf), NULL, 0, NI_NUMERICHOST);
1705	printf("     Connected to %s", remotehost);
1706	if (strcmp(remotehost, hbuf) != 0)
1707		printf(" (%s)", hbuf);
1708	printf("\r\n");
1709	if (logged_in) {
1710		if (guest)
1711			printf("     Logged in anonymously\r\n");
1712		else
1713			printf("     Logged in as %s\r\n", pw->pw_name);
1714	} else if (askpasswd)
1715		printf("     Waiting for password\r\n");
1716	else
1717		printf("     Waiting for user name\r\n");
1718	printf("     TYPE: %s", typenames[type]);
1719	if (type == TYPE_A || type == TYPE_E)
1720		printf(", FORM: %s", formnames[form]);
1721	if (type == TYPE_L)
1722#if NBBY == 8
1723		printf(" %d", NBBY);
1724#else
1725		printf(" %d", bytesize);	/* need definition! */
1726#endif
1727	printf("; STRUcture: %s; transfer MODE: %s\r\n",
1728	    strunames[stru], modenames[mode]);
1729	ispassive = 0;
1730	if (data != -1)
1731		printf("     Data connection open\r\n");
1732	else if (pdata != -1) {
1733		printf("     in Passive mode\r\n");
1734		su = (union sockunion *)&pasv_addr;
1735		ispassive++;
1736		goto printaddr;
1737	} else if (usedefault == 0) {
1738		su = (union sockunion *)&data_dest;
1739printaddr:
1740		/* PASV/PORT */
1741		if (su->su_family == AF_INET) {
1742			if (ispassive)
1743				printf("211- PASV ");
1744			else
1745				printf("211- PORT ");
1746			a = (u_char *) &su->su_sin.sin_addr;
1747			p = (u_char *) &su->su_sin.sin_port;
1748			printf("(%u,%u,%u,%u,%u,%u)\r\n",
1749			    a[0], a[1], a[2], a[3],
1750			    p[0], p[1]);
1751		}
1752
1753		/* LPSV/LPRT */
1754	    {
1755		int alen, af, i;
1756
1757		alen = 0;
1758		switch (su->su_family) {
1759		case AF_INET:
1760			a = (u_char *) &su->su_sin.sin_addr;
1761			p = (u_char *) &su->su_sin.sin_port;
1762			alen = sizeof(su->su_sin.sin_addr);
1763			af = 4;
1764			break;
1765		case AF_INET6:
1766			a = (u_char *) &su->su_sin6.sin6_addr;
1767			p = (u_char *) &su->su_sin6.sin6_port;
1768			alen = sizeof(su->su_sin6.sin6_addr);
1769			af = 6;
1770			break;
1771		default:
1772			af = 0;
1773			break;
1774		}
1775		if (af) {
1776			if (ispassive)
1777				printf("211- LPSV ");
1778			else
1779				printf("211- LPRT ");
1780			printf("(%u,%u", af, alen);
1781			for (i = 0; i < alen; i++)
1782				printf(",%u", a[i]);
1783			printf(",%u,%u,%u)\r\n", 2, p[0], p[1]);
1784		}
1785	    }
1786
1787		/* EPRT/EPSV */
1788epsvonly:
1789	    {
1790		u_char af;
1791
1792		switch (su->su_family) {
1793		case AF_INET:
1794			af = 1;
1795			break;
1796		case AF_INET6:
1797			af = 2;
1798			break;
1799		default:
1800			af = 0;
1801			break;
1802		}
1803		if (af) {
1804			char hbuf[MAXHOSTNAMELEN], pbuf[10];
1805			if (getnameinfo((struct sockaddr *)su, su->su_len,
1806			    hbuf, sizeof(hbuf), pbuf, sizeof(pbuf),
1807			    NI_NUMERICHOST) == 0) {
1808				if (ispassive)
1809					printf("211- EPSV ");
1810				else
1811					printf("211- EPRT ");
1812				printf("(|%u|%s|%s|)\r\n",
1813					af, hbuf, pbuf);
1814			}
1815		}
1816	    }
1817	} else
1818		printf("     No data connection\r\n");
1819	reply(211, "End of status");
1820}
1821
1822void
1823fatal(s)
1824	char *s;
1825{
1826
1827	reply(451, "Error in server: %s\n", s);
1828	reply(221, "Closing connection due to server error.");
1829	dologout(0);
1830	/* NOTREACHED */
1831}
1832
1833void
1834#ifdef __STDC__
1835reply(int n, const char *fmt, ...)
1836#else
1837reply(n, fmt, va_alist)
1838	int n;
1839	char *fmt;
1840	va_dcl
1841#endif
1842{
1843	char *buf, *p, *next;
1844	va_list ap;
1845#ifdef __STDC__
1846	va_start(ap, fmt);
1847#else
1848	va_start(ap);
1849#endif
1850	if (vasprintf(&buf, fmt, ap) == -1 || buf == NULL) {
1851		printf("412 Local resource failure: malloc\r\n");
1852		fflush(stdout);
1853		dologout(1);
1854	}
1855	next = buf;
1856	while ((p = strsep(&next, "\n\r"))) {
1857		printf("%d%s %s\r\n", n, (next != '\0') ? "-" : "", p);
1858		if (debug)
1859			syslog(LOG_DEBUG, "<--- %d%s %s", n,
1860			    (next != '\0') ? "-" : "", p);
1861	}
1862	(void)fflush(stdout);
1863	free(buf);
1864}
1865
1866void
1867#ifdef __STDC__
1868lreply(int n, const char *fmt, ...)
1869#else
1870lreply(n, fmt, va_alist)
1871	int n;
1872	char *fmt;
1873	va_dcl
1874#endif
1875{
1876	va_list ap;
1877#ifdef __STDC__
1878	va_start(ap, fmt);
1879#else
1880	va_start(ap);
1881#endif
1882	(void)printf("%d- ", n);
1883	(void)vprintf(fmt, ap);
1884	va_end(ap);
1885	(void)printf("\r\n");
1886	(void)fflush(stdout);
1887	if (debug) {
1888#ifdef __STDC__
1889		va_start(ap, fmt);
1890#else
1891		va_start(ap);
1892#endif
1893		syslog(LOG_DEBUG, "<--- %d- ", n);
1894		vsyslog(LOG_DEBUG, fmt, ap);
1895		va_end(ap);
1896	}
1897}
1898
1899static void
1900ack(s)
1901	char *s;
1902{
1903
1904	reply(250, "%s command successful.", s);
1905}
1906
1907void
1908nack(s)
1909	char *s;
1910{
1911
1912	reply(502, "%s command not implemented.", s);
1913}
1914
1915/* ARGSUSED */
1916void
1917yyerror(s)
1918	char *s;
1919{
1920	char *cp;
1921
1922	if ((cp = strchr(cbuf,'\n')))
1923		*cp = '\0';
1924	reply(500, "'%s': command not understood.", cbuf);
1925}
1926
1927void
1928delete(name)
1929	char *name;
1930{
1931	struct stat st;
1932
1933	LOGCMD("delete", name);
1934	if (stat(name, &st) < 0) {
1935		perror_reply(550, name);
1936		return;
1937	}
1938	if ((st.st_mode&S_IFMT) == S_IFDIR) {
1939		if (rmdir(name) < 0) {
1940			perror_reply(550, name);
1941			return;
1942		}
1943		goto done;
1944	}
1945	if (unlink(name) < 0) {
1946		perror_reply(550, name);
1947		return;
1948	}
1949done:
1950	ack("DELE");
1951}
1952
1953void
1954cwd(path)
1955	char *path;
1956{
1957	FILE *message;
1958
1959	if (chdir(path) < 0)
1960		perror_reply(550, path);
1961	else {
1962		if ((message = fopen(_PATH_CWDMESG, "r")) != NULL) {
1963			char *cp, line[LINE_MAX];
1964
1965			while (fgets(line, sizeof(line), message) != NULL) {
1966				if ((cp = strchr(line, '\n')) != NULL)
1967					*cp = '\0';
1968				lreply(250, "%s", line);
1969			}
1970			(void) fflush(stdout);
1971			(void) fclose(message);
1972		}
1973		ack("CWD");
1974	}
1975}
1976
1977void
1978replydirname(name, message)
1979	const char *name, *message;
1980{
1981	char *p, *ep;
1982	char npath[MAXPATHLEN * 2];
1983
1984	p = npath;
1985	ep = &npath[sizeof(npath) - 1];
1986	while (*name) {
1987		if (*name == '"') {
1988			if (ep - p < 2)
1989				break;
1990			*p++ = *name++;
1991			*p++ = '"';
1992		} else {
1993			if (ep - p < 1)
1994				break;
1995			*p++ = *name++;
1996		}
1997	}
1998	*p = '\0';
1999	reply(257, "\"%s\" %s", npath, message);
2000}
2001
2002void
2003makedir(name)
2004	char *name;
2005{
2006
2007	LOGCMD("mkdir", name);
2008	if (mkdir(name, 0777) < 0)
2009		perror_reply(550, name);
2010	else
2011		replydirname(name, "directory created.");
2012}
2013
2014void
2015removedir(name)
2016	char *name;
2017{
2018
2019	LOGCMD("rmdir", name);
2020	if (rmdir(name) < 0)
2021		perror_reply(550, name);
2022	else
2023		ack("RMD");
2024}
2025
2026void
2027pwd()
2028{
2029	char path[MAXPATHLEN];
2030
2031	if (getcwd(path, sizeof(path)) == NULL)
2032		reply(550, "Can't get current directory: %s.", strerror(errno));
2033	else
2034		replydirname(path, "is current directory.");
2035}
2036
2037char *
2038renamefrom(name)
2039	char *name;
2040{
2041	struct stat st;
2042
2043	if (stat(name, &st) < 0) {
2044		perror_reply(550, name);
2045		return ((char *)0);
2046	}
2047	reply(350, "File exists, ready for destination name");
2048	return (name);
2049}
2050
2051void
2052renamecmd(from, to)
2053	char *from, *to;
2054{
2055
2056	LOGCMD2("rename", from, to);
2057	if (rename(from, to) < 0)
2058		perror_reply(550, "rename");
2059	else
2060		ack("RNTO");
2061}
2062
2063static void
2064dolog(sa)
2065	struct sockaddr *sa;
2066{
2067	char hbuf[sizeof(remotehost)];
2068
2069	getnameinfo(sa, sa->sa_len, hbuf, sizeof(hbuf), NULL, 0, 0);
2070	(void) strlcpy(remotehost, hbuf, sizeof(remotehost));
2071
2072#ifdef HASSETPROCTITLE
2073	snprintf(proctitle, sizeof(proctitle), "%s: connected", remotehost);
2074	setproctitle("%s", proctitle);
2075#endif /* HASSETPROCTITLE */
2076
2077	if (logging)
2078		syslog(LOG_INFO, "connection from %s", remotehost);
2079}
2080
2081/*
2082 * Record logout in wtmp file
2083 * and exit with supplied status.
2084 */
2085void
2086dologout(status)
2087	int status;
2088{
2089
2090	transflag = 0;
2091
2092	if (logged_in) {
2093		sigprocmask(SIG_BLOCK, &allsigs, NULL);
2094		(void) seteuid((uid_t)0);
2095		ftpdlogwtmp(ttyline, "", "");
2096		if (doutmp)
2097			logout(utmp.ut_line);
2098	}
2099	/* beware of flushing buffers after a SIGPIPE */
2100	_exit(status);
2101}
2102
2103static void
2104myoob(signo)
2105	int signo;
2106{
2107	char *cp;
2108	int save_errno = errno;
2109
2110	/* only process if transfer occurring */
2111	if (!transflag)
2112		return;
2113	cp = tmpline;
2114	if (getline(cp, 7, stdin) == NULL) {
2115		reply(221, "You could at least say goodbye.");
2116		dologout(0);
2117	}
2118	upper(cp);
2119	if (strcmp(cp, "ABOR\r\n") == 0) {
2120		tmpline[0] = '\0';
2121		reply(426, "Transfer aborted. Data connection closed.");
2122		reply(226, "Abort successful");
2123		longjmp(urgcatch, 1);
2124	}
2125	if (strcmp(cp, "STAT\r\n") == 0) {
2126		tmpline[0] = '\0';
2127		if (file_size != (off_t) -1)
2128			reply(213, "Status: %qd of %qd bytes transferred",
2129			    byte_count, file_size);
2130		else
2131			reply(213, "Status: %qd bytes transferred", byte_count);
2132	}
2133	errno = save_errno;
2134}
2135
2136/*
2137 * Note: a response of 425 is not mentioned as a possible response to
2138 *	the PASV command in RFC959. However, it has been blessed as
2139 *	a legitimate response by Jon Postel in a telephone conversation
2140 *	with Rick Adams on 25 Jan 89.
2141 */
2142void
2143passive()
2144{
2145	int len, on;
2146	u_char *p, *a;
2147
2148	if (pw == NULL) {
2149		reply(530, "Please login with USER and PASS");
2150		return;
2151	}
2152	if (pdata >= 0)
2153		close(pdata);
2154	/*
2155	 * XXX
2156	 * At this point, it would be nice to have an algorithm that
2157	 * inserted a growing delay in an attack scenario.  Such a thing
2158	 * would look like continual passive sockets being opened, but
2159	 * nothing serious being done with them.  They're not used to
2160	 * move data; the entire attempt is just to use tcp FIN_WAIT
2161	 * resources.
2162	 */
2163	pdata = socket(AF_INET, SOCK_STREAM, 0);
2164	if (pdata < 0) {
2165		perror_reply(425, "Can't open passive connection");
2166		return;
2167	}
2168
2169#ifdef IP_PORTRANGE
2170	on = high_data_ports ? IP_PORTRANGE_HIGH : IP_PORTRANGE_DEFAULT;
2171	if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2172	    (char *)&on, sizeof(on)) < 0)
2173		goto pasv_error;
2174#endif
2175
2176	pasv_addr = ctrl_addr;
2177	pasv_addr.su_sin.sin_port = 0;
2178	if (bind(pdata, (struct sockaddr *)&pasv_addr,
2179		 pasv_addr.su_len) < 0)
2180		goto pasv_error;
2181
2182	len = sizeof(pasv_addr);
2183	if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2184		goto pasv_error;
2185	if (listen(pdata, 1) < 0)
2186		goto pasv_error;
2187	a = (u_char *) &pasv_addr.su_sin.sin_addr;
2188	p = (u_char *) &pasv_addr.su_sin.sin_port;
2189
2190	reply(227, "Entering Passive Mode (%u,%u,%u,%u,%u,%u)", a[0],
2191	    a[1], a[2], a[3], p[0], p[1]);
2192	return;
2193
2194pasv_error:
2195	(void) seteuid((uid_t)pw->pw_uid);
2196	(void) close(pdata);
2197	pdata = -1;
2198	perror_reply(425, "Can't open passive connection");
2199	return;
2200}
2201
2202/*
2203 * convert protocol identifier to/from AF
2204 */
2205int
2206lpsvproto2af(int proto)
2207{
2208
2209	switch (proto) {
2210	case 4:	return AF_INET;
2211#ifdef INET6
2212	case 6:	return AF_INET6;
2213#endif
2214	default: return -1;
2215	}
2216}
2217
2218int
2219af2lpsvproto(int af)
2220{
2221
2222	switch (af) {
2223	case AF_INET:	return 4;
2224#ifdef INET6
2225	case AF_INET6:	return 6;
2226#endif
2227	default:	return -1;
2228	}
2229}
2230
2231int
2232epsvproto2af(int proto)
2233{
2234
2235	switch (proto) {
2236	case 1:	return AF_INET;
2237#ifdef INET6
2238	case 2:	return AF_INET6;
2239#endif
2240	default: return -1;
2241	}
2242}
2243
2244int
2245af2epsvproto(int af)
2246{
2247
2248	switch (af) {
2249	case AF_INET:	return 1;
2250#ifdef INET6
2251	case AF_INET6:	return 2;
2252#endif
2253	default:	return -1;
2254	}
2255}
2256
2257/*
2258 * 228 Entering Long Passive Mode (af, hal, h1, h2, h3,..., pal, p1, p2...)
2259 * 229 Entering Extended Passive Mode (|||port|)
2260 */
2261void
2262long_passive(char *cmd, int pf)
2263{
2264	int len, on;
2265	register u_char *p, *a;
2266
2267	if (!logged_in) {
2268		syslog(LOG_NOTICE, "long passive but not logged in");
2269		reply(503, "Login with USER first.");
2270		return;
2271	}
2272
2273	if (pf != PF_UNSPEC && ctrl_addr.su_family != pf) {
2274		/*
2275		 * XXX
2276		 * only EPRT/EPSV ready clients will understand this
2277		 */
2278		if (strcmp(cmd, "EPSV") != 0)
2279			reply(501, "Network protocol mismatch"); /*XXX*/
2280		else
2281			epsv_protounsupp("Network protocol mismatch");
2282
2283		return;
2284	}
2285
2286	if (pdata >= 0)
2287		close(pdata);
2288	/*
2289	 * XXX
2290	 * At this point, it would be nice to have an algorithm that
2291	 * inserted a growing delay in an attack scenario.  Such a thing
2292	 * would look like continual passive sockets being opened, but
2293	 * nothing serious being done with them.  They not used to move
2294	 * data; the entire attempt is just to use tcp FIN_WAIT
2295	 * resources.
2296	 */
2297	pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2298	if (pdata < 0) {
2299		perror_reply(425, "Can't open passive connection");
2300		return;
2301	}
2302
2303	switch (ctrl_addr.su_family) {
2304	case AF_INET:
2305#ifdef IP_PORTRANGE
2306		on = high_data_ports ? IP_PORTRANGE_HIGH : IP_PORTRANGE_DEFAULT;
2307		if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2308		    (char *)&on, sizeof(on)) < 0)
2309			goto pasv_error;
2310#endif
2311		break;
2312	case AF_INET6:
2313#ifdef IPV6_PORTRANGE
2314		on = high_data_ports ? IPV6_PORTRANGE_HIGH
2315				     : IPV6_PORTRANGE_DEFAULT;
2316		if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2317		    (char *)&on, sizeof(on)) < 0)
2318			goto pasv_error;
2319#endif
2320		break;
2321	}
2322
2323	pasv_addr = ctrl_addr;
2324	pasv_addr.su_port = 0;
2325	(void) seteuid((uid_t) 0);
2326	if (bind(pdata, (struct sockaddr *) &pasv_addr, pasv_addr.su_len) < 0) {
2327		(void) seteuid((uid_t) pw->pw_uid);
2328		goto pasv_error;
2329	}
2330	(void) seteuid((uid_t) pw->pw_uid);
2331	len = pasv_addr.su_len;
2332	if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2333		goto pasv_error;
2334	if (listen(pdata, 1) < 0)
2335		goto pasv_error;
2336	p = (u_char *) &pasv_addr.su_port;
2337
2338	if (strcmp(cmd, "LPSV") == 0) {
2339		switch (pasv_addr.su_family) {
2340		case AF_INET:
2341			a = (u_char *) &pasv_addr.su_sin.sin_addr;
2342			reply(228,
2343			    "Entering Long Passive Mode (%u,%u,%u,%u,%u,%u,%u,%u,%u)",
2344			    4, 4, a[0], a[1], a[2], a[3], 2, p[0], p[1]);
2345			return;
2346		case AF_INET6:
2347			a = (char *) &pasv_addr.su_sin6.sin6_addr;
2348			reply(228,
2349			    "Entering Long Passive Mode (%u,%u,%u,%u,%u,%u,"
2350			    "%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u)",
2351				6, 16, a[0], a[1], a[2], a[3], a[4],
2352				a[5], a[6], a[7], a[8], a[9], a[10],
2353				a[11], a[12], a[13], a[14], a[15],
2354				2, p[0], p[1]);
2355			return;
2356		}
2357	} else if (strcmp(cmd, "EPSV") == 0) {
2358		switch (pasv_addr.su_family) {
2359		case AF_INET:
2360		case AF_INET6:
2361			reply(229, "Entering Extended Passive Mode (|||%u|)",
2362			    ntohs(pasv_addr.su_port));
2363			return;
2364		}
2365	} else {
2366		/* more proper error code? */
2367	}
2368
2369  pasv_error:
2370	(void) close(pdata);
2371	pdata = -1;
2372	perror_reply(425, "Can't open passive connection");
2373	return;
2374}
2375
2376/*
2377 * EPRT |proto|addr|port|
2378 */
2379int
2380extended_port(const char *arg)
2381{
2382	char *tmp = NULL;
2383	char *result[3];
2384	char *p, *q;
2385	char delim;
2386	struct addrinfo hints;
2387	struct addrinfo *res = NULL;
2388	int i;
2389	unsigned long proto;
2390
2391	if (epsvall) {
2392		reply(501, "EPRT disallowed after EPSV ALL");
2393		return -1;
2394	}
2395
2396	usedefault = 0;
2397	if (pdata >= 0) {
2398		(void) close(pdata);
2399		pdata = -1;
2400	}
2401
2402	tmp = strdup(arg);
2403	if (!tmp) {
2404		fatal("not enough core.");
2405		/*NOTREACHED*/
2406	}
2407	p = tmp;
2408	delim = p[0];
2409	p++;
2410	memset(result, 0, sizeof(result));
2411	for (i = 0; i < 3; i++) {
2412		q = strchr(p, delim);
2413		if (!q || *q != delim)
2414			goto parsefail;
2415		*q++ = '\0';
2416		result[i] = p;
2417		p = q;
2418	}
2419
2420	/* some more sanity check */
2421	p = NULL;
2422	(void)strtoul(result[2], &p, 10);
2423	if (!*result[2] || *p)
2424		goto protounsupp;
2425	p = NULL;
2426	proto = strtoul(result[0], &p, 10);
2427	if (!*result[0] || *p)
2428		goto protounsupp;
2429
2430	memset(&hints, 0, sizeof(hints));
2431	hints.ai_family = epsvproto2af((int)proto);
2432	if (hints.ai_family < 0)
2433		goto protounsupp;
2434	hints.ai_socktype = SOCK_STREAM;
2435	hints.ai_flags = AI_NUMERICHOST;	/*no DNS*/
2436	if (getaddrinfo(result[1], result[2], &hints, &res))
2437		goto parsefail;
2438	if (res->ai_next)
2439		goto parsefail;
2440	if (sizeof(data_dest) < res->ai_addrlen)
2441		goto parsefail;
2442	memcpy(&data_dest, res->ai_addr, res->ai_addrlen);
2443	if (his_addr.su_family == AF_INET6 &&
2444	    data_dest.su_family == AF_INET6) {
2445		/* XXX more sanity checks! */
2446		data_dest.su_sin6.sin6_scope_id =
2447		    his_addr.su_sin6.sin6_scope_id;
2448	}
2449	if (pdata >= 0) {
2450		(void) close(pdata);
2451		pdata = -1;
2452	}
2453	reply(200, "EPRT command successful.");
2454
2455	if (tmp)
2456		free(tmp);
2457	if (res)
2458		freeaddrinfo(res);
2459	return 0;
2460
2461parsefail:
2462	reply(500, "Invalid argument, rejected.");
2463	usedefault = 1;
2464	if (tmp)
2465		free(tmp);
2466	if (res)
2467		freeaddrinfo(res);
2468	return -1;
2469
2470protounsupp:
2471	epsv_protounsupp("Protocol not supported");
2472	usedefault = 1;
2473	if (tmp)
2474		free(tmp);
2475	if (res)
2476		freeaddrinfo(res);
2477	return -1;
2478}
2479
2480/*
2481 * 522 Protocol not supported (proto,...)
2482 * as we assume address family for control and data connections are the same,
2483 * we do not return the list of address families we support - instead, we
2484 * return the address family of the control connection.
2485 */
2486void
2487epsv_protounsupp(const char *message)
2488{
2489	int proto;
2490
2491	proto = af2epsvproto(ctrl_addr.su_family);
2492	if (proto < 0)
2493		reply(501, "%s", message);	/*XXX*/
2494	else
2495		reply(522, "%s, use (%d)", message, proto);
2496}
2497
2498/*
2499 * Generate unique name for file with basename "local".
2500 * The file named "local" is already known to exist.
2501 * Generates failure reply on error.
2502 */
2503static int
2504guniquefd(local, nam)
2505	char *local;
2506	char **nam;
2507{
2508	static char new[MAXPATHLEN];
2509	struct stat st;
2510	int count, len, fd;
2511	char *cp;
2512
2513	cp = strrchr(local, '/');
2514	if (cp)
2515		*cp = '\0';
2516	if (stat(cp ? local : ".", &st) < 0) {
2517		perror_reply(553, cp ? local : ".");
2518		return (-1);
2519	}
2520	if (cp)
2521		*cp = '/';
2522	len = strlcpy(new, local, sizeof(new));
2523	if (len+2+1 >= sizeof(new)-1)
2524		return (-1);
2525	cp = new + len;
2526	*cp++ = '.';
2527	for (count = 1; count < 100; count++) {
2528		(void)snprintf(cp, sizeof(new) - (cp - new), "%d", count);
2529		fd = open(new, O_RDWR|O_CREAT|O_EXCL, 0666);
2530		if (fd == -1)
2531			continue;
2532		if (nam)
2533			*nam = new;
2534		return (fd);
2535	}
2536	reply(452, "Unique file name cannot be created.");
2537	return (-1);
2538}
2539
2540/*
2541 * Format and send reply containing system error number.
2542 */
2543void
2544perror_reply(code, string)
2545	int code;
2546	char *string;
2547{
2548
2549	reply(code, "%s: %s.", string, strerror(errno));
2550}
2551
2552static char *onefile[] = {
2553	"",
2554	0
2555};
2556
2557void
2558send_file_list(whichf)
2559	char *whichf;
2560{
2561	struct stat st;
2562	DIR *dirp = NULL;
2563	struct dirent *dir;
2564	FILE *dout = NULL;
2565	char **dirlist, *dirname;
2566	int simple = 0;
2567	int freeglob = 0;
2568	glob_t gl;
2569
2570	if (strpbrk(whichf, "~{[*?") != NULL) {
2571		memset(&gl, 0, sizeof(gl));
2572		freeglob = 1;
2573		if (glob(whichf,
2574		    GLOB_BRACE|GLOB_NOCHECK|GLOB_QUOTE|GLOB_TILDE|GLOB_LIMIT,
2575		    0, &gl)) {
2576			reply(550, "not found");
2577			goto out;
2578		} else if (gl.gl_pathc == 0) {
2579			errno = ENOENT;
2580			perror_reply(550, whichf);
2581			goto out;
2582		}
2583		dirlist = gl.gl_pathv;
2584	} else {
2585		onefile[0] = whichf;
2586		dirlist = onefile;
2587		simple = 1;
2588	}
2589
2590	if (setjmp(urgcatch)) {
2591		transflag = 0;
2592		goto out;
2593	}
2594	while ((dirname = *dirlist++)) {
2595		if (stat(dirname, &st) < 0) {
2596			/*
2597			 * If user typed "ls -l", etc, and the client
2598			 * used NLST, do what the user meant.
2599			 */
2600			if (dirname[0] == '-' && *dirlist == NULL &&
2601			    transflag == 0) {
2602				retrieve("/bin/ls %s", dirname);
2603				goto out;
2604			}
2605			perror_reply(550, whichf);
2606			if (dout != NULL) {
2607				(void) fclose(dout);
2608				transflag = 0;
2609				data = -1;
2610				pdata = -1;
2611			}
2612			goto out;
2613		}
2614
2615		if (S_ISREG(st.st_mode)) {
2616			if (dout == NULL) {
2617				dout = dataconn("file list", (off_t)-1, "w");
2618				if (dout == NULL)
2619					goto out;
2620				transflag++;
2621			}
2622			fprintf(dout, "%s%s\n", dirname,
2623				type == TYPE_A ? "\r" : "");
2624			byte_count += strlen(dirname) + 1;
2625			continue;
2626		} else if (!S_ISDIR(st.st_mode))
2627			continue;
2628
2629		if ((dirp = opendir(dirname)) == NULL)
2630			continue;
2631
2632		while ((dir = readdir(dirp)) != NULL) {
2633			char nbuf[MAXPATHLEN];
2634
2635			if (dir->d_name[0] == '.' && dir->d_namlen == 1)
2636				continue;
2637			if (dir->d_name[0] == '.' && dir->d_name[1] == '.' &&
2638			    dir->d_namlen == 2)
2639				continue;
2640
2641			snprintf(nbuf, sizeof(nbuf), "%s/%s", dirname,
2642				 dir->d_name);
2643
2644			/*
2645			 * We have to do a stat to insure it's
2646			 * not a directory or special file.
2647			 */
2648			if (simple || (stat(nbuf, &st) == 0 &&
2649			    S_ISREG(st.st_mode))) {
2650				if (dout == NULL) {
2651					dout = dataconn("file list", (off_t)-1,
2652						"w");
2653					if (dout == NULL)
2654						goto out;
2655					transflag++;
2656				}
2657				if (nbuf[0] == '.' && nbuf[1] == '/')
2658					fprintf(dout, "%s%s\n", &nbuf[2],
2659						type == TYPE_A ? "\r" : "");
2660				else
2661					fprintf(dout, "%s%s\n", nbuf,
2662						type == TYPE_A ? "\r" : "");
2663				byte_count += strlen(nbuf) + 1;
2664			}
2665		}
2666		(void) closedir(dirp);
2667	}
2668
2669	if (dout == NULL)
2670		reply(550, "No files found.");
2671	else if (ferror(dout) != 0)
2672		perror_reply(550, "Data connection");
2673	else
2674		reply(226, "Transfer complete.");
2675
2676	transflag = 0;
2677	if (dout != NULL)
2678		(void) fclose(dout);
2679	else {
2680		if (pdata >= 0)
2681			close(pdata);
2682	}
2683	data = -1;
2684	pdata = -1;
2685out:
2686	if (freeglob) {
2687		freeglob = 0;
2688		globfree(&gl);
2689	}
2690}
2691
2692static void
2693reapchild(signo)
2694	int signo;
2695{
2696	int save_errno = errno;
2697
2698	while (wait3(NULL, WNOHANG, NULL) > 0)
2699		;
2700	errno = save_errno;
2701}
2702
2703void
2704logxfer(name, size, start)
2705	char *name;
2706	off_t size;
2707	time_t start;
2708{
2709	char buf[400 + MAXHOSTNAMELEN*4 + MAXPATHLEN*4];
2710	char dir[MAXPATHLEN], path[MAXPATHLEN], rpath[MAXPATHLEN];
2711	char vremotehost[MAXHOSTNAMELEN*4], vpath[MAXPATHLEN*4];
2712	char *vpw;
2713	time_t now;
2714	int len;
2715
2716	if ((statfd >= 0) && (getcwd(dir, sizeof(dir)) != NULL)) {
2717		time(&now);
2718
2719		vpw = malloc(strlen(guest ? guestpw : pw->pw_name) * 4 + 1);
2720		if (vpw == NULL)
2721			return;
2722
2723		snprintf(path, sizeof(path), "%s/%s", dir, name);
2724		if (realpath(path, rpath) == NULL)
2725			strlcpy(rpath, path, sizeof(rpath));
2726		strvis(vpath, rpath, VIS_SAFE|VIS_NOSLASH);
2727
2728		strvis(vremotehost, remotehost, VIS_SAFE|VIS_NOSLASH);
2729		strvis(vpw, guest? guestpw : pw->pw_name, VIS_SAFE|VIS_NOSLASH);
2730
2731		len = snprintf(buf, sizeof(buf),
2732		    "%.24s %d %s %qd %s %c %s %c %c %s ftp %d %s %s\n",
2733		    ctime(&now), now - start + (now == start),
2734		    vremotehost, (long long) size, vpath,
2735		    ((type == TYPE_A) ? 'a' : 'b'), "*" /* none yet */,
2736		    'o', ((guest) ? 'a' : 'r'),
2737		    vpw, 0 /* none yet */,
2738		    ((guest) ? "*" : pw->pw_name), dhostname);
2739		if (len >= sizeof(buf)) {
2740			len = sizeof(buf);
2741			buf[sizeof(buf) - 1] = '\n';
2742		}
2743		write(statfd, buf, len);
2744		free(vpw);
2745	}
2746}
2747
2748#if defined(TCPWRAPPERS)
2749static int
2750check_host(sa)
2751	struct sockaddr *sa;
2752{
2753	struct sockaddr_in *sin;
2754	struct hostent *hp;
2755	char *addr;
2756
2757	if (sa->sa_family != AF_INET)
2758		return 1;	/*XXX*/
2759
2760	sin = (struct sockaddr_in *)sa;
2761	hp = gethostbyaddr((char *)&sin->sin_addr,
2762	    sizeof(struct in_addr), AF_INET);
2763	addr = inet_ntoa(sin->sin_addr);
2764	if (hp) {
2765		if (!hosts_ctl("ftpd", hp->h_name, addr, STRING_UNKNOWN)) {
2766			syslog(LOG_NOTICE, "tcpwrappers rejected: %s [%s]",
2767			    hp->h_name, addr);
2768			return (0);
2769		}
2770	} else {
2771		if (!hosts_ctl("ftpd", STRING_UNKNOWN, addr, STRING_UNKNOWN)) {
2772			syslog(LOG_NOTICE, "tcpwrappers rejected: [%s]", addr);
2773			return (0);
2774		}
2775	}
2776	return (1);
2777}
2778#endif	/* TCPWRAPPERS */
2779
2780/*
2781 * Allocate space and return a copy of the specified dir.
2782 * If 'dir' begins with a tilde (~), expand it.
2783 */
2784char *
2785copy_dir(dir, pw)
2786	char *dir;
2787	struct passwd *pw;
2788{
2789	char *cp;
2790	char *newdir;
2791	char *user = NULL;
2792	size_t dirsiz;
2793
2794	/* Nothing to expand */
2795	if (dir[0] !=  '~')
2796		return (strdup(dir));
2797
2798	/* "dir" is of form ~user/some/dir, lookup user. */
2799	if (dir[1] != '/' && dir[1] != '\0') {
2800		if ((cp = strchr(dir + 1, '/')) == NULL)
2801		    cp = dir + strlen(dir);
2802		if ((user = malloc(cp - dir)) == NULL)
2803			return (NULL);
2804		strlcpy(user, dir + 1, cp - dir);
2805
2806		/* Only do lookup if it is a different user. */
2807		if (strcmp(user, pw->pw_name) != 0) {
2808			if ((pw = getpwnam(user)) == NULL) {
2809				/* No such user, interpret literally */
2810				free(user);
2811				return(strdup(dir));
2812			}
2813		}
2814	}
2815
2816	/*
2817	 * If there is no directory separator (/) then it is just pw_dir.
2818	 * Otherwise, replace ~foo with  pw_dir.
2819	 */
2820	if ((cp = strchr(dir + 1, '/')) == NULL) {
2821		newdir = strdup(pw->pw_dir);
2822	} else {
2823		dirsiz = strlen(cp) + strlen(pw->pw_dir) + 1;
2824		if ((newdir = malloc(dirsiz)) == NULL)
2825			return (NULL);
2826		strcpy(newdir, pw->pw_dir);
2827		strcat(newdir, cp);
2828	}
2829
2830	if (user)
2831		free(user);
2832	return(newdir);
2833}
2834