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