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