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