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