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