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