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