xref: /freebsd/libexec/ftpd/ftpd.c (revision 6780ab54325a71e7e70112b11657973edde8655e)
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, %s",
1407 				    remotehost, curname);
1408 			pw = NULL;
1409 			if (login_attempts++ >= 5) {
1410 				syslog(LOG_NOTICE,
1411 				    "repeated login failures from %s",
1412 				    remotehost);
1413 				exit(0);
1414 			}
1415 			return;
1416 		}
1417 	}
1418 	login_attempts = 0;		/* this time successful */
1419 	if (setegid((gid_t)pw->pw_gid) < 0) {
1420 		reply(550, "Can't set gid.");
1421 		return;
1422 	}
1423 	/* May be overridden by login.conf */
1424 	(void) umask(defumask);
1425 #ifdef	LOGIN_CAP
1426 	if ((lc = login_getpwclass(pw)) != NULL) {
1427 		char	remote_ip[MAXHOSTNAMELEN];
1428 
1429 		getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
1430 			remote_ip, sizeof(remote_ip) - 1, NULL, 0,
1431 			NI_NUMERICHOST);
1432 		remote_ip[sizeof(remote_ip) - 1] = 0;
1433 		if (!auth_hostok(lc, remotehost, remote_ip)) {
1434 			syslog(LOG_INFO|LOG_AUTH,
1435 			    "FTP LOGIN FAILED (HOST) as %s: permission denied.",
1436 			    pw->pw_name);
1437 			reply(530, "Permission denied.\n");
1438 			pw = NULL;
1439 			return;
1440 		}
1441 		if (!auth_timeok(lc, time(NULL))) {
1442 			reply(530, "Login not available right now.\n");
1443 			pw = NULL;
1444 			return;
1445 		}
1446 	}
1447 	setusercontext(lc, pw, (uid_t)0,
1448 		LOGIN_SETLOGIN|LOGIN_SETGROUP|LOGIN_SETPRIORITY|
1449 		LOGIN_SETRESOURCES|LOGIN_SETUMASK|LOGIN_SETMAC);
1450 #else
1451 	setlogin(pw->pw_name);
1452 	(void) initgroups(pw->pw_name, pw->pw_gid);
1453 #endif
1454 
1455 #ifdef USE_PAM
1456 	if (pamh) {
1457 		if ((e = pam_open_session(pamh, 0)) != PAM_SUCCESS) {
1458 			syslog(LOG_ERR, "pam_open_session: %s", pam_strerror(pamh, e));
1459 		} else if ((e = pam_setcred(pamh, PAM_ESTABLISH_CRED)) != PAM_SUCCESS) {
1460 			syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e));
1461 		}
1462 	}
1463 #endif
1464 
1465 	/* open wtmp before chroot */
1466 	if (dowtmp)
1467 		ftpd_logwtmp(ttyline, pw->pw_name,
1468 		    (struct sockaddr *)&his_addr);
1469 	logged_in = 1;
1470 
1471 	if (guest && stats && statfd < 0)
1472 #ifdef VIRTUAL_HOSTING
1473 		if ((statfd = open(thishost->statfile, O_WRONLY|O_APPEND)) < 0)
1474 #else
1475 		if ((statfd = open(_PATH_FTPDSTATFILE, O_WRONLY|O_APPEND)) < 0)
1476 #endif
1477 			stats = 0;
1478 
1479 	dochroot =
1480 		checkuser(_PATH_FTPCHROOT, pw->pw_name, 1, &residue)
1481 #ifdef	LOGIN_CAP	/* Allow login.conf configuration as well */
1482 		|| login_getcapbool(lc, "ftp-chroot", 0)
1483 #endif
1484 	;
1485 	chrootdir = NULL;
1486 	/*
1487 	 * For a chrooted local user,
1488 	 * a) see whether ftpchroot(5) specifies a chroot directory,
1489 	 * b) extract the directory pathname from the line,
1490 	 * c) expand it to the absolute pathname if necessary.
1491 	 */
1492 	if (dochroot && residue &&
1493 	    (chrootdir = strtok(residue, " \t")) != NULL &&
1494 	    chrootdir[0] != '/') {
1495 		asprintf(&chrootdir, "%s/%s", pw->pw_dir, chrootdir);
1496 		if (chrootdir == NULL)
1497 			fatalerror("Ran out of memory.");
1498 
1499 	}
1500 	if (guest || dochroot) {
1501 		/*
1502 		 * If no chroot directory set yet, use the login directory.
1503 		 * Copy it so it can be modified while pw->pw_dir stays intact.
1504 		 */
1505 		if (chrootdir == NULL &&
1506 		    (chrootdir = strdup(pw->pw_dir)) == NULL)
1507 			fatalerror("Ran out of memory.");
1508 		/*
1509 		 * Check for the "/chroot/./home" syntax,
1510 		 * separate the chroot and home directory pathnames.
1511 		 */
1512 		if ((homedir = strstr(chrootdir, "/./")) != NULL) {
1513 			*(homedir++) = '\0';	/* wipe '/' */
1514 			homedir++;		/* skip '.' */
1515 			/* so chrootdir can be freed later */
1516 			if ((homedir = strdup(homedir)) == NULL)
1517 				fatalerror("Ran out of memory.");
1518 		} else {
1519 			/*
1520 			 * We MUST do a chdir() after the chroot. Otherwise
1521 			 * the old current directory will be accessible as "."
1522 			 * outside the new root!
1523 			 */
1524 			homedir = "/";
1525 		}
1526 		/*
1527 		 * Finally, do chroot()
1528 		 */
1529 		if (chroot(chrootdir) < 0) {
1530 			reply(550, "Can't change root.");
1531 			goto bad;
1532 		}
1533 	} else	/* real user w/o chroot */
1534 		homedir = pw->pw_dir;
1535 	/*
1536 	 * Set euid *before* doing chdir() so
1537 	 * a) the user won't be carried to a directory that he couldn't reach
1538 	 *    on his own due to no permission to upper path components,
1539 	 * b) NFS mounted homedirs w/restrictive permissions will be accessible
1540 	 *    (uid 0 has no root power over NFS if not mapped explicitly.)
1541 	 */
1542 	if (seteuid((uid_t)pw->pw_uid) < 0) {
1543 		reply(550, "Can't set uid.");
1544 		goto bad;
1545 	}
1546 	if (chdir(homedir) < 0) {
1547 		if (guest || dochroot) {
1548 			reply(550, "Can't change to base directory.");
1549 			goto bad;
1550 		} else {
1551 			if (chdir("/") < 0) {
1552 				reply(550, "Root is inaccessible.");
1553 				goto bad;
1554 			}
1555 			lreply(230, "No directory! Logging in with home=/");
1556 		}
1557 	}
1558 
1559 	/*
1560 	 * Display a login message, if it exists.
1561 	 * N.B. reply(230,) must follow the message.
1562 	 */
1563 #ifdef VIRTUAL_HOSTING
1564 	if ((fd = fopen(thishost->loginmsg, "r")) != NULL) {
1565 #else
1566 	if ((fd = fopen(_PATH_FTPLOGINMESG, "r")) != NULL) {
1567 #endif
1568 		char *cp, line[LINE_MAX];
1569 
1570 		while (fgets(line, sizeof(line), fd) != NULL) {
1571 			if ((cp = strchr(line, '\n')) != NULL)
1572 				*cp = '\0';
1573 			lreply(230, "%s", line);
1574 		}
1575 		(void) fflush(stdout);
1576 		(void) fclose(fd);
1577 	}
1578 	if (guest) {
1579 		if (ident != NULL)
1580 			free(ident);
1581 		ident = strdup(passwd);
1582 		if (ident == NULL)
1583 			fatalerror("Ran out of memory.");
1584 
1585 		reply(230, "Guest login ok, access restrictions apply.");
1586 #ifdef SETPROCTITLE
1587 #ifdef VIRTUAL_HOSTING
1588 		if (thishost != firsthost)
1589 			snprintf(proctitle, sizeof(proctitle),
1590 				 "%s: anonymous(%s)/%s", remotehost, hostname,
1591 				 passwd);
1592 		else
1593 #endif
1594 			snprintf(proctitle, sizeof(proctitle),
1595 				 "%s: anonymous/%s", remotehost, passwd);
1596 		setproctitle("%s", proctitle);
1597 #endif /* SETPROCTITLE */
1598 		if (logging)
1599 			syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s, %s",
1600 			    remotehost, passwd);
1601 	} else {
1602 		if (dochroot)
1603 			reply(230, "User %s logged in, "
1604 				   "access restrictions apply.", pw->pw_name);
1605 		else
1606 			reply(230, "User %s logged in.", pw->pw_name);
1607 
1608 #ifdef SETPROCTITLE
1609 		snprintf(proctitle, sizeof(proctitle),
1610 			 "%s: user/%s", remotehost, pw->pw_name);
1611 		setproctitle("%s", proctitle);
1612 #endif /* SETPROCTITLE */
1613 		if (logging)
1614 			syslog(LOG_INFO, "FTP LOGIN FROM %s as %s",
1615 			    remotehost, pw->pw_name);
1616 	}
1617 #ifdef	LOGIN_CAP
1618 	login_close(lc);
1619 #endif
1620 	if (chrootdir)
1621 		free(chrootdir);
1622 	if (residue)
1623 		free(residue);
1624 	return;
1625 bad:
1626 	/* Forget all about it... */
1627 #ifdef	LOGIN_CAP
1628 	login_close(lc);
1629 #endif
1630 	if (chrootdir)
1631 		free(chrootdir);
1632 	if (residue)
1633 		free(residue);
1634 	end_login();
1635 }
1636 
1637 void
1638 retrieve(char *cmd, char *name)
1639 {
1640 	FILE *fin, *dout;
1641 	struct stat st;
1642 	int (*closefunc)(FILE *);
1643 	time_t start;
1644 
1645 	if (cmd == 0) {
1646 		fin = fopen(name, "r"), closefunc = fclose;
1647 		st.st_size = 0;
1648 	} else {
1649 		char line[BUFSIZ];
1650 
1651 		(void) snprintf(line, sizeof(line), cmd, name), name = line;
1652 		fin = ftpd_popen(line, "r"), closefunc = ftpd_pclose;
1653 		st.st_size = -1;
1654 		st.st_blksize = BUFSIZ;
1655 	}
1656 	if (fin == NULL) {
1657 		if (errno != 0) {
1658 			perror_reply(550, name);
1659 			if (cmd == 0) {
1660 				LOGCMD("get", name);
1661 			}
1662 		}
1663 		return;
1664 	}
1665 	byte_count = -1;
1666 	if (cmd == 0) {
1667 		if (fstat(fileno(fin), &st) < 0) {
1668 			perror_reply(550, name);
1669 			goto done;
1670 		}
1671 		if (!S_ISREG(st.st_mode)) {
1672 			if (guest) {
1673 				reply(550, "%s: not a plain file.", name);
1674 				goto done;
1675 			}
1676 			st.st_size = -1;
1677 			/* st.st_blksize is set for all descriptor types */
1678 		}
1679 	}
1680 	if (restart_point) {
1681 		if (type == TYPE_A) {
1682 			off_t i, n;
1683 			int c;
1684 
1685 			n = restart_point;
1686 			i = 0;
1687 			while (i++ < n) {
1688 				if ((c=getc(fin)) == EOF) {
1689 					perror_reply(550, name);
1690 					goto done;
1691 				}
1692 				if (c == '\n')
1693 					i++;
1694 			}
1695 		} else if (lseek(fileno(fin), restart_point, L_SET) < 0) {
1696 			perror_reply(550, name);
1697 			goto done;
1698 		}
1699 	}
1700 	dout = dataconn(name, st.st_size, "w");
1701 	if (dout == NULL)
1702 		goto done;
1703 	time(&start);
1704 	send_data(fin, dout, st.st_blksize, st.st_size,
1705 		  restart_point == 0 && cmd == 0 && S_ISREG(st.st_mode));
1706 	if (cmd == 0 && guest && stats)
1707 		logxfer(name, st.st_size, start);
1708 	(void) fclose(dout);
1709 	data = -1;
1710 	pdata = -1;
1711 done:
1712 	if (cmd == 0)
1713 		LOGBYTES("get", name, byte_count);
1714 	(*closefunc)(fin);
1715 }
1716 
1717 void
1718 store(char *name, char *mode, int unique)
1719 {
1720 	int fd;
1721 	FILE *fout, *din;
1722 	int (*closefunc)(FILE *);
1723 
1724 	if (*mode == 'a') {		/* APPE */
1725 		if (unique) {
1726 			/* Programming error */
1727 			syslog(LOG_ERR, "Internal: unique flag to APPE");
1728 			unique = 0;
1729 		}
1730 		if (guest && noguestmod) {
1731 			reply(550, "Appending to existing file denied");
1732 			goto err;
1733 		}
1734 		restart_point = 0;	/* not affected by preceding REST */
1735 	}
1736 	if (unique)			/* STOU overrides REST */
1737 		restart_point = 0;
1738 	if (guest && noguestmod) {
1739 		if (restart_point) {	/* guest STOR w/REST */
1740 			reply(550, "Modifying existing file denied");
1741 			goto err;
1742 		} else			/* treat guest STOR as STOU */
1743 			unique = 1;
1744 	}
1745 
1746 	if (restart_point)
1747 		mode = "r+";	/* so ASCII manual seek can work */
1748 	if (unique) {
1749 		if ((fd = guniquefd(name, &name)) < 0)
1750 			goto err;
1751 		fout = fdopen(fd, mode);
1752 	} else
1753 		fout = fopen(name, mode);
1754 	closefunc = fclose;
1755 	if (fout == NULL) {
1756 		perror_reply(553, name);
1757 		goto err;
1758 	}
1759 	byte_count = -1;
1760 	if (restart_point) {
1761 		if (type == TYPE_A) {
1762 			off_t i, n;
1763 			int c;
1764 
1765 			n = restart_point;
1766 			i = 0;
1767 			while (i++ < n) {
1768 				if ((c=getc(fout)) == EOF) {
1769 					perror_reply(550, name);
1770 					goto done;
1771 				}
1772 				if (c == '\n')
1773 					i++;
1774 			}
1775 			/*
1776 			 * We must do this seek to "current" position
1777 			 * because we are changing from reading to
1778 			 * writing.
1779 			 */
1780 			if (fseeko(fout, (off_t)0, SEEK_CUR) < 0) {
1781 				perror_reply(550, name);
1782 				goto done;
1783 			}
1784 		} else if (lseek(fileno(fout), restart_point, L_SET) < 0) {
1785 			perror_reply(550, name);
1786 			goto done;
1787 		}
1788 	}
1789 	din = dataconn(name, (off_t)-1, "r");
1790 	if (din == NULL)
1791 		goto done;
1792 	if (receive_data(din, fout) == 0) {
1793 		if (unique)
1794 			reply(226, "Transfer complete (unique file name:%s).",
1795 			    name);
1796 		else
1797 			reply(226, "Transfer complete.");
1798 	}
1799 	(void) fclose(din);
1800 	data = -1;
1801 	pdata = -1;
1802 done:
1803 	LOGBYTES(*mode == 'a' ? "append" : "put", name, byte_count);
1804 	(*closefunc)(fout);
1805 	return;
1806 err:
1807 	LOGCMD(*mode == 'a' ? "append" : "put" , name);
1808 	return;
1809 }
1810 
1811 static FILE *
1812 getdatasock(char *mode)
1813 {
1814 	int on = 1, s, t, tries;
1815 
1816 	if (data >= 0)
1817 		return (fdopen(data, mode));
1818 	(void) seteuid((uid_t)0);
1819 
1820 	s = socket(data_dest.su_family, SOCK_STREAM, 0);
1821 	if (s < 0)
1822 		goto bad;
1823 	if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
1824 		syslog(LOG_WARNING, "data setsockopt (SO_REUSEADDR): %m");
1825 	/* anchor socket to avoid multi-homing problems */
1826 	data_source = ctrl_addr;
1827 	data_source.su_port = htons(dataport);
1828 	for (tries = 1; ; tries++) {
1829 		if (bind(s, (struct sockaddr *)&data_source,
1830 		    data_source.su_len) >= 0)
1831 			break;
1832 		if (errno != EADDRINUSE || tries > 10)
1833 			goto bad;
1834 		sleep(tries);
1835 	}
1836 	(void) seteuid((uid_t)pw->pw_uid);
1837 #ifdef IP_TOS
1838 	if (data_source.su_family == AF_INET)
1839       {
1840 	on = IPTOS_THROUGHPUT;
1841 	if (setsockopt(s, IPPROTO_IP, IP_TOS, &on, sizeof(int)) < 0)
1842 		syslog(LOG_WARNING, "data setsockopt (IP_TOS): %m");
1843       }
1844 #endif
1845 #ifdef TCP_NOPUSH
1846 	/*
1847 	 * Turn off push flag to keep sender TCP from sending short packets
1848 	 * at the boundaries of each write().  Should probably do a SO_SNDBUF
1849 	 * to set the send buffer size as well, but that may not be desirable
1850 	 * in heavy-load situations.
1851 	 */
1852 	on = 1;
1853 	if (setsockopt(s, IPPROTO_TCP, TCP_NOPUSH, &on, sizeof on) < 0)
1854 		syslog(LOG_WARNING, "data setsockopt (TCP_NOPUSH): %m");
1855 #endif
1856 #ifdef SO_SNDBUF
1857 	on = 65536;
1858 	if (setsockopt(s, SOL_SOCKET, SO_SNDBUF, &on, sizeof on) < 0)
1859 		syslog(LOG_WARNING, "data setsockopt (SO_SNDBUF): %m");
1860 #endif
1861 
1862 	return (fdopen(s, mode));
1863 bad:
1864 	/* Return the real value of errno (close may change it) */
1865 	t = errno;
1866 	(void) seteuid((uid_t)pw->pw_uid);
1867 	(void) close(s);
1868 	errno = t;
1869 	return (NULL);
1870 }
1871 
1872 static FILE *
1873 dataconn(char *name, off_t size, char *mode)
1874 {
1875 	char sizebuf[32];
1876 	FILE *file;
1877 	int retry = 0, tos, conerrno;
1878 
1879 	file_size = size;
1880 	byte_count = 0;
1881 	if (size != (off_t) -1)
1882 		(void) snprintf(sizebuf, sizeof(sizebuf), " (%qd bytes)", size);
1883 	else
1884 		*sizebuf = '\0';
1885 	if (pdata >= 0) {
1886 		union sockunion from;
1887 		int flags;
1888 		int s, fromlen = ctrl_addr.su_len;
1889 		struct timeval timeout;
1890 		fd_set set;
1891 
1892 		FD_ZERO(&set);
1893 		FD_SET(pdata, &set);
1894 
1895 		timeout.tv_usec = 0;
1896 		timeout.tv_sec = 120;
1897 
1898 		/*
1899 		 * Granted a socket is in the blocking I/O mode,
1900 		 * accept() will block after a successful select()
1901 		 * if the selected connection dies in between.
1902 		 * Therefore set the non-blocking I/O flag here.
1903 		 */
1904 		if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1905 		    fcntl(pdata, F_SETFL, flags | O_NONBLOCK) == -1)
1906 			goto pdata_err;
1907 		if (select(pdata+1, &set, (fd_set *) 0, (fd_set *) 0, &timeout) <= 0 ||
1908 		    (s = accept(pdata, (struct sockaddr *) &from, &fromlen)) < 0)
1909 			goto pdata_err;
1910 		(void) close(pdata);
1911 		pdata = s;
1912 		/*
1913 		 * Unset the inherited non-blocking I/O flag
1914 		 * on the child socket so stdio can work on it.
1915 		 */
1916 		if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1917 		    fcntl(pdata, F_SETFL, flags & ~O_NONBLOCK) == -1)
1918 			goto pdata_err;
1919 #ifdef IP_TOS
1920 		if (from.su_family == AF_INET)
1921 	      {
1922 		tos = IPTOS_THROUGHPUT;
1923 		if (setsockopt(s, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
1924 			syslog(LOG_WARNING, "pdata setsockopt (IP_TOS): %m");
1925 	      }
1926 #endif
1927 		reply(150, "Opening %s mode data connection for '%s'%s.",
1928 		     type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1929 		return (fdopen(pdata, mode));
1930 pdata_err:
1931 		reply(425, "Can't open data connection.");
1932 		(void) close(pdata);
1933 		pdata = -1;
1934 		return (NULL);
1935 	}
1936 	if (data >= 0) {
1937 		reply(125, "Using existing data connection for '%s'%s.",
1938 		    name, sizebuf);
1939 		usedefault = 1;
1940 		return (fdopen(data, mode));
1941 	}
1942 	if (usedefault)
1943 		data_dest = his_addr;
1944 	usedefault = 1;
1945 	do {
1946 		file = getdatasock(mode);
1947 		if (file == NULL) {
1948 			char hostbuf[BUFSIZ], portbuf[BUFSIZ];
1949 			getnameinfo((struct sockaddr *)&data_source,
1950 				data_source.su_len, hostbuf, sizeof(hostbuf) - 1,
1951 				portbuf, sizeof(portbuf),
1952 				NI_NUMERICHOST|NI_NUMERICSERV);
1953 			reply(425, "Can't create data socket (%s,%s): %s.",
1954 				hostbuf, portbuf, strerror(errno));
1955 			return (NULL);
1956 		}
1957 		data = fileno(file);
1958 		conerrno = 0;
1959 		if (connect(data, (struct sockaddr *)&data_dest,
1960 		    data_dest.su_len) == 0)
1961 			break;
1962 		conerrno = errno;
1963 		(void) fclose(file);
1964 		data = -1;
1965 		if (conerrno == EADDRINUSE) {
1966 			sleep((unsigned) swaitint);
1967 			retry += swaitint;
1968 		} else {
1969 			break;
1970 		}
1971 	} while (retry <= swaitmax);
1972 	if (conerrno != 0) {
1973 		perror_reply(425, "Can't build data connection");
1974 		return (NULL);
1975 	}
1976 	reply(150, "Opening %s mode data connection for '%s'%s.",
1977 	     type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1978 	return (file);
1979 }
1980 
1981 /*
1982  * Tranfer the contents of "instr" to "outstr" peer using the appropriate
1983  * encapsulation of the data subject to Mode, Structure, and Type.
1984  *
1985  * NB: Form isn't handled.
1986  */
1987 static int
1988 send_data(FILE *instr, FILE *outstr, off_t blksize, off_t filesize, int isreg)
1989 {
1990 	int c, filefd, netfd;
1991 	char *buf;
1992 	off_t cnt;
1993 
1994 	transflag++;
1995 	switch (type) {
1996 
1997 	case TYPE_A:
1998 		while ((c = getc(instr)) != EOF) {
1999 			if (recvurg)
2000 				goto got_oob;
2001 			byte_count++;
2002 			if (c == '\n') {
2003 				if (ferror(outstr))
2004 					goto data_err;
2005 				(void) putc('\r', outstr);
2006 			}
2007 			(void) putc(c, outstr);
2008 		}
2009 		if (recvurg)
2010 			goto got_oob;
2011 		fflush(outstr);
2012 		transflag = 0;
2013 		if (ferror(instr))
2014 			goto file_err;
2015 		if (ferror(outstr))
2016 			goto data_err;
2017 		reply(226, "Transfer complete.");
2018 		return (0);
2019 
2020 	case TYPE_I:
2021 	case TYPE_L:
2022 		/*
2023 		 * isreg is only set if we are not doing restart and we
2024 		 * are sending a regular file
2025 		 */
2026 		netfd = fileno(outstr);
2027 		filefd = fileno(instr);
2028 
2029 		if (isreg) {
2030 
2031 			off_t offset;
2032 			int err;
2033 
2034 			err = cnt = offset = 0;
2035 
2036 			while (err != -1 && filesize > 0) {
2037 				err = sendfile(filefd, netfd, offset, 0,
2038 					(struct sf_hdtr *) NULL, &cnt, 0);
2039 				/*
2040 				 * Calculate byte_count before OOB processing.
2041 				 * It can be used in myoob() later.
2042 				 */
2043 				byte_count += cnt;
2044 				if (recvurg)
2045 					goto got_oob;
2046 				offset += cnt;
2047 				filesize -= cnt;
2048 
2049 				if (err == -1) {
2050 					if (!cnt)
2051 						goto oldway;
2052 
2053 					goto data_err;
2054 				}
2055 			}
2056 
2057 			transflag = 0;
2058 			reply(226, "Transfer complete.");
2059 			return (0);
2060 		}
2061 
2062 oldway:
2063 		if ((buf = malloc((u_int)blksize)) == NULL) {
2064 			transflag = 0;
2065 			perror_reply(451, "Local resource failure: malloc");
2066 			return (-1);
2067 		}
2068 
2069 		while ((cnt = read(filefd, buf, (u_int)blksize)) > 0 &&
2070 		    write(netfd, buf, cnt) == cnt)
2071 			byte_count += cnt;
2072 		transflag = 0;
2073 		(void)free(buf);
2074 		if (cnt != 0) {
2075 			if (cnt < 0)
2076 				goto file_err;
2077 			goto data_err;
2078 		}
2079 		reply(226, "Transfer complete.");
2080 		return (0);
2081 	default:
2082 		transflag = 0;
2083 		reply(550, "Unimplemented TYPE %d in send_data", type);
2084 		return (-1);
2085 	}
2086 
2087 data_err:
2088 	transflag = 0;
2089 	perror_reply(426, "Data connection");
2090 	return (-1);
2091 
2092 file_err:
2093 	transflag = 0;
2094 	perror_reply(551, "Error on input file");
2095 	return (-1);
2096 
2097 got_oob:
2098 	myoob();
2099 	recvurg = 0;
2100 	transflag = 0;
2101 	return (-1);
2102 }
2103 
2104 /*
2105  * Transfer data from peer to "outstr" using the appropriate encapulation of
2106  * the data subject to Mode, Structure, and Type.
2107  *
2108  * N.B.: Form isn't handled.
2109  */
2110 static int
2111 receive_data(FILE *instr, FILE *outstr)
2112 {
2113 	int c;
2114 	int cnt, bare_lfs;
2115 	char buf[BUFSIZ];
2116 
2117 	transflag++;
2118 	bare_lfs = 0;
2119 
2120 	switch (type) {
2121 
2122 	case TYPE_I:
2123 	case TYPE_L:
2124 		while ((cnt = read(fileno(instr), buf, sizeof(buf))) > 0) {
2125 			if (recvurg)
2126 				goto got_oob;
2127 			if (write(fileno(outstr), buf, cnt) != cnt)
2128 				goto file_err;
2129 			byte_count += cnt;
2130 		}
2131 		if (recvurg)
2132 			goto got_oob;
2133 		if (cnt < 0)
2134 			goto data_err;
2135 		transflag = 0;
2136 		return (0);
2137 
2138 	case TYPE_E:
2139 		reply(553, "TYPE E not implemented.");
2140 		transflag = 0;
2141 		return (-1);
2142 
2143 	case TYPE_A:
2144 		while ((c = getc(instr)) != EOF) {
2145 			if (recvurg)
2146 				goto got_oob;
2147 			byte_count++;
2148 			if (c == '\n')
2149 				bare_lfs++;
2150 			while (c == '\r') {
2151 				if (ferror(outstr))
2152 					goto data_err;
2153 				if ((c = getc(instr)) != '\n') {
2154 					(void) putc ('\r', outstr);
2155 					if (c == '\0' || c == EOF)
2156 						goto contin2;
2157 				}
2158 			}
2159 			(void) putc(c, outstr);
2160 	contin2:	;
2161 		}
2162 		if (recvurg)
2163 			goto got_oob;
2164 		fflush(outstr);
2165 		if (ferror(instr))
2166 			goto data_err;
2167 		if (ferror(outstr))
2168 			goto file_err;
2169 		transflag = 0;
2170 		if (bare_lfs) {
2171 			lreply(226,
2172 		"WARNING! %d bare linefeeds received in ASCII mode",
2173 			    bare_lfs);
2174 		(void)printf("   File may not have transferred correctly.\r\n");
2175 		}
2176 		return (0);
2177 	default:
2178 		reply(550, "Unimplemented TYPE %d in receive_data", type);
2179 		transflag = 0;
2180 		return (-1);
2181 	}
2182 
2183 data_err:
2184 	transflag = 0;
2185 	perror_reply(426, "Data Connection");
2186 	return (-1);
2187 
2188 file_err:
2189 	transflag = 0;
2190 	perror_reply(452, "Error writing file");
2191 	return (-1);
2192 
2193 got_oob:
2194 	myoob();
2195 	recvurg = 0;
2196 	transflag = 0;
2197 	return (-1);
2198 }
2199 
2200 void
2201 statfilecmd(char *filename)
2202 {
2203 	FILE *fin;
2204 	int atstart;
2205 	int c;
2206 	char line[LINE_MAX];
2207 
2208 	(void)snprintf(line, sizeof(line), _PATH_LS " -lgA %s", filename);
2209 	fin = ftpd_popen(line, "r");
2210 	lreply(211, "status of %s:", filename);
2211 	atstart = 1;
2212 	while ((c = getc(fin)) != EOF) {
2213 		if (c == '\n') {
2214 			if (ferror(stdout)){
2215 				perror_reply(421, "control connection");
2216 				(void) ftpd_pclose(fin);
2217 				dologout(1);
2218 				/* NOTREACHED */
2219 			}
2220 			if (ferror(fin)) {
2221 				perror_reply(551, filename);
2222 				(void) ftpd_pclose(fin);
2223 				return;
2224 			}
2225 			(void) putc('\r', stdout);
2226 		}
2227 		/*
2228 		 * RFC 959 says neutral text should be prepended before
2229 		 * a leading 3-digit number followed by whitespace, but
2230 		 * many ftp clients can be confused by any leading digits,
2231 		 * as a matter of fact.
2232 		 */
2233 		if (atstart && isdigit(c))
2234 			(void) putc(' ', stdout);
2235 		(void) putc(c, stdout);
2236 		atstart = (c == '\n');
2237 	}
2238 	(void) ftpd_pclose(fin);
2239 	reply(211, "End of Status");
2240 }
2241 
2242 void
2243 statcmd(void)
2244 {
2245 	union sockunion *su;
2246 	u_char *a, *p;
2247 	char hname[NI_MAXHOST];
2248 	int ispassive;
2249 
2250 	if (hostinfo) {
2251 		lreply(211, "%s FTP server status:", hostname);
2252 		printf("     %s\r\n", version);
2253 	} else
2254 		lreply(211, "FTP server status:");
2255 	printf("     Connected to %s", remotehost);
2256 	if (!getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
2257 			 hname, sizeof(hname) - 1, NULL, 0, NI_NUMERICHOST)) {
2258 		if (strcmp(hname, remotehost) != 0)
2259 			printf(" (%s)", hname);
2260 	}
2261 	printf("\r\n");
2262 	if (logged_in) {
2263 		if (guest)
2264 			printf("     Logged in anonymously\r\n");
2265 		else
2266 			printf("     Logged in as %s\r\n", pw->pw_name);
2267 	} else if (askpasswd)
2268 		printf("     Waiting for password\r\n");
2269 	else
2270 		printf("     Waiting for user name\r\n");
2271 	printf("     TYPE: %s", typenames[type]);
2272 	if (type == TYPE_A || type == TYPE_E)
2273 		printf(", FORM: %s", formnames[form]);
2274 	if (type == TYPE_L)
2275 #if CHAR_BIT == 8
2276 		printf(" %d", CHAR_BIT);
2277 #else
2278 		printf(" %d", bytesize);	/* need definition! */
2279 #endif
2280 	printf("; STRUcture: %s; transfer MODE: %s\r\n",
2281 	    strunames[stru], modenames[mode]);
2282 	if (data != -1)
2283 		printf("     Data connection open\r\n");
2284 	else if (pdata != -1) {
2285 		ispassive = 1;
2286 		su = &pasv_addr;
2287 		goto printaddr;
2288 	} else if (usedefault == 0) {
2289 		ispassive = 0;
2290 		su = &data_dest;
2291 printaddr:
2292 #define UC(b) (((int) b) & 0xff)
2293 		if (epsvall) {
2294 			printf("     EPSV only mode (EPSV ALL)\r\n");
2295 			goto epsvonly;
2296 		}
2297 
2298 		/* PORT/PASV */
2299 		if (su->su_family == AF_INET) {
2300 			a = (u_char *) &su->su_sin.sin_addr;
2301 			p = (u_char *) &su->su_sin.sin_port;
2302 			printf("     %s (%d,%d,%d,%d,%d,%d)\r\n",
2303 				ispassive ? "PASV" : "PORT",
2304 				UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2305 				UC(p[0]), UC(p[1]));
2306 		}
2307 
2308 		/* LPRT/LPSV */
2309 	    {
2310 		int alen, af, i;
2311 
2312 		switch (su->su_family) {
2313 		case AF_INET:
2314 			a = (u_char *) &su->su_sin.sin_addr;
2315 			p = (u_char *) &su->su_sin.sin_port;
2316 			alen = sizeof(su->su_sin.sin_addr);
2317 			af = 4;
2318 			break;
2319 		case AF_INET6:
2320 			a = (u_char *) &su->su_sin6.sin6_addr;
2321 			p = (u_char *) &su->su_sin6.sin6_port;
2322 			alen = sizeof(su->su_sin6.sin6_addr);
2323 			af = 6;
2324 			break;
2325 		default:
2326 			af = 0;
2327 			break;
2328 		}
2329 		if (af) {
2330 			printf("     %s (%d,%d,", ispassive ? "LPSV" : "LPRT",
2331 				af, alen);
2332 			for (i = 0; i < alen; i++)
2333 				printf("%d,", UC(a[i]));
2334 			printf("%d,%d,%d)\r\n", 2, UC(p[0]), UC(p[1]));
2335 		}
2336 	    }
2337 
2338 epsvonly:;
2339 		/* EPRT/EPSV */
2340 	    {
2341 		int af;
2342 
2343 		switch (su->su_family) {
2344 		case AF_INET:
2345 			af = 1;
2346 			break;
2347 		case AF_INET6:
2348 			af = 2;
2349 			break;
2350 		default:
2351 			af = 0;
2352 			break;
2353 		}
2354 		if (af) {
2355 			union sockunion tmp;
2356 
2357 			tmp = *su;
2358 			if (tmp.su_family == AF_INET6)
2359 				tmp.su_sin6.sin6_scope_id = 0;
2360 			if (!getnameinfo((struct sockaddr *)&tmp, tmp.su_len,
2361 					hname, sizeof(hname) - 1, NULL, 0,
2362 					NI_NUMERICHOST)) {
2363 				printf("     %s |%d|%s|%d|\r\n",
2364 					ispassive ? "EPSV" : "EPRT",
2365 					af, hname, htons(tmp.su_port));
2366 			}
2367 		}
2368 	    }
2369 #undef UC
2370 	} else
2371 		printf("     No data connection\r\n");
2372 	reply(211, "End of status");
2373 }
2374 
2375 void
2376 fatalerror(char *s)
2377 {
2378 
2379 	reply(451, "Error in server: %s\n", s);
2380 	reply(221, "Closing connection due to server error.");
2381 	dologout(0);
2382 	/* NOTREACHED */
2383 }
2384 
2385 void
2386 reply(int n, const char *fmt, ...)
2387 {
2388 	va_list ap;
2389 
2390 	va_start(ap, fmt);
2391 	(void)printf("%d ", n);
2392 	(void)vprintf(fmt, ap);
2393 	(void)printf("\r\n");
2394 	(void)fflush(stdout);
2395 	if (ftpdebug) {
2396 		syslog(LOG_DEBUG, "<--- %d ", n);
2397 		vsyslog(LOG_DEBUG, fmt, ap);
2398 	}
2399 }
2400 
2401 void
2402 lreply(int n, const char *fmt, ...)
2403 {
2404 	va_list ap;
2405 
2406 	va_start(ap, fmt);
2407 	(void)printf("%d- ", n);
2408 	(void)vprintf(fmt, ap);
2409 	(void)printf("\r\n");
2410 	(void)fflush(stdout);
2411 	if (ftpdebug) {
2412 		syslog(LOG_DEBUG, "<--- %d- ", n);
2413 		vsyslog(LOG_DEBUG, fmt, ap);
2414 	}
2415 }
2416 
2417 static void
2418 ack(char *s)
2419 {
2420 
2421 	reply(250, "%s command successful.", s);
2422 }
2423 
2424 void
2425 nack(char *s)
2426 {
2427 
2428 	reply(502, "%s command not implemented.", s);
2429 }
2430 
2431 /* ARGSUSED */
2432 void
2433 yyerror(char *s)
2434 {
2435 	char *cp;
2436 
2437 	if ((cp = strchr(cbuf,'\n')))
2438 		*cp = '\0';
2439 	reply(500, "'%s': command not understood.", cbuf);
2440 }
2441 
2442 void
2443 delete(char *name)
2444 {
2445 	struct stat st;
2446 
2447 	LOGCMD("delete", name);
2448 	if (lstat(name, &st) < 0) {
2449 		perror_reply(550, name);
2450 		return;
2451 	}
2452 	if ((st.st_mode&S_IFMT) == S_IFDIR) {
2453 		if (rmdir(name) < 0) {
2454 			perror_reply(550, name);
2455 			return;
2456 		}
2457 		goto done;
2458 	}
2459 	if (unlink(name) < 0) {
2460 		perror_reply(550, name);
2461 		return;
2462 	}
2463 done:
2464 	ack("DELE");
2465 }
2466 
2467 void
2468 cwd(char *path)
2469 {
2470 
2471 	if (chdir(path) < 0)
2472 		perror_reply(550, path);
2473 	else
2474 		ack("CWD");
2475 }
2476 
2477 void
2478 makedir(char *name)
2479 {
2480 	char *s;
2481 
2482 	LOGCMD("mkdir", name);
2483 	if (guest && noguestmkd)
2484 		reply(550, "%s: permission denied", name);
2485 	else if (mkdir(name, 0777) < 0)
2486 		perror_reply(550, name);
2487 	else {
2488 		if ((s = doublequote(name)) == NULL)
2489 			fatalerror("Ran out of memory.");
2490 		reply(257, "\"%s\" directory created.", s);
2491 		free(s);
2492 	}
2493 }
2494 
2495 void
2496 removedir(char *name)
2497 {
2498 
2499 	LOGCMD("rmdir", name);
2500 	if (rmdir(name) < 0)
2501 		perror_reply(550, name);
2502 	else
2503 		ack("RMD");
2504 }
2505 
2506 void
2507 pwd(void)
2508 {
2509 	char *s, path[MAXPATHLEN + 1];
2510 
2511 	if (getwd(path) == (char *)NULL)
2512 		reply(550, "%s.", path);
2513 	else {
2514 		if ((s = doublequote(path)) == NULL)
2515 			fatalerror("Ran out of memory.");
2516 		reply(257, "\"%s\" is current directory.", s);
2517 		free(s);
2518 	}
2519 }
2520 
2521 char *
2522 renamefrom(char *name)
2523 {
2524 	struct stat st;
2525 
2526 	if (lstat(name, &st) < 0) {
2527 		perror_reply(550, name);
2528 		return ((char *)0);
2529 	}
2530 	reply(350, "File exists, ready for destination name");
2531 	return (name);
2532 }
2533 
2534 void
2535 renamecmd(char *from, char *to)
2536 {
2537 	struct stat st;
2538 
2539 	LOGCMD2("rename", from, to);
2540 
2541 	if (guest && (stat(to, &st) == 0)) {
2542 		reply(550, "%s: permission denied", to);
2543 		return;
2544 	}
2545 
2546 	if (rename(from, to) < 0)
2547 		perror_reply(550, "rename");
2548 	else
2549 		ack("RNTO");
2550 }
2551 
2552 static void
2553 dolog(struct sockaddr *who)
2554 {
2555 	int error;
2556 
2557 	realhostname_sa(remotehost, sizeof(remotehost) - 1, who, who->sa_len);
2558 
2559 #ifdef SETPROCTITLE
2560 #ifdef VIRTUAL_HOSTING
2561 	if (thishost != firsthost)
2562 		snprintf(proctitle, sizeof(proctitle), "%s: connected (to %s)",
2563 			 remotehost, hostname);
2564 	else
2565 #endif
2566 		snprintf(proctitle, sizeof(proctitle), "%s: connected",
2567 			 remotehost);
2568 	setproctitle("%s", proctitle);
2569 #endif /* SETPROCTITLE */
2570 
2571 	if (logging) {
2572 #ifdef VIRTUAL_HOSTING
2573 		if (thishost != firsthost)
2574 			syslog(LOG_INFO, "connection from %s (to %s)",
2575 			       remotehost, hostname);
2576 		else
2577 #endif
2578 		{
2579 			char	who_name[MAXHOSTNAMELEN];
2580 
2581 			error = getnameinfo(who, who->sa_len,
2582 					    who_name, sizeof(who_name) - 1,
2583 					    NULL, 0, NI_NUMERICHOST);
2584 			syslog(LOG_INFO, "connection from %s (%s)", remotehost,
2585 			       error == 0 ? who_name : "");
2586 		}
2587 	}
2588 }
2589 
2590 /*
2591  * Record logout in wtmp file
2592  * and exit with supplied status.
2593  */
2594 void
2595 dologout(int status)
2596 {
2597 	/*
2598 	 * Prevent reception of SIGURG from resulting in a resumption
2599 	 * back to the main program loop.
2600 	 */
2601 	transflag = 0;
2602 
2603 	if (logged_in && dowtmp) {
2604 		(void) seteuid((uid_t)0);
2605 		ftpd_logwtmp(ttyline, "", NULL);
2606 	}
2607 	/* beware of flushing buffers after a SIGPIPE */
2608 	_exit(status);
2609 }
2610 
2611 static void
2612 sigurg(int signo)
2613 {
2614 
2615 	recvurg = 1;
2616 }
2617 
2618 static void
2619 myoob(void)
2620 {
2621 	char *cp;
2622 
2623 	/* only process if transfer occurring */
2624 	if (!transflag)
2625 		return;
2626 	cp = tmpline;
2627 	if (getline(cp, 7, stdin) == NULL) {
2628 		reply(221, "You could at least say goodbye.");
2629 		dologout(0);
2630 	}
2631 	upper(cp);
2632 	if (strcmp(cp, "ABOR\r\n") == 0) {
2633 		tmpline[0] = '\0';
2634 		reply(426, "Transfer aborted. Data connection closed.");
2635 		reply(226, "Abort successful");
2636 	}
2637 	if (strcmp(cp, "STAT\r\n") == 0) {
2638 		tmpline[0] = '\0';
2639 		if (file_size != (off_t) -1)
2640 			reply(213, "Status: %qd of %qd bytes transferred",
2641 			    byte_count, file_size);
2642 		else
2643 			reply(213, "Status: %qd bytes transferred", byte_count);
2644 	}
2645 }
2646 
2647 /*
2648  * Note: a response of 425 is not mentioned as a possible response to
2649  *	the PASV command in RFC959. However, it has been blessed as
2650  *	a legitimate response by Jon Postel in a telephone conversation
2651  *	with Rick Adams on 25 Jan 89.
2652  */
2653 void
2654 passive(void)
2655 {
2656 	int len, on;
2657 	char *p, *a;
2658 
2659 	if (pdata >= 0)		/* close old port if one set */
2660 		close(pdata);
2661 
2662 	pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2663 	if (pdata < 0) {
2664 		perror_reply(425, "Can't open passive connection");
2665 		return;
2666 	}
2667 	on = 1;
2668 	if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
2669 		syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
2670 
2671 	(void) seteuid((uid_t)0);
2672 
2673 #ifdef IP_PORTRANGE
2674 	if (ctrl_addr.su_family == AF_INET) {
2675 	    on = restricted_data_ports ? IP_PORTRANGE_HIGH
2676 				       : IP_PORTRANGE_DEFAULT;
2677 
2678 	    if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2679 			    &on, sizeof(on)) < 0)
2680 		    goto pasv_error;
2681 	}
2682 #endif
2683 #ifdef IPV6_PORTRANGE
2684 	if (ctrl_addr.su_family == AF_INET6) {
2685 	    on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
2686 				       : IPV6_PORTRANGE_DEFAULT;
2687 
2688 	    if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2689 			    &on, sizeof(on)) < 0)
2690 		    goto pasv_error;
2691 	}
2692 #endif
2693 
2694 	pasv_addr = ctrl_addr;
2695 	pasv_addr.su_port = 0;
2696 	if (bind(pdata, (struct sockaddr *)&pasv_addr, pasv_addr.su_len) < 0)
2697 		goto pasv_error;
2698 
2699 	(void) seteuid((uid_t)pw->pw_uid);
2700 
2701 	len = sizeof(pasv_addr);
2702 	if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2703 		goto pasv_error;
2704 	if (listen(pdata, 1) < 0)
2705 		goto pasv_error;
2706 	if (pasv_addr.su_family == AF_INET)
2707 		a = (char *) &pasv_addr.su_sin.sin_addr;
2708 	else if (pasv_addr.su_family == AF_INET6 &&
2709 		 IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr))
2710 		a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
2711 	else
2712 		goto pasv_error;
2713 
2714 	p = (char *) &pasv_addr.su_port;
2715 
2716 #define UC(b) (((int) b) & 0xff)
2717 
2718 	reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
2719 		UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
2720 	return;
2721 
2722 pasv_error:
2723 	(void) seteuid((uid_t)pw->pw_uid);
2724 	(void) close(pdata);
2725 	pdata = -1;
2726 	perror_reply(425, "Can't open passive connection");
2727 	return;
2728 }
2729 
2730 /*
2731  * Long Passive defined in RFC 1639.
2732  *     228 Entering Long Passive Mode
2733  *         (af, hal, h1, h2, h3,..., pal, p1, p2...)
2734  */
2735 
2736 void
2737 long_passive(char *cmd, int pf)
2738 {
2739 	int len, on;
2740 	char *p, *a;
2741 
2742 	if (pdata >= 0)		/* close old port if one set */
2743 		close(pdata);
2744 
2745 	if (pf != PF_UNSPEC) {
2746 		if (ctrl_addr.su_family != pf) {
2747 			switch (ctrl_addr.su_family) {
2748 			case AF_INET:
2749 				pf = 1;
2750 				break;
2751 			case AF_INET6:
2752 				pf = 2;
2753 				break;
2754 			default:
2755 				pf = 0;
2756 				break;
2757 			}
2758 			/*
2759 			 * XXX
2760 			 * only EPRT/EPSV ready clients will understand this
2761 			 */
2762 			if (strcmp(cmd, "EPSV") == 0 && pf) {
2763 				reply(522, "Network protocol mismatch, "
2764 					"use (%d)", pf);
2765 			} else
2766 				reply(501, "Network protocol mismatch"); /*XXX*/
2767 
2768 			return;
2769 		}
2770 	}
2771 
2772 	pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2773 	if (pdata < 0) {
2774 		perror_reply(425, "Can't open passive connection");
2775 		return;
2776 	}
2777 	on = 1;
2778 	if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
2779 		syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
2780 
2781 	(void) seteuid((uid_t)0);
2782 
2783 	pasv_addr = ctrl_addr;
2784 	pasv_addr.su_port = 0;
2785 	len = pasv_addr.su_len;
2786 
2787 #ifdef IP_PORTRANGE
2788 	if (ctrl_addr.su_family == AF_INET) {
2789 	    on = restricted_data_ports ? IP_PORTRANGE_HIGH
2790 				       : IP_PORTRANGE_DEFAULT;
2791 
2792 	    if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2793 			    &on, sizeof(on)) < 0)
2794 		    goto pasv_error;
2795 	}
2796 #endif
2797 #ifdef IPV6_PORTRANGE
2798 	if (ctrl_addr.su_family == AF_INET6) {
2799 	    on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
2800 				       : IPV6_PORTRANGE_DEFAULT;
2801 
2802 	    if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2803 			    &on, sizeof(on)) < 0)
2804 		    goto pasv_error;
2805 	}
2806 #endif
2807 
2808 	if (bind(pdata, (struct sockaddr *)&pasv_addr, len) < 0)
2809 		goto pasv_error;
2810 
2811 	(void) seteuid((uid_t)pw->pw_uid);
2812 
2813 	if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2814 		goto pasv_error;
2815 	if (listen(pdata, 1) < 0)
2816 		goto pasv_error;
2817 
2818 #define UC(b) (((int) b) & 0xff)
2819 
2820 	if (strcmp(cmd, "LPSV") == 0) {
2821 		p = (char *)&pasv_addr.su_port;
2822 		switch (pasv_addr.su_family) {
2823 		case AF_INET:
2824 			a = (char *) &pasv_addr.su_sin.sin_addr;
2825 		v4_reply:
2826 			reply(228,
2827 "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)",
2828 			      4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2829 			      2, UC(p[0]), UC(p[1]));
2830 			return;
2831 		case AF_INET6:
2832 			if (IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr)) {
2833 				a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
2834 				goto v4_reply;
2835 			}
2836 			a = (char *) &pasv_addr.su_sin6.sin6_addr;
2837 			reply(228,
2838 "Entering Long Passive Mode "
2839 "(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)",
2840 			      6, 16, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2841 			      UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]),
2842 			      UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]),
2843 			      UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]),
2844 			      2, UC(p[0]), UC(p[1]));
2845 			return;
2846 		}
2847 	} else if (strcmp(cmd, "EPSV") == 0) {
2848 		switch (pasv_addr.su_family) {
2849 		case AF_INET:
2850 		case AF_INET6:
2851 			reply(229, "Entering Extended Passive Mode (|||%d|)",
2852 				ntohs(pasv_addr.su_port));
2853 			return;
2854 		}
2855 	} else {
2856 		/* more proper error code? */
2857 	}
2858 
2859 pasv_error:
2860 	(void) seteuid((uid_t)pw->pw_uid);
2861 	(void) close(pdata);
2862 	pdata = -1;
2863 	perror_reply(425, "Can't open passive connection");
2864 	return;
2865 }
2866 
2867 /*
2868  * Generate unique name for file with basename "local"
2869  * and open the file in order to avoid possible races.
2870  * Try "local" first, then "local.1", "local.2" etc, up to "local.99".
2871  * Return descriptor to the file, set "name" to its name.
2872  *
2873  * Generates failure reply on error.
2874  */
2875 static int
2876 guniquefd(char *local, char **name)
2877 {
2878 	static char new[MAXPATHLEN];
2879 	struct stat st;
2880 	char *cp;
2881 	int count;
2882 	int fd;
2883 
2884 	cp = strrchr(local, '/');
2885 	if (cp)
2886 		*cp = '\0';
2887 	if (stat(cp ? local : ".", &st) < 0) {
2888 		perror_reply(553, cp ? local : ".");
2889 		return (-1);
2890 	}
2891 	if (cp) {
2892 		/*
2893 		 * Let not overwrite dirname with counter suffix.
2894 		 * -4 is for /nn\0
2895 		 * In this extreme case dot won't be put in front of suffix.
2896 		 */
2897 		if (strlen(local) > sizeof(new) - 4) {
2898 			reply(553, "Pathname too long");
2899 			return (-1);
2900 		}
2901 		*cp = '/';
2902 	}
2903 	/* -4 is for the .nn<null> we put on the end below */
2904 	(void) snprintf(new, sizeof(new) - 4, "%s", local);
2905 	cp = new + strlen(new);
2906 	/*
2907 	 * Don't generate dotfile unless requested explicitly.
2908 	 * This covers the case when basename gets truncated off
2909 	 * by buffer size.
2910 	 */
2911 	if (cp > new && cp[-1] != '/')
2912 		*cp++ = '.';
2913 	for (count = 0; count < 100; count++) {
2914 		/* At count 0 try unmodified name */
2915 		if (count)
2916 			(void)sprintf(cp, "%d", count);
2917 		if ((fd = open(count ? new : local,
2918 		    O_RDWR | O_CREAT | O_EXCL, 0666)) >= 0) {
2919 			*name = count ? new : local;
2920 			return (fd);
2921 		}
2922 		if (errno != EEXIST) {
2923 			perror_reply(553, count ? new : local);
2924 			return (-1);
2925 		}
2926 	}
2927 	reply(452, "Unique file name cannot be created.");
2928 	return (-1);
2929 }
2930 
2931 /*
2932  * Format and send reply containing system error number.
2933  */
2934 void
2935 perror_reply(int code, char *string)
2936 {
2937 
2938 	reply(code, "%s: %s.", string, strerror(errno));
2939 }
2940 
2941 static char *onefile[] = {
2942 	"",
2943 	0
2944 };
2945 
2946 void
2947 send_file_list(char *whichf)
2948 {
2949 	struct stat st;
2950 	DIR *dirp = NULL;
2951 	struct dirent *dir;
2952 	FILE *dout = NULL;
2953 	char **dirlist, *dirname;
2954 	int simple = 0;
2955 	int freeglob = 0;
2956 	glob_t gl;
2957 
2958 	if (strpbrk(whichf, "~{[*?") != NULL) {
2959 		int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
2960 
2961 		memset(&gl, 0, sizeof(gl));
2962 		gl.gl_matchc = MAXGLOBARGS;
2963 		flags |= GLOB_LIMIT;
2964 		freeglob = 1;
2965 		if (glob(whichf, flags, 0, &gl)) {
2966 			reply(550, "not found");
2967 			goto out;
2968 		} else if (gl.gl_pathc == 0) {
2969 			errno = ENOENT;
2970 			perror_reply(550, whichf);
2971 			goto out;
2972 		}
2973 		dirlist = gl.gl_pathv;
2974 	} else {
2975 		onefile[0] = whichf;
2976 		dirlist = onefile;
2977 		simple = 1;
2978 	}
2979 
2980 	while ((dirname = *dirlist++)) {
2981 		if (stat(dirname, &st) < 0) {
2982 			/*
2983 			 * If user typed "ls -l", etc, and the client
2984 			 * used NLST, do what the user meant.
2985 			 */
2986 			if (dirname[0] == '-' && *dirlist == NULL &&
2987 			    transflag == 0) {
2988 				retrieve(_PATH_LS " %s", dirname);
2989 				goto out;
2990 			}
2991 			perror_reply(550, whichf);
2992 			if (dout != NULL) {
2993 				(void) fclose(dout);
2994 				transflag = 0;
2995 				data = -1;
2996 				pdata = -1;
2997 			}
2998 			goto out;
2999 		}
3000 
3001 		if (S_ISREG(st.st_mode)) {
3002 			if (dout == NULL) {
3003 				dout = dataconn("file list", (off_t)-1, "w");
3004 				if (dout == NULL)
3005 					goto out;
3006 				transflag++;
3007 			}
3008 			fprintf(dout, "%s%s\n", dirname,
3009 				type == TYPE_A ? "\r" : "");
3010 			byte_count += strlen(dirname) + 1;
3011 			continue;
3012 		} else if (!S_ISDIR(st.st_mode))
3013 			continue;
3014 
3015 		if ((dirp = opendir(dirname)) == NULL)
3016 			continue;
3017 
3018 		while ((dir = readdir(dirp)) != NULL) {
3019 			char nbuf[MAXPATHLEN];
3020 
3021 			if (recvurg) {
3022 				myoob();
3023 				recvurg = 0;
3024 				transflag = 0;
3025 				goto out;
3026 			}
3027 
3028 			if (dir->d_name[0] == '.' && dir->d_namlen == 1)
3029 				continue;
3030 			if (dir->d_name[0] == '.' && dir->d_name[1] == '.' &&
3031 			    dir->d_namlen == 2)
3032 				continue;
3033 
3034 			snprintf(nbuf, sizeof(nbuf),
3035 				"%s/%s", dirname, dir->d_name);
3036 
3037 			/*
3038 			 * We have to do a stat to insure it's
3039 			 * not a directory or special file.
3040 			 */
3041 			if (simple || (stat(nbuf, &st) == 0 &&
3042 			    S_ISREG(st.st_mode))) {
3043 				if (dout == NULL) {
3044 					dout = dataconn("file list", (off_t)-1,
3045 						"w");
3046 					if (dout == NULL)
3047 						goto out;
3048 					transflag++;
3049 				}
3050 				if (nbuf[0] == '.' && nbuf[1] == '/')
3051 					fprintf(dout, "%s%s\n", &nbuf[2],
3052 						type == TYPE_A ? "\r" : "");
3053 				else
3054 					fprintf(dout, "%s%s\n", nbuf,
3055 						type == TYPE_A ? "\r" : "");
3056 				byte_count += strlen(nbuf) + 1;
3057 			}
3058 		}
3059 		(void) closedir(dirp);
3060 	}
3061 
3062 	if (dout == NULL)
3063 		reply(550, "No files found.");
3064 	else if (ferror(dout) != 0)
3065 		perror_reply(550, "Data connection");
3066 	else
3067 		reply(226, "Transfer complete.");
3068 
3069 	transflag = 0;
3070 	if (dout != NULL)
3071 		(void) fclose(dout);
3072 	data = -1;
3073 	pdata = -1;
3074 out:
3075 	if (freeglob) {
3076 		freeglob = 0;
3077 		globfree(&gl);
3078 	}
3079 }
3080 
3081 void
3082 reapchild(int signo)
3083 {
3084 	while (wait3(NULL, WNOHANG, NULL) > 0);
3085 }
3086 
3087 #ifdef OLD_SETPROCTITLE
3088 /*
3089  * Clobber argv so ps will show what we're doing.  (Stolen from sendmail.)
3090  * Warning, since this is usually started from inetd.conf, it often doesn't
3091  * have much of an environment or arglist to overwrite.
3092  */
3093 void
3094 setproctitle(const char *fmt, ...)
3095 {
3096 	int i;
3097 	va_list ap;
3098 	char *p, *bp, ch;
3099 	char buf[LINE_MAX];
3100 
3101 	va_start(ap, fmt);
3102 	(void)vsnprintf(buf, sizeof(buf), fmt, ap);
3103 
3104 	/* make ps print our process name */
3105 	p = Argv[0];
3106 	*p++ = '-';
3107 
3108 	i = strlen(buf);
3109 	if (i > LastArgv - p - 2) {
3110 		i = LastArgv - p - 2;
3111 		buf[i] = '\0';
3112 	}
3113 	bp = buf;
3114 	while (ch = *bp++)
3115 		if (ch != '\n' && ch != '\r')
3116 			*p++ = ch;
3117 	while (p < LastArgv)
3118 		*p++ = ' ';
3119 }
3120 #endif /* OLD_SETPROCTITLE */
3121 
3122 static void
3123 logxfer(char *name, off_t size, time_t start)
3124 {
3125 	char buf[1024];
3126 	char path[MAXPATHLEN + 1];
3127 	time_t now;
3128 
3129 	if (statfd >= 0 && getwd(path) != NULL) {
3130 		time(&now);
3131 		snprintf(buf, sizeof(buf), "%.20s!%s!%s!%s/%s!%qd!%ld\n",
3132 			ctime(&now)+4, ident, remotehost,
3133 			path, name, (long long)size,
3134 			(long)(now - start + (now == start)));
3135 		write(statfd, buf, strlen(buf));
3136 	}
3137 }
3138 
3139 static char *
3140 doublequote(char *s)
3141 {
3142 	int n;
3143 	char *p, *s2;
3144 
3145 	for (p = s, n = 0; *p; p++)
3146 		if (*p == '"')
3147 			n++;
3148 
3149 	if ((s2 = malloc(p - s + n + 1)) == NULL)
3150 		return (NULL);
3151 
3152 	for (p = s2; *s; s++, p++) {
3153 		if ((*p = *s) == '"')
3154 			*(++p) = '"';
3155 	}
3156 	*p = '\0';
3157 
3158 	return (s2);
3159 }
3160