xref: /netbsd-src/libexec/ftpd/ftpd.c (revision aaf4ece63a859a04e37cf3a7229b5fab0157cc06)
1 /*	$NetBSD: ftpd.c,v 1.170 2005/11/24 23:47:23 lukem Exp $	*/
2 
3 /*
4  * Copyright (c) 1997-2004 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Luke Mewburn.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *        This product includes software developed by the NetBSD
21  *        Foundation, Inc. and its contributors.
22  * 4. Neither the name of The NetBSD Foundation nor the names of its
23  *    contributors may be used to endorse or promote products derived
24  *    from this software without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36  * POSSIBILITY OF SUCH DAMAGE.
37  */
38 
39 /*
40  * Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994
41  *	The Regents of the University of California.  All rights reserved.
42  *
43  * Redistribution and use in source and binary forms, with or without
44  * modification, are permitted provided that the following conditions
45  * are met:
46  * 1. Redistributions of source code must retain the above copyright
47  *    notice, this list of conditions and the following disclaimer.
48  * 2. Redistributions in binary form must reproduce the above copyright
49  *    notice, this list of conditions and the following disclaimer in the
50  *    documentation and/or other materials provided with the distribution.
51  * 3. Neither the name of the University nor the names of its contributors
52  *    may be used to endorse or promote products derived from this software
53  *    without specific prior written permission.
54  *
55  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
56  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
57  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
58  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
59  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
60  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
61  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
62  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
63  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
64  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
65  * SUCH DAMAGE.
66  */
67 
68 /*
69  * Copyright (C) 1997 and 1998 WIDE Project.
70  * All rights reserved.
71  *
72  * Redistribution and use in source and binary forms, with or without
73  * modification, are permitted provided that the following conditions
74  * are met:
75  * 1. Redistributions of source code must retain the above copyright
76  *    notice, this list of conditions and the following disclaimer.
77  * 2. Redistributions in binary form must reproduce the above copyright
78  *    notice, this list of conditions and the following disclaimer in the
79  *    documentation and/or other materials provided with the distribution.
80  * 3. Neither the name of the project nor the names of its contributors
81  *    may be used to endorse or promote products derived from this software
82  *    without specific prior written permission.
83  *
84  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
85  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
86  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
87  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
88  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
89  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
90  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
91  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
92  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
93  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
94  * SUCH DAMAGE.
95  */
96 
97 #include <sys/cdefs.h>
98 #ifndef lint
99 __COPYRIGHT(
100 "@(#) Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994\n\
101 	The Regents of the University of California.  All rights reserved.\n");
102 #endif /* not lint */
103 
104 #ifndef lint
105 #if 0
106 static char sccsid[] = "@(#)ftpd.c	8.5 (Berkeley) 4/28/95";
107 #else
108 __RCSID("$NetBSD: ftpd.c,v 1.170 2005/11/24 23:47:23 lukem Exp $");
109 #endif
110 #endif /* not lint */
111 
112 /*
113  * FTP server.
114  */
115 #include <sys/param.h>
116 #include <sys/stat.h>
117 #include <sys/ioctl.h>
118 #include <sys/socket.h>
119 #include <sys/wait.h>
120 #include <sys/mman.h>
121 #include <sys/resource.h>
122 
123 #include <netinet/in.h>
124 #include <netinet/in_systm.h>
125 #include <netinet/ip.h>
126 
127 #define	FTP_NAMES
128 #include <arpa/ftp.h>
129 #include <arpa/inet.h>
130 #include <arpa/telnet.h>
131 
132 #include <ctype.h>
133 #include <dirent.h>
134 #include <err.h>
135 #include <errno.h>
136 #include <fcntl.h>
137 #include <fnmatch.h>
138 #include <glob.h>
139 #include <grp.h>
140 #include <limits.h>
141 #include <netdb.h>
142 #include <pwd.h>
143 #include <poll.h>
144 #include <signal.h>
145 #include <stdarg.h>
146 #include <stdio.h>
147 #include <stdlib.h>
148 #include <string.h>
149 #include <syslog.h>
150 #include <time.h>
151 #include <tzfile.h>
152 #include <unistd.h>
153 #include <util.h>
154 #ifdef SUPPORT_UTMP
155 #include <utmp.h>
156 #endif
157 #ifdef SUPPORT_UTMPX
158 #include <utmpx.h>
159 #endif
160 #ifdef SKEY
161 #include <skey.h>
162 #endif
163 #ifdef KERBEROS5
164 #include <com_err.h>
165 #include <krb5/krb5.h>
166 #endif
167 
168 #ifdef	LOGIN_CAP
169 #include <login_cap.h>
170 #endif
171 
172 #ifdef USE_PAM
173 #include <security/pam_appl.h>
174 #endif
175 
176 #define	GLOBAL
177 #include "extern.h"
178 #include "pathnames.h"
179 #include "version.h"
180 
181 volatile sig_atomic_t	transflag;
182 volatile sig_atomic_t	urgflag;
183 
184 int	data;
185 int	Dflag;
186 int	sflag;
187 int	stru;			/* avoid C keyword */
188 int	mode;
189 int	dataport;		/* use specific data port */
190 int	dopidfile;		/* maintain pid file */
191 int	doutmp;			/* update utmp file */
192 int	dowtmp;			/* update wtmp file */
193 int	doxferlog;		/* syslog/write wu-ftpd style xferlog entries */
194 int	xferlogfd;		/* fd to write wu-ftpd xferlog entries to */
195 int	dropprivs;		/* if privileges should or have been dropped */
196 int	mapped;			/* IPv4 connection on AF_INET6 socket */
197 off_t	file_size;
198 off_t	byte_count;
199 static char ttyline[20];
200 
201 #ifdef USE_PAM
202 static int	auth_pam(struct passwd **, const char *);
203 pam_handle_t	*pamh = NULL;
204 #endif
205 
206 #ifdef SUPPORT_UTMP
207 static struct utmp utmp;	/* for utmp */
208 #endif
209 #ifdef SUPPORT_UTMPX
210 static struct utmpx utmpx;	/* for utmpx */
211 #endif
212 
213 static const char *anondir = NULL;
214 static const char *confdir = _DEFAULT_CONFDIR;
215 
216 static char	*curname;		/* current USER name */
217 static size_t	curname_len;		/* length of curname (include NUL) */
218 
219 #if defined(KERBEROS) || defined(KERBEROS5)
220 int	has_ccache = 0;
221 int	notickets = 1;
222 char	*krbtkfile_env = NULL;
223 char	*tty = ttyline;
224 int	login_krb5_forwardable_tgt = 0;
225 #endif
226 
227 int epsvall = 0;
228 
229 /*
230  * Timeout intervals for retrying connections
231  * to hosts that don't accept PORT cmds.  This
232  * is a kludge, but given the problems with TCP...
233  */
234 #define	SWAITMAX	90	/* wait at most 90 seconds */
235 #define	SWAITINT	5	/* interval between retries */
236 
237 int	swaitmax = SWAITMAX;
238 int	swaitint = SWAITINT;
239 
240 enum send_status {
241 	SS_SUCCESS,
242 	SS_ABORTED,			/* transfer aborted */
243 	SS_NO_TRANSFER,			/* no transfer made yet */
244 	SS_FILE_ERROR,			/* file read error */
245 	SS_DATA_ERROR			/* data send error */
246 };
247 
248 static int	 bind_pasv_addr(void);
249 static int	 checkuser(const char *, const char *, int, int, char **);
250 static int	 checkaccess(const char *);
251 static int	 checkpassword(const struct passwd *, const char *);
252 static void	 end_login(void);
253 static FILE	*getdatasock(const char *);
254 static char	*gunique(const char *);
255 static void	 login_utmp(const char *, const char *, const char *,
256 		     struct sockinet *);
257 static void	 logremotehost(struct sockinet *);
258 static void	 lostconn(int);
259 static void	 toolong(int);
260 static void	 sigquit(int);
261 static void	 sigurg(int);
262 static int	 handleoobcmd(void);
263 static int	 receive_data(FILE *, FILE *);
264 static int	 send_data(FILE *, FILE *, const struct stat *, int);
265 static struct passwd *sgetpwnam(const char *);
266 static int	 write_data(int, char *, size_t, off_t *, struct timeval *,
267 		     int);
268 static enum send_status
269 		 send_data_with_read(int, int, const struct stat *, int);
270 static enum send_status
271 		 send_data_with_mmap(int, int, const struct stat *, int);
272 static void	 logrusage(const struct rusage *, const struct rusage *);
273 static void	 logout_utmp(void);
274 
275 int	main(int, char *[]);
276 
277 #if defined(KERBEROS)
278 int	klogin(struct passwd *, char *, char *, char *);
279 void	kdestroy(void);
280 #endif
281 #if defined(KERBEROS5)
282 int	k5login(struct passwd *, char *, char *, char *);
283 void	k5destroy(void);
284 #endif
285 
286 int
287 main(int argc, char *argv[])
288 {
289 	int		addrlen, ch, on = 1, tos, keepalive;
290 #ifdef KERBEROS5
291 	krb5_error_code	kerror;
292 #endif
293 	char		*p;
294 	const char	*xferlogname = NULL;
295 	long		l;
296 	struct sigaction sa;
297 	sa_family_t	af = AF_UNSPEC;
298 
299 	connections = 1;
300 	debug = 0;
301 	logging = 0;
302 	pdata = -1;
303 	Dflag = 0;
304 	sflag = 0;
305 	dataport = 0;
306 	dopidfile = 1;		/* default: DO use a pid file to count users */
307 	doutmp = 0;		/* default: Do NOT log to utmp */
308 	dowtmp = 1;		/* default: DO log to wtmp */
309 	doxferlog = 0;		/* default: Do NOT syslog xferlog */
310 	xferlogfd = -1;		/* default: Do NOT write xferlog file */
311 	dropprivs = 0;
312 	mapped = 0;
313 	usedefault = 1;
314 	emailaddr = NULL;
315 	hostname[0] = '\0';
316 	homedir[0] = '\0';
317 	gidcount = 0;
318 	is_oob = 0;
319 	version = FTPD_VERSION;
320 
321 	/*
322 	 * LOG_NDELAY sets up the logging connection immediately,
323 	 * necessary for anonymous ftp's that chroot and can't do it later.
324 	 */
325 	openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
326 
327 	while ((ch = getopt(argc, argv,
328 	    "46a:c:C:Dde:h:HlL:P:qQrst:T:uUvV:wWX")) != -1) {
329 		switch (ch) {
330 		case '4':
331 			af = AF_INET;
332 			break;
333 
334 		case '6':
335 			af = AF_INET6;
336 			break;
337 
338 		case 'a':
339 			anondir = optarg;
340 			break;
341 
342 		case 'c':
343 			confdir = optarg;
344 			break;
345 
346 		case 'C':
347 			pw = sgetpwnam(optarg);
348 			exit(checkaccess(optarg) ? 0 : 1);
349 			/* NOTREACHED */
350 
351 		case 'D':
352 			Dflag = 1;
353 			break;
354 
355 		case 'd':
356 		case 'v':		/* deprecated */
357 			debug = 1;
358 			break;
359 
360 		case 'e':
361 			emailaddr = optarg;
362 			break;
363 
364 		case 'h':
365 			strlcpy(hostname, optarg, sizeof(hostname));
366 			break;
367 
368 		case 'H':
369 			if (gethostname(hostname, sizeof(hostname)) == -1)
370 				hostname[0] = '\0';
371 			hostname[sizeof(hostname) - 1] = '\0';
372 			break;
373 
374 		case 'l':
375 			logging++;	/* > 1 == extra logging */
376 			break;
377 
378 		case 'L':
379 			xferlogname = optarg;
380 			break;
381 
382 		case 'P':
383 			errno = 0;
384 			p = NULL;
385 			l = strtol(optarg, &p, 10);
386 			if (errno || *optarg == '\0' || *p != '\0' ||
387 			    l < IPPORT_RESERVED ||
388 			    l > IPPORT_ANONMAX) {
389 				syslog(LOG_WARNING, "Invalid dataport %s",
390 				    optarg);
391 				dataport = 0;
392 			}
393 			dataport = (int)l;
394 			break;
395 
396 		case 'q':
397 			dopidfile = 1;
398 			break;
399 
400 		case 'Q':
401 			dopidfile = 0;
402 			break;
403 
404 		case 'r':
405 			dropprivs = 1;
406 			break;
407 
408 		case 's':
409 			sflag = 1;
410 			break;
411 
412 		case 't':
413 		case 'T':
414 			syslog(LOG_WARNING,
415 			    "-%c has been deprecated in favour of ftpd.conf",
416 			    ch);
417 			break;
418 
419 		case 'u':
420 			doutmp = 1;
421 			break;
422 
423 		case 'U':
424 			doutmp = 0;
425 			break;
426 
427 		case 'V':
428 			if (EMPTYSTR(optarg) || strcmp(optarg, "-") == 0)
429 				version = NULL;
430 			else
431 				version = xstrdup(optarg);
432 			break;
433 
434 		case 'w':
435 			dowtmp = 1;
436 			break;
437 
438 		case 'W':
439 			dowtmp = 0;
440 			break;
441 
442 		case 'X':
443 			doxferlog |= 1;
444 			break;
445 
446 		default:
447 			if (optopt == 'a' || optopt == 'C')
448 				exit(1);
449 			syslog(LOG_WARNING, "unknown flag -%c ignored", optopt);
450 			break;
451 		}
452 	}
453 	if (EMPTYSTR(confdir))
454 		confdir = _DEFAULT_CONFDIR;
455 
456 	if (dowtmp) {
457 #ifdef SUPPORT_UTMPX
458 		ftpd_initwtmpx();
459 #endif
460 #ifdef SUPPORT_UTMP
461 		ftpd_initwtmp();
462 #endif
463 	}
464 	errno = 0;
465 	l = sysconf(_SC_LOGIN_NAME_MAX);
466 	if (l == -1 && errno != 0) {
467 		syslog(LOG_ERR, "sysconf _SC_LOGIN_NAME_MAX: %m");
468 		exit(1);
469 	} else if (l <= 0) {
470 		syslog(LOG_WARNING, "using conservative LOGIN_NAME_MAX value");
471 		curname_len = _POSIX_LOGIN_NAME_MAX;
472 	} else
473 		curname_len = (size_t)l;
474 	curname = malloc(curname_len);
475 	if (curname == NULL) {
476 		syslog(LOG_ERR, "malloc: %m");
477 		exit(1);
478 	}
479 	curname[0] = '\0';
480 
481 	if (Dflag) {
482 		int error, fd, i, n, *socks;
483 		struct pollfd *fds;
484 		struct addrinfo hints, *res, *res0;
485 
486 		if (daemon(1, 0) == -1) {
487 			syslog(LOG_ERR, "failed to daemonize: %m");
488 			exit(1);
489 		}
490 		(void)memset(&sa, 0, sizeof(sa));
491 		sa.sa_handler = SIG_IGN;
492 		sa.sa_flags = SA_NOCLDWAIT;
493 		sigemptyset(&sa.sa_mask);
494 		(void)sigaction(SIGCHLD, &sa, NULL);
495 
496 		(void)memset(&hints, 0, sizeof(hints));
497 		hints.ai_flags = AI_PASSIVE;
498 		hints.ai_family = af;
499 		hints.ai_socktype = SOCK_STREAM;
500 		error = getaddrinfo(NULL, "ftp", &hints, &res0);
501 		if (error) {
502 			syslog(LOG_ERR, "getaddrinfo: %s", gai_strerror(error));
503 			exit(1);
504 		}
505 
506 		for (n = 0, res = res0; res != NULL; res = res->ai_next)
507 			n++;
508 		if (n == 0) {
509 			syslog(LOG_ERR, "no addresses available");
510 			exit(1);
511 		}
512 		socks = malloc(n * sizeof(int));
513 		fds = malloc(n * sizeof(struct pollfd));
514 		if (socks == NULL || fds == NULL) {
515 			syslog(LOG_ERR, "malloc: %m");
516 			exit(1);
517 		}
518 
519 		for (n = 0, res = res0; res != NULL; res = res->ai_next) {
520 			socks[n] = socket(res->ai_family, res->ai_socktype,
521 			    res->ai_protocol);
522 			if (socks[n] == -1)
523 				continue;
524 			(void)setsockopt(socks[n], SOL_SOCKET, SO_REUSEADDR,
525 			    &on, sizeof(on));
526 			if (bind(socks[n], res->ai_addr, res->ai_addrlen)
527 			    == -1) {
528 				(void)close(socks[n]);
529 				continue;
530 			}
531 			if (listen(socks[n], 12) == -1) {
532 				(void)close(socks[n]);
533 				continue;
534 			}
535 
536 			fds[n].fd = socks[n];
537 			fds[n].events = POLLIN;
538 			n++;
539 		}
540 		if (n == 0) {
541 			syslog(LOG_ERR, "%m");
542 			exit(1);
543 		}
544 		freeaddrinfo(res0);
545 
546 		if (pidfile(NULL) == -1)
547 			syslog(LOG_ERR, "failed to write a pid file: %m");
548 
549 		for (;;) {
550 			if (poll(fds, n, INFTIM) == -1) {
551 				if (errno == EINTR)
552 					continue;
553 				syslog(LOG_ERR, "poll: %m");
554 				exit(1);
555 			}
556 			for (i = 0; i < n; i++) {
557 				if (fds[i].revents & POLLIN) {
558 					fd = accept(fds[i].fd, NULL, NULL);
559 					if (fd == -1) {
560 						syslog(LOG_ERR, "accept: %m");
561 						continue;
562 					}
563 					switch (fork()) {
564 					case -1:
565 						syslog(LOG_ERR, "fork: %m");
566 						break;
567 					case 0:
568 						goto child;
569 						/* NOTREACHED */
570 					}
571 					(void)close(fd);
572 				}
573 			}
574 		}
575  child:
576 		(void)dup2(fd, STDIN_FILENO);
577 		(void)dup2(fd, STDOUT_FILENO);
578 		(void)dup2(fd, STDERR_FILENO);
579 		for (i = 0; i < n; i++)
580 			(void)close(socks[i]);
581 	}
582 
583 	memset((char *)&his_addr, 0, sizeof(his_addr));
584 	addrlen = sizeof(his_addr.si_su);
585 	if (getpeername(0, (struct sockaddr *)&his_addr.si_su, &addrlen) < 0) {
586 		syslog(LOG_ERR, "getpeername (%s): %m",argv[0]);
587 		exit(1);
588 	}
589 	his_addr.su_len = addrlen;
590 	memset((char *)&ctrl_addr, 0, sizeof(ctrl_addr));
591 	addrlen = sizeof(ctrl_addr.si_su);
592 	if (getsockname(0, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) {
593 		syslog(LOG_ERR, "getsockname (%s): %m",argv[0]);
594 		exit(1);
595 	}
596 	ctrl_addr.su_len = addrlen;
597 #ifdef INET6
598 	if (his_addr.su_family == AF_INET6
599 	 && IN6_IS_ADDR_V4MAPPED(&his_addr.su_6addr)) {
600 #if 1
601 		/*
602 		 * IPv4 control connection arrived to AF_INET6 socket.
603 		 * I hate to do this, but this is the easiest solution.
604 		 *
605 		 * The assumption is untrue on SIIT environment.
606 		 */
607 		struct sockinet tmp_addr;
608 		const int off = sizeof(struct in6_addr) - sizeof(struct in_addr);
609 
610 		tmp_addr = his_addr;
611 		memset(&his_addr, 0, sizeof(his_addr));
612 		his_addr.su_family = AF_INET;
613 		his_addr.su_len = sizeof(his_addr.si_su.su_sin);
614 		memcpy(&his_addr.su_addr, &tmp_addr.su_6addr.s6_addr[off],
615 		    sizeof(his_addr.su_addr));
616 		his_addr.su_port = tmp_addr.su_port;
617 
618 		tmp_addr = ctrl_addr;
619 		memset(&ctrl_addr, 0, sizeof(ctrl_addr));
620 		ctrl_addr.su_family = AF_INET;
621 		ctrl_addr.su_len = sizeof(ctrl_addr.si_su.su_sin);
622 		memcpy(&ctrl_addr.su_addr, &tmp_addr.su_6addr.s6_addr[off],
623 		    sizeof(ctrl_addr.su_addr));
624 		ctrl_addr.su_port = tmp_addr.su_port;
625 #else
626 		while (fgets(line, sizeof(line), fd) != NULL) {
627 			if ((cp = strchr(line, '\n')) != NULL)
628 				*cp = '\0';
629 			reply(-530, "%s", line);
630 		}
631 		(void) fflush(stdout);
632 		(void) fclose(fd);
633 		reply(530,
634 		    "Connection from IPv4 mapped address is not supported.");
635 		exit(0);
636 #endif
637 
638 		mapped = 1;
639 	} else
640 #endif /* INET6 */
641 		mapped = 0;
642 #ifdef IP_TOS
643 	if (!mapped && his_addr.su_family == AF_INET) {
644 		tos = IPTOS_LOWDELAY;
645 		if (setsockopt(0, IPPROTO_IP, IP_TOS, (char *)&tos,
646 			       sizeof(int)) < 0)
647 			syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
648 	}
649 #endif
650 	/* if the hostname hasn't been given, attempt to determine it */
651 	if (hostname[0] == '\0') {
652 		if (getnameinfo((struct sockaddr *)&ctrl_addr.si_su,
653 		    ctrl_addr.su_len, hostname, sizeof(hostname), NULL, 0, 0)
654 		    != 0)
655 			(void)gethostname(hostname, sizeof(hostname));
656 		hostname[sizeof(hostname) - 1] = '\0';
657 	}
658 
659 	/* set this here so klogin can use it... */
660 	(void)snprintf(ttyline, sizeof(ttyline), "ftp%d", getpid());
661 
662 	(void) freopen(_PATH_DEVNULL, "w", stderr);
663 
664 	memset(&sa, 0, sizeof(sa));
665 	sa.sa_handler = SIG_DFL;
666 	sa.sa_flags = SA_RESTART;
667 	sigemptyset(&sa.sa_mask);
668 	(void) sigaction(SIGCHLD, &sa, NULL);
669 
670 	sa.sa_handler = sigquit;
671 	sa.sa_flags = SA_RESTART;
672 	sigfillset(&sa.sa_mask);	/* block all sigs in these handlers */
673 	(void) sigaction(SIGHUP, &sa, NULL);
674 	(void) sigaction(SIGINT, &sa, NULL);
675 	(void) sigaction(SIGQUIT, &sa, NULL);
676 	(void) sigaction(SIGTERM, &sa, NULL);
677 	sa.sa_handler = lostconn;
678 	(void) sigaction(SIGPIPE, &sa, NULL);
679 	sa.sa_handler = toolong;
680 	(void) sigaction(SIGALRM, &sa, NULL);
681 	sa.sa_handler = sigurg;
682 	(void) sigaction(SIGURG, &sa, NULL);
683 
684 	/* Try to handle urgent data inline */
685 #ifdef SO_OOBINLINE
686 	if (setsockopt(0, SOL_SOCKET, SO_OOBINLINE, (char *)&on, sizeof(on)) < 0)
687 		syslog(LOG_WARNING, "setsockopt: %m");
688 #endif
689 	/* Set keepalives on the socket to detect dropped connections.  */
690 #ifdef SO_KEEPALIVE
691 	keepalive = 1;
692 	if (setsockopt(0, SOL_SOCKET, SO_KEEPALIVE, (char *)&keepalive,
693 	    sizeof(int)) < 0)
694 		syslog(LOG_WARNING, "setsockopt (SO_KEEPALIVE): %m");
695 #endif
696 
697 #ifdef	F_SETOWN
698 	if (fcntl(fileno(stdin), F_SETOWN, getpid()) == -1)
699 		syslog(LOG_WARNING, "fcntl F_SETOWN: %m");
700 #endif
701 	logremotehost(&his_addr);
702 	/*
703 	 * Set up default state
704 	 */
705 	data = -1;
706 	type = TYPE_A;
707 	form = FORM_N;
708 	stru = STRU_F;
709 	mode = MODE_S;
710 	tmpline[0] = '\0';
711 	hasyyerrored = 0;
712 
713 #ifdef KERBEROS5
714 	kerror = krb5_init_context(&kcontext);
715 	if (kerror) {
716 		syslog(LOG_ERR, "%s when initializing Kerberos context",
717 		    error_message(kerror));
718 		exit(0);
719 	}
720 #endif /* KERBEROS5 */
721 
722 	init_curclass();
723 	curclass.timeout = 300;		/* 5 minutes, as per login(1) */
724 	curclass.type = CLASS_REAL;
725 
726 	/* If logins are disabled, print out the message. */
727 	if (display_file(_PATH_NOLOGIN, 530)) {
728 		reply(530, "System not available.");
729 		exit(0);
730 	}
731 	(void)display_file(conffilename(_NAME_FTPWELCOME), 220);
732 		/* reply(220,) must follow */
733 	if (EMPTYSTR(version))
734 		reply(220, "%s FTP server ready.", hostname);
735 	else
736 		reply(220, "%s FTP server (%s) ready.", hostname, version);
737 
738 	if (xferlogname != NULL) {
739 		xferlogfd = open(xferlogname, O_WRONLY | O_APPEND | O_CREAT,
740 		    0660);
741 		if (xferlogfd == -1)
742 			syslog(LOG_WARNING, "open xferlog `%s': %m",
743 			    xferlogname);
744 		else
745 			doxferlog |= 2;
746 	}
747 
748 	ftp_loop();
749 	/* NOTREACHED */
750 }
751 
752 static void
753 lostconn(int signo)
754 {
755 
756 	if (debug)
757 		syslog(LOG_DEBUG, "lost connection");
758 	dologout(1);
759 }
760 
761 static void
762 toolong(int signo)
763 {
764 
765 		/* XXXSIGRACE */
766 	reply(421,
767 	    "Timeout (" LLF " seconds): closing control connection.",
768 	    (LLT)curclass.timeout);
769 	if (logging)
770 		syslog(LOG_INFO, "User %s timed out after " LLF " seconds",
771 		    (pw ? pw->pw_name : "unknown"), (LLT)curclass.timeout);
772 	dologout(1);
773 }
774 
775 static void
776 sigquit(int signo)
777 {
778 
779 	if (debug)
780 		syslog(LOG_DEBUG, "got signal %d", signo);
781 	dologout(1);
782 }
783 
784 static void
785 sigurg(int signo)
786 {
787 
788 	urgflag = 1;
789 }
790 
791 
792 /*
793  * Save the result of a getpwnam.  Used for USER command, since
794  * the data returned must not be clobbered by any other command
795  * (e.g., globbing).
796  */
797 static struct passwd *
798 sgetpwnam(const char *name)
799 {
800 	static struct passwd save;
801 	struct passwd *p;
802 
803 	if ((p = getpwnam(name)) == NULL)
804 		return (p);
805 	if (save.pw_name) {
806 		free((char *)save.pw_name);
807 		memset(save.pw_passwd, 0, strlen(save.pw_passwd));
808 		free((char *)save.pw_passwd);
809 		free((char *)save.pw_gecos);
810 		free((char *)save.pw_dir);
811 		free((char *)save.pw_shell);
812 	}
813 	save = *p;
814 	save.pw_name = xstrdup(p->pw_name);
815 	save.pw_passwd = xstrdup(p->pw_passwd);
816 	save.pw_gecos = xstrdup(p->pw_gecos);
817 	save.pw_dir = xstrdup(p->pw_dir);
818 	save.pw_shell = xstrdup(p->pw_shell);
819 	return (&save);
820 }
821 
822 static int	login_attempts;	/* number of failed login attempts */
823 static int	askpasswd;	/* had USER command, ask for PASSwd */
824 static int	permitted;	/* USER permitted */
825 
826 /*
827  * USER command.
828  * Sets global passwd pointer pw if named account exists and is acceptable;
829  * sets askpasswd if a PASS command is expected.  If logged in previously,
830  * need to reset state.  If name is "ftp" or "anonymous", the name is not in
831  * _NAME_FTPUSERS, and ftp account exists, set guest and pw, then just return.
832  * If account doesn't exist, ask for passwd anyway.  Otherwise, check user
833  * requesting login privileges.  Disallow anyone who does not have a standard
834  * shell as returned by getusershell().  Disallow anyone mentioned in the file
835  * _NAME_FTPUSERS to allow people such as root and uucp to be avoided.
836  */
837 void
838 user(const char *name)
839 {
840 	char	*class;
841 #ifdef	LOGIN_CAP
842 	login_cap_t *lc = NULL;
843 #endif
844 
845 	class = NULL;
846 	if (logged_in) {
847 		switch (curclass.type) {
848 		case CLASS_GUEST:
849 			reply(530, "Can't change user from guest login.");
850 			return;
851 		case CLASS_CHROOT:
852 			reply(530, "Can't change user from chroot user.");
853 			return;
854 		case CLASS_REAL:
855 			if (dropprivs) {
856 				reply(530, "Can't change user.");
857 				return;
858 			}
859 			end_login();
860 			break;
861 		default:
862 			abort();
863 		}
864 	}
865 
866 #if defined(KERBEROS)
867 	kdestroy();
868 #endif
869 #if defined(KERBEROS5)
870 	k5destroy();
871 #endif
872 
873 	curclass.type = CLASS_REAL;
874 	askpasswd = 0;
875 	permitted = 0;
876 
877 	if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) {
878 			/* need `pw' setup for checkaccess() and checkuser () */
879 		if ((pw = sgetpwnam("ftp")) == NULL)
880 			reply(530, "User %s unknown.", name);
881 		else if (! checkaccess("ftp") || ! checkaccess("anonymous"))
882 			reply(530, "User %s access denied.", name);
883 		else {
884 			curclass.type = CLASS_GUEST;
885 			askpasswd = 1;
886 			reply(331,
887 			    "Guest login ok, type your name as password.");
888 		}
889 		if (!askpasswd) {
890 			if (logging)
891 				syslog(LOG_NOTICE,
892 				    "ANONYMOUS FTP LOGIN REFUSED FROM %s",
893 				    remotehost);
894 			end_login();
895 			goto cleanup_user;
896 		}
897 		name = "ftp";
898 	} else
899 		pw = sgetpwnam(name);
900 
901 	strlcpy(curname, name, curname_len);
902 
903 			/* check user in /etc/ftpusers, and setup class */
904 	permitted = checkuser(_NAME_FTPUSERS, curname, 1, 0, &class);
905 
906 			/* check user in /etc/ftpchroot */
907 	lc = login_getpwclass(pw);
908 	if (checkuser(_NAME_FTPCHROOT, curname, 0, 0, NULL)
909 #ifdef	LOGIN_CAP	/* Allow login.conf configuration as well */
910 	    || login_getcapbool(lc, "ftp-chroot", 0)
911 #endif
912 	) {
913 		if (curclass.type == CLASS_GUEST) {
914 			syslog(LOG_NOTICE,
915 	    "Can't change guest user to chroot class; remove entry in %s",
916 			    _NAME_FTPCHROOT);
917 			exit(1);
918 		}
919 		curclass.type = CLASS_CHROOT;
920 	}
921 			/* determine default class */
922 	if (class == NULL) {
923 		switch (curclass.type) {
924 		case CLASS_GUEST:
925 			class = xstrdup("guest");
926 			break;
927 		case CLASS_CHROOT:
928 			class = xstrdup("chroot");
929 			break;
930 		case CLASS_REAL:
931 			class = xstrdup("real");
932 			break;
933 		default:
934 			syslog(LOG_ERR, "unknown curclass.type %d; aborting",
935 			    curclass.type);
936 			abort();
937 		}
938 	}
939 			/* parse ftpd.conf, setting up various parameters */
940 	parse_conf(class);
941 			/* if not guest user, check for valid shell */
942 	if (pw == NULL)
943 		permitted = 0;
944 	else {
945 		const char	*cp, *shell;
946 
947 		if ((shell = pw->pw_shell) == NULL || *shell == 0)
948 			shell = _PATH_BSHELL;
949 		while ((cp = getusershell()) != NULL)
950 			if (strcmp(cp, shell) == 0)
951 				break;
952 		endusershell();
953 		if (cp == NULL && curclass.type != CLASS_GUEST)
954 			permitted = 0;
955 	}
956 
957 			/* deny quickly (after USER not PASS) if requested */
958 	if (CURCLASS_FLAGS_ISSET(denyquick) && !permitted) {
959 		reply(530, "User %s may not use FTP.", curname);
960 		if (logging)
961 			syslog(LOG_NOTICE, "FTP LOGIN REFUSED FROM %s, %s",
962 			    remotehost, curname);
963 		end_login();
964 		goto cleanup_user;
965 	}
966 
967 			/* if haven't asked yet (i.e, not anon), ask now */
968 	if (!askpasswd) {
969 		askpasswd = 1;
970 #ifdef SKEY
971 		if (skey_haskey(curname) == 0) {
972 			const char *myskey;
973 
974 			myskey = skey_keyinfo(curname);
975 			reply(331, "Password [ %s ] required for %s.",
976 			    myskey ? myskey : "error getting challenge",
977 			    curname);
978 		} else
979 #endif
980 			reply(331, "Password required for %s.", curname);
981 	}
982 
983  cleanup_user:
984 #ifdef LOGIN_CAP
985 	login_close(lc);
986 #endif
987 	/*
988 	 * Delay before reading passwd after first failed
989 	 * attempt to slow down passwd-guessing programs.
990 	 */
991 	if (login_attempts)
992 		sleep((unsigned) login_attempts);
993 
994 	if (class)
995 		free(class);
996 }
997 
998 /*
999  * Determine whether something is to happen (allow access, chroot)
1000  * for a user. Each line is a shell-style glob followed by
1001  * `yes' or `no'.
1002  *
1003  * For backward compatibility, `allow' and `deny' are synonymns
1004  * for `yes' and `no', respectively.
1005  *
1006  * Each glob is matched against the username in turn, and the first
1007  * match found is used. If no match is found, the result is the
1008  * argument `def'. If a match is found but without and explicit
1009  * `yes'/`no', the result is the opposite of def.
1010  *
1011  * If the file doesn't exist at all, the result is the argument
1012  * `nofile'
1013  *
1014  * Any line starting with `#' is considered a comment and ignored.
1015  *
1016  * Returns 0 if the user is denied, or 1 if they are allowed.
1017  *
1018  * NOTE: needs struct passwd *pw setup before use.
1019  */
1020 static int
1021 checkuser(const char *fname, const char *name, int def, int nofile,
1022 	    char **retclass)
1023 {
1024 	FILE	*fd;
1025 	int	 retval;
1026 	char	*word, *perm, *class, *buf, *p;
1027 	size_t	 len, line;
1028 
1029 	retval = def;
1030 	if (retclass != NULL)
1031 		*retclass = NULL;
1032 	if ((fd = fopen(conffilename(fname), "r")) == NULL)
1033 		return nofile;
1034 
1035 	line = 0;
1036 	for (;
1037 	    (buf = fparseln(fd, &len, &line, NULL, FPARSELN_UNESCCOMM |
1038 			    FPARSELN_UNESCCONT | FPARSELN_UNESCESC)) != NULL;
1039 	    free(buf), buf = NULL) {
1040 		word = perm = class = NULL;
1041 		p = buf;
1042 		if (len < 1)
1043 			continue;
1044 		if (p[len - 1] == '\n')
1045 			p[--len] = '\0';
1046 		if (EMPTYSTR(p))
1047 			continue;
1048 
1049 		NEXTWORD(p, word);
1050 		NEXTWORD(p, perm);
1051 		NEXTWORD(p, class);
1052 		if (EMPTYSTR(word))
1053 			continue;
1054 		if (!EMPTYSTR(class)) {
1055 			if (strcasecmp(class, "all") == 0 ||
1056 			    strcasecmp(class, "none") == 0) {
1057 				syslog(LOG_WARNING,
1058 		"%s line %d: illegal user-defined class `%s' - skipping entry",
1059 					    fname, (int)line, class);
1060 				continue;
1061 			}
1062 		}
1063 
1064 					/* have a host specifier */
1065 		if ((p = strchr(word, '@')) != NULL) {
1066 			unsigned long	net, mask, addr;
1067 			int		bits;
1068 
1069 			*p++ = '\0';
1070 					/* check against network or CIDR */
1071 			if (isdigit((unsigned char)*p) &&
1072 			    (bits = inet_net_pton(AF_INET, p,
1073 			    &net, sizeof(net))) != -1) {
1074 				net = ntohl(net);
1075 				mask = 0xffffffffU << (32 - bits);
1076 				addr = ntohl(his_addr.su_addr.s_addr);
1077 				if ((addr & mask) != net)
1078 					continue;
1079 
1080 					/* check against hostname glob */
1081 			} else if (fnmatch(p, remotehost, FNM_CASEFOLD) != 0)
1082 				continue;
1083 		}
1084 
1085 					/* have a group specifier */
1086 		if ((p = strchr(word, ':')) != NULL) {
1087 			gid_t	*groups, *ng;
1088 			int	 gsize, i, found;
1089 
1090 			if (pw == NULL)
1091 				continue;	/* no match for unknown user */
1092 			*p++ = '\0';
1093 			groups = NULL;
1094 			gsize = 16;
1095 			do {
1096 				ng = realloc(groups, gsize * sizeof(gid_t));
1097 				if (ng == NULL)
1098 					fatal(
1099 					    "Local resource failure: realloc");
1100 				groups = ng;
1101 			} while (getgrouplist(pw->pw_name, pw->pw_gid,
1102 						groups, &gsize) == -1);
1103 			found = 0;
1104 			for (i = 0; i < gsize; i++) {
1105 				struct group *g;
1106 
1107 				if ((g = getgrgid(groups[i])) == NULL)
1108 					continue;
1109 				if (fnmatch(p, g->gr_name, 0) == 0) {
1110 					found = 1;
1111 					break;
1112 				}
1113 			}
1114 			free(groups);
1115 			if (!found)
1116 				continue;
1117 		}
1118 
1119 					/* check against username glob */
1120 		if (fnmatch(word, name, 0) != 0)
1121 			continue;
1122 
1123 		if (perm != NULL &&
1124 		    ((strcasecmp(perm, "allow") == 0) ||
1125 		     (strcasecmp(perm, "yes") == 0)))
1126 			retval = 1;
1127 		else if (perm != NULL &&
1128 		    ((strcasecmp(perm, "deny") == 0) ||
1129 		     (strcasecmp(perm, "no") == 0)))
1130 			retval = 0;
1131 		else
1132 			retval = !def;
1133 		if (!EMPTYSTR(class) && retclass != NULL)
1134 			*retclass = xstrdup(class);
1135 		free(buf);
1136 		break;
1137 	}
1138 	(void) fclose(fd);
1139 	return (retval);
1140 }
1141 
1142 /*
1143  * Check if user is allowed by /etc/ftpusers
1144  * returns 1 for yes, 0 for no
1145  *
1146  * NOTE: needs struct passwd *pw setup (for checkuser())
1147  */
1148 static int
1149 checkaccess(const char *name)
1150 {
1151 
1152 	return (checkuser(_NAME_FTPUSERS, name, 1, 0, NULL));
1153 }
1154 
1155 static void
1156 login_utmp(const char *line, const char *name, const char *host,
1157     struct sockinet *haddr)
1158 {
1159 #if defined(SUPPORT_UTMPX) || defined(SUPPORT_UTMP)
1160 	struct timeval tv;
1161 	(void)gettimeofday(&tv, NULL);
1162 #endif
1163 #ifdef SUPPORT_UTMPX
1164 	if (doutmp) {
1165 		(void)memset(&utmpx, 0, sizeof(utmpx));
1166 		utmpx.ut_tv = tv;
1167 		utmpx.ut_pid = getpid();
1168 		utmpx.ut_id[0] = 'f';
1169 		utmpx.ut_id[1] = 't';
1170 		utmpx.ut_id[2] = 'p';
1171 		utmpx.ut_id[3] = '*';
1172 		utmpx.ut_type = USER_PROCESS;
1173 		(void)strncpy(utmpx.ut_name, name, sizeof(utmpx.ut_name));
1174 		(void)strncpy(utmpx.ut_line, line, sizeof(utmpx.ut_line));
1175 		(void)strncpy(utmpx.ut_host, host, sizeof(utmpx.ut_host));
1176 		(void)memcpy(&utmpx.ut_ss, &haddr->si_su, haddr->su_len);
1177 		ftpd_loginx(&utmpx);
1178 	}
1179 	if (dowtmp)
1180 		ftpd_logwtmpx(line, name, host, haddr, 0, USER_PROCESS);
1181 #endif
1182 #ifdef SUPPORT_UTMP
1183 	if (doutmp) {
1184 		(void)memset(&utmp, 0, sizeof(utmp));
1185 		(void)time(&utmp.ut_time);
1186 		(void)strncpy(utmp.ut_name, name, sizeof(utmp.ut_name));
1187 		(void)strncpy(utmp.ut_line, line, sizeof(utmp.ut_line));
1188 		(void)strncpy(utmp.ut_host, host, sizeof(utmp.ut_host));
1189 		ftpd_login(&utmp);
1190 	}
1191 	if (dowtmp)
1192 		ftpd_logwtmp(line, name, host);
1193 #endif
1194 }
1195 
1196 static void
1197 logout_utmp(void)
1198 {
1199 #ifdef SUPPORT_UTMPX
1200 	int okwtmpx = dowtmp;
1201 #endif
1202 #ifdef SUPPORT_UTMP
1203 	int okwtmp = dowtmp;
1204 #endif
1205 	if (logged_in) {
1206 #ifdef SUPPORT_UTMPX
1207 		if (doutmp)
1208 			okwtmpx &= ftpd_logoutx(ttyline, 0, DEAD_PROCESS);
1209 		if (okwtmpx)
1210 			ftpd_logwtmpx(ttyline, "", "", NULL, 0, DEAD_PROCESS);
1211 #endif
1212 #ifdef SUPPORT_UTMP
1213 		if (doutmp)
1214 			okwtmp &= ftpd_logout(ttyline);
1215 		if (okwtmp)
1216 			ftpd_logwtmp(ttyline, "", "");
1217 #endif
1218 	}
1219 }
1220 
1221 /*
1222  * Terminate login as previous user (if any), resetting state;
1223  * used when USER command is given or login fails.
1224  */
1225 static void
1226 end_login(void)
1227 {
1228 #ifdef USE_PAM
1229 	int e;
1230 #endif
1231 	logout_utmp();
1232 	show_chdir_messages(-1);		/* flush chdir cache */
1233 	if (pw != NULL && pw->pw_passwd != NULL)
1234 		memset(pw->pw_passwd, 0, strlen(pw->pw_passwd));
1235 	pw = NULL;
1236 	logged_in = 0;
1237 	askpasswd = 0;
1238 	permitted = 0;
1239 	quietmessages = 0;
1240 	gidcount = 0;
1241 	curclass.type = CLASS_REAL;
1242 	(void) seteuid((uid_t)0);
1243 #ifdef	LOGIN_CAP
1244 	setusercontext(NULL, getpwuid(0), 0,
1245 		       LOGIN_SETPRIORITY|LOGIN_SETRESOURCES|LOGIN_SETUMASK);
1246 #endif
1247 #ifdef USE_PAM
1248 	if (pamh) {
1249 		if ((e = pam_setcred(pamh, PAM_DELETE_CRED)) != PAM_SUCCESS)
1250 			syslog(LOG_ERR, "pam_setcred: %s",
1251 			    pam_strerror(pamh, e));
1252 		if ((e = pam_close_session(pamh,0)) != PAM_SUCCESS)
1253 			syslog(LOG_ERR, "pam_close_session: %s",
1254 			    pam_strerror(pamh, e));
1255 		if ((e = pam_end(pamh, e)) != PAM_SUCCESS)
1256 			syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1257 		pamh = NULL;
1258 	}
1259 #endif
1260 }
1261 
1262 void
1263 pass(const char *passwd)
1264 {
1265 	int		 rval;
1266 	char		 root[MAXPATHLEN];
1267 #ifdef	LOGIN_CAP
1268 	login_cap_t *lc = NULL;
1269 #endif
1270 #ifdef USE_PAM
1271 	int e;
1272 #endif
1273 	if (logged_in || askpasswd == 0) {
1274 		reply(503, "Login with USER first.");
1275 		return;
1276 	}
1277 	askpasswd = 0;
1278 	if (curclass.type != CLASS_GUEST) {
1279 			/* "ftp" is the only account allowed with no password */
1280 		if (pw == NULL) {
1281 			rval = 1;	/* failure below */
1282 			goto skip;
1283 		}
1284 #ifdef USE_PAM
1285 		rval = auth_pam(&pw, passwd);
1286 #ifdef notdef
1287 		/* If PAM fails, we proceed with other authentications */
1288 		if (rval >= 0) {
1289 			goto skip;
1290 		}
1291 #else
1292 		/* If PAM fails, that's it */
1293 		goto skip;
1294 #endif
1295 #endif
1296 #if defined(KERBEROS)
1297 		if (klogin(pw, "", hostname, (char *)passwd) == 0) {
1298 			rval = 0;
1299 			goto skip;
1300 		}
1301 #endif
1302 #if defined(KERBEROS5)
1303 		if (k5login(pw, "", hostname, (char *)passwd) == 0) {
1304 			rval = 0;
1305 			goto skip;
1306 		}
1307 #endif
1308 #ifdef SKEY
1309 		if (skey_haskey(pw->pw_name) == 0) {
1310 			char *p;
1311 			int r;
1312 
1313 			p = xstrdup(passwd);
1314 			r = skey_passcheck(pw->pw_name, p);
1315 			free(p);
1316 			if (r != -1) {
1317 				rval = 0;
1318 				goto skip;
1319 			}
1320 		}
1321 #endif
1322 		if (!sflag)
1323 			rval = checkpassword(pw, passwd);
1324 		else
1325 			rval = 1;
1326 
1327  skip:
1328 
1329 			/*
1330 			 * If rval > 0, the user failed the authentication check
1331 			 * above.  If rval == 0, either Kerberos or local
1332 			 * authentication succeeded.
1333 			 */
1334 		if (rval) {
1335 			reply(530, "%s", rval == 2 ? "Password expired." :
1336 			    "Login incorrect.");
1337 			if (logging) {
1338 				syslog(LOG_NOTICE,
1339 				    "FTP LOGIN FAILED FROM %s", remotehost);
1340 				syslog(LOG_AUTHPRIV | LOG_NOTICE,
1341 				    "FTP LOGIN FAILED FROM %s, %s",
1342 				    remotehost, curname);
1343 			}
1344 			pw = NULL;
1345 			if (login_attempts++ >= 5) {
1346 				syslog(LOG_NOTICE,
1347 				    "repeated login failures from %s",
1348 				    remotehost);
1349 				exit(0);
1350 			}
1351 			return;
1352 		}
1353 	}
1354 
1355 			/* password ok; check if anything else prevents login */
1356 	if (! permitted) {
1357 		reply(530, "User %s may not use FTP.", pw->pw_name);
1358 		if (logging)
1359 			syslog(LOG_NOTICE, "FTP LOGIN REFUSED FROM %s, %s",
1360 			    remotehost, pw->pw_name);
1361 		goto bad;
1362 	}
1363 
1364 	login_attempts = 0;		/* this time successful */
1365 	if (setegid((gid_t)pw->pw_gid) < 0) {
1366 		reply(550, "Can't set gid.");
1367 		goto bad;
1368 	}
1369 #ifdef	LOGIN_CAP
1370 	if ((lc = login_getpwclass(pw)) != NULL) {
1371 #ifdef notyet
1372 		char	remote_ip[NI_MAXHOST];
1373 
1374 		if (getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
1375 			remote_ip, sizeof(remote_ip) - 1, NULL, 0,
1376 			NI_NUMERICHOST))
1377 				*remote_ip = 0;
1378 		remote_ip[sizeof(remote_ip) - 1] = 0;
1379 		if (!auth_hostok(lc, remotehost, remote_ip)) {
1380 			syslog(LOG_INFO|LOG_AUTH,
1381 			    "FTP LOGIN FAILED (HOST) as %s: permission denied.",
1382 			    pw->pw_name);
1383 			reply(530, "Permission denied.");
1384 			pw = NULL;
1385 			return;
1386 		}
1387 		if (!auth_timeok(lc, time(NULL))) {
1388 			reply(530, "Login not available right now.");
1389 			pw = NULL;
1390 			return;
1391 		}
1392 #endif
1393 	}
1394 	setsid();
1395 	setusercontext(lc, pw, 0,
1396 		LOGIN_SETLOGIN|LOGIN_SETGROUP|LOGIN_SETPRIORITY|
1397 		LOGIN_SETRESOURCES|LOGIN_SETUMASK);
1398 #else
1399 	(void) initgroups(pw->pw_name, pw->pw_gid);
1400 			/* cache groups for cmds.c::matchgroup() */
1401 #endif
1402 #ifdef USE_PAM
1403 	if (pamh) {
1404 		if ((e = pam_open_session(pamh, 0)) != PAM_SUCCESS) {
1405 			syslog(LOG_ERR, "pam_open_session: %s",
1406 			    pam_strerror(pamh, e));
1407 		} else if ((e = pam_setcred(pamh, PAM_ESTABLISH_CRED))
1408 		    != PAM_SUCCESS) {
1409 			syslog(LOG_ERR, "pam_setcred: %s",
1410 			    pam_strerror(pamh, e));
1411 		}
1412 	}
1413 #endif
1414 	gidcount = getgroups(0, NULL);
1415 	if (gidlist)
1416 		free(gidlist);
1417 	gidlist = malloc(gidcount * sizeof *gidlist);
1418 	gidcount = getgroups(gidcount, gidlist);
1419 
1420 	/* open utmp/wtmp before chroot */
1421 	login_utmp(ttyline, pw->pw_name, remotehost, &his_addr);
1422 
1423 	logged_in = 1;
1424 
1425 	connections = 1;
1426 	if (dopidfile)
1427 		count_users();
1428 	if (curclass.limit != -1 && connections > curclass.limit) {
1429 		if (! EMPTYSTR(curclass.limitfile))
1430 			(void)display_file(conffilename(curclass.limitfile),
1431 			    530);
1432 		reply(530,
1433 		    "User %s access denied, connection limit of " LLF
1434 		    " reached.",
1435 		    pw->pw_name, (LLT)curclass.limit);
1436 		syslog(LOG_NOTICE,
1437 		    "Maximum connection limit of " LLF
1438 		    " for class %s reached, login refused for %s",
1439 		    (LLT)curclass.limit, curclass.classname, pw->pw_name);
1440 		goto bad;
1441 	}
1442 
1443 	homedir[0] = '/';
1444 	switch (curclass.type) {
1445 	case CLASS_GUEST:
1446 			/*
1447 			 * We MUST do a chdir() after the chroot. Otherwise
1448 			 * the old current directory will be accessible as "."
1449 			 * outside the new root!
1450 			 */
1451 		format_path(root,
1452 		    curclass.chroot ? curclass.chroot :
1453 		    anondir ? anondir :
1454 		    pw->pw_dir);
1455 		format_path(homedir,
1456 		    curclass.homedir ? curclass.homedir :
1457 		    "/");
1458 		if (EMPTYSTR(homedir))
1459 			homedir[0] = '/';
1460 		if (EMPTYSTR(root) || chroot(root) < 0) {
1461 			syslog(LOG_NOTICE,
1462 			    "GUEST user %s: can't chroot to %s: %m",
1463 			    pw->pw_name, root);
1464 			goto bad_guest;
1465 		}
1466 		if (chdir(homedir) < 0) {
1467 			syslog(LOG_NOTICE,
1468 			    "GUEST user %s: can't chdir to %s: %m",
1469 			    pw->pw_name, homedir);
1470  bad_guest:
1471 			reply(550, "Can't set guest privileges.");
1472 			goto bad;
1473 		}
1474 		break;
1475 	case CLASS_CHROOT:
1476 		format_path(root,
1477 		    curclass.chroot ? curclass.chroot :
1478 		    pw->pw_dir);
1479 		format_path(homedir,
1480 		    curclass.homedir ? curclass.homedir :
1481 		    "/");
1482 		if (EMPTYSTR(homedir))
1483 			homedir[0] = '/';
1484 		if (EMPTYSTR(root) || chroot(root) < 0) {
1485 			syslog(LOG_NOTICE,
1486 			    "CHROOT user %s: can't chroot to %s: %m",
1487 			    pw->pw_name, root);
1488 			goto bad_chroot;
1489 		}
1490 		if (chdir(homedir) < 0) {
1491 			syslog(LOG_NOTICE,
1492 			    "CHROOT user %s: can't chdir to %s: %m",
1493 			    pw->pw_name, homedir);
1494  bad_chroot:
1495 			reply(550, "Can't change root.");
1496 			goto bad;
1497 		}
1498 		break;
1499 	case CLASS_REAL:
1500 			/* only chroot REAL if explictly requested */
1501 		if (! EMPTYSTR(curclass.chroot)) {
1502 			format_path(root, curclass.chroot);
1503 			if (EMPTYSTR(root) || chroot(root) < 0) {
1504 				syslog(LOG_NOTICE,
1505 				    "REAL user %s: can't chroot to %s: %m",
1506 				    pw->pw_name, root);
1507 				goto bad_chroot;
1508 			}
1509 		}
1510 		format_path(homedir,
1511 		    curclass.homedir ? curclass.homedir :
1512 		    pw->pw_dir);
1513 		if (EMPTYSTR(homedir) || chdir(homedir) < 0) {
1514 			if (chdir("/") < 0) {
1515 				syslog(LOG_NOTICE,
1516 				    "REAL user %s: can't chdir to %s: %m",
1517 				    pw->pw_name,
1518 				    !EMPTYSTR(homedir) ?  homedir : "/");
1519 				reply(530,
1520 				    "User %s: can't change directory to %s.",
1521 				    pw->pw_name,
1522 				    !EMPTYSTR(homedir) ? homedir : "/");
1523 				goto bad;
1524 			} else {
1525 				reply(-230,
1526 				    "No directory! Logging in with home=/");
1527 				homedir[0] = '/';
1528 			}
1529 		}
1530 		break;
1531 	}
1532 #ifndef LOGIN_CAP
1533 	setsid();
1534 	setlogin(pw->pw_name);
1535 #endif
1536 	if (dropprivs ||
1537 	    (curclass.type != CLASS_REAL &&
1538 	    ntohs(ctrl_addr.su_port) > IPPORT_RESERVED + 1)) {
1539 		dropprivs++;
1540 		if (setgid((gid_t)pw->pw_gid) < 0) {
1541 			reply(550, "Can't set gid.");
1542 			goto bad;
1543 		}
1544 		if (setuid((uid_t)pw->pw_uid) < 0) {
1545 			reply(550, "Can't set uid.");
1546 			goto bad;
1547 		}
1548 	} else {
1549 		if (seteuid((uid_t)pw->pw_uid) < 0) {
1550 			reply(550, "Can't set uid.");
1551 			goto bad;
1552 		}
1553 	}
1554 	setenv("HOME", homedir, 1);
1555 
1556 	if (curclass.type == CLASS_GUEST && passwd[0] == '-')
1557 		quietmessages = 1;
1558 
1559 			/*
1560 			 * Display a login message, if it exists.
1561 			 * N.B. reply(230,) must follow the message.
1562 			 */
1563 	if (! EMPTYSTR(curclass.motd))
1564 		(void)display_file(conffilename(curclass.motd), 230);
1565 	show_chdir_messages(230);
1566 	if (curclass.type == CLASS_GUEST) {
1567 		char *p;
1568 
1569 		reply(230, "Guest login ok, access restrictions apply.");
1570 #if HAVE_SETPROCTITLE
1571 		snprintf(proctitle, sizeof(proctitle),
1572 		    "%s: anonymous/%s", remotehost, passwd);
1573 		setproctitle("%s", proctitle);
1574 #endif /* HAVE_SETPROCTITLE */
1575 		if (logging)
1576 			syslog(LOG_INFO,
1577 			"ANONYMOUS FTP LOGIN FROM %s, %s (class: %s, type: %s)",
1578 			    remotehost, passwd,
1579 			    curclass.classname, CURCLASSTYPE);
1580 			/* store guest password reply into pw_passwd */
1581 		REASSIGN(pw->pw_passwd, xstrdup(passwd));
1582 		for (p = pw->pw_passwd; *p; p++)
1583 			if (!isgraph((unsigned char)*p))
1584 				*p = '_';
1585 	} else {
1586 		reply(230, "User %s logged in.", pw->pw_name);
1587 #if HAVE_SETPROCTITLE
1588 		snprintf(proctitle, sizeof(proctitle),
1589 		    "%s: %s", remotehost, pw->pw_name);
1590 		setproctitle("%s", proctitle);
1591 #endif /* HAVE_SETPROCTITLE */
1592 		if (logging)
1593 			syslog(LOG_INFO,
1594 			    "FTP LOGIN FROM %s as %s (class: %s, type: %s)",
1595 			    remotehost, pw->pw_name,
1596 			    curclass.classname, CURCLASSTYPE);
1597 	}
1598 	(void) umask(curclass.umask);
1599 #ifdef	LOGIN_CAP
1600 	login_close(lc);
1601 #endif
1602 	return;
1603 
1604  bad:
1605 #ifdef	LOGIN_CAP
1606 	login_close(lc);
1607 #endif
1608 			/* Forget all about it... */
1609 	end_login();
1610 }
1611 
1612 void
1613 retrieve(char *argv[], const char *name)
1614 {
1615 	FILE *fin, *dout;
1616 	struct stat st;
1617 	int (*closefunc)(FILE *) = NULL;
1618 	int dolog, sendrv, closerv, stderrfd, isconversion, isdata, isls;
1619 	struct timeval start, finish, td, *tdp;
1620 	struct rusage rusage_before, rusage_after;
1621 	const char *dispname;
1622 	char *error;
1623 
1624 	sendrv = closerv = stderrfd = -1;
1625 	isconversion = isdata = isls = dolog = 0;
1626 	tdp = NULL;
1627 	dispname = name;
1628 	fin = dout = NULL;
1629 	error = NULL;
1630 	if (argv == NULL) {		/* if not running a command ... */
1631 		dolog = 1;
1632 		isdata = 1;
1633 		fin = fopen(name, "r");
1634 		closefunc = fclose;
1635 		if (fin == NULL)	/* doesn't exist?; try a conversion */
1636 			argv = do_conversion(name);
1637 		if (argv != NULL) {
1638 			isconversion++;
1639 			syslog(LOG_DEBUG, "get command: '%s' on '%s'",
1640 			    argv[0], name);
1641 		}
1642 	}
1643 	if (argv != NULL) {
1644 		char temp[MAXPATHLEN];
1645 
1646 		if (strcmp(argv[0], INTERNAL_LS) == 0) {
1647 			isls = 1;
1648 			stderrfd = -1;
1649 		} else {
1650 			(void)snprintf(temp, sizeof(temp), "%s", TMPFILE);
1651 			stderrfd = mkstemp(temp);
1652 			if (stderrfd != -1)
1653 				(void)unlink(temp);
1654 		}
1655 		dispname = argv[0];
1656 		fin = ftpd_popen(argv, "r", stderrfd);
1657 		closefunc = ftpd_pclose;
1658 		st.st_size = -1;
1659 		st.st_blksize = BUFSIZ;
1660 	}
1661 	if (fin == NULL) {
1662 		if (errno != 0) {
1663 			perror_reply(550, dispname);
1664 			if (dolog)
1665 				logxfer("get", -1, name, NULL, NULL,
1666 				    strerror(errno));
1667 		}
1668 		goto cleanupretrieve;
1669 	}
1670 	byte_count = -1;
1671 	if (argv == NULL
1672 	    && (fstat(fileno(fin), &st) < 0 || !S_ISREG(st.st_mode))) {
1673 		error = "Not a plain file";
1674 		reply(550, "%s: %s.", dispname, error);
1675 		goto done;
1676 	}
1677 	if (restart_point) {
1678 		if (type == TYPE_A) {
1679 			off_t i;
1680 			int c;
1681 
1682 			for (i = 0; i < restart_point; i++) {
1683 				if ((c=getc(fin)) == EOF) {
1684 					error = strerror(errno);
1685 					perror_reply(550, dispname);
1686 					goto done;
1687 				}
1688 				if (c == '\n')
1689 					i++;
1690 			}
1691 		} else if (lseek(fileno(fin), restart_point, SEEK_SET) < 0) {
1692 			error = strerror(errno);
1693 			perror_reply(550, dispname);
1694 			goto done;
1695 		}
1696 	}
1697 	dout = dataconn(dispname, st.st_size, "w");
1698 	if (dout == NULL)
1699 		goto done;
1700 
1701 	(void)getrusage(RUSAGE_SELF, &rusage_before);
1702 	(void)gettimeofday(&start, NULL);
1703 	sendrv = send_data(fin, dout, &st, isdata);
1704 	(void)gettimeofday(&finish, NULL);
1705 	(void)getrusage(RUSAGE_SELF, &rusage_after);
1706 	closedataconn(dout);		/* close now to affect timing stats */
1707 	timersub(&finish, &start, &td);
1708 	tdp = &td;
1709  done:
1710 	if (dolog) {
1711 		logxfer("get", byte_count, name, NULL, tdp, error);
1712 		if (tdp != NULL)
1713 			logrusage(&rusage_before, &rusage_after);
1714 	}
1715 	closerv = (*closefunc)(fin);
1716 	if (sendrv == 0) {
1717 		FILE *errf;
1718 		struct stat sb;
1719 
1720 		if (!isls && argv != NULL && closerv != 0) {
1721 			reply(-226,
1722 			    "Command returned an exit status of %d",
1723 			    closerv);
1724 			if (isconversion)
1725 				syslog(LOG_WARNING,
1726 				    "retrieve command: '%s' returned %d",
1727 				    argv[0], closerv);
1728 		}
1729 		if (!isls && argv != NULL && stderrfd != -1 &&
1730 		    (fstat(stderrfd, &sb) == 0) && sb.st_size > 0 &&
1731 		    ((errf = fdopen(stderrfd, "r")) != NULL)) {
1732 			char *cp, line[LINE_MAX];
1733 
1734 			reply(-226, "Command error messages:");
1735 			rewind(errf);
1736 			while (fgets(line, sizeof(line), errf) != NULL) {
1737 				if ((cp = strchr(line, '\n')) != NULL)
1738 					*cp = '\0';
1739 				reply(0, "  %s", line);
1740 			}
1741 			(void) fflush(stdout);
1742 			(void) fclose(errf);
1743 				/* a reply(226,) must follow */
1744 		}
1745 		reply(226, "Transfer complete.");
1746 	}
1747  cleanupretrieve:
1748 	if (stderrfd != -1)
1749 		(void)close(stderrfd);
1750 	if (isconversion)
1751 		free(argv);
1752 }
1753 
1754 void
1755 store(const char *name, const char *fmode, int unique)
1756 {
1757 	FILE *fout, *din;
1758 	struct stat st;
1759 	int (*closefunc)(FILE *);
1760 	struct timeval start, finish, td, *tdp;
1761 	char *desc, *error;
1762 
1763 	din = NULL;
1764 	desc = (*fmode == 'w') ? "put" : "append";
1765 	error = NULL;
1766 	if (unique && stat(name, &st) == 0 &&
1767 	    (name = gunique(name)) == NULL) {
1768 		logxfer(desc, -1, name, NULL, NULL,
1769 		    "cannot create unique file");
1770 		goto cleanupstore;
1771 	}
1772 
1773 	if (restart_point)
1774 		fmode = "r+";
1775 	fout = fopen(name, fmode);
1776 	closefunc = fclose;
1777 	tdp = NULL;
1778 	if (fout == NULL) {
1779 		perror_reply(553, name);
1780 		logxfer(desc, -1, name, NULL, NULL, strerror(errno));
1781 		goto cleanupstore;
1782 	}
1783 	byte_count = -1;
1784 	if (restart_point) {
1785 		if (type == TYPE_A) {
1786 			off_t i;
1787 			int c;
1788 
1789 			for (i = 0; i < restart_point; i++) {
1790 				if ((c=getc(fout)) == EOF) {
1791 					error = strerror(errno);
1792 					perror_reply(550, name);
1793 					goto done;
1794 				}
1795 				if (c == '\n')
1796 					i++;
1797 			}
1798 			/*
1799 			 * We must do this seek to "current" position
1800 			 * because we are changing from reading to
1801 			 * writing.
1802 			 */
1803 			if (fseek(fout, 0L, SEEK_CUR) < 0) {
1804 				error = strerror(errno);
1805 				perror_reply(550, name);
1806 				goto done;
1807 			}
1808 		} else if (lseek(fileno(fout), restart_point, SEEK_SET) < 0) {
1809 			error = strerror(errno);
1810 			perror_reply(550, name);
1811 			goto done;
1812 		}
1813 	}
1814 	din = dataconn(name, (off_t)-1, "r");
1815 	if (din == NULL)
1816 		goto done;
1817 	(void)gettimeofday(&start, NULL);
1818 	if (receive_data(din, fout) == 0) {
1819 		if (unique)
1820 			reply(226, "Transfer complete (unique file name:%s).",
1821 			    name);
1822 		else
1823 			reply(226, "Transfer complete.");
1824 	}
1825 	(void)gettimeofday(&finish, NULL);
1826 	closedataconn(din);		/* close now to affect timing stats */
1827 	timersub(&finish, &start, &td);
1828 	tdp = &td;
1829  done:
1830 	logxfer(desc, byte_count, name, NULL, tdp, error);
1831 	(*closefunc)(fout);
1832  cleanupstore:
1833 	;
1834 }
1835 
1836 static FILE *
1837 getdatasock(const char *fmode)
1838 {
1839 	int		on, s, t, tries;
1840 	in_port_t	port;
1841 
1842 	on = 1;
1843 	if (data >= 0)
1844 		return (fdopen(data, fmode));
1845 	if (! dropprivs)
1846 		(void) seteuid((uid_t)0);
1847 	s = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
1848 	if (s < 0)
1849 		goto bad;
1850 	if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
1851 	    (char *) &on, sizeof(on)) < 0)
1852 		goto bad;
1853 	if (setsockopt(s, SOL_SOCKET, SO_KEEPALIVE,
1854 	    (char *) &on, sizeof(on)) < 0)
1855 		goto bad;
1856 			/* anchor socket to avoid multi-homing problems */
1857 	data_source = ctrl_addr;
1858 			/*
1859 			 * By default source port for PORT connctions is
1860 			 * ctrlport-1 (see RFC959 section 5.2).
1861 			 * However, if privs have been dropped and that
1862 			 * would be < IPPORT_RESERVED, use a random port
1863 			 * instead.
1864 			 */
1865 	if (dataport)
1866 		port = dataport;
1867 	else
1868 		port = ntohs(ctrl_addr.su_port) - 1;
1869 	if (dropprivs && port < IPPORT_RESERVED)
1870 		port = 0;		/* use random port */
1871 	data_source.su_port = htons(port);
1872 
1873 	for (tries = 1; ; tries++) {
1874 		if (bind(s, (struct sockaddr *)&data_source.si_su,
1875 		    data_source.su_len) >= 0)
1876 			break;
1877 		if (errno != EADDRINUSE || tries > 10)
1878 			goto bad;
1879 		sleep(tries);
1880 	}
1881 	if (! dropprivs)
1882 		(void) seteuid((uid_t)pw->pw_uid);
1883 #ifdef IP_TOS
1884 	if (!mapped && ctrl_addr.su_family == AF_INET) {
1885 		on = IPTOS_THROUGHPUT;
1886 		if (setsockopt(s, IPPROTO_IP, IP_TOS, (char *)&on,
1887 			       sizeof(int)) < 0)
1888 			syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
1889 	}
1890 #endif
1891 	return (fdopen(s, fmode));
1892  bad:
1893 		/* Return the real value of errno (close may change it) */
1894 	t = errno;
1895 	if (! dropprivs)
1896 		(void) seteuid((uid_t)pw->pw_uid);
1897 	(void) close(s);
1898 	errno = t;
1899 	return (NULL);
1900 }
1901 
1902 FILE *
1903 dataconn(const char *name, off_t size, const char *fmode)
1904 {
1905 	char sizebuf[32];
1906 	FILE *file;
1907 	int retry, tos, keepalive, conerrno;
1908 
1909 	file_size = size;
1910 	byte_count = 0;
1911 	if (size != (off_t) -1)
1912 		(void)snprintf(sizebuf, sizeof(sizebuf), " (" LLF " byte%s)",
1913 		    (LLT)size, PLURAL(size));
1914 	else
1915 		sizebuf[0] = '\0';
1916 	if (pdata >= 0) {
1917 		struct sockinet from;
1918 		int s, fromlen = sizeof(from.su_len);
1919 
1920 		(void) alarm(curclass.timeout);
1921 		s = accept(pdata, (struct sockaddr *)&from.si_su, &fromlen);
1922 		(void) alarm(0);
1923 		if (s < 0) {
1924 			reply(425, "Can't open data connection.");
1925 			(void) close(pdata);
1926 			pdata = -1;
1927 			return (NULL);
1928 		}
1929 		(void) close(pdata);
1930 		pdata = s;
1931 		switch (from.su_family) {
1932 		case AF_INET:
1933 #ifdef IP_TOS
1934 			if (!mapped) {
1935 				tos = IPTOS_THROUGHPUT;
1936 				(void) setsockopt(s, IPPROTO_IP, IP_TOS,
1937 				    (char *)&tos, sizeof(int));
1938 			}
1939 			break;
1940 #endif
1941 		}
1942 		/* Set keepalives on the socket to detect dropped conns. */
1943 #ifdef SO_KEEPALIVE
1944 		keepalive = 1;
1945 		(void) setsockopt(s, SOL_SOCKET, SO_KEEPALIVE,
1946 		    (char *)&keepalive, sizeof(int));
1947 #endif
1948 		reply(150, "Opening %s mode data connection for '%s'%s.",
1949 		     type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1950 		return (fdopen(pdata, fmode));
1951 	}
1952 	if (data >= 0) {
1953 		reply(125, "Using existing data connection for '%s'%s.",
1954 		    name, sizebuf);
1955 		usedefault = 1;
1956 		return (fdopen(data, fmode));
1957 	}
1958 	if (usedefault)
1959 		data_dest = his_addr;
1960 	usedefault = 1;
1961 	retry = conerrno = 0;
1962 	do {
1963 		file = getdatasock(fmode);
1964 		if (file == NULL) {
1965 			char hbuf[NI_MAXHOST];
1966 			char pbuf[NI_MAXSERV];
1967 
1968 			if (getnameinfo((struct sockaddr *)&data_source.si_su,
1969 			    data_source.su_len, hbuf, sizeof(hbuf), pbuf,
1970 			    sizeof(pbuf), NI_NUMERICHOST | NI_NUMERICSERV))
1971 				strlcpy(hbuf, "?", sizeof(hbuf));
1972 			reply(425, "Can't create data socket (%s,%s): %s.",
1973 			      hbuf, pbuf, strerror(errno));
1974 			return (NULL);
1975 		}
1976 		data = fileno(file);
1977 		conerrno = 0;
1978 		if (connect(data, (struct sockaddr *)&data_dest.si_su,
1979 		    data_dest.su_len) == 0)
1980 			break;
1981 		conerrno = errno;
1982 		(void) fclose(file);
1983 		data = -1;
1984 		if (conerrno == EADDRINUSE) {
1985 			sleep((unsigned) swaitint);
1986 			retry += swaitint;
1987 		} else {
1988 			break;
1989 		}
1990 	} while (retry <= swaitmax);
1991 	if (conerrno != 0) {
1992 		perror_reply(425, "Can't build data connection");
1993 		return (NULL);
1994 	}
1995 	reply(150, "Opening %s mode data connection for '%s'%s.",
1996 	     type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1997 	return (file);
1998 }
1999 
2000 void
2001 closedataconn(FILE *fd)
2002 {
2003 
2004 	if (fd == NULL)
2005 		return;
2006 	(void)fclose(fd);
2007 	data = -1;
2008 	if (pdata >= 0)
2009 		(void)close(pdata);
2010 	pdata = -1;
2011 }
2012 
2013 int
2014 write_data(int fd, char *buf, size_t size, off_t *bufrem,
2015     struct timeval *then, int isdata)
2016 {
2017 	struct timeval now, td;
2018 	ssize_t c;
2019 
2020 	while (size > 0) {
2021 		c = size;
2022 		if (curclass.writesize) {
2023 			if (curclass.writesize < c)
2024 				c = curclass.writesize;
2025 		}
2026 		if (curclass.rateget) {
2027 			if (*bufrem < c)
2028 				c = *bufrem;
2029 		}
2030 		(void) alarm(curclass.timeout);
2031 		c = write(fd, buf, c);
2032 		if (c <= 0)
2033 			return (1);
2034 		buf += c;
2035 		size -= c;
2036 		byte_count += c;
2037 		if (isdata) {
2038 			total_data_out += c;
2039 			total_data += c;
2040 		}
2041 		total_bytes_out += c;
2042 		total_bytes += c;
2043 		if (curclass.rateget) {
2044 			*bufrem -= c;
2045 			if (*bufrem == 0) {
2046 				(void)gettimeofday(&now, NULL);
2047 				timersub(&now, then, &td);
2048 				if (td.tv_sec == 0) {
2049 					usleep(1000000 - td.tv_usec);
2050 					(void)gettimeofday(then, NULL);
2051 				} else
2052 					*then = now;
2053 				*bufrem = curclass.rateget;
2054 			}
2055 		}
2056 	}
2057 	return (0);
2058 }
2059 
2060 static enum send_status
2061 send_data_with_read(int filefd, int netfd, const struct stat *st, int isdata)
2062 {
2063 	struct timeval then;
2064 	off_t bufrem;
2065 	size_t readsize;
2066 	char *buf;
2067 	int c, error;
2068 
2069 	if (curclass.readsize)
2070 		readsize = curclass.readsize;
2071 	else
2072 		readsize = (size_t)st->st_blksize;
2073 	if ((buf = malloc(readsize)) == NULL) {
2074 		perror_reply(451, "Local resource failure: malloc");
2075 		return (SS_NO_TRANSFER);
2076 	}
2077 
2078 	if (curclass.rateget) {
2079 		bufrem = curclass.rateget;
2080 		(void)gettimeofday(&then, NULL);
2081 	}
2082 	while (1) {
2083 		(void) alarm(curclass.timeout);
2084 		c = read(filefd, buf, readsize);
2085 		if (c == 0)
2086 			error = SS_SUCCESS;
2087 		else if (c < 0)
2088 			error = SS_FILE_ERROR;
2089 		else if (write_data(netfd, buf, c, &bufrem, &then, isdata))
2090 			error = SS_DATA_ERROR;
2091 		else if (urgflag && handleoobcmd())
2092 			error = SS_ABORTED;
2093 		else
2094 			continue;
2095 
2096 		free(buf);
2097 		return (error);
2098 	}
2099 }
2100 
2101 static enum send_status
2102 send_data_with_mmap(int filefd, int netfd, const struct stat *st, int isdata)
2103 {
2104 	struct timeval then;
2105 	off_t bufrem, filesize, off, origoff;
2106 	size_t mapsize, winsize;
2107 	int error, sendbufsize, sendlowat;
2108 	void *win;
2109 
2110 	if (curclass.sendbufsize) {
2111 		sendbufsize = curclass.sendbufsize;
2112 		if (setsockopt(netfd, SOL_SOCKET, SO_SNDBUF,
2113 		    &sendbufsize, sizeof(int)) == -1)
2114 			syslog(LOG_WARNING, "setsockopt(SO_SNDBUF, %d): %m",
2115 			    sendbufsize);
2116 	}
2117 
2118 	if (curclass.sendlowat) {
2119 		sendlowat = curclass.sendlowat;
2120 		if (setsockopt(netfd, SOL_SOCKET, SO_SNDLOWAT,
2121 		    &sendlowat, sizeof(int)) == -1)
2122 			syslog(LOG_WARNING, "setsockopt(SO_SNDLOWAT, %d): %m",
2123 			    sendlowat);
2124 	}
2125 
2126 	winsize = curclass.mmapsize;
2127 	filesize = st->st_size;
2128 	if (debug)
2129 		syslog(LOG_INFO, "mmapsize = %ld, writesize = %ld",
2130 		    (long)winsize, (long)curclass.writesize);
2131 	if (winsize == 0)
2132 		goto try_read;
2133 
2134 	off = lseek(filefd, (off_t)0, SEEK_CUR);
2135 	if (off == -1)
2136 		goto try_read;
2137 
2138 	origoff = off;
2139 	if (curclass.rateget) {
2140 		bufrem = curclass.rateget;
2141 		(void)gettimeofday(&then, NULL);
2142 	}
2143 	while (1) {
2144 		mapsize = MIN(filesize - off, winsize);
2145 		if (mapsize == 0)
2146 			break;
2147 		win = mmap(NULL, mapsize, PROT_READ,
2148 		    MAP_FILE|MAP_SHARED, filefd, off);
2149 		if (win == MAP_FAILED) {
2150 			if (off == origoff)
2151 				goto try_read;
2152 			return (SS_FILE_ERROR);
2153 		}
2154 		(void) madvise(win, mapsize, MADV_SEQUENTIAL);
2155 		error = write_data(netfd, win, mapsize, &bufrem, &then,
2156 		    isdata);
2157 		(void) madvise(win, mapsize, MADV_DONTNEED);
2158 		munmap(win, mapsize);
2159 		if (urgflag && handleoobcmd())
2160 			return (SS_ABORTED);
2161 		if (error)
2162 			return (SS_DATA_ERROR);
2163 		off += mapsize;
2164 	}
2165 	return (SS_SUCCESS);
2166 
2167  try_read:
2168 	return (send_data_with_read(filefd, netfd, st, isdata));
2169 }
2170 
2171 /*
2172  * Tranfer the contents of "instr" to "outstr" peer using the appropriate
2173  * encapsulation of the data subject to Mode, Structure, and Type.
2174  *
2175  * NB: Form isn't handled.
2176  */
2177 static int
2178 send_data(FILE *instr, FILE *outstr, const struct stat *st, int isdata)
2179 {
2180 	int	 c, filefd, netfd, rval;
2181 
2182 	urgflag = 0;
2183 	transflag = 1;
2184 	rval = -1;
2185 
2186 	switch (type) {
2187 
2188 	case TYPE_A:
2189  /* XXXLUKEM: rate limit ascii send (get) */
2190 		(void) alarm(curclass.timeout);
2191 		while ((c = getc(instr)) != EOF) {
2192 			if (urgflag && handleoobcmd())
2193 				goto cleanup_send_data;
2194 			byte_count++;
2195 			if (c == '\n') {
2196 				if (ferror(outstr))
2197 					goto data_err;
2198 				(void) putc('\r', outstr);
2199 				if (isdata) {
2200 					total_data_out++;
2201 					total_data++;
2202 				}
2203 				total_bytes_out++;
2204 				total_bytes++;
2205 			}
2206 			(void) putc(c, outstr);
2207 			if (isdata) {
2208 				total_data_out++;
2209 				total_data++;
2210 			}
2211 			total_bytes_out++;
2212 			total_bytes++;
2213 			if ((byte_count % 4096) == 0)
2214 				(void) alarm(curclass.timeout);
2215 		}
2216 		(void) alarm(0);
2217 		fflush(outstr);
2218 		if (ferror(instr))
2219 			goto file_err;
2220 		if (ferror(outstr))
2221 			goto data_err;
2222 		rval = 0;
2223 		goto cleanup_send_data;
2224 
2225 	case TYPE_I:
2226 	case TYPE_L:
2227 		filefd = fileno(instr);
2228 		netfd = fileno(outstr);
2229 		switch (send_data_with_mmap(filefd, netfd, st, isdata)) {
2230 
2231 		case SS_SUCCESS:
2232 			break;
2233 
2234 		case SS_ABORTED:
2235 		case SS_NO_TRANSFER:
2236 			goto cleanup_send_data;
2237 
2238 		case SS_FILE_ERROR:
2239 			goto file_err;
2240 
2241 		case SS_DATA_ERROR:
2242 			goto data_err;
2243 		}
2244 		rval = 0;
2245 		goto cleanup_send_data;
2246 
2247 	default:
2248 		reply(550, "Unimplemented TYPE %d in send_data", type);
2249 		goto cleanup_send_data;
2250 	}
2251 
2252  data_err:
2253 	(void) alarm(0);
2254 	perror_reply(426, "Data connection");
2255 	goto cleanup_send_data;
2256 
2257  file_err:
2258 	(void) alarm(0);
2259 	perror_reply(551, "Error on input file");
2260 	goto cleanup_send_data;
2261 
2262  cleanup_send_data:
2263 	(void) alarm(0);
2264 	transflag = 0;
2265 	urgflag = 0;
2266 	if (isdata) {
2267 		total_files_out++;
2268 		total_files++;
2269 	}
2270 	total_xfers_out++;
2271 	total_xfers++;
2272 	return (rval);
2273 }
2274 
2275 /*
2276  * Transfer data from peer to "outstr" using the appropriate encapulation of
2277  * the data subject to Mode, Structure, and Type.
2278  *
2279  * N.B.: Form isn't handled.
2280  */
2281 static int
2282 receive_data(FILE *instr, FILE *outstr)
2283 {
2284 	int	c, bare_lfs, netfd, filefd, rval;
2285 	off_t	byteswritten;
2286 	char	*buf;
2287 	size_t	readsize;
2288 	struct sigaction sa, sa_saved;
2289 	struct stat st;
2290 #ifdef __GNUC__
2291 	(void) &bare_lfs;
2292 #endif
2293 
2294 	memset(&sa, 0, sizeof(sa));
2295 	sigfillset(&sa.sa_mask);
2296 	sa.sa_flags = SA_RESTART;
2297 	sa.sa_handler = lostconn;
2298 	(void) sigaction(SIGALRM, &sa, &sa_saved);
2299 
2300 	bare_lfs = 0;
2301 	urgflag = 0;
2302 	transflag = 1;
2303 	rval = -1;
2304 	byteswritten = 0;
2305 	buf = NULL;
2306 
2307 #define FILESIZECHECK(x) \
2308 			do { \
2309 				if (curclass.maxfilesize != -1 && \
2310 				    (x) > curclass.maxfilesize) { \
2311 					errno = EFBIG; \
2312 					goto file_err; \
2313 				} \
2314 			} while (0)
2315 
2316 	switch (type) {
2317 
2318 	case TYPE_I:
2319 	case TYPE_L:
2320 		netfd = fileno(instr);
2321 		filefd = fileno(outstr);
2322 		(void) alarm(curclass.timeout);
2323 		if (curclass.readsize)
2324 			readsize = curclass.readsize;
2325 		else if (fstat(filefd, &st))
2326 			readsize = (size_t)st.st_blksize;
2327 		else
2328 			readsize = BUFSIZ;
2329 		if ((buf = malloc(readsize)) == NULL) {
2330 			perror_reply(451, "Local resource failure: malloc");
2331 			goto cleanup_recv_data;
2332 		}
2333 		if (curclass.rateput) {
2334 			while (1) {
2335 				int d;
2336 				struct timeval then, now, td;
2337 				off_t bufrem;
2338 
2339 				(void)gettimeofday(&then, NULL);
2340 				errno = c = d = 0;
2341 				for (bufrem = curclass.rateput; bufrem > 0; ) {
2342 					if ((c = read(netfd, buf,
2343 					    MIN(readsize, bufrem))) <= 0)
2344 						goto recvdone;
2345 					if (urgflag && handleoobcmd())
2346 						goto cleanup_recv_data;
2347 					FILESIZECHECK(byte_count + c);
2348 					if ((d = write(filefd, buf, c)) != c)
2349 						goto file_err;
2350 					(void) alarm(curclass.timeout);
2351 					bufrem -= c;
2352 					byte_count += c;
2353 					total_data_in += c;
2354 					total_data += c;
2355 					total_bytes_in += c;
2356 					total_bytes += c;
2357 				}
2358 				(void)gettimeofday(&now, NULL);
2359 				timersub(&now, &then, &td);
2360 				if (td.tv_sec == 0)
2361 					usleep(1000000 - td.tv_usec);
2362 			}
2363 		} else {
2364 			while ((c = read(netfd, buf, readsize)) > 0) {
2365 				if (urgflag && handleoobcmd())
2366 					goto cleanup_recv_data;
2367 				FILESIZECHECK(byte_count + c);
2368 				if (write(filefd, buf, c) != c)
2369 					goto file_err;
2370 				(void) alarm(curclass.timeout);
2371 				byte_count += c;
2372 				total_data_in += c;
2373 				total_data += c;
2374 				total_bytes_in += c;
2375 				total_bytes += c;
2376 			}
2377 		}
2378  recvdone:
2379 		if (c < 0)
2380 			goto data_err;
2381 		rval = 0;
2382 		goto cleanup_recv_data;
2383 
2384 	case TYPE_E:
2385 		reply(553, "TYPE E not implemented.");
2386 		goto cleanup_recv_data;
2387 
2388 	case TYPE_A:
2389 		(void) alarm(curclass.timeout);
2390  /* XXXLUKEM: rate limit ascii receive (put) */
2391 		while ((c = getc(instr)) != EOF) {
2392 			if (urgflag && handleoobcmd())
2393 				goto cleanup_recv_data;
2394 			byte_count++;
2395 			total_data_in++;
2396 			total_data++;
2397 			total_bytes_in++;
2398 			total_bytes++;
2399 			if ((byte_count % 4096) == 0)
2400 				(void) alarm(curclass.timeout);
2401 			if (c == '\n')
2402 				bare_lfs++;
2403 			while (c == '\r') {
2404 				if (ferror(outstr))
2405 					goto data_err;
2406 				if ((c = getc(instr)) != '\n') {
2407 					byte_count++;
2408 					total_data_in++;
2409 					total_data++;
2410 					total_bytes_in++;
2411 					total_bytes++;
2412 					if ((byte_count % 4096) == 0)
2413 						(void) alarm(curclass.timeout);
2414 					byteswritten++;
2415 					FILESIZECHECK(byteswritten);
2416 					(void) putc ('\r', outstr);
2417 					if (c == '\0' || c == EOF)
2418 						goto contin2;
2419 				}
2420 			}
2421 			byteswritten++;
2422 			FILESIZECHECK(byteswritten);
2423 			(void) putc(c, outstr);
2424  contin2:	;
2425 		}
2426 		(void) alarm(0);
2427 		fflush(outstr);
2428 		if (ferror(instr))
2429 			goto data_err;
2430 		if (ferror(outstr))
2431 			goto file_err;
2432 		if (bare_lfs) {
2433 			reply(-226,
2434 			    "WARNING! %d bare linefeeds received in ASCII mode",
2435 			    bare_lfs);
2436 			reply(0, "File may not have transferred correctly.");
2437 		}
2438 		rval = 0;
2439 		goto cleanup_recv_data;
2440 
2441 	default:
2442 		reply(550, "Unimplemented TYPE %d in receive_data", type);
2443 		goto cleanup_recv_data;
2444 	}
2445 #undef FILESIZECHECK
2446 
2447  data_err:
2448 	(void) alarm(0);
2449 	perror_reply(426, "Data Connection");
2450 	goto cleanup_recv_data;
2451 
2452  file_err:
2453 	(void) alarm(0);
2454 	perror_reply(452, "Error writing file");
2455 	goto cleanup_recv_data;
2456 
2457  cleanup_recv_data:
2458 	(void) alarm(0);
2459 	(void) sigaction(SIGALRM, &sa_saved, NULL);
2460 	if (buf)
2461 		free(buf);
2462 	transflag = 0;
2463 	urgflag = 0;
2464 	total_files_in++;
2465 	total_files++;
2466 	total_xfers_in++;
2467 	total_xfers++;
2468 	return (rval);
2469 }
2470 
2471 void
2472 statcmd(void)
2473 {
2474 	struct sockinet *su = NULL;
2475 	static char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
2476 	u_char *a, *p;
2477 	int ispassive, af;
2478 	off_t otbi, otbo, otb;
2479 
2480 	a = p = (u_char *)NULL;
2481 
2482 	reply(-211, "%s FTP server status:", hostname);
2483 	reply(0, "Version: %s", EMPTYSTR(version) ? "<suppressed>" : version);
2484 	hbuf[0] = '\0';
2485 	if (!getnameinfo((struct sockaddr *)&his_addr.si_su, his_addr.su_len,
2486 			hbuf, sizeof(hbuf), NULL, 0, NI_NUMERICHOST)
2487 	    && strcmp(remotehost, hbuf) != 0)
2488 		reply(0, "Connected to %s (%s)", remotehost, hbuf);
2489 	else
2490 		reply(0, "Connected to %s", remotehost);
2491 
2492 	if (logged_in) {
2493 		if (curclass.type == CLASS_GUEST)
2494 			reply(0, "Logged in anonymously");
2495 		else
2496 			reply(0, "Logged in as %s%s", pw->pw_name,
2497 			    curclass.type == CLASS_CHROOT ? " (chroot)" : "");
2498 	} else if (askpasswd)
2499 		reply(0, "Waiting for password");
2500 	else
2501 		reply(0, "Waiting for user name");
2502 	cprintf(stdout, "    TYPE: %s", typenames[type]);
2503 	if (type == TYPE_A || type == TYPE_E)
2504 		cprintf(stdout, ", FORM: %s", formnames[form]);
2505 	if (type == TYPE_L) {
2506 #if NBBY == 8
2507 		cprintf(stdout, " %d", NBBY);
2508 #else
2509 			/* XXX: `bytesize' needs to be defined in this case */
2510 		cprintf(stdout, " %d", bytesize);
2511 #endif
2512 	}
2513 	cprintf(stdout, "; STRUcture: %s; transfer MODE: %s\r\n",
2514 	    strunames[stru], modenames[mode]);
2515 	ispassive = 0;
2516 	if (data != -1) {
2517 		reply(0, "Data connection open");
2518 		su = NULL;
2519 	} else if (pdata != -1) {
2520 		reply(0, "in Passive mode");
2521 		if (curclass.advertise.su_len != 0)
2522 			su = &curclass.advertise;
2523 		else
2524 			su = &pasv_addr;
2525 		ispassive = 1;
2526 		goto printaddr;
2527 	} else if (usedefault == 0) {
2528 		if (epsvall) {
2529 			reply(0, "EPSV only mode (EPSV ALL)");
2530 			goto epsvonly;
2531 		}
2532 		su = (struct sockinet *)&data_dest;
2533  printaddr:
2534 							/* PASV/PORT */
2535 		if (su->su_family == AF_INET) {
2536 			a = (u_char *) &su->su_addr;
2537 			p = (u_char *) &su->su_port;
2538 #define UC(b) (((int) b) & 0xff)
2539 			reply(0, "%s (%d,%d,%d,%d,%d,%d)",
2540 				ispassive ? "PASV" : "PORT" ,
2541 				UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2542 				UC(p[0]), UC(p[1]));
2543 		}
2544 
2545 							/* LPSV/LPRT */
2546 	    {
2547 		int alen, i;
2548 
2549 		alen = 0;
2550 		switch (su->su_family) {
2551 		case AF_INET:
2552 			a = (u_char *) &su->su_addr;
2553 			p = (u_char *) &su->su_port;
2554 			alen = sizeof(su->su_addr);
2555 			af = 4;
2556 			break;
2557 #ifdef INET6
2558 		case AF_INET6:
2559 			a = (u_char *) &su->su_6addr;
2560 			p = (u_char *) &su->su_port;
2561 			alen = sizeof(su->su_6addr);
2562 			af = 6;
2563 			break;
2564 #endif
2565 		default:
2566 			af = 0;
2567 			break;
2568 		}
2569 		if (af) {
2570 			cprintf(stdout, "    %s (%d,%d",
2571 			    ispassive ? "LPSV" : "LPRT", af, alen);
2572 			for (i = 0; i < alen; i++)
2573 				cprintf(stdout, ",%d", UC(a[i]));
2574 			cprintf(stdout, ",%d,%d,%d)\r\n",
2575 			    2, UC(p[0]), UC(p[1]));
2576 #undef UC
2577 		}
2578 	    }
2579 
2580 		/* EPRT/EPSV */
2581  epsvonly:
2582 		af = af2epsvproto(su->su_family);
2583 		hbuf[0] = '\0';
2584 		if (af > 0) {
2585 			struct sockinet tmp;
2586 
2587 			tmp = *su;
2588 #ifdef INET6
2589 			if (tmp.su_family == AF_INET6)
2590 				tmp.su_scope_id = 0;
2591 #endif
2592 			if (getnameinfo((struct sockaddr *)&tmp.si_su,
2593 			    tmp.su_len, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf),
2594 			    NI_NUMERICHOST | NI_NUMERICSERV) == 0)
2595 				reply(0, "%s (|%d|%s|%s|)",
2596 				    ispassive ? "EPSV" : "EPRT",
2597 				    af, hbuf, sbuf);
2598 		}
2599 	} else
2600 		reply(0, "No data connection");
2601 
2602 	if (logged_in) {
2603 		reply(0,
2604 		    "Data sent:        " LLF " byte%s in " LLF " file%s",
2605 		    (LLT)total_data_out, PLURAL(total_data_out),
2606 		    (LLT)total_files_out, PLURAL(total_files_out));
2607 		reply(0,
2608 		    "Data received:    " LLF " byte%s in " LLF " file%s",
2609 		    (LLT)total_data_in, PLURAL(total_data_in),
2610 		    (LLT)total_files_in, PLURAL(total_files_in));
2611 		reply(0,
2612 		    "Total data:       " LLF " byte%s in " LLF " file%s",
2613 		    (LLT)total_data, PLURAL(total_data),
2614 		    (LLT)total_files, PLURAL(total_files));
2615 	}
2616 	otbi = total_bytes_in;
2617 	otbo = total_bytes_out;
2618 	otb = total_bytes;
2619 	reply(0, "Traffic sent:     " LLF " byte%s in " LLF " transfer%s",
2620 	    (LLT)otbo, PLURAL(otbo),
2621 	    (LLT)total_xfers_out, PLURAL(total_xfers_out));
2622 	reply(0, "Traffic received: " LLF " byte%s in " LLF " transfer%s",
2623 	    (LLT)otbi, PLURAL(otbi),
2624 	    (LLT)total_xfers_in, PLURAL(total_xfers_in));
2625 	reply(0, "Total traffic:    " LLF " byte%s in " LLF " transfer%s",
2626 	    (LLT)otb, PLURAL(otb),
2627 	    (LLT)total_xfers, PLURAL(total_xfers));
2628 
2629 	if (logged_in && !CURCLASS_FLAGS_ISSET(private)) {
2630 		struct ftpconv *cp;
2631 
2632 		reply(0, "%s", "");
2633 		reply(0, "Class: %s, type: %s",
2634 		    curclass.classname, CURCLASSTYPE);
2635 		reply(0, "Check PORT/LPRT commands: %sabled",
2636 		    CURCLASS_FLAGS_ISSET(checkportcmd) ? "en" : "dis");
2637 		if (! EMPTYSTR(curclass.display))
2638 			reply(0, "Display file: %s", curclass.display);
2639 		if (! EMPTYSTR(curclass.notify))
2640 			reply(0, "Notify fileglob: %s", curclass.notify);
2641 		reply(0, "Idle timeout: " LLF ", maximum timeout: " LLF,
2642 		    (LLT)curclass.timeout, (LLT)curclass.maxtimeout);
2643 		reply(0, "Current connections: %d", connections);
2644 		if (curclass.limit == -1)
2645 			reply(0, "Maximum connections: unlimited");
2646 		else
2647 			reply(0, "Maximum connections: " LLF,
2648 			    (LLT)curclass.limit);
2649 		if (curclass.limitfile)
2650 			reply(0, "Connection limit exceeded message file: %s",
2651 			    conffilename(curclass.limitfile));
2652 		if (! EMPTYSTR(curclass.chroot))
2653 			reply(0, "Chroot format: %s", curclass.chroot);
2654 		reply(0, "Deny bad ftpusers(5) quickly: %sabled",
2655 		    CURCLASS_FLAGS_ISSET(denyquick) ? "en" : "dis");
2656 		if (! EMPTYSTR(curclass.homedir))
2657 			reply(0, "Homedir format: %s", curclass.homedir);
2658 		if (curclass.maxfilesize == -1)
2659 			reply(0, "Maximum file size: unlimited");
2660 		else
2661 			reply(0, "Maximum file size: " LLF,
2662 			    (LLT)curclass.maxfilesize);
2663 		if (! EMPTYSTR(curclass.motd))
2664 			reply(0, "MotD file: %s", conffilename(curclass.motd));
2665 		reply(0,
2666 	    "Modify commands (CHMOD, DELE, MKD, RMD, RNFR, UMASK): %sabled",
2667 		    CURCLASS_FLAGS_ISSET(modify) ? "en" : "dis");
2668 		reply(0, "Upload commands (APPE, STOR, STOU): %sabled",
2669 		    CURCLASS_FLAGS_ISSET(upload) ? "en" : "dis");
2670 		reply(0, "Sanitize file names: %sabled",
2671 		    CURCLASS_FLAGS_ISSET(sanenames) ? "en" : "dis");
2672 		reply(0, "PASV/LPSV/EPSV connections: %sabled",
2673 		    CURCLASS_FLAGS_ISSET(passive) ? "en" : "dis");
2674 		if (curclass.advertise.su_len != 0) {
2675 			char buf[50];	/* big enough for IPv6 address */
2676 			const char *bp;
2677 
2678 			bp = inet_ntop(curclass.advertise.su_family,
2679 			    (void *)&curclass.advertise.su_addr,
2680 			    buf, sizeof(buf));
2681 			if (bp != NULL)
2682 				reply(0, "PASV advertise address: %s", bp);
2683 		}
2684 		if (curclass.portmin && curclass.portmax)
2685 			reply(0, "PASV port range: " LLF " - " LLF,
2686 			    (LLT)curclass.portmin, (LLT)curclass.portmax);
2687 		if (curclass.rateget)
2688 			reply(0, "Rate get limit: " LLF " bytes/sec",
2689 			    (LLT)curclass.rateget);
2690 		else
2691 			reply(0, "Rate get limit: disabled");
2692 		if (curclass.rateput)
2693 			reply(0, "Rate put limit: " LLF " bytes/sec",
2694 			    (LLT)curclass.rateput);
2695 		else
2696 			reply(0, "Rate put limit: disabled");
2697 		if (curclass.mmapsize)
2698 			reply(0, "Mmap size: " LLF, (LLT)curclass.mmapsize);
2699 		else
2700 			reply(0, "Mmap size: disabled");
2701 		if (curclass.readsize)
2702 			reply(0, "Read size: " LLF, (LLT)curclass.readsize);
2703 		else
2704 			reply(0, "Read size: default");
2705 		if (curclass.writesize)
2706 			reply(0, "Write size: " LLF, (LLT)curclass.writesize);
2707 		else
2708 			reply(0, "Write size: default");
2709 		if (curclass.recvbufsize)
2710 			reply(0, "Receive buffer size: " LLF,
2711 			    (LLT)curclass.recvbufsize);
2712 		else
2713 			reply(0, "Receive buffer size: default");
2714 		if (curclass.sendbufsize)
2715 			reply(0, "Send buffer size: " LLF,
2716 			    (LLT)curclass.sendbufsize);
2717 		else
2718 			reply(0, "Send buffer size: default");
2719 		if (curclass.sendlowat)
2720 			reply(0, "Send low water mark: " LLF,
2721 			    (LLT)curclass.sendlowat);
2722 		else
2723 			reply(0, "Send low water mark: default");
2724 		reply(0, "Umask: %.04o", curclass.umask);
2725 		for (cp = curclass.conversions; cp != NULL; cp=cp->next) {
2726 			if (cp->suffix == NULL || cp->types == NULL ||
2727 			    cp->command == NULL)
2728 				continue;
2729 			reply(0, "Conversion: %s [%s] disable: %s, command: %s",
2730 			    cp->suffix, cp->types, cp->disable, cp->command);
2731 		}
2732 	}
2733 
2734 	reply(211, "End of status");
2735 }
2736 
2737 void
2738 fatal(const char *s)
2739 {
2740 
2741 	reply(451, "Error in server: %s\n", s);
2742 	reply(221, "Closing connection due to server error.");
2743 	dologout(0);
2744 	/* NOTREACHED */
2745 }
2746 
2747 /*
2748  * reply() --
2749  *	depending on the value of n, display fmt with a trailing CRLF and
2750  *	prefix of:
2751  *	n < -1		prefix the message with abs(n) + "-"	(initial line)
2752  *	n == 0		prefix the message with 4 spaces	(middle lines)
2753  *	n >  0		prefix the message with n + " "		(final line)
2754  */
2755 void
2756 reply(int n, const char *fmt, ...)
2757 {
2758 	char	msg[MAXPATHLEN * 2 + 100];
2759 	size_t	b;
2760 	va_list	ap;
2761 
2762 	b = 0;
2763 	if (n == 0)
2764 		b = snprintf(msg, sizeof(msg), "    ");
2765 	else if (n < 0)
2766 		b = snprintf(msg, sizeof(msg), "%d-", -n);
2767 	else
2768 		b = snprintf(msg, sizeof(msg), "%d ", n);
2769 	va_start(ap, fmt);
2770 	vsnprintf(msg + b, sizeof(msg) - b, fmt, ap);
2771 	va_end(ap);
2772 	cprintf(stdout, "%s\r\n", msg);
2773 	(void)fflush(stdout);
2774 	if (debug)
2775 		syslog(LOG_DEBUG, "<--- %s", msg);
2776 }
2777 
2778 static void
2779 logremotehost(struct sockinet *who)
2780 {
2781 
2782 	if (getnameinfo((struct sockaddr *)&who->si_su,
2783 	    who->su_len, remotehost, sizeof(remotehost), NULL, 0, 0))
2784 		strlcpy(remotehost, "?", sizeof(remotehost));
2785 
2786 #if HAVE_SETPROCTITLE
2787 	snprintf(proctitle, sizeof(proctitle), "%s: connected", remotehost);
2788 	setproctitle("%s", proctitle);
2789 #endif /* HAVE_SETPROCTITLE */
2790 	if (logging)
2791 		syslog(LOG_INFO, "connection from %s to %s",
2792 		    remotehost, hostname);
2793 }
2794 
2795 /*
2796  * Record logout in wtmp file and exit with supplied status.
2797  * NOTE: because this is called from signal handlers it cannot
2798  *       use stdio (or call other functions that use stdio).
2799  */
2800 void
2801 dologout(int status)
2802 {
2803 	/*
2804 	* Prevent reception of SIGURG from resulting in a resumption
2805 	* back to the main program loop.
2806 	*/
2807 	transflag = 0;
2808 	logout_utmp();
2809 	if (logged_in) {
2810 #ifdef KERBEROS
2811 		if (!notickets && krbtkfile_env)
2812 			unlink(krbtkfile_env);
2813 #endif
2814 	}
2815 	/* beware of flushing buffers after a SIGPIPE */
2816 	if (xferlogfd != -1)
2817 		close(xferlogfd);
2818 	_exit(status);
2819 }
2820 
2821 void
2822 abor(void)
2823 {
2824 
2825 	if (!transflag)
2826 		return;
2827 	tmpline[0] = '\0';
2828 	is_oob = 0;
2829 	reply(426, "Transfer aborted. Data connection closed.");
2830 	reply(226, "Abort successful");
2831 	transflag = 0;		/* flag that the transfer has aborted */
2832 }
2833 
2834 void
2835 statxfer(void)
2836 {
2837 
2838 	if (!transflag)
2839 		return;
2840 	tmpline[0] = '\0';
2841 	is_oob = 0;
2842 	if (file_size != (off_t) -1)
2843 		reply(213,
2844 		    "Status: " LLF " of " LLF " byte%s transferred",
2845 		    (LLT)byte_count, (LLT)file_size,
2846 		    PLURAL(byte_count));
2847 	else
2848 		reply(213, "Status: " LLF " byte%s transferred",
2849 		    (LLT)byte_count, PLURAL(byte_count));
2850 }
2851 
2852 /*
2853  * Call when urgflag != 0 to handle Out Of Band commands.
2854  * Returns non zero if the OOB command aborted the transfer
2855  * by setting transflag to 0. (c.f., "ABOR").
2856  */
2857 static int
2858 handleoobcmd()
2859 {
2860 	char *cp;
2861 
2862 	if (!urgflag)
2863 		return (0);
2864 	urgflag = 0;
2865 	/* only process if transfer occurring */
2866 	if (!transflag)
2867 		return (0);
2868 	cp = tmpline;
2869 	if (getline(cp, sizeof(tmpline), stdin) == NULL) {
2870 		reply(221, "You could at least say goodbye.");
2871 		dologout(0);
2872 	}
2873 		/*
2874 		 * Manually parse OOB commands, because we can't
2875 		 * recursively call the yacc parser...
2876 		 */
2877 	if (strcasecmp(cp, "ABOR\r\n") == 0) {
2878 		abor();
2879 	} else if (strcasecmp(cp, "STAT\r\n") == 0) {
2880 		statxfer();
2881 	} else {
2882 		/* XXX: error with "500 unknown command" ? */
2883 	}
2884 	return (transflag == 0);
2885 }
2886 
2887 static int
2888 bind_pasv_addr(void)
2889 {
2890 	static int passiveport;
2891 	int port, len;
2892 
2893 	len = pasv_addr.su_len;
2894 	if (curclass.portmin == 0 && curclass.portmax == 0) {
2895 		pasv_addr.su_port = 0;
2896 		return (bind(pdata, (struct sockaddr *)&pasv_addr.si_su, len));
2897 	}
2898 
2899 	if (passiveport == 0) {
2900 		srand(getpid());
2901 		passiveport = rand() % (curclass.portmax - curclass.portmin)
2902 		    + curclass.portmin;
2903 	}
2904 
2905 	port = passiveport;
2906 	while (1) {
2907 		port++;
2908 		if (port > curclass.portmax)
2909 			port = curclass.portmin;
2910 		else if (port == passiveport) {
2911 			errno = EAGAIN;
2912 			return (-1);
2913 		}
2914 		pasv_addr.su_port = htons(port);
2915 		if (bind(pdata, (struct sockaddr *)&pasv_addr.si_su, len) == 0)
2916 			break;
2917 		if (errno != EADDRINUSE)
2918 			return (-1);
2919 	}
2920 	passiveport = port;
2921 	return (0);
2922 }
2923 
2924 /*
2925  * Note: a response of 425 is not mentioned as a possible response to
2926  *	the PASV command in RFC959. However, it has been blessed as
2927  *	a legitimate response by Jon Postel in a telephone conversation
2928  *	with Rick Adams on 25 Jan 89.
2929  */
2930 void
2931 passive(void)
2932 {
2933 	int len, recvbufsize;
2934 	char *p, *a;
2935 
2936 	if (pdata >= 0)
2937 		close(pdata);
2938 	pdata = socket(AF_INET, SOCK_STREAM, 0);
2939 	if (pdata < 0 || !logged_in) {
2940 		perror_reply(425, "Can't open passive connection");
2941 		return;
2942 	}
2943 	pasv_addr = ctrl_addr;
2944 
2945 	if (bind_pasv_addr() < 0)
2946 		goto pasv_error;
2947 	len = pasv_addr.su_len;
2948 	if (getsockname(pdata, (struct sockaddr *) &pasv_addr.si_su, &len) < 0)
2949 		goto pasv_error;
2950 	pasv_addr.su_len = len;
2951 	if (curclass.recvbufsize) {
2952 		recvbufsize = curclass.recvbufsize;
2953 		if (setsockopt(pdata, SOL_SOCKET, SO_RCVBUF, &recvbufsize,
2954 			       sizeof(int)) == -1)
2955 			syslog(LOG_WARNING, "setsockopt(SO_RCVBUF, %d): %m",
2956 			       recvbufsize);
2957 	}
2958 	if (listen(pdata, 1) < 0)
2959 		goto pasv_error;
2960 	if (curclass.advertise.su_len != 0)
2961 		a = (char *) &curclass.advertise.su_addr;
2962 	else
2963 		a = (char *) &pasv_addr.su_addr;
2964 	p = (char *) &pasv_addr.su_port;
2965 
2966 #define UC(b) (((int) b) & 0xff)
2967 
2968 	reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
2969 		UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
2970 	return;
2971 
2972  pasv_error:
2973 	(void) close(pdata);
2974 	pdata = -1;
2975 	perror_reply(425, "Can't open passive connection");
2976 	return;
2977 }
2978 
2979 /*
2980  * convert protocol identifier to/from AF
2981  */
2982 int
2983 lpsvproto2af(int proto)
2984 {
2985 
2986 	switch (proto) {
2987 	case 4:
2988 		return AF_INET;
2989 #ifdef INET6
2990 	case 6:
2991 		return AF_INET6;
2992 #endif
2993 	default:
2994 		return -1;
2995 	}
2996 }
2997 
2998 int
2999 af2lpsvproto(int af)
3000 {
3001 
3002 	switch (af) {
3003 	case AF_INET:
3004 		return 4;
3005 #ifdef INET6
3006 	case AF_INET6:
3007 		return 6;
3008 #endif
3009 	default:
3010 		return -1;
3011 	}
3012 }
3013 
3014 int
3015 epsvproto2af(int proto)
3016 {
3017 
3018 	switch (proto) {
3019 	case 1:
3020 		return AF_INET;
3021 #ifdef INET6
3022 	case 2:
3023 		return AF_INET6;
3024 #endif
3025 	default:
3026 		return -1;
3027 	}
3028 }
3029 
3030 int
3031 af2epsvproto(int af)
3032 {
3033 
3034 	switch (af) {
3035 	case AF_INET:
3036 		return 1;
3037 #ifdef INET6
3038 	case AF_INET6:
3039 		return 2;
3040 #endif
3041 	default:
3042 		return -1;
3043 	}
3044 }
3045 
3046 /*
3047  * 228 Entering Long Passive Mode (af, hal, h1, h2, h3,..., pal, p1, p2...)
3048  * 229 Entering Extended Passive Mode (|||port|)
3049  */
3050 void
3051 long_passive(char *cmd, int pf)
3052 {
3053 	int len;
3054 	char *p, *a;
3055 
3056 	if (!logged_in) {
3057 		syslog(LOG_NOTICE, "long passive but not logged in");
3058 		reply(503, "Login with USER first.");
3059 		return;
3060 	}
3061 
3062 	if (pf != PF_UNSPEC && ctrl_addr.su_family != pf) {
3063 		/*
3064 		 * XXX: only EPRT/EPSV ready clients will understand this
3065 		 */
3066 		if (strcmp(cmd, "EPSV") != 0)
3067 			reply(501, "Network protocol mismatch"); /*XXX*/
3068 		else
3069 			epsv_protounsupp("Network protocol mismatch");
3070 
3071 		return;
3072 	}
3073 
3074 	if (pdata >= 0)
3075 		close(pdata);
3076 	pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
3077 	if (pdata < 0) {
3078 		perror_reply(425, "Can't open passive connection");
3079 		return;
3080 	}
3081 	pasv_addr = ctrl_addr;
3082 	if (bind_pasv_addr() < 0)
3083 		goto pasv_error;
3084 	len = pasv_addr.su_len;
3085 	if (getsockname(pdata, (struct sockaddr *) &pasv_addr.si_su, &len) < 0)
3086 		goto pasv_error;
3087 	pasv_addr.su_len = len;
3088 	if (listen(pdata, 1) < 0)
3089 		goto pasv_error;
3090 	p = (char *) &pasv_addr.su_port;
3091 
3092 #define UC(b) (((int) b) & 0xff)
3093 
3094 	if (strcmp(cmd, "LPSV") == 0) {
3095 		struct sockinet *advert;
3096 
3097 		if (curclass.advertise.su_len != 0)
3098 			advert = &curclass.advertise;
3099 		else
3100 			advert = &pasv_addr;
3101 		switch (advert->su_family) {
3102 		case AF_INET:
3103 			a = (char *) &advert->su_addr;
3104 			reply(228,
3105     "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)",
3106 				4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
3107 				2, UC(p[0]), UC(p[1]));
3108 			return;
3109 #ifdef INET6
3110 		case AF_INET6:
3111 			a = (char *) &advert->su_6addr;
3112 			reply(228,
3113     "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)",
3114 				6, 16,
3115 				UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
3116 				UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]),
3117 				UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]),
3118 				UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]),
3119 				2, UC(p[0]), UC(p[1]));
3120 			return;
3121 #endif
3122 		}
3123 #undef UC
3124 	} else if (strcmp(cmd, "EPSV") == 0) {
3125 		switch (pasv_addr.su_family) {
3126 		case AF_INET:
3127 #ifdef INET6
3128 		case AF_INET6:
3129 #endif
3130 			reply(229, "Entering Extended Passive Mode (|||%d|)",
3131 			    ntohs(pasv_addr.su_port));
3132 			return;
3133 		}
3134 	} else {
3135 		/* more proper error code? */
3136 	}
3137 
3138  pasv_error:
3139 	(void) close(pdata);
3140 	pdata = -1;
3141 	perror_reply(425, "Can't open passive connection");
3142 	return;
3143 }
3144 
3145 int
3146 extended_port(const char *arg)
3147 {
3148 	char *tmp = NULL;
3149 	char *result[3];
3150 	char *p, *q;
3151 	char delim;
3152 	struct addrinfo hints;
3153 	struct addrinfo *res = NULL;
3154 	int i;
3155 	unsigned long proto;
3156 
3157 	tmp = xstrdup(arg);
3158 	p = tmp;
3159 	delim = p[0];
3160 	p++;
3161 	memset(result, 0, sizeof(result));
3162 	for (i = 0; i < 3; i++) {
3163 		q = strchr(p, delim);
3164 		if (!q || *q != delim)
3165 			goto parsefail;
3166 		*q++ = '\0';
3167 		result[i] = p;
3168 		p = q;
3169 	}
3170 
3171 			/* some more sanity checks */
3172 	errno = 0;
3173 	p = NULL;
3174 	(void)strtoul(result[2], &p, 10);
3175 	if (errno || !*result[2] || *p)
3176 		goto parsefail;
3177 	errno = 0;
3178 	p = NULL;
3179 	proto = strtoul(result[0], &p, 10);
3180 	if (errno || !*result[0] || *p)
3181 		goto protounsupp;
3182 
3183 	memset(&hints, 0, sizeof(hints));
3184 	hints.ai_family = epsvproto2af((int)proto);
3185 	if (hints.ai_family < 0)
3186 		goto protounsupp;
3187 	hints.ai_socktype = SOCK_STREAM;
3188 	hints.ai_flags = AI_NUMERICHOST;
3189 	if (getaddrinfo(result[1], result[2], &hints, &res))
3190 		goto parsefail;
3191 	if (res->ai_next)
3192 		goto parsefail;
3193 	if (sizeof(data_dest) < res->ai_addrlen)
3194 		goto parsefail;
3195 	memcpy(&data_dest.si_su, res->ai_addr, res->ai_addrlen);
3196 	data_dest.su_len = res->ai_addrlen;
3197 #ifdef INET6
3198 	if (his_addr.su_family == AF_INET6 &&
3199 	    data_dest.su_family == AF_INET6) {
3200 			/* XXX: more sanity checks! */
3201 		data_dest.su_scope_id = his_addr.su_scope_id;
3202 	}
3203 #endif
3204 
3205 	if (tmp != NULL)
3206 		free(tmp);
3207 	if (res)
3208 		freeaddrinfo(res);
3209 	return 0;
3210 
3211  parsefail:
3212 	reply(500, "Invalid argument, rejected.");
3213 	usedefault = 1;
3214 	if (tmp != NULL)
3215 		free(tmp);
3216 	if (res)
3217 		freeaddrinfo(res);
3218 	return -1;
3219 
3220  protounsupp:
3221 	epsv_protounsupp("Protocol not supported");
3222 	usedefault = 1;
3223 	if (tmp != NULL)
3224 		free(tmp);
3225 	if (res)
3226 		freeaddrinfo(res);
3227 	return -1;
3228 }
3229 
3230 /*
3231  * 522 Protocol not supported (proto,...)
3232  * as we assume address family for control and data connections are the same,
3233  * we do not return the list of address families we support - instead, we
3234  * return the address family of the control connection.
3235  */
3236 void
3237 epsv_protounsupp(const char *message)
3238 {
3239 	int proto;
3240 
3241 	proto = af2epsvproto(ctrl_addr.su_family);
3242 	if (proto < 0)
3243 		reply(501, "%s", message);	/* XXX */
3244 	else
3245 		reply(522, "%s, use (%d)", message, proto);
3246 }
3247 
3248 /*
3249  * Generate unique name for file with basename "local".
3250  * The file named "local" is already known to exist.
3251  * Generates failure reply on error.
3252  *
3253  * XXX:	this function should under go changes similar to
3254  *	the mktemp(3)/mkstemp(3) changes.
3255  */
3256 static char *
3257 gunique(const char *local)
3258 {
3259 	static char new[MAXPATHLEN];
3260 	struct stat st;
3261 	char *cp;
3262 	int count;
3263 
3264 	cp = strrchr(local, '/');
3265 	if (cp)
3266 		*cp = '\0';
3267 	if (stat(cp ? local : ".", &st) < 0) {
3268 		perror_reply(553, cp ? local : ".");
3269 		return (NULL);
3270 	}
3271 	if (cp)
3272 		*cp = '/';
3273 	for (count = 1; count < 100; count++) {
3274 		(void)snprintf(new, sizeof(new) - 1, "%s.%d", local, count);
3275 		if (stat(new, &st) < 0)
3276 			return (new);
3277 	}
3278 	reply(452, "Unique file name cannot be created.");
3279 	return (NULL);
3280 }
3281 
3282 /*
3283  * Format and send reply containing system error number.
3284  */
3285 void
3286 perror_reply(int code, const char *string)
3287 {
3288 	int save_errno;
3289 
3290 	save_errno = errno;
3291 	reply(code, "%s: %s.", string, strerror(errno));
3292 	errno = save_errno;
3293 }
3294 
3295 static char *onefile[] = {
3296 	"",
3297 	0
3298 };
3299 
3300 void
3301 send_file_list(const char *whichf)
3302 {
3303 	struct stat st;
3304 	DIR *dirp = NULL;
3305 	struct dirent *dir;
3306 	FILE *dout = NULL;
3307 	char **dirlist, *dirname, *p;
3308 	char *notglob = NULL;
3309 	int simple = 0;
3310 	int freeglob = 0;
3311 	glob_t gl;
3312 
3313 #ifdef __GNUC__
3314 	(void) &dout;
3315 	(void) &dirlist;
3316 	(void) &simple;
3317 	(void) &freeglob;
3318 #endif
3319 	urgflag = 0;
3320 
3321 	p = NULL;
3322 	if (strpbrk(whichf, "~{[*?") != NULL) {
3323 		int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE|GLOB_LIMIT;
3324 
3325 		memset(&gl, 0, sizeof(gl));
3326 		freeglob = 1;
3327 		if (glob(whichf, flags, 0, &gl)) {
3328 			reply(450, "Not found");
3329 			goto cleanup_send_file_list;
3330 		} else if (gl.gl_pathc == 0) {
3331 			errno = ENOENT;
3332 			perror_reply(450, whichf);
3333 			goto cleanup_send_file_list;
3334 		}
3335 		dirlist = gl.gl_pathv;
3336 	} else {
3337 		notglob = xstrdup(whichf);
3338 		onefile[0] = notglob;
3339 		dirlist = onefile;
3340 		simple = 1;
3341 	}
3342 					/* XXX: } for vi sm */
3343 
3344 	while ((dirname = *dirlist++) != NULL) {
3345 		int trailingslash = 0;
3346 
3347 		if (stat(dirname, &st) < 0) {
3348 			/*
3349 			 * If user typed "ls -l", etc, and the client
3350 			 * used NLST, do what the user meant.
3351 			 */
3352 			/* XXX: nuke this support? */
3353 			if (dirname[0] == '-' && *dirlist == NULL &&
3354 			    transflag == 0) {
3355 				char *argv[] = { INTERNAL_LS, "", NULL };
3356 
3357 				argv[1] = dirname;
3358 				retrieve(argv, dirname);
3359 				goto cleanup_send_file_list;
3360 			}
3361 			perror_reply(450, whichf);
3362 			goto cleanup_send_file_list;
3363 		}
3364 
3365 		if (S_ISREG(st.st_mode)) {
3366 			/*
3367 			 * XXXRFC:
3368 			 *	should we follow RFC959 and not work
3369 			 *	for non directories?
3370 			 */
3371 			if (dout == NULL) {
3372 				dout = dataconn("file list", (off_t)-1, "w");
3373 				if (dout == NULL)
3374 					goto cleanup_send_file_list;
3375 				transflag = 1;
3376 			}
3377 			cprintf(dout, "%s%s\n", dirname,
3378 			    type == TYPE_A ? "\r" : "");
3379 			continue;
3380 		} else if (!S_ISDIR(st.st_mode))
3381 			continue;
3382 
3383 		if (dirname[strlen(dirname) - 1] == '/')
3384 			trailingslash++;
3385 
3386 		if ((dirp = opendir(dirname)) == NULL)
3387 			continue;
3388 
3389 		while ((dir = readdir(dirp)) != NULL) {
3390 			char nbuf[MAXPATHLEN];
3391 
3392 			if (urgflag && handleoobcmd())
3393 				goto cleanup_send_file_list;
3394 
3395 			if (ISDOTDIR(dir->d_name) || ISDOTDOTDIR(dir->d_name))
3396 				continue;
3397 
3398 			(void)snprintf(nbuf, sizeof(nbuf), "%s%s%s", dirname,
3399 			    trailingslash ? "" : "/", dir->d_name);
3400 
3401 			/*
3402 			 * We have to do a stat to ensure it's
3403 			 * not a directory or special file.
3404 			 */
3405 			/*
3406 			 * XXXRFC:
3407 			 *	should we follow RFC959 and filter out
3408 			 *	non files ?   lukem - NO!, or not until
3409 			 *	our ftp client uses MLS{T,D} for completion.
3410 			 */
3411 			if (simple || (stat(nbuf, &st) == 0 &&
3412 			    S_ISREG(st.st_mode))) {
3413 				if (dout == NULL) {
3414 					dout = dataconn("file list", (off_t)-1,
3415 						"w");
3416 					if (dout == NULL)
3417 						goto cleanup_send_file_list;
3418 					transflag = 1;
3419 				}
3420 				p = nbuf;
3421 				if (nbuf[0] == '.' && nbuf[1] == '/')
3422 					p = &nbuf[2];
3423 				cprintf(dout, "%s%s\n", p,
3424 				    type == TYPE_A ? "\r" : "");
3425 			}
3426 		}
3427 		(void) closedir(dirp);
3428 	}
3429 
3430 	if (dout == NULL)
3431 		reply(450, "No files found.");
3432 	else if (ferror(dout) != 0)
3433 		perror_reply(451, "Data connection");
3434 	else
3435 		reply(226, "Transfer complete.");
3436 
3437  cleanup_send_file_list:
3438 	closedataconn(dout);
3439 	transflag = 0;
3440 	urgflag = 0;
3441 	total_xfers++;
3442 	total_xfers_out++;
3443 	if (notglob)
3444 		free(notglob);
3445 	if (freeglob)
3446 		globfree(&gl);
3447 }
3448 
3449 char *
3450 conffilename(const char *s)
3451 {
3452 	static char filename[MAXPATHLEN];
3453 
3454 	if (*s == '/')
3455 		strlcpy(filename, s, sizeof(filename));
3456 	else
3457 		(void)snprintf(filename, sizeof(filename), "%s/%s", confdir ,s);
3458 	return (filename);
3459 }
3460 
3461 /*
3462  * logxfer --
3463  *	if logging > 1, then based on the arguments, syslog a message:
3464  *	 if bytes != -1		"<command> <file1> = <bytes> bytes"
3465  *	 else if file2 != NULL	"<command> <file1> <file2>"
3466  *	 else			"<command> <file1>"
3467  *	if elapsed != NULL, append "in xxx.yyy seconds"
3468  *	if error != NULL, append ": " + error
3469  *
3470  *	if doxferlog != 0, bytes != -1, and command is "get", "put",
3471  *	or "append", syslog and/or write a wu-ftpd style xferlog entry
3472  */
3473 void
3474 logxfer(const char *command, off_t bytes, const char *file1, const char *file2,
3475     const struct timeval *elapsed, const char *error)
3476 {
3477 	char		 buf[MAXPATHLEN * 2 + 100];
3478 	char		 realfile1[MAXPATHLEN], realfile2[MAXPATHLEN];
3479 	const char	*r1, *r2;
3480 	char		 direction;
3481 	size_t		 len;
3482 	time_t		 now;
3483 
3484 	if (logging <=1 && !doxferlog)
3485 		return;
3486 
3487 	r1 = r2 = NULL;
3488 	if ((r1 = realpath(file1, realfile1)) == NULL)
3489 		r1 = file1;
3490 	if (file2 != NULL)
3491 		if ((r2 = realpath(file2, realfile2)) == NULL)
3492 			r2 = file2;
3493 
3494 		/*
3495 		 * syslog command
3496 		 */
3497 	if (logging > 1) {
3498 		len = snprintf(buf, sizeof(buf), "%s %s", command, r1);
3499 		if (bytes != (off_t)-1)
3500 			len += snprintf(buf + len, sizeof(buf) - len,
3501 			    " = " LLF " byte%s", (LLT) bytes, PLURAL(bytes));
3502 		else if (r2 != NULL)
3503 			len += snprintf(buf + len, sizeof(buf) - len,
3504 			    " %s", r2);
3505 		if (elapsed != NULL)
3506 			len += snprintf(buf + len, sizeof(buf) - len,
3507 			    " in %ld.%.03d seconds", elapsed->tv_sec,
3508 			    (int)(elapsed->tv_usec / 1000));
3509 		if (error != NULL)
3510 			len += snprintf(buf + len, sizeof(buf) - len,
3511 			    ": %s", error);
3512 		syslog(LOG_INFO, "%s", buf);
3513 	}
3514 
3515 		/*
3516 		 * syslog wu-ftpd style log entry, prefixed with "xferlog: "
3517 		 */
3518 	if (!doxferlog || bytes == -1)
3519 		return;
3520 
3521 	if (strcmp(command, "get") == 0)
3522 		direction = 'o';
3523 	else if (strcmp(command, "put") == 0 || strcmp(command, "append") == 0)
3524 		direction = 'i';
3525 	else
3526 		return;
3527 
3528 	time(&now);
3529 	len = snprintf(buf, sizeof(buf),
3530 	    "%.24s %ld %s " LLF " %s %c %s %c %c %s FTP 0 * %c\n",
3531 
3532 /*
3533  * XXX: wu-ftpd puts ' (send)' or ' (recv)' in the syslog message, and removes
3534  *	the full date.  This may be problematic for accurate log parsing,
3535  *	given that syslog messages don't contain the full date.
3536  */
3537 	    ctime(&now),
3538 	    elapsed == NULL ? 0 : elapsed->tv_sec + (elapsed->tv_usec > 0),
3539 	    remotehost,
3540 	    (LLT) bytes,
3541 	    r1,
3542 	    type == TYPE_A ? 'a' : 'b',
3543 	    "_",		/* XXX: take conversions into account? */
3544 	    direction,
3545 
3546 	    curclass.type == CLASS_GUEST ?  'a' :
3547 	    curclass.type == CLASS_CHROOT ? 'g' :
3548 	    curclass.type == CLASS_REAL ?   'r' : '?',
3549 
3550 	    curclass.type == CLASS_GUEST ? pw->pw_passwd : pw->pw_name,
3551 	    error != NULL ? 'i' : 'c'
3552 	    );
3553 
3554 	if ((doxferlog & 2) && xferlogfd != -1)
3555 		write(xferlogfd, buf, len);
3556 	if ((doxferlog & 1)) {
3557 		buf[len-1] = '\n';	/* strip \n from syslog message */
3558 		syslog(LOG_INFO, "xferlog: %s", buf);
3559 	}
3560 }
3561 
3562 /*
3563  * Log the resource usage.
3564  *
3565  * XXX: more resource usage to logging?
3566  */
3567 void
3568 logrusage(const struct rusage *rusage_before,
3569     const struct rusage *rusage_after)
3570 {
3571 	struct timeval usrtime, systime;
3572 
3573 	if (logging <= 1)
3574 		return;
3575 
3576 	timersub(&rusage_after->ru_utime, &rusage_before->ru_utime, &usrtime);
3577 	timersub(&rusage_after->ru_stime, &rusage_before->ru_stime, &systime);
3578 	syslog(LOG_INFO, "%ld.%.03du %ld.%.03ds %ld+%ldio %ldpf+%ldw",
3579 	    usrtime.tv_sec, (int)(usrtime.tv_usec / 1000),
3580 	    systime.tv_sec, (int)(systime.tv_usec / 1000),
3581 	    rusage_after->ru_inblock - rusage_before->ru_inblock,
3582 	    rusage_after->ru_oublock - rusage_before->ru_oublock,
3583 	    rusage_after->ru_majflt - rusage_before->ru_majflt,
3584 	    rusage_after->ru_nswap - rusage_before->ru_nswap);
3585 }
3586 
3587 /*
3588  * Determine if `password' is valid for user given in `pw'.
3589  * Returns 2 if password expired, 1 if otherwise failed, 0 if ok
3590  */
3591 int
3592 checkpassword(const struct passwd *pwent, const char *password)
3593 {
3594 	char	*orig, *new;
3595 	time_t	 change, expire, now;
3596 
3597 	change = expire = 0;
3598 	if (pwent == NULL)
3599 		return 1;
3600 
3601 	time(&now);
3602 	orig = pwent->pw_passwd;	/* save existing password */
3603 	expire = pwent->pw_expire;
3604 	change = (pwent->pw_change == _PASSWORD_CHGNOW)? now : pwent->pw_change;
3605 
3606 	if (orig[0] == '\0')		/* don't allow empty passwords */
3607 		return 1;
3608 
3609 	new = crypt(password, orig);	/* encrypt given password */
3610 	if (strcmp(new, orig) != 0)	/* compare */
3611 		return 1;
3612 
3613 	if ((expire && now >= expire) || (change && now >= change))
3614 		return 2;		/* check if expired */
3615 
3616 	return 0;			/* OK! */
3617 }
3618 
3619 char *
3620 xstrdup(const char *s)
3621 {
3622 	char *new = strdup(s);
3623 
3624 	if (new == NULL)
3625 		fatal("Local resource failure: malloc");
3626 		/* NOTREACHED */
3627 	return (new);
3628 }
3629 
3630 /*
3631  * As per fprintf(), but increment total_bytes and total_bytes_out,
3632  * by the appropriate amount.
3633  */
3634 void
3635 cprintf(FILE *fd, const char *fmt, ...)
3636 {
3637 	off_t b;
3638 	va_list ap;
3639 
3640 	va_start(ap, fmt);
3641 	b = vfprintf(fd, fmt, ap);
3642 	va_end(ap);
3643 	total_bytes += b;
3644 	total_bytes_out += b;
3645 }
3646 
3647 #ifdef USE_PAM
3648 /*
3649  * the following code is stolen from imap-uw PAM authentication module and
3650  * login.c
3651  */
3652 #define COPY_STRING(s) (s ? strdup(s) : NULL)
3653 
3654 struct cred_t {
3655 	const char *uname;		/* user name */
3656 	const char *pass;		/* password */
3657 };
3658 typedef struct cred_t cred_t;
3659 
3660 static int
3661 auth_conv(int num_msg, const struct pam_message **msg,
3662     struct pam_response **resp, void *appdata)
3663 {
3664 	int i;
3665 	cred_t *cred = (cred_t *) appdata;
3666 	struct pam_response *myreply;
3667 
3668 	myreply = calloc(num_msg, sizeof *myreply);
3669 	if (myreply == NULL)
3670 		return PAM_BUF_ERR;
3671 
3672 	for (i = 0; i < num_msg; i++) {
3673 		switch (msg[i]->msg_style) {
3674 		case PAM_PROMPT_ECHO_ON:	/* assume want user name */
3675 			myreply[i].resp_retcode = PAM_SUCCESS;
3676 			myreply[i].resp = COPY_STRING(cred->uname);
3677 			/* PAM frees resp. */
3678 			break;
3679 		case PAM_PROMPT_ECHO_OFF:	/* assume want password */
3680 			myreply[i].resp_retcode = PAM_SUCCESS;
3681 			myreply[i].resp = COPY_STRING(cred->pass);
3682 			/* PAM frees resp. */
3683 			break;
3684 		case PAM_TEXT_INFO:
3685 		case PAM_ERROR_MSG:
3686 			myreply[i].resp_retcode = PAM_SUCCESS;
3687 			myreply[i].resp = NULL;
3688 			break;
3689 		default:			/* unknown message style */
3690 			free(myreply);
3691 			return PAM_CONV_ERR;
3692 		}
3693 	}
3694 
3695 	*resp = myreply;
3696 	return PAM_SUCCESS;
3697 }
3698 
3699 /*
3700  * Attempt to authenticate the user using PAM.  Returns 0 if the user is
3701  * authenticated, or 1 if not authenticated.  If some sort of PAM system
3702  * error occurs (e.g., the "/etc/pam.conf" file is missing) then this
3703  * function returns -1.  This can be used as an indication that we should
3704  * fall back to a different authentication mechanism.
3705  */
3706 static int
3707 auth_pam(struct passwd **ppw, const char *pwstr)
3708 {
3709 	const char *tmpl_user;
3710 	const void *item;
3711 	int rval;
3712 	int e;
3713 	cred_t auth_cred = { (*ppw)->pw_name, pwstr };
3714 	struct pam_conv conv = { &auth_conv, &auth_cred };
3715 
3716 	e = pam_start("ftpd", (*ppw)->pw_name, &conv, &pamh);
3717 	if (e != PAM_SUCCESS) {
3718 		/*
3719 		 * In OpenPAM, it's OK to pass NULL to pam_strerror()
3720 		 * if context creation has failed in the first place.
3721 		 */
3722 		syslog(LOG_ERR, "pam_start: %s", pam_strerror(NULL, e));
3723 		return -1;
3724 	}
3725 
3726 	e = pam_set_item(pamh, PAM_RHOST, remotehost);
3727 	if (e != PAM_SUCCESS) {
3728 		syslog(LOG_ERR, "pam_set_item(PAM_RHOST): %s",
3729 			pam_strerror(pamh, e));
3730 		if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
3731 			syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
3732 		}
3733 		pamh = NULL;
3734 		return -1;
3735 	}
3736 
3737 	e = pam_authenticate(pamh, 0);
3738 	switch (e) {
3739 	case PAM_SUCCESS:
3740 		/*
3741 		 * With PAM we support the concept of a "template"
3742 		 * user.  The user enters a login name which is
3743 		 * authenticated by PAM, usually via a remote service
3744 		 * such as RADIUS or TACACS+.  If authentication
3745 		 * succeeds, a different but related "template" name
3746 		 * is used for setting the credentials, shell, and
3747 		 * home directory.  The name the user enters need only
3748 		 * exist on the remote authentication server, but the
3749 		 * template name must be present in the local password
3750 		 * database.
3751 		 *
3752 		 * This is supported by two various mechanisms in the
3753 		 * individual modules.  However, from the application's
3754 		 * point of view, the template user is always passed
3755 		 * back as a changed value of the PAM_USER item.
3756 		 */
3757 		if ((e = pam_get_item(pamh, PAM_USER, &item)) ==
3758 		    PAM_SUCCESS) {
3759 			tmpl_user = (const char *) item;
3760 			if (strcmp((*ppw)->pw_name, tmpl_user) != 0)
3761 				*ppw = sgetpwnam(tmpl_user);
3762 		} else
3763 			syslog(LOG_ERR, "Couldn't get PAM_USER: %s",
3764 			    pam_strerror(pamh, e));
3765 		rval = 0;
3766 		break;
3767 
3768 	case PAM_AUTH_ERR:
3769 	case PAM_USER_UNKNOWN:
3770 	case PAM_MAXTRIES:
3771 		rval = 1;
3772 		break;
3773 
3774 	default:
3775 		syslog(LOG_ERR, "pam_authenticate: %s", pam_strerror(pamh, e));
3776 		rval = -1;
3777 		break;
3778 	}
3779 
3780 	if (rval == 0) {
3781 		e = pam_acct_mgmt(pamh, 0);
3782 		if (e != PAM_SUCCESS) {
3783 			syslog(LOG_ERR, "pam_acct_mgmt: %s",
3784 						pam_strerror(pamh, e));
3785 			rval = 1;
3786 		}
3787 	}
3788 
3789 	if (rval != 0) {
3790 		if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
3791 			syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
3792 		}
3793 		pamh = NULL;
3794 	}
3795 	return rval;
3796 }
3797 
3798 #endif /* USE_PAM */
3799