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