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