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