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