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