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