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