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