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