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