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