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