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