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