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