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