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