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