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