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