xref: /freebsd/libexec/ftpd/ftpd.c (revision 0b87f79976047c8f4332bbf7dc03146f6b0de79f)
1 /*
2  * Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 #if 0
35 #ifndef lint
36 static char copyright[] =
37 "@(#) Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994\n\
38 	The Regents of the University of California.  All rights reserved.\n";
39 #endif /* not lint */
40 #endif
41 
42 #ifndef lint
43 #if 0
44 static char sccsid[] = "@(#)ftpd.c	8.4 (Berkeley) 4/16/94";
45 #endif
46 static const char rcsid[] =
47   "$FreeBSD$";
48 #endif /* not lint */
49 
50 /*
51  * FTP server.
52  */
53 #include <sys/param.h>
54 #include <sys/ioctl.h>
55 #include <sys/mman.h>
56 #include <sys/socket.h>
57 #include <sys/stat.h>
58 #include <sys/time.h>
59 #include <sys/wait.h>
60 
61 #include <netinet/in.h>
62 #include <netinet/in_systm.h>
63 #include <netinet/ip.h>
64 #include <netinet/tcp.h>
65 
66 #define	FTP_NAMES
67 #include <arpa/ftp.h>
68 #include <arpa/inet.h>
69 #include <arpa/telnet.h>
70 
71 #include <ctype.h>
72 #include <dirent.h>
73 #include <err.h>
74 #include <errno.h>
75 #include <fcntl.h>
76 #include <glob.h>
77 #include <limits.h>
78 #include <netdb.h>
79 #include <pwd.h>
80 #include <grp.h>
81 #include <opie.h>
82 #include <signal.h>
83 #include <stdio.h>
84 #include <stdlib.h>
85 #include <string.h>
86 #include <syslog.h>
87 #include <time.h>
88 #include <unistd.h>
89 #include <libutil.h>
90 #ifdef	LOGIN_CAP
91 #include <login_cap.h>
92 #endif
93 
94 #ifdef USE_PAM
95 #include <security/pam_appl.h>
96 #endif
97 
98 #include "pathnames.h"
99 #include "extern.h"
100 
101 #include <stdarg.h>
102 
103 static char version[] = "Version 6.00LS";
104 #undef main
105 
106 extern	off_t restart_point;
107 extern	char cbuf[];
108 
109 union sockunion server_addr;
110 union sockunion ctrl_addr;
111 union sockunion data_source;
112 union sockunion data_dest;
113 union sockunion his_addr;
114 union sockunion pasv_addr;
115 
116 int	daemon_mode;
117 int	data;
118 int	logged_in;
119 struct	passwd *pw;
120 int	ftpdebug;
121 int	timeout = 900;    /* timeout after 15 minutes of inactivity */
122 int	maxtimeout = 7200;/* don't allow idle time to be set beyond 2 hours */
123 int	logging;
124 int	restricted_data_ports = 1;
125 int	paranoid = 1;	  /* be extra careful about security */
126 int	anon_only = 0;    /* Only anonymous ftp allowed */
127 int	guest;
128 int	dochroot;
129 int	stats;
130 int	statfd = -1;
131 int	type;
132 int	form;
133 int	stru;			/* avoid C keyword */
134 int	mode;
135 int	usedefault = 1;		/* for data transfers */
136 int	pdata = -1;		/* for passive mode */
137 int	readonly=0;		/* Server is in readonly mode.	*/
138 int	noepsv=0;		/* EPSV command is disabled.	*/
139 int	noretr=0;		/* RETR command is disabled.	*/
140 int	noguestretr=0;		/* RETR command is disabled for anon users. */
141 int	noguestmkd=0;		/* MKD command is disabled for anon users. */
142 
143 static volatile sig_atomic_t recvurg;
144 sig_atomic_t transflag;
145 off_t	file_size;
146 off_t	byte_count;
147 #if !defined(CMASK) || CMASK == 0
148 #undef CMASK
149 #define CMASK 027
150 #endif
151 int	defumask = CMASK;		/* default umask value */
152 char	tmpline[7];
153 char	*hostname;
154 int	epsvall = 0;
155 
156 #ifdef VIRTUAL_HOSTING
157 char	*ftpuser;
158 
159 static struct ftphost {
160 	struct ftphost	*next;
161 	struct addrinfo *hostinfo;
162 	char		*hostname;
163 	char		*anonuser;
164 	char		*statfile;
165 	char		*welcome;
166 	char		*loginmsg;
167 } *thishost, *firsthost;
168 
169 #endif
170 char	remotehost[MAXHOSTNAMELEN];
171 char	*ident = NULL;
172 
173 static char ttyline[20];
174 char	*tty = ttyline;		/* for klogin */
175 
176 #ifdef USE_PAM
177 static int	auth_pam(struct passwd**, const char*);
178 pam_handle_t *pamh = NULL;
179 #endif
180 
181 static struct opie opiedata;
182 static char opieprompt[OPIE_CHALLENGE_MAX+1];
183 static int pwok;
184 
185 char	*pid_file = NULL;
186 
187 /*
188  * Limit number of pathnames that glob can return.
189  * A limit of 0 indicates the number of pathnames is unlimited.
190  */
191 #define MAXGLOBARGS	16384
192 #
193 
194 /*
195  * Timeout intervals for retrying connections
196  * to hosts that don't accept PORT cmds.  This
197  * is a kludge, but given the problems with TCP...
198  */
199 #define	SWAITMAX	90	/* wait at most 90 seconds */
200 #define	SWAITINT	5	/* interval between retries */
201 
202 int	swaitmax = SWAITMAX;
203 int	swaitint = SWAITINT;
204 
205 #ifdef SETPROCTITLE
206 #ifdef OLD_SETPROCTITLE
207 char	**Argv = NULL;		/* pointer to argument vector */
208 char	*LastArgv = NULL;	/* end of argv */
209 #endif /* OLD_SETPROCTITLE */
210 char	proctitle[LINE_MAX];	/* initial part of title */
211 #endif /* SETPROCTITLE */
212 
213 #define LOGCMD(cmd, file) \
214 	if (logging > 1) \
215 	    syslog(LOG_INFO,"%s %s%s", cmd, \
216 		*(file) == '/' ? "" : curdir(), file);
217 #define LOGCMD2(cmd, file1, file2) \
218 	 if (logging > 1) \
219 	    syslog(LOG_INFO,"%s %s%s %s%s", cmd, \
220 		*(file1) == '/' ? "" : curdir(), file1, \
221 		*(file2) == '/' ? "" : curdir(), file2);
222 #define LOGBYTES(cmd, file, cnt) \
223 	if (logging > 1) { \
224 		if (cnt == (off_t)-1) \
225 		    syslog(LOG_INFO,"%s %s%s", cmd, \
226 			*(file) == '/' ? "" : curdir(), file); \
227 		else \
228 		    syslog(LOG_INFO, "%s %s%s = %qd bytes", \
229 			cmd, (*(file) == '/') ? "" : curdir(), file, cnt); \
230 	}
231 
232 #ifdef VIRTUAL_HOSTING
233 static void	 inithosts(void);
234 static void	selecthost(union sockunion *);
235 #endif
236 static void	 ack(char *);
237 static void	 sigurg(int);
238 static void	 myoob(void);
239 static int	 checkuser(char *, char *, int);
240 static FILE	*dataconn(char *, off_t, char *);
241 static void	 dolog(struct sockaddr *);
242 static char	*curdir(void);
243 static void	 end_login(void);
244 static FILE	*getdatasock(char *);
245 static char	*gunique(char *);
246 static void	 lostconn(int);
247 static void	 sigquit(int);
248 static int	 receive_data(FILE *, FILE *);
249 static int	 send_data(FILE *, FILE *, off_t, off_t, int);
250 static struct passwd *
251 		 sgetpwnam(char *);
252 static char	*sgetsave(char *);
253 static void	 reapchild(int);
254 static void      logxfer(char *, off_t, time_t);
255 
256 static char *
257 curdir(void)
258 {
259 	static char path[MAXPATHLEN+1+1];	/* path + '/' + '\0' */
260 
261 	if (getcwd(path, sizeof(path)-2) == NULL)
262 		return ("");
263 	if (path[1] != '\0')		/* special case for root dir. */
264 		strcat(path, "/");
265 	/* For guest account, skip / since it's chrooted */
266 	return (guest ? path+1 : path);
267 }
268 
269 int
270 main(int argc, char *argv[], char **envp)
271 {
272 	int addrlen, ch, on = 1, tos;
273 	char *cp, line[LINE_MAX];
274 	FILE *fd;
275 	int error;
276 	char	*bindname = NULL;
277 	int	family = AF_UNSPEC;
278 	int	enable_v4 = 0;
279 	struct sigaction sa;
280 
281 	tzset();		/* in case no timezone database in ~ftp */
282 	sigemptyset(&sa.sa_mask);
283 	sa.sa_flags = SA_RESTART;
284 
285 #ifdef OLD_SETPROCTITLE
286 	/*
287 	 *  Save start and extent of argv for setproctitle.
288 	 */
289 	Argv = argv;
290 	while (*envp)
291 		envp++;
292 	LastArgv = envp[-1] + strlen(envp[-1]);
293 #endif /* OLD_SETPROCTITLE */
294 
295 
296 	while ((ch = getopt(argc, argv, "AdlDESURrt:T:u:vMOoa:p:46")) != -1) {
297 		switch (ch) {
298 		case 'D':
299 			daemon_mode++;
300 			break;
301 
302 		case 'd':
303 			ftpdebug++;
304 			break;
305 
306 		case 'E':
307 			noepsv = 1;
308 			break;
309 
310 		case 'l':
311 			logging++;	/* > 1 == extra logging */
312 			break;
313 
314 		case 'r':
315 			readonly = 1;
316 			break;
317 
318 		case 'R':
319 			paranoid = 0;
320 			break;
321 
322 		case 'S':
323 			stats++;
324 			break;
325 
326 		case 'T':
327 			maxtimeout = atoi(optarg);
328 			if (timeout > maxtimeout)
329 				timeout = maxtimeout;
330 			break;
331 
332 		case 't':
333 			timeout = atoi(optarg);
334 			if (maxtimeout < timeout)
335 				maxtimeout = timeout;
336 			break;
337 
338 		case 'U':
339 			restricted_data_ports = 0;
340 			break;
341 
342 		case 'a':
343 			bindname = optarg;
344 			break;
345 
346 		case 'p':
347 			pid_file = optarg;
348 			break;
349 
350 		case 'u':
351 		    {
352 			long val = 0;
353 
354 			val = strtol(optarg, &optarg, 8);
355 			if (*optarg != '\0' || val < 0)
356 				warnx("bad value for -u");
357 			else
358 				defumask = val;
359 			break;
360 		    }
361 		case 'A':
362 			anon_only = 1;
363 			break;
364 
365 		case 'v':
366 			ftpdebug = 1;
367 			break;
368 
369 		case '4':
370 			enable_v4 = 1;
371 			if (family == AF_UNSPEC)
372 				family = AF_INET;
373 			break;
374 
375 		case '6':
376 			family = AF_INET6;
377 			break;
378 
379 		case 'M':
380 			noguestmkd = 1;
381 			break;
382 
383 		case 'O':
384 			noguestretr = 1;
385 			break;
386 
387 		case 'o':
388 			noretr = 1;
389 			break;
390 
391 		default:
392 			warnx("unknown flag -%c ignored", optopt);
393 			break;
394 		}
395 	}
396 
397 #ifdef VIRTUAL_HOSTING
398 	inithosts();
399 #endif
400 	(void) freopen(_PATH_DEVNULL, "w", stderr);
401 
402 	/*
403 	 * LOG_NDELAY sets up the logging connection immediately,
404 	 * necessary for anonymous ftp's that chroot and can't do it later.
405 	 */
406 	openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
407 
408 	if (daemon_mode) {
409 		int ctl_sock, fd;
410 		struct addrinfo hints, *res;
411 
412 		/*
413 		 * Detach from parent.
414 		 */
415 		if (daemon(1, 1) < 0) {
416 			syslog(LOG_ERR, "failed to become a daemon");
417 			exit(1);
418 		}
419 		sa.sa_handler = reapchild;
420 		(void)sigaction(SIGCHLD, &sa, NULL);
421 		/* init bind_sa */
422 		memset(&hints, 0, sizeof(hints));
423 
424 		hints.ai_family = family == AF_UNSPEC ? AF_INET : family;
425 		hints.ai_socktype = SOCK_STREAM;
426 		hints.ai_protocol = 0;
427 		hints.ai_flags = AI_PASSIVE;
428 		error = getaddrinfo(bindname, "ftp", &hints, &res);
429 		if (error) {
430 			if (family == AF_UNSPEC) {
431 				hints.ai_family = AF_UNSPEC;
432 				error = getaddrinfo(bindname, "ftp", &hints,
433 						    &res);
434 			}
435 		}
436 		if (error) {
437 			syslog(LOG_ERR, "%s", gai_strerror(error));
438 			if (error == EAI_SYSTEM)
439 				syslog(LOG_ERR, "%s", strerror(errno));
440 			exit(1);
441 		}
442 		if (res->ai_addr == NULL) {
443 			syslog(LOG_ERR, "-a %s: getaddrinfo failed", hostname);
444 			exit(1);
445 		} else
446 			family = res->ai_addr->sa_family;
447 		/*
448 		 * Open a socket, bind it to the FTP port, and start
449 		 * listening.
450 		 */
451 		ctl_sock = socket(family, SOCK_STREAM, 0);
452 		if (ctl_sock < 0) {
453 			syslog(LOG_ERR, "control socket: %m");
454 			exit(1);
455 		}
456 		if (setsockopt(ctl_sock, SOL_SOCKET, SO_REUSEADDR,
457 		    (char *)&on, sizeof(on)) < 0)
458 			syslog(LOG_ERR, "control setsockopt: %m");
459 #ifdef IPV6_BINDV6ONLY
460 		if (family == AF_INET6 && enable_v4 == 0) {
461 			if (setsockopt(ctl_sock, IPPROTO_IPV6, IPV6_BINDV6ONLY,
462 				       (char *)&on, sizeof (on)) < 0)
463 				syslog(LOG_ERR,
464 				       "control setsockopt(IPV6_BINDV6ONLY): %m");
465 		}
466 #endif /* IPV6_BINDV6ONLY */
467 		memcpy(&server_addr, res->ai_addr, res->ai_addr->sa_len);
468 		if (bind(ctl_sock, (struct sockaddr *)&server_addr,
469 			 server_addr.su_len) < 0) {
470 			syslog(LOG_ERR, "control bind: %m");
471 			exit(1);
472 		}
473 		if (listen(ctl_sock, 32) < 0) {
474 			syslog(LOG_ERR, "control listen: %m");
475 			exit(1);
476 		}
477 		/*
478 		 * Atomically write process ID
479 		 */
480 		if (pid_file)
481 		{
482 			int fd;
483 			char buf[20];
484 
485 			fd = open(pid_file, O_CREAT | O_WRONLY | O_TRUNC
486 				| O_NONBLOCK | O_EXLOCK, 0644);
487 			if (fd < 0) {
488 				if (errno == EAGAIN)
489 					errx(1, "%s: file locked", pid_file);
490 				else
491 					err(1, "%s", pid_file);
492 			}
493 			snprintf(buf, sizeof(buf),
494 				"%lu\n", (unsigned long) getpid());
495 			if (write(fd, buf, strlen(buf)) < 0)
496 				err(1, "%s: write", pid_file);
497 			/* Leave the pid file open and locked */
498 		}
499 		/*
500 		 * Loop forever accepting connection requests and forking off
501 		 * children to handle them.
502 		 */
503 		while (1) {
504 			addrlen = server_addr.su_len;
505 			fd = accept(ctl_sock, (struct sockaddr *)&his_addr, &addrlen);
506 			if (fork() == 0) {
507 				/* child */
508 				(void) dup2(fd, 0);
509 				(void) dup2(fd, 1);
510 				close(ctl_sock);
511 				break;
512 			}
513 			close(fd);
514 		}
515 	} else {
516 		addrlen = sizeof(his_addr);
517 		if (getpeername(0, (struct sockaddr *)&his_addr, &addrlen) < 0) {
518 			syslog(LOG_ERR, "getpeername (%s): %m",argv[0]);
519 			exit(1);
520 		}
521 	}
522 
523 	sa.sa_handler = SIG_DFL;
524 	(void)sigaction(SIGCHLD, &sa, NULL);
525 
526 	sa.sa_handler = sigurg;
527 	sa.sa_flags = 0;		/* don't restart syscalls for SIGURG */
528 	(void)sigaction(SIGURG, &sa, NULL);
529 
530 	sigfillset(&sa.sa_mask);	/* block all signals in handler */
531 	sa.sa_flags = SA_RESTART;
532 	sa.sa_handler = sigquit;
533 	(void)sigaction(SIGHUP, &sa, NULL);
534 	(void)sigaction(SIGINT, &sa, NULL);
535 	(void)sigaction(SIGQUIT, &sa, NULL);
536 	(void)sigaction(SIGTERM, &sa, NULL);
537 
538 	sa.sa_handler = lostconn;
539 	(void)sigaction(SIGPIPE, &sa, NULL);
540 
541 	addrlen = sizeof(ctrl_addr);
542 	if (getsockname(0, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) {
543 		syslog(LOG_ERR, "getsockname (%s): %m",argv[0]);
544 		exit(1);
545 	}
546 #ifdef VIRTUAL_HOSTING
547 	/* select our identity from virtual host table */
548 	selecthost(&ctrl_addr);
549 #endif
550 #ifdef IP_TOS
551 	if (ctrl_addr.su_family == AF_INET)
552       {
553 	tos = IPTOS_LOWDELAY;
554 	if (setsockopt(0, IPPROTO_IP, IP_TOS, (char *)&tos, sizeof(int)) < 0)
555 		syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
556       }
557 #endif
558 	/*
559 	 * Disable Nagle on the control channel so that we don't have to wait
560 	 * for peer's ACK before issuing our next reply.
561 	 */
562 	if (setsockopt(0, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) < 0)
563 		syslog(LOG_WARNING, "control setsockopt TCP_NODELAY: %m");
564 
565 	data_source.su_port = htons(ntohs(ctrl_addr.su_port) - 1);
566 
567 	/* set this here so klogin can use it... */
568 	(void)snprintf(ttyline, sizeof(ttyline), "ftp%d", getpid());
569 
570 	/* Try to handle urgent data inline */
571 #ifdef SO_OOBINLINE
572 	if (setsockopt(0, SOL_SOCKET, SO_OOBINLINE, (char *)&on, sizeof(on)) < 0)
573 		syslog(LOG_ERR, "setsockopt: %m");
574 #endif
575 
576 #ifdef	F_SETOWN
577 	if (fcntl(fileno(stdin), F_SETOWN, getpid()) == -1)
578 		syslog(LOG_ERR, "fcntl F_SETOWN: %m");
579 #endif
580 	dolog((struct sockaddr *)&his_addr);
581 	/*
582 	 * Set up default state
583 	 */
584 	data = -1;
585 	type = TYPE_A;
586 	form = FORM_N;
587 	stru = STRU_F;
588 	mode = MODE_S;
589 	tmpline[0] = '\0';
590 
591 	/* If logins are disabled, print out the message. */
592 	if ((fd = fopen(_PATH_NOLOGIN,"r")) != NULL) {
593 		while (fgets(line, sizeof(line), fd) != NULL) {
594 			if ((cp = strchr(line, '\n')) != NULL)
595 				*cp = '\0';
596 			lreply(530, "%s", line);
597 		}
598 		(void) fflush(stdout);
599 		(void) fclose(fd);
600 		reply(530, "System not available.");
601 		exit(0);
602 	}
603 #ifdef VIRTUAL_HOSTING
604 	if ((fd = fopen(thishost->welcome, "r")) != NULL) {
605 #else
606 	if ((fd = fopen(_PATH_FTPWELCOME, "r")) != NULL) {
607 #endif
608 		while (fgets(line, sizeof(line), fd) != NULL) {
609 			if ((cp = strchr(line, '\n')) != NULL)
610 				*cp = '\0';
611 			lreply(220, "%s", line);
612 		}
613 		(void) fflush(stdout);
614 		(void) fclose(fd);
615 		/* reply(220,) must follow */
616 	}
617 #ifndef VIRTUAL_HOSTING
618 	if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
619 		fatalerror("Ran out of memory.");
620 	(void) gethostname(hostname, MAXHOSTNAMELEN - 1);
621 	hostname[MAXHOSTNAMELEN - 1] = '\0';
622 #endif
623 	reply(220, "%s FTP server (%s) ready.", hostname, version);
624 	for (;;)
625 		(void) yyparse();
626 	/* NOTREACHED */
627 }
628 
629 static void
630 lostconn(int signo)
631 {
632 
633 	if (ftpdebug)
634 		syslog(LOG_DEBUG, "lost connection");
635 	dologout(1);
636 }
637 
638 static void
639 sigquit(int signo)
640 {
641 
642 	syslog(LOG_ERR, "got signal %d", signo);
643 	dologout(1);
644 }
645 
646 #ifdef VIRTUAL_HOSTING
647 /*
648  * read in virtual host tables (if they exist)
649  */
650 
651 static void
652 inithosts(void)
653 {
654 	int insert;
655 	size_t len;
656 	FILE *fp;
657 	char *cp, *mp, *line;
658 	char *hostname;
659 	char *vhost, *anonuser, *statfile, *welcome, *loginmsg;
660 	struct ftphost *hrp, *lhrp;
661 	struct addrinfo hints, *res, *ai;
662 
663 	/*
664 	 * Fill in the default host information
665 	 */
666 	if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
667 		fatalerror("Ran out of memory.");
668 	if (gethostname(hostname, MAXHOSTNAMELEN) < 0)
669 		hostname[0] = '\0';
670 	hostname[MAXHOSTNAMELEN - 1] = '\0';
671 	if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
672 		fatalerror("Ran out of memory.");
673 	hrp->hostname = hostname;
674 	hrp->hostinfo = NULL;
675 
676 	memset(&hints, 0, sizeof(hints));
677 	hints.ai_flags = AI_CANONNAME;
678 	hints.ai_family = AF_UNSPEC;
679 	getaddrinfo(hrp->hostname, NULL, &hints, &res);
680 	if (res)
681 		hrp->hostinfo = res;
682 	hrp->statfile = _PATH_FTPDSTATFILE;
683 	hrp->welcome  = _PATH_FTPWELCOME;
684 	hrp->loginmsg = _PATH_FTPLOGINMESG;
685 	hrp->anonuser = "ftp";
686 	hrp->next = NULL;
687 	thishost = firsthost = lhrp = hrp;
688 	if ((fp = fopen(_PATH_FTPHOSTS, "r")) != NULL) {
689 		int addrsize, error, gothost;
690 		void *addr;
691 		struct hostent *hp;
692 
693 		while ((line = fgetln(fp, &len)) != NULL) {
694 			int	i, hp_error;
695 
696 			/* skip comments */
697 			if (line[0] == '#')
698 				continue;
699 			if (line[len - 1] == '\n') {
700 				line[len - 1] = '\0';
701 				mp = NULL;
702 			} else {
703 				if ((mp = malloc(len + 1)) == NULL)
704 					fatalerror("Ran out of memory.");
705 				memcpy(mp, line, len);
706 				mp[len] = '\0';
707 				line = mp;
708 			}
709 			cp = strtok(line, " \t");
710 			/* skip empty lines */
711 			if (cp == NULL)
712 				goto nextline;
713 			vhost = cp;
714 
715 			/* set defaults */
716 			anonuser = "ftp";
717 			statfile = _PATH_FTPDSTATFILE;
718 			welcome  = _PATH_FTPWELCOME;
719 			loginmsg = _PATH_FTPLOGINMESG;
720 
721 			/*
722 			 * Preparse the line so we can use its info
723 			 * for all the addresses associated with
724 			 * the virtual host name.
725 			 * Field 0, the virtual host name, is special:
726 			 * it's already parsed off and will be strdup'ed
727 			 * later, after we know its canonical form.
728 			 */
729 			for (i = 1; i < 5 && (cp = strtok(NULL, " \t")); i++)
730 				if (*cp != '-' && (cp = strdup(cp)))
731 					switch (i) {
732 					case 1:	/* anon user permissions */
733 						anonuser = cp;
734 						break;
735 					case 2: /* statistics file */
736 						statfile = cp;
737 						break;
738 					case 3: /* welcome message */
739 						welcome  = cp;
740 						break;
741 					case 4: /* login message */
742 						loginmsg = cp;
743 						break;
744 					default: /* programming error */
745 						abort();
746 						/* NOTREACHED */
747 					}
748 
749 			hints.ai_flags = 0;
750 			hints.ai_family = AF_UNSPEC;
751 			hints.ai_flags = AI_PASSIVE;
752 			error = getaddrinfo(vhost, NULL, &hints, &res);
753 			if (error != NULL)
754 				goto nextline;
755 			for (ai = res; ai != NULL && ai->ai_addr != NULL;
756 			     ai = ai->ai_next) {
757 
758 			gothost = 0;
759 			for (hrp = firsthost; hrp != NULL; hrp = hrp->next) {
760 				struct addrinfo *hi;
761 
762 				for (hi = hrp->hostinfo; hi != NULL;
763 				     hi = hi->ai_next)
764 					if (hi->ai_addrlen == ai->ai_addrlen &&
765 					    memcmp(hi->ai_addr,
766 						   ai->ai_addr,
767 						   ai->ai_addr->sa_len) == 0) {
768 						gothost++;
769 						break;
770 					}
771 				if (gothost)
772 					break;
773 			}
774 			if (hrp == NULL) {
775 				if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
776 					goto nextline;
777 				insert = 1;
778 			} else
779 				insert = 0; /* host already in the chain */
780 			hrp->hostinfo = res;
781 
782 			/*
783 			 * determine hostname to use.
784 			 * force defined name if there is a valid alias
785 			 * otherwise fallback to primary hostname
786 			 */
787 			/* XXX: getaddrinfo() can't do alias check */
788 			switch(hrp->hostinfo->ai_family) {
789 			case AF_INET:
790 				addr = &((struct sockaddr_in *)hrp->hostinfo->ai_addr)->sin_addr;
791 				addrsize = sizeof(struct in_addr);
792 				break;
793 			case AF_INET6:
794 				addr = &((struct sockaddr_in6 *)hrp->hostinfo->ai_addr)->sin6_addr;
795 				addrsize = sizeof(struct in6_addr);
796 				break;
797 			default:
798 				/* should not reach here */
799 				if (hrp->hostinfo != NULL)
800 					freeaddrinfo(hrp->hostinfo);
801 				free(hrp);
802 				goto nextline;
803 				/* NOTREACHED */
804 			}
805 			if ((hp = getipnodebyaddr((char*)addr, addrsize,
806 						  hrp->hostinfo->ai_family,
807 						  &hp_error)) != NULL) {
808 				if (strcmp(vhost, hp->h_name) != 0) {
809 					if (hp->h_aliases == NULL)
810 						vhost = hp->h_name;
811 					else {
812 						i = 0;
813 						while (hp->h_aliases[i] &&
814 						       strcmp(vhost, hp->h_aliases[i]) != 0)
815 							++i;
816 						if (hp->h_aliases[i] == NULL)
817 							vhost = hp->h_name;
818 					}
819 				}
820 			}
821 			if ((hrp->hostname = strdup(vhost)) == NULL)
822 				goto nextline;
823 			hrp->anonuser = anonuser;
824 			hrp->statfile = statfile;
825 			hrp->welcome  = welcome;
826 			hrp->loginmsg = loginmsg;
827 			if (insert) {
828 				hrp->next  = NULL;
829 				lhrp->next = hrp;
830 				lhrp = hrp;
831 			}
832 			if (hp)
833 				freehostent(hp);
834 		      }
835 nextline:
836 			if (mp)
837 				free(mp);
838 		}
839 		(void) fclose(fp);
840 	}
841 }
842 
843 static void
844 selecthost(union sockunion *su)
845 {
846 	struct ftphost	*hrp;
847 	u_int16_t port;
848 #ifdef INET6
849 	struct in6_addr *mapped_in6 = NULL;
850 #endif
851 	struct addrinfo *hi;
852 
853 #ifdef INET6
854 	/*
855 	 * XXX IPv4 mapped IPv6 addr consideraton,
856 	 * specified in rfc2373.
857 	 */
858 	if (su->su_family == AF_INET6 &&
859 	    IN6_IS_ADDR_V4MAPPED(&su->su_sin6.sin6_addr))
860 		mapped_in6 = &su->su_sin6.sin6_addr;
861 #endif
862 
863 	hrp = thishost = firsthost;	/* default */
864 	port = su->su_port;
865 	su->su_port = 0;
866 	while (hrp != NULL) {
867 	    for (hi = hrp->hostinfo; hi != NULL; hi = hi->ai_next) {
868 		if (memcmp(su, hi->ai_addr, hi->ai_addrlen) == 0) {
869 			thishost = hrp;
870 			break;
871 		}
872 #ifdef INET6
873 		/* XXX IPv4 mapped IPv6 addr consideraton */
874 		if (hi->ai_addr->sa_family == AF_INET && mapped_in6 != NULL &&
875 		    (memcmp(&mapped_in6->s6_addr[12],
876 			    &((struct sockaddr_in *)hi->ai_addr)->sin_addr,
877 			    sizeof(struct in_addr)) == 0)) {
878 			thishost = hrp;
879 			break;
880 		}
881 #endif
882 	    }
883 	    hrp = hrp->next;
884 	}
885 	su->su_port = port;
886 	/* setup static variables as appropriate */
887 	hostname = thishost->hostname;
888 	ftpuser = thishost->anonuser;
889 }
890 #endif
891 
892 /*
893  * Helper function for sgetpwnam().
894  */
895 static char *
896 sgetsave(char *s)
897 {
898 	char *new = malloc((unsigned) strlen(s) + 1);
899 
900 	if (new == NULL) {
901 		perror_reply(421, "Local resource failure: malloc");
902 		dologout(1);
903 		/* NOTREACHED */
904 	}
905 	(void) strcpy(new, s);
906 	return (new);
907 }
908 
909 /*
910  * Save the result of a getpwnam.  Used for USER command, since
911  * the data returned must not be clobbered by any other command
912  * (e.g., globbing).
913  */
914 static struct passwd *
915 sgetpwnam(char *name)
916 {
917 	static struct passwd save;
918 	struct passwd *p;
919 
920 	if ((p = getpwnam(name)) == NULL)
921 		return (p);
922 	if (save.pw_name) {
923 		free(save.pw_name);
924 		free(save.pw_passwd);
925 		free(save.pw_gecos);
926 		free(save.pw_dir);
927 		free(save.pw_shell);
928 	}
929 	save = *p;
930 	save.pw_name = sgetsave(p->pw_name);
931 	save.pw_passwd = sgetsave(p->pw_passwd);
932 	save.pw_gecos = sgetsave(p->pw_gecos);
933 	save.pw_dir = sgetsave(p->pw_dir);
934 	save.pw_shell = sgetsave(p->pw_shell);
935 	return (&save);
936 }
937 
938 static int login_attempts;	/* number of failed login attempts */
939 static int askpasswd;		/* had user command, ask for passwd */
940 static char curname[MAXLOGNAME];	/* current USER name */
941 
942 /*
943  * USER command.
944  * Sets global passwd pointer pw if named account exists and is acceptable;
945  * sets askpasswd if a PASS command is expected.  If logged in previously,
946  * need to reset state.  If name is "ftp" or "anonymous", the name is not in
947  * _PATH_FTPUSERS, and ftp account exists, set guest and pw, then just return.
948  * If account doesn't exist, ask for passwd anyway.  Otherwise, check user
949  * requesting login privileges.  Disallow anyone who does not have a standard
950  * shell as returned by getusershell().  Disallow anyone mentioned in the file
951  * _PATH_FTPUSERS to allow people such as root and uucp to be avoided.
952  */
953 void
954 user(char *name)
955 {
956 	char *cp, *shell;
957 
958 	if (logged_in) {
959 		if (guest) {
960 			reply(530, "Can't change user from guest login.");
961 			return;
962 		} else if (dochroot) {
963 			reply(530, "Can't change user from chroot user.");
964 			return;
965 		}
966 		end_login();
967 	}
968 
969 	guest = 0;
970 	if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) {
971 		if (checkuser(_PATH_FTPUSERS, "ftp", 0) ||
972 		    checkuser(_PATH_FTPUSERS, "anonymous", 0))
973 			reply(530, "User %s access denied.", name);
974 #ifdef VIRTUAL_HOSTING
975 		else if ((pw = sgetpwnam(thishost->anonuser)) != NULL) {
976 #else
977 		else if ((pw = sgetpwnam("ftp")) != NULL) {
978 #endif
979 			guest = 1;
980 			askpasswd = 1;
981 			reply(331,
982 			"Guest login ok, send your email address as password.");
983 		} else
984 			reply(530, "User %s unknown.", name);
985 		if (!askpasswd && logging)
986 			syslog(LOG_NOTICE,
987 			    "ANONYMOUS FTP LOGIN REFUSED FROM %s", remotehost);
988 		return;
989 	}
990 	if (anon_only != 0) {
991 		reply(530, "Sorry, only anonymous ftp allowed.");
992 		return;
993 	}
994 
995 	if ((pw = sgetpwnam(name))) {
996 		if ((shell = pw->pw_shell) == NULL || *shell == 0)
997 			shell = _PATH_BSHELL;
998 		while ((cp = getusershell()) != NULL)
999 			if (strcmp(cp, shell) == 0)
1000 				break;
1001 		endusershell();
1002 
1003 		if (cp == NULL || checkuser(_PATH_FTPUSERS, name, 1)) {
1004 			reply(530, "User %s access denied.", name);
1005 			if (logging)
1006 				syslog(LOG_NOTICE,
1007 				    "FTP LOGIN REFUSED FROM %s, %s",
1008 				    remotehost, name);
1009 			pw = (struct passwd *) NULL;
1010 			return;
1011 		}
1012 	}
1013 	if (logging)
1014 		strncpy(curname, name, sizeof(curname)-1);
1015 
1016 	pwok = 0;
1017 #ifdef USE_PAM
1018 	/* XXX Kluge! The conversation mechanism needs to be fixed. */
1019 #endif
1020 	if (opiechallenge(&opiedata, name, opieprompt) == 0) {
1021 		pwok = (pw != NULL) &&
1022 		       opieaccessfile(remotehost) &&
1023 		       opiealways(pw->pw_dir);
1024 		reply(331, "Response to %s %s for %s.",
1025 		      opieprompt, pwok ? "requested" : "required", name);
1026 	} else {
1027 		pwok = 1;
1028 		reply(331, "Password required for %s.", name);
1029 	}
1030 	askpasswd = 1;
1031 	/*
1032 	 * Delay before reading passwd after first failed
1033 	 * attempt to slow down passwd-guessing programs.
1034 	 */
1035 	if (login_attempts)
1036 		sleep((unsigned) login_attempts);
1037 }
1038 
1039 /*
1040  * Check if a user is in the file "fname"
1041  */
1042 static int
1043 checkuser(char *fname, char *name, int pwset)
1044 {
1045 	FILE *fd;
1046 	int found = 0;
1047 	size_t len;
1048 	char *line, *mp, *p;
1049 
1050 	if ((fd = fopen(fname, "r")) != NULL) {
1051 		while (!found && (line = fgetln(fd, &len)) != NULL) {
1052 			/* skip comments */
1053 			if (line[0] == '#')
1054 				continue;
1055 			if (line[len - 1] == '\n') {
1056 				line[len - 1] = '\0';
1057 				mp = NULL;
1058 			} else {
1059 				if ((mp = malloc(len + 1)) == NULL)
1060 					fatalerror("Ran out of memory.");
1061 				memcpy(mp, line, len);
1062 				mp[len] = '\0';
1063 				line = mp;
1064 			}
1065 			/* avoid possible leading and trailing whitespace */
1066 			p = strtok(line, " \t");
1067 			/* skip empty lines */
1068 			if (p == NULL)
1069 				goto nextline;
1070 			/*
1071 			 * if first chr is '@', check group membership
1072 			 */
1073 			if (p[0] == '@') {
1074 				int i = 0;
1075 				struct group *grp;
1076 
1077 				if ((grp = getgrnam(p+1)) == NULL)
1078 					goto nextline;
1079 				/*
1080 				 * Check user's default group
1081 				 */
1082 				if (pwset && grp->gr_gid == pw->pw_gid)
1083 					found = 1;
1084 				/*
1085 				 * Check supplementary groups
1086 				 */
1087 				while (!found && grp->gr_mem[i])
1088 					found = strcmp(name,
1089 						grp->gr_mem[i++])
1090 						== 0;
1091 			}
1092 			/*
1093 			 * Otherwise, just check for username match
1094 			 */
1095 			else
1096 				found = strcmp(p, name) == 0;
1097 nextline:
1098 			if (mp)
1099 				free(mp);
1100 		}
1101 		(void) fclose(fd);
1102 	}
1103 	return (found);
1104 }
1105 
1106 /*
1107  * Terminate login as previous user, if any, resetting state;
1108  * used when USER command is given or login fails.
1109  */
1110 static void
1111 end_login(void)
1112 {
1113 #ifdef USE_PAM
1114 	int e;
1115 #endif
1116 
1117 	(void) seteuid((uid_t)0);
1118 	if (logged_in)
1119 		ftpd_logwtmp(ttyline, "", NULL);
1120 	pw = NULL;
1121 #ifdef	LOGIN_CAP
1122 	setusercontext(NULL, getpwuid(0), (uid_t)0,
1123 		       LOGIN_SETPRIORITY|LOGIN_SETRESOURCES|LOGIN_SETUMASK);
1124 #endif
1125 #ifdef USE_PAM
1126 	if ((e = pam_setcred(pamh, PAM_DELETE_CRED)) != PAM_SUCCESS)
1127 		syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e));
1128 	if ((e = pam_close_session(pamh,0)) != PAM_SUCCESS)
1129 		syslog(LOG_ERR, "pam_close_session: %s", pam_strerror(pamh, e));
1130 	if ((e = pam_end(pamh, e)) != PAM_SUCCESS)
1131 		syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1132 	pamh = NULL;
1133 #endif
1134 	logged_in = 0;
1135 	guest = 0;
1136 	dochroot = 0;
1137 }
1138 
1139 #ifdef USE_PAM
1140 
1141 /*
1142  * the following code is stolen from imap-uw PAM authentication module and
1143  * login.c
1144  */
1145 #define COPY_STRING(s) (s ? strdup(s) : NULL)
1146 
1147 struct cred_t {
1148 	const char *uname;		/* user name */
1149 	const char *pass;		/* password */
1150 };
1151 typedef struct cred_t cred_t;
1152 
1153 static int
1154 auth_conv(int num_msg, const struct pam_message **msg,
1155 	  struct pam_response **resp, void *appdata)
1156 {
1157 	int i;
1158 	cred_t *cred = (cred_t *) appdata;
1159 	struct pam_response *reply;
1160 
1161 	reply = calloc(num_msg, sizeof *reply);
1162 	if (reply == NULL)
1163 		return PAM_BUF_ERR;
1164 
1165 	for (i = 0; i < num_msg; i++) {
1166 		switch (msg[i]->msg_style) {
1167 		case PAM_PROMPT_ECHO_ON:	/* assume want user name */
1168 			reply[i].resp_retcode = PAM_SUCCESS;
1169 			reply[i].resp = COPY_STRING(cred->uname);
1170 			/* PAM frees resp. */
1171 			break;
1172 		case PAM_PROMPT_ECHO_OFF:	/* assume want password */
1173 			reply[i].resp_retcode = PAM_SUCCESS;
1174 			reply[i].resp = COPY_STRING(cred->pass);
1175 			/* PAM frees resp. */
1176 			break;
1177 		case PAM_TEXT_INFO:
1178 		case PAM_ERROR_MSG:
1179 			reply[i].resp_retcode = PAM_SUCCESS;
1180 			reply[i].resp = NULL;
1181 			break;
1182 		default:			/* unknown message style */
1183 			free(reply);
1184 			return PAM_CONV_ERR;
1185 		}
1186 	}
1187 
1188 	*resp = reply;
1189 	return PAM_SUCCESS;
1190 }
1191 
1192 /*
1193  * Attempt to authenticate the user using PAM.  Returns 0 if the user is
1194  * authenticated, or 1 if not authenticated.  If some sort of PAM system
1195  * error occurs (e.g., the "/etc/pam.conf" file is missing) then this
1196  * function returns -1.  This can be used as an indication that we should
1197  * fall back to a different authentication mechanism.
1198  */
1199 static int
1200 auth_pam(struct passwd **ppw, const char *pass)
1201 {
1202 	pam_handle_t *pamh = NULL;
1203 	const char *tmpl_user;
1204 	const void *item;
1205 	int rval;
1206 	int e;
1207 	cred_t auth_cred = { (*ppw)->pw_name, pass };
1208 	struct pam_conv conv = { &auth_conv, &auth_cred };
1209 
1210 	e = pam_start("ftpd", (*ppw)->pw_name, &conv, &pamh);
1211 	if (e != PAM_SUCCESS) {
1212 		syslog(LOG_ERR, "pam_start: %s", pam_strerror(pamh, e));
1213 		return -1;
1214 	}
1215 
1216 	e = pam_set_item(pamh, PAM_RHOST, remotehost);
1217 	if (e != PAM_SUCCESS) {
1218 		syslog(LOG_ERR, "pam_set_item(PAM_RHOST): %s",
1219 			pam_strerror(pamh, e));
1220 		return -1;
1221 	}
1222 
1223 	e = pam_authenticate(pamh, 0);
1224 	switch (e) {
1225 	case PAM_SUCCESS:
1226 		/*
1227 		 * With PAM we support the concept of a "template"
1228 		 * user.  The user enters a login name which is
1229 		 * authenticated by PAM, usually via a remote service
1230 		 * such as RADIUS or TACACS+.  If authentication
1231 		 * succeeds, a different but related "template" name
1232 		 * is used for setting the credentials, shell, and
1233 		 * home directory.  The name the user enters need only
1234 		 * exist on the remote authentication server, but the
1235 		 * template name must be present in the local password
1236 		 * database.
1237 		 *
1238 		 * This is supported by two various mechanisms in the
1239 		 * individual modules.  However, from the application's
1240 		 * point of view, the template user is always passed
1241 		 * back as a changed value of the PAM_USER item.
1242 		 */
1243 		if ((e = pam_get_item(pamh, PAM_USER, &item)) ==
1244 		    PAM_SUCCESS) {
1245 			tmpl_user = (const char *) item;
1246 			if (strcmp((*ppw)->pw_name, tmpl_user) != 0)
1247 				*ppw = getpwnam(tmpl_user);
1248 		} else
1249 			syslog(LOG_ERR, "Couldn't get PAM_USER: %s",
1250 			    pam_strerror(pamh, e));
1251 		rval = 0;
1252 		break;
1253 
1254 	case PAM_AUTH_ERR:
1255 	case PAM_USER_UNKNOWN:
1256 	case PAM_MAXTRIES:
1257 		rval = 1;
1258 		break;
1259 
1260 	default:
1261 		syslog(LOG_ERR, "pam_authenticate: %s", pam_strerror(pamh, e));
1262 		rval = -1;
1263 		break;
1264 	}
1265 
1266 	if (rval == 0) {
1267 		e = pam_acct_mgmt(pamh, 0);
1268 		if (e == PAM_NEW_AUTHTOK_REQD) {
1269 			e = pam_chauthtok(pamh, PAM_CHANGE_EXPIRED_AUTHTOK);
1270 			if (e != PAM_SUCCESS) {
1271 				syslog(LOG_ERR, "pam_chauthtok: %s", pam_strerror(pamh, e));
1272 				rval = 1;
1273 			}
1274 		} else if (e != PAM_SUCCESS) {
1275 			rval = 1;
1276 		}
1277 	}
1278 
1279 	if (rval != 0) {
1280 		if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
1281 			syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1282 		}
1283 		pamh = NULL;
1284 	}
1285 	return rval;
1286 }
1287 
1288 #endif /* USE_PAM */
1289 
1290 void
1291 pass(char *passwd)
1292 {
1293 	int rval;
1294 	FILE *fd;
1295 #ifdef	LOGIN_CAP
1296 	login_cap_t *lc = NULL;
1297 #endif
1298 #ifdef USE_PAM
1299 	int e;
1300 #endif
1301 	char *xpasswd;
1302 
1303 	if (logged_in || askpasswd == 0) {
1304 		reply(503, "Login with USER first.");
1305 		return;
1306 	}
1307 	askpasswd = 0;
1308 	if (!guest) {		/* "ftp" is only account allowed no password */
1309 		if (pw == NULL) {
1310 			rval = 1;	/* failure below */
1311 			goto skip;
1312 		}
1313 #ifdef USE_PAM
1314 		rval = auth_pam(&pw, passwd);
1315 		if (rval >= 0) {
1316 			opieunlock();
1317 			goto skip;
1318 		}
1319 #endif
1320 		if (opieverify(&opiedata, passwd) == 0)
1321 			xpasswd = pw->pw_passwd;
1322 		else if (pwok) {
1323 			xpasswd = crypt(passwd, pw->pw_passwd);
1324 			if (passwd[0] == '\0' && pw->pw_passwd[0] != '\0')
1325 				xpasswd = ":";
1326 		} else {
1327 			rval = 1;
1328 			goto skip;
1329 		}
1330 		rval = strcmp(pw->pw_passwd, xpasswd);
1331 		if (pw->pw_expire && time(NULL) >= pw->pw_expire)
1332 			rval = 1;	/* failure */
1333 skip:
1334 		/*
1335 		 * If rval == 1, the user failed the authentication check
1336 		 * above.  If rval == 0, either PAM or local authentication
1337 		 * succeeded.
1338 		 */
1339 		if (rval) {
1340 			reply(530, "Login incorrect.");
1341 			if (logging)
1342 				syslog(LOG_NOTICE,
1343 				    "FTP LOGIN FAILED FROM %s, %s",
1344 				    remotehost, curname);
1345 			pw = NULL;
1346 			if (login_attempts++ >= 5) {
1347 				syslog(LOG_NOTICE,
1348 				    "repeated login failures from %s",
1349 				    remotehost);
1350 				exit(0);
1351 			}
1352 			return;
1353 		}
1354 	}
1355 	login_attempts = 0;		/* this time successful */
1356 	if (setegid((gid_t)pw->pw_gid) < 0) {
1357 		reply(550, "Can't set gid.");
1358 		return;
1359 	}
1360 	/* May be overridden by login.conf */
1361 	(void) umask(defumask);
1362 #ifdef	LOGIN_CAP
1363 	if ((lc = login_getpwclass(pw)) != NULL) {
1364 		char	remote_ip[MAXHOSTNAMELEN];
1365 
1366 		getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
1367 			remote_ip, sizeof(remote_ip) - 1, NULL, 0,
1368 			NI_NUMERICHOST);
1369 		remote_ip[sizeof(remote_ip) - 1] = 0;
1370 		if (!auth_hostok(lc, remotehost, remote_ip)) {
1371 			syslog(LOG_INFO|LOG_AUTH,
1372 			    "FTP LOGIN FAILED (HOST) as %s: permission denied.",
1373 			    pw->pw_name);
1374 			reply(530, "Permission denied.\n");
1375 			pw = NULL;
1376 			return;
1377 		}
1378 		if (!auth_timeok(lc, time(NULL))) {
1379 			reply(530, "Login not available right now.\n");
1380 			pw = NULL;
1381 			return;
1382 		}
1383 	}
1384 	setusercontext(lc, pw, (uid_t)0,
1385 		LOGIN_SETLOGIN|LOGIN_SETGROUP|LOGIN_SETPRIORITY|
1386 		LOGIN_SETRESOURCES|LOGIN_SETUMASK);
1387 #else
1388 	setlogin(pw->pw_name);
1389 	(void) initgroups(pw->pw_name, pw->pw_gid);
1390 #endif
1391 
1392 #ifdef USE_PAM
1393 	if (pamh) {
1394 		if ((e = pam_open_session(pamh, 0)) != PAM_SUCCESS) {
1395 			syslog(LOG_ERR, "pam_open_session: %s", pam_strerror(pamh, e));
1396 		} else if ((e = pam_setcred(pamh, PAM_ESTABLISH_CRED)) != PAM_SUCCESS) {
1397 			syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e));
1398 		}
1399 	}
1400 #endif
1401 
1402 	/* open wtmp before chroot */
1403 	ftpd_logwtmp(ttyline, pw->pw_name, (struct sockaddr *)&his_addr);
1404 	logged_in = 1;
1405 
1406 	if (guest && stats && statfd < 0)
1407 #ifdef VIRTUAL_HOSTING
1408 		if ((statfd = open(thishost->statfile, O_WRONLY|O_APPEND)) < 0)
1409 #else
1410 		if ((statfd = open(_PATH_FTPDSTATFILE, O_WRONLY|O_APPEND)) < 0)
1411 #endif
1412 			stats = 0;
1413 
1414 	dochroot =
1415 #ifdef	LOGIN_CAP	/* Allow login.conf configuration as well */
1416 		login_getcapbool(lc, "ftp-chroot", 0) ||
1417 #endif
1418 		checkuser(_PATH_FTPCHROOT, pw->pw_name, 1);
1419 	if (guest) {
1420 		/*
1421 		 * We MUST do a chdir() after the chroot. Otherwise
1422 		 * the old current directory will be accessible as "."
1423 		 * outside the new root!
1424 		 */
1425 		if (chroot(pw->pw_dir) < 0 || chdir("/") < 0) {
1426 			reply(550, "Can't set guest privileges.");
1427 			goto bad;
1428 		}
1429 	} else if (dochroot) {
1430 		if (chroot(pw->pw_dir) < 0 || chdir("/") < 0) {
1431 			reply(550, "Can't change root.");
1432 			goto bad;
1433 		}
1434 	} else if (chdir(pw->pw_dir) < 0) {
1435 		if (chdir("/") < 0) {
1436 			reply(530, "User %s: can't change directory to %s.",
1437 			    pw->pw_name, pw->pw_dir);
1438 			goto bad;
1439 		} else
1440 			lreply(230, "No directory! Logging in with home=/");
1441 	}
1442 	if (seteuid((uid_t)pw->pw_uid) < 0) {
1443 		reply(550, "Can't set uid.");
1444 		goto bad;
1445 	}
1446 
1447 	/*
1448 	 * Display a login message, if it exists.
1449 	 * N.B. reply(230,) must follow the message.
1450 	 */
1451 #ifdef VIRTUAL_HOSTING
1452 	if ((fd = fopen(thishost->loginmsg, "r")) != NULL) {
1453 #else
1454 	if ((fd = fopen(_PATH_FTPLOGINMESG, "r")) != NULL) {
1455 #endif
1456 		char *cp, line[LINE_MAX];
1457 
1458 		while (fgets(line, sizeof(line), fd) != NULL) {
1459 			if ((cp = strchr(line, '\n')) != NULL)
1460 				*cp = '\0';
1461 			lreply(230, "%s", line);
1462 		}
1463 		(void) fflush(stdout);
1464 		(void) fclose(fd);
1465 	}
1466 	if (guest) {
1467 		if (ident != NULL)
1468 			free(ident);
1469 		ident = strdup(passwd);
1470 		if (ident == NULL)
1471 			fatalerror("Ran out of memory.");
1472 
1473 		reply(230, "Guest login ok, access restrictions apply.");
1474 #ifdef SETPROCTITLE
1475 #ifdef VIRTUAL_HOSTING
1476 		if (thishost != firsthost)
1477 			snprintf(proctitle, sizeof(proctitle),
1478 				 "%s: anonymous(%s)/%s", remotehost, hostname,
1479 				 passwd);
1480 		else
1481 #endif
1482 			snprintf(proctitle, sizeof(proctitle),
1483 				 "%s: anonymous/%s", remotehost, passwd);
1484 		setproctitle("%s", proctitle);
1485 #endif /* SETPROCTITLE */
1486 		if (logging)
1487 			syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s, %s",
1488 			    remotehost, passwd);
1489 	} else {
1490 		if (dochroot)
1491 			reply(230, "User %s logged in, "
1492 				   "access restrictions apply.", pw->pw_name);
1493 		else
1494 			reply(230, "User %s logged in.", pw->pw_name);
1495 
1496 #ifdef SETPROCTITLE
1497 		snprintf(proctitle, sizeof(proctitle),
1498 			 "%s: user/%s", remotehost, pw->pw_name);
1499 		setproctitle("%s", proctitle);
1500 #endif /* SETPROCTITLE */
1501 		if (logging)
1502 			syslog(LOG_INFO, "FTP LOGIN FROM %s as %s",
1503 			    remotehost, pw->pw_name);
1504 	}
1505 #ifdef	LOGIN_CAP
1506 	login_close(lc);
1507 #endif
1508 	return;
1509 bad:
1510 	/* Forget all about it... */
1511 #ifdef	LOGIN_CAP
1512 	login_close(lc);
1513 #endif
1514 	end_login();
1515 }
1516 
1517 void
1518 retrieve(char *cmd, char *name)
1519 {
1520 	FILE *fin, *dout;
1521 	struct stat st;
1522 	int (*closefunc)(FILE *);
1523 	time_t start;
1524 
1525 	if (cmd == 0) {
1526 		fin = fopen(name, "r"), closefunc = fclose;
1527 		st.st_size = 0;
1528 	} else {
1529 		char line[BUFSIZ];
1530 
1531 		(void) snprintf(line, sizeof(line), cmd, name), name = line;
1532 		fin = ftpd_popen(line, "r"), closefunc = ftpd_pclose;
1533 		st.st_size = -1;
1534 		st.st_blksize = BUFSIZ;
1535 	}
1536 	if (fin == NULL) {
1537 		if (errno != 0) {
1538 			perror_reply(550, name);
1539 			if (cmd == 0) {
1540 				LOGCMD("get", name);
1541 			}
1542 		}
1543 		return;
1544 	}
1545 	byte_count = -1;
1546 	if (cmd == 0 && (fstat(fileno(fin), &st) < 0 || !S_ISREG(st.st_mode))) {
1547 		reply(550, "%s: not a plain file.", name);
1548 		goto done;
1549 	}
1550 	if (restart_point) {
1551 		if (type == TYPE_A) {
1552 			off_t i, n;
1553 			int c;
1554 
1555 			n = restart_point;
1556 			i = 0;
1557 			while (i++ < n) {
1558 				if ((c=getc(fin)) == EOF) {
1559 					perror_reply(550, name);
1560 					goto done;
1561 				}
1562 				if (c == '\n')
1563 					i++;
1564 			}
1565 		} else if (lseek(fileno(fin), restart_point, L_SET) < 0) {
1566 			perror_reply(550, name);
1567 			goto done;
1568 		}
1569 	}
1570 	dout = dataconn(name, st.st_size, "w");
1571 	if (dout == NULL)
1572 		goto done;
1573 	time(&start);
1574 	send_data(fin, dout, st.st_blksize, st.st_size,
1575 		  restart_point == 0 && cmd == 0 && S_ISREG(st.st_mode));
1576 	if (cmd == 0 && guest && stats)
1577 		logxfer(name, st.st_size, start);
1578 	(void) fclose(dout);
1579 	data = -1;
1580 	pdata = -1;
1581 done:
1582 	if (cmd == 0)
1583 		LOGBYTES("get", name, byte_count);
1584 	(*closefunc)(fin);
1585 }
1586 
1587 void
1588 store(char *name, char *mode, int unique)
1589 {
1590 	FILE *fout, *din;
1591 	struct stat st;
1592 	int (*closefunc)(FILE *);
1593 
1594 	if ((unique || guest) && stat(name, &st) == 0 &&
1595 	    (name = gunique(name)) == NULL) {
1596 		LOGCMD(*mode == 'w' ? "put" : "append", name);
1597 		return;
1598 	}
1599 
1600 	if (restart_point)
1601 		mode = "r+";
1602 	fout = fopen(name, mode);
1603 	closefunc = fclose;
1604 	if (fout == NULL) {
1605 		perror_reply(553, name);
1606 		LOGCMD(*mode == 'w' ? "put" : "append", name);
1607 		return;
1608 	}
1609 	byte_count = -1;
1610 	if (restart_point) {
1611 		if (type == TYPE_A) {
1612 			off_t i, n;
1613 			int c;
1614 
1615 			n = restart_point;
1616 			i = 0;
1617 			while (i++ < n) {
1618 				if ((c=getc(fout)) == EOF) {
1619 					perror_reply(550, name);
1620 					goto done;
1621 				}
1622 				if (c == '\n')
1623 					i++;
1624 			}
1625 			/*
1626 			 * We must do this seek to "current" position
1627 			 * because we are changing from reading to
1628 			 * writing.
1629 			 */
1630 			if (fseeko(fout, (off_t)0, SEEK_CUR) < 0) {
1631 				perror_reply(550, name);
1632 				goto done;
1633 			}
1634 		} else if (lseek(fileno(fout), restart_point, L_SET) < 0) {
1635 			perror_reply(550, name);
1636 			goto done;
1637 		}
1638 	}
1639 	din = dataconn(name, (off_t)-1, "r");
1640 	if (din == NULL)
1641 		goto done;
1642 	if (receive_data(din, fout) == 0) {
1643 		if (unique)
1644 			reply(226, "Transfer complete (unique file name:%s).",
1645 			    name);
1646 		else
1647 			reply(226, "Transfer complete.");
1648 	}
1649 	(void) fclose(din);
1650 	data = -1;
1651 	pdata = -1;
1652 done:
1653 	LOGBYTES(*mode == 'w' ? "put" : "append", name, byte_count);
1654 	(*closefunc)(fout);
1655 }
1656 
1657 static FILE *
1658 getdatasock(char *mode)
1659 {
1660 	int on = 1, s, t, tries;
1661 
1662 	if (data >= 0)
1663 		return (fdopen(data, mode));
1664 	(void) seteuid((uid_t)0);
1665 
1666 	s = socket(data_dest.su_family, SOCK_STREAM, 0);
1667 	if (s < 0)
1668 		goto bad;
1669 	if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
1670 	    (char *) &on, sizeof(on)) < 0)
1671 		goto bad;
1672 	/* anchor socket to avoid multi-homing problems */
1673 	data_source = ctrl_addr;
1674 	data_source.su_port = htons(20); /* ftp-data port */
1675 	for (tries = 1; ; tries++) {
1676 		if (bind(s, (struct sockaddr *)&data_source,
1677 		    data_source.su_len) >= 0)
1678 			break;
1679 		if (errno != EADDRINUSE || tries > 10)
1680 			goto bad;
1681 		sleep(tries);
1682 	}
1683 	(void) seteuid((uid_t)pw->pw_uid);
1684 #ifdef IP_TOS
1685 	if (data_source.su_family == AF_INET)
1686       {
1687 	on = IPTOS_THROUGHPUT;
1688 	if (setsockopt(s, IPPROTO_IP, IP_TOS, (char *)&on, sizeof(int)) < 0)
1689 		syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
1690       }
1691 #endif
1692 #ifdef TCP_NOPUSH
1693 	/*
1694 	 * Turn off push flag to keep sender TCP from sending short packets
1695 	 * at the boundaries of each write().  Should probably do a SO_SNDBUF
1696 	 * to set the send buffer size as well, but that may not be desirable
1697 	 * in heavy-load situations.
1698 	 */
1699 	on = 1;
1700 	if (setsockopt(s, IPPROTO_TCP, TCP_NOPUSH, (char *)&on, sizeof on) < 0)
1701 		syslog(LOG_WARNING, "setsockopt (TCP_NOPUSH): %m");
1702 #endif
1703 #ifdef SO_SNDBUF
1704 	on = 65536;
1705 	if (setsockopt(s, SOL_SOCKET, SO_SNDBUF, (char *)&on, sizeof on) < 0)
1706 		syslog(LOG_WARNING, "setsockopt (SO_SNDBUF): %m");
1707 #endif
1708 
1709 	return (fdopen(s, mode));
1710 bad:
1711 	/* Return the real value of errno (close may change it) */
1712 	t = errno;
1713 	(void) seteuid((uid_t)pw->pw_uid);
1714 	(void) close(s);
1715 	errno = t;
1716 	return (NULL);
1717 }
1718 
1719 static FILE *
1720 dataconn(char *name, off_t size, char *mode)
1721 {
1722 	char sizebuf[32];
1723 	FILE *file;
1724 	int retry = 0, tos;
1725 
1726 	file_size = size;
1727 	byte_count = 0;
1728 	if (size != (off_t) -1)
1729 		(void) snprintf(sizebuf, sizeof(sizebuf), " (%qd bytes)", size);
1730 	else
1731 		*sizebuf = '\0';
1732 	if (pdata >= 0) {
1733 		union sockunion from;
1734 		int flags;
1735 		int s, fromlen = ctrl_addr.su_len;
1736 		struct timeval timeout;
1737 		fd_set set;
1738 
1739 		FD_ZERO(&set);
1740 		FD_SET(pdata, &set);
1741 
1742 		timeout.tv_usec = 0;
1743 		timeout.tv_sec = 120;
1744 
1745 		/*
1746 		 * Granted a socket is in the blocking I/O mode,
1747 		 * accept() will block after a successful select()
1748 		 * if the selected connection dies in between.
1749 		 * Therefore set the non-blocking I/O flag here.
1750 		 */
1751 		if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1752 		    fcntl(pdata, F_SETFL, flags | O_NONBLOCK) == -1)
1753 			goto pdata_err;
1754 		if (select(pdata+1, &set, (fd_set *) 0, (fd_set *) 0, &timeout) <= 0 ||
1755 		    (s = accept(pdata, (struct sockaddr *) &from, &fromlen)) < 0)
1756 			goto pdata_err;
1757 		(void) close(pdata);
1758 		pdata = s;
1759 		/*
1760 		 * Unset the blocking I/O flag on the child socket
1761 		 * again so stdio can work on it.
1762 		 */
1763 		if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1764 		    fcntl(pdata, F_SETFL, flags & ~O_NONBLOCK) == -1)
1765 			goto pdata_err;
1766 #ifdef IP_TOS
1767 		if (from.su_family == AF_INET)
1768 	      {
1769 		tos = IPTOS_THROUGHPUT;
1770 		(void) setsockopt(s, IPPROTO_IP, IP_TOS, (char *)&tos,
1771 		    sizeof(int));
1772 	      }
1773 #endif
1774 		reply(150, "Opening %s mode data connection for '%s'%s.",
1775 		     type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1776 		return (fdopen(pdata, mode));
1777 pdata_err:
1778 		reply(425, "Can't open data connection.");
1779 		(void) close(pdata);
1780 		pdata = -1;
1781 		return (NULL);
1782 	}
1783 	if (data >= 0) {
1784 		reply(125, "Using existing data connection for '%s'%s.",
1785 		    name, sizebuf);
1786 		usedefault = 1;
1787 		return (fdopen(data, mode));
1788 	}
1789 	if (usedefault)
1790 		data_dest = his_addr;
1791 	usedefault = 1;
1792 	file = getdatasock(mode);
1793 	if (file == NULL) {
1794 		char hostbuf[BUFSIZ], portbuf[BUFSIZ];
1795 		getnameinfo((struct sockaddr *)&data_source,
1796 			data_source.su_len, hostbuf, sizeof(hostbuf) - 1,
1797 			portbuf, sizeof(portbuf),
1798 			NI_NUMERICHOST|NI_NUMERICSERV);
1799 		reply(425, "Can't create data socket (%s,%s): %s.",
1800 			hostbuf, portbuf, strerror(errno));
1801 		return (NULL);
1802 	}
1803 	data = fileno(file);
1804 	while (connect(data, (struct sockaddr *)&data_dest,
1805 	    data_dest.su_len) < 0) {
1806 		if (errno == EADDRINUSE && retry < swaitmax) {
1807 			sleep((unsigned) swaitint);
1808 			retry += swaitint;
1809 			continue;
1810 		}
1811 		perror_reply(425, "Can't build data connection");
1812 		(void) fclose(file);
1813 		data = -1;
1814 		return (NULL);
1815 	}
1816 	reply(150, "Opening %s mode data connection for '%s'%s.",
1817 	     type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1818 	return (file);
1819 }
1820 
1821 /*
1822  * Tranfer the contents of "instr" to "outstr" peer using the appropriate
1823  * encapsulation of the data subject to Mode, Structure, and Type.
1824  *
1825  * NB: Form isn't handled.
1826  */
1827 static int
1828 send_data(FILE *instr, FILE *outstr, off_t blksize, off_t filesize, int isreg)
1829 {
1830 	int c, filefd, netfd;
1831 	char *buf;
1832 	off_t cnt;
1833 
1834 	transflag++;
1835 	switch (type) {
1836 
1837 	case TYPE_A:
1838 		while ((c = getc(instr)) != EOF) {
1839 			if (recvurg)
1840 				goto got_oob;
1841 			byte_count++;
1842 			if (c == '\n') {
1843 				if (ferror(outstr))
1844 					goto data_err;
1845 				(void) putc('\r', outstr);
1846 			}
1847 			(void) putc(c, outstr);
1848 		}
1849 		if (recvurg)
1850 			goto got_oob;
1851 		fflush(outstr);
1852 		transflag = 0;
1853 		if (ferror(instr))
1854 			goto file_err;
1855 		if (ferror(outstr))
1856 			goto data_err;
1857 		reply(226, "Transfer complete.");
1858 		return (0);
1859 
1860 	case TYPE_I:
1861 	case TYPE_L:
1862 		/*
1863 		 * isreg is only set if we are not doing restart and we
1864 		 * are sending a regular file
1865 		 */
1866 		netfd = fileno(outstr);
1867 		filefd = fileno(instr);
1868 
1869 		if (isreg) {
1870 
1871 			off_t offset;
1872 			int err;
1873 
1874 			err = cnt = offset = 0;
1875 
1876 			while (err != -1 && filesize > 0) {
1877 				err = sendfile(filefd, netfd, offset, 0,
1878 					(struct sf_hdtr *) NULL, &cnt, 0);
1879 				/*
1880 				 * Calculate byte_count before OOB processing.
1881 				 * It can be used in myoob() later.
1882 				 */
1883 				byte_count += cnt;
1884 				if (recvurg)
1885 					goto got_oob;
1886 				offset += cnt;
1887 				filesize -= cnt;
1888 
1889 				if (err == -1) {
1890 					if (!cnt)
1891 						goto oldway;
1892 
1893 					goto data_err;
1894 				}
1895 			}
1896 
1897 			transflag = 0;
1898 			reply(226, "Transfer complete.");
1899 			return (0);
1900 		}
1901 
1902 oldway:
1903 		if ((buf = malloc((u_int)blksize)) == NULL) {
1904 			transflag = 0;
1905 			perror_reply(451, "Local resource failure: malloc");
1906 			return (-1);
1907 		}
1908 
1909 		while ((cnt = read(filefd, buf, (u_int)blksize)) > 0 &&
1910 		    write(netfd, buf, cnt) == cnt)
1911 			byte_count += cnt;
1912 		transflag = 0;
1913 		(void)free(buf);
1914 		if (cnt != 0) {
1915 			if (cnt < 0)
1916 				goto file_err;
1917 			goto data_err;
1918 		}
1919 		reply(226, "Transfer complete.");
1920 		return (0);
1921 	default:
1922 		transflag = 0;
1923 		reply(550, "Unimplemented TYPE %d in send_data", type);
1924 		return (-1);
1925 	}
1926 
1927 data_err:
1928 	transflag = 0;
1929 	perror_reply(426, "Data connection");
1930 	return (-1);
1931 
1932 file_err:
1933 	transflag = 0;
1934 	perror_reply(551, "Error on input file");
1935 	return (-1);
1936 
1937 got_oob:
1938 	myoob();
1939 	recvurg = 0;
1940 	transflag = 0;
1941 	return (-1);
1942 }
1943 
1944 /*
1945  * Transfer data from peer to "outstr" using the appropriate encapulation of
1946  * the data subject to Mode, Structure, and Type.
1947  *
1948  * N.B.: Form isn't handled.
1949  */
1950 static int
1951 receive_data(FILE *instr, FILE *outstr)
1952 {
1953 	int c;
1954 	int cnt, bare_lfs;
1955 	char buf[BUFSIZ];
1956 
1957 	transflag++;
1958 	bare_lfs = 0;
1959 
1960 	switch (type) {
1961 
1962 	case TYPE_I:
1963 	case TYPE_L:
1964 		while ((cnt = read(fileno(instr), buf, sizeof(buf))) > 0) {
1965 			if (recvurg)
1966 				goto got_oob;
1967 			if (write(fileno(outstr), buf, cnt) != cnt)
1968 				goto file_err;
1969 			byte_count += cnt;
1970 		}
1971 		if (recvurg)
1972 			goto got_oob;
1973 		if (cnt < 0)
1974 			goto data_err;
1975 		transflag = 0;
1976 		return (0);
1977 
1978 	case TYPE_E:
1979 		reply(553, "TYPE E not implemented.");
1980 		transflag = 0;
1981 		return (-1);
1982 
1983 	case TYPE_A:
1984 		while ((c = getc(instr)) != EOF) {
1985 			if (recvurg)
1986 				goto got_oob;
1987 			byte_count++;
1988 			if (c == '\n')
1989 				bare_lfs++;
1990 			while (c == '\r') {
1991 				if (ferror(outstr))
1992 					goto data_err;
1993 				if ((c = getc(instr)) != '\n') {
1994 					(void) putc ('\r', outstr);
1995 					if (c == '\0' || c == EOF)
1996 						goto contin2;
1997 				}
1998 			}
1999 			(void) putc(c, outstr);
2000 	contin2:	;
2001 		}
2002 		if (recvurg)
2003 			goto got_oob;
2004 		fflush(outstr);
2005 		if (ferror(instr))
2006 			goto data_err;
2007 		if (ferror(outstr))
2008 			goto file_err;
2009 		transflag = 0;
2010 		if (bare_lfs) {
2011 			lreply(226,
2012 		"WARNING! %d bare linefeeds received in ASCII mode",
2013 			    bare_lfs);
2014 		(void)printf("   File may not have transferred correctly.\r\n");
2015 		}
2016 		return (0);
2017 	default:
2018 		reply(550, "Unimplemented TYPE %d in receive_data", type);
2019 		transflag = 0;
2020 		return (-1);
2021 	}
2022 
2023 data_err:
2024 	transflag = 0;
2025 	perror_reply(426, "Data Connection");
2026 	return (-1);
2027 
2028 file_err:
2029 	transflag = 0;
2030 	perror_reply(452, "Error writing file");
2031 	return (-1);
2032 
2033 got_oob:
2034 	myoob();
2035 	recvurg = 0;
2036 	transflag = 0;
2037 	return (-1);
2038 }
2039 
2040 void
2041 statfilecmd(char *filename)
2042 {
2043 	FILE *fin;
2044 	int c;
2045 	char line[LINE_MAX];
2046 
2047 	(void)snprintf(line, sizeof(line), _PATH_LS " -lgA %s", filename);
2048 	fin = ftpd_popen(line, "r");
2049 	lreply(211, "status of %s:", filename);
2050 	while ((c = getc(fin)) != EOF) {
2051 		if (c == '\n') {
2052 			if (ferror(stdout)){
2053 				perror_reply(421, "control connection");
2054 				(void) ftpd_pclose(fin);
2055 				dologout(1);
2056 				/* NOTREACHED */
2057 			}
2058 			if (ferror(fin)) {
2059 				perror_reply(551, filename);
2060 				(void) ftpd_pclose(fin);
2061 				return;
2062 			}
2063 			(void) putc('\r', stdout);
2064 		}
2065 		(void) putc(c, stdout);
2066 	}
2067 	(void) ftpd_pclose(fin);
2068 	reply(211, "End of Status");
2069 }
2070 
2071 void
2072 statcmd(void)
2073 {
2074 	union sockunion *su;
2075 	u_char *a, *p;
2076 	char hname[NI_MAXHOST];
2077 	int ispassive;
2078 
2079 	lreply(211, "%s FTP server status:", hostname, version);
2080 	printf("     %s\r\n", version);
2081 	printf("     Connected to %s", remotehost);
2082 	if (!getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
2083 			 hname, sizeof(hname) - 1, NULL, 0, NI_NUMERICHOST)) {
2084 		if (strcmp(hname, remotehost) != 0)
2085 			printf(" (%s)", hname);
2086 	}
2087 	printf("\r\n");
2088 	if (logged_in) {
2089 		if (guest)
2090 			printf("     Logged in anonymously\r\n");
2091 		else
2092 			printf("     Logged in as %s\r\n", pw->pw_name);
2093 	} else if (askpasswd)
2094 		printf("     Waiting for password\r\n");
2095 	else
2096 		printf("     Waiting for user name\r\n");
2097 	printf("     TYPE: %s", typenames[type]);
2098 	if (type == TYPE_A || type == TYPE_E)
2099 		printf(", FORM: %s", formnames[form]);
2100 	if (type == TYPE_L)
2101 #if NBBY == 8
2102 		printf(" %d", NBBY);
2103 #else
2104 		printf(" %d", bytesize);	/* need definition! */
2105 #endif
2106 	printf("; STRUcture: %s; transfer MODE: %s\r\n",
2107 	    strunames[stru], modenames[mode]);
2108 	if (data != -1)
2109 		printf("     Data connection open\r\n");
2110 	else if (pdata != -1) {
2111 		ispassive = 1;
2112 		su = &pasv_addr;
2113 		goto printaddr;
2114 	} else if (usedefault == 0) {
2115 		ispassive = 0;
2116 		su = &data_dest;
2117 printaddr:
2118 #define UC(b) (((int) b) & 0xff)
2119 		if (epsvall) {
2120 			printf("     EPSV only mode (EPSV ALL)\r\n");
2121 			goto epsvonly;
2122 		}
2123 
2124 		/* PORT/PASV */
2125 		if (su->su_family == AF_INET) {
2126 			a = (u_char *) &su->su_sin.sin_addr;
2127 			p = (u_char *) &su->su_sin.sin_port;
2128 			printf("     %s (%d,%d,%d,%d,%d,%d)\r\n",
2129 				ispassive ? "PASV" : "PORT",
2130 				UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2131 				UC(p[0]), UC(p[1]));
2132 		}
2133 
2134 		/* LPRT/LPSV */
2135 	    {
2136 		int alen, af, i;
2137 
2138 		switch (su->su_family) {
2139 		case AF_INET:
2140 			a = (u_char *) &su->su_sin.sin_addr;
2141 			p = (u_char *) &su->su_sin.sin_port;
2142 			alen = sizeof(su->su_sin.sin_addr);
2143 			af = 4;
2144 			break;
2145 		case AF_INET6:
2146 			a = (u_char *) &su->su_sin6.sin6_addr;
2147 			p = (u_char *) &su->su_sin6.sin6_port;
2148 			alen = sizeof(su->su_sin6.sin6_addr);
2149 			af = 6;
2150 			break;
2151 		default:
2152 			af = 0;
2153 			break;
2154 		}
2155 		if (af) {
2156 			printf("     %s (%d,%d,", ispassive ? "LPSV" : "LPRT",
2157 				af, alen);
2158 			for (i = 0; i < alen; i++)
2159 				printf("%d,", UC(a[i]));
2160 			printf("%d,%d,%d)\r\n", 2, UC(p[0]), UC(p[1]));
2161 		}
2162 	    }
2163 
2164 epsvonly:;
2165 		/* EPRT/EPSV */
2166 	    {
2167 		int af;
2168 
2169 		switch (su->su_family) {
2170 		case AF_INET:
2171 			af = 1;
2172 			break;
2173 		case AF_INET6:
2174 			af = 2;
2175 			break;
2176 		default:
2177 			af = 0;
2178 			break;
2179 		}
2180 		if (af) {
2181 			union sockunion tmp;
2182 
2183 			tmp = *su;
2184 			if (tmp.su_family == AF_INET6)
2185 				tmp.su_sin6.sin6_scope_id = 0;
2186 			if (!getnameinfo((struct sockaddr *)&tmp, tmp.su_len,
2187 					hname, sizeof(hname) - 1, NULL, 0,
2188 					NI_NUMERICHOST)) {
2189 				printf("     %s |%d|%s|%d|\r\n",
2190 					ispassive ? "EPSV" : "EPRT",
2191 					af, hname, htons(tmp.su_port));
2192 			}
2193 		}
2194 	    }
2195 #undef UC
2196 	} else
2197 		printf("     No data connection\r\n");
2198 	reply(211, "End of status");
2199 }
2200 
2201 void
2202 fatalerror(char *s)
2203 {
2204 
2205 	reply(451, "Error in server: %s\n", s);
2206 	reply(221, "Closing connection due to server error.");
2207 	dologout(0);
2208 	/* NOTREACHED */
2209 }
2210 
2211 void
2212 reply(int n, const char *fmt, ...)
2213 {
2214 	va_list ap;
2215 
2216 	va_start(ap, fmt);
2217 	(void)printf("%d ", n);
2218 	(void)vprintf(fmt, ap);
2219 	(void)printf("\r\n");
2220 	(void)fflush(stdout);
2221 	if (ftpdebug) {
2222 		syslog(LOG_DEBUG, "<--- %d ", n);
2223 		vsyslog(LOG_DEBUG, fmt, ap);
2224 	}
2225 }
2226 
2227 void
2228 lreply(int n, const char *fmt, ...)
2229 {
2230 	va_list ap;
2231 
2232 	va_start(ap, fmt);
2233 	(void)printf("%d- ", n);
2234 	(void)vprintf(fmt, ap);
2235 	(void)printf("\r\n");
2236 	(void)fflush(stdout);
2237 	if (ftpdebug) {
2238 		syslog(LOG_DEBUG, "<--- %d- ", n);
2239 		vsyslog(LOG_DEBUG, fmt, ap);
2240 	}
2241 }
2242 
2243 static void
2244 ack(char *s)
2245 {
2246 
2247 	reply(250, "%s command successful.", s);
2248 }
2249 
2250 void
2251 nack(char *s)
2252 {
2253 
2254 	reply(502, "%s command not implemented.", s);
2255 }
2256 
2257 /* ARGSUSED */
2258 void
2259 yyerror(char *s)
2260 {
2261 	char *cp;
2262 
2263 	if ((cp = strchr(cbuf,'\n')))
2264 		*cp = '\0';
2265 	reply(500, "'%s': command not understood.", cbuf);
2266 }
2267 
2268 void
2269 delete(char *name)
2270 {
2271 	struct stat st;
2272 
2273 	LOGCMD("delete", name);
2274 	if (stat(name, &st) < 0) {
2275 		perror_reply(550, name);
2276 		return;
2277 	}
2278 	if ((st.st_mode&S_IFMT) == S_IFDIR) {
2279 		if (rmdir(name) < 0) {
2280 			perror_reply(550, name);
2281 			return;
2282 		}
2283 		goto done;
2284 	}
2285 	if (unlink(name) < 0) {
2286 		perror_reply(550, name);
2287 		return;
2288 	}
2289 done:
2290 	ack("DELE");
2291 }
2292 
2293 void
2294 cwd(char *path)
2295 {
2296 
2297 	if (chdir(path) < 0)
2298 		perror_reply(550, path);
2299 	else
2300 		ack("CWD");
2301 }
2302 
2303 void
2304 makedir(char *name)
2305 {
2306 
2307 	LOGCMD("mkdir", name);
2308 	if (guest && noguestmkd)
2309 		reply(550, "%s: permission denied", name);
2310 	else if (mkdir(name, 0777) < 0)
2311 		perror_reply(550, name);
2312 	else
2313 		reply(257, "MKD command successful.");
2314 }
2315 
2316 void
2317 removedir(char *name)
2318 {
2319 
2320 	LOGCMD("rmdir", name);
2321 	if (rmdir(name) < 0)
2322 		perror_reply(550, name);
2323 	else
2324 		ack("RMD");
2325 }
2326 
2327 void
2328 pwd(void)
2329 {
2330 	char path[MAXPATHLEN + 1];
2331 
2332 	if (getwd(path) == (char *)NULL)
2333 		reply(550, "%s.", path);
2334 	else
2335 		reply(257, "\"%s\" is current directory.", path);
2336 }
2337 
2338 char *
2339 renamefrom(char *name)
2340 {
2341 	struct stat st;
2342 
2343 	if (stat(name, &st) < 0) {
2344 		perror_reply(550, name);
2345 		return ((char *)0);
2346 	}
2347 	reply(350, "File exists, ready for destination name");
2348 	return (name);
2349 }
2350 
2351 void
2352 renamecmd(char *from, char *to)
2353 {
2354 	struct stat st;
2355 
2356 	LOGCMD2("rename", from, to);
2357 
2358 	if (guest && (stat(to, &st) == 0)) {
2359 		reply(550, "%s: permission denied", to);
2360 		return;
2361 	}
2362 
2363 	if (rename(from, to) < 0)
2364 		perror_reply(550, "rename");
2365 	else
2366 		ack("RNTO");
2367 }
2368 
2369 static void
2370 dolog(struct sockaddr *who)
2371 {
2372 	int error;
2373 
2374 	realhostname_sa(remotehost, sizeof(remotehost) - 1, who, who->sa_len);
2375 
2376 #ifdef SETPROCTITLE
2377 #ifdef VIRTUAL_HOSTING
2378 	if (thishost != firsthost)
2379 		snprintf(proctitle, sizeof(proctitle), "%s: connected (to %s)",
2380 			 remotehost, hostname);
2381 	else
2382 #endif
2383 		snprintf(proctitle, sizeof(proctitle), "%s: connected",
2384 			 remotehost);
2385 	setproctitle("%s", proctitle);
2386 #endif /* SETPROCTITLE */
2387 
2388 	if (logging) {
2389 #ifdef VIRTUAL_HOSTING
2390 		if (thishost != firsthost)
2391 			syslog(LOG_INFO, "connection from %s (to %s)",
2392 			       remotehost, hostname);
2393 		else
2394 #endif
2395 		{
2396 			char	who_name[MAXHOSTNAMELEN];
2397 
2398 			error = getnameinfo(who, who->sa_len,
2399 					    who_name, sizeof(who_name) - 1,
2400 					    NULL, 0, NI_NUMERICHOST);
2401 			syslog(LOG_INFO, "connection from %s (%s)", remotehost,
2402 			       error == 0 ? who_name : "");
2403 		}
2404 	}
2405 }
2406 
2407 /*
2408  * Record logout in wtmp file
2409  * and exit with supplied status.
2410  */
2411 void
2412 dologout(int status)
2413 {
2414 	/*
2415 	 * Prevent reception of SIGURG from resulting in a resumption
2416 	 * back to the main program loop.
2417 	 */
2418 	transflag = 0;
2419 
2420 	if (logged_in) {
2421 		(void) seteuid((uid_t)0);
2422 		ftpd_logwtmp(ttyline, "", NULL);
2423 	}
2424 	/* beware of flushing buffers after a SIGPIPE */
2425 	_exit(status);
2426 }
2427 
2428 static void
2429 sigurg(int signo)
2430 {
2431 
2432 	recvurg = 1;
2433 }
2434 
2435 static void
2436 myoob(void)
2437 {
2438 	char *cp;
2439 
2440 	/* only process if transfer occurring */
2441 	if (!transflag)
2442 		return;
2443 	cp = tmpline;
2444 	if (getline(cp, 7, stdin) == NULL) {
2445 		reply(221, "You could at least say goodbye.");
2446 		dologout(0);
2447 	}
2448 	upper(cp);
2449 	if (strcmp(cp, "ABOR\r\n") == 0) {
2450 		tmpline[0] = '\0';
2451 		reply(426, "Transfer aborted. Data connection closed.");
2452 		reply(226, "Abort successful");
2453 	}
2454 	if (strcmp(cp, "STAT\r\n") == 0) {
2455 		tmpline[0] = '\0';
2456 		if (file_size != (off_t) -1)
2457 			reply(213, "Status: %qd of %qd bytes transferred",
2458 			    byte_count, file_size);
2459 		else
2460 			reply(213, "Status: %qd bytes transferred", byte_count);
2461 	}
2462 }
2463 
2464 /*
2465  * Note: a response of 425 is not mentioned as a possible response to
2466  *	the PASV command in RFC959. However, it has been blessed as
2467  *	a legitimate response by Jon Postel in a telephone conversation
2468  *	with Rick Adams on 25 Jan 89.
2469  */
2470 void
2471 passive(void)
2472 {
2473 	int len;
2474 	char *p, *a;
2475 
2476 	if (pdata >= 0)		/* close old port if one set */
2477 		close(pdata);
2478 
2479 	pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2480 	if (pdata < 0) {
2481 		perror_reply(425, "Can't open passive connection");
2482 		return;
2483 	}
2484 
2485 	(void) seteuid((uid_t)0);
2486 
2487 #ifdef IP_PORTRANGE
2488 	if (ctrl_addr.su_family == AF_INET) {
2489 	    int on = restricted_data_ports ? IP_PORTRANGE_HIGH
2490 					   : IP_PORTRANGE_DEFAULT;
2491 
2492 	    if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2493 			    (char *)&on, sizeof(on)) < 0)
2494 		    goto pasv_error;
2495 	}
2496 #endif
2497 #ifdef IPV6_PORTRANGE
2498 	if (ctrl_addr.su_family == AF_INET6) {
2499 	    int on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
2500 					   : IPV6_PORTRANGE_DEFAULT;
2501 
2502 	    if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2503 			    (char *)&on, sizeof(on)) < 0)
2504 		    goto pasv_error;
2505 	}
2506 #endif
2507 
2508 	pasv_addr = ctrl_addr;
2509 	pasv_addr.su_port = 0;
2510 	if (bind(pdata, (struct sockaddr *)&pasv_addr, pasv_addr.su_len) < 0)
2511 		goto pasv_error;
2512 
2513 	(void) seteuid((uid_t)pw->pw_uid);
2514 
2515 	len = sizeof(pasv_addr);
2516 	if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2517 		goto pasv_error;
2518 	if (listen(pdata, 1) < 0)
2519 		goto pasv_error;
2520 	if (pasv_addr.su_family == AF_INET)
2521 		a = (char *) &pasv_addr.su_sin.sin_addr;
2522 	else if (pasv_addr.su_family == AF_INET6 &&
2523 		 IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr))
2524 		a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
2525 	else
2526 		goto pasv_error;
2527 
2528 	p = (char *) &pasv_addr.su_port;
2529 
2530 #define UC(b) (((int) b) & 0xff)
2531 
2532 	reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
2533 		UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
2534 	return;
2535 
2536 pasv_error:
2537 	(void) seteuid((uid_t)pw->pw_uid);
2538 	(void) close(pdata);
2539 	pdata = -1;
2540 	perror_reply(425, "Can't open passive connection");
2541 	return;
2542 }
2543 
2544 /*
2545  * Long Passive defined in RFC 1639.
2546  *     228 Entering Long Passive Mode
2547  *         (af, hal, h1, h2, h3,..., pal, p1, p2...)
2548  */
2549 
2550 void
2551 long_passive(char *cmd, int pf)
2552 {
2553 	int len;
2554 	char *p, *a;
2555 
2556 	if (pdata >= 0)		/* close old port if one set */
2557 		close(pdata);
2558 
2559 	if (pf != PF_UNSPEC) {
2560 		if (ctrl_addr.su_family != pf) {
2561 			switch (ctrl_addr.su_family) {
2562 			case AF_INET:
2563 				pf = 1;
2564 				break;
2565 			case AF_INET6:
2566 				pf = 2;
2567 				break;
2568 			default:
2569 				pf = 0;
2570 				break;
2571 			}
2572 			/*
2573 			 * XXX
2574 			 * only EPRT/EPSV ready clients will understand this
2575 			 */
2576 			if (strcmp(cmd, "EPSV") == 0 && pf) {
2577 				reply(522, "Network protocol mismatch, "
2578 					"use (%d)", pf);
2579 			} else
2580 				reply(501, "Network protocol mismatch"); /*XXX*/
2581 
2582 			return;
2583 		}
2584 	}
2585 
2586 	pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2587 	if (pdata < 0) {
2588 		perror_reply(425, "Can't open passive connection");
2589 		return;
2590 	}
2591 
2592 	(void) seteuid((uid_t)0);
2593 
2594 	pasv_addr = ctrl_addr;
2595 	pasv_addr.su_port = 0;
2596 	len = pasv_addr.su_len;
2597 
2598 #ifdef IP_PORTRANGE
2599 	if (ctrl_addr.su_family == AF_INET) {
2600 	    int on = restricted_data_ports ? IP_PORTRANGE_HIGH
2601 					   : IP_PORTRANGE_DEFAULT;
2602 
2603 	    if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2604 			    (char *)&on, sizeof(on)) < 0)
2605 		    goto pasv_error;
2606 	}
2607 #endif
2608 #ifdef IPV6_PORTRANGE
2609 	if (ctrl_addr.su_family == AF_INET6) {
2610 	    int on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
2611 					   : IPV6_PORTRANGE_DEFAULT;
2612 
2613 	    if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2614 			    (char *)&on, sizeof(on)) < 0)
2615 		    goto pasv_error;
2616 	}
2617 #endif
2618 
2619 	if (bind(pdata, (struct sockaddr *)&pasv_addr, len) < 0)
2620 		goto pasv_error;
2621 
2622 	(void) seteuid((uid_t)pw->pw_uid);
2623 
2624 	if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2625 		goto pasv_error;
2626 	if (listen(pdata, 1) < 0)
2627 		goto pasv_error;
2628 
2629 #define UC(b) (((int) b) & 0xff)
2630 
2631 	if (strcmp(cmd, "LPSV") == 0) {
2632 		p = (char *)&pasv_addr.su_port;
2633 		switch (pasv_addr.su_family) {
2634 		case AF_INET:
2635 			a = (char *) &pasv_addr.su_sin.sin_addr;
2636 		v4_reply:
2637 			reply(228,
2638 "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)",
2639 			      4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2640 			      2, UC(p[0]), UC(p[1]));
2641 			return;
2642 		case AF_INET6:
2643 			if (IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr)) {
2644 				a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
2645 				goto v4_reply;
2646 			}
2647 			a = (char *) &pasv_addr.su_sin6.sin6_addr;
2648 			reply(228,
2649 "Entering Long Passive Mode "
2650 "(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)",
2651 			      6, 16, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2652 			      UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]),
2653 			      UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]),
2654 			      UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]),
2655 			      2, UC(p[0]), UC(p[1]));
2656 			return;
2657 		}
2658 	} else if (strcmp(cmd, "EPSV") == 0) {
2659 		switch (pasv_addr.su_family) {
2660 		case AF_INET:
2661 		case AF_INET6:
2662 			reply(229, "Entering Extended Passive Mode (|||%d|)",
2663 				ntohs(pasv_addr.su_port));
2664 			return;
2665 		}
2666 	} else {
2667 		/* more proper error code? */
2668 	}
2669 
2670 pasv_error:
2671 	(void) seteuid((uid_t)pw->pw_uid);
2672 	(void) close(pdata);
2673 	pdata = -1;
2674 	perror_reply(425, "Can't open passive connection");
2675 	return;
2676 }
2677 
2678 /*
2679  * Generate unique name for file with basename "local".
2680  * The file named "local" is already known to exist.
2681  * Generates failure reply on error.
2682  */
2683 static char *
2684 gunique(char *local)
2685 {
2686 	static char new[MAXPATHLEN];
2687 	struct stat st;
2688 	int count;
2689 	char *cp;
2690 
2691 	cp = strrchr(local, '/');
2692 	if (cp)
2693 		*cp = '\0';
2694 	if (stat(cp ? local : ".", &st) < 0) {
2695 		perror_reply(553, cp ? local : ".");
2696 		return ((char *) 0);
2697 	}
2698 	if (cp)
2699 		*cp = '/';
2700 	/* -4 is for the .nn<null> we put on the end below */
2701 	(void) snprintf(new, sizeof(new) - 4, "%s", local);
2702 	cp = new + strlen(new);
2703 	*cp++ = '.';
2704 	for (count = 1; count < 100; count++) {
2705 		(void)sprintf(cp, "%d", count);
2706 		if (stat(new, &st) < 0)
2707 			return (new);
2708 	}
2709 	reply(452, "Unique file name cannot be created.");
2710 	return (NULL);
2711 }
2712 
2713 /*
2714  * Format and send reply containing system error number.
2715  */
2716 void
2717 perror_reply(int code, char *string)
2718 {
2719 
2720 	reply(code, "%s: %s.", string, strerror(errno));
2721 }
2722 
2723 static char *onefile[] = {
2724 	"",
2725 	0
2726 };
2727 
2728 void
2729 send_file_list(char *whichf)
2730 {
2731 	struct stat st;
2732 	DIR *dirp = NULL;
2733 	struct dirent *dir;
2734 	FILE *dout = NULL;
2735 	char **dirlist, *dirname;
2736 	int simple = 0;
2737 	int freeglob = 0;
2738 	glob_t gl;
2739 
2740 	if (strpbrk(whichf, "~{[*?") != NULL) {
2741 		int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
2742 
2743 		memset(&gl, 0, sizeof(gl));
2744 		gl.gl_matchc = MAXGLOBARGS;
2745 		flags |= GLOB_LIMIT;
2746 		freeglob = 1;
2747 		if (glob(whichf, flags, 0, &gl)) {
2748 			reply(550, "not found");
2749 			goto out;
2750 		} else if (gl.gl_pathc == 0) {
2751 			errno = ENOENT;
2752 			perror_reply(550, whichf);
2753 			goto out;
2754 		}
2755 		dirlist = gl.gl_pathv;
2756 	} else {
2757 		onefile[0] = whichf;
2758 		dirlist = onefile;
2759 		simple = 1;
2760 	}
2761 
2762 	while ((dirname = *dirlist++)) {
2763 		if (stat(dirname, &st) < 0) {
2764 			/*
2765 			 * If user typed "ls -l", etc, and the client
2766 			 * used NLST, do what the user meant.
2767 			 */
2768 			if (dirname[0] == '-' && *dirlist == NULL &&
2769 			    transflag == 0) {
2770 				retrieve(_PATH_LS " %s", dirname);
2771 				goto out;
2772 			}
2773 			perror_reply(550, whichf);
2774 			if (dout != NULL) {
2775 				(void) fclose(dout);
2776 				transflag = 0;
2777 				data = -1;
2778 				pdata = -1;
2779 			}
2780 			goto out;
2781 		}
2782 
2783 		if (S_ISREG(st.st_mode)) {
2784 			if (dout == NULL) {
2785 				dout = dataconn("file list", (off_t)-1, "w");
2786 				if (dout == NULL)
2787 					goto out;
2788 				transflag++;
2789 			}
2790 			fprintf(dout, "%s%s\n", dirname,
2791 				type == TYPE_A ? "\r" : "");
2792 			byte_count += strlen(dirname) + 1;
2793 			continue;
2794 		} else if (!S_ISDIR(st.st_mode))
2795 			continue;
2796 
2797 		if ((dirp = opendir(dirname)) == NULL)
2798 			continue;
2799 
2800 		while ((dir = readdir(dirp)) != NULL) {
2801 			char nbuf[MAXPATHLEN];
2802 
2803 			if (recvurg) {
2804 				myoob();
2805 				recvurg = 0;
2806 				transflag = 0;
2807 				goto out;
2808 			}
2809 
2810 			if (dir->d_name[0] == '.' && dir->d_namlen == 1)
2811 				continue;
2812 			if (dir->d_name[0] == '.' && dir->d_name[1] == '.' &&
2813 			    dir->d_namlen == 2)
2814 				continue;
2815 
2816 			snprintf(nbuf, sizeof(nbuf),
2817 				"%s/%s", dirname, dir->d_name);
2818 
2819 			/*
2820 			 * We have to do a stat to insure it's
2821 			 * not a directory or special file.
2822 			 */
2823 			if (simple || (stat(nbuf, &st) == 0 &&
2824 			    S_ISREG(st.st_mode))) {
2825 				if (dout == NULL) {
2826 					dout = dataconn("file list", (off_t)-1,
2827 						"w");
2828 					if (dout == NULL)
2829 						goto out;
2830 					transflag++;
2831 				}
2832 				if (nbuf[0] == '.' && nbuf[1] == '/')
2833 					fprintf(dout, "%s%s\n", &nbuf[2],
2834 						type == TYPE_A ? "\r" : "");
2835 				else
2836 					fprintf(dout, "%s%s\n", nbuf,
2837 						type == TYPE_A ? "\r" : "");
2838 				byte_count += strlen(nbuf) + 1;
2839 			}
2840 		}
2841 		(void) closedir(dirp);
2842 	}
2843 
2844 	if (dout == NULL)
2845 		reply(550, "No files found.");
2846 	else if (ferror(dout) != 0)
2847 		perror_reply(550, "Data connection");
2848 	else
2849 		reply(226, "Transfer complete.");
2850 
2851 	transflag = 0;
2852 	if (dout != NULL)
2853 		(void) fclose(dout);
2854 	data = -1;
2855 	pdata = -1;
2856 out:
2857 	if (freeglob) {
2858 		freeglob = 0;
2859 		globfree(&gl);
2860 	}
2861 }
2862 
2863 void
2864 reapchild(int signo)
2865 {
2866 	while (wait3(NULL, WNOHANG, NULL) > 0);
2867 }
2868 
2869 #ifdef OLD_SETPROCTITLE
2870 /*
2871  * Clobber argv so ps will show what we're doing.  (Stolen from sendmail.)
2872  * Warning, since this is usually started from inetd.conf, it often doesn't
2873  * have much of an environment or arglist to overwrite.
2874  */
2875 void
2876 setproctitle(const char *fmt, ...)
2877 {
2878 	int i;
2879 	va_list ap;
2880 	char *p, *bp, ch;
2881 	char buf[LINE_MAX];
2882 
2883 	va_start(ap, fmt);
2884 	(void)vsnprintf(buf, sizeof(buf), fmt, ap);
2885 
2886 	/* make ps print our process name */
2887 	p = Argv[0];
2888 	*p++ = '-';
2889 
2890 	i = strlen(buf);
2891 	if (i > LastArgv - p - 2) {
2892 		i = LastArgv - p - 2;
2893 		buf[i] = '\0';
2894 	}
2895 	bp = buf;
2896 	while (ch = *bp++)
2897 		if (ch != '\n' && ch != '\r')
2898 			*p++ = ch;
2899 	while (p < LastArgv)
2900 		*p++ = ' ';
2901 }
2902 #endif /* OLD_SETPROCTITLE */
2903 
2904 static void
2905 logxfer(char *name, off_t size, time_t start)
2906 {
2907 	char buf[1024];
2908 	char path[MAXPATHLEN + 1];
2909 	time_t now;
2910 
2911 	if (statfd >= 0 && getwd(path) != NULL) {
2912 		time(&now);
2913 		snprintf(buf, sizeof(buf), "%.20s!%s!%s!%s/%s!%qd!%ld\n",
2914 			ctime(&now)+4, ident, remotehost,
2915 			path, name, (long long)size,
2916 			(long)(now - start + (now == start)));
2917 		write(statfd, buf, strlen(buf));
2918 	}
2919 }
2920