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