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