1/*
2 * Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 *    must display the following acknowledgement:
15 *	This product includes software developed by the University of
16 *	California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 *    may be used to endorse or promote products derived from this software
19 *    without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 */
33
34#if 0
35#ifndef lint
36static char copyright[] =
37"@(#) Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994\n\
38	The Regents of the University of California.  All rights reserved.\n";
39#endif /* not lint */
40#endif
41
42#ifndef lint
43#if 0
44static char sccsid[] = "@(#)ftpd.c	8.4 (Berkeley) 4/16/94";
45#endif
46#endif /* not lint */
47
48#include <sys/cdefs.h>
49__FBSDID("$FreeBSD: src/libexec/ftpd/ftpd.c,v 1.212 2007/04/18 22:43:39 yar Exp $");
50
51/*
52 * FTP server.
53 */
54#include <sys/param.h>
55#include <sys/ioctl.h>
56//#include <sys/mman.h>
57#include <sys/socket.h>
58#include <sys/stat.h>
59#include <sys/time.h>
60#include <sys/wait.h>
61
62#include <netinet/in.h>
63#include <netinet/in_systm.h>
64#include <netinet/ip.h>
65#include <netinet/tcp.h>
66
67#define	FTP_NAMES
68#include <arpa/ftp.h>
69#include <arpa/inet.h>
70#include <arpa/telnet.h>
71
72#include <ctype.h>
73#include <dirent.h>
74#include <err.h>
75#include <errno.h>
76#include <fcntl.h>
77#include <glob.h>
78#include <limits.h>
79#include <netdb.h>
80#include <pwd.h>
81#include <grp.h>
82#ifdef HAVE_LIBOPIE
83#include <opie.h>
84#endif
85#include <signal.h>
86#include <stdint.h>
87#include <stdio.h>
88#include <stdlib.h>
89#include <string.h>
90#include <syslog.h>
91#include <time.h>
92#include <unistd.h>
93#include <libutil.h>
94#ifdef	LOGIN_CAP
95#include <login_cap.h>
96#endif
97
98#ifdef USE_PAM
99#include <security/pam_appl.h>
100#endif
101
102#ifdef __HAIKU__
103#include <shadow.h>
104#endif
105
106#include "pathnames.h"
107#include "extern.h"
108
109#include <stdarg.h>
110
111static char version[] = "Version 6.00LS";
112#undef main
113
114extern	off_t restart_point;
115extern	char cbuf[];
116
117union sockunion ctrl_addr;
118union sockunion data_source;
119union sockunion data_dest;
120union sockunion his_addr;
121union sockunion pasv_addr;
122
123int	daemon_mode;
124int	data;
125int	dataport;
126int	hostinfo = 1;	/* print host-specific info in messages */
127int	logged_in;
128struct	passwd *pw;
129char	*homedir;
130int	ftpdebug;
131int	timeout = 900;    /* timeout after 15 minutes of inactivity */
132int	maxtimeout = 7200;/* don't allow idle time to be set beyond 2 hours */
133int	logging;
134int	restricted_data_ports = 1;
135int	paranoid = 1;	  /* be extra careful about security */
136int	anon_only = 0;    /* Only anonymous ftp allowed */
137int	assumeutf8 = 0;   /* Assume that server file names are in UTF-8 */
138int	guest;
139int	dochroot;
140char	*chrootdir;
141int	dowtmp = 1;
142int	stats;
143int	statfd = -1;
144int	type;
145int	form;
146int	stru;			/* avoid C keyword */
147int	mode;
148int	usedefault = 1;		/* for data transfers */
149int	pdata = -1;		/* for passive mode */
150int	readonly = 0;		/* Server is in readonly mode.	*/
151int	noepsv = 0;		/* EPSV command is disabled.	*/
152int	noretr = 0;		/* RETR command is disabled.	*/
153int	noguestretr = 0;	/* RETR command is disabled for anon users. */
154int	noguestmkd = 0;		/* MKD command is disabled for anon users. */
155int	noguestmod = 1;		/* anon users may not modify existing files. */
156
157off_t	file_size;
158off_t	byte_count;
159#if !defined(CMASK) || CMASK == 0
160#undef CMASK
161#define CMASK 027
162#endif
163int	defumask = CMASK;		/* default umask value */
164char	tmpline[7];
165char	*hostname;
166int	epsvall = 0;
167
168#ifdef VIRTUAL_HOSTING
169char	*ftpuser;
170
171static struct ftphost {
172	struct ftphost	*next;
173	struct addrinfo *hostinfo;
174	char		*hostname;
175	char		*anonuser;
176	char		*statfile;
177	char		*welcome;
178	char		*loginmsg;
179} *thishost, *firsthost;
180
181#endif
182char	remotehost[NI_MAXHOST];
183char	*ident = NULL;
184
185static char	ttyline[20];
186char		*tty = ttyline;		/* for klogin */
187
188#ifdef USE_PAM
189static int	auth_pam(struct passwd**, const char*);
190pam_handle_t	*pamh = NULL;
191#endif
192
193#ifdef HAVE_LIBOPIE
194static struct opie	opiedata;
195static char		opieprompt[OPIE_CHALLENGE_MAX+1];
196#endif
197static int		pwok;
198
199char	*pid_file = NULL; /* means default location to pidfile(3) */
200
201/*
202 * Limit number of pathnames that glob can return.
203 * A limit of 0 indicates the number of pathnames is unlimited.
204 */
205#define MAXGLOBARGS	16384
206#
207
208/*
209 * Timeout intervals for retrying connections
210 * to hosts that don't accept PORT cmds.  This
211 * is a kludge, but given the problems with TCP...
212 */
213#define	SWAITMAX	90	/* wait at most 90 seconds */
214#define	SWAITINT	5	/* interval between retries */
215
216int	swaitmax = SWAITMAX;
217int	swaitint = SWAITINT;
218
219#ifdef SETPROCTITLE
220char	proctitle[LINE_MAX];	/* initial part of title */
221#endif /* SETPROCTITLE */
222
223#define LOGCMD(cmd, file)		logcmd((cmd), (file), NULL, -1)
224#define LOGCMD2(cmd, file1, file2)	logcmd((cmd), (file1), (file2), -1)
225#define LOGBYTES(cmd, file, cnt)	logcmd((cmd), (file), NULL, (cnt))
226
227static	volatile sig_atomic_t recvurg;
228static	int transflag;		/* NB: for debugging only */
229
230#define STARTXFER	flagxfer(1)
231#define ENDXFER		flagxfer(0)
232
233#define START_UNSAFE	maskurg(1)
234#define END_UNSAFE	maskurg(0)
235
236/* It's OK to put an `else' clause after this macro. */
237#define CHECKOOB(action)						\
238	if (recvurg) {							\
239		recvurg = 0;						\
240		if (myoob()) {						\
241			ENDXFER;					\
242			action;						\
243		}							\
244	}
245
246#ifdef VIRTUAL_HOSTING
247static void	 inithosts(int);
248static void	 selecthost(union sockunion *);
249#endif
250static void	 ack(char *);
251static void	 sigurg(int);
252static void	 maskurg(int);
253static void	 flagxfer(int);
254static int	 myoob(void);
255static int	 checkuser(char *, char *, int, char **);
256static FILE	*dataconn(char *, off_t, char *);
257static void	 dolog(struct sockaddr *);
258static void	 end_login(void);
259static FILE	*getdatasock(char *);
260static int	 guniquefd(char *, char **);
261static void	 lostconn(int);
262static void	 sigquit(int);
263static int	 receive_data(FILE *, FILE *);
264static int	 send_data(FILE *, FILE *, size_t, off_t, int);
265static struct passwd *
266		 sgetpwnam(char *);
267static char	*sgetsave(char *);
268static void	 reapchild(int);
269static void	 appendf(char **, char *, ...) __printflike(2, 3);
270static void	 logcmd(char *, char *, char *, off_t);
271static void      logxfer(char *, off_t, time_t);
272static char	*doublequote(char *);
273static int	*socksetup(int, char *, const char *);
274
275int
276main(int argc, char *argv[], char **envp)
277{
278	socklen_t addrlen;
279	int ch, on = 1, tos;
280	char *cp, line[LINE_MAX];
281	FILE *fd;
282	char	*bindname = NULL;
283	const char *bindport = "ftp";
284	int	family = AF_UNSPEC;
285	struct sigaction sa;
286
287	tzset();		/* in case no timezone database in ~ftp */
288	sigemptyset(&sa.sa_mask);
289	sa.sa_flags = SA_RESTART;
290
291	/*
292	 * Prevent diagnostic messages from appearing on stderr.
293	 * We run as a daemon or from inetd; in both cases, there's
294	 * more reason in logging to syslog.
295	 */
296	(void) freopen(_PATH_DEVNULL, "w", stderr);
297	opterr = 0;
298
299	/*
300	 * LOG_NDELAY sets up the logging connection immediately,
301	 * necessary for anonymous ftp's that chroot and can't do it later.
302	 */
303	openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
304
305	while ((ch = getopt(argc, argv,
306	                    "468a:AdDEhlmMoOp:P:rRSt:T:u:UvW")) != -1) {
307		switch (ch) {
308		case '4':
309			family = (family == AF_INET6) ? AF_UNSPEC : AF_INET;
310			break;
311
312		case '6':
313			family = (family == AF_INET) ? AF_UNSPEC : AF_INET6;
314			break;
315
316		case '8':
317			assumeutf8 = 1;
318			break;
319
320		case 'a':
321			bindname = optarg;
322			break;
323
324		case 'A':
325			anon_only = 1;
326			break;
327
328		case 'd':
329			ftpdebug++;
330			break;
331
332		case 'D':
333			daemon_mode++;
334			break;
335
336		case 'E':
337			noepsv = 1;
338			break;
339
340		case 'h':
341			hostinfo = 0;
342			break;
343
344		case 'l':
345			logging++;	/* > 1 == extra logging */
346			break;
347
348		case 'm':
349			noguestmod = 0;
350			break;
351
352		case 'M':
353			noguestmkd = 1;
354			break;
355
356		case 'o':
357			noretr = 1;
358			break;
359
360		case 'O':
361			noguestretr = 1;
362			break;
363
364		case 'p':
365			pid_file = optarg;
366			break;
367
368		case 'P':
369			bindport = optarg;
370			break;
371
372		case 'r':
373			readonly = 1;
374			break;
375
376		case 'R':
377			paranoid = 0;
378			break;
379
380		case 'S':
381			stats++;
382			break;
383
384		case 't':
385			timeout = atoi(optarg);
386			if (maxtimeout < timeout)
387				maxtimeout = timeout;
388			break;
389
390		case 'T':
391			maxtimeout = atoi(optarg);
392			if (timeout > maxtimeout)
393				timeout = maxtimeout;
394			break;
395
396		case 'u':
397		    {
398			long val = 0;
399
400			val = strtol(optarg, &optarg, 8);
401			if (*optarg != '\0' || val < 0)
402				syslog(LOG_WARNING, "bad value for -u");
403			else
404				defumask = val;
405			break;
406		    }
407		case 'U':
408			restricted_data_ports = 0;
409			break;
410
411		case 'v':
412			ftpdebug++;
413			break;
414
415		case 'W':
416			dowtmp = 0;
417			break;
418
419		default:
420			syslog(LOG_WARNING, "unknown flag -%c ignored", optopt);
421			break;
422		}
423	}
424
425	if (daemon_mode) {
426		int *ctl_sock, fd, maxfd = -1, nfds, i;
427		fd_set defreadfds, readfds;
428		pid_t pid;
429		struct pidfh *pfh;
430
431		if ((pfh = pidfile_open(pid_file, 0600, &pid)) == NULL) {
432			if (errno == EEXIST) {
433				syslog(LOG_ERR, "%s already running, pid %d",
434				       getprogname(), (int)pid);
435				exit(1);
436			}
437			syslog(LOG_WARNING, "pidfile_open: %m");
438		}
439
440		/*
441		 * Detach from parent.
442		 */
443		if (daemon(1, 1) < 0) {
444			syslog(LOG_ERR, "failed to become a daemon");
445			exit(1);
446		}
447
448		if (pfh != NULL && pidfile_write(pfh) == -1)
449			syslog(LOG_WARNING, "pidfile_write: %m");
450
451		sa.sa_handler = reapchild;
452		(void)sigaction(SIGCHLD, &sa, NULL);
453
454#ifdef VIRTUAL_HOSTING
455		inithosts(family);
456#endif
457
458		/*
459		 * Open a socket, bind it to the FTP port, and start
460		 * listening.
461		 */
462		ctl_sock = socksetup(family, bindname, bindport);
463		if (ctl_sock == NULL)
464			exit(1);
465
466		FD_ZERO(&defreadfds);
467		for (i = 1; i <= *ctl_sock; i++) {
468			FD_SET(ctl_sock[i], &defreadfds);
469			if (listen(ctl_sock[i], 32) < 0) {
470				syslog(LOG_ERR, "control listen: %m");
471				exit(1);
472			}
473			if (maxfd < ctl_sock[i])
474				maxfd = ctl_sock[i];
475		}
476
477		/*
478		 * Loop forever accepting connection requests and forking off
479		 * children to handle them.
480		 */
481		while (1) {
482			FD_COPY(&defreadfds, &readfds);
483			nfds = select(maxfd + 1, &readfds, NULL, NULL, 0);
484			if (nfds <= 0) {
485				if (nfds < 0 && errno != EINTR)
486					syslog(LOG_WARNING, "select: %m");
487				continue;
488			}
489
490			pid = -1;
491                        for (i = 1; i <= *ctl_sock; i++)
492				if (FD_ISSET(ctl_sock[i], &readfds)) {
493					addrlen = sizeof(his_addr);
494					fd = accept(ctl_sock[i],
495					    (struct sockaddr *)&his_addr,
496					    &addrlen);
497					if (fd == -1) {
498						syslog(LOG_WARNING,
499						       "accept: %m");
500						continue;
501					}
502					switch (pid = fork()) {
503					case 0:
504						/* child */
505						(void) dup2(fd, 0);
506						(void) dup2(fd, 1);
507						(void) close(fd);
508						for (i = 1; i <= *ctl_sock; i++)
509							close(ctl_sock[i]);
510						if (pfh != NULL)
511							pidfile_close(pfh);
512						goto gotchild;
513					case -1:
514						syslog(LOG_WARNING, "fork: %m");
515						/* FALLTHROUGH */
516					default:
517						close(fd);
518					}
519				}
520		}
521	} else {
522		addrlen = sizeof(his_addr);
523		if (getpeername(0, (struct sockaddr *)&his_addr, &addrlen) < 0) {
524			syslog(LOG_ERR, "getpeername (%s): %m",argv[0]);
525			exit(1);
526		}
527
528#ifdef VIRTUAL_HOSTING
529		if (his_addr.su_family == AF_INET6 &&
530		    IN6_IS_ADDR_V4MAPPED(&his_addr.su_sin6.sin6_addr))
531			family = AF_INET;
532		else
533			family = his_addr.su_family;
534		inithosts(family);
535#endif
536	}
537
538gotchild:
539	sa.sa_handler = SIG_DFL;
540	(void)sigaction(SIGCHLD, &sa, NULL);
541
542	sa.sa_handler = sigurg;
543	sa.sa_flags = 0;		/* don't restart syscalls for SIGURG */
544	(void)sigaction(SIGURG, &sa, NULL);
545
546	sigfillset(&sa.sa_mask);	/* block all signals in handler */
547	sa.sa_flags = SA_RESTART;
548	sa.sa_handler = sigquit;
549	(void)sigaction(SIGHUP, &sa, NULL);
550	(void)sigaction(SIGINT, &sa, NULL);
551	(void)sigaction(SIGQUIT, &sa, NULL);
552	(void)sigaction(SIGTERM, &sa, NULL);
553
554	sa.sa_handler = lostconn;
555	(void)sigaction(SIGPIPE, &sa, NULL);
556
557	addrlen = sizeof(ctrl_addr);
558	if (getsockname(0, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) {
559		syslog(LOG_ERR, "getsockname (%s): %m",argv[0]);
560		exit(1);
561	}
562	dataport = ntohs(ctrl_addr.su_port) - 1; /* as per RFC 959 */
563#ifdef VIRTUAL_HOSTING
564	/* select our identity from virtual host table */
565	selecthost(&ctrl_addr);
566#endif
567#ifdef IP_TOS
568	if (ctrl_addr.su_family == AF_INET)
569      {
570	tos = IPTOS_LOWDELAY;
571	if (setsockopt(0, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
572		syslog(LOG_WARNING, "control setsockopt (IP_TOS): %m");
573      }
574#endif
575	/*
576	 * Disable Nagle on the control channel so that we don't have to wait
577	 * for peer's ACK before issuing our next reply.
578	 */
579	if (setsockopt(0, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) < 0)
580		syslog(LOG_WARNING, "control setsockopt (TCP_NODELAY): %m");
581
582	data_source.su_port = htons(ntohs(ctrl_addr.su_port) - 1);
583
584	/* set this here so klogin can use it... */
585	(void)snprintf(ttyline, sizeof(ttyline), "ftp%d", (int)getpid());
586
587	/* Try to handle urgent data inline */
588#ifdef SO_OOBINLINE
589	if (setsockopt(0, SOL_SOCKET, SO_OOBINLINE, &on, sizeof(on)) < 0)
590		syslog(LOG_WARNING, "control setsockopt (SO_OOBINLINE): %m");
591#endif
592
593#ifdef	F_SETOWN
594	if (fcntl(fileno(stdin), F_SETOWN, getpid()) == -1)
595		syslog(LOG_ERR, "fcntl F_SETOWN: %m");
596#endif
597	dolog((struct sockaddr *)&his_addr);
598	/*
599	 * Set up default state
600	 */
601	data = -1;
602	type = TYPE_A;
603	form = FORM_N;
604	stru = STRU_F;
605	mode = MODE_S;
606	tmpline[0] = '\0';
607
608	/* If logins are disabled, print out the message. */
609	if ((fd = fopen(_PATH_NOLOGIN,"r")) != NULL) {
610		while (fgets(line, sizeof(line), fd) != NULL) {
611			if ((cp = strchr(line, '\n')) != NULL)
612				*cp = '\0';
613			lreply(530, "%s", line);
614		}
615		(void) fflush(stdout);
616		(void) fclose(fd);
617		reply(530, "System not available.");
618		exit(0);
619	}
620#ifdef VIRTUAL_HOSTING
621	fd = fopen(thishost->welcome, "r");
622#else
623	fd = fopen(_PATH_FTPWELCOME, "r");
624#endif
625	if (fd != NULL) {
626		while (fgets(line, sizeof(line), fd) != NULL) {
627			if ((cp = strchr(line, '\n')) != NULL)
628				*cp = '\0';
629			lreply(220, "%s", line);
630		}
631		(void) fflush(stdout);
632		(void) fclose(fd);
633		/* reply(220,) must follow */
634	}
635#ifndef VIRTUAL_HOSTING
636	if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
637		fatalerror("Ran out of memory.");
638	if (gethostname(hostname, MAXHOSTNAMELEN - 1) < 0)
639		hostname[0] = '\0';
640	hostname[MAXHOSTNAMELEN - 1] = '\0';
641#endif
642	if (hostinfo)
643		reply(220, "%s FTP server (%s) ready.", hostname, version);
644	else
645		reply(220, "FTP server ready.");
646	for (;;)
647		(void) yyparse();
648	/* NOTREACHED */
649}
650
651static void
652lostconn(int signo)
653{
654
655	if (ftpdebug)
656		syslog(LOG_DEBUG, "lost connection");
657	dologout(1);
658}
659
660static void
661sigquit(int signo)
662{
663
664	syslog(LOG_ERR, "got signal %d", signo);
665	dologout(1);
666}
667
668#ifdef VIRTUAL_HOSTING
669/*
670 * read in virtual host tables (if they exist)
671 */
672
673static void
674inithosts(int family)
675{
676	int insert;
677	size_t len;
678	FILE *fp;
679	char *cp, *mp, *line;
680	char *hostname;
681	char *vhost, *anonuser, *statfile, *welcome, *loginmsg;
682	struct ftphost *hrp, *lhrp;
683	struct addrinfo hints, *res, *ai;
684
685	/*
686	 * Fill in the default host information
687	 */
688	if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
689		fatalerror("Ran out of memory.");
690	if (gethostname(hostname, MAXHOSTNAMELEN - 1) < 0)
691		hostname[0] = '\0';
692	hostname[MAXHOSTNAMELEN - 1] = '\0';
693	if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
694		fatalerror("Ran out of memory.");
695	hrp->hostname = hostname;
696	hrp->hostinfo = NULL;
697
698	memset(&hints, 0, sizeof(hints));
699	hints.ai_flags = AI_PASSIVE;
700	hints.ai_family = family;
701	hints.ai_socktype = SOCK_STREAM;
702	if (getaddrinfo(hrp->hostname, NULL, &hints, &res) == 0)
703		hrp->hostinfo = res;
704	hrp->statfile = _PATH_FTPDSTATFILE;
705	hrp->welcome  = _PATH_FTPWELCOME;
706	hrp->loginmsg = _PATH_FTPLOGINMESG;
707	hrp->anonuser = "ftp";
708	hrp->next = NULL;
709	thishost = firsthost = lhrp = hrp;
710	if ((fp = fopen(_PATH_FTPHOSTS, "r")) != NULL) {
711		int addrsize, gothost;
712		void *addr;
713		struct hostent *hp;
714
715		while ((line = fgetln(fp, &len)) != NULL) {
716			int	i, hp_error;
717
718			/* skip comments */
719			if (line[0] == '#')
720				continue;
721			if (line[len - 1] == '\n') {
722				line[len - 1] = '\0';
723				mp = NULL;
724			} else {
725				if ((mp = malloc(len + 1)) == NULL)
726					fatalerror("Ran out of memory.");
727				memcpy(mp, line, len);
728				mp[len] = '\0';
729				line = mp;
730			}
731			cp = strtok(line, " \t");
732			/* skip empty lines */
733			if (cp == NULL)
734				goto nextline;
735			vhost = cp;
736
737			/* set defaults */
738			anonuser = "ftp";
739			statfile = _PATH_FTPDSTATFILE;
740			welcome  = _PATH_FTPWELCOME;
741			loginmsg = _PATH_FTPLOGINMESG;
742
743			/*
744			 * Preparse the line so we can use its info
745			 * for all the addresses associated with
746			 * the virtual host name.
747			 * Field 0, the virtual host name, is special:
748			 * it's already parsed off and will be strdup'ed
749			 * later, after we know its canonical form.
750			 */
751			for (i = 1; i < 5 && (cp = strtok(NULL, " \t")); i++)
752				if (*cp != '-' && (cp = strdup(cp)))
753					switch (i) {
754					case 1:	/* anon user permissions */
755						anonuser = cp;
756						break;
757					case 2: /* statistics file */
758						statfile = cp;
759						break;
760					case 3: /* welcome message */
761						welcome  = cp;
762						break;
763					case 4: /* login message */
764						loginmsg = cp;
765						break;
766					default: /* programming error */
767						abort();
768						/* NOTREACHED */
769					}
770
771			hints.ai_flags = AI_PASSIVE;
772			hints.ai_family = family;
773			hints.ai_socktype = SOCK_STREAM;
774			if (getaddrinfo(vhost, NULL, &hints, &res) != 0)
775				goto nextline;
776			for (ai = res; ai != NULL && ai->ai_addr != NULL;
777			     ai = ai->ai_next) {
778
779			gothost = 0;
780			for (hrp = firsthost; hrp != NULL; hrp = hrp->next) {
781				struct addrinfo *hi;
782
783				for (hi = hrp->hostinfo; hi != NULL;
784				     hi = hi->ai_next)
785					if (hi->ai_addrlen == ai->ai_addrlen &&
786					    memcmp(hi->ai_addr,
787						   ai->ai_addr,
788						   ai->ai_addr->sa_len) == 0) {
789						gothost++;
790						break;
791					}
792				if (gothost)
793					break;
794			}
795			if (hrp == NULL) {
796				if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
797					goto nextline;
798				hrp->hostname = NULL;
799				insert = 1;
800			} else {
801				if (hrp->hostinfo && hrp->hostinfo != res)
802					freeaddrinfo(hrp->hostinfo);
803				insert = 0; /* host already in the chain */
804			}
805			hrp->hostinfo = res;
806
807			/*
808			 * determine hostname to use.
809			 * force defined name if there is a valid alias
810			 * otherwise fallback to primary hostname
811			 */
812			/* XXX: getaddrinfo() can't do alias check */
813			switch(hrp->hostinfo->ai_family) {
814			case AF_INET:
815				addr = &((struct sockaddr_in *)hrp->hostinfo->ai_addr)->sin_addr;
816				addrsize = sizeof(struct in_addr);
817				break;
818			case AF_INET6:
819				addr = &((struct sockaddr_in6 *)hrp->hostinfo->ai_addr)->sin6_addr;
820				addrsize = sizeof(struct in6_addr);
821				break;
822			default:
823				/* should not reach here */
824				freeaddrinfo(hrp->hostinfo);
825				if (insert)
826					free(hrp); /*not in chain, can free*/
827				else
828					hrp->hostinfo = NULL; /*mark as blank*/
829				goto nextline;
830				/* NOTREACHED */
831			}
832			if ((hp = getipnodebyaddr(addr, addrsize,
833						  hrp->hostinfo->ai_family,
834						  &hp_error)) != NULL) {
835				if (strcmp(vhost, hp->h_name) != 0) {
836					if (hp->h_aliases == NULL)
837						vhost = hp->h_name;
838					else {
839						i = 0;
840						while (hp->h_aliases[i] &&
841						       strcmp(vhost, hp->h_aliases[i]) != 0)
842							++i;
843						if (hp->h_aliases[i] == NULL)
844							vhost = hp->h_name;
845					}
846				}
847			}
848			if (hrp->hostname &&
849			    strcmp(hrp->hostname, vhost) != 0) {
850				free(hrp->hostname);
851				hrp->hostname = NULL;
852			}
853			if (hrp->hostname == NULL &&
854			    (hrp->hostname = strdup(vhost)) == NULL) {
855				freeaddrinfo(hrp->hostinfo);
856				hrp->hostinfo = NULL; /* mark as blank */
857				if (hp)
858					freehostent(hp);
859				goto nextline;
860			}
861			hrp->anonuser = anonuser;
862			hrp->statfile = statfile;
863			hrp->welcome  = welcome;
864			hrp->loginmsg = loginmsg;
865			if (insert) {
866				hrp->next  = NULL;
867				lhrp->next = hrp;
868				lhrp = hrp;
869			}
870			if (hp)
871				freehostent(hp);
872		      }
873nextline:
874			if (mp)
875				free(mp);
876		}
877		(void) fclose(fp);
878	}
879}
880
881static void
882selecthost(union sockunion *su)
883{
884	struct ftphost	*hrp;
885	u_int16_t port;
886#ifdef INET6
887	struct in6_addr *mapped_in6 = NULL;
888#endif
889	struct addrinfo *hi;
890
891#ifdef INET6
892	/*
893	 * XXX IPv4 mapped IPv6 addr consideraton,
894	 * specified in rfc2373.
895	 */
896	if (su->su_family == AF_INET6 &&
897	    IN6_IS_ADDR_V4MAPPED(&su->su_sin6.sin6_addr))
898		mapped_in6 = &su->su_sin6.sin6_addr;
899#endif
900
901	hrp = thishost = firsthost;	/* default */
902	port = su->su_port;
903	su->su_port = 0;
904	while (hrp != NULL) {
905	    for (hi = hrp->hostinfo; hi != NULL; hi = hi->ai_next) {
906		if (memcmp(su, hi->ai_addr, hi->ai_addrlen) == 0) {
907			thishost = hrp;
908			goto found;
909		}
910#ifdef INET6
911		/* XXX IPv4 mapped IPv6 addr consideraton */
912		if (hi->ai_addr->sa_family == AF_INET && mapped_in6 != NULL &&
913		    (memcmp(&mapped_in6->s6_addr[12],
914			    &((struct sockaddr_in *)hi->ai_addr)->sin_addr,
915			    sizeof(struct in_addr)) == 0)) {
916			thishost = hrp;
917			goto found;
918		}
919#endif
920	    }
921	    hrp = hrp->next;
922	}
923found:
924	su->su_port = port;
925	/* setup static variables as appropriate */
926	hostname = thishost->hostname;
927	ftpuser = thishost->anonuser;
928}
929#endif
930
931/*
932 * Helper function for sgetpwnam().
933 */
934static char *
935sgetsave(char *s)
936{
937	char *new = malloc(strlen(s) + 1);
938
939	if (new == NULL) {
940		reply(421, "Ran out of memory.");
941		dologout(1);
942		/* NOTREACHED */
943	}
944	(void) strcpy(new, s);
945	return (new);
946}
947
948/*
949 * Save the result of a getpwnam.  Used for USER command, since
950 * the data returned must not be clobbered by any other command
951 * (e.g., globbing).
952 * NB: The data returned by sgetpwnam() will remain valid until
953 * the next call to this function.  Its difference from getpwnam()
954 * is that sgetpwnam() is known to be called from ftpd code only.
955 */
956static struct passwd *
957sgetpwnam(char *name)
958{
959	static struct passwd save;
960	struct passwd *p;
961#ifdef __HAIKU__
962	struct spwd *sp = NULL;
963#endif
964
965	if ((p = getpwnam(name)) == NULL)
966		return (p);
967#ifdef __HAIKU__
968	if (strcmp(p->pw_passwd, "x") == 0) {
969		if ((sp = getspnam(name)) == NULL)
970			return (p);
971	}
972#endif
973	if (save.pw_name) {
974		free(save.pw_name);
975		free(save.pw_passwd);
976		free(save.pw_gecos);
977		free(save.pw_dir);
978		free(save.pw_shell);
979	}
980	save = *p;
981	save.pw_name = sgetsave(p->pw_name);
982#ifdef __HAIKU__
983	if (sp)
984		save.pw_passwd = sgetsave(sp->sp_pwdp);
985	else
986#endif
987	save.pw_passwd = sgetsave(p->pw_passwd);
988	save.pw_gecos = sgetsave(p->pw_gecos);
989	save.pw_dir = sgetsave(p->pw_dir);
990	save.pw_shell = sgetsave(p->pw_shell);
991	return (&save);
992}
993
994static int login_attempts;	/* number of failed login attempts */
995static int askpasswd;		/* had user command, ask for passwd */
996static char curname[MAXLOGNAME];	/* current USER name */
997
998/*
999 * USER command.
1000 * Sets global passwd pointer pw if named account exists and is acceptable;
1001 * sets askpasswd if a PASS command is expected.  If logged in previously,
1002 * need to reset state.  If name is "ftp" or "anonymous", the name is not in
1003 * _PATH_FTPUSERS, and ftp account exists, set guest and pw, then just return.
1004 * If account doesn't exist, ask for passwd anyway.  Otherwise, check user
1005 * requesting login privileges.  Disallow anyone who does not have a standard
1006 * shell as returned by getusershell().  Disallow anyone mentioned in the file
1007 * _PATH_FTPUSERS to allow people such as root and uucp to be avoided.
1008 */
1009void
1010user(char *name)
1011{
1012	char *cp, *shell;
1013
1014	if (logged_in) {
1015		if (guest) {
1016			reply(530, "Can't change user from guest login.");
1017			return;
1018		} else if (dochroot) {
1019			reply(530, "Can't change user from chroot user.");
1020			return;
1021		}
1022		end_login();
1023	}
1024
1025	guest = 0;
1026#ifdef VIRTUAL_HOSTING
1027	pw = sgetpwnam(thishost->anonuser);
1028#else
1029	pw = sgetpwnam("ftp");
1030#endif
1031	if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) {
1032		if (checkuser(_PATH_FTPUSERS, "ftp", 0, NULL) ||
1033		    checkuser(_PATH_FTPUSERS, "anonymous", 0, NULL))
1034			reply(530, "User %s access denied.", name);
1035		else if (pw != NULL) {
1036			guest = 1;
1037			askpasswd = 1;
1038			reply(331,
1039			"Guest login ok, send your email address as password.");
1040		} else
1041			reply(530, "User %s unknown.", name);
1042		if (!askpasswd && logging)
1043			syslog(LOG_NOTICE,
1044			    "ANONYMOUS FTP LOGIN REFUSED FROM %s", remotehost);
1045		return;
1046	}
1047	if (anon_only != 0) {
1048		reply(530, "Sorry, only anonymous ftp allowed.");
1049		return;
1050	}
1051
1052	if ((pw = sgetpwnam(name))) {
1053		if ((shell = pw->pw_shell) == NULL || *shell == 0)
1054			shell = _PATH_BSHELL;
1055		setusershell();
1056		while ((cp = getusershell()) != NULL)
1057			if (strcmp(cp, shell) == 0)
1058				break;
1059		endusershell();
1060
1061		if (cp == NULL || checkuser(_PATH_FTPUSERS, name, 1, NULL)) {
1062			reply(530, "User %s access denied.", name);
1063			if (logging)
1064				syslog(LOG_NOTICE,
1065				    "FTP LOGIN REFUSED FROM %s, %s",
1066				    remotehost, name);
1067			pw = NULL;
1068			return;
1069		}
1070	}
1071	if (logging)
1072		strlcpy(curname, name, sizeof(curname));
1073
1074	pwok = 0;
1075#ifdef USE_PAM
1076	/* XXX Kluge! The conversation mechanism needs to be fixed. */
1077#endif
1078#ifdef HAVE_LIBOPIE
1079	if (opiechallenge(&opiedata, name, opieprompt) == 0) {
1080		pwok = (pw != NULL) &&
1081		       opieaccessfile(remotehost) &&
1082		       opiealways(pw->pw_dir);
1083		reply(331, "Response to %s %s for %s.",
1084		      opieprompt, pwok ? "requested" : "required", name);
1085	} else
1086#endif
1087	{
1088		pwok = 1;
1089		reply(331, "Password required for %s.", name);
1090	}
1091	askpasswd = 1;
1092	/*
1093	 * Delay before reading passwd after first failed
1094	 * attempt to slow down passwd-guessing programs.
1095	 */
1096	if (login_attempts)
1097		sleep(login_attempts);
1098}
1099
1100/*
1101 * Check if a user is in the file "fname",
1102 * return a pointer to a malloc'd string with the rest
1103 * of the matching line in "residue" if not NULL.
1104 */
1105static int
1106checkuser(char *fname, char *name, int pwset, char **residue)
1107{
1108	FILE *fd;
1109	int found = 0;
1110	size_t len;
1111	char *line, *mp, *p;
1112
1113	if ((fd = fopen(fname, "r")) != NULL) {
1114		while (!found && (line = fgetln(fd, &len)) != NULL) {
1115			/* skip comments */
1116			if (line[0] == '#')
1117				continue;
1118			if (line[len - 1] == '\n') {
1119				line[len - 1] = '\0';
1120				mp = NULL;
1121			} else {
1122				if ((mp = malloc(len + 1)) == NULL)
1123					fatalerror("Ran out of memory.");
1124				memcpy(mp, line, len);
1125				mp[len] = '\0';
1126				line = mp;
1127			}
1128			/* avoid possible leading and trailing whitespace */
1129			p = strtok(line, " \t");
1130			/* skip empty lines */
1131			if (p == NULL)
1132				goto nextline;
1133			/*
1134			 * if first chr is '@', check group membership
1135			 */
1136			if (p[0] == '@') {
1137				int i = 0;
1138				struct group *grp;
1139
1140				if (p[1] == '\0') /* single @ matches anyone */
1141					found = 1;
1142				else {
1143					if ((grp = getgrnam(p+1)) == NULL)
1144						goto nextline;
1145					/*
1146					 * Check user's default group
1147					 */
1148					if (pwset && grp->gr_gid == pw->pw_gid)
1149						found = 1;
1150					/*
1151					 * Check supplementary groups
1152					 */
1153					while (!found && grp->gr_mem[i])
1154						found = strcmp(name,
1155							grp->gr_mem[i++])
1156							== 0;
1157				}
1158			}
1159			/*
1160			 * Otherwise, just check for username match
1161			 */
1162			else
1163				found = strcmp(p, name) == 0;
1164			/*
1165			 * Save the rest of line to "residue" if matched
1166			 */
1167			if (found && residue) {
1168				if ((p = strtok(NULL, "")) != NULL)
1169					p += strspn(p, " \t");
1170				if (p && *p) {
1171				 	if ((*residue = strdup(p)) == NULL)
1172						fatalerror("Ran out of memory.");
1173				} else
1174					*residue = NULL;
1175			}
1176nextline:
1177			if (mp)
1178				free(mp);
1179		}
1180		(void) fclose(fd);
1181	}
1182	return (found);
1183}
1184
1185/*
1186 * Terminate login as previous user, if any, resetting state;
1187 * used when USER command is given or login fails.
1188 */
1189static void
1190end_login(void)
1191{
1192#ifdef USE_PAM
1193	int e;
1194#endif
1195
1196	(void) seteuid(0);
1197	if (logged_in && dowtmp)
1198		ftpd_logwtmp(ttyline, "", NULL);
1199	pw = NULL;
1200#ifdef	LOGIN_CAP
1201	setusercontext(NULL, getpwuid(0), 0,
1202		       LOGIN_SETPRIORITY|LOGIN_SETRESOURCES|LOGIN_SETUMASK|
1203		       LOGIN_SETMAC);
1204#endif
1205#ifdef USE_PAM
1206	if (pamh) {
1207		if ((e = pam_setcred(pamh, PAM_DELETE_CRED)) != PAM_SUCCESS)
1208			syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e));
1209		if ((e = pam_close_session(pamh,0)) != PAM_SUCCESS)
1210			syslog(LOG_ERR, "pam_close_session: %s", pam_strerror(pamh, e));
1211		if ((e = pam_end(pamh, e)) != PAM_SUCCESS)
1212			syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1213		pamh = NULL;
1214	}
1215#endif
1216	logged_in = 0;
1217	guest = 0;
1218	dochroot = 0;
1219}
1220
1221#ifdef USE_PAM
1222
1223/*
1224 * the following code is stolen from imap-uw PAM authentication module and
1225 * login.c
1226 */
1227#define COPY_STRING(s) (s ? strdup(s) : NULL)
1228
1229struct cred_t {
1230	const char *uname;		/* user name */
1231	const char *pass;		/* password */
1232};
1233typedef struct cred_t cred_t;
1234
1235static int
1236auth_conv(int num_msg, const struct pam_message **msg,
1237	  struct pam_response **resp, void *appdata)
1238{
1239	int i;
1240	cred_t *cred = (cred_t *) appdata;
1241	struct pam_response *reply;
1242
1243	reply = calloc(num_msg, sizeof *reply);
1244	if (reply == NULL)
1245		return PAM_BUF_ERR;
1246
1247	for (i = 0; i < num_msg; i++) {
1248		switch (msg[i]->msg_style) {
1249		case PAM_PROMPT_ECHO_ON:	/* assume want user name */
1250			reply[i].resp_retcode = PAM_SUCCESS;
1251			reply[i].resp = COPY_STRING(cred->uname);
1252			/* PAM frees resp. */
1253			break;
1254		case PAM_PROMPT_ECHO_OFF:	/* assume want password */
1255			reply[i].resp_retcode = PAM_SUCCESS;
1256			reply[i].resp = COPY_STRING(cred->pass);
1257			/* PAM frees resp. */
1258			break;
1259		case PAM_TEXT_INFO:
1260		case PAM_ERROR_MSG:
1261			reply[i].resp_retcode = PAM_SUCCESS;
1262			reply[i].resp = NULL;
1263			break;
1264		default:			/* unknown message style */
1265			free(reply);
1266			return PAM_CONV_ERR;
1267		}
1268	}
1269
1270	*resp = reply;
1271	return PAM_SUCCESS;
1272}
1273
1274/*
1275 * Attempt to authenticate the user using PAM.  Returns 0 if the user is
1276 * authenticated, or 1 if not authenticated.  If some sort of PAM system
1277 * error occurs (e.g., the "/etc/pam.conf" file is missing) then this
1278 * function returns -1.  This can be used as an indication that we should
1279 * fall back to a different authentication mechanism.
1280 */
1281static int
1282auth_pam(struct passwd **ppw, const char *pass)
1283{
1284	const char *tmpl_user;
1285	const void *item;
1286	int rval;
1287	int e;
1288	cred_t auth_cred = { (*ppw)->pw_name, pass };
1289	struct pam_conv conv = { &auth_conv, &auth_cred };
1290
1291	e = pam_start("ftpd", (*ppw)->pw_name, &conv, &pamh);
1292	if (e != PAM_SUCCESS) {
1293		/*
1294		 * In OpenPAM, it's OK to pass NULL to pam_strerror()
1295		 * if context creation has failed in the first place.
1296		 */
1297		syslog(LOG_ERR, "pam_start: %s", pam_strerror(NULL, e));
1298		return -1;
1299	}
1300
1301	e = pam_set_item(pamh, PAM_RHOST, remotehost);
1302	if (e != PAM_SUCCESS) {
1303		syslog(LOG_ERR, "pam_set_item(PAM_RHOST): %s",
1304			pam_strerror(pamh, e));
1305		if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
1306			syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1307		}
1308		pamh = NULL;
1309		return -1;
1310	}
1311
1312	e = pam_authenticate(pamh, 0);
1313	switch (e) {
1314	case PAM_SUCCESS:
1315		/*
1316		 * With PAM we support the concept of a "template"
1317		 * user.  The user enters a login name which is
1318		 * authenticated by PAM, usually via a remote service
1319		 * such as RADIUS or TACACS+.  If authentication
1320		 * succeeds, a different but related "template" name
1321		 * is used for setting the credentials, shell, and
1322		 * home directory.  The name the user enters need only
1323		 * exist on the remote authentication server, but the
1324		 * template name must be present in the local password
1325		 * database.
1326		 *
1327		 * This is supported by two various mechanisms in the
1328		 * individual modules.  However, from the application's
1329		 * point of view, the template user is always passed
1330		 * back as a changed value of the PAM_USER item.
1331		 */
1332		if ((e = pam_get_item(pamh, PAM_USER, &item)) ==
1333		    PAM_SUCCESS) {
1334			tmpl_user = (const char *) item;
1335			if (strcmp((*ppw)->pw_name, tmpl_user) != 0)
1336				*ppw = getpwnam(tmpl_user);
1337		} else
1338			syslog(LOG_ERR, "Couldn't get PAM_USER: %s",
1339			    pam_strerror(pamh, e));
1340		rval = 0;
1341		break;
1342
1343	case PAM_AUTH_ERR:
1344	case PAM_USER_UNKNOWN:
1345	case PAM_MAXTRIES:
1346		rval = 1;
1347		break;
1348
1349	default:
1350		syslog(LOG_ERR, "pam_authenticate: %s", pam_strerror(pamh, e));
1351		rval = -1;
1352		break;
1353	}
1354
1355	if (rval == 0) {
1356		e = pam_acct_mgmt(pamh, 0);
1357		if (e != PAM_SUCCESS) {
1358			syslog(LOG_ERR, "pam_acct_mgmt: %s",
1359						pam_strerror(pamh, e));
1360			rval = 1;
1361		}
1362	}
1363
1364	if (rval != 0) {
1365		if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
1366			syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1367		}
1368		pamh = NULL;
1369	}
1370	return rval;
1371}
1372
1373#endif /* USE_PAM */
1374
1375void
1376pass(char *passwd)
1377{
1378	int rval;
1379	FILE *fd;
1380#ifdef	LOGIN_CAP
1381	login_cap_t *lc = NULL;
1382#endif
1383#ifdef USE_PAM
1384	int e;
1385#endif
1386	char *residue = NULL;
1387	char *xpasswd;
1388
1389	if (logged_in || askpasswd == 0) {
1390		reply(503, "Login with USER first.");
1391		return;
1392	}
1393	askpasswd = 0;
1394	if (!guest) {		/* "ftp" is only account allowed no password */
1395		if (pw == NULL) {
1396			rval = 1;	/* failure below */
1397			goto skip;
1398		}
1399#ifdef USE_PAM
1400		rval = auth_pam(&pw, passwd);
1401		if (rval >= 0) {
1402			opieunlock();
1403			goto skip;
1404		}
1405#endif
1406#ifdef HAVE_LIBOPIE
1407		if (opieverify(&opiedata, passwd) == 0)
1408			xpasswd = pw->pw_passwd;
1409		else
1410#endif
1411		if (pwok) {
1412			xpasswd = crypt(passwd, pw->pw_passwd);
1413			if (passwd[0] == '\0' && pw->pw_passwd[0] != '\0')
1414				xpasswd = ":";
1415		} else {
1416			rval = 1;
1417			goto skip;
1418		}
1419		rval = strcmp(pw->pw_passwd, xpasswd);
1420#if (!defined(__BEOS__) && !defined(__HAIKU__))
1421		if (pw->pw_expire && time(NULL) >= pw->pw_expire)
1422			rval = 1;	/* failure */
1423#endif
1424skip:
1425		/*
1426		 * If rval == 1, the user failed the authentication check
1427		 * above.  If rval == 0, either PAM or local authentication
1428		 * succeeded.
1429		 */
1430		if (rval) {
1431			reply(530, "Login incorrect.");
1432			if (logging) {
1433				syslog(LOG_NOTICE,
1434				    "FTP LOGIN FAILED FROM %s",
1435				    remotehost);
1436				syslog(LOG_AUTHPRIV | LOG_NOTICE,
1437				    "FTP LOGIN FAILED FROM %s, %s",
1438				    remotehost, curname);
1439			}
1440			pw = NULL;
1441			if (login_attempts++ >= 5) {
1442				syslog(LOG_NOTICE,
1443				    "repeated login failures from %s",
1444				    remotehost);
1445				exit(0);
1446			}
1447			return;
1448		}
1449	}
1450	login_attempts = 0;		/* this time successful */
1451	if (setegid(pw->pw_gid) < 0) {
1452		reply(550, "Can't set gid.");
1453		return;
1454	}
1455	/* May be overridden by login.conf */
1456	(void) umask(defumask);
1457#ifdef	LOGIN_CAP
1458	if ((lc = login_getpwclass(pw)) != NULL) {
1459		char	remote_ip[NI_MAXHOST];
1460
1461		if (getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
1462			remote_ip, sizeof(remote_ip) - 1, NULL, 0,
1463			NI_NUMERICHOST))
1464				*remote_ip = 0;
1465		remote_ip[sizeof(remote_ip) - 1] = 0;
1466		if (!auth_hostok(lc, remotehost, remote_ip)) {
1467			syslog(LOG_INFO|LOG_AUTH,
1468			    "FTP LOGIN FAILED (HOST) as %s: permission denied.",
1469			    pw->pw_name);
1470			reply(530, "Permission denied.");
1471			pw = NULL;
1472			return;
1473		}
1474		if (!auth_timeok(lc, time(NULL))) {
1475			reply(530, "Login not available right now.");
1476			pw = NULL;
1477			return;
1478		}
1479	}
1480	setusercontext(lc, pw, 0,
1481		LOGIN_SETLOGIN|LOGIN_SETGROUP|LOGIN_SETPRIORITY|
1482		LOGIN_SETRESOURCES|LOGIN_SETUMASK|LOGIN_SETMAC);
1483#elif !(defined(__BEOS__) || defined(__HAIKU__))
1484	setlogin(pw->pw_name);
1485	(void) initgroups(pw->pw_name, pw->pw_gid);
1486#endif
1487
1488#ifdef USE_PAM
1489	if (pamh) {
1490		if ((e = pam_open_session(pamh, 0)) != PAM_SUCCESS) {
1491			syslog(LOG_ERR, "pam_open_session: %s", pam_strerror(pamh, e));
1492		} else if ((e = pam_setcred(pamh, PAM_ESTABLISH_CRED)) != PAM_SUCCESS) {
1493			syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e));
1494		}
1495	}
1496#endif
1497
1498	/* open wtmp before chroot */
1499	if (dowtmp)
1500		ftpd_logwtmp(ttyline, pw->pw_name,
1501		    (struct sockaddr *)&his_addr);
1502	logged_in = 1;
1503
1504	if (guest && stats && statfd < 0) {
1505#ifdef VIRTUAL_HOSTING
1506		statfd = open(thishost->statfile, O_WRONLY|O_APPEND);
1507#else
1508		statfd = open(_PATH_FTPDSTATFILE, O_WRONLY|O_APPEND);
1509#endif
1510		if (statfd < 0)
1511			stats = 0;
1512	}
1513
1514	dochroot =
1515		checkuser(_PATH_FTPCHROOT, pw->pw_name, 1, &residue)
1516#ifdef	LOGIN_CAP	/* Allow login.conf configuration as well */
1517		|| login_getcapbool(lc, "ftp-chroot", 0)
1518#endif
1519	;
1520	chrootdir = NULL;
1521#if (!defined(__BEOS__) && !defined(__HAIKU__))
1522	/*
1523	 * For a chrooted local user,
1524	 * a) see whether ftpchroot(5) specifies a chroot directory,
1525	 * b) extract the directory pathname from the line,
1526	 * c) expand it to the absolute pathname if necessary.
1527	 */
1528	if (dochroot && residue &&
1529	    (chrootdir = strtok(residue, " \t")) != NULL) {
1530		if (chrootdir[0] != '/')
1531			asprintf(&chrootdir, "%s/%s", pw->pw_dir, chrootdir);
1532		else
1533			chrootdir = strdup(chrootdir); /* make it permanent */
1534		if (chrootdir == NULL)
1535			fatalerror("Ran out of memory.");
1536	}
1537#endif
1538	if (guest || dochroot) {
1539#if (!defined(__BEOS__) && !defined(__HAIKU__))
1540		/*
1541		 * If no chroot directory set yet, use the login directory.
1542		 * Copy it so it can be modified while pw->pw_dir stays intact.
1543		 */
1544		if (chrootdir == NULL &&
1545		    (chrootdir = strdup(pw->pw_dir)) == NULL)
1546			fatalerror("Ran out of memory.");
1547		/*
1548		 * Check for the "/chroot/./home" syntax,
1549		 * separate the chroot and home directory pathnames.
1550		 */
1551		if ((homedir = strstr(chrootdir, "/./")) != NULL) {
1552			*(homedir++) = '\0';	/* wipe '/' */
1553			homedir++;		/* skip '.' */
1554		} else {
1555			/*
1556			 * We MUST do a chdir() after the chroot. Otherwise
1557			 * the old current directory will be accessible as "."
1558			 * outside the new root!
1559			 */
1560			homedir = "/";
1561		}
1562		/*
1563		 * Finally, do chroot()
1564		 */
1565		if (chroot(chrootdir) < 0) {
1566			reply(550, "Can't change root.");
1567			goto bad;
1568		}
1569#else
1570		homedir = "/";
1571#endif
1572	} else	/* real user w/o chroot */
1573		homedir = pw->pw_dir;
1574	/*
1575	 * Set euid *before* doing chdir() so
1576	 * a) the user won't be carried to a directory that he couldn't reach
1577	 *    on his own due to no permission to upper path components,
1578	 * b) NFS mounted homedirs w/restrictive permissions will be accessible
1579	 *    (uid 0 has no root power over NFS if not mapped explicitly.)
1580	 */
1581	if (seteuid(pw->pw_uid) < 0) {
1582		reply(550, "Can't set uid.");
1583		goto bad;
1584	}
1585	if (chdir(homedir) < 0) {
1586		if (guest || dochroot) {
1587			reply(550, "Can't change to base directory.");
1588			goto bad;
1589		} else {
1590			if (chdir("/") < 0) {
1591				reply(550, "Root is inaccessible.");
1592				goto bad;
1593			}
1594			lreply(230, "No directory! Logging in with home=/.");
1595		}
1596	}
1597
1598	/*
1599	 * Display a login message, if it exists.
1600	 * N.B. reply(230,) must follow the message.
1601	 */
1602#ifdef VIRTUAL_HOSTING
1603	fd = fopen(thishost->loginmsg, "r");
1604#else
1605	fd = fopen(_PATH_FTPLOGINMESG, "r");
1606#endif
1607	if (fd != NULL) {
1608		char *cp, line[LINE_MAX];
1609
1610		while (fgets(line, sizeof(line), fd) != NULL) {
1611			if ((cp = strchr(line, '\n')) != NULL)
1612				*cp = '\0';
1613			lreply(230, "%s", line);
1614		}
1615		(void) fflush(stdout);
1616		(void) fclose(fd);
1617	}
1618	if (guest) {
1619		if (ident != NULL)
1620			free(ident);
1621		ident = strdup(passwd);
1622		if (ident == NULL)
1623			fatalerror("Ran out of memory.");
1624
1625		reply(230, "Guest login ok, access restrictions apply.");
1626#ifdef SETPROCTITLE
1627#ifdef VIRTUAL_HOSTING
1628		if (thishost != firsthost)
1629			snprintf(proctitle, sizeof(proctitle),
1630				 "%s: anonymous(%s)/%s", remotehost, hostname,
1631				 passwd);
1632		else
1633#endif
1634			snprintf(proctitle, sizeof(proctitle),
1635				 "%s: anonymous/%s", remotehost, passwd);
1636		setproctitle("%s", proctitle);
1637#endif /* SETPROCTITLE */
1638		if (logging)
1639			syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s, %s",
1640			    remotehost, passwd);
1641	} else {
1642		if (dochroot)
1643			reply(230, "User %s logged in, "
1644				   "access restrictions apply.", pw->pw_name);
1645		else
1646			reply(230, "User %s logged in.", pw->pw_name);
1647
1648#ifdef SETPROCTITLE
1649		snprintf(proctitle, sizeof(proctitle),
1650			 "%s: user/%s", remotehost, pw->pw_name);
1651		setproctitle("%s", proctitle);
1652#endif /* SETPROCTITLE */
1653		if (logging)
1654			syslog(LOG_INFO, "FTP LOGIN FROM %s as %s",
1655			    remotehost, pw->pw_name);
1656	}
1657	if (logging && (guest || dochroot))
1658		syslog(LOG_INFO, "session root changed to %s", chrootdir);
1659#ifdef	LOGIN_CAP
1660	login_close(lc);
1661#endif
1662	if (residue)
1663		free(residue);
1664	return;
1665bad:
1666	/* Forget all about it... */
1667#ifdef	LOGIN_CAP
1668	login_close(lc);
1669#endif
1670	if (residue)
1671		free(residue);
1672	end_login();
1673}
1674
1675void
1676retrieve(char *cmd, char *name)
1677{
1678	FILE *fin, *dout;
1679	struct stat st;
1680	int (*closefunc)(FILE *);
1681	time_t start;
1682
1683	if (cmd == 0) {
1684		fin = fopen(name, "r"), closefunc = fclose;
1685		st.st_size = 0;
1686	} else {
1687		char line[BUFSIZ];
1688
1689		(void) snprintf(line, sizeof(line), cmd, name), name = line;
1690		fin = ftpd_popen(line, "r"), closefunc = ftpd_pclose;
1691		st.st_size = -1;
1692		st.st_blksize = BUFSIZ;
1693	}
1694	if (fin == NULL) {
1695		if (errno != 0) {
1696			perror_reply(550, name);
1697			if (cmd == 0) {
1698				LOGCMD("get", name);
1699			}
1700		}
1701		return;
1702	}
1703	byte_count = -1;
1704	if (cmd == 0) {
1705		if (fstat(fileno(fin), &st) < 0) {
1706			perror_reply(550, name);
1707			goto done;
1708		}
1709		if (!S_ISREG(st.st_mode)) {
1710			/*
1711			 * Never sending a raw directory is a workaround
1712			 * for buggy clients that will attempt to RETR
1713			 * a directory before listing it, e.g., Mozilla.
1714			 * Preventing a guest from getting irregular files
1715			 * is a simple security measure.
1716			 */
1717			if (S_ISDIR(st.st_mode) || guest) {
1718				reply(550, "%s: not a plain file.", name);
1719				goto done;
1720			}
1721			st.st_size = -1;
1722			/* st.st_blksize is set for all descriptor types */
1723		}
1724	}
1725	if (restart_point) {
1726		if (type == TYPE_A) {
1727			off_t i, n;
1728			int c;
1729
1730			n = restart_point;
1731			i = 0;
1732			while (i++ < n) {
1733				if ((c=getc(fin)) == EOF) {
1734					perror_reply(550, name);
1735					goto done;
1736				}
1737				if (c == '\n')
1738					i++;
1739			}
1740		} else if (lseek(fileno(fin), restart_point, L_SET) < 0) {
1741			perror_reply(550, name);
1742			goto done;
1743		}
1744	}
1745	dout = dataconn(name, st.st_size, "w");
1746	if (dout == NULL)
1747		goto done;
1748	time(&start);
1749	send_data(fin, dout, st.st_blksize, st.st_size,
1750		  restart_point == 0 && cmd == 0 && S_ISREG(st.st_mode));
1751	if (cmd == 0 && guest && stats && byte_count > 0)
1752		logxfer(name, byte_count, start);
1753	(void) fclose(dout);
1754	data = -1;
1755	pdata = -1;
1756done:
1757	if (cmd == 0)
1758		LOGBYTES("get", name, byte_count);
1759	(*closefunc)(fin);
1760}
1761
1762void
1763store(char *name, char *mode, int unique)
1764{
1765	int fd;
1766	FILE *fout, *din;
1767	int (*closefunc)(FILE *);
1768
1769	if (*mode == 'a') {		/* APPE */
1770		if (unique) {
1771			/* Programming error */
1772			syslog(LOG_ERR, "Internal: unique flag to APPE");
1773			unique = 0;
1774		}
1775		if (guest && noguestmod) {
1776			reply(550, "Appending to existing file denied.");
1777			goto err;
1778		}
1779		restart_point = 0;	/* not affected by preceding REST */
1780	}
1781	if (unique)			/* STOU overrides REST */
1782		restart_point = 0;
1783	if (guest && noguestmod) {
1784		if (restart_point) {	/* guest STOR w/REST */
1785			reply(550, "Modifying existing file denied.");
1786			goto err;
1787		} else			/* treat guest STOR as STOU */
1788			unique = 1;
1789	}
1790
1791	if (restart_point)
1792		mode = "r+";	/* so ASCII manual seek can work */
1793	if (unique) {
1794		if ((fd = guniquefd(name, &name)) < 0)
1795			goto err;
1796		fout = fdopen(fd, mode);
1797	} else
1798		fout = fopen(name, mode);
1799	closefunc = fclose;
1800	if (fout == NULL) {
1801		perror_reply(553, name);
1802		goto err;
1803	}
1804	byte_count = -1;
1805	if (restart_point) {
1806		if (type == TYPE_A) {
1807			off_t i, n;
1808			int c;
1809
1810			n = restart_point;
1811			i = 0;
1812			while (i++ < n) {
1813				if ((c=getc(fout)) == EOF) {
1814					perror_reply(550, name);
1815					goto done;
1816				}
1817				if (c == '\n')
1818					i++;
1819			}
1820			/*
1821			 * We must do this seek to "current" position
1822			 * because we are changing from reading to
1823			 * writing.
1824			 */
1825			if (fseeko(fout, 0, SEEK_CUR) < 0) {
1826				perror_reply(550, name);
1827				goto done;
1828			}
1829		} else if (lseek(fileno(fout), restart_point, L_SET) < 0) {
1830			perror_reply(550, name);
1831			goto done;
1832		}
1833	}
1834	din = dataconn(name, -1, "r");
1835	if (din == NULL)
1836		goto done;
1837	if (receive_data(din, fout) == 0) {
1838		if (unique)
1839			reply(226, "Transfer complete (unique file name:%s).",
1840			    name);
1841		else
1842			reply(226, "Transfer complete.");
1843	}
1844	(void) fclose(din);
1845	data = -1;
1846	pdata = -1;
1847done:
1848	LOGBYTES(*mode == 'a' ? "append" : "put", name, byte_count);
1849	(*closefunc)(fout);
1850	return;
1851err:
1852	LOGCMD(*mode == 'a' ? "append" : "put" , name);
1853	return;
1854}
1855
1856static FILE *
1857getdatasock(char *mode)
1858{
1859	int on = 1, s, t, tries;
1860
1861	if (data >= 0)
1862		return (fdopen(data, mode));
1863
1864	s = socket(data_dest.su_family, SOCK_STREAM, 0);
1865	if (s < 0)
1866		goto bad;
1867	if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
1868		syslog(LOG_WARNING, "data setsockopt (SO_REUSEADDR): %m");
1869	/* anchor socket to avoid multi-homing problems */
1870	data_source = ctrl_addr;
1871	data_source.su_port = htons(dataport);
1872	(void) seteuid(0);
1873	for (tries = 1; ; tries++) {
1874		/*
1875		 * We should loop here since it's possible that
1876		 * another ftpd instance has passed this point and is
1877		 * trying to open a data connection in active mode now.
1878		 * Until the other connection is opened, we'll be getting
1879		 * EADDRINUSE because no SOCK_STREAM sockets in the system
1880		 * can share both local and remote addresses, localIP:20
1881		 * and *:* in this case.
1882		 */
1883		if (bind(s, (struct sockaddr *)&data_source,
1884		    data_source.su_len) >= 0)
1885			break;
1886		if (errno != EADDRINUSE || tries > 10)
1887			goto bad;
1888		sleep(tries);
1889	}
1890	(void) seteuid(pw->pw_uid);
1891#ifdef IP_TOS
1892	if (data_source.su_family == AF_INET)
1893      {
1894	on = IPTOS_THROUGHPUT;
1895	if (setsockopt(s, IPPROTO_IP, IP_TOS, &on, sizeof(int)) < 0)
1896		syslog(LOG_WARNING, "data setsockopt (IP_TOS): %m");
1897      }
1898#endif
1899#ifdef TCP_NOPUSH
1900	/*
1901	 * Turn off push flag to keep sender TCP from sending short packets
1902	 * at the boundaries of each write().
1903	 */
1904	on = 1;
1905	if (setsockopt(s, IPPROTO_TCP, TCP_NOPUSH, &on, sizeof on) < 0)
1906		syslog(LOG_WARNING, "data setsockopt (TCP_NOPUSH): %m");
1907#endif
1908	return (fdopen(s, mode));
1909bad:
1910	/* Return the real value of errno (close may change it) */
1911	t = errno;
1912	(void) seteuid(pw->pw_uid);
1913	(void) close(s);
1914	errno = t;
1915	return (NULL);
1916}
1917
1918static FILE *
1919dataconn(char *name, off_t size, char *mode)
1920{
1921	char sizebuf[32];
1922	FILE *file;
1923	int retry = 0, tos, conerrno;
1924
1925	file_size = size;
1926	byte_count = 0;
1927	if (size != -1)
1928		(void) snprintf(sizebuf, sizeof(sizebuf),
1929				" (%lld bytes)", (intmax_t)size);
1930	else
1931		*sizebuf = '\0';
1932	if (pdata >= 0) {
1933		union sockunion from;
1934		socklen_t fromlen = ctrl_addr.su_len;
1935		int flags, s;
1936		struct timeval timeout;
1937		fd_set set;
1938
1939		FD_ZERO(&set);
1940		FD_SET(pdata, &set);
1941
1942		timeout.tv_usec = 0;
1943		timeout.tv_sec = 120;
1944
1945		/*
1946		 * Granted a socket is in the blocking I/O mode,
1947		 * accept() will block after a successful select()
1948		 * if the selected connection dies in between.
1949		 * Therefore set the non-blocking I/O flag here.
1950		 */
1951		if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1952		    fcntl(pdata, F_SETFL, flags | O_NONBLOCK) == -1)
1953			goto pdata_err;
1954		if (select(pdata+1, &set, NULL, NULL, &timeout) <= 0 ||
1955		    (s = accept(pdata, (struct sockaddr *) &from, &fromlen)) < 0)
1956			goto pdata_err;
1957		(void) close(pdata);
1958		pdata = s;
1959		/*
1960		 * Unset the inherited non-blocking I/O flag
1961		 * on the child socket so stdio can work on it.
1962		 */
1963		if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1964		    fcntl(pdata, F_SETFL, flags & ~O_NONBLOCK) == -1)
1965			goto pdata_err;
1966#ifdef IP_TOS
1967		if (from.su_family == AF_INET)
1968	      {
1969		tos = IPTOS_THROUGHPUT;
1970		if (setsockopt(s, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
1971			syslog(LOG_WARNING, "pdata setsockopt (IP_TOS): %m");
1972	      }
1973#endif
1974		reply(150, "Opening %s mode data connection for '%s'%s.",
1975		     type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1976		return (fdopen(pdata, mode));
1977pdata_err:
1978		reply(425, "Can't open data connection.");
1979		(void) close(pdata);
1980		pdata = -1;
1981		return (NULL);
1982	}
1983	if (data >= 0) {
1984		reply(125, "Using existing data connection for '%s'%s.",
1985		    name, sizebuf);
1986		usedefault = 1;
1987		return (fdopen(data, mode));
1988	}
1989	if (usedefault)
1990		data_dest = his_addr;
1991	usedefault = 1;
1992	do {
1993		file = getdatasock(mode);
1994		if (file == NULL) {
1995			char hostbuf[NI_MAXHOST], portbuf[NI_MAXSERV];
1996
1997			if (getnameinfo((struct sockaddr *)&data_source,
1998				data_source.su_len,
1999				hostbuf, sizeof(hostbuf) - 1,
2000				portbuf, sizeof(portbuf) - 1,
2001				NI_NUMERICHOST|NI_NUMERICSERV))
2002					*hostbuf = *portbuf = 0;
2003			hostbuf[sizeof(hostbuf) - 1] = 0;
2004			portbuf[sizeof(portbuf) - 1] = 0;
2005			reply(425, "Can't create data socket (%s,%s): %s.",
2006				hostbuf, portbuf, strerror(errno));
2007			return (NULL);
2008		}
2009		data = fileno(file);
2010		conerrno = 0;
2011		if (connect(data, (struct sockaddr *)&data_dest,
2012		    data_dest.su_len) == 0)
2013			break;
2014		conerrno = errno;
2015		(void) fclose(file);
2016		data = -1;
2017		if (conerrno == EADDRINUSE) {
2018			sleep(swaitint);
2019			retry += swaitint;
2020		} else {
2021			break;
2022		}
2023	} while (retry <= swaitmax);
2024	if (conerrno != 0) {
2025		reply(425, "Can't build data connection: %s.",
2026			   strerror(conerrno));
2027		return (NULL);
2028	}
2029	reply(150, "Opening %s mode data connection for '%s'%s.",
2030	     type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
2031	return (file);
2032}
2033
2034/*
2035 * A helper macro to avoid code duplication
2036 * in send_data() and receive_data().
2037 *
2038 * XXX We have to block SIGURG during putc() because BSD stdio
2039 * is unable to restart interrupted write operations and hence
2040 * the entire buffer contents will be lost as soon as a write()
2041 * call indicates EINTR to stdio.
2042 */
2043#define FTPD_PUTC(ch, file, label)					\
2044	do {								\
2045		int ret;						\
2046									\
2047		do {							\
2048			START_UNSAFE;					\
2049			ret = putc((ch), (file));			\
2050			END_UNSAFE;					\
2051			CHECKOOB(return (-1))				\
2052			else if (ferror(file))				\
2053				goto label;				\
2054			clearerr(file);					\
2055		} while (ret == EOF);					\
2056	} while (0)
2057
2058/*
2059 * Tranfer the contents of "instr" to "outstr" peer using the appropriate
2060 * encapsulation of the data subject to Mode, Structure, and Type.
2061 *
2062 * NB: Form isn't handled.
2063 */
2064static int
2065send_data(FILE *instr, FILE *outstr, size_t blksize, off_t filesize, int isreg)
2066{
2067	int c, cp, filefd, netfd;
2068	char *buf;
2069
2070	STARTXFER;
2071
2072	switch (type) {
2073
2074	case TYPE_A:
2075		cp = EOF;
2076		for (;;) {
2077			c = getc(instr);
2078			CHECKOOB(return (-1))
2079			else if (c == EOF && ferror(instr))
2080				goto file_err;
2081			if (c == EOF) {
2082				if (ferror(instr)) {	/* resume after OOB */
2083					clearerr(instr);
2084					continue;
2085				}
2086				if (feof(instr))	/* EOF */
2087					break;
2088				syslog(LOG_ERR, "Internal: impossible condition"
2089						" on file after getc()");
2090				goto file_err;
2091			}
2092			if (c == '\n' && cp != '\r') {
2093				FTPD_PUTC('\r', outstr, data_err);
2094				byte_count++;
2095			}
2096			FTPD_PUTC(c, outstr, data_err);
2097			byte_count++;
2098			cp = c;
2099		}
2100#ifdef notyet	/* BSD stdio isn't ready for that */
2101		while (fflush(outstr) == EOF) {
2102			CHECKOOB(return (-1))
2103			else
2104				goto data_err;
2105			clearerr(outstr);
2106		}
2107		ENDXFER;
2108#else
2109		ENDXFER;
2110		if (fflush(outstr) == EOF)
2111			goto data_err;
2112#endif
2113		reply(226, "Transfer complete.");
2114		return (0);
2115
2116	case TYPE_I:
2117	case TYPE_L:
2118		/*
2119		 * isreg is only set if we are not doing restart and we
2120		 * are sending a regular file
2121		 */
2122		netfd = fileno(outstr);
2123		filefd = fileno(instr);
2124
2125#if (!defined(__BEOS__) && !defined(__HAIKU__))
2126		if (isreg) {
2127			char *msg = "Transfer complete.";
2128			off_t cnt, offset;
2129			int err;
2130
2131			cnt = offset = 0;
2132
2133			while (filesize > 0) {
2134				err = sendfile(filefd, netfd, offset, 0,
2135					       NULL, &cnt, 0);
2136				/*
2137				 * Calculate byte_count before OOB processing.
2138				 * It can be used in myoob() later.
2139				 */
2140				byte_count += cnt;
2141				offset += cnt;
2142				filesize -= cnt;
2143				CHECKOOB(return (-1))
2144				else if (err == -1) {
2145					if (errno != EINTR &&
2146					    cnt == 0 && offset == 0)
2147						goto oldway;
2148					goto data_err;
2149				}
2150				if (err == -1)	/* resume after OOB */
2151					continue;
2152				/*
2153				 * We hit the EOF prematurely.
2154				 * Perhaps the file was externally truncated.
2155				 */
2156				if (cnt == 0) {
2157					msg = "Transfer finished due to "
2158					      "premature end of file.";
2159					break;
2160				}
2161			}
2162			ENDXFER;
2163			reply(226, "%s", msg);
2164			return (0);
2165		}
2166
2167oldway:
2168#endif	/* !__BEOS__ */
2169		if ((buf = malloc(blksize)) == NULL) {
2170			ENDXFER;
2171			reply(451, "Ran out of memory.");
2172			return (-1);
2173		}
2174
2175		for (;;) {
2176			int cnt, len;
2177			char *bp;
2178
2179			cnt = read(filefd, buf, blksize);
2180			CHECKOOB(free(buf); return (-1))
2181			else if (cnt < 0) {
2182				free(buf);
2183				goto file_err;
2184			}
2185			if (cnt < 0)	/* resume after OOB */
2186				continue;
2187			if (cnt == 0)	/* EOF */
2188				break;
2189			for (len = cnt, bp = buf; len > 0;) {
2190				cnt = write(netfd, bp, len);
2191				CHECKOOB(free(buf); return (-1))
2192				else if (cnt < 0) {
2193					free(buf);
2194					goto data_err;
2195				}
2196				if (cnt <= 0)
2197					continue;
2198				len -= cnt;
2199				bp += cnt;
2200				byte_count += cnt;
2201			}
2202		}
2203		ENDXFER;
2204		free(buf);
2205		reply(226, "Transfer complete.");
2206		return (0);
2207	default:
2208		ENDXFER;
2209		reply(550, "Unimplemented TYPE %d in send_data.", type);
2210		return (-1);
2211	}
2212
2213data_err:
2214	ENDXFER;
2215	perror_reply(426, "Data connection");
2216	return (-1);
2217
2218file_err:
2219	ENDXFER;
2220	perror_reply(551, "Error on input file");
2221	return (-1);
2222}
2223
2224/*
2225 * Transfer data from peer to "outstr" using the appropriate encapulation of
2226 * the data subject to Mode, Structure, and Type.
2227 *
2228 * N.B.: Form isn't handled.
2229 */
2230static int
2231receive_data(FILE *instr, FILE *outstr)
2232{
2233	int c, cp;
2234	int bare_lfs = 0;
2235
2236	STARTXFER;
2237
2238	switch (type) {
2239
2240	case TYPE_I:
2241	case TYPE_L:
2242		for (;;) {
2243			int cnt, len;
2244			char *bp;
2245			char buf[BUFSIZ];
2246
2247			cnt = read(fileno(instr), buf, sizeof(buf));
2248			CHECKOOB(return (-1))
2249			else if (cnt < 0)
2250				goto data_err;
2251			if (cnt < 0)	/* resume after OOB */
2252				continue;
2253			if (cnt == 0)	/* EOF */
2254				break;
2255			for (len = cnt, bp = buf; len > 0;) {
2256				cnt = write(fileno(outstr), bp, len);
2257				CHECKOOB(return (-1))
2258				else if (cnt < 0)
2259					goto file_err;
2260				if (cnt <= 0)
2261					continue;
2262				len -= cnt;
2263				bp += cnt;
2264				byte_count += cnt;
2265			}
2266		}
2267		ENDXFER;
2268		return (0);
2269
2270	case TYPE_E:
2271		ENDXFER;
2272		reply(553, "TYPE E not implemented.");
2273		return (-1);
2274
2275	case TYPE_A:
2276		cp = EOF;
2277		for (;;) {
2278			c = getc(instr);
2279			CHECKOOB(return (-1))
2280			else if (c == EOF && ferror(instr))
2281				goto data_err;
2282			if (c == EOF && ferror(instr)) { /* resume after OOB */
2283				clearerr(instr);
2284				continue;
2285			}
2286
2287			if (cp == '\r') {
2288				if (c != '\n')
2289					FTPD_PUTC('\r', outstr, file_err);
2290			} else
2291				if (c == '\n')
2292					bare_lfs++;
2293			if (c == '\r') {
2294				byte_count++;
2295				cp = c;
2296				continue;
2297			}
2298
2299			/* Check for EOF here in order not to lose last \r. */
2300			if (c == EOF) {
2301				if (feof(instr))	/* EOF */
2302					break;
2303				syslog(LOG_ERR, "Internal: impossible condition"
2304						" on data stream after getc()");
2305				goto data_err;
2306			}
2307
2308			byte_count++;
2309			FTPD_PUTC(c, outstr, file_err);
2310			cp = c;
2311		}
2312#ifdef notyet	/* BSD stdio isn't ready for that */
2313		while (fflush(outstr) == EOF) {
2314			CHECKOOB(return (-1))
2315			else
2316				goto file_err;
2317			clearerr(outstr);
2318		}
2319		ENDXFER;
2320#else
2321		ENDXFER;
2322		if (fflush(outstr) == EOF)
2323			goto file_err;
2324#endif
2325		if (bare_lfs) {
2326			lreply(226,
2327		"WARNING! %d bare linefeeds received in ASCII mode.",
2328			    bare_lfs);
2329		(void)printf("   File may not have transferred correctly.\r\n");
2330		}
2331		return (0);
2332	default:
2333		ENDXFER;
2334		reply(550, "Unimplemented TYPE %d in receive_data.", type);
2335		return (-1);
2336	}
2337
2338data_err:
2339	ENDXFER;
2340	perror_reply(426, "Data connection");
2341	return (-1);
2342
2343file_err:
2344	ENDXFER;
2345	perror_reply(452, "Error writing to file");
2346	return (-1);
2347}
2348
2349void
2350statfilecmd(char *filename)
2351{
2352	FILE *fin;
2353	int atstart;
2354	int c, code;
2355	char line[LINE_MAX];
2356	struct stat st;
2357
2358	code = lstat(filename, &st) == 0 && S_ISDIR(st.st_mode) ? 212 : 213;
2359	(void)snprintf(line, sizeof(line), _PATH_LS " -lgA %s", filename);
2360	fin = ftpd_popen(line, "r");
2361	if (fin == NULL) {
2362			perror_reply(551, filename);
2363			return;
2364	}
2365	lreply(code, "Status of %s:", filename);
2366	atstart = 1;
2367	while ((c = getc(fin)) != EOF) {
2368		if (c == '\n') {
2369			if (ferror(stdout)){
2370				perror_reply(421, "Control connection");
2371				(void) ftpd_pclose(fin);
2372				dologout(1);
2373				/* NOTREACHED */
2374			}
2375			if (ferror(fin)) {
2376				perror_reply(551, filename);
2377				(void) ftpd_pclose(fin);
2378				return;
2379			}
2380			(void) putc('\r', stdout);
2381		}
2382		/*
2383		 * RFC 959 says neutral text should be prepended before
2384		 * a leading 3-digit number followed by whitespace, but
2385		 * many ftp clients can be confused by any leading digits,
2386		 * as a matter of fact.
2387		 */
2388		if (atstart && isdigit(c))
2389			(void) putc(' ', stdout);
2390		(void) putc(c, stdout);
2391		atstart = (c == '\n');
2392	}
2393	(void) ftpd_pclose(fin);
2394	reply(code, "End of status.");
2395}
2396
2397void
2398statcmd(void)
2399{
2400	union sockunion *su;
2401	u_char *a, *p;
2402	char hname[NI_MAXHOST];
2403	int ispassive;
2404
2405	if (hostinfo) {
2406		lreply(211, "%s FTP server status:", hostname);
2407		printf("     %s\r\n", version);
2408	} else
2409		lreply(211, "FTP server status:");
2410	printf("     Connected to %s", remotehost);
2411	if (!getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
2412			 hname, sizeof(hname) - 1, NULL, 0, NI_NUMERICHOST)) {
2413		hname[sizeof(hname) - 1] = 0;
2414		if (strcmp(hname, remotehost) != 0)
2415			printf(" (%s)", hname);
2416	}
2417	printf("\r\n");
2418	if (logged_in) {
2419		if (guest)
2420			printf("     Logged in anonymously\r\n");
2421		else
2422			printf("     Logged in as %s\r\n", pw->pw_name);
2423	} else if (askpasswd)
2424		printf("     Waiting for password\r\n");
2425	else
2426		printf("     Waiting for user name\r\n");
2427	printf("     TYPE: %s", typenames[type]);
2428	if (type == TYPE_A || type == TYPE_E)
2429		printf(", FORM: %s", formnames[form]);
2430	if (type == TYPE_L)
2431#if CHAR_BIT == 8
2432		printf(" %d", CHAR_BIT);
2433#else
2434		printf(" %d", bytesize);	/* need definition! */
2435#endif
2436	printf("; STRUcture: %s; transfer MODE: %s\r\n",
2437	    strunames[stru], modenames[mode]);
2438	if (data != -1)
2439		printf("     Data connection open\r\n");
2440	else if (pdata != -1) {
2441		ispassive = 1;
2442		su = &pasv_addr;
2443		goto printaddr;
2444	} else if (usedefault == 0) {
2445		ispassive = 0;
2446		su = &data_dest;
2447printaddr:
2448#define UC(b) (((int) b) & 0xff)
2449		if (epsvall) {
2450			printf("     EPSV only mode (EPSV ALL)\r\n");
2451			goto epsvonly;
2452		}
2453
2454		/* PORT/PASV */
2455		if (su->su_family == AF_INET) {
2456			a = (u_char *) &su->su_sin.sin_addr;
2457			p = (u_char *) &su->su_sin.sin_port;
2458			printf("     %s (%d,%d,%d,%d,%d,%d)\r\n",
2459				ispassive ? "PASV" : "PORT",
2460				UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2461				UC(p[0]), UC(p[1]));
2462		}
2463
2464		/* LPRT/LPSV */
2465	    {
2466		int alen, af, i;
2467
2468		switch (su->su_family) {
2469		case AF_INET:
2470			a = (u_char *) &su->su_sin.sin_addr;
2471			p = (u_char *) &su->su_sin.sin_port;
2472			alen = sizeof(su->su_sin.sin_addr);
2473			af = 4;
2474			break;
2475		case AF_INET6:
2476			a = (u_char *) &su->su_sin6.sin6_addr;
2477			p = (u_char *) &su->su_sin6.sin6_port;
2478			alen = sizeof(su->su_sin6.sin6_addr);
2479			af = 6;
2480			break;
2481		default:
2482			af = 0;
2483			break;
2484		}
2485		if (af) {
2486			printf("     %s (%d,%d,", ispassive ? "LPSV" : "LPRT",
2487				af, alen);
2488			for (i = 0; i < alen; i++)
2489				printf("%d,", UC(a[i]));
2490			printf("%d,%d,%d)\r\n", 2, UC(p[0]), UC(p[1]));
2491		}
2492	    }
2493
2494epsvonly:;
2495		/* EPRT/EPSV */
2496	    {
2497		int af;
2498
2499		switch (su->su_family) {
2500		case AF_INET:
2501			af = 1;
2502			break;
2503		case AF_INET6:
2504			af = 2;
2505			break;
2506		default:
2507			af = 0;
2508			break;
2509		}
2510		if (af) {
2511			union sockunion tmp;
2512
2513			tmp = *su;
2514			if (tmp.su_family == AF_INET6)
2515				tmp.su_sin6.sin6_scope_id = 0;
2516			if (!getnameinfo((struct sockaddr *)&tmp, tmp.su_len,
2517					hname, sizeof(hname) - 1, NULL, 0,
2518					NI_NUMERICHOST)) {
2519				hname[sizeof(hname) - 1] = 0;
2520				printf("     %s |%d|%s|%d|\r\n",
2521					ispassive ? "EPSV" : "EPRT",
2522					af, hname, htons(tmp.su_port));
2523			}
2524		}
2525	    }
2526#undef UC
2527	} else
2528		printf("     No data connection\r\n");
2529	reply(211, "End of status.");
2530}
2531
2532void
2533fatalerror(char *s)
2534{
2535
2536	reply(451, "Error in server: %s", s);
2537	reply(221, "Closing connection due to server error.");
2538	dologout(0);
2539	/* NOTREACHED */
2540}
2541
2542void
2543reply(int n, const char *fmt, ...)
2544{
2545	va_list ap;
2546
2547	(void)printf("%d ", n);
2548	va_start(ap, fmt);
2549	(void)vprintf(fmt, ap);
2550	va_end(ap);
2551	(void)printf("\r\n");
2552	(void)fflush(stdout);
2553	if (ftpdebug) {
2554		syslog(LOG_DEBUG, "<--- %d ", n);
2555		va_start(ap, fmt);
2556		vsyslog(LOG_DEBUG, fmt, ap);
2557		va_end(ap);
2558	}
2559}
2560
2561void
2562lreply(int n, const char *fmt, ...)
2563{
2564	va_list ap;
2565
2566	(void)printf("%d- ", n);
2567	va_start(ap, fmt);
2568	(void)vprintf(fmt, ap);
2569	va_end(ap);
2570	(void)printf("\r\n");
2571	(void)fflush(stdout);
2572	if (ftpdebug) {
2573		syslog(LOG_DEBUG, "<--- %d- ", n);
2574		va_start(ap, fmt);
2575		vsyslog(LOG_DEBUG, fmt, ap);
2576		va_end(ap);
2577	}
2578}
2579
2580static void
2581ack(char *s)
2582{
2583
2584	reply(250, "%s command successful.", s);
2585}
2586
2587void
2588nack(char *s)
2589{
2590
2591	reply(502, "%s command not implemented.", s);
2592}
2593
2594/* ARGSUSED */
2595void
2596yyerror(char *s)
2597{
2598	char *cp;
2599
2600	if ((cp = strchr(cbuf,'\n')))
2601		*cp = '\0';
2602	reply(500, "%s: command not understood.", cbuf);
2603}
2604
2605void
2606delete(char *name)
2607{
2608	struct stat st;
2609
2610	LOGCMD("delete", name);
2611	if (lstat(name, &st) < 0) {
2612		perror_reply(550, name);
2613		return;
2614	}
2615	if (S_ISDIR(st.st_mode)) {
2616		if (rmdir(name) < 0) {
2617			perror_reply(550, name);
2618			return;
2619		}
2620		goto done;
2621	}
2622	if (guest && noguestmod) {
2623		reply(550, "Operation not permitted.");
2624		return;
2625	}
2626	if (unlink(name) < 0) {
2627		perror_reply(550, name);
2628		return;
2629	}
2630done:
2631	ack("DELE");
2632}
2633
2634void
2635cwd(char *path)
2636{
2637
2638	if (chdir(path) < 0)
2639		perror_reply(550, path);
2640	else
2641		ack("CWD");
2642}
2643
2644void
2645makedir(char *name)
2646{
2647	char *s;
2648
2649	LOGCMD("mkdir", name);
2650	if (guest && noguestmkd)
2651		reply(550, "Operation not permitted.");
2652	else if (mkdir(name, 0777) < 0)
2653		perror_reply(550, name);
2654	else {
2655		if ((s = doublequote(name)) == NULL)
2656			fatalerror("Ran out of memory.");
2657		reply(257, "\"%s\" directory created.", s);
2658		free(s);
2659	}
2660}
2661
2662void
2663removedir(char *name)
2664{
2665
2666	LOGCMD("rmdir", name);
2667	if (rmdir(name) < 0)
2668		perror_reply(550, name);
2669	else
2670		ack("RMD");
2671}
2672
2673void
2674pwd(void)
2675{
2676	char *s, path[MAXPATHLEN + 1];
2677
2678	if (getcwd(path, sizeof(path)) == NULL)
2679		perror_reply(550, "Get current directory");
2680	else {
2681		if ((s = doublequote(path)) == NULL)
2682			fatalerror("Ran out of memory.");
2683		reply(257, "\"%s\" is current directory.", s);
2684		free(s);
2685	}
2686}
2687
2688char *
2689renamefrom(char *name)
2690{
2691	struct stat st;
2692
2693	if (guest && noguestmod) {
2694		reply(550, "Operation not permitted.");
2695		return (NULL);
2696	}
2697	if (lstat(name, &st) < 0) {
2698		perror_reply(550, name);
2699		return (NULL);
2700	}
2701	reply(350, "File exists, ready for destination name.");
2702	return (name);
2703}
2704
2705void
2706renamecmd(char *from, char *to)
2707{
2708	struct stat st;
2709
2710	LOGCMD2("rename", from, to);
2711
2712	if (guest && (stat(to, &st) == 0)) {
2713		reply(550, "%s: permission denied.", to);
2714		return;
2715	}
2716
2717	if (rename(from, to) < 0)
2718		perror_reply(550, "rename");
2719	else
2720		ack("RNTO");
2721}
2722
2723static void
2724dolog(struct sockaddr *who)
2725{
2726	char who_name[NI_MAXHOST];
2727
2728	realhostname_sa(remotehost, sizeof(remotehost) - 1, who, who->sa_len);
2729	remotehost[sizeof(remotehost) - 1] = 0;
2730	if (getnameinfo(who, who->sa_len,
2731		who_name, sizeof(who_name) - 1, NULL, 0, NI_NUMERICHOST))
2732			*who_name = 0;
2733	who_name[sizeof(who_name) - 1] = 0;
2734
2735#ifdef SETPROCTITLE
2736#ifdef VIRTUAL_HOSTING
2737	if (thishost != firsthost)
2738		snprintf(proctitle, sizeof(proctitle), "%s: connected (to %s)",
2739			 remotehost, hostname);
2740	else
2741#endif
2742		snprintf(proctitle, sizeof(proctitle), "%s: connected",
2743			 remotehost);
2744	setproctitle("%s", proctitle);
2745#endif /* SETPROCTITLE */
2746
2747	if (logging) {
2748#ifdef VIRTUAL_HOSTING
2749		if (thishost != firsthost)
2750			syslog(LOG_INFO, "connection from %s (%s) to %s",
2751			       remotehost, who_name, hostname);
2752		else
2753#endif
2754			syslog(LOG_INFO, "connection from %s (%s)",
2755			       remotehost, who_name);
2756	}
2757}
2758
2759/*
2760 * Record logout in wtmp file
2761 * and exit with supplied status.
2762 */
2763void
2764dologout(int status)
2765{
2766
2767	if (logged_in && dowtmp) {
2768		(void) seteuid(0);
2769		ftpd_logwtmp(ttyline, "", NULL);
2770	}
2771	/* beware of flushing buffers after a SIGPIPE */
2772	_exit(status);
2773}
2774
2775static void
2776sigurg(int signo)
2777{
2778
2779	recvurg = 1;
2780}
2781
2782static void
2783maskurg(int flag)
2784{
2785	int oerrno;
2786	sigset_t sset;
2787
2788	if (!transflag) {
2789		syslog(LOG_ERR, "Internal: maskurg() while no transfer");
2790		return;
2791	}
2792	oerrno = errno;
2793	sigemptyset(&sset);
2794	sigaddset(&sset, SIGURG);
2795	sigprocmask(flag ? SIG_BLOCK : SIG_UNBLOCK, &sset, NULL);
2796	errno = oerrno;
2797}
2798
2799static void
2800flagxfer(int flag)
2801{
2802
2803	if (flag) {
2804		if (transflag)
2805			syslog(LOG_ERR, "Internal: flagxfer(1): "
2806					"transfer already under way");
2807		transflag = 1;
2808		maskurg(0);
2809		recvurg = 0;
2810	} else {
2811		if (!transflag)
2812			syslog(LOG_ERR, "Internal: flagxfer(0): "
2813					"no active transfer");
2814		maskurg(1);
2815		transflag = 0;
2816	}
2817}
2818
2819/*
2820 * Returns 0 if OK to resume or -1 if abort requested.
2821 */
2822static int
2823myoob(void)
2824{
2825	char *cp;
2826	int ret;
2827
2828	if (!transflag) {
2829		syslog(LOG_ERR, "Internal: myoob() while no transfer");
2830		return (0);
2831	}
2832	cp = tmpline;
2833	ret = getline(cp, 7, stdin);
2834	if (ret == -1) {
2835		reply(221, "You could at least say goodbye.");
2836		dologout(0);
2837	} else if (ret == -2) {
2838			/* Ignore truncated command. */
2839			return (0);
2840	}
2841	upper(cp);
2842	if (strcmp(cp, "ABOR\r\n") == 0) {
2843		tmpline[0] = '\0';
2844		reply(426, "Transfer aborted. Data connection closed.");
2845		reply(226, "Abort successful.");
2846		return (-1);
2847	}
2848	if (strcmp(cp, "STAT\r\n") == 0) {
2849		tmpline[0] = '\0';
2850		if (file_size != -1)
2851			reply(213, "Status: %lld of %lld bytes transferred.",
2852				   (intmax_t)byte_count, (intmax_t)file_size);
2853		else
2854			reply(213, "Status: %lld bytes transferred.",
2855				   (intmax_t)byte_count);
2856	}
2857	return (0);
2858}
2859
2860/*
2861 * Note: a response of 425 is not mentioned as a possible response to
2862 *	the PASV command in RFC959. However, it has been blessed as
2863 *	a legitimate response by Jon Postel in a telephone conversation
2864 *	with Rick Adams on 25 Jan 89.
2865 */
2866void
2867passive(void)
2868{
2869	socklen_t len;
2870	int on;
2871	char *p, *a;
2872
2873	if (pdata >= 0)		/* close old port if one set */
2874		close(pdata);
2875
2876	pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2877	if (pdata < 0) {
2878		perror_reply(425, "Can't open passive connection");
2879		return;
2880	}
2881	on = 1;
2882	if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
2883		syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
2884
2885	(void) seteuid(0);
2886
2887#ifdef IP_PORTRANGE
2888	if (ctrl_addr.su_family == AF_INET) {
2889	    on = restricted_data_ports ? IP_PORTRANGE_HIGH
2890				       : IP_PORTRANGE_DEFAULT;
2891
2892	    if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2893			    &on, sizeof(on)) < 0)
2894		    goto pasv_error;
2895	}
2896#endif
2897#ifdef IPV6_PORTRANGE
2898	if (ctrl_addr.su_family == AF_INET6) {
2899	    on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
2900				       : IPV6_PORTRANGE_DEFAULT;
2901
2902	    if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2903			    &on, sizeof(on)) < 0)
2904		    goto pasv_error;
2905	}
2906#endif
2907
2908	pasv_addr = ctrl_addr;
2909	pasv_addr.su_port = 0;
2910	if (bind(pdata, (struct sockaddr *)&pasv_addr, pasv_addr.su_len) < 0)
2911		goto pasv_error;
2912
2913	(void) seteuid(pw->pw_uid);
2914
2915	len = sizeof(pasv_addr);
2916	if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2917		goto pasv_error;
2918	if (listen(pdata, 1) < 0)
2919		goto pasv_error;
2920	if (pasv_addr.su_family == AF_INET)
2921		a = (char *) &pasv_addr.su_sin.sin_addr;
2922#ifdef HAVE_AF_INET6
2923	else if (pasv_addr.su_family == AF_INET6 &&
2924		 IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr))
2925		a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
2926#endif
2927	else
2928		goto pasv_error;
2929
2930	p = (char *) &pasv_addr.su_port;
2931
2932#define UC(b) (((int) b) & 0xff)
2933
2934	reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
2935		UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
2936	return;
2937
2938pasv_error:
2939	(void) seteuid(pw->pw_uid);
2940	(void) close(pdata);
2941	pdata = -1;
2942	perror_reply(425, "Can't open passive connection");
2943	return;
2944}
2945
2946/*
2947 * Long Passive defined in RFC 1639.
2948 *     228 Entering Long Passive Mode
2949 *         (af, hal, h1, h2, h3,..., pal, p1, p2...)
2950 */
2951
2952void
2953long_passive(char *cmd, int pf)
2954{
2955	socklen_t len;
2956	int on;
2957	char *p, *a;
2958
2959	if (pdata >= 0)		/* close old port if one set */
2960		close(pdata);
2961
2962	if (pf != PF_UNSPEC) {
2963		if (ctrl_addr.su_family != pf) {
2964			switch (ctrl_addr.su_family) {
2965			case AF_INET:
2966				pf = 1;
2967				break;
2968			case AF_INET6:
2969				pf = 2;
2970				break;
2971			default:
2972				pf = 0;
2973				break;
2974			}
2975			/*
2976			 * XXX
2977			 * only EPRT/EPSV ready clients will understand this
2978			 */
2979			if (strcmp(cmd, "EPSV") == 0 && pf) {
2980				reply(522, "Network protocol mismatch, "
2981					"use (%d)", pf);
2982			} else
2983				reply(501, "Network protocol mismatch."); /*XXX*/
2984
2985			return;
2986		}
2987	}
2988
2989	pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2990	if (pdata < 0) {
2991		perror_reply(425, "Can't open passive connection");
2992		return;
2993	}
2994	on = 1;
2995	if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
2996		syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
2997
2998	(void) seteuid(0);
2999
3000	pasv_addr = ctrl_addr;
3001	pasv_addr.su_port = 0;
3002	len = pasv_addr.su_len;
3003
3004#ifdef IP_PORTRANGE
3005	if (ctrl_addr.su_family == AF_INET) {
3006	    on = restricted_data_ports ? IP_PORTRANGE_HIGH
3007				       : IP_PORTRANGE_DEFAULT;
3008
3009	    if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
3010			    &on, sizeof(on)) < 0)
3011		    goto pasv_error;
3012	}
3013#endif
3014#ifdef IPV6_PORTRANGE
3015	if (ctrl_addr.su_family == AF_INET6) {
3016	    on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
3017				       : IPV6_PORTRANGE_DEFAULT;
3018
3019	    if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
3020			    &on, sizeof(on)) < 0)
3021		    goto pasv_error;
3022	}
3023#endif
3024
3025	if (bind(pdata, (struct sockaddr *)&pasv_addr, len) < 0)
3026		goto pasv_error;
3027
3028	(void) seteuid(pw->pw_uid);
3029
3030	if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
3031		goto pasv_error;
3032	if (listen(pdata, 1) < 0)
3033		goto pasv_error;
3034
3035#define UC(b) (((int) b) & 0xff)
3036
3037	if (strcmp(cmd, "LPSV") == 0) {
3038		p = (char *)&pasv_addr.su_port;
3039		switch (pasv_addr.su_family) {
3040		case AF_INET:
3041			a = (char *) &pasv_addr.su_sin.sin_addr;
3042#ifdef HAVE_AF_INET6
3043		v4_reply:
3044#endif
3045			reply(228,
3046"Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)",
3047			      4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
3048			      2, UC(p[0]), UC(p[1]));
3049			return;
3050#ifdef HAVE_AF_INET6
3051		case AF_INET6:
3052			if (IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr)) {
3053				a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
3054				goto v4_reply;
3055			}
3056			a = (char *) &pasv_addr.su_sin6.sin6_addr;
3057			reply(228,
3058"Entering Long Passive Mode "
3059"(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)",
3060			      6, 16, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
3061			      UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]),
3062			      UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]),
3063			      UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]),
3064			      2, UC(p[0]), UC(p[1]));
3065			return;
3066#endif
3067		}
3068	} else if (strcmp(cmd, "EPSV") == 0) {
3069		switch (pasv_addr.su_family) {
3070		case AF_INET:
3071		case AF_INET6:
3072			reply(229, "Entering Extended Passive Mode (|||%d|)",
3073				ntohs(pasv_addr.su_port));
3074			return;
3075		}
3076	} else {
3077		/* more proper error code? */
3078	}
3079
3080pasv_error:
3081	(void) seteuid(pw->pw_uid);
3082	(void) close(pdata);
3083	pdata = -1;
3084	perror_reply(425, "Can't open passive connection");
3085	return;
3086}
3087
3088/*
3089 * Generate unique name for file with basename "local"
3090 * and open the file in order to avoid possible races.
3091 * Try "local" first, then "local.1", "local.2" etc, up to "local.99".
3092 * Return descriptor to the file, set "name" to its name.
3093 *
3094 * Generates failure reply on error.
3095 */
3096static int
3097guniquefd(char *local, char **name)
3098{
3099	static char new[MAXPATHLEN];
3100	struct stat st;
3101	char *cp;
3102	int count;
3103	int fd;
3104
3105	cp = strrchr(local, '/');
3106	if (cp)
3107		*cp = '\0';
3108	if (stat(cp ? local : ".", &st) < 0) {
3109		perror_reply(553, cp ? local : ".");
3110		return (-1);
3111	}
3112	if (cp) {
3113		/*
3114		 * Let not overwrite dirname with counter suffix.
3115		 * -4 is for /nn\0
3116		 * In this extreme case dot won't be put in front of suffix.
3117		 */
3118		if (strlen(local) > sizeof(new) - 4) {
3119			reply(553, "Pathname too long.");
3120			return (-1);
3121		}
3122		*cp = '/';
3123	}
3124	/* -4 is for the .nn<null> we put on the end below */
3125	(void) snprintf(new, sizeof(new) - 4, "%s", local);
3126	cp = new + strlen(new);
3127	/*
3128	 * Don't generate dotfile unless requested explicitly.
3129	 * This covers the case when basename gets truncated off
3130	 * by buffer size.
3131	 */
3132	if (cp > new && cp[-1] != '/')
3133		*cp++ = '.';
3134	for (count = 0; count < 100; count++) {
3135		/* At count 0 try unmodified name */
3136		if (count)
3137			(void)sprintf(cp, "%d", count);
3138		if ((fd = open(count ? new : local,
3139		    O_RDWR | O_CREAT | O_EXCL, 0666)) >= 0) {
3140			*name = count ? new : local;
3141			return (fd);
3142		}
3143		if (errno != EEXIST) {
3144			perror_reply(553, count ? new : local);
3145			return (-1);
3146		}
3147	}
3148	reply(452, "Unique file name cannot be created.");
3149	return (-1);
3150}
3151
3152/*
3153 * Format and send reply containing system error number.
3154 */
3155void
3156perror_reply(int code, char *string)
3157{
3158
3159	reply(code, "%s: %s.", string, strerror(errno));
3160}
3161
3162static char *onefile[] = {
3163	"",
3164	0
3165};
3166
3167void
3168send_file_list(char *whichf)
3169{
3170	struct stat st;
3171	DIR *dirp = NULL;
3172	struct dirent *dir;
3173	FILE *dout = NULL;
3174	char **dirlist, *dirname;
3175	int simple = 0;
3176	int freeglob = 0;
3177	glob_t gl;
3178
3179	if (strpbrk(whichf, "~{[*?") != NULL) {
3180		int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
3181
3182		memset(&gl, 0, sizeof(gl));
3183		gl.gl_matchc = MAXGLOBARGS;
3184		flags |= GLOB_LIMIT;
3185		freeglob = 1;
3186		if (glob(whichf, flags, 0, &gl)) {
3187			reply(550, "No matching files found.");
3188			goto out;
3189		} else if (gl.gl_pathc == 0) {
3190			errno = ENOENT;
3191			perror_reply(550, whichf);
3192			goto out;
3193		}
3194		dirlist = gl.gl_pathv;
3195	} else {
3196		onefile[0] = whichf;
3197		dirlist = onefile;
3198		simple = 1;
3199	}
3200
3201	while ((dirname = *dirlist++)) {
3202		if (stat(dirname, &st) < 0) {
3203			/*
3204			 * If user typed "ls -l", etc, and the client
3205			 * used NLST, do what the user meant.
3206			 */
3207			if (dirname[0] == '-' && *dirlist == NULL &&
3208			    dout == NULL)
3209				retrieve(_PATH_LS " %s", dirname);
3210			else
3211				perror_reply(550, whichf);
3212			goto out;
3213		}
3214
3215		if (S_ISREG(st.st_mode)) {
3216			if (dout == NULL) {
3217				dout = dataconn("file list", -1, "w");
3218				if (dout == NULL)
3219					goto out;
3220				STARTXFER;
3221			}
3222			START_UNSAFE;
3223			fprintf(dout, "%s%s\n", dirname,
3224				type == TYPE_A ? "\r" : "");
3225			END_UNSAFE;
3226			if (ferror(dout))
3227				goto data_err;
3228			byte_count += strlen(dirname) +
3229				      (type == TYPE_A ? 2 : 1);
3230			CHECKOOB(goto abrt);
3231			continue;
3232		} else if (!S_ISDIR(st.st_mode))
3233			continue;
3234
3235		if ((dirp = opendir(dirname)) == NULL)
3236			continue;
3237
3238		while ((dir = readdir(dirp)) != NULL) {
3239			char nbuf[MAXPATHLEN];
3240
3241			CHECKOOB(goto abrt);
3242
3243#if (defined(__BEOS__) || defined(__HAIKU__))
3244			if (dir->d_name[0] == '.' && dir->d_name[1] == '\0')
3245				continue;
3246			if (dir->d_name[0] == '.' && dir->d_name[1] == '.' &&
3247			    dir->d_name[2] == '\0')
3248				continue;
3249#else
3250			if (dir->d_name[0] == '.' && dir->d_namlen == 1)
3251				continue;
3252			if (dir->d_name[0] == '.' && dir->d_name[1] == '.' &&
3253			    dir->d_namlen == 2)
3254				continue;
3255#endif
3256
3257			snprintf(nbuf, sizeof(nbuf),
3258				"%s/%s", dirname, dir->d_name);
3259
3260			/*
3261			 * We have to do a stat to insure it's
3262			 * not a directory or special file.
3263			 */
3264			if (simple || (stat(nbuf, &st) == 0 &&
3265			    S_ISREG(st.st_mode))) {
3266				if (dout == NULL) {
3267					dout = dataconn("file list", -1, "w");
3268					if (dout == NULL)
3269						goto out;
3270					STARTXFER;
3271				}
3272				START_UNSAFE;
3273				if (nbuf[0] == '.' && nbuf[1] == '/')
3274					fprintf(dout, "%s%s\n", &nbuf[2],
3275						type == TYPE_A ? "\r" : "");
3276				else
3277					fprintf(dout, "%s%s\n", nbuf,
3278						type == TYPE_A ? "\r" : "");
3279				END_UNSAFE;
3280				if (ferror(dout))
3281					goto data_err;
3282				byte_count += strlen(nbuf) +
3283					      (type == TYPE_A ? 2 : 1);
3284				CHECKOOB(goto abrt);
3285			}
3286		}
3287		(void) closedir(dirp);
3288		dirp = NULL;
3289	}
3290
3291	if (dout == NULL)
3292		reply(550, "No files found.");
3293	else if (ferror(dout))
3294data_err:	perror_reply(550, "Data connection");
3295	else
3296		reply(226, "Transfer complete.");
3297out:
3298	if (dout) {
3299		ENDXFER;
3300abrt:
3301		(void) fclose(dout);
3302		data = -1;
3303		pdata = -1;
3304	}
3305	if (dirp)
3306		(void) closedir(dirp);
3307	if (freeglob) {
3308		freeglob = 0;
3309		globfree(&gl);
3310	}
3311}
3312
3313void
3314reapchild(int signo)
3315{
3316	while (waitpid(-1, NULL, WNOHANG) > 0);
3317}
3318
3319static void
3320appendf(char **strp, char *fmt, ...)
3321{
3322	va_list ap;
3323	char *ostr, *p;
3324
3325	va_start(ap, fmt);
3326	vasprintf(&p, fmt, ap);
3327	va_end(ap);
3328	if (p == NULL)
3329		fatalerror("Ran out of memory.");
3330	if (*strp == NULL)
3331		*strp = p;
3332	else {
3333		ostr = *strp;
3334		asprintf(strp, "%s%s", ostr, p);
3335		if (*strp == NULL)
3336			fatalerror("Ran out of memory.");
3337		free(ostr);
3338	}
3339}
3340
3341static void
3342logcmd(char *cmd, char *file1, char *file2, off_t cnt)
3343{
3344	char *msg = NULL;
3345	char wd[MAXPATHLEN + 1];
3346
3347	if (logging <= 1)
3348		return;
3349
3350	if (getcwd(wd, sizeof(wd) - 1) == NULL)
3351		strcpy(wd, strerror(errno));
3352
3353	appendf(&msg, "%s", cmd);
3354	if (file1)
3355		appendf(&msg, " %s", file1);
3356	if (file2)
3357		appendf(&msg, " %s", file2);
3358	if (cnt >= 0)
3359		appendf(&msg, " = %lld bytes", (intmax_t)cnt);
3360	appendf(&msg, " (wd: %s", wd);
3361	if (guest || dochroot)
3362		appendf(&msg, "; chrooted");
3363	appendf(&msg, ")");
3364	syslog(LOG_INFO, "%s", msg);
3365	free(msg);
3366}
3367
3368static void
3369logxfer(char *name, off_t size, time_t start)
3370{
3371	char buf[MAXPATHLEN + 1024];
3372	char path[MAXPATHLEN + 1];
3373	time_t now;
3374
3375	if (statfd >= 0) {
3376		time(&now);
3377		if (realpath(name, path) == NULL) {
3378			syslog(LOG_NOTICE, "realpath failed on %s: %m", path);
3379			return;
3380		}
3381		snprintf(buf, sizeof(buf), "%.20s!%s!%s!%s!%lld!%ld\n",
3382			ctime(&now)+4, ident, remotehost,
3383			path, (intmax_t)size,
3384			(long)(now - start + (now == start)));
3385		write(statfd, buf, strlen(buf));
3386	}
3387}
3388
3389static char *
3390doublequote(char *s)
3391{
3392	int n;
3393	char *p, *s2;
3394
3395	for (p = s, n = 0; *p; p++)
3396		if (*p == '"')
3397			n++;
3398
3399	if ((s2 = malloc(p - s + n + 1)) == NULL)
3400		return (NULL);
3401
3402	for (p = s2; *s; s++, p++) {
3403		if ((*p = *s) == '"')
3404			*(++p) = '"';
3405	}
3406	*p = '\0';
3407
3408	return (s2);
3409}
3410
3411/* setup server socket for specified address family */
3412/* if af is PF_UNSPEC more than one socket may be returned */
3413/* the returned list is dynamically allocated, so caller needs to free it */
3414static int *
3415socksetup(int af, char *bindname, const char *bindport)
3416{
3417	struct addrinfo hints, *res, *r;
3418	int error, maxs, *s, *socks;
3419	const int on = 1;
3420
3421	memset(&hints, 0, sizeof(hints));
3422	hints.ai_flags = AI_PASSIVE;
3423	hints.ai_family = af;
3424	hints.ai_socktype = SOCK_STREAM;
3425	error = getaddrinfo(bindname, bindport, &hints, &res);
3426	if (error) {
3427		syslog(LOG_ERR, "%s", gai_strerror(error));
3428		if (error == EAI_SYSTEM)
3429			syslog(LOG_ERR, "%s", strerror(errno));
3430		return NULL;
3431	}
3432
3433	/* Count max number of sockets we may open */
3434	for (maxs = 0, r = res; r; r = r->ai_next, maxs++)
3435		;
3436	socks = malloc((maxs + 1) * sizeof(int));
3437	if (!socks) {
3438		freeaddrinfo(res);
3439		syslog(LOG_ERR, "couldn't allocate memory for sockets");
3440		return NULL;
3441	}
3442
3443	*socks = 0;   /* num of sockets counter at start of array */
3444	s = socks + 1;
3445	for (r = res; r; r = r->ai_next) {
3446		*s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
3447		if (*s < 0) {
3448			syslog(LOG_DEBUG, "control socket: %m");
3449			continue;
3450		}
3451		if (setsockopt(*s, SOL_SOCKET, SO_REUSEADDR,
3452		    &on, sizeof(on)) < 0)
3453			syslog(LOG_WARNING,
3454			    "control setsockopt (SO_REUSEADDR): %m");
3455#ifdef HAVE_AF_INET6
3456		if (r->ai_family == AF_INET6) {
3457			if (setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY,
3458			    &on, sizeof(on)) < 0)
3459				syslog(LOG_WARNING,
3460				    "control setsockopt (IPV6_V6ONLY): %m");
3461		}
3462#endif
3463		if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
3464			syslog(LOG_DEBUG, "control bind: %m");
3465			close(*s);
3466			continue;
3467		}
3468		(*socks)++;
3469		s++;
3470	}
3471
3472	if (res)
3473		freeaddrinfo(res);
3474
3475	if (*socks == 0) {
3476		syslog(LOG_ERR, "control socket: Couldn't bind to any socket");
3477		free(socks);
3478		return NULL;
3479	}
3480	return(socks);
3481}
3482