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