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