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