xref: /freebsd/libexec/ftpd/ftpd.c (revision ec489d64bb4c1bca1a6bdfdf7e37900a85f886bc)
1ea022d16SRodney W. Grimes /*
2ea022d16SRodney W. Grimes  * Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994
3ea022d16SRodney W. Grimes  *	The Regents of the University of California.  All rights reserved.
4ea022d16SRodney W. Grimes  *
5ea022d16SRodney W. Grimes  * Redistribution and use in source and binary forms, with or without
6ea022d16SRodney W. Grimes  * modification, are permitted provided that the following conditions
7ea022d16SRodney W. Grimes  * are met:
8ea022d16SRodney W. Grimes  * 1. Redistributions of source code must retain the above copyright
9ea022d16SRodney W. Grimes  *    notice, this list of conditions and the following disclaimer.
10ea022d16SRodney W. Grimes  * 2. Redistributions in binary form must reproduce the above copyright
11ea022d16SRodney W. Grimes  *    notice, this list of conditions and the following disclaimer in the
12ea022d16SRodney W. Grimes  *    documentation and/or other materials provided with the distribution.
135efaea4cSChristian Brueffer  * 3. Neither the name of the University nor the names of its contributors
14ea022d16SRodney W. Grimes  *    may be used to endorse or promote products derived from this software
15ea022d16SRodney W. Grimes  *    without specific prior written permission.
16ea022d16SRodney W. Grimes  *
17ea022d16SRodney W. Grimes  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18ea022d16SRodney W. Grimes  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19ea022d16SRodney W. Grimes  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20ea022d16SRodney W. Grimes  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21ea022d16SRodney W. Grimes  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22ea022d16SRodney W. Grimes  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23ea022d16SRodney W. Grimes  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24ea022d16SRodney W. Grimes  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25ea022d16SRodney W. Grimes  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26ea022d16SRodney W. Grimes  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27ea022d16SRodney W. Grimes  * SUCH DAMAGE.
28ea022d16SRodney W. Grimes  */
29ea022d16SRodney W. Grimes 
309aca17cbSMark Murray #if 0
31ea022d16SRodney W. Grimes #ifndef lint
32ea022d16SRodney W. Grimes static char copyright[] =
33ea022d16SRodney W. Grimes "@(#) Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994\n\
34ea022d16SRodney W. Grimes 	The Regents of the University of California.  All rights reserved.\n";
35ea022d16SRodney W. Grimes #endif /* not lint */
369aca17cbSMark Murray #endif
37ea022d16SRodney W. Grimes 
38ea022d16SRodney W. Grimes #ifndef lint
39e02897faSPhilippe Charnier #if 0
40ea022d16SRodney W. Grimes static char sccsid[] = "@(#)ftpd.c	8.4 (Berkeley) 4/16/94";
419aca17cbSMark Murray #endif
42e02897faSPhilippe Charnier #endif /* not lint */
43ea022d16SRodney W. Grimes 
440c4b401fSYaroslav Tykhiy #include <sys/cdefs.h>
450c4b401fSYaroslav Tykhiy __FBSDID("$FreeBSD$");
460c4b401fSYaroslav Tykhiy 
47ea022d16SRodney W. Grimes /*
48ea022d16SRodney W. Grimes  * FTP server.
49ea022d16SRodney W. Grimes  */
50ea022d16SRodney W. Grimes #include <sys/param.h>
51ea022d16SRodney W. Grimes #include <sys/ioctl.h>
529fc5823aSGarrett Wollman #include <sys/mman.h>
53eb2fc780SGarrett Wollman #include <sys/socket.h>
54eb2fc780SGarrett Wollman #include <sys/stat.h>
55eb2fc780SGarrett Wollman #include <sys/time.h>
56eb2fc780SGarrett Wollman #include <sys/wait.h>
57ea022d16SRodney W. Grimes 
58ea022d16SRodney W. Grimes #include <netinet/in.h>
59ea022d16SRodney W. Grimes #include <netinet/in_systm.h>
60ea022d16SRodney W. Grimes #include <netinet/ip.h>
619fc5823aSGarrett Wollman #include <netinet/tcp.h>
62ea022d16SRodney W. Grimes 
63ea022d16SRodney W. Grimes #define	FTP_NAMES
64ea022d16SRodney W. Grimes #include <arpa/ftp.h>
65ea022d16SRodney W. Grimes #include <arpa/inet.h>
66ea022d16SRodney W. Grimes #include <arpa/telnet.h>
67ea022d16SRodney W. Grimes 
68ea022d16SRodney W. Grimes #include <ctype.h>
69ea022d16SRodney W. Grimes #include <dirent.h>
70ea022d16SRodney W. Grimes #include <err.h>
71ea022d16SRodney W. Grimes #include <errno.h>
72ea022d16SRodney W. Grimes #include <fcntl.h>
73ea022d16SRodney W. Grimes #include <glob.h>
74ea022d16SRodney W. Grimes #include <limits.h>
75ea022d16SRodney W. Grimes #include <netdb.h>
76ea022d16SRodney W. Grimes #include <pwd.h>
7731fea7b8SDavid Nugent #include <grp.h>
7847499ecdSAndrey A. Chernov #include <opie.h>
79ea022d16SRodney W. Grimes #include <signal.h>
80a57e1ef0SYaroslav Tykhiy #include <stdint.h>
81ea022d16SRodney W. Grimes #include <stdio.h>
82ea022d16SRodney W. Grimes #include <stdlib.h>
83ea022d16SRodney W. Grimes #include <string.h>
84ea022d16SRodney W. Grimes #include <syslog.h>
85ea022d16SRodney W. Grimes #include <time.h>
86ea022d16SRodney W. Grimes #include <unistd.h>
87b63e1fe2SPeter Wemm #include <libutil.h>
88b071c689SDavid Nugent #ifdef	LOGIN_CAP
89b071c689SDavid Nugent #include <login_cap.h>
90b071c689SDavid Nugent #endif
91ea022d16SRodney W. Grimes 
925bc9d93dSMark Murray #ifdef USE_PAM
936c9134c0SMark Murray #include <security/pam_appl.h>
946c9134c0SMark Murray #endif
956c9134c0SMark Murray 
96ea022d16SRodney W. Grimes #include "pathnames.h"
97ea022d16SRodney W. Grimes #include "extern.h"
98ea022d16SRodney W. Grimes 
99ea022d16SRodney W. Grimes #include <stdarg.h>
100ea022d16SRodney W. Grimes 
101af85d782SDavid Nugent static char version[] = "Version 6.00LS";
102af85d782SDavid Nugent #undef main
103ea022d16SRodney W. Grimes 
1044dd8b5abSYoshinobu Inoue union sockunion ctrl_addr;
1054dd8b5abSYoshinobu Inoue union sockunion data_source;
1064dd8b5abSYoshinobu Inoue union sockunion data_dest;
1074dd8b5abSYoshinobu Inoue union sockunion his_addr;
1084dd8b5abSYoshinobu Inoue union sockunion pasv_addr;
109ea022d16SRodney W. Grimes 
110cf09a206SDavid Greenman int	daemon_mode;
111ea022d16SRodney W. Grimes int	data;
11263591ba5SYaroslav Tykhiy int	dataport;
113c152df28SYaroslav Tykhiy int	hostinfo = 1;	/* print host-specific info in messages */
114ea022d16SRodney W. Grimes int	logged_in;
115ea022d16SRodney W. Grimes struct	passwd *pw;
116ce9287fcSYaroslav Tykhiy char	*homedir;
117618b0bbaSMark Murray int	ftpdebug;
118ea022d16SRodney W. Grimes int	timeout = 900;    /* timeout after 15 minutes of inactivity */
119ea022d16SRodney W. Grimes int	maxtimeout = 7200;/* don't allow idle time to be set beyond 2 hours */
120ea022d16SRodney W. Grimes int	logging;
1214c450ad7SPaul Traina int	restricted_data_ports = 1;
122a5a4544eSPaul Traina int	paranoid = 1;	  /* be extra careful about security */
1235a392aecSTorsten Blum int	anon_only = 0;    /* Only anonymous ftp allowed */
1242ea42282SYaroslav Tykhiy int	assumeutf8 = 0;   /* Assume that server file names are in UTF-8 */
125ea022d16SRodney W. Grimes int	guest;
126a5a4544eSPaul Traina int	dochroot;
127215a9f9dSYaroslav Tykhiy char	*chrootdir;
1285d7e0128SYaroslav Tykhiy int	dowtmp = 1;
1293eb568f2SGuido van Rooij int	stats;
1303eb568f2SGuido van Rooij int	statfd = -1;
131ea022d16SRodney W. Grimes int	type;
132ea022d16SRodney W. Grimes int	form;
133ea022d16SRodney W. Grimes int	stru;			/* avoid C keyword */
134ea022d16SRodney W. Grimes int	mode;
135ea022d16SRodney W. Grimes int	usedefault = 1;		/* for data transfers */
136ea022d16SRodney W. Grimes int	pdata = -1;		/* for passive mode */
137a4b77a2aSPoul-Henning Kamp int	readonly = 0;		/* Server is in readonly mode.	*/
138a4b77a2aSPoul-Henning Kamp int	noepsv = 0;		/* EPSV command is disabled.	*/
13962513e76SNik Clayton int	noretr = 0;		/* RETR command is disabled.	*/
1401cc9f0bbSSheldon Hearn int	noguestretr = 0;	/* RETR command is disabled for anon users. */
141d186bb12SMatthew N. Dodd int	noguestmkd = 0;		/* MKD command is disabled for anon users. */
142a117c345SYaroslav Tykhiy int	noguestmod = 1;		/* anon users may not modify existing files. */
14362513e76SNik Clayton 
144ea022d16SRodney W. Grimes off_t	file_size;
145ea022d16SRodney W. Grimes off_t	byte_count;
146ea022d16SRodney W. Grimes #if !defined(CMASK) || CMASK == 0
147ea022d16SRodney W. Grimes #undef CMASK
148ea022d16SRodney W. Grimes #define CMASK 027
149ea022d16SRodney W. Grimes #endif
150ea022d16SRodney W. Grimes int	defumask = CMASK;		/* default umask value */
151ea022d16SRodney W. Grimes char	tmpline[7];
152ea4e54b9SDavid Nugent char	*hostname;
153ad442344SDima Dorfman int	epsvall = 0;
154ad442344SDima Dorfman 
1550512556aSDavid Nugent #ifdef VIRTUAL_HOSTING
156ea4e54b9SDavid Nugent char	*ftpuser;
157ea4e54b9SDavid Nugent 
158ea4e54b9SDavid Nugent static struct ftphost {
159ea4e54b9SDavid Nugent 	struct ftphost	*next;
160f38c6cadSYoshinobu Inoue 	struct addrinfo *hostinfo;
161ea4e54b9SDavid Nugent 	char		*hostname;
162ea4e54b9SDavid Nugent 	char		*anonuser;
163ea4e54b9SDavid Nugent 	char		*statfile;
164ea4e54b9SDavid Nugent 	char		*welcome;
165ea4e54b9SDavid Nugent 	char		*loginmsg;
166ea4e54b9SDavid Nugent } *thishost, *firsthost;
167ea4e54b9SDavid Nugent 
168ea4e54b9SDavid Nugent #endif
16904683b2cSYaroslav Tykhiy char	remotehost[NI_MAXHOST];
1703eb568f2SGuido van Rooij char	*ident = NULL;
171a5a4544eSPaul Traina 
17280643af0SEd Schouten static char	wtmpid[20];
173a5a4544eSPaul Traina 
1745bc9d93dSMark Murray #ifdef USE_PAM
175e4bc453cSWarner Losh static int	auth_pam(struct passwd**, const char*);
1765bc9d93dSMark Murray pam_handle_t	*pamh = NULL;
17747499ecdSAndrey A. Chernov #endif
178fa1746c9SMark Murray 
179fa1746c9SMark Murray static struct opie	opiedata;
180fa1746c9SMark Murray static char		opieprompt[OPIE_CHALLENGE_MAX+1];
18147499ecdSAndrey A. Chernov static int		pwok;
1829aca17cbSMark Murray 
183125b9635SYaroslav Tykhiy char	*pid_file = NULL; /* means default location to pidfile(3) */
184105a3c98SJulian Elischer 
185ea022d16SRodney W. Grimes /*
1866d10cb2fSJonathan Lemon  * Limit number of pathnames that glob can return.
1876d10cb2fSJonathan Lemon  * A limit of 0 indicates the number of pathnames is unlimited.
1886d10cb2fSJonathan Lemon  */
1896d10cb2fSJonathan Lemon #define MAXGLOBARGS	16384
1906d10cb2fSJonathan Lemon #
1916d10cb2fSJonathan Lemon 
1926d10cb2fSJonathan Lemon /*
193ea022d16SRodney W. Grimes  * Timeout intervals for retrying connections
194ea022d16SRodney W. Grimes  * to hosts that don't accept PORT cmds.  This
195ea022d16SRodney W. Grimes  * is a kludge, but given the problems with TCP...
196ea022d16SRodney W. Grimes  */
197ea022d16SRodney W. Grimes #define	SWAITMAX	90	/* wait at most 90 seconds */
198ea022d16SRodney W. Grimes #define	SWAITINT	5	/* interval between retries */
199ea022d16SRodney W. Grimes 
200ea022d16SRodney W. Grimes int	swaitmax = SWAITMAX;
201ea022d16SRodney W. Grimes int	swaitint = SWAITINT;
202ea022d16SRodney W. Grimes 
203ea022d16SRodney W. Grimes #ifdef SETPROCTITLE
204b63e1fe2SPeter Wemm #ifdef OLD_SETPROCTITLE
205ea022d16SRodney W. Grimes char	**Argv = NULL;		/* pointer to argument vector */
206ea022d16SRodney W. Grimes char	*LastArgv = NULL;	/* end of argv */
207b63e1fe2SPeter Wemm #endif /* OLD_SETPROCTITLE */
208ea022d16SRodney W. Grimes char	proctitle[LINE_MAX];	/* initial part of title */
209ea022d16SRodney W. Grimes #endif /* SETPROCTITLE */
210ea022d16SRodney W. Grimes 
2116b2dee6bSYaroslav Tykhiy #define LOGCMD(cmd, file)		logcmd((cmd), (file), NULL, -1)
2126b2dee6bSYaroslav Tykhiy #define LOGCMD2(cmd, file1, file2)	logcmd((cmd), (file1), (file2), -1)
2136b2dee6bSYaroslav Tykhiy #define LOGBYTES(cmd, file, cnt)	logcmd((cmd), (file), NULL, (cnt))
214ea022d16SRodney W. Grimes 
2154cd51076SYaroslav Tykhiy static	volatile sig_atomic_t recvurg;
2164cd51076SYaroslav Tykhiy static	int transflag;		/* NB: for debugging only */
2174cd51076SYaroslav Tykhiy 
2184cd51076SYaroslav Tykhiy #define STARTXFER	flagxfer(1)
2194cd51076SYaroslav Tykhiy #define ENDXFER		flagxfer(0)
2204cd51076SYaroslav Tykhiy 
2214cd51076SYaroslav Tykhiy #define START_UNSAFE	maskurg(1)
2224cd51076SYaroslav Tykhiy #define END_UNSAFE	maskurg(0)
2234cd51076SYaroslav Tykhiy 
2244cd51076SYaroslav Tykhiy /* It's OK to put an `else' clause after this macro. */
2254cd51076SYaroslav Tykhiy #define CHECKOOB(action)						\
2264cd51076SYaroslav Tykhiy 	if (recvurg) {							\
2274cd51076SYaroslav Tykhiy 		recvurg = 0;						\
2284cd51076SYaroslav Tykhiy 		if (myoob()) {						\
2294cd51076SYaroslav Tykhiy 			ENDXFER;					\
2304cd51076SYaroslav Tykhiy 			action;						\
2314cd51076SYaroslav Tykhiy 		}							\
2324cd51076SYaroslav Tykhiy 	}
2334cd51076SYaroslav Tykhiy 
234ea4e54b9SDavid Nugent #ifdef VIRTUAL_HOSTING
2352c9fd5f2SHajimu UMEMOTO static void	 inithosts(int);
236e4bc453cSWarner Losh static void	 selecthost(union sockunion *);
237ea4e54b9SDavid Nugent #endif
238e4bc453cSWarner Losh static void	 ack(char *);
239e4bc453cSWarner Losh static void	 sigurg(int);
2404cd51076SYaroslav Tykhiy static void	 maskurg(int);
2414cd51076SYaroslav Tykhiy static void	 flagxfer(int);
2424cd51076SYaroslav Tykhiy static int	 myoob(void);
243cefb6785SChristian S.J. Peron static int	 checkuser(char *, char *, int, char **, int *);
244e4bc453cSWarner Losh static FILE	*dataconn(char *, off_t, char *);
245e4bc453cSWarner Losh static void	 dolog(struct sockaddr *);
246e4bc453cSWarner Losh static void	 end_login(void);
247e4bc453cSWarner Losh static FILE	*getdatasock(char *);
248a117c345SYaroslav Tykhiy static int	 guniquefd(char *, char **);
249e4bc453cSWarner Losh static void	 lostconn(int);
250e4bc453cSWarner Losh static void	 sigquit(int);
251e4bc453cSWarner Losh static int	 receive_data(FILE *, FILE *);
2526e4b0a55SYaroslav Tykhiy static int	 send_data(FILE *, FILE *, size_t, off_t, int);
253ea022d16SRodney W. Grimes static struct passwd *
254e4bc453cSWarner Losh 		 sgetpwnam(char *);
255e4bc453cSWarner Losh static char	*sgetsave(char *);
256e4bc453cSWarner Losh static void	 reapchild(int);
257eb5b2bb3SYaroslav Tykhiy static void	 appendf(char **, char *, ...) __printflike(2, 3);
2586b2dee6bSYaroslav Tykhiy static void	 logcmd(char *, char *, char *, off_t);
259e4bc453cSWarner Losh static void      logxfer(char *, off_t, time_t);
260e4648f05SYaroslav Tykhiy static char	*doublequote(char *);
261206fe568SHajimu UMEMOTO static int	*socksetup(int, char *, const char *);
262ea022d16SRodney W. Grimes 
263ea022d16SRodney W. Grimes int
264e4bc453cSWarner Losh main(int argc, char *argv[], char **envp)
265ea022d16SRodney W. Grimes {
26678e3eed0SStefan Farfeleder 	socklen_t addrlen;
26778e3eed0SStefan Farfeleder 	int ch, on = 1, tos;
268ea022d16SRodney W. Grimes 	char *cp, line[LINE_MAX];
269ea022d16SRodney W. Grimes 	FILE *fd;
2704dd8b5abSYoshinobu Inoue 	char	*bindname = NULL;
27163591ba5SYaroslav Tykhiy 	const char *bindport = "ftp";
2724dd8b5abSYoshinobu Inoue 	int	family = AF_UNSPEC;
2734b82fc95SYaroslav Tykhiy 	struct sigaction sa;
274ea022d16SRodney W. Grimes 
27534d1ba5cSAndrey A. Chernov 	tzset();		/* in case no timezone database in ~ftp */
2764b82fc95SYaroslav Tykhiy 	sigemptyset(&sa.sa_mask);
2774b82fc95SYaroslav Tykhiy 	sa.sa_flags = SA_RESTART;
27834d1ba5cSAndrey A. Chernov 
279b63e1fe2SPeter Wemm #ifdef OLD_SETPROCTITLE
280ea022d16SRodney W. Grimes 	/*
281ea022d16SRodney W. Grimes 	 *  Save start and extent of argv for setproctitle.
282ea022d16SRodney W. Grimes 	 */
283ea022d16SRodney W. Grimes 	Argv = argv;
284ea022d16SRodney W. Grimes 	while (*envp)
285ea022d16SRodney W. Grimes 		envp++;
286ea022d16SRodney W. Grimes 	LastArgv = envp[-1] + strlen(envp[-1]);
287b63e1fe2SPeter Wemm #endif /* OLD_SETPROCTITLE */
288ea022d16SRodney W. Grimes 
2896c98f401SYaroslav Tykhiy 	/*
2906c98f401SYaroslav Tykhiy 	 * Prevent diagnostic messages from appearing on stderr.
2916c98f401SYaroslav Tykhiy 	 * We run as a daemon or from inetd; in both cases, there's
2926c98f401SYaroslav Tykhiy 	 * more reason in logging to syslog.
2936c98f401SYaroslav Tykhiy 	 */
2946c98f401SYaroslav Tykhiy 	(void) freopen(_PATH_DEVNULL, "w", stderr);
2956c98f401SYaroslav Tykhiy 	opterr = 0;
2966c98f401SYaroslav Tykhiy 
2976c98f401SYaroslav Tykhiy 	/*
2986c98f401SYaroslav Tykhiy 	 * LOG_NDELAY sets up the logging connection immediately,
2996c98f401SYaroslav Tykhiy 	 * necessary for anonymous ftp's that chroot and can't do it later.
3006c98f401SYaroslav Tykhiy 	 */
3016c98f401SYaroslav Tykhiy 	openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
3023eb568f2SGuido van Rooij 
303c152df28SYaroslav Tykhiy 	while ((ch = getopt(argc, argv,
3042ea42282SYaroslav Tykhiy 	                    "468a:AdDEhlmMoOp:P:rRSt:T:u:UvW")) != -1) {
305ea022d16SRodney W. Grimes 		switch (ch) {
3060e063efeSYaroslav Tykhiy 		case '4':
307206fe568SHajimu UMEMOTO 			family = (family == AF_INET6) ? AF_UNSPEC : AF_INET;
3080e063efeSYaroslav Tykhiy 			break;
3090e063efeSYaroslav Tykhiy 
3100e063efeSYaroslav Tykhiy 		case '6':
311206fe568SHajimu UMEMOTO 			family = (family == AF_INET) ? AF_UNSPEC : AF_INET6;
3120e063efeSYaroslav Tykhiy 			break;
3130e063efeSYaroslav Tykhiy 
3142ea42282SYaroslav Tykhiy 		case '8':
3152ea42282SYaroslav Tykhiy 			assumeutf8 = 1;
3162ea42282SYaroslav Tykhiy 			break;
3172ea42282SYaroslav Tykhiy 
3180e063efeSYaroslav Tykhiy 		case 'a':
3190e063efeSYaroslav Tykhiy 			bindname = optarg;
3200e063efeSYaroslav Tykhiy 			break;
3210e063efeSYaroslav Tykhiy 
3220e063efeSYaroslav Tykhiy 		case 'A':
3230e063efeSYaroslav Tykhiy 			anon_only = 1;
324cf09a206SDavid Greenman 			break;
325cf09a206SDavid Greenman 
326ea022d16SRodney W. Grimes 		case 'd':
327618b0bbaSMark Murray 			ftpdebug++;
328ea022d16SRodney W. Grimes 			break;
329ea022d16SRodney W. Grimes 
3300e063efeSYaroslav Tykhiy 		case 'D':
3310e063efeSYaroslav Tykhiy 			daemon_mode++;
3320e063efeSYaroslav Tykhiy 			break;
3330e063efeSYaroslav Tykhiy 
334a4b77a2aSPoul-Henning Kamp 		case 'E':
335a4b77a2aSPoul-Henning Kamp 			noepsv = 1;
336a4b77a2aSPoul-Henning Kamp 			break;
337a4b77a2aSPoul-Henning Kamp 
338c152df28SYaroslav Tykhiy 		case 'h':
339c152df28SYaroslav Tykhiy 			hostinfo = 0;
340c152df28SYaroslav Tykhiy 			break;
341c152df28SYaroslav Tykhiy 
342ea022d16SRodney W. Grimes 		case 'l':
343ea022d16SRodney W. Grimes 			logging++;	/* > 1 == extra logging */
344ea022d16SRodney W. Grimes 			break;
345ea022d16SRodney W. Grimes 
346a117c345SYaroslav Tykhiy 		case 'm':
347a117c345SYaroslav Tykhiy 			noguestmod = 0;
348a117c345SYaroslav Tykhiy 			break;
349a117c345SYaroslav Tykhiy 
3500e063efeSYaroslav Tykhiy 		case 'M':
3510e063efeSYaroslav Tykhiy 			noguestmkd = 1;
3520e063efeSYaroslav Tykhiy 			break;
3530e063efeSYaroslav Tykhiy 
3540e063efeSYaroslav Tykhiy 		case 'o':
3550e063efeSYaroslav Tykhiy 			noretr = 1;
3560e063efeSYaroslav Tykhiy 			break;
3570e063efeSYaroslav Tykhiy 
3580e063efeSYaroslav Tykhiy 		case 'O':
3590e063efeSYaroslav Tykhiy 			noguestretr = 1;
3600e063efeSYaroslav Tykhiy 			break;
3610e063efeSYaroslav Tykhiy 
3620e063efeSYaroslav Tykhiy 		case 'p':
3630e063efeSYaroslav Tykhiy 			pid_file = optarg;
3640e063efeSYaroslav Tykhiy 			break;
3650e063efeSYaroslav Tykhiy 
36663591ba5SYaroslav Tykhiy 		case 'P':
36763591ba5SYaroslav Tykhiy 			bindport = optarg;
36863591ba5SYaroslav Tykhiy 			break;
36963591ba5SYaroslav Tykhiy 
370a4b77a2aSPoul-Henning Kamp 		case 'r':
371a4b77a2aSPoul-Henning Kamp 			readonly = 1;
372a4b77a2aSPoul-Henning Kamp 			break;
373a4b77a2aSPoul-Henning Kamp 
374a5a4544eSPaul Traina 		case 'R':
375a5a4544eSPaul Traina 			paranoid = 0;
376a5a4544eSPaul Traina 			break;
377a5a4544eSPaul Traina 
378a5a4544eSPaul Traina 		case 'S':
379a5a4544eSPaul Traina 			stats++;
380a5a4544eSPaul Traina 			break;
381a5a4544eSPaul Traina 
382ea022d16SRodney W. Grimes 		case 't':
383ea022d16SRodney W. Grimes 			timeout = atoi(optarg);
384ea022d16SRodney W. Grimes 			if (maxtimeout < timeout)
385ea022d16SRodney W. Grimes 				maxtimeout = timeout;
386ea022d16SRodney W. Grimes 			break;
387a5a4544eSPaul Traina 
3880e063efeSYaroslav Tykhiy 		case 'T':
3890e063efeSYaroslav Tykhiy 			maxtimeout = atoi(optarg);
3900e063efeSYaroslav Tykhiy 			if (timeout > maxtimeout)
3910e063efeSYaroslav Tykhiy 				timeout = maxtimeout;
392105a3c98SJulian Elischer 			break;
393105a3c98SJulian Elischer 
394ea022d16SRodney W. Grimes 		case 'u':
395ea022d16SRodney W. Grimes 		    {
396ea022d16SRodney W. Grimes 			long val = 0;
397ea022d16SRodney W. Grimes 
398ea022d16SRodney W. Grimes 			val = strtol(optarg, &optarg, 8);
399ea022d16SRodney W. Grimes 			if (*optarg != '\0' || val < 0)
4006c98f401SYaroslav Tykhiy 				syslog(LOG_WARNING, "bad value for -u");
401ea022d16SRodney W. Grimes 			else
402ea022d16SRodney W. Grimes 				defumask = val;
403ea022d16SRodney W. Grimes 			break;
404ea022d16SRodney W. Grimes 		    }
4050e063efeSYaroslav Tykhiy 		case 'U':
4060e063efeSYaroslav Tykhiy 			restricted_data_ports = 0;
4075a392aecSTorsten Blum 			break;
408ea022d16SRodney W. Grimes 
409ea022d16SRodney W. Grimes 		case 'v':
41093bd9dc5SYaroslav Tykhiy 			ftpdebug++;
411ea022d16SRodney W. Grimes 			break;
412ea022d16SRodney W. Grimes 
4135d7e0128SYaroslav Tykhiy 		case 'W':
4145d7e0128SYaroslav Tykhiy 			dowtmp = 0;
4155d7e0128SYaroslav Tykhiy 			break;
4165d7e0128SYaroslav Tykhiy 
417ea022d16SRodney W. Grimes 		default:
4186c98f401SYaroslav Tykhiy 			syslog(LOG_WARNING, "unknown flag -%c ignored", optopt);
419ea022d16SRodney W. Grimes 			break;
420ea022d16SRodney W. Grimes 		}
421ea022d16SRodney W. Grimes 	}
422cf09a206SDavid Greenman 
423cf09a206SDavid Greenman 	if (daemon_mode) {
424206fe568SHajimu UMEMOTO 		int *ctl_sock, fd, maxfd = -1, nfds, i;
425206fe568SHajimu UMEMOTO 		fd_set defreadfds, readfds;
426206fe568SHajimu UMEMOTO 		pid_t pid;
427125b9635SYaroslav Tykhiy 		struct pidfh *pfh;
428125b9635SYaroslav Tykhiy 
429125b9635SYaroslav Tykhiy 		if ((pfh = pidfile_open(pid_file, 0600, &pid)) == NULL) {
430125b9635SYaroslav Tykhiy 			if (errno == EEXIST) {
431125b9635SYaroslav Tykhiy 				syslog(LOG_ERR, "%s already running, pid %d",
432125b9635SYaroslav Tykhiy 				       getprogname(), (int)pid);
433125b9635SYaroslav Tykhiy 				exit(1);
434125b9635SYaroslav Tykhiy 			}
435125b9635SYaroslav Tykhiy 			syslog(LOG_WARNING, "pidfile_open: %m");
436125b9635SYaroslav Tykhiy 		}
437cf09a206SDavid Greenman 
438cf09a206SDavid Greenman 		/*
439cf09a206SDavid Greenman 		 * Detach from parent.
440cf09a206SDavid Greenman 		 */
441cf09a206SDavid Greenman 		if (daemon(1, 1) < 0) {
442cf09a206SDavid Greenman 			syslog(LOG_ERR, "failed to become a daemon");
443cf09a206SDavid Greenman 			exit(1);
444cf09a206SDavid Greenman 		}
445125b9635SYaroslav Tykhiy 
446125b9635SYaroslav Tykhiy 		if (pfh != NULL && pidfile_write(pfh) == -1)
447125b9635SYaroslav Tykhiy 			syslog(LOG_WARNING, "pidfile_write: %m");
448125b9635SYaroslav Tykhiy 
4494b82fc95SYaroslav Tykhiy 		sa.sa_handler = reapchild;
4504b82fc95SYaroslav Tykhiy 		(void)sigaction(SIGCHLD, &sa, NULL);
4514dd8b5abSYoshinobu Inoue 
4522c9fd5f2SHajimu UMEMOTO #ifdef VIRTUAL_HOSTING
4532c9fd5f2SHajimu UMEMOTO 		inithosts(family);
4542c9fd5f2SHajimu UMEMOTO #endif
4552c9fd5f2SHajimu UMEMOTO 
456cf09a206SDavid Greenman 		/*
457cf09a206SDavid Greenman 		 * Open a socket, bind it to the FTP port, and start
458cf09a206SDavid Greenman 		 * listening.
459cf09a206SDavid Greenman 		 */
460206fe568SHajimu UMEMOTO 		ctl_sock = socksetup(family, bindname, bindport);
461206fe568SHajimu UMEMOTO 		if (ctl_sock == NULL)
462cf09a206SDavid Greenman 			exit(1);
463206fe568SHajimu UMEMOTO 
464206fe568SHajimu UMEMOTO 		FD_ZERO(&defreadfds);
465206fe568SHajimu UMEMOTO 		for (i = 1; i <= *ctl_sock; i++) {
466206fe568SHajimu UMEMOTO 			FD_SET(ctl_sock[i], &defreadfds);
467206fe568SHajimu UMEMOTO 			if (listen(ctl_sock[i], 32) < 0) {
468cf09a206SDavid Greenman 				syslog(LOG_ERR, "control listen: %m");
469cf09a206SDavid Greenman 				exit(1);
470cf09a206SDavid Greenman 			}
471206fe568SHajimu UMEMOTO 			if (maxfd < ctl_sock[i])
472206fe568SHajimu UMEMOTO 				maxfd = ctl_sock[i];
473206fe568SHajimu UMEMOTO 		}
474206fe568SHajimu UMEMOTO 
475cf09a206SDavid Greenman 		/*
476cf09a206SDavid Greenman 		 * Loop forever accepting connection requests and forking off
477cf09a206SDavid Greenman 		 * children to handle them.
478cf09a206SDavid Greenman 		 */
479cf09a206SDavid Greenman 		while (1) {
480206fe568SHajimu UMEMOTO 			FD_COPY(&defreadfds, &readfds);
481206fe568SHajimu UMEMOTO 			nfds = select(maxfd + 1, &readfds, NULL, NULL, 0);
482206fe568SHajimu UMEMOTO 			if (nfds <= 0) {
483206fe568SHajimu UMEMOTO 				if (nfds < 0 && errno != EINTR)
484206fe568SHajimu UMEMOTO 					syslog(LOG_WARNING, "select: %m");
485206fe568SHajimu UMEMOTO 				continue;
486206fe568SHajimu UMEMOTO 			}
487206fe568SHajimu UMEMOTO 
488206fe568SHajimu UMEMOTO 			pid = -1;
489206fe568SHajimu UMEMOTO                         for (i = 1; i <= *ctl_sock; i++)
490206fe568SHajimu UMEMOTO 				if (FD_ISSET(ctl_sock[i], &readfds)) {
491206fe568SHajimu UMEMOTO 					addrlen = sizeof(his_addr);
492206fe568SHajimu UMEMOTO 					fd = accept(ctl_sock[i],
493206fe568SHajimu UMEMOTO 					    (struct sockaddr *)&his_addr,
494206fe568SHajimu UMEMOTO 					    &addrlen);
495a599a64aSYaroslav Tykhiy 					if (fd == -1) {
496a599a64aSYaroslav Tykhiy 						syslog(LOG_WARNING,
497a599a64aSYaroslav Tykhiy 						       "accept: %m");
498a599a64aSYaroslav Tykhiy 						continue;
499cf09a206SDavid Greenman 					}
500a599a64aSYaroslav Tykhiy 					switch (pid = fork()) {
501a599a64aSYaroslav Tykhiy 					case 0:
5028eb0508fSYaroslav Tykhiy 						/* child */
5038eb0508fSYaroslav Tykhiy 						(void) dup2(fd, 0);
5048eb0508fSYaroslav Tykhiy 						(void) dup2(fd, 1);
505a599a64aSYaroslav Tykhiy 						(void) close(fd);
506a599a64aSYaroslav Tykhiy 						for (i = 1; i <= *ctl_sock; i++)
5078eb0508fSYaroslav Tykhiy 							close(ctl_sock[i]);
508125b9635SYaroslav Tykhiy 						if (pfh != NULL)
509125b9635SYaroslav Tykhiy 							pidfile_close(pfh);
510a599a64aSYaroslav Tykhiy 						goto gotchild;
511a599a64aSYaroslav Tykhiy 					case -1:
512a599a64aSYaroslav Tykhiy 						syslog(LOG_WARNING, "fork: %m");
513a599a64aSYaroslav Tykhiy 						/* FALLTHROUGH */
514a599a64aSYaroslav Tykhiy 					default:
515a599a64aSYaroslav Tykhiy 						close(fd);
516a599a64aSYaroslav Tykhiy 					}
517206fe568SHajimu UMEMOTO 				}
518125b9635SYaroslav Tykhiy 		}
519cf09a206SDavid Greenman 	} else {
520cf09a206SDavid Greenman 		addrlen = sizeof(his_addr);
521cf09a206SDavid Greenman 		if (getpeername(0, (struct sockaddr *)&his_addr, &addrlen) < 0) {
522cf09a206SDavid Greenman 			syslog(LOG_ERR, "getpeername (%s): %m",argv[0]);
523cf09a206SDavid Greenman 			exit(1);
524cf09a206SDavid Greenman 		}
5252c9fd5f2SHajimu UMEMOTO 
5262c9fd5f2SHajimu UMEMOTO #ifdef VIRTUAL_HOSTING
5272c9fd5f2SHajimu UMEMOTO 		if (his_addr.su_family == AF_INET6 &&
5282c9fd5f2SHajimu UMEMOTO 		    IN6_IS_ADDR_V4MAPPED(&his_addr.su_sin6.sin6_addr))
5292c9fd5f2SHajimu UMEMOTO 			family = AF_INET;
5302c9fd5f2SHajimu UMEMOTO 		else
5312c9fd5f2SHajimu UMEMOTO 			family = his_addr.su_family;
5322c9fd5f2SHajimu UMEMOTO 		inithosts(family);
5332c9fd5f2SHajimu UMEMOTO #endif
534cf09a206SDavid Greenman 	}
535cf09a206SDavid Greenman 
536a599a64aSYaroslav Tykhiy gotchild:
5374b82fc95SYaroslav Tykhiy 	sa.sa_handler = SIG_DFL;
5384b82fc95SYaroslav Tykhiy 	(void)sigaction(SIGCHLD, &sa, NULL);
5394b82fc95SYaroslav Tykhiy 
5404b82fc95SYaroslav Tykhiy 	sa.sa_handler = sigurg;
5414b82fc95SYaroslav Tykhiy 	sa.sa_flags = 0;		/* don't restart syscalls for SIGURG */
5424b82fc95SYaroslav Tykhiy 	(void)sigaction(SIGURG, &sa, NULL);
5434b82fc95SYaroslav Tykhiy 
5444b82fc95SYaroslav Tykhiy 	sigfillset(&sa.sa_mask);	/* block all signals in handler */
5454b82fc95SYaroslav Tykhiy 	sa.sa_flags = SA_RESTART;
5464b82fc95SYaroslav Tykhiy 	sa.sa_handler = sigquit;
5474b82fc95SYaroslav Tykhiy 	(void)sigaction(SIGHUP, &sa, NULL);
5484b82fc95SYaroslav Tykhiy 	(void)sigaction(SIGINT, &sa, NULL);
5494b82fc95SYaroslav Tykhiy 	(void)sigaction(SIGQUIT, &sa, NULL);
5504b82fc95SYaroslav Tykhiy 	(void)sigaction(SIGTERM, &sa, NULL);
5514b82fc95SYaroslav Tykhiy 
5524b82fc95SYaroslav Tykhiy 	sa.sa_handler = lostconn;
5534b82fc95SYaroslav Tykhiy 	(void)sigaction(SIGPIPE, &sa, NULL);
554ea022d16SRodney W. Grimes 
555cf09a206SDavid Greenman 	addrlen = sizeof(ctrl_addr);
556cf09a206SDavid Greenman 	if (getsockname(0, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) {
557cf09a206SDavid Greenman 		syslog(LOG_ERR, "getsockname (%s): %m",argv[0]);
558cf09a206SDavid Greenman 		exit(1);
559cf09a206SDavid Greenman 	}
56063591ba5SYaroslav Tykhiy 	dataport = ntohs(ctrl_addr.su_port) - 1; /* as per RFC 959 */
561ea4e54b9SDavid Nugent #ifdef VIRTUAL_HOSTING
562ea4e54b9SDavid Nugent 	/* select our identity from virtual host table */
5634dd8b5abSYoshinobu Inoue 	selecthost(&ctrl_addr);
564ea4e54b9SDavid Nugent #endif
565cf09a206SDavid Greenman #ifdef IP_TOS
5664dd8b5abSYoshinobu Inoue 	if (ctrl_addr.su_family == AF_INET)
5674dd8b5abSYoshinobu Inoue       {
568cf09a206SDavid Greenman 	tos = IPTOS_LOWDELAY;
56957d4ef07SYaroslav Tykhiy 	if (setsockopt(0, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
570406d1ae9SYaroslav Tykhiy 		syslog(LOG_WARNING, "control setsockopt (IP_TOS): %m");
5714dd8b5abSYoshinobu Inoue       }
572cf09a206SDavid Greenman #endif
573dadb9fb3SDavid Greenman 	/*
574dadb9fb3SDavid Greenman 	 * Disable Nagle on the control channel so that we don't have to wait
575dadb9fb3SDavid Greenman 	 * for peer's ACK before issuing our next reply.
576dadb9fb3SDavid Greenman 	 */
577dadb9fb3SDavid Greenman 	if (setsockopt(0, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) < 0)
578406d1ae9SYaroslav Tykhiy 		syslog(LOG_WARNING, "control setsockopt (TCP_NODELAY): %m");
579dadb9fb3SDavid Greenman 
5804dd8b5abSYoshinobu Inoue 	data_source.su_port = htons(ntohs(ctrl_addr.su_port) - 1);
581cf09a206SDavid Greenman 
58280643af0SEd Schouten 	(void)snprintf(wtmpid, sizeof(wtmpid), "%xftpd", getpid());
583a5a4544eSPaul Traina 
584ea022d16SRodney W. Grimes 	/* Try to handle urgent data inline */
585ea022d16SRodney W. Grimes #ifdef SO_OOBINLINE
58657d4ef07SYaroslav Tykhiy 	if (setsockopt(0, SOL_SOCKET, SO_OOBINLINE, &on, sizeof(on)) < 0)
587406d1ae9SYaroslav Tykhiy 		syslog(LOG_WARNING, "control setsockopt (SO_OOBINLINE): %m");
588ea022d16SRodney W. Grimes #endif
589ea022d16SRodney W. Grimes 
590ea022d16SRodney W. Grimes #ifdef	F_SETOWN
591ea022d16SRodney W. Grimes 	if (fcntl(fileno(stdin), F_SETOWN, getpid()) == -1)
592ea022d16SRodney W. Grimes 		syslog(LOG_ERR, "fcntl F_SETOWN: %m");
593ea022d16SRodney W. Grimes #endif
5944dd8b5abSYoshinobu Inoue 	dolog((struct sockaddr *)&his_addr);
595ea022d16SRodney W. Grimes 	/*
596ea022d16SRodney W. Grimes 	 * Set up default state
597ea022d16SRodney W. Grimes 	 */
598ea022d16SRodney W. Grimes 	data = -1;
599ea022d16SRodney W. Grimes 	type = TYPE_A;
600ea022d16SRodney W. Grimes 	form = FORM_N;
601ea022d16SRodney W. Grimes 	stru = STRU_F;
602ea022d16SRodney W. Grimes 	mode = MODE_S;
603ea022d16SRodney W. Grimes 	tmpline[0] = '\0';
604ea022d16SRodney W. Grimes 
605ea022d16SRodney W. Grimes 	/* If logins are disabled, print out the message. */
606ea022d16SRodney W. Grimes 	if ((fd = fopen(_PATH_NOLOGIN,"r")) != NULL) {
607ea022d16SRodney W. Grimes 		while (fgets(line, sizeof(line), fd) != NULL) {
608ea022d16SRodney W. Grimes 			if ((cp = strchr(line, '\n')) != NULL)
609ea022d16SRodney W. Grimes 				*cp = '\0';
610ea022d16SRodney W. Grimes 			lreply(530, "%s", line);
611ea022d16SRodney W. Grimes 		}
612ea022d16SRodney W. Grimes 		(void) fflush(stdout);
613ea022d16SRodney W. Grimes 		(void) fclose(fd);
614ea022d16SRodney W. Grimes 		reply(530, "System not available.");
615ea022d16SRodney W. Grimes 		exit(0);
616ea022d16SRodney W. Grimes 	}
617ea4e54b9SDavid Nugent #ifdef VIRTUAL_HOSTING
61863047c6fSDavid E. O'Brien 	fd = fopen(thishost->welcome, "r");
619ea4e54b9SDavid Nugent #else
62063047c6fSDavid E. O'Brien 	fd = fopen(_PATH_FTPWELCOME, "r");
621ea4e54b9SDavid Nugent #endif
62263047c6fSDavid E. O'Brien 	if (fd != NULL) {
623ea022d16SRodney W. Grimes 		while (fgets(line, sizeof(line), fd) != NULL) {
624ea022d16SRodney W. Grimes 			if ((cp = strchr(line, '\n')) != NULL)
625ea022d16SRodney W. Grimes 				*cp = '\0';
626ea022d16SRodney W. Grimes 			lreply(220, "%s", line);
627ea022d16SRodney W. Grimes 		}
628ea022d16SRodney W. Grimes 		(void) fflush(stdout);
629ea022d16SRodney W. Grimes 		(void) fclose(fd);
630ea022d16SRodney W. Grimes 		/* reply(220,) must follow */
631ea022d16SRodney W. Grimes 	}
632ea4e54b9SDavid Nugent #ifndef VIRTUAL_HOSTING
6330512556aSDavid Nugent 	if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
634618b0bbaSMark Murray 		fatalerror("Ran out of memory.");
63504683b2cSYaroslav Tykhiy 	if (gethostname(hostname, MAXHOSTNAMELEN - 1) < 0)
63604683b2cSYaroslav Tykhiy 		hostname[0] = '\0';
6379e9a43bdSBrian Somers 	hostname[MAXHOSTNAMELEN - 1] = '\0';
638ea4e54b9SDavid Nugent #endif
639c152df28SYaroslav Tykhiy 	if (hostinfo)
640ea022d16SRodney W. Grimes 		reply(220, "%s FTP server (%s) ready.", hostname, version);
641c152df28SYaroslav Tykhiy 	else
642c152df28SYaroslav Tykhiy 		reply(220, "FTP server ready.");
643ea022d16SRodney W. Grimes 	for (;;)
644ea022d16SRodney W. Grimes 		(void) yyparse();
645ea022d16SRodney W. Grimes 	/* NOTREACHED */
646ea022d16SRodney W. Grimes }
647ea022d16SRodney W. Grimes 
648ea022d16SRodney W. Grimes static void
649e4bc453cSWarner Losh lostconn(int signo)
650ea022d16SRodney W. Grimes {
651ea022d16SRodney W. Grimes 
652618b0bbaSMark Murray 	if (ftpdebug)
653ea022d16SRodney W. Grimes 		syslog(LOG_DEBUG, "lost connection");
654e02897faSPhilippe Charnier 	dologout(1);
655ea022d16SRodney W. Grimes }
656ea022d16SRodney W. Grimes 
6574b82fc95SYaroslav Tykhiy static void
658e4bc453cSWarner Losh sigquit(int signo)
6594b82fc95SYaroslav Tykhiy {
6604b82fc95SYaroslav Tykhiy 
6614b82fc95SYaroslav Tykhiy 	syslog(LOG_ERR, "got signal %d", signo);
6624b82fc95SYaroslav Tykhiy 	dologout(1);
6634b82fc95SYaroslav Tykhiy }
6644b82fc95SYaroslav Tykhiy 
665ea4e54b9SDavid Nugent #ifdef VIRTUAL_HOSTING
666ea4e54b9SDavid Nugent /*
667ea4e54b9SDavid Nugent  * read in virtual host tables (if they exist)
668ea4e54b9SDavid Nugent  */
669ea4e54b9SDavid Nugent 
670ea4e54b9SDavid Nugent static void
6712c9fd5f2SHajimu UMEMOTO inithosts(int family)
672ea4e54b9SDavid Nugent {
67355b54aa7SYaroslav Tykhiy 	int insert;
674737d08f3SYaroslav Tykhiy 	size_t len;
675ea4e54b9SDavid Nugent 	FILE *fp;
676737d08f3SYaroslav Tykhiy 	char *cp, *mp, *line;
677737d08f3SYaroslav Tykhiy 	char *hostname;
67855b54aa7SYaroslav Tykhiy 	char *vhost, *anonuser, *statfile, *welcome, *loginmsg;
679ea4e54b9SDavid Nugent 	struct ftphost *hrp, *lhrp;
6804dd8b5abSYoshinobu Inoue 	struct addrinfo hints, *res, *ai;
681ea4e54b9SDavid Nugent 
682ea4e54b9SDavid Nugent 	/*
683ea4e54b9SDavid Nugent 	 * Fill in the default host information
684ea4e54b9SDavid Nugent 	 */
685737d08f3SYaroslav Tykhiy 	if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
686618b0bbaSMark Murray 		fatalerror("Ran out of memory.");
68704683b2cSYaroslav Tykhiy 	if (gethostname(hostname, MAXHOSTNAMELEN - 1) < 0)
688737d08f3SYaroslav Tykhiy 		hostname[0] = '\0';
689737d08f3SYaroslav Tykhiy 	hostname[MAXHOSTNAMELEN - 1] = '\0';
690737d08f3SYaroslav Tykhiy 	if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
691737d08f3SYaroslav Tykhiy 		fatalerror("Ran out of memory.");
692737d08f3SYaroslav Tykhiy 	hrp->hostname = hostname;
693f38c6cadSYoshinobu Inoue 	hrp->hostinfo = NULL;
6944dd8b5abSYoshinobu Inoue 
6954dd8b5abSYoshinobu Inoue 	memset(&hints, 0, sizeof(hints));
6962c9fd5f2SHajimu UMEMOTO 	hints.ai_flags = AI_PASSIVE;
6972c9fd5f2SHajimu UMEMOTO 	hints.ai_family = family;
6982c9fd5f2SHajimu UMEMOTO 	hints.ai_socktype = SOCK_STREAM;
699b1d8d5cdSYaroslav Tykhiy 	if (getaddrinfo(hrp->hostname, NULL, &hints, &res) == 0)
700f38c6cadSYoshinobu Inoue 		hrp->hostinfo = res;
701ea4e54b9SDavid Nugent 	hrp->statfile = _PATH_FTPDSTATFILE;
702ea4e54b9SDavid Nugent 	hrp->welcome  = _PATH_FTPWELCOME;
703ea4e54b9SDavid Nugent 	hrp->loginmsg = _PATH_FTPLOGINMESG;
704ea4e54b9SDavid Nugent 	hrp->anonuser = "ftp";
705ea4e54b9SDavid Nugent 	hrp->next = NULL;
706ea4e54b9SDavid Nugent 	thishost = firsthost = lhrp = hrp;
707ea4e54b9SDavid Nugent 	if ((fp = fopen(_PATH_FTPHOSTS, "r")) != NULL) {
708ec009cf0SYaroslav Tykhiy 		int addrsize, gothost;
7094dd8b5abSYoshinobu Inoue 		void *addr;
7104dd8b5abSYoshinobu Inoue 		struct hostent *hp;
7114dd8b5abSYoshinobu Inoue 
712737d08f3SYaroslav Tykhiy 		while ((line = fgetln(fp, &len)) != NULL) {
7134dd8b5abSYoshinobu Inoue 			int	i, hp_error;
714ea4e54b9SDavid Nugent 
715737d08f3SYaroslav Tykhiy 			/* skip comments */
716737d08f3SYaroslav Tykhiy 			if (line[0] == '#')
717ea4e54b9SDavid Nugent 				continue;
718737d08f3SYaroslav Tykhiy 			if (line[len - 1] == '\n') {
719737d08f3SYaroslav Tykhiy 				line[len - 1] = '\0';
720737d08f3SYaroslav Tykhiy 				mp = NULL;
721737d08f3SYaroslav Tykhiy 			} else {
722737d08f3SYaroslav Tykhiy 				if ((mp = malloc(len + 1)) == NULL)
723737d08f3SYaroslav Tykhiy 					fatalerror("Ran out of memory.");
724737d08f3SYaroslav Tykhiy 				memcpy(mp, line, len);
725737d08f3SYaroslav Tykhiy 				mp[len] = '\0';
726737d08f3SYaroslav Tykhiy 				line = mp;
727ea4e54b9SDavid Nugent 			}
728ea4e54b9SDavid Nugent 			cp = strtok(line, " \t");
729737d08f3SYaroslav Tykhiy 			/* skip empty lines */
730737d08f3SYaroslav Tykhiy 			if (cp == NULL)
731737d08f3SYaroslav Tykhiy 				goto nextline;
73255b54aa7SYaroslav Tykhiy 			vhost = cp;
73355b54aa7SYaroslav Tykhiy 
73455b54aa7SYaroslav Tykhiy 			/* set defaults */
73555b54aa7SYaroslav Tykhiy 			anonuser = "ftp";
73655b54aa7SYaroslav Tykhiy 			statfile = _PATH_FTPDSTATFILE;
73755b54aa7SYaroslav Tykhiy 			welcome  = _PATH_FTPWELCOME;
73855b54aa7SYaroslav Tykhiy 			loginmsg = _PATH_FTPLOGINMESG;
73955b54aa7SYaroslav Tykhiy 
74055b54aa7SYaroslav Tykhiy 			/*
74155b54aa7SYaroslav Tykhiy 			 * Preparse the line so we can use its info
74255b54aa7SYaroslav Tykhiy 			 * for all the addresses associated with
74355b54aa7SYaroslav Tykhiy 			 * the virtual host name.
74455b54aa7SYaroslav Tykhiy 			 * Field 0, the virtual host name, is special:
74555b54aa7SYaroslav Tykhiy 			 * it's already parsed off and will be strdup'ed
74655b54aa7SYaroslav Tykhiy 			 * later, after we know its canonical form.
74755b54aa7SYaroslav Tykhiy 			 */
74855b54aa7SYaroslav Tykhiy 			for (i = 1; i < 5 && (cp = strtok(NULL, " \t")); i++)
74955b54aa7SYaroslav Tykhiy 				if (*cp != '-' && (cp = strdup(cp)))
75055b54aa7SYaroslav Tykhiy 					switch (i) {
75155b54aa7SYaroslav Tykhiy 					case 1:	/* anon user permissions */
75255b54aa7SYaroslav Tykhiy 						anonuser = cp;
75355b54aa7SYaroslav Tykhiy 						break;
75455b54aa7SYaroslav Tykhiy 					case 2: /* statistics file */
75555b54aa7SYaroslav Tykhiy 						statfile = cp;
75655b54aa7SYaroslav Tykhiy 						break;
75755b54aa7SYaroslav Tykhiy 					case 3: /* welcome message */
75855b54aa7SYaroslav Tykhiy 						welcome  = cp;
75955b54aa7SYaroslav Tykhiy 						break;
76055b54aa7SYaroslav Tykhiy 					case 4: /* login message */
76155b54aa7SYaroslav Tykhiy 						loginmsg = cp;
76255b54aa7SYaroslav Tykhiy 						break;
76355b54aa7SYaroslav Tykhiy 					default: /* programming error */
76455b54aa7SYaroslav Tykhiy 						abort();
76555b54aa7SYaroslav Tykhiy 						/* NOTREACHED */
76655b54aa7SYaroslav Tykhiy 					}
7674dd8b5abSYoshinobu Inoue 
7684dd8b5abSYoshinobu Inoue 			hints.ai_flags = AI_PASSIVE;
7692c9fd5f2SHajimu UMEMOTO 			hints.ai_family = family;
7702c9fd5f2SHajimu UMEMOTO 			hints.ai_socktype = SOCK_STREAM;
771b1d8d5cdSYaroslav Tykhiy 			if (getaddrinfo(vhost, NULL, &hints, &res) != 0)
772737d08f3SYaroslav Tykhiy 				goto nextline;
7734dd8b5abSYoshinobu Inoue 			for (ai = res; ai != NULL && ai->ai_addr != NULL;
774b535a9bfSDavid Nugent 			     ai = ai->ai_next) {
7754dd8b5abSYoshinobu Inoue 
776b535a9bfSDavid Nugent 			gothost = 0;
777ea4e54b9SDavid Nugent 			for (hrp = firsthost; hrp != NULL; hrp = hrp->next) {
778f38c6cadSYoshinobu Inoue 				struct addrinfo *hi;
779f38c6cadSYoshinobu Inoue 
780f38c6cadSYoshinobu Inoue 				for (hi = hrp->hostinfo; hi != NULL;
781f38c6cadSYoshinobu Inoue 				     hi = hi->ai_next)
782f38c6cadSYoshinobu Inoue 					if (hi->ai_addrlen == ai->ai_addrlen &&
783f38c6cadSYoshinobu Inoue 					    memcmp(hi->ai_addr,
7844dd8b5abSYoshinobu Inoue 						   ai->ai_addr,
785b535a9bfSDavid Nugent 						   ai->ai_addr->sa_len) == 0) {
786b535a9bfSDavid Nugent 						gothost++;
787b535a9bfSDavid Nugent 						break;
788b535a9bfSDavid Nugent 					}
789b535a9bfSDavid Nugent 				if (gothost)
790ea4e54b9SDavid Nugent 					break;
791ea4e54b9SDavid Nugent 			}
792ea4e54b9SDavid Nugent 			if (hrp == NULL) {
793ea4e54b9SDavid Nugent 				if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
794737d08f3SYaroslav Tykhiy 					goto nextline;
795b1d8d5cdSYaroslav Tykhiy 				hrp->hostname = NULL;
79655b54aa7SYaroslav Tykhiy 				insert = 1;
797f2fe752dSYaroslav Tykhiy 			} else {
7981f75c13eSYaroslav Tykhiy 				if (hrp->hostinfo && hrp->hostinfo != res)
799b1d8d5cdSYaroslav Tykhiy 					freeaddrinfo(hrp->hostinfo);
800f2fe752dSYaroslav Tykhiy 				insert = 0; /* host already in the chain */
801f2fe752dSYaroslav Tykhiy 			}
802f38c6cadSYoshinobu Inoue 			hrp->hostinfo = res;
803f38c6cadSYoshinobu Inoue 
804ea4e54b9SDavid Nugent 			/*
805ea4e54b9SDavid Nugent 			 * determine hostname to use.
8064dd8b5abSYoshinobu Inoue 			 * force defined name if there is a valid alias
807ea4e54b9SDavid Nugent 			 * otherwise fallback to primary hostname
808ea4e54b9SDavid Nugent 			 */
8094dd8b5abSYoshinobu Inoue 			/* XXX: getaddrinfo() can't do alias check */
810f38c6cadSYoshinobu Inoue 			switch(hrp->hostinfo->ai_family) {
8114dd8b5abSYoshinobu Inoue 			case AF_INET:
8124b4cc4c6SYaroslav Tykhiy 				addr = &((struct sockaddr_in *)hrp->hostinfo->ai_addr)->sin_addr;
8134b4cc4c6SYaroslav Tykhiy 				addrsize = sizeof(struct in_addr);
8144dd8b5abSYoshinobu Inoue 				break;
8154dd8b5abSYoshinobu Inoue 			case AF_INET6:
8164b4cc4c6SYaroslav Tykhiy 				addr = &((struct sockaddr_in6 *)hrp->hostinfo->ai_addr)->sin6_addr;
8174b4cc4c6SYaroslav Tykhiy 				addrsize = sizeof(struct in6_addr);
8184dd8b5abSYoshinobu Inoue 				break;
8194dd8b5abSYoshinobu Inoue 			default:
8204dd8b5abSYoshinobu Inoue 				/* should not reach here */
821f38c6cadSYoshinobu Inoue 				freeaddrinfo(hrp->hostinfo);
822f2fe752dSYaroslav Tykhiy 				if (insert)
823f2fe752dSYaroslav Tykhiy 					free(hrp); /*not in chain, can free*/
824f2fe752dSYaroslav Tykhiy 				else
825f2fe752dSYaroslav Tykhiy 					hrp->hostinfo = NULL; /*mark as blank*/
826737d08f3SYaroslav Tykhiy 				goto nextline;
8274dd8b5abSYoshinobu Inoue 				/* NOTREACHED */
8284dd8b5abSYoshinobu Inoue 			}
82957d4ef07SYaroslav Tykhiy 			if ((hp = getipnodebyaddr(addr, addrsize,
830f38c6cadSYoshinobu Inoue 						  hrp->hostinfo->ai_family,
8314dd8b5abSYoshinobu Inoue 						  &hp_error)) != NULL) {
83255b54aa7SYaroslav Tykhiy 				if (strcmp(vhost, hp->h_name) != 0) {
833ea4e54b9SDavid Nugent 					if (hp->h_aliases == NULL)
83455b54aa7SYaroslav Tykhiy 						vhost = hp->h_name;
835ea4e54b9SDavid Nugent 					else {
836ea4e54b9SDavid Nugent 						i = 0;
837ea4e54b9SDavid Nugent 						while (hp->h_aliases[i] &&
83855b54aa7SYaroslav Tykhiy 						       strcmp(vhost, hp->h_aliases[i]) != 0)
839ea4e54b9SDavid Nugent 							++i;
840ea4e54b9SDavid Nugent 						if (hp->h_aliases[i] == NULL)
84155b54aa7SYaroslav Tykhiy 							vhost = hp->h_name;
842ea4e54b9SDavid Nugent 					}
843ea4e54b9SDavid Nugent 				}
844ea4e54b9SDavid Nugent 			}
845b1d8d5cdSYaroslav Tykhiy 			if (hrp->hostname &&
846b1d8d5cdSYaroslav Tykhiy 			    strcmp(hrp->hostname, vhost) != 0) {
847b1d8d5cdSYaroslav Tykhiy 				free(hrp->hostname);
848b1d8d5cdSYaroslav Tykhiy 				hrp->hostname = NULL;
849b1d8d5cdSYaroslav Tykhiy 			}
850b1d8d5cdSYaroslav Tykhiy 			if (hrp->hostname == NULL &&
851f2fe752dSYaroslav Tykhiy 			    (hrp->hostname = strdup(vhost)) == NULL) {
852f2fe752dSYaroslav Tykhiy 				freeaddrinfo(hrp->hostinfo);
853f2fe752dSYaroslav Tykhiy 				hrp->hostinfo = NULL; /* mark as blank */
854f2fe752dSYaroslav Tykhiy 				if (hp)
855f2fe752dSYaroslav Tykhiy 					freehostent(hp);
85655b54aa7SYaroslav Tykhiy 				goto nextline;
857f2fe752dSYaroslav Tykhiy 			}
85855b54aa7SYaroslav Tykhiy 			hrp->anonuser = anonuser;
85955b54aa7SYaroslav Tykhiy 			hrp->statfile = statfile;
86055b54aa7SYaroslav Tykhiy 			hrp->welcome  = welcome;
86155b54aa7SYaroslav Tykhiy 			hrp->loginmsg = loginmsg;
86255b54aa7SYaroslav Tykhiy 			if (insert) {
86355b54aa7SYaroslav Tykhiy 				hrp->next  = NULL;
86455b54aa7SYaroslav Tykhiy 				lhrp->next = hrp;
86555b54aa7SYaroslav Tykhiy 				lhrp = hrp;
86655b54aa7SYaroslav Tykhiy 			}
867233c0f66SYaroslav Tykhiy 			if (hp)
8684dd8b5abSYoshinobu Inoue 				freehostent(hp);
8694dd8b5abSYoshinobu Inoue 		      }
870737d08f3SYaroslav Tykhiy nextline:
871737d08f3SYaroslav Tykhiy 			if (mp)
872737d08f3SYaroslav Tykhiy 				free(mp);
873ea4e54b9SDavid Nugent 		}
874ea4e54b9SDavid Nugent 		(void) fclose(fp);
875ea4e54b9SDavid Nugent 	}
876ea4e54b9SDavid Nugent }
877ea4e54b9SDavid Nugent 
878ea4e54b9SDavid Nugent static void
879e4bc453cSWarner Losh selecthost(union sockunion *su)
880ea4e54b9SDavid Nugent {
881ea4e54b9SDavid Nugent 	struct ftphost	*hrp;
8824dd8b5abSYoshinobu Inoue 	u_int16_t port;
8834dd8b5abSYoshinobu Inoue #ifdef INET6
8844dd8b5abSYoshinobu Inoue 	struct in6_addr *mapped_in6 = NULL;
8854dd8b5abSYoshinobu Inoue #endif
886f38c6cadSYoshinobu Inoue 	struct addrinfo *hi;
8874dd8b5abSYoshinobu Inoue 
8884dd8b5abSYoshinobu Inoue #ifdef INET6
8894dd8b5abSYoshinobu Inoue 	/*
8904dd8b5abSYoshinobu Inoue 	 * XXX IPv4 mapped IPv6 addr consideraton,
8914dd8b5abSYoshinobu Inoue 	 * specified in rfc2373.
8924dd8b5abSYoshinobu Inoue 	 */
8934dd8b5abSYoshinobu Inoue 	if (su->su_family == AF_INET6 &&
8944dd8b5abSYoshinobu Inoue 	    IN6_IS_ADDR_V4MAPPED(&su->su_sin6.sin6_addr))
8954dd8b5abSYoshinobu Inoue 		mapped_in6 = &su->su_sin6.sin6_addr;
8964dd8b5abSYoshinobu Inoue #endif
897ea4e54b9SDavid Nugent 
898ea4e54b9SDavid Nugent 	hrp = thishost = firsthost;	/* default */
8994dd8b5abSYoshinobu Inoue 	port = su->su_port;
9004dd8b5abSYoshinobu Inoue 	su->su_port = 0;
901ea4e54b9SDavid Nugent 	while (hrp != NULL) {
902b535a9bfSDavid Nugent 	    for (hi = hrp->hostinfo; hi != NULL; hi = hi->ai_next) {
903f38c6cadSYoshinobu Inoue 		if (memcmp(su, hi->ai_addr, hi->ai_addrlen) == 0) {
904ea4e54b9SDavid Nugent 			thishost = hrp;
905ebd83647SYaroslav Tykhiy 			goto found;
906ea4e54b9SDavid Nugent 		}
9074dd8b5abSYoshinobu Inoue #ifdef INET6
9084dd8b5abSYoshinobu Inoue 		/* XXX IPv4 mapped IPv6 addr consideraton */
909f38c6cadSYoshinobu Inoue 		if (hi->ai_addr->sa_family == AF_INET && mapped_in6 != NULL &&
9104dd8b5abSYoshinobu Inoue 		    (memcmp(&mapped_in6->s6_addr[12],
911f38c6cadSYoshinobu Inoue 			    &((struct sockaddr_in *)hi->ai_addr)->sin_addr,
9124dd8b5abSYoshinobu Inoue 			    sizeof(struct in_addr)) == 0)) {
9134dd8b5abSYoshinobu Inoue 			thishost = hrp;
914ebd83647SYaroslav Tykhiy 			goto found;
9154dd8b5abSYoshinobu Inoue 		}
9164dd8b5abSYoshinobu Inoue #endif
917f38c6cadSYoshinobu Inoue 	    }
918ea4e54b9SDavid Nugent 	    hrp = hrp->next;
919ea4e54b9SDavid Nugent 	}
920ebd83647SYaroslav Tykhiy found:
9214dd8b5abSYoshinobu Inoue 	su->su_port = port;
922ea4e54b9SDavid Nugent 	/* setup static variables as appropriate */
923ea4e54b9SDavid Nugent 	hostname = thishost->hostname;
924ea4e54b9SDavid Nugent 	ftpuser = thishost->anonuser;
925ea4e54b9SDavid Nugent }
926ea4e54b9SDavid Nugent #endif
927ea4e54b9SDavid Nugent 
928ea022d16SRodney W. Grimes /*
929ea022d16SRodney W. Grimes  * Helper function for sgetpwnam().
930ea022d16SRodney W. Grimes  */
931ea022d16SRodney W. Grimes static char *
932e4bc453cSWarner Losh sgetsave(char *s)
933ea022d16SRodney W. Grimes {
934e3765043SYaroslav Tykhiy 	char *new = malloc(strlen(s) + 1);
935ea022d16SRodney W. Grimes 
936ea022d16SRodney W. Grimes 	if (new == NULL) {
93702c97492SYaroslav Tykhiy 		reply(421, "Ran out of memory.");
938ea022d16SRodney W. Grimes 		dologout(1);
939ea022d16SRodney W. Grimes 		/* NOTREACHED */
940ea022d16SRodney W. Grimes 	}
941ea022d16SRodney W. Grimes 	(void) strcpy(new, s);
942ea022d16SRodney W. Grimes 	return (new);
943ea022d16SRodney W. Grimes }
944ea022d16SRodney W. Grimes 
945ea022d16SRodney W. Grimes /*
946ea022d16SRodney W. Grimes  * Save the result of a getpwnam.  Used for USER command, since
947ea022d16SRodney W. Grimes  * the data returned must not be clobbered by any other command
948ea022d16SRodney W. Grimes  * (e.g., globbing).
949c29b9b47SYaroslav Tykhiy  * NB: The data returned by sgetpwnam() will remain valid until
950c29b9b47SYaroslav Tykhiy  * the next call to this function.  Its difference from getpwnam()
951c29b9b47SYaroslav Tykhiy  * is that sgetpwnam() is known to be called from ftpd code only.
952ea022d16SRodney W. Grimes  */
953ea022d16SRodney W. Grimes static struct passwd *
954e4bc453cSWarner Losh sgetpwnam(char *name)
955ea022d16SRodney W. Grimes {
956ea022d16SRodney W. Grimes 	static struct passwd save;
957ea022d16SRodney W. Grimes 	struct passwd *p;
958ea022d16SRodney W. Grimes 
959ea022d16SRodney W. Grimes 	if ((p = getpwnam(name)) == NULL)
960ea022d16SRodney W. Grimes 		return (p);
961ea022d16SRodney W. Grimes 	if (save.pw_name) {
962ea022d16SRodney W. Grimes 		free(save.pw_name);
963ea022d16SRodney W. Grimes 		free(save.pw_passwd);
96403d34cccSChristian Brueffer 		free(save.pw_class);
965ea022d16SRodney W. Grimes 		free(save.pw_gecos);
966ea022d16SRodney W. Grimes 		free(save.pw_dir);
967ea022d16SRodney W. Grimes 		free(save.pw_shell);
968ea022d16SRodney W. Grimes 	}
969ea022d16SRodney W. Grimes 	save = *p;
970ea022d16SRodney W. Grimes 	save.pw_name = sgetsave(p->pw_name);
971ea022d16SRodney W. Grimes 	save.pw_passwd = sgetsave(p->pw_passwd);
97203d34cccSChristian Brueffer 	save.pw_class = sgetsave(p->pw_class);
973ea022d16SRodney W. Grimes 	save.pw_gecos = sgetsave(p->pw_gecos);
974ea022d16SRodney W. Grimes 	save.pw_dir = sgetsave(p->pw_dir);
975ea022d16SRodney W. Grimes 	save.pw_shell = sgetsave(p->pw_shell);
976ea022d16SRodney W. Grimes 	return (&save);
977ea022d16SRodney W. Grimes }
978ea022d16SRodney W. Grimes 
979ea022d16SRodney W. Grimes static int login_attempts;	/* number of failed login attempts */
980ea022d16SRodney W. Grimes static int askpasswd;		/* had user command, ask for passwd */
98190906a46SSheldon Hearn static char curname[MAXLOGNAME];	/* current USER name */
982ea022d16SRodney W. Grimes 
983ea022d16SRodney W. Grimes /*
984ea022d16SRodney W. Grimes  * USER command.
985ea022d16SRodney W. Grimes  * Sets global passwd pointer pw if named account exists and is acceptable;
986ea022d16SRodney W. Grimes  * sets askpasswd if a PASS command is expected.  If logged in previously,
987ea022d16SRodney W. Grimes  * need to reset state.  If name is "ftp" or "anonymous", the name is not in
988ea022d16SRodney W. Grimes  * _PATH_FTPUSERS, and ftp account exists, set guest and pw, then just return.
989ea022d16SRodney W. Grimes  * If account doesn't exist, ask for passwd anyway.  Otherwise, check user
990ea022d16SRodney W. Grimes  * requesting login privileges.  Disallow anyone who does not have a standard
991ea022d16SRodney W. Grimes  * shell as returned by getusershell().  Disallow anyone mentioned in the file
992ea022d16SRodney W. Grimes  * _PATH_FTPUSERS to allow people such as root and uucp to be avoided.
993ea022d16SRodney W. Grimes  */
994ea022d16SRodney W. Grimes void
995e4bc453cSWarner Losh user(char *name)
996ea022d16SRodney W. Grimes {
997cefb6785SChristian S.J. Peron 	int ecode;
998ea022d16SRodney W. Grimes 	char *cp, *shell;
999ea022d16SRodney W. Grimes 
1000ea022d16SRodney W. Grimes 	if (logged_in) {
1001ea022d16SRodney W. Grimes 		if (guest) {
1002ea022d16SRodney W. Grimes 			reply(530, "Can't change user from guest login.");
1003ea022d16SRodney W. Grimes 			return;
1004a5a4544eSPaul Traina 		} else if (dochroot) {
1005a5a4544eSPaul Traina 			reply(530, "Can't change user from chroot user.");
1006a5a4544eSPaul Traina 			return;
1007ea022d16SRodney W. Grimes 		}
1008ea022d16SRodney W. Grimes 		end_login();
1009ea022d16SRodney W. Grimes 	}
1010ea022d16SRodney W. Grimes 
1011ea022d16SRodney W. Grimes 	guest = 0;
101263047c6fSDavid E. O'Brien #ifdef VIRTUAL_HOSTING
101363047c6fSDavid E. O'Brien 	pw = sgetpwnam(thishost->anonuser);
101463047c6fSDavid E. O'Brien #else
101563047c6fSDavid E. O'Brien 	pw = sgetpwnam("ftp");
101663047c6fSDavid E. O'Brien #endif
1017ea022d16SRodney W. Grimes 	if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) {
1018cefb6785SChristian S.J. Peron 		if (checkuser(_PATH_FTPUSERS, "ftp", 0, NULL, &ecode) ||
1019cefb6785SChristian S.J. Peron 		    (ecode != 0 && ecode != ENOENT))
1020cefb6785SChristian S.J. Peron 			reply(530, "User %s access denied.", name);
1021cefb6785SChristian S.J. Peron 		else if (checkuser(_PATH_FTPUSERS, "anonymous", 0, NULL, &ecode) ||
1022cefb6785SChristian S.J. Peron 		    (ecode != 0 && ecode != ENOENT))
1023ea022d16SRodney W. Grimes 			reply(530, "User %s access denied.", name);
102463047c6fSDavid E. O'Brien 		else if (pw != NULL) {
1025ea022d16SRodney W. Grimes 			guest = 1;
1026ea022d16SRodney W. Grimes 			askpasswd = 1;
1027ea022d16SRodney W. Grimes 			reply(331,
10282c60c54cSPaul Traina 			"Guest login ok, send your email address as password.");
1029ea022d16SRodney W. Grimes 		} else
1030ea022d16SRodney W. Grimes 			reply(530, "User %s unknown.", name);
1031ea022d16SRodney W. Grimes 		if (!askpasswd && logging)
1032ea022d16SRodney W. Grimes 			syslog(LOG_NOTICE,
1033ea022d16SRodney W. Grimes 			    "ANONYMOUS FTP LOGIN REFUSED FROM %s", remotehost);
1034ea022d16SRodney W. Grimes 		return;
1035ea022d16SRodney W. Grimes 	}
10365a392aecSTorsten Blum 	if (anon_only != 0) {
10375a392aecSTorsten Blum 		reply(530, "Sorry, only anonymous ftp allowed.");
10385a392aecSTorsten Blum 		return;
10395a392aecSTorsten Blum 	}
10405a392aecSTorsten Blum 
10419aca17cbSMark Murray 	if ((pw = sgetpwnam(name))) {
1042ea022d16SRodney W. Grimes 		if ((shell = pw->pw_shell) == NULL || *shell == 0)
1043ea022d16SRodney W. Grimes 			shell = _PATH_BSHELL;
1044c433c9daSPhilippe Charnier 		setusershell();
1045ea022d16SRodney W. Grimes 		while ((cp = getusershell()) != NULL)
1046ea022d16SRodney W. Grimes 			if (strcmp(cp, shell) == 0)
1047ea022d16SRodney W. Grimes 				break;
1048ea022d16SRodney W. Grimes 		endusershell();
1049ea022d16SRodney W. Grimes 
1050cefb6785SChristian S.J. Peron 		if (cp == NULL ||
1051cefb6785SChristian S.J. Peron 		    (checkuser(_PATH_FTPUSERS, name, 1, NULL, &ecode) ||
1052cefb6785SChristian S.J. Peron 		    (ecode != 0 && ecode != ENOENT))) {
1053ea022d16SRodney W. Grimes 			reply(530, "User %s access denied.", name);
1054ea022d16SRodney W. Grimes 			if (logging)
1055ea022d16SRodney W. Grimes 				syslog(LOG_NOTICE,
1056ea022d16SRodney W. Grimes 				    "FTP LOGIN REFUSED FROM %s, %s",
1057ea022d16SRodney W. Grimes 				    remotehost, name);
10587e295315SYaroslav Tykhiy 			pw = NULL;
1059ea022d16SRodney W. Grimes 			return;
1060ea022d16SRodney W. Grimes 		}
1061ea022d16SRodney W. Grimes 	}
1062ea022d16SRodney W. Grimes 	if (logging)
1063ea022d16SRodney W. Grimes 		strncpy(curname, name, sizeof(curname)-1);
106447499ecdSAndrey A. Chernov 
106547499ecdSAndrey A. Chernov 	pwok = 0;
1066fa1746c9SMark Murray #ifdef USE_PAM
1067fa1746c9SMark Murray 	/* XXX Kluge! The conversation mechanism needs to be fixed. */
1068726040deSGuido van Rooij #endif
106947499ecdSAndrey A. Chernov 	if (opiechallenge(&opiedata, name, opieprompt) == 0) {
107047499ecdSAndrey A. Chernov 		pwok = (pw != NULL) &&
107147499ecdSAndrey A. Chernov 		       opieaccessfile(remotehost) &&
107247499ecdSAndrey A. Chernov 		       opiealways(pw->pw_dir);
107347499ecdSAndrey A. Chernov 		reply(331, "Response to %s %s for %s.",
107447499ecdSAndrey A. Chernov 		      opieprompt, pwok ? "requested" : "required", name);
107547499ecdSAndrey A. Chernov 	} else {
107647499ecdSAndrey A. Chernov 		pwok = 1;
107747499ecdSAndrey A. Chernov 		reply(331, "Password required for %s.", name);
107847499ecdSAndrey A. Chernov 	}
1079ea022d16SRodney W. Grimes 	askpasswd = 1;
1080ea022d16SRodney W. Grimes 	/*
1081ea022d16SRodney W. Grimes 	 * Delay before reading passwd after first failed
1082ea022d16SRodney W. Grimes 	 * attempt to slow down passwd-guessing programs.
1083ea022d16SRodney W. Grimes 	 */
1084ea022d16SRodney W. Grimes 	if (login_attempts)
1085e3765043SYaroslav Tykhiy 		sleep(login_attempts);
1086ea022d16SRodney W. Grimes }
1087ea022d16SRodney W. Grimes 
1088ea022d16SRodney W. Grimes /*
10898657b576SYaroslav Tykhiy  * Check if a user is in the file "fname",
10908657b576SYaroslav Tykhiy  * return a pointer to a malloc'd string with the rest
10918657b576SYaroslav Tykhiy  * of the matching line in "residue" if not NULL.
1092ea022d16SRodney W. Grimes  */
1093ea022d16SRodney W. Grimes static int
1094cefb6785SChristian S.J. Peron checkuser(char *fname, char *name, int pwset, char **residue, int *ecode)
1095ea022d16SRodney W. Grimes {
1096ea022d16SRodney W. Grimes 	FILE *fd;
1097ea022d16SRodney W. Grimes 	int found = 0;
1098737d08f3SYaroslav Tykhiy 	size_t len;
1099737d08f3SYaroslav Tykhiy 	char *line, *mp, *p;
1100ea022d16SRodney W. Grimes 
1101cefb6785SChristian S.J. Peron 	if (ecode != NULL)
1102cefb6785SChristian S.J. Peron 		*ecode = 0;
1103a5a4544eSPaul Traina 	if ((fd = fopen(fname, "r")) != NULL) {
1104737d08f3SYaroslav Tykhiy 		while (!found && (line = fgetln(fd, &len)) != NULL) {
1105737d08f3SYaroslav Tykhiy 			/* skip comments */
1106ea022d16SRodney W. Grimes 			if (line[0] == '#')
1107ea022d16SRodney W. Grimes 				continue;
1108737d08f3SYaroslav Tykhiy 			if (line[len - 1] == '\n') {
1109737d08f3SYaroslav Tykhiy 				line[len - 1] = '\0';
1110737d08f3SYaroslav Tykhiy 				mp = NULL;
1111737d08f3SYaroslav Tykhiy 			} else {
1112737d08f3SYaroslav Tykhiy 				if ((mp = malloc(len + 1)) == NULL)
1113737d08f3SYaroslav Tykhiy 					fatalerror("Ran out of memory.");
1114737d08f3SYaroslav Tykhiy 				memcpy(mp, line, len);
1115737d08f3SYaroslav Tykhiy 				mp[len] = '\0';
1116737d08f3SYaroslav Tykhiy 				line = mp;
1117737d08f3SYaroslav Tykhiy 			}
1118737d08f3SYaroslav Tykhiy 			/* avoid possible leading and trailing whitespace */
1119737d08f3SYaroslav Tykhiy 			p = strtok(line, " \t");
1120737d08f3SYaroslav Tykhiy 			/* skip empty lines */
1121737d08f3SYaroslav Tykhiy 			if (p == NULL)
1122737d08f3SYaroslav Tykhiy 				goto nextline;
112331fea7b8SDavid Nugent 			/*
112431fea7b8SDavid Nugent 			 * if first chr is '@', check group membership
112531fea7b8SDavid Nugent 			 */
1126737d08f3SYaroslav Tykhiy 			if (p[0] == '@') {
112731fea7b8SDavid Nugent 				int i = 0;
112831fea7b8SDavid Nugent 				struct group *grp;
112931fea7b8SDavid Nugent 
11308657b576SYaroslav Tykhiy 				if (p[1] == '\0') /* single @ matches anyone */
11318657b576SYaroslav Tykhiy 					found = 1;
11328657b576SYaroslav Tykhiy 				else {
1133737d08f3SYaroslav Tykhiy 					if ((grp = getgrnam(p+1)) == NULL)
1134737d08f3SYaroslav Tykhiy 						goto nextline;
11357edcb936SSteve Price 					/*
11367edcb936SSteve Price 					 * Check user's default group
11377edcb936SSteve Price 					 */
11387edcb936SSteve Price 					if (pwset && grp->gr_gid == pw->pw_gid)
11397edcb936SSteve Price 						found = 1;
11407edcb936SSteve Price 					/*
11417edcb936SSteve Price 					 * Check supplementary groups
11427edcb936SSteve Price 					 */
114331fea7b8SDavid Nugent 					while (!found && grp->gr_mem[i])
114431fea7b8SDavid Nugent 						found = strcmp(name,
114531fea7b8SDavid Nugent 							grp->gr_mem[i++])
114631fea7b8SDavid Nugent 							== 0;
1147ea022d16SRodney W. Grimes 				}
11488657b576SYaroslav Tykhiy 			}
114931fea7b8SDavid Nugent 			/*
115031fea7b8SDavid Nugent 			 * Otherwise, just check for username match
115131fea7b8SDavid Nugent 			 */
115231fea7b8SDavid Nugent 			else
1153737d08f3SYaroslav Tykhiy 				found = strcmp(p, name) == 0;
11548657b576SYaroslav Tykhiy 			/*
11558657b576SYaroslav Tykhiy 			 * Save the rest of line to "residue" if matched
11568657b576SYaroslav Tykhiy 			 */
11578657b576SYaroslav Tykhiy 			if (found && residue) {
11580ba71e24SYaroslav Tykhiy 				if ((p = strtok(NULL, "")) != NULL)
11590ba71e24SYaroslav Tykhiy 					p += strspn(p, " \t");
11600ba71e24SYaroslav Tykhiy 				if (p && *p) {
11618657b576SYaroslav Tykhiy 				 	if ((*residue = strdup(p)) == NULL)
11628657b576SYaroslav Tykhiy 						fatalerror("Ran out of memory.");
11638657b576SYaroslav Tykhiy 				} else
11648657b576SYaroslav Tykhiy 					*residue = NULL;
11658657b576SYaroslav Tykhiy 			}
1166737d08f3SYaroslav Tykhiy nextline:
1167737d08f3SYaroslav Tykhiy 			if (mp)
1168737d08f3SYaroslav Tykhiy 				free(mp);
1169ea022d16SRodney W. Grimes 		}
1170ea022d16SRodney W. Grimes 		(void) fclose(fd);
1171cefb6785SChristian S.J. Peron 	} else if (ecode != NULL)
1172cefb6785SChristian S.J. Peron 		*ecode = errno;
1173ea022d16SRodney W. Grimes 	return (found);
1174ea022d16SRodney W. Grimes }
1175ea022d16SRodney W. Grimes 
1176ea022d16SRodney W. Grimes /*
1177ea022d16SRodney W. Grimes  * Terminate login as previous user, if any, resetting state;
1178ea022d16SRodney W. Grimes  * used when USER command is given or login fails.
1179ea022d16SRodney W. Grimes  */
1180ea022d16SRodney W. Grimes static void
1181e4bc453cSWarner Losh end_login(void)
1182ea022d16SRodney W. Grimes {
11835bc9d93dSMark Murray #ifdef USE_PAM
11845bc9d93dSMark Murray 	int e;
11855bc9d93dSMark Murray #endif
1186ea022d16SRodney W. Grimes 
118752e7ee74SYaroslav Tykhiy 	(void) seteuid(0);
11889f37b1a2SEd Schouten 	if (logged_in && dowtmp)
11899f37b1a2SEd Schouten 		ftpd_logwtmp(wtmpid, NULL, NULL);
1190ea022d16SRodney W. Grimes 	pw = NULL;
1191b071c689SDavid Nugent #ifdef	LOGIN_CAP
1192e81b1c71SEdward Tomasz Napierala 	setusercontext(NULL, getpwuid(0), 0, LOGIN_SETALL & ~(LOGIN_SETLOGIN |
1193e81b1c71SEdward Tomasz Napierala 		       LOGIN_SETUSER | LOGIN_SETGROUP | LOGIN_SETPATH |
1194e81b1c71SEdward Tomasz Napierala 		       LOGIN_SETENV));
1195b071c689SDavid Nugent #endif
11965bc9d93dSMark Murray #ifdef USE_PAM
1197de45162dSYaroslav Tykhiy 	if (pamh) {
11985bc9d93dSMark Murray 		if ((e = pam_setcred(pamh, PAM_DELETE_CRED)) != PAM_SUCCESS)
11995bc9d93dSMark Murray 			syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e));
12005bc9d93dSMark Murray 		if ((e = pam_close_session(pamh,0)) != PAM_SUCCESS)
12015bc9d93dSMark Murray 			syslog(LOG_ERR, "pam_close_session: %s", pam_strerror(pamh, e));
12025bc9d93dSMark Murray 		if ((e = pam_end(pamh, e)) != PAM_SUCCESS)
12035bc9d93dSMark Murray 			syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
12045bc9d93dSMark Murray 		pamh = NULL;
1205de45162dSYaroslav Tykhiy 	}
12065bc9d93dSMark Murray #endif
1207ea022d16SRodney W. Grimes 	logged_in = 0;
1208ea022d16SRodney W. Grimes 	guest = 0;
1209a5a4544eSPaul Traina 	dochroot = 0;
1210ea022d16SRodney W. Grimes }
1211ea022d16SRodney W. Grimes 
12125bc9d93dSMark Murray #ifdef USE_PAM
12136c9134c0SMark Murray 
12146c9134c0SMark Murray /*
12156c9134c0SMark Murray  * the following code is stolen from imap-uw PAM authentication module and
12166c9134c0SMark Murray  * login.c
12176c9134c0SMark Murray  */
12186c9134c0SMark Murray #define COPY_STRING(s) (s ? strdup(s) : NULL)
12196c9134c0SMark Murray 
12206c9134c0SMark Murray struct cred_t {
12216c9134c0SMark Murray 	const char *uname;		/* user name */
12226c9134c0SMark Murray 	const char *pass;		/* password */
12236c9134c0SMark Murray };
12246c9134c0SMark Murray typedef struct cred_t cred_t;
12256c9134c0SMark Murray 
12266c9134c0SMark Murray static int
12276c9134c0SMark Murray auth_conv(int num_msg, const struct pam_message **msg,
12286c9134c0SMark Murray 	  struct pam_response **resp, void *appdata)
12296c9134c0SMark Murray {
12306c9134c0SMark Murray 	int i;
12316c9134c0SMark Murray 	cred_t *cred = (cred_t *) appdata;
123260769b19SDag-Erling Smørgrav 	struct pam_response *reply;
123360769b19SDag-Erling Smørgrav 
123460769b19SDag-Erling Smørgrav 	reply = calloc(num_msg, sizeof *reply);
123560769b19SDag-Erling Smørgrav 	if (reply == NULL)
123660769b19SDag-Erling Smørgrav 		return PAM_BUF_ERR;
12376c9134c0SMark Murray 
12386c9134c0SMark Murray 	for (i = 0; i < num_msg; i++) {
12396c9134c0SMark Murray 		switch (msg[i]->msg_style) {
12406c9134c0SMark Murray 		case PAM_PROMPT_ECHO_ON:	/* assume want user name */
12416c9134c0SMark Murray 			reply[i].resp_retcode = PAM_SUCCESS;
12426c9134c0SMark Murray 			reply[i].resp = COPY_STRING(cred->uname);
12436c9134c0SMark Murray 			/* PAM frees resp. */
12446c9134c0SMark Murray 			break;
12456c9134c0SMark Murray 		case PAM_PROMPT_ECHO_OFF:	/* assume want password */
12466c9134c0SMark Murray 			reply[i].resp_retcode = PAM_SUCCESS;
12476c9134c0SMark Murray 			reply[i].resp = COPY_STRING(cred->pass);
12486c9134c0SMark Murray 			/* PAM frees resp. */
12496c9134c0SMark Murray 			break;
12506c9134c0SMark Murray 		case PAM_TEXT_INFO:
12516c9134c0SMark Murray 		case PAM_ERROR_MSG:
12526c9134c0SMark Murray 			reply[i].resp_retcode = PAM_SUCCESS;
12536c9134c0SMark Murray 			reply[i].resp = NULL;
12546c9134c0SMark Murray 			break;
12556c9134c0SMark Murray 		default:			/* unknown message style */
12566c9134c0SMark Murray 			free(reply);
12576c9134c0SMark Murray 			return PAM_CONV_ERR;
12586c9134c0SMark Murray 		}
12596c9134c0SMark Murray 	}
12606c9134c0SMark Murray 
12616c9134c0SMark Murray 	*resp = reply;
12626c9134c0SMark Murray 	return PAM_SUCCESS;
12636c9134c0SMark Murray }
12646c9134c0SMark Murray 
12656c9134c0SMark Murray /*
12666c9134c0SMark Murray  * Attempt to authenticate the user using PAM.  Returns 0 if the user is
12676c9134c0SMark Murray  * authenticated, or 1 if not authenticated.  If some sort of PAM system
12686c9134c0SMark Murray  * error occurs (e.g., the "/etc/pam.conf" file is missing) then this
12696c9134c0SMark Murray  * function returns -1.  This can be used as an indication that we should
12706c9134c0SMark Murray  * fall back to a different authentication mechanism.
12716c9134c0SMark Murray  */
12726c9134c0SMark Murray static int
12736c9134c0SMark Murray auth_pam(struct passwd **ppw, const char *pass)
12746c9134c0SMark Murray {
12756c9134c0SMark Murray 	const char *tmpl_user;
12766c9134c0SMark Murray 	const void *item;
12776c9134c0SMark Murray 	int rval;
12786c9134c0SMark Murray 	int e;
12796c9134c0SMark Murray 	cred_t auth_cred = { (*ppw)->pw_name, pass };
12806c9134c0SMark Murray 	struct pam_conv conv = { &auth_conv, &auth_cred };
12816c9134c0SMark Murray 
12826c9134c0SMark Murray 	e = pam_start("ftpd", (*ppw)->pw_name, &conv, &pamh);
12836c9134c0SMark Murray 	if (e != PAM_SUCCESS) {
1284545ea864SYaroslav Tykhiy 		/*
1285545ea864SYaroslav Tykhiy 		 * In OpenPAM, it's OK to pass NULL to pam_strerror()
1286545ea864SYaroslav Tykhiy 		 * if context creation has failed in the first place.
1287545ea864SYaroslav Tykhiy 		 */
1288545ea864SYaroslav Tykhiy 		syslog(LOG_ERR, "pam_start: %s", pam_strerror(NULL, e));
12896c9134c0SMark Murray 		return -1;
12906c9134c0SMark Murray 	}
12916c9134c0SMark Murray 
1292ea413ab7SGuido van Rooij 	e = pam_set_item(pamh, PAM_RHOST, remotehost);
1293ea413ab7SGuido van Rooij 	if (e != PAM_SUCCESS) {
1294ea413ab7SGuido van Rooij 		syslog(LOG_ERR, "pam_set_item(PAM_RHOST): %s",
1295ea413ab7SGuido van Rooij 			pam_strerror(pamh, e));
1296de45162dSYaroslav Tykhiy 		if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
1297de45162dSYaroslav Tykhiy 			syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1298de45162dSYaroslav Tykhiy 		}
1299de45162dSYaroslav Tykhiy 		pamh = NULL;
1300ea413ab7SGuido van Rooij 		return -1;
1301ea413ab7SGuido van Rooij 	}
1302ea413ab7SGuido van Rooij 
13036c9134c0SMark Murray 	e = pam_authenticate(pamh, 0);
13046c9134c0SMark Murray 	switch (e) {
13056c9134c0SMark Murray 	case PAM_SUCCESS:
13066c9134c0SMark Murray 		/*
13076c9134c0SMark Murray 		 * With PAM we support the concept of a "template"
13086c9134c0SMark Murray 		 * user.  The user enters a login name which is
13096c9134c0SMark Murray 		 * authenticated by PAM, usually via a remote service
13106c9134c0SMark Murray 		 * such as RADIUS or TACACS+.  If authentication
13116c9134c0SMark Murray 		 * succeeds, a different but related "template" name
13126c9134c0SMark Murray 		 * is used for setting the credentials, shell, and
13136c9134c0SMark Murray 		 * home directory.  The name the user enters need only
13146c9134c0SMark Murray 		 * exist on the remote authentication server, but the
13156c9134c0SMark Murray 		 * template name must be present in the local password
13166c9134c0SMark Murray 		 * database.
13176c9134c0SMark Murray 		 *
13186c9134c0SMark Murray 		 * This is supported by two various mechanisms in the
13196c9134c0SMark Murray 		 * individual modules.  However, from the application's
13206c9134c0SMark Murray 		 * point of view, the template user is always passed
13216c9134c0SMark Murray 		 * back as a changed value of the PAM_USER item.
13226c9134c0SMark Murray 		 */
13236c9134c0SMark Murray 		if ((e = pam_get_item(pamh, PAM_USER, &item)) ==
13246c9134c0SMark Murray 		    PAM_SUCCESS) {
13256c9134c0SMark Murray 			tmpl_user = (const char *) item;
13266c9134c0SMark Murray 			if (strcmp((*ppw)->pw_name, tmpl_user) != 0)
13276c9134c0SMark Murray 				*ppw = getpwnam(tmpl_user);
13286c9134c0SMark Murray 		} else
13296c9134c0SMark Murray 			syslog(LOG_ERR, "Couldn't get PAM_USER: %s",
13306c9134c0SMark Murray 			    pam_strerror(pamh, e));
13316c9134c0SMark Murray 		rval = 0;
13326c9134c0SMark Murray 		break;
13336c9134c0SMark Murray 
13346c9134c0SMark Murray 	case PAM_AUTH_ERR:
13356c9134c0SMark Murray 	case PAM_USER_UNKNOWN:
13366c9134c0SMark Murray 	case PAM_MAXTRIES:
13376c9134c0SMark Murray 		rval = 1;
13386c9134c0SMark Murray 		break;
13396c9134c0SMark Murray 
13406c9134c0SMark Murray 	default:
13415bc9d93dSMark Murray 		syslog(LOG_ERR, "pam_authenticate: %s", pam_strerror(pamh, e));
13426c9134c0SMark Murray 		rval = -1;
13436c9134c0SMark Murray 		break;
13446c9134c0SMark Murray 	}
13456c9134c0SMark Murray 
13465bc9d93dSMark Murray 	if (rval == 0) {
13475bc9d93dSMark Murray 		e = pam_acct_mgmt(pamh, 0);
13485bc9d93dSMark Murray 		if (e != PAM_SUCCESS) {
13494cbc4ad6SYaroslav Tykhiy 			syslog(LOG_ERR, "pam_acct_mgmt: %s",
13504cbc4ad6SYaroslav Tykhiy 						pam_strerror(pamh, e));
13515bc9d93dSMark Murray 			rval = 1;
13525bc9d93dSMark Murray 		}
13535bc9d93dSMark Murray 	}
13545bc9d93dSMark Murray 
13555bc9d93dSMark Murray 	if (rval != 0) {
13566c9134c0SMark Murray 		if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
13576c9134c0SMark Murray 			syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
13585bc9d93dSMark Murray 		}
13595bc9d93dSMark Murray 		pamh = NULL;
13606c9134c0SMark Murray 	}
13616c9134c0SMark Murray 	return rval;
13626c9134c0SMark Murray }
13636c9134c0SMark Murray 
13645bc9d93dSMark Murray #endif /* USE_PAM */
13656c9134c0SMark Murray 
1366ea022d16SRodney W. Grimes void
1367e4bc453cSWarner Losh pass(char *passwd)
1368ea022d16SRodney W. Grimes {
1369cefb6785SChristian S.J. Peron 	int rval, ecode;
1370ea022d16SRodney W. Grimes 	FILE *fd;
1371b071c689SDavid Nugent #ifdef	LOGIN_CAP
1372b071c689SDavid Nugent 	login_cap_t *lc = NULL;
1373b071c689SDavid Nugent #endif
13745bc9d93dSMark Murray #ifdef USE_PAM
13755bc9d93dSMark Murray 	int e;
13765bc9d93dSMark Murray #endif
1377341e476eSYaroslav Tykhiy 	char *residue = NULL;
137847499ecdSAndrey A. Chernov 	char *xpasswd;
1379ea022d16SRodney W. Grimes 
1380ea022d16SRodney W. Grimes 	if (logged_in || askpasswd == 0) {
1381ea022d16SRodney W. Grimes 		reply(503, "Login with USER first.");
1382ea022d16SRodney W. Grimes 		return;
1383ea022d16SRodney W. Grimes 	}
1384ea022d16SRodney W. Grimes 	askpasswd = 0;
1385ea022d16SRodney W. Grimes 	if (!guest) {		/* "ftp" is only account allowed no password */
1386a5a4544eSPaul Traina 		if (pw == NULL) {
1387a5a4544eSPaul Traina 			rval = 1;	/* failure below */
1388a5a4544eSPaul Traina 			goto skip;
1389a5a4544eSPaul Traina 		}
13905bc9d93dSMark Murray #ifdef USE_PAM
13916c9134c0SMark Murray 		rval = auth_pam(&pw, passwd);
1392f650a124SAndrey A. Chernov 		if (rval >= 0) {
1393f650a124SAndrey A. Chernov 			opieunlock();
1394a5a4544eSPaul Traina 			goto skip;
1395f650a124SAndrey A. Chernov 		}
1396f650a124SAndrey A. Chernov #endif
139747499ecdSAndrey A. Chernov 		if (opieverify(&opiedata, passwd) == 0)
139847499ecdSAndrey A. Chernov 			xpasswd = pw->pw_passwd;
1399f650a124SAndrey A. Chernov 		else if (pwok) {
140047499ecdSAndrey A. Chernov 			xpasswd = crypt(passwd, pw->pw_passwd);
1401f650a124SAndrey A. Chernov 			if (passwd[0] == '\0' && pw->pw_passwd[0] != '\0')
1402f650a124SAndrey A. Chernov 				xpasswd = ":";
1403f650a124SAndrey A. Chernov 		} else {
140447499ecdSAndrey A. Chernov 			rval = 1;
140547499ecdSAndrey A. Chernov 			goto skip;
140647499ecdSAndrey A. Chernov 		}
140747499ecdSAndrey A. Chernov 		rval = strcmp(pw->pw_passwd, xpasswd);
1408f650a124SAndrey A. Chernov 		if (pw->pw_expire && time(NULL) >= pw->pw_expire)
1409a5a4544eSPaul Traina 			rval = 1;	/* failure */
1410a5a4544eSPaul Traina skip:
1411a5a4544eSPaul Traina 		/*
1412a5a4544eSPaul Traina 		 * If rval == 1, the user failed the authentication check
14136c9134c0SMark Murray 		 * above.  If rval == 0, either PAM or local authentication
1414a5a4544eSPaul Traina 		 * succeeded.
1415a5a4544eSPaul Traina 		 */
1416a5a4544eSPaul Traina 		if (rval) {
1417ea022d16SRodney W. Grimes 			reply(530, "Login incorrect.");
1418b8939f6fSYaroslav Tykhiy 			if (logging) {
1419ea022d16SRodney W. Grimes 				syslog(LOG_NOTICE,
1420b8939f6fSYaroslav Tykhiy 				    "FTP LOGIN FAILED FROM %s",
1421b8939f6fSYaroslav Tykhiy 				    remotehost);
1422b8939f6fSYaroslav Tykhiy 				syslog(LOG_AUTHPRIV | LOG_NOTICE,
1423ea022d16SRodney W. Grimes 				    "FTP LOGIN FAILED FROM %s, %s",
1424ea022d16SRodney W. Grimes 				    remotehost, curname);
1425b8939f6fSYaroslav Tykhiy 			}
1426ea022d16SRodney W. Grimes 			pw = NULL;
1427ea022d16SRodney W. Grimes 			if (login_attempts++ >= 5) {
1428ea022d16SRodney W. Grimes 				syslog(LOG_NOTICE,
1429ea022d16SRodney W. Grimes 				    "repeated login failures from %s",
1430ea022d16SRodney W. Grimes 				    remotehost);
1431ea022d16SRodney W. Grimes 				exit(0);
1432ea022d16SRodney W. Grimes 			}
1433ea022d16SRodney W. Grimes 			return;
1434ea022d16SRodney W. Grimes 		}
1435ea022d16SRodney W. Grimes 	}
1436ea022d16SRodney W. Grimes 	login_attempts = 0;		/* this time successful */
1437c4536e21SYaroslav Tykhiy 	if (setegid(pw->pw_gid) < 0) {
1438ea022d16SRodney W. Grimes 		reply(550, "Can't set gid.");
1439ea022d16SRodney W. Grimes 		return;
1440ea022d16SRodney W. Grimes 	}
1441b071c689SDavid Nugent 	/* May be overridden by login.conf */
1442b071c689SDavid Nugent 	(void) umask(defumask);
1443b071c689SDavid Nugent #ifdef	LOGIN_CAP
14445d0bfe39SDavid Nugent 	if ((lc = login_getpwclass(pw)) != NULL) {
144504683b2cSYaroslav Tykhiy 		char	remote_ip[NI_MAXHOST];
1446b071c689SDavid Nugent 
144704683b2cSYaroslav Tykhiy 		if (getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
14484dd8b5abSYoshinobu Inoue 			remote_ip, sizeof(remote_ip) - 1, NULL, 0,
144904683b2cSYaroslav Tykhiy 			NI_NUMERICHOST))
145004683b2cSYaroslav Tykhiy 				*remote_ip = 0;
1451b071c689SDavid Nugent 		remote_ip[sizeof(remote_ip) - 1] = 0;
1452b071c689SDavid Nugent 		if (!auth_hostok(lc, remotehost, remote_ip)) {
1453b071c689SDavid Nugent 			syslog(LOG_INFO|LOG_AUTH,
1454b071c689SDavid Nugent 			    "FTP LOGIN FAILED (HOST) as %s: permission denied.",
1455b071c689SDavid Nugent 			    pw->pw_name);
14564a3e5acdSYaroslav Tykhiy 			reply(530, "Permission denied.");
1457b071c689SDavid Nugent 			pw = NULL;
1458b071c689SDavid Nugent 			return;
1459b071c689SDavid Nugent 		}
1460b071c689SDavid Nugent 		if (!auth_timeok(lc, time(NULL))) {
14614a3e5acdSYaroslav Tykhiy 			reply(530, "Login not available right now.");
1462b071c689SDavid Nugent 			pw = NULL;
1463b071c689SDavid Nugent 			return;
1464b071c689SDavid Nugent 		}
1465b071c689SDavid Nugent 	}
1466e81b1c71SEdward Tomasz Napierala 	setusercontext(lc, pw, 0, LOGIN_SETALL &
1467e81b1c71SEdward Tomasz Napierala 		       ~(LOGIN_SETUSER | LOGIN_SETPATH | LOGIN_SETENV));
1468b071c689SDavid Nugent #else
1469e6fa0d43SDag-Erling Smørgrav 	setlogin(pw->pw_name);
1470ea022d16SRodney W. Grimes 	(void) initgroups(pw->pw_name, pw->pw_gid);
1471b071c689SDavid Nugent #endif
1472ea022d16SRodney W. Grimes 
14735bc9d93dSMark Murray #ifdef USE_PAM
14745bc9d93dSMark Murray 	if (pamh) {
14755bc9d93dSMark Murray 		if ((e = pam_open_session(pamh, 0)) != PAM_SUCCESS) {
14765bc9d93dSMark Murray 			syslog(LOG_ERR, "pam_open_session: %s", pam_strerror(pamh, e));
14775bc9d93dSMark Murray 		} else if ((e = pam_setcred(pamh, PAM_ESTABLISH_CRED)) != PAM_SUCCESS) {
14785bc9d93dSMark Murray 			syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e));
14795bc9d93dSMark Murray 		}
14805bc9d93dSMark Murray 	}
14815bc9d93dSMark Murray #endif
14825bc9d93dSMark Murray 
148380643af0SEd Schouten 	dochroot =
1484cefb6785SChristian S.J. Peron 		checkuser(_PATH_FTPCHROOT, pw->pw_name, 1, &residue, &ecode)
148580643af0SEd Schouten #ifdef	LOGIN_CAP	/* Allow login.conf configuration as well */
148680643af0SEd Schouten 		|| login_getcapbool(lc, "ftp-chroot", 0)
148780643af0SEd Schouten #endif
148880643af0SEd Schouten 	;
1489cefb6785SChristian S.J. Peron 	/*
1490cefb6785SChristian S.J. Peron 	 * It is possible that checkuser() failed to open the chroot file.
1491cefb6785SChristian S.J. Peron 	 * If this is the case, report that logins are un-available, since we
1492cefb6785SChristian S.J. Peron 	 * have no way of checking whether or not the user should be chrooted.
1493cefb6785SChristian S.J. Peron 	 * We ignore ENOENT since it is not required that this file be present.
1494cefb6785SChristian S.J. Peron 	 */
1495cefb6785SChristian S.J. Peron 	if (ecode != 0 && ecode != ENOENT) {
1496cefb6785SChristian S.J. Peron 		reply(530, "Login not available right now.");
1497cefb6785SChristian S.J. Peron 		return;
1498cefb6785SChristian S.J. Peron 	}
149980643af0SEd Schouten 	chrootdir = NULL;
150080643af0SEd Schouten 
15019f37b1a2SEd Schouten 	/* Disable wtmp logging when chrooting. */
15029f37b1a2SEd Schouten 	if (dochroot || guest)
15039f37b1a2SEd Schouten 		dowtmp = 0;
15049f37b1a2SEd Schouten 	if (dowtmp)
150580643af0SEd Schouten 		ftpd_logwtmp(wtmpid, pw->pw_name,
15065d7e0128SYaroslav Tykhiy 		    (struct sockaddr *)&his_addr);
1507ea022d16SRodney W. Grimes 	logged_in = 1;
1508ea022d16SRodney W. Grimes 
1509a5a4544eSPaul Traina 	if (guest && stats && statfd < 0)
1510ea4e54b9SDavid Nugent #ifdef VIRTUAL_HOSTING
151163047c6fSDavid E. O'Brien 		statfd = open(thishost->statfile, O_WRONLY|O_APPEND);
1512ea4e54b9SDavid Nugent #else
151363047c6fSDavid E. O'Brien 		statfd = open(_PATH_FTPDSTATFILE, O_WRONLY|O_APPEND);
1514ea4e54b9SDavid Nugent #endif
151563047c6fSDavid E. O'Brien 		if (statfd < 0)
15163eb568f2SGuido van Rooij 			stats = 0;
15173eb568f2SGuido van Rooij 
1518ea022d16SRodney W. Grimes 	/*
1519ce9287fcSYaroslav Tykhiy 	 * For a chrooted local user,
1520ce9287fcSYaroslav Tykhiy 	 * a) see whether ftpchroot(5) specifies a chroot directory,
1521ce9287fcSYaroslav Tykhiy 	 * b) extract the directory pathname from the line,
1522ce9287fcSYaroslav Tykhiy 	 * c) expand it to the absolute pathname if necessary.
1523ea022d16SRodney W. Grimes 	 */
1524ce9287fcSYaroslav Tykhiy 	if (dochroot && residue &&
152539bce482SYaroslav Tykhiy 	    (chrootdir = strtok(residue, " \t")) != NULL) {
152639bce482SYaroslav Tykhiy 		if (chrootdir[0] != '/')
1527341e476eSYaroslav Tykhiy 			asprintf(&chrootdir, "%s/%s", pw->pw_dir, chrootdir);
152839bce482SYaroslav Tykhiy 		else
1529215a9f9dSYaroslav Tykhiy 			chrootdir = strdup(chrootdir); /* make it permanent */
1530341e476eSYaroslav Tykhiy 		if (chrootdir == NULL)
15318657b576SYaroslav Tykhiy 			fatalerror("Ran out of memory.");
15328657b576SYaroslav Tykhiy 	}
1533ce9287fcSYaroslav Tykhiy 	if (guest || dochroot) {
1534ce9287fcSYaroslav Tykhiy 		/*
1535ce9287fcSYaroslav Tykhiy 		 * If no chroot directory set yet, use the login directory.
1536ce9287fcSYaroslav Tykhiy 		 * Copy it so it can be modified while pw->pw_dir stays intact.
1537ce9287fcSYaroslav Tykhiy 		 */
1538ce9287fcSYaroslav Tykhiy 		if (chrootdir == NULL &&
1539ce9287fcSYaroslav Tykhiy 		    (chrootdir = strdup(pw->pw_dir)) == NULL)
1540ce9287fcSYaroslav Tykhiy 			fatalerror("Ran out of memory.");
1541ce9287fcSYaroslav Tykhiy 		/*
1542ce9287fcSYaroslav Tykhiy 		 * Check for the "/chroot/./home" syntax,
1543ce9287fcSYaroslav Tykhiy 		 * separate the chroot and home directory pathnames.
1544ce9287fcSYaroslav Tykhiy 		 */
1545ce9287fcSYaroslav Tykhiy 		if ((homedir = strstr(chrootdir, "/./")) != NULL) {
1546ce9287fcSYaroslav Tykhiy 			*(homedir++) = '\0';	/* wipe '/' */
1547ce9287fcSYaroslav Tykhiy 			homedir++;		/* skip '.' */
1548ce9287fcSYaroslav Tykhiy 		} else {
1549ce9287fcSYaroslav Tykhiy 			/*
1550ce9287fcSYaroslav Tykhiy 			 * We MUST do a chdir() after the chroot. Otherwise
1551ce9287fcSYaroslav Tykhiy 			 * the old current directory will be accessible as "."
1552ce9287fcSYaroslav Tykhiy 			 * outside the new root!
1553ce9287fcSYaroslav Tykhiy 			 */
1554ce9287fcSYaroslav Tykhiy 			homedir = "/";
1555ce9287fcSYaroslav Tykhiy 		}
1556ce9287fcSYaroslav Tykhiy 		/*
1557ce9287fcSYaroslav Tykhiy 		 * Finally, do chroot()
1558ce9287fcSYaroslav Tykhiy 		 */
1559ce9287fcSYaroslav Tykhiy 		if (chroot(chrootdir) < 0) {
1560a5a4544eSPaul Traina 			reply(550, "Can't change root.");
1561a5a4544eSPaul Traina 			goto bad;
1562a5a4544eSPaul Traina 		}
15633e65b9c6SColin Percival 		__FreeBSD_libc_enter_restricted_mode();
1564ce9287fcSYaroslav Tykhiy 	} else	/* real user w/o chroot */
1565ce9287fcSYaroslav Tykhiy 		homedir = pw->pw_dir;
1566ce9287fcSYaroslav Tykhiy 	/*
1567ce9287fcSYaroslav Tykhiy 	 * Set euid *before* doing chdir() so
1568ce9287fcSYaroslav Tykhiy 	 * a) the user won't be carried to a directory that he couldn't reach
1569ce9287fcSYaroslav Tykhiy 	 *    on his own due to no permission to upper path components,
1570ce9287fcSYaroslav Tykhiy 	 * b) NFS mounted homedirs w/restrictive permissions will be accessible
1571ce9287fcSYaroslav Tykhiy 	 *    (uid 0 has no root power over NFS if not mapped explicitly.)
1572ce9287fcSYaroslav Tykhiy 	 */
157352e7ee74SYaroslav Tykhiy 	if (seteuid(pw->pw_uid) < 0) {
1574ea022d16SRodney W. Grimes 		reply(550, "Can't set uid.");
1575ea022d16SRodney W. Grimes 		goto bad;
1576ea022d16SRodney W. Grimes 	}
1577ce9287fcSYaroslav Tykhiy 	if (chdir(homedir) < 0) {
1578ce9287fcSYaroslav Tykhiy 		if (guest || dochroot) {
1579ce9287fcSYaroslav Tykhiy 			reply(550, "Can't change to base directory.");
1580ce9287fcSYaroslav Tykhiy 			goto bad;
1581ce9287fcSYaroslav Tykhiy 		} else {
1582ce9287fcSYaroslav Tykhiy 			if (chdir("/") < 0) {
1583ce9287fcSYaroslav Tykhiy 				reply(550, "Root is inaccessible.");
1584ce9287fcSYaroslav Tykhiy 				goto bad;
1585ce9287fcSYaroslav Tykhiy 			}
158602c97492SYaroslav Tykhiy 			lreply(230, "No directory! Logging in with home=/.");
1587ce9287fcSYaroslav Tykhiy 		}
1588ce9287fcSYaroslav Tykhiy 	}
158982c76939SDavid Greenman 
159082c76939SDavid Greenman 	/*
1591ea022d16SRodney W. Grimes 	 * Display a login message, if it exists.
1592ea022d16SRodney W. Grimes 	 * N.B. reply(230,) must follow the message.
1593ea022d16SRodney W. Grimes 	 */
1594ea4e54b9SDavid Nugent #ifdef VIRTUAL_HOSTING
159563047c6fSDavid E. O'Brien 	fd = fopen(thishost->loginmsg, "r");
1596ea4e54b9SDavid Nugent #else
159763047c6fSDavid E. O'Brien 	fd = fopen(_PATH_FTPLOGINMESG, "r");
1598ea4e54b9SDavid Nugent #endif
159963047c6fSDavid E. O'Brien 	if (fd != NULL) {
1600ea022d16SRodney W. Grimes 		char *cp, line[LINE_MAX];
1601ea022d16SRodney W. Grimes 
1602ea022d16SRodney W. Grimes 		while (fgets(line, sizeof(line), fd) != NULL) {
1603ea022d16SRodney W. Grimes 			if ((cp = strchr(line, '\n')) != NULL)
1604ea022d16SRodney W. Grimes 				*cp = '\0';
1605ea022d16SRodney W. Grimes 			lreply(230, "%s", line);
1606ea022d16SRodney W. Grimes 		}
1607ea022d16SRodney W. Grimes 		(void) fflush(stdout);
1608ea022d16SRodney W. Grimes 		(void) fclose(fd);
1609ea022d16SRodney W. Grimes 	}
1610ea022d16SRodney W. Grimes 	if (guest) {
16113eb568f2SGuido van Rooij 		if (ident != NULL)
16123eb568f2SGuido van Rooij 			free(ident);
161361f891a6SPaul Traina 		ident = strdup(passwd);
161461f891a6SPaul Traina 		if (ident == NULL)
1615618b0bbaSMark Murray 			fatalerror("Ran out of memory.");
161661f891a6SPaul Traina 
1617ea022d16SRodney W. Grimes 		reply(230, "Guest login ok, access restrictions apply.");
1618ea022d16SRodney W. Grimes #ifdef SETPROCTITLE
1619ea4e54b9SDavid Nugent #ifdef VIRTUAL_HOSTING
1620ea4e54b9SDavid Nugent 		if (thishost != firsthost)
1621ea4e54b9SDavid Nugent 			snprintf(proctitle, sizeof(proctitle),
1622b3a0a7cdSMike Heffner 				 "%s: anonymous(%s)/%s", remotehost, hostname,
1623b3a0a7cdSMike Heffner 				 passwd);
1624ea4e54b9SDavid Nugent 		else
1625ea4e54b9SDavid Nugent #endif
1626ea022d16SRodney W. Grimes 			snprintf(proctitle, sizeof(proctitle),
1627b3a0a7cdSMike Heffner 				 "%s: anonymous/%s", remotehost, passwd);
1628b63e1fe2SPeter Wemm 		setproctitle("%s", proctitle);
1629ea022d16SRodney W. Grimes #endif /* SETPROCTITLE */
1630ea022d16SRodney W. Grimes 		if (logging)
1631ea022d16SRodney W. Grimes 			syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s, %s",
1632ea022d16SRodney W. Grimes 			    remotehost, passwd);
1633ea022d16SRodney W. Grimes 	} else {
16343401a71fSDaniel O'Callaghan 		if (dochroot)
163511342ab1SYaroslav Tykhiy 			reply(230, "User %s logged in, "
163611342ab1SYaroslav Tykhiy 				   "access restrictions apply.", pw->pw_name);
16373401a71fSDaniel O'Callaghan 		else
1638ea022d16SRodney W. Grimes 			reply(230, "User %s logged in.", pw->pw_name);
16393401a71fSDaniel O'Callaghan 
1640ea022d16SRodney W. Grimes #ifdef SETPROCTITLE
1641ea022d16SRodney W. Grimes 		snprintf(proctitle, sizeof(proctitle),
16427a29d7daSYaroslav Tykhiy 			 "%s: user/%s", remotehost, pw->pw_name);
1643b63e1fe2SPeter Wemm 		setproctitle("%s", proctitle);
1644ea022d16SRodney W. Grimes #endif /* SETPROCTITLE */
1645ea022d16SRodney W. Grimes 		if (logging)
1646ea022d16SRodney W. Grimes 			syslog(LOG_INFO, "FTP LOGIN FROM %s as %s",
1647ea022d16SRodney W. Grimes 			    remotehost, pw->pw_name);
1648ea022d16SRodney W. Grimes 	}
1649220223fdSYaroslav Tykhiy 	if (logging && (guest || dochroot))
1650e897216fSYaroslav Tykhiy 		syslog(LOG_INFO, "session root changed to %s", chrootdir);
1651b071c689SDavid Nugent #ifdef	LOGIN_CAP
1652b071c689SDavid Nugent 	login_close(lc);
1653b071c689SDavid Nugent #endif
1654ce9287fcSYaroslav Tykhiy 	if (residue)
1655ce9287fcSYaroslav Tykhiy 		free(residue);
1656ea022d16SRodney W. Grimes 	return;
1657ea022d16SRodney W. Grimes bad:
1658ea022d16SRodney W. Grimes 	/* Forget all about it... */
1659b071c689SDavid Nugent #ifdef	LOGIN_CAP
1660b071c689SDavid Nugent 	login_close(lc);
1661b071c689SDavid Nugent #endif
1662ce9287fcSYaroslav Tykhiy 	if (residue)
1663ce9287fcSYaroslav Tykhiy 		free(residue);
1664ea022d16SRodney W. Grimes 	end_login();
1665ea022d16SRodney W. Grimes }
1666ea022d16SRodney W. Grimes 
1667ea022d16SRodney W. Grimes void
1668e4bc453cSWarner Losh retrieve(char *cmd, char *name)
1669ea022d16SRodney W. Grimes {
1670ea022d16SRodney W. Grimes 	FILE *fin, *dout;
1671ea022d16SRodney W. Grimes 	struct stat st;
1672e4bc453cSWarner Losh 	int (*closefunc)(FILE *);
1673158a00b2SJohn Birrell 	time_t start;
1674ea022d16SRodney W. Grimes 
1675ea022d16SRodney W. Grimes 	if (cmd == 0) {
1676ea022d16SRodney W. Grimes 		fin = fopen(name, "r"), closefunc = fclose;
1677ea022d16SRodney W. Grimes 		st.st_size = 0;
1678ea022d16SRodney W. Grimes 	} else {
1679ea022d16SRodney W. Grimes 		char line[BUFSIZ];
1680ea022d16SRodney W. Grimes 
1681e760ef2cSWarner Losh 		(void) snprintf(line, sizeof(line), cmd, name), name = line;
1682ea022d16SRodney W. Grimes 		fin = ftpd_popen(line, "r"), closefunc = ftpd_pclose;
1683ea022d16SRodney W. Grimes 		st.st_size = -1;
1684ea022d16SRodney W. Grimes 		st.st_blksize = BUFSIZ;
1685ea022d16SRodney W. Grimes 	}
1686ea022d16SRodney W. Grimes 	if (fin == NULL) {
1687ea022d16SRodney W. Grimes 		if (errno != 0) {
1688ea022d16SRodney W. Grimes 			perror_reply(550, name);
1689ea022d16SRodney W. Grimes 			if (cmd == 0) {
1690ea022d16SRodney W. Grimes 				LOGCMD("get", name);
1691ea022d16SRodney W. Grimes 			}
1692ea022d16SRodney W. Grimes 		}
1693ea022d16SRodney W. Grimes 		return;
1694ea022d16SRodney W. Grimes 	}
1695ea022d16SRodney W. Grimes 	byte_count = -1;
1696ea701226SYaroslav Tykhiy 	if (cmd == 0) {
1697ea701226SYaroslav Tykhiy 		if (fstat(fileno(fin), &st) < 0) {
1698ea701226SYaroslav Tykhiy 			perror_reply(550, name);
1699ea701226SYaroslav Tykhiy 			goto done;
1700ea701226SYaroslav Tykhiy 		}
1701ea701226SYaroslav Tykhiy 		if (!S_ISREG(st.st_mode)) {
170210e89104SYaroslav Tykhiy 			/*
170310e89104SYaroslav Tykhiy 			 * Never sending a raw directory is a workaround
170410e89104SYaroslav Tykhiy 			 * for buggy clients that will attempt to RETR
170510e89104SYaroslav Tykhiy 			 * a directory before listing it, e.g., Mozilla.
170610e89104SYaroslav Tykhiy 			 * Preventing a guest from getting irregular files
170710e89104SYaroslav Tykhiy 			 * is a simple security measure.
170810e89104SYaroslav Tykhiy 			 */
170910e89104SYaroslav Tykhiy 			if (S_ISDIR(st.st_mode) || guest) {
1710ea022d16SRodney W. Grimes 				reply(550, "%s: not a plain file.", name);
1711ea022d16SRodney W. Grimes 				goto done;
1712ea022d16SRodney W. Grimes 			}
1713ea701226SYaroslav Tykhiy 			st.st_size = -1;
1714ea701226SYaroslav Tykhiy 			/* st.st_blksize is set for all descriptor types */
1715ea701226SYaroslav Tykhiy 		}
1716ea701226SYaroslav Tykhiy 	}
1717ea022d16SRodney W. Grimes 	if (restart_point) {
1718ea022d16SRodney W. Grimes 		if (type == TYPE_A) {
1719ea022d16SRodney W. Grimes 			off_t i, n;
1720ea022d16SRodney W. Grimes 			int c;
1721ea022d16SRodney W. Grimes 
1722ea022d16SRodney W. Grimes 			n = restart_point;
1723ea022d16SRodney W. Grimes 			i = 0;
1724ea022d16SRodney W. Grimes 			while (i++ < n) {
1725ea022d16SRodney W. Grimes 				if ((c=getc(fin)) == EOF) {
1726ea022d16SRodney W. Grimes 					perror_reply(550, name);
1727ea022d16SRodney W. Grimes 					goto done;
1728ea022d16SRodney W. Grimes 				}
1729ea022d16SRodney W. Grimes 				if (c == '\n')
1730ea022d16SRodney W. Grimes 					i++;
1731ea022d16SRodney W. Grimes 			}
1732ea022d16SRodney W. Grimes 		} else if (lseek(fileno(fin), restart_point, L_SET) < 0) {
1733ea022d16SRodney W. Grimes 			perror_reply(550, name);
1734ea022d16SRodney W. Grimes 			goto done;
1735ea022d16SRodney W. Grimes 		}
1736ea022d16SRodney W. Grimes 	}
1737ea022d16SRodney W. Grimes 	dout = dataconn(name, st.st_size, "w");
1738ea022d16SRodney W. Grimes 	if (dout == NULL)
1739ea022d16SRodney W. Grimes 		goto done;
17403eb568f2SGuido van Rooij 	time(&start);
17419fc5823aSGarrett Wollman 	send_data(fin, dout, st.st_blksize, st.st_size,
17429fc5823aSGarrett Wollman 		  restart_point == 0 && cmd == 0 && S_ISREG(st.st_mode));
1743c999732bSYaroslav Tykhiy 	if (cmd == 0 && guest && stats && byte_count > 0)
1744c999732bSYaroslav Tykhiy 		logxfer(name, byte_count, start);
1745ea022d16SRodney W. Grimes 	(void) fclose(dout);
1746ea022d16SRodney W. Grimes 	data = -1;
1747ea022d16SRodney W. Grimes 	pdata = -1;
1748ea022d16SRodney W. Grimes done:
1749ea022d16SRodney W. Grimes 	if (cmd == 0)
1750ea022d16SRodney W. Grimes 		LOGBYTES("get", name, byte_count);
1751ea022d16SRodney W. Grimes 	(*closefunc)(fin);
1752ea022d16SRodney W. Grimes }
1753ea022d16SRodney W. Grimes 
1754ea022d16SRodney W. Grimes void
1755e4bc453cSWarner Losh store(char *name, char *mode, int unique)
1756ea022d16SRodney W. Grimes {
1757a117c345SYaroslav Tykhiy 	int fd;
1758ea022d16SRodney W. Grimes 	FILE *fout, *din;
1759e4bc453cSWarner Losh 	int (*closefunc)(FILE *);
1760ea022d16SRodney W. Grimes 
1761a117c345SYaroslav Tykhiy 	if (*mode == 'a') {		/* APPE */
1762a117c345SYaroslav Tykhiy 		if (unique) {
1763a117c345SYaroslav Tykhiy 			/* Programming error */
1764a117c345SYaroslav Tykhiy 			syslog(LOG_ERR, "Internal: unique flag to APPE");
1765a117c345SYaroslav Tykhiy 			unique = 0;
1766a117c345SYaroslav Tykhiy 		}
1767a117c345SYaroslav Tykhiy 		if (guest && noguestmod) {
176802c97492SYaroslav Tykhiy 			reply(550, "Appending to existing file denied.");
1769a117c345SYaroslav Tykhiy 			goto err;
1770a117c345SYaroslav Tykhiy 		}
1771a117c345SYaroslav Tykhiy 		restart_point = 0;	/* not affected by preceding REST */
1772a117c345SYaroslav Tykhiy 	}
1773a117c345SYaroslav Tykhiy 	if (unique)			/* STOU overrides REST */
1774a117c345SYaroslav Tykhiy 		restart_point = 0;
1775a117c345SYaroslav Tykhiy 	if (guest && noguestmod) {
1776a117c345SYaroslav Tykhiy 		if (restart_point) {	/* guest STOR w/REST */
177702c97492SYaroslav Tykhiy 			reply(550, "Modifying existing file denied.");
1778a117c345SYaroslav Tykhiy 			goto err;
1779a117c345SYaroslav Tykhiy 		} else			/* treat guest STOR as STOU */
1780a117c345SYaroslav Tykhiy 			unique = 1;
1781ea022d16SRodney W. Grimes 	}
1782ea022d16SRodney W. Grimes 
1783ea022d16SRodney W. Grimes 	if (restart_point)
1784a117c345SYaroslav Tykhiy 		mode = "r+";	/* so ASCII manual seek can work */
1785a117c345SYaroslav Tykhiy 	if (unique) {
1786a117c345SYaroslav Tykhiy 		if ((fd = guniquefd(name, &name)) < 0)
1787a117c345SYaroslav Tykhiy 			goto err;
1788a117c345SYaroslav Tykhiy 		fout = fdopen(fd, mode);
1789a117c345SYaroslav Tykhiy 	} else
1790ea022d16SRodney W. Grimes 		fout = fopen(name, mode);
1791ea022d16SRodney W. Grimes 	closefunc = fclose;
1792ea022d16SRodney W. Grimes 	if (fout == NULL) {
1793ea022d16SRodney W. Grimes 		perror_reply(553, name);
1794a117c345SYaroslav Tykhiy 		goto err;
1795ea022d16SRodney W. Grimes 	}
1796ea022d16SRodney W. Grimes 	byte_count = -1;
1797ea022d16SRodney W. Grimes 	if (restart_point) {
1798ea022d16SRodney W. Grimes 		if (type == TYPE_A) {
1799ea022d16SRodney W. Grimes 			off_t i, n;
1800ea022d16SRodney W. Grimes 			int c;
1801ea022d16SRodney W. Grimes 
1802ea022d16SRodney W. Grimes 			n = restart_point;
1803ea022d16SRodney W. Grimes 			i = 0;
1804ea022d16SRodney W. Grimes 			while (i++ < n) {
1805ea022d16SRodney W. Grimes 				if ((c=getc(fout)) == EOF) {
1806ea022d16SRodney W. Grimes 					perror_reply(550, name);
1807ea022d16SRodney W. Grimes 					goto done;
1808ea022d16SRodney W. Grimes 				}
1809ea022d16SRodney W. Grimes 				if (c == '\n')
1810ea022d16SRodney W. Grimes 					i++;
1811ea022d16SRodney W. Grimes 			}
1812ea022d16SRodney W. Grimes 			/*
1813ea022d16SRodney W. Grimes 			 * We must do this seek to "current" position
1814ea022d16SRodney W. Grimes 			 * because we are changing from reading to
1815ea022d16SRodney W. Grimes 			 * writing.
1816ea022d16SRodney W. Grimes 			 */
18170e519c96SYaroslav Tykhiy 			if (fseeko(fout, 0, SEEK_CUR) < 0) {
1818ea022d16SRodney W. Grimes 				perror_reply(550, name);
1819ea022d16SRodney W. Grimes 				goto done;
1820ea022d16SRodney W. Grimes 			}
1821ea022d16SRodney W. Grimes 		} else if (lseek(fileno(fout), restart_point, L_SET) < 0) {
1822ea022d16SRodney W. Grimes 			perror_reply(550, name);
1823ea022d16SRodney W. Grimes 			goto done;
1824ea022d16SRodney W. Grimes 		}
1825ea022d16SRodney W. Grimes 	}
18260e519c96SYaroslav Tykhiy 	din = dataconn(name, -1, "r");
1827ea022d16SRodney W. Grimes 	if (din == NULL)
1828ea022d16SRodney W. Grimes 		goto done;
1829ea022d16SRodney W. Grimes 	if (receive_data(din, fout) == 0) {
1830ea022d16SRodney W. Grimes 		if (unique)
1831ea022d16SRodney W. Grimes 			reply(226, "Transfer complete (unique file name:%s).",
1832ea022d16SRodney W. Grimes 			    name);
1833ea022d16SRodney W. Grimes 		else
1834ea022d16SRodney W. Grimes 			reply(226, "Transfer complete.");
1835ea022d16SRodney W. Grimes 	}
1836ea022d16SRodney W. Grimes 	(void) fclose(din);
1837ea022d16SRodney W. Grimes 	data = -1;
1838ea022d16SRodney W. Grimes 	pdata = -1;
1839ea022d16SRodney W. Grimes done:
18407c20f337SYaroslav Tykhiy 	LOGBYTES(*mode == 'a' ? "append" : "put", name, byte_count);
1841ea022d16SRodney W. Grimes 	(*closefunc)(fout);
1842a117c345SYaroslav Tykhiy 	return;
1843a117c345SYaroslav Tykhiy err:
1844a117c345SYaroslav Tykhiy 	LOGCMD(*mode == 'a' ? "append" : "put" , name);
1845a117c345SYaroslav Tykhiy 	return;
1846ea022d16SRodney W. Grimes }
1847ea022d16SRodney W. Grimes 
1848ea022d16SRodney W. Grimes static FILE *
1849e4bc453cSWarner Losh getdatasock(char *mode)
1850ea022d16SRodney W. Grimes {
1851ea022d16SRodney W. Grimes 	int on = 1, s, t, tries;
1852ea022d16SRodney W. Grimes 
1853ea022d16SRodney W. Grimes 	if (data >= 0)
1854ea022d16SRodney W. Grimes 		return (fdopen(data, mode));
18554dd8b5abSYoshinobu Inoue 
18564dd8b5abSYoshinobu Inoue 	s = socket(data_dest.su_family, SOCK_STREAM, 0);
1857ea022d16SRodney W. Grimes 	if (s < 0)
1858ea022d16SRodney W. Grimes 		goto bad;
185957d4ef07SYaroslav Tykhiy 	if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
1860406d1ae9SYaroslav Tykhiy 		syslog(LOG_WARNING, "data setsockopt (SO_REUSEADDR): %m");
1861ea022d16SRodney W. Grimes 	/* anchor socket to avoid multi-homing problems */
18624dd8b5abSYoshinobu Inoue 	data_source = ctrl_addr;
186363591ba5SYaroslav Tykhiy 	data_source.su_port = htons(dataport);
186452e7ee74SYaroslav Tykhiy 	(void) seteuid(0);
1865ea022d16SRodney W. Grimes 	for (tries = 1; ; tries++) {
18669ec7612aSYaroslav Tykhiy 		/*
18679ec7612aSYaroslav Tykhiy 		 * We should loop here since it's possible that
18689ec7612aSYaroslav Tykhiy 		 * another ftpd instance has passed this point and is
18699ec7612aSYaroslav Tykhiy 		 * trying to open a data connection in active mode now.
18709ec7612aSYaroslav Tykhiy 		 * Until the other connection is opened, we'll be getting
18719ec7612aSYaroslav Tykhiy 		 * EADDRINUSE because no SOCK_STREAM sockets in the system
18729ec7612aSYaroslav Tykhiy 		 * can share both local and remote addresses, localIP:20
18739ec7612aSYaroslav Tykhiy 		 * and *:* in this case.
18749ec7612aSYaroslav Tykhiy 		 */
1875ea022d16SRodney W. Grimes 		if (bind(s, (struct sockaddr *)&data_source,
18764dd8b5abSYoshinobu Inoue 		    data_source.su_len) >= 0)
1877ea022d16SRodney W. Grimes 			break;
1878ea022d16SRodney W. Grimes 		if (errno != EADDRINUSE || tries > 10)
1879ea022d16SRodney W. Grimes 			goto bad;
1880ea022d16SRodney W. Grimes 		sleep(tries);
1881ea022d16SRodney W. Grimes 	}
188252e7ee74SYaroslav Tykhiy 	(void) seteuid(pw->pw_uid);
1883ea022d16SRodney W. Grimes #ifdef IP_TOS
18844dd8b5abSYoshinobu Inoue 	if (data_source.su_family == AF_INET)
18854dd8b5abSYoshinobu Inoue       {
1886ea022d16SRodney W. Grimes 	on = IPTOS_THROUGHPUT;
188757d4ef07SYaroslav Tykhiy 	if (setsockopt(s, IPPROTO_IP, IP_TOS, &on, sizeof(int)) < 0)
1888406d1ae9SYaroslav Tykhiy 		syslog(LOG_WARNING, "data setsockopt (IP_TOS): %m");
18894dd8b5abSYoshinobu Inoue       }
1890ea022d16SRodney W. Grimes #endif
18919fc5823aSGarrett Wollman #ifdef TCP_NOPUSH
18929fc5823aSGarrett Wollman 	/*
18939fc5823aSGarrett Wollman 	 * Turn off push flag to keep sender TCP from sending short packets
189432072720SYaroslav Tykhiy 	 * at the boundaries of each write().
18959fc5823aSGarrett Wollman 	 */
18969fc5823aSGarrett Wollman 	on = 1;
189757d4ef07SYaroslav Tykhiy 	if (setsockopt(s, IPPROTO_TCP, TCP_NOPUSH, &on, sizeof on) < 0)
1898406d1ae9SYaroslav Tykhiy 		syslog(LOG_WARNING, "data setsockopt (TCP_NOPUSH): %m");
18999fc5823aSGarrett Wollman #endif
1900ea022d16SRodney W. Grimes 	return (fdopen(s, mode));
1901ea022d16SRodney W. Grimes bad:
1902ea022d16SRodney W. Grimes 	/* Return the real value of errno (close may change it) */
1903ea022d16SRodney W. Grimes 	t = errno;
190452e7ee74SYaroslav Tykhiy 	(void) seteuid(pw->pw_uid);
1905ea022d16SRodney W. Grimes 	(void) close(s);
1906ea022d16SRodney W. Grimes 	errno = t;
1907ea022d16SRodney W. Grimes 	return (NULL);
1908ea022d16SRodney W. Grimes }
1909ea022d16SRodney W. Grimes 
1910ea022d16SRodney W. Grimes static FILE *
1911e4bc453cSWarner Losh dataconn(char *name, off_t size, char *mode)
1912ea022d16SRodney W. Grimes {
1913ea022d16SRodney W. Grimes 	char sizebuf[32];
1914ea022d16SRodney W. Grimes 	FILE *file;
1915e5094456SCrist J. Clark 	int retry = 0, tos, conerrno;
1916ea022d16SRodney W. Grimes 
1917ea022d16SRodney W. Grimes 	file_size = size;
1918ea022d16SRodney W. Grimes 	byte_count = 0;
19190e519c96SYaroslav Tykhiy 	if (size != -1)
1920a57e1ef0SYaroslav Tykhiy 		(void) snprintf(sizebuf, sizeof(sizebuf),
1921a57e1ef0SYaroslav Tykhiy 				" (%jd bytes)", (intmax_t)size);
1922ea022d16SRodney W. Grimes 	else
1923e760ef2cSWarner Losh 		*sizebuf = '\0';
1924ea022d16SRodney W. Grimes 	if (pdata >= 0) {
19254dd8b5abSYoshinobu Inoue 		union sockunion from;
192678e3eed0SStefan Farfeleder 		socklen_t fromlen = ctrl_addr.su_len;
192778e3eed0SStefan Farfeleder 		int flags, s;
1928d6ed3c37SGuido van Rooij 		struct timeval timeout;
1929d6ed3c37SGuido van Rooij 		fd_set set;
1930ea022d16SRodney W. Grimes 
1931d6ed3c37SGuido van Rooij 		FD_ZERO(&set);
1932d6ed3c37SGuido van Rooij 		FD_SET(pdata, &set);
1933d6ed3c37SGuido van Rooij 
1934d6ed3c37SGuido van Rooij 		timeout.tv_usec = 0;
1935d6ed3c37SGuido van Rooij 		timeout.tv_sec = 120;
1936d6ed3c37SGuido van Rooij 
19374cd48bacSYaroslav Tykhiy 		/*
19384cd48bacSYaroslav Tykhiy 		 * Granted a socket is in the blocking I/O mode,
19394cd48bacSYaroslav Tykhiy 		 * accept() will block after a successful select()
19404cd48bacSYaroslav Tykhiy 		 * if the selected connection dies in between.
19414cd48bacSYaroslav Tykhiy 		 * Therefore set the non-blocking I/O flag here.
19424cd48bacSYaroslav Tykhiy 		 */
19434cd48bacSYaroslav Tykhiy 		if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
19444cd48bacSYaroslav Tykhiy 		    fcntl(pdata, F_SETFL, flags | O_NONBLOCK) == -1)
19454cd48bacSYaroslav Tykhiy 			goto pdata_err;
1946aa5a9d3fSYaroslav Tykhiy 		if (select(pdata+1, &set, NULL, NULL, &timeout) <= 0 ||
19474cd48bacSYaroslav Tykhiy 		    (s = accept(pdata, (struct sockaddr *) &from, &fromlen)) < 0)
19484cd48bacSYaroslav Tykhiy 			goto pdata_err;
1949ea022d16SRodney W. Grimes 		(void) close(pdata);
1950ea022d16SRodney W. Grimes 		pdata = s;
19514cd48bacSYaroslav Tykhiy 		/*
1952f6daca0dSYaroslav Tykhiy 		 * Unset the inherited non-blocking I/O flag
1953f6daca0dSYaroslav Tykhiy 		 * on the child socket so stdio can work on it.
19544cd48bacSYaroslav Tykhiy 		 */
19554cd48bacSYaroslav Tykhiy 		if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
19564cd48bacSYaroslav Tykhiy 		    fcntl(pdata, F_SETFL, flags & ~O_NONBLOCK) == -1)
19574cd48bacSYaroslav Tykhiy 			goto pdata_err;
1958ea022d16SRodney W. Grimes #ifdef IP_TOS
19594dd8b5abSYoshinobu Inoue 		if (from.su_family == AF_INET)
19604dd8b5abSYoshinobu Inoue 	      {
1961a5a4544eSPaul Traina 		tos = IPTOS_THROUGHPUT;
196257d4ef07SYaroslav Tykhiy 		if (setsockopt(s, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
1963406d1ae9SYaroslav Tykhiy 			syslog(LOG_WARNING, "pdata setsockopt (IP_TOS): %m");
19644dd8b5abSYoshinobu Inoue 	      }
1965ea022d16SRodney W. Grimes #endif
1966ea022d16SRodney W. Grimes 		reply(150, "Opening %s mode data connection for '%s'%s.",
1967ea022d16SRodney W. Grimes 		     type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1968ea022d16SRodney W. Grimes 		return (fdopen(pdata, mode));
19694cd48bacSYaroslav Tykhiy pdata_err:
19704cd48bacSYaroslav Tykhiy 		reply(425, "Can't open data connection.");
19714cd48bacSYaroslav Tykhiy 		(void) close(pdata);
19724cd48bacSYaroslav Tykhiy 		pdata = -1;
19734cd48bacSYaroslav Tykhiy 		return (NULL);
1974ea022d16SRodney W. Grimes 	}
1975ea022d16SRodney W. Grimes 	if (data >= 0) {
1976ea022d16SRodney W. Grimes 		reply(125, "Using existing data connection for '%s'%s.",
1977ea022d16SRodney W. Grimes 		    name, sizebuf);
1978ea022d16SRodney W. Grimes 		usedefault = 1;
1979ea022d16SRodney W. Grimes 		return (fdopen(data, mode));
1980ea022d16SRodney W. Grimes 	}
1981ea022d16SRodney W. Grimes 	if (usedefault)
1982ea022d16SRodney W. Grimes 		data_dest = his_addr;
1983ea022d16SRodney W. Grimes 	usedefault = 1;
1984e5094456SCrist J. Clark 	do {
1985ea022d16SRodney W. Grimes 		file = getdatasock(mode);
1986ea022d16SRodney W. Grimes 		if (file == NULL) {
198704683b2cSYaroslav Tykhiy 			char hostbuf[NI_MAXHOST], portbuf[NI_MAXSERV];
198804683b2cSYaroslav Tykhiy 
198904683b2cSYaroslav Tykhiy 			if (getnameinfo((struct sockaddr *)&data_source,
199004683b2cSYaroslav Tykhiy 				data_source.su_len,
199104683b2cSYaroslav Tykhiy 				hostbuf, sizeof(hostbuf) - 1,
199204683b2cSYaroslav Tykhiy 				portbuf, sizeof(portbuf) - 1,
199304683b2cSYaroslav Tykhiy 				NI_NUMERICHOST|NI_NUMERICSERV))
199404683b2cSYaroslav Tykhiy 					*hostbuf = *portbuf = 0;
199504683b2cSYaroslav Tykhiy 			hostbuf[sizeof(hostbuf) - 1] = 0;
199604683b2cSYaroslav Tykhiy 			portbuf[sizeof(portbuf) - 1] = 0;
19974dd8b5abSYoshinobu Inoue 			reply(425, "Can't create data socket (%s,%s): %s.",
19984dd8b5abSYoshinobu Inoue 				hostbuf, portbuf, strerror(errno));
1999ea022d16SRodney W. Grimes 			return (NULL);
2000ea022d16SRodney W. Grimes 		}
2001ea022d16SRodney W. Grimes 		data = fileno(file);
2002e5094456SCrist J. Clark 		conerrno = 0;
2003e5094456SCrist J. Clark 		if (connect(data, (struct sockaddr *)&data_dest,
2004e5094456SCrist J. Clark 		    data_dest.su_len) == 0)
2005e5094456SCrist J. Clark 			break;
2006e5094456SCrist J. Clark 		conerrno = errno;
2007ea022d16SRodney W. Grimes 		(void) fclose(file);
2008ea022d16SRodney W. Grimes 		data = -1;
2009e5094456SCrist J. Clark 		if (conerrno == EADDRINUSE) {
2010e3765043SYaroslav Tykhiy 			sleep(swaitint);
2011e5094456SCrist J. Clark 			retry += swaitint;
2012e5094456SCrist J. Clark 		} else {
2013e5094456SCrist J. Clark 			break;
2014e5094456SCrist J. Clark 		}
2015e5094456SCrist J. Clark 	} while (retry <= swaitmax);
2016e5094456SCrist J. Clark 	if (conerrno != 0) {
201782c03024SYaroslav Tykhiy 		reply(425, "Can't build data connection: %s.",
201882c03024SYaroslav Tykhiy 			   strerror(conerrno));
2019ea022d16SRodney W. Grimes 		return (NULL);
2020ea022d16SRodney W. Grimes 	}
2021ea022d16SRodney W. Grimes 	reply(150, "Opening %s mode data connection for '%s'%s.",
2022ea022d16SRodney W. Grimes 	     type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
2023ea022d16SRodney W. Grimes 	return (file);
2024ea022d16SRodney W. Grimes }
2025ea022d16SRodney W. Grimes 
2026ea022d16SRodney W. Grimes /*
20274cd51076SYaroslav Tykhiy  * A helper macro to avoid code duplication
20284cd51076SYaroslav Tykhiy  * in send_data() and receive_data().
20294cd51076SYaroslav Tykhiy  *
20304cd51076SYaroslav Tykhiy  * XXX We have to block SIGURG during putc() because BSD stdio
20314cd51076SYaroslav Tykhiy  * is unable to restart interrupted write operations and hence
20324cd51076SYaroslav Tykhiy  * the entire buffer contents will be lost as soon as a write()
20334cd51076SYaroslav Tykhiy  * call indicates EINTR to stdio.
20344cd51076SYaroslav Tykhiy  */
20354cd51076SYaroslav Tykhiy #define FTPD_PUTC(ch, file, label)					\
20364cd51076SYaroslav Tykhiy 	do {								\
20374cd51076SYaroslav Tykhiy 		int ret;						\
20384cd51076SYaroslav Tykhiy 									\
20394cd51076SYaroslav Tykhiy 		do {							\
20404cd51076SYaroslav Tykhiy 			START_UNSAFE;					\
20414cd51076SYaroslav Tykhiy 			ret = putc((ch), (file));			\
20424cd51076SYaroslav Tykhiy 			END_UNSAFE;					\
20434cd51076SYaroslav Tykhiy 			CHECKOOB(return (-1))				\
20444cd51076SYaroslav Tykhiy 			else if (ferror(file))				\
20454cd51076SYaroslav Tykhiy 				goto label;				\
20464cd51076SYaroslav Tykhiy 			clearerr(file);					\
20474cd51076SYaroslav Tykhiy 		} while (ret == EOF);					\
20484cd51076SYaroslav Tykhiy 	} while (0)
20494cd51076SYaroslav Tykhiy 
20504cd51076SYaroslav Tykhiy /*
2051*ec489d64SPedro F. Giffuni  * Transfer the contents of "instr" to "outstr" peer using the appropriate
20529fc5823aSGarrett Wollman  * encapsulation of the data subject to Mode, Structure, and Type.
2053ea022d16SRodney W. Grimes  *
2054ea022d16SRodney W. Grimes  * NB: Form isn't handled.
2055ea022d16SRodney W. Grimes  */
20564b82fc95SYaroslav Tykhiy static int
20576e4b0a55SYaroslav Tykhiy send_data(FILE *instr, FILE *outstr, size_t blksize, off_t filesize, int isreg)
2058ea022d16SRodney W. Grimes {
2059db1c2da3SYaroslav Tykhiy 	int c, cp, filefd, netfd;
2060f6f0c4b9SDan Moschuk 	char *buf;
2061ea022d16SRodney W. Grimes 
20624cd51076SYaroslav Tykhiy 	STARTXFER;
20634cd51076SYaroslav Tykhiy 
2064ea022d16SRodney W. Grimes 	switch (type) {
2065ea022d16SRodney W. Grimes 
2066ea022d16SRodney W. Grimes 	case TYPE_A:
20674cd51076SYaroslav Tykhiy 		cp = EOF;
20684cd51076SYaroslav Tykhiy 		for (;;) {
20694cd51076SYaroslav Tykhiy 			c = getc(instr);
20704cd51076SYaroslav Tykhiy 			CHECKOOB(return (-1))
20714cd51076SYaroslav Tykhiy 			else if (c == EOF && ferror(instr))
20724cd51076SYaroslav Tykhiy 				goto file_err;
20734cd51076SYaroslav Tykhiy 			if (c == EOF) {
20744cd51076SYaroslav Tykhiy 				if (ferror(instr)) {	/* resume after OOB */
20754cd51076SYaroslav Tykhiy 					clearerr(instr);
20764cd51076SYaroslav Tykhiy 					continue;
2077ea022d16SRodney W. Grimes 				}
20784cd51076SYaroslav Tykhiy 				if (feof(instr))	/* EOF */
20794cd51076SYaroslav Tykhiy 					break;
20804cd51076SYaroslav Tykhiy 				syslog(LOG_ERR, "Internal: impossible condition"
20814cd51076SYaroslav Tykhiy 						" on file after getc()");
20824cd51076SYaroslav Tykhiy 				goto file_err;
20834cd51076SYaroslav Tykhiy 			}
20844cd51076SYaroslav Tykhiy 			if (c == '\n' && cp != '\r') {
20854cd51076SYaroslav Tykhiy 				FTPD_PUTC('\r', outstr, data_err);
20864cd51076SYaroslav Tykhiy 				byte_count++;
20874cd51076SYaroslav Tykhiy 			}
20884cd51076SYaroslav Tykhiy 			FTPD_PUTC(c, outstr, data_err);
20894cd51076SYaroslav Tykhiy 			byte_count++;
2090db1c2da3SYaroslav Tykhiy 			cp = c;
2091ea022d16SRodney W. Grimes 		}
20924cd51076SYaroslav Tykhiy #ifdef notyet	/* BSD stdio isn't ready for that */
20934cd51076SYaroslav Tykhiy 		while (fflush(outstr) == EOF) {
20944cd51076SYaroslav Tykhiy 			CHECKOOB(return (-1))
20954cd51076SYaroslav Tykhiy 			else
2096ea022d16SRodney W. Grimes 				goto data_err;
20974cd51076SYaroslav Tykhiy 			clearerr(outstr);
20984cd51076SYaroslav Tykhiy 		}
20994cd51076SYaroslav Tykhiy 		ENDXFER;
21004cd51076SYaroslav Tykhiy #else
21014cd51076SYaroslav Tykhiy 		ENDXFER;
21024cd51076SYaroslav Tykhiy 		if (fflush(outstr) == EOF)
21034cd51076SYaroslav Tykhiy 			goto data_err;
21044cd51076SYaroslav Tykhiy #endif
2105ea022d16SRodney W. Grimes 		reply(226, "Transfer complete.");
21064b82fc95SYaroslav Tykhiy 		return (0);
2107ea022d16SRodney W. Grimes 
2108ea022d16SRodney W. Grimes 	case TYPE_I:
2109ea022d16SRodney W. Grimes 	case TYPE_L:
21109fc5823aSGarrett Wollman 		/*
21119fc5823aSGarrett Wollman 		 * isreg is only set if we are not doing restart and we
21129fc5823aSGarrett Wollman 		 * are sending a regular file
21139fc5823aSGarrett Wollman 		 */
21149fc5823aSGarrett Wollman 		netfd = fileno(outstr);
21159fc5823aSGarrett Wollman 		filefd = fileno(instr);
21169fc5823aSGarrett Wollman 
2117f6f0c4b9SDan Moschuk 		if (isreg) {
21182e22b914SYaroslav Tykhiy 			char *msg = "Transfer complete.";
21194cd51076SYaroslav Tykhiy 			off_t cnt, offset;
2120f6f0c4b9SDan Moschuk 			int err;
2121f6f0c4b9SDan Moschuk 
21222f492fc8SYaroslav Tykhiy 			cnt = offset = 0;
2123f6f0c4b9SDan Moschuk 
21242f492fc8SYaroslav Tykhiy 			while (filesize > 0) {
2125492f1d9cSMaxim Konovalov 				err = sendfile(filefd, netfd, offset, 0,
21267e295315SYaroslav Tykhiy 					       NULL, &cnt, 0);
21273af48c42SMaxim Konovalov 				/*
21283af48c42SMaxim Konovalov 				 * Calculate byte_count before OOB processing.
21293af48c42SMaxim Konovalov 				 * It can be used in myoob() later.
21303af48c42SMaxim Konovalov 				 */
21313af48c42SMaxim Konovalov 				byte_count += cnt;
2132f6f0c4b9SDan Moschuk 				offset += cnt;
2133492f1d9cSMaxim Konovalov 				filesize -= cnt;
21344cd51076SYaroslav Tykhiy 				CHECKOOB(return (-1))
21354cd51076SYaroslav Tykhiy 				else if (err == -1) {
21364cd51076SYaroslav Tykhiy 					if (errno != EINTR &&
21374cd51076SYaroslav Tykhiy 					    cnt == 0 && offset == 0)
2138f6f0c4b9SDan Moschuk 						goto oldway;
21399fc5823aSGarrett Wollman 					goto data_err;
2140f6f0c4b9SDan Moschuk 				}
21414cd51076SYaroslav Tykhiy 				if (err == -1)	/* resume after OOB */
21424cd51076SYaroslav Tykhiy 					continue;
21432e22b914SYaroslav Tykhiy 				/*
21442e22b914SYaroslav Tykhiy 				 * We hit the EOF prematurely.
21452e22b914SYaroslav Tykhiy 				 * Perhaps the file was externally truncated.
21462e22b914SYaroslav Tykhiy 				 */
21472e22b914SYaroslav Tykhiy 				if (cnt == 0) {
21482e22b914SYaroslav Tykhiy 					msg = "Transfer finished due to "
21492e22b914SYaroslav Tykhiy 					      "premature end of file.";
21502e22b914SYaroslav Tykhiy 					break;
21512e22b914SYaroslav Tykhiy 				}
2152f6f0c4b9SDan Moschuk 			}
21534cd51076SYaroslav Tykhiy 			ENDXFER;
215462f390ecSEd Maste 			reply(226, "%s", msg);
21554b82fc95SYaroslav Tykhiy 			return (0);
21569fc5823aSGarrett Wollman 		}
21579fc5823aSGarrett Wollman 
21589fc5823aSGarrett Wollman oldway:
2159e3765043SYaroslav Tykhiy 		if ((buf = malloc(blksize)) == NULL) {
21604cd51076SYaroslav Tykhiy 			ENDXFER;
216102c97492SYaroslav Tykhiy 			reply(451, "Ran out of memory.");
21624b82fc95SYaroslav Tykhiy 			return (-1);
2163ea022d16SRodney W. Grimes 		}
21649fc5823aSGarrett Wollman 
21654cd51076SYaroslav Tykhiy 		for (;;) {
21664cd51076SYaroslav Tykhiy 			int cnt, len;
21674cd51076SYaroslav Tykhiy 			char *bp;
21684cd51076SYaroslav Tykhiy 
21694cd51076SYaroslav Tykhiy 			cnt = read(filefd, buf, blksize);
21704cd51076SYaroslav Tykhiy 			CHECKOOB(free(buf); return (-1))
21714cd51076SYaroslav Tykhiy 			else if (cnt < 0) {
21728efc8b18SYaroslav Tykhiy 				free(buf);
2173ea022d16SRodney W. Grimes 				goto file_err;
21744cd51076SYaroslav Tykhiy 			}
21754cd51076SYaroslav Tykhiy 			if (cnt < 0)	/* resume after OOB */
21764cd51076SYaroslav Tykhiy 				continue;
21774cd51076SYaroslav Tykhiy 			if (cnt == 0)	/* EOF */
21784cd51076SYaroslav Tykhiy 				break;
21794cd51076SYaroslav Tykhiy 			for (len = cnt, bp = buf; len > 0;) {
21804cd51076SYaroslav Tykhiy 				cnt = write(netfd, bp, len);
21814cd51076SYaroslav Tykhiy 				CHECKOOB(free(buf); return (-1))
21824cd51076SYaroslav Tykhiy 				else if (cnt < 0) {
21834cd51076SYaroslav Tykhiy 					free(buf);
2184ea022d16SRodney W. Grimes 					goto data_err;
2185ea022d16SRodney W. Grimes 				}
21864cd51076SYaroslav Tykhiy 				if (cnt <= 0)
21874cd51076SYaroslav Tykhiy 					continue;
21884cd51076SYaroslav Tykhiy 				len -= cnt;
21894cd51076SYaroslav Tykhiy 				bp += cnt;
21904cd51076SYaroslav Tykhiy 				byte_count += cnt;
21914cd51076SYaroslav Tykhiy 			}
21924cd51076SYaroslav Tykhiy 		}
21934cd51076SYaroslav Tykhiy 		ENDXFER;
21944cd51076SYaroslav Tykhiy 		free(buf);
2195ea022d16SRodney W. Grimes 		reply(226, "Transfer complete.");
21964b82fc95SYaroslav Tykhiy 		return (0);
2197ea022d16SRodney W. Grimes 	default:
21984cd51076SYaroslav Tykhiy 		ENDXFER;
219902c97492SYaroslav Tykhiy 		reply(550, "Unimplemented TYPE %d in send_data.", type);
22004b82fc95SYaroslav Tykhiy 		return (-1);
2201ea022d16SRodney W. Grimes 	}
2202ea022d16SRodney W. Grimes 
2203ea022d16SRodney W. Grimes data_err:
22044cd51076SYaroslav Tykhiy 	ENDXFER;
2205ea022d16SRodney W. Grimes 	perror_reply(426, "Data connection");
22064b82fc95SYaroslav Tykhiy 	return (-1);
2207ea022d16SRodney W. Grimes 
2208ea022d16SRodney W. Grimes file_err:
22094cd51076SYaroslav Tykhiy 	ENDXFER;
2210ea022d16SRodney W. Grimes 	perror_reply(551, "Error on input file");
22114b82fc95SYaroslav Tykhiy 	return (-1);
2212ea022d16SRodney W. Grimes }
2213ea022d16SRodney W. Grimes 
2214ea022d16SRodney W. Grimes /*
2215ea022d16SRodney W. Grimes  * Transfer data from peer to "outstr" using the appropriate encapulation of
2216ea022d16SRodney W. Grimes  * the data subject to Mode, Structure, and Type.
2217ea022d16SRodney W. Grimes  *
2218ea022d16SRodney W. Grimes  * N.B.: Form isn't handled.
2219ea022d16SRodney W. Grimes  */
2220ea022d16SRodney W. Grimes static int
2221e4bc453cSWarner Losh receive_data(FILE *instr, FILE *outstr)
2222ea022d16SRodney W. Grimes {
22234cd51076SYaroslav Tykhiy 	int c, cp;
22244cd51076SYaroslav Tykhiy 	int bare_lfs = 0;
2225ea022d16SRodney W. Grimes 
22264cd51076SYaroslav Tykhiy 	STARTXFER;
222761f891a6SPaul Traina 
2228ea022d16SRodney W. Grimes 	switch (type) {
2229ea022d16SRodney W. Grimes 
2230ea022d16SRodney W. Grimes 	case TYPE_I:
2231ea022d16SRodney W. Grimes 	case TYPE_L:
22324cd51076SYaroslav Tykhiy 		for (;;) {
22334cd51076SYaroslav Tykhiy 			int cnt, len;
22344cd51076SYaroslav Tykhiy 			char *bp;
22354cd51076SYaroslav Tykhiy 			char buf[BUFSIZ];
22364cd51076SYaroslav Tykhiy 
22374cd51076SYaroslav Tykhiy 			cnt = read(fileno(instr), buf, sizeof(buf));
22384cd51076SYaroslav Tykhiy 			CHECKOOB(return (-1))
22394cd51076SYaroslav Tykhiy 			else if (cnt < 0)
22404cd51076SYaroslav Tykhiy 				goto data_err;
22414cd51076SYaroslav Tykhiy 			if (cnt < 0)	/* resume after OOB */
22424cd51076SYaroslav Tykhiy 				continue;
22434cd51076SYaroslav Tykhiy 			if (cnt == 0)	/* EOF */
22444cd51076SYaroslav Tykhiy 				break;
22454cd51076SYaroslav Tykhiy 			for (len = cnt, bp = buf; len > 0;) {
22464cd51076SYaroslav Tykhiy 				cnt = write(fileno(outstr), bp, len);
22474cd51076SYaroslav Tykhiy 				CHECKOOB(return (-1))
22484cd51076SYaroslav Tykhiy 				else if (cnt < 0)
2249ea022d16SRodney W. Grimes 					goto file_err;
22504cd51076SYaroslav Tykhiy 				if (cnt <= 0)
22514cd51076SYaroslav Tykhiy 					continue;
22524cd51076SYaroslav Tykhiy 				len -= cnt;
22534cd51076SYaroslav Tykhiy 				bp += cnt;
2254ea022d16SRodney W. Grimes 				byte_count += cnt;
2255ea022d16SRodney W. Grimes 			}
22564cd51076SYaroslav Tykhiy 		}
22574cd51076SYaroslav Tykhiy 		ENDXFER;
2258ea022d16SRodney W. Grimes 		return (0);
2259ea022d16SRodney W. Grimes 
2260ea022d16SRodney W. Grimes 	case TYPE_E:
22614cd51076SYaroslav Tykhiy 		ENDXFER;
2262ea022d16SRodney W. Grimes 		reply(553, "TYPE E not implemented.");
2263ea022d16SRodney W. Grimes 		return (-1);
2264ea022d16SRodney W. Grimes 
2265ea022d16SRodney W. Grimes 	case TYPE_A:
22664cd51076SYaroslav Tykhiy 		cp = EOF;
22674cd51076SYaroslav Tykhiy 		for (;;) {
22684cd51076SYaroslav Tykhiy 			c = getc(instr);
22694cd51076SYaroslav Tykhiy 			CHECKOOB(return (-1))
22704cd51076SYaroslav Tykhiy 			else if (c == EOF && ferror(instr))
22714cd51076SYaroslav Tykhiy 				goto data_err;
22724cd51076SYaroslav Tykhiy 			if (c == EOF && ferror(instr)) { /* resume after OOB */
22734cd51076SYaroslav Tykhiy 				clearerr(instr);
22744cd51076SYaroslav Tykhiy 				continue;
22754cd51076SYaroslav Tykhiy 			}
22764cd51076SYaroslav Tykhiy 
22774cd51076SYaroslav Tykhiy 			if (cp == '\r') {
22784cd51076SYaroslav Tykhiy 				if (c != '\n')
22794cd51076SYaroslav Tykhiy 					FTPD_PUTC('\r', outstr, file_err);
22804cd51076SYaroslav Tykhiy 			} else
2281ea022d16SRodney W. Grimes 				if (c == '\n')
2282ea022d16SRodney W. Grimes 					bare_lfs++;
22834cd51076SYaroslav Tykhiy 			if (c == '\r') {
22844cd51076SYaroslav Tykhiy 				byte_count++;
22854cd51076SYaroslav Tykhiy 				cp = c;
22864cd51076SYaroslav Tykhiy 				continue;
22874cd51076SYaroslav Tykhiy 			}
22884cd51076SYaroslav Tykhiy 
22894cd51076SYaroslav Tykhiy 			/* Check for EOF here in order not to lose last \r. */
22904cd51076SYaroslav Tykhiy 			if (c == EOF) {
22914cd51076SYaroslav Tykhiy 				if (feof(instr))	/* EOF */
22924cd51076SYaroslav Tykhiy 					break;
22934cd51076SYaroslav Tykhiy 				syslog(LOG_ERR, "Internal: impossible condition"
22944cd51076SYaroslav Tykhiy 						" on data stream after getc()");
2295ea022d16SRodney W. Grimes 				goto data_err;
2296ea022d16SRodney W. Grimes 			}
22974cd51076SYaroslav Tykhiy 
22984cd51076SYaroslav Tykhiy 			byte_count++;
22994cd51076SYaroslav Tykhiy 			FTPD_PUTC(c, outstr, file_err);
23004cd51076SYaroslav Tykhiy 			cp = c;
2301ea022d16SRodney W. Grimes 		}
23024cd51076SYaroslav Tykhiy #ifdef notyet	/* BSD stdio isn't ready for that */
23034cd51076SYaroslav Tykhiy 		while (fflush(outstr) == EOF) {
23044cd51076SYaroslav Tykhiy 			CHECKOOB(return (-1))
23054cd51076SYaroslav Tykhiy 			else
2306ea022d16SRodney W. Grimes 				goto file_err;
23074cd51076SYaroslav Tykhiy 			clearerr(outstr);
23084cd51076SYaroslav Tykhiy 		}
23094cd51076SYaroslav Tykhiy 		ENDXFER;
23104cd51076SYaroslav Tykhiy #else
23114cd51076SYaroslav Tykhiy 		ENDXFER;
23124cd51076SYaroslav Tykhiy 		if (fflush(outstr) == EOF)
23134cd51076SYaroslav Tykhiy 			goto file_err;
23144cd51076SYaroslav Tykhiy #endif
2315ea022d16SRodney W. Grimes 		if (bare_lfs) {
2316ea022d16SRodney W. Grimes 			lreply(226,
231702c97492SYaroslav Tykhiy 		"WARNING! %d bare linefeeds received in ASCII mode.",
2318ea022d16SRodney W. Grimes 			    bare_lfs);
2319ea022d16SRodney W. Grimes 		(void)printf("   File may not have transferred correctly.\r\n");
2320ea022d16SRodney W. Grimes 		}
2321ea022d16SRodney W. Grimes 		return (0);
2322ea022d16SRodney W. Grimes 	default:
23234cd51076SYaroslav Tykhiy 		ENDXFER;
232402c97492SYaroslav Tykhiy 		reply(550, "Unimplemented TYPE %d in receive_data.", type);
2325ea022d16SRodney W. Grimes 		return (-1);
2326ea022d16SRodney W. Grimes 	}
2327ea022d16SRodney W. Grimes 
2328ea022d16SRodney W. Grimes data_err:
23294cd51076SYaroslav Tykhiy 	ENDXFER;
233002c97492SYaroslav Tykhiy 	perror_reply(426, "Data connection");
2331ea022d16SRodney W. Grimes 	return (-1);
2332ea022d16SRodney W. Grimes 
2333ea022d16SRodney W. Grimes file_err:
23344cd51076SYaroslav Tykhiy 	ENDXFER;
233502c97492SYaroslav Tykhiy 	perror_reply(452, "Error writing to file");
2336ea022d16SRodney W. Grimes 	return (-1);
2337ea022d16SRodney W. Grimes }
2338ea022d16SRodney W. Grimes 
2339ea022d16SRodney W. Grimes void
2340e4bc453cSWarner Losh statfilecmd(char *filename)
2341ea022d16SRodney W. Grimes {
2342ea022d16SRodney W. Grimes 	FILE *fin;
2343f8a581a0SYaroslav Tykhiy 	int atstart;
234441c57b48SYaroslav Tykhiy 	int c, code;
2345ea022d16SRodney W. Grimes 	char line[LINE_MAX];
234641c57b48SYaroslav Tykhiy 	struct stat st;
2347ea022d16SRodney W. Grimes 
234841c57b48SYaroslav Tykhiy 	code = lstat(filename, &st) == 0 && S_ISDIR(st.st_mode) ? 212 : 213;
2349af85d782SDavid Nugent 	(void)snprintf(line, sizeof(line), _PATH_LS " -lgA %s", filename);
2350ea022d16SRodney W. Grimes 	fin = ftpd_popen(line, "r");
2351763e8c96SEd Maste 	if (fin == NULL) {
2352763e8c96SEd Maste 		perror_reply(551, filename);
2353763e8c96SEd Maste 		return;
2354763e8c96SEd Maste 	}
23553b48b877SYaroslav Tykhiy 	lreply(code, "Status of %s:", filename);
2356f8a581a0SYaroslav Tykhiy 	atstart = 1;
2357ea022d16SRodney W. Grimes 	while ((c = getc(fin)) != EOF) {
2358ea022d16SRodney W. Grimes 		if (c == '\n') {
2359ea022d16SRodney W. Grimes 			if (ferror(stdout)){
236002c97492SYaroslav Tykhiy 				perror_reply(421, "Control connection");
2361ea022d16SRodney W. Grimes 				(void) ftpd_pclose(fin);
2362ea022d16SRodney W. Grimes 				dologout(1);
2363ea022d16SRodney W. Grimes 				/* NOTREACHED */
2364ea022d16SRodney W. Grimes 			}
2365ea022d16SRodney W. Grimes 			if (ferror(fin)) {
2366ea022d16SRodney W. Grimes 				perror_reply(551, filename);
2367ea022d16SRodney W. Grimes 				(void) ftpd_pclose(fin);
2368ea022d16SRodney W. Grimes 				return;
2369ea022d16SRodney W. Grimes 			}
2370ea022d16SRodney W. Grimes 			(void) putc('\r', stdout);
2371ea022d16SRodney W. Grimes 		}
2372f8a581a0SYaroslav Tykhiy 		/*
2373f8a581a0SYaroslav Tykhiy 		 * RFC 959 says neutral text should be prepended before
2374f8a581a0SYaroslav Tykhiy 		 * a leading 3-digit number followed by whitespace, but
2375f8a581a0SYaroslav Tykhiy 		 * many ftp clients can be confused by any leading digits,
2376f8a581a0SYaroslav Tykhiy 		 * as a matter of fact.
2377f8a581a0SYaroslav Tykhiy 		 */
2378f8a581a0SYaroslav Tykhiy 		if (atstart && isdigit(c))
2379f8a581a0SYaroslav Tykhiy 			(void) putc(' ', stdout);
2380ea022d16SRodney W. Grimes 		(void) putc(c, stdout);
2381f8a581a0SYaroslav Tykhiy 		atstart = (c == '\n');
2382ea022d16SRodney W. Grimes 	}
2383ea022d16SRodney W. Grimes 	(void) ftpd_pclose(fin);
238402c97492SYaroslav Tykhiy 	reply(code, "End of status.");
2385ea022d16SRodney W. Grimes }
2386ea022d16SRodney W. Grimes 
2387ea022d16SRodney W. Grimes void
2388e4bc453cSWarner Losh statcmd(void)
2389ea022d16SRodney W. Grimes {
23904dd8b5abSYoshinobu Inoue 	union sockunion *su;
2391ea022d16SRodney W. Grimes 	u_char *a, *p;
2392b0f06defSHajimu UMEMOTO 	char hname[NI_MAXHOST];
23934dd8b5abSYoshinobu Inoue 	int ispassive;
2394ea022d16SRodney W. Grimes 
2395c152df28SYaroslav Tykhiy 	if (hostinfo) {
2396a23f61bcSYaroslav Tykhiy 		lreply(211, "%s FTP server status:", hostname);
2397ea022d16SRodney W. Grimes 		printf("     %s\r\n", version);
2398c152df28SYaroslav Tykhiy 	} else
2399c152df28SYaroslav Tykhiy 		lreply(211, "FTP server status:");
2400ea022d16SRodney W. Grimes 	printf("     Connected to %s", remotehost);
24014dd8b5abSYoshinobu Inoue 	if (!getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
2402b0f06defSHajimu UMEMOTO 			 hname, sizeof(hname) - 1, NULL, 0, NI_NUMERICHOST)) {
240304683b2cSYaroslav Tykhiy 		hname[sizeof(hname) - 1] = 0;
24044dd8b5abSYoshinobu Inoue 		if (strcmp(hname, remotehost) != 0)
24054dd8b5abSYoshinobu Inoue 			printf(" (%s)", hname);
24064dd8b5abSYoshinobu Inoue 	}
2407ea022d16SRodney W. Grimes 	printf("\r\n");
2408ea022d16SRodney W. Grimes 	if (logged_in) {
2409ea022d16SRodney W. Grimes 		if (guest)
2410ea022d16SRodney W. Grimes 			printf("     Logged in anonymously\r\n");
2411ea022d16SRodney W. Grimes 		else
2412ea022d16SRodney W. Grimes 			printf("     Logged in as %s\r\n", pw->pw_name);
2413ea022d16SRodney W. Grimes 	} else if (askpasswd)
2414ea022d16SRodney W. Grimes 		printf("     Waiting for password\r\n");
2415ea022d16SRodney W. Grimes 	else
2416ea022d16SRodney W. Grimes 		printf("     Waiting for user name\r\n");
2417ea022d16SRodney W. Grimes 	printf("     TYPE: %s", typenames[type]);
2418ea022d16SRodney W. Grimes 	if (type == TYPE_A || type == TYPE_E)
2419ea022d16SRodney W. Grimes 		printf(", FORM: %s", formnames[form]);
2420ea022d16SRodney W. Grimes 	if (type == TYPE_L)
242189fdc4e1SMike Barcroft #if CHAR_BIT == 8
242289fdc4e1SMike Barcroft 		printf(" %d", CHAR_BIT);
2423ea022d16SRodney W. Grimes #else
2424ea022d16SRodney W. Grimes 		printf(" %d", bytesize);	/* need definition! */
2425ea022d16SRodney W. Grimes #endif
2426ea022d16SRodney W. Grimes 	printf("; STRUcture: %s; transfer MODE: %s\r\n",
2427ea022d16SRodney W. Grimes 	    strunames[stru], modenames[mode]);
2428ea022d16SRodney W. Grimes 	if (data != -1)
2429ea022d16SRodney W. Grimes 		printf("     Data connection open\r\n");
2430ea022d16SRodney W. Grimes 	else if (pdata != -1) {
24314dd8b5abSYoshinobu Inoue 		ispassive = 1;
24324dd8b5abSYoshinobu Inoue 		su = &pasv_addr;
2433ea022d16SRodney W. Grimes 		goto printaddr;
2434ea022d16SRodney W. Grimes 	} else if (usedefault == 0) {
24354dd8b5abSYoshinobu Inoue 		ispassive = 0;
24364dd8b5abSYoshinobu Inoue 		su = &data_dest;
2437ea022d16SRodney W. Grimes printaddr:
2438ea022d16SRodney W. Grimes #define UC(b) (((int) b) & 0xff)
24394dd8b5abSYoshinobu Inoue 		if (epsvall) {
24404dd8b5abSYoshinobu Inoue 			printf("     EPSV only mode (EPSV ALL)\r\n");
24414dd8b5abSYoshinobu Inoue 			goto epsvonly;
24424dd8b5abSYoshinobu Inoue 		}
24434dd8b5abSYoshinobu Inoue 
24444dd8b5abSYoshinobu Inoue 		/* PORT/PASV */
24454dd8b5abSYoshinobu Inoue 		if (su->su_family == AF_INET) {
24464dd8b5abSYoshinobu Inoue 			a = (u_char *) &su->su_sin.sin_addr;
24474dd8b5abSYoshinobu Inoue 			p = (u_char *) &su->su_sin.sin_port;
24484dd8b5abSYoshinobu Inoue 			printf("     %s (%d,%d,%d,%d,%d,%d)\r\n",
24494dd8b5abSYoshinobu Inoue 				ispassive ? "PASV" : "PORT",
24504dd8b5abSYoshinobu Inoue 				UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
24514dd8b5abSYoshinobu Inoue 				UC(p[0]), UC(p[1]));
24524dd8b5abSYoshinobu Inoue 		}
24534dd8b5abSYoshinobu Inoue 
24544dd8b5abSYoshinobu Inoue 		/* LPRT/LPSV */
24554dd8b5abSYoshinobu Inoue 	    {
24564dd8b5abSYoshinobu Inoue 		int alen, af, i;
24574dd8b5abSYoshinobu Inoue 
24584dd8b5abSYoshinobu Inoue 		switch (su->su_family) {
24594dd8b5abSYoshinobu Inoue 		case AF_INET:
24604dd8b5abSYoshinobu Inoue 			a = (u_char *) &su->su_sin.sin_addr;
24614dd8b5abSYoshinobu Inoue 			p = (u_char *) &su->su_sin.sin_port;
24624dd8b5abSYoshinobu Inoue 			alen = sizeof(su->su_sin.sin_addr);
24634dd8b5abSYoshinobu Inoue 			af = 4;
24644dd8b5abSYoshinobu Inoue 			break;
24654dd8b5abSYoshinobu Inoue 		case AF_INET6:
24664dd8b5abSYoshinobu Inoue 			a = (u_char *) &su->su_sin6.sin6_addr;
24674dd8b5abSYoshinobu Inoue 			p = (u_char *) &su->su_sin6.sin6_port;
24684dd8b5abSYoshinobu Inoue 			alen = sizeof(su->su_sin6.sin6_addr);
24694dd8b5abSYoshinobu Inoue 			af = 6;
24704dd8b5abSYoshinobu Inoue 			break;
24714dd8b5abSYoshinobu Inoue 		default:
24724dd8b5abSYoshinobu Inoue 			af = 0;
24734dd8b5abSYoshinobu Inoue 			break;
24744dd8b5abSYoshinobu Inoue 		}
24754dd8b5abSYoshinobu Inoue 		if (af) {
24764dd8b5abSYoshinobu Inoue 			printf("     %s (%d,%d,", ispassive ? "LPSV" : "LPRT",
24774dd8b5abSYoshinobu Inoue 				af, alen);
24784dd8b5abSYoshinobu Inoue 			for (i = 0; i < alen; i++)
24794dd8b5abSYoshinobu Inoue 				printf("%d,", UC(a[i]));
24804dd8b5abSYoshinobu Inoue 			printf("%d,%d,%d)\r\n", 2, UC(p[0]), UC(p[1]));
24814dd8b5abSYoshinobu Inoue 		}
24824dd8b5abSYoshinobu Inoue 	    }
24834dd8b5abSYoshinobu Inoue 
24844dd8b5abSYoshinobu Inoue epsvonly:;
24854dd8b5abSYoshinobu Inoue 		/* EPRT/EPSV */
24864dd8b5abSYoshinobu Inoue 	    {
24874dd8b5abSYoshinobu Inoue 		int af;
24884dd8b5abSYoshinobu Inoue 
24894dd8b5abSYoshinobu Inoue 		switch (su->su_family) {
24904dd8b5abSYoshinobu Inoue 		case AF_INET:
24914dd8b5abSYoshinobu Inoue 			af = 1;
24924dd8b5abSYoshinobu Inoue 			break;
24934dd8b5abSYoshinobu Inoue 		case AF_INET6:
24944dd8b5abSYoshinobu Inoue 			af = 2;
24954dd8b5abSYoshinobu Inoue 			break;
24964dd8b5abSYoshinobu Inoue 		default:
24974dd8b5abSYoshinobu Inoue 			af = 0;
24984dd8b5abSYoshinobu Inoue 			break;
24994dd8b5abSYoshinobu Inoue 		}
25004dd8b5abSYoshinobu Inoue 		if (af) {
2501b0f06defSHajimu UMEMOTO 			union sockunion tmp;
2502b0f06defSHajimu UMEMOTO 
2503b0f06defSHajimu UMEMOTO 			tmp = *su;
2504b0f06defSHajimu UMEMOTO 			if (tmp.su_family == AF_INET6)
2505b0f06defSHajimu UMEMOTO 				tmp.su_sin6.sin6_scope_id = 0;
2506b0f06defSHajimu UMEMOTO 			if (!getnameinfo((struct sockaddr *)&tmp, tmp.su_len,
25074dd8b5abSYoshinobu Inoue 					hname, sizeof(hname) - 1, NULL, 0,
25084dd8b5abSYoshinobu Inoue 					NI_NUMERICHOST)) {
250904683b2cSYaroslav Tykhiy 				hname[sizeof(hname) - 1] = 0;
25104dd8b5abSYoshinobu Inoue 				printf("     %s |%d|%s|%d|\r\n",
25114dd8b5abSYoshinobu Inoue 					ispassive ? "EPSV" : "EPRT",
2512b0f06defSHajimu UMEMOTO 					af, hname, htons(tmp.su_port));
25134dd8b5abSYoshinobu Inoue 			}
25144dd8b5abSYoshinobu Inoue 		}
25154dd8b5abSYoshinobu Inoue 	    }
2516ea022d16SRodney W. Grimes #undef UC
2517ea022d16SRodney W. Grimes 	} else
2518ea022d16SRodney W. Grimes 		printf("     No data connection\r\n");
251902c97492SYaroslav Tykhiy 	reply(211, "End of status.");
2520ea022d16SRodney W. Grimes }
2521ea022d16SRodney W. Grimes 
2522ea022d16SRodney W. Grimes void
2523e4bc453cSWarner Losh fatalerror(char *s)
2524ea022d16SRodney W. Grimes {
2525ea022d16SRodney W. Grimes 
25264a3e5acdSYaroslav Tykhiy 	reply(451, "Error in server: %s", s);
2527ea022d16SRodney W. Grimes 	reply(221, "Closing connection due to server error.");
2528ea022d16SRodney W. Grimes 	dologout(0);
2529ea022d16SRodney W. Grimes 	/* NOTREACHED */
2530ea022d16SRodney W. Grimes }
2531ea022d16SRodney W. Grimes 
2532ea022d16SRodney W. Grimes void
2533ea022d16SRodney W. Grimes reply(int n, const char *fmt, ...)
2534ea022d16SRodney W. Grimes {
2535ea022d16SRodney W. Grimes 	va_list ap;
2536e4bc453cSWarner Losh 
2537ea022d16SRodney W. Grimes 	(void)printf("%d ", n);
25389cbb335cSTim J. Robbins 	va_start(ap, fmt);
2539ea022d16SRodney W. Grimes 	(void)vprintf(fmt, ap);
25409cbb335cSTim J. Robbins 	va_end(ap);
2541ea022d16SRodney W. Grimes 	(void)printf("\r\n");
2542ea022d16SRodney W. Grimes 	(void)fflush(stdout);
2543618b0bbaSMark Murray 	if (ftpdebug) {
2544ea022d16SRodney W. Grimes 		syslog(LOG_DEBUG, "<--- %d ", n);
25459cbb335cSTim J. Robbins 		va_start(ap, fmt);
2546ea022d16SRodney W. Grimes 		vsyslog(LOG_DEBUG, fmt, ap);
25479cbb335cSTim J. Robbins 		va_end(ap);
2548ea022d16SRodney W. Grimes 	}
2549ea022d16SRodney W. Grimes }
2550ea022d16SRodney W. Grimes 
2551ea022d16SRodney W. Grimes void
2552ea022d16SRodney W. Grimes lreply(int n, const char *fmt, ...)
2553ea022d16SRodney W. Grimes {
2554ea022d16SRodney W. Grimes 	va_list ap;
2555e4bc453cSWarner Losh 
2556ea022d16SRodney W. Grimes 	(void)printf("%d- ", n);
25579cbb335cSTim J. Robbins 	va_start(ap, fmt);
2558ea022d16SRodney W. Grimes 	(void)vprintf(fmt, ap);
25599cbb335cSTim J. Robbins 	va_end(ap);
2560ea022d16SRodney W. Grimes 	(void)printf("\r\n");
2561ea022d16SRodney W. Grimes 	(void)fflush(stdout);
2562618b0bbaSMark Murray 	if (ftpdebug) {
2563ea022d16SRodney W. Grimes 		syslog(LOG_DEBUG, "<--- %d- ", n);
25649cbb335cSTim J. Robbins 		va_start(ap, fmt);
2565ea022d16SRodney W. Grimes 		vsyslog(LOG_DEBUG, fmt, ap);
25669cbb335cSTim J. Robbins 		va_end(ap);
2567ea022d16SRodney W. Grimes 	}
2568ea022d16SRodney W. Grimes }
2569ea022d16SRodney W. Grimes 
2570ea022d16SRodney W. Grimes static void
2571e4bc453cSWarner Losh ack(char *s)
2572ea022d16SRodney W. Grimes {
2573ea022d16SRodney W. Grimes 
2574ea022d16SRodney W. Grimes 	reply(250, "%s command successful.", s);
2575ea022d16SRodney W. Grimes }
2576ea022d16SRodney W. Grimes 
2577ea022d16SRodney W. Grimes void
2578e4bc453cSWarner Losh nack(char *s)
2579ea022d16SRodney W. Grimes {
2580ea022d16SRodney W. Grimes 
2581ea022d16SRodney W. Grimes 	reply(502, "%s command not implemented.", s);
2582ea022d16SRodney W. Grimes }
2583ea022d16SRodney W. Grimes 
2584ea022d16SRodney W. Grimes /* ARGSUSED */
2585ea022d16SRodney W. Grimes void
2586e4bc453cSWarner Losh yyerror(char *s)
2587ea022d16SRodney W. Grimes {
2588ea022d16SRodney W. Grimes 	char *cp;
2589ea022d16SRodney W. Grimes 
25909aca17cbSMark Murray 	if ((cp = strchr(cbuf,'\n')))
2591ea022d16SRodney W. Grimes 		*cp = '\0';
259202c97492SYaroslav Tykhiy 	reply(500, "%s: command not understood.", cbuf);
2593ea022d16SRodney W. Grimes }
2594ea022d16SRodney W. Grimes 
2595ea022d16SRodney W. Grimes void
2596e4bc453cSWarner Losh delete(char *name)
2597ea022d16SRodney W. Grimes {
2598ea022d16SRodney W. Grimes 	struct stat st;
2599ea022d16SRodney W. Grimes 
2600ea022d16SRodney W. Grimes 	LOGCMD("delete", name);
26011b0e12d7SYaroslav Tykhiy 	if (lstat(name, &st) < 0) {
2602ea022d16SRodney W. Grimes 		perror_reply(550, name);
2603ea022d16SRodney W. Grimes 		return;
2604ea022d16SRodney W. Grimes 	}
2605ac4f2391SYaroslav Tykhiy 	if (S_ISDIR(st.st_mode)) {
2606ea022d16SRodney W. Grimes 		if (rmdir(name) < 0) {
2607ea022d16SRodney W. Grimes 			perror_reply(550, name);
2608ea022d16SRodney W. Grimes 			return;
2609ea022d16SRodney W. Grimes 		}
2610ea022d16SRodney W. Grimes 		goto done;
2611ea022d16SRodney W. Grimes 	}
26123f8b9cfeSYaroslav Tykhiy 	if (guest && noguestmod) {
261302c97492SYaroslav Tykhiy 		reply(550, "Operation not permitted.");
26143f8b9cfeSYaroslav Tykhiy 		return;
26153f8b9cfeSYaroslav Tykhiy 	}
26163f8b9cfeSYaroslav Tykhiy 	if (unlink(name) < 0) {
2617ea022d16SRodney W. Grimes 		perror_reply(550, name);
2618ea022d16SRodney W. Grimes 		return;
2619ea022d16SRodney W. Grimes 	}
2620ea022d16SRodney W. Grimes done:
2621ea022d16SRodney W. Grimes 	ack("DELE");
2622ea022d16SRodney W. Grimes }
2623ea022d16SRodney W. Grimes 
2624ea022d16SRodney W. Grimes void
2625e4bc453cSWarner Losh cwd(char *path)
2626ea022d16SRodney W. Grimes {
2627ea022d16SRodney W. Grimes 
2628ea022d16SRodney W. Grimes 	if (chdir(path) < 0)
2629ea022d16SRodney W. Grimes 		perror_reply(550, path);
2630ea022d16SRodney W. Grimes 	else
2631ea022d16SRodney W. Grimes 		ack("CWD");
2632ea022d16SRodney W. Grimes }
2633ea022d16SRodney W. Grimes 
2634ea022d16SRodney W. Grimes void
2635e4bc453cSWarner Losh makedir(char *name)
2636ea022d16SRodney W. Grimes {
26372b748987SYaroslav Tykhiy 	char *s;
2638ea022d16SRodney W. Grimes 
2639ea022d16SRodney W. Grimes 	LOGCMD("mkdir", name);
2640d186bb12SMatthew N. Dodd 	if (guest && noguestmkd)
2641405e2987SYaroslav Tykhiy 		reply(550, "Operation not permitted.");
2642d186bb12SMatthew N. Dodd 	else if (mkdir(name, 0777) < 0)
2643ea022d16SRodney W. Grimes 		perror_reply(550, name);
26442b748987SYaroslav Tykhiy 	else {
26452b748987SYaroslav Tykhiy 		if ((s = doublequote(name)) == NULL)
26462b748987SYaroslav Tykhiy 			fatalerror("Ran out of memory.");
26472b748987SYaroslav Tykhiy 		reply(257, "\"%s\" directory created.", s);
26482b748987SYaroslav Tykhiy 		free(s);
26492b748987SYaroslav Tykhiy 	}
2650ea022d16SRodney W. Grimes }
2651ea022d16SRodney W. Grimes 
2652ea022d16SRodney W. Grimes void
2653e4bc453cSWarner Losh removedir(char *name)
2654ea022d16SRodney W. Grimes {
2655ea022d16SRodney W. Grimes 
2656ea022d16SRodney W. Grimes 	LOGCMD("rmdir", name);
2657ea022d16SRodney W. Grimes 	if (rmdir(name) < 0)
2658ea022d16SRodney W. Grimes 		perror_reply(550, name);
2659ea022d16SRodney W. Grimes 	else
2660ea022d16SRodney W. Grimes 		ack("RMD");
2661ea022d16SRodney W. Grimes }
2662ea022d16SRodney W. Grimes 
2663ea022d16SRodney W. Grimes void
2664e4bc453cSWarner Losh pwd(void)
2665ea022d16SRodney W. Grimes {
2666e4648f05SYaroslav Tykhiy 	char *s, path[MAXPATHLEN + 1];
2667ea022d16SRodney W. Grimes 
2668de9b6c03SYaroslav Tykhiy 	if (getcwd(path, sizeof(path)) == NULL)
266975933089SYaroslav Tykhiy 		perror_reply(550, "Get current directory");
2670e4648f05SYaroslav Tykhiy 	else {
2671e4648f05SYaroslav Tykhiy 		if ((s = doublequote(path)) == NULL)
2672e4648f05SYaroslav Tykhiy 			fatalerror("Ran out of memory.");
2673e4648f05SYaroslav Tykhiy 		reply(257, "\"%s\" is current directory.", s);
2674e4648f05SYaroslav Tykhiy 		free(s);
2675e4648f05SYaroslav Tykhiy 	}
2676ea022d16SRodney W. Grimes }
2677ea022d16SRodney W. Grimes 
2678ea022d16SRodney W. Grimes char *
2679e4bc453cSWarner Losh renamefrom(char *name)
2680ea022d16SRodney W. Grimes {
2681ea022d16SRodney W. Grimes 	struct stat st;
2682ea022d16SRodney W. Grimes 
2683b943b3c4SYaroslav Tykhiy 	if (guest && noguestmod) {
268402c97492SYaroslav Tykhiy 		reply(550, "Operation not permitted.");
2685b943b3c4SYaroslav Tykhiy 		return (NULL);
2686b943b3c4SYaroslav Tykhiy 	}
26871b0e12d7SYaroslav Tykhiy 	if (lstat(name, &st) < 0) {
2688ea022d16SRodney W. Grimes 		perror_reply(550, name);
2689385f9bf0SYaroslav Tykhiy 		return (NULL);
2690ea022d16SRodney W. Grimes 	}
269102c97492SYaroslav Tykhiy 	reply(350, "File exists, ready for destination name.");
2692ea022d16SRodney W. Grimes 	return (name);
2693ea022d16SRodney W. Grimes }
2694ea022d16SRodney W. Grimes 
2695ea022d16SRodney W. Grimes void
2696e4bc453cSWarner Losh renamecmd(char *from, char *to)
2697ea022d16SRodney W. Grimes {
269861f891a6SPaul Traina 	struct stat st;
2699ea022d16SRodney W. Grimes 
2700ea022d16SRodney W. Grimes 	LOGCMD2("rename", from, to);
270161f891a6SPaul Traina 
270261f891a6SPaul Traina 	if (guest && (stat(to, &st) == 0)) {
270302c97492SYaroslav Tykhiy 		reply(550, "%s: permission denied.", to);
270461f891a6SPaul Traina 		return;
270561f891a6SPaul Traina 	}
270661f891a6SPaul Traina 
2707ea022d16SRodney W. Grimes 	if (rename(from, to) < 0)
2708ea022d16SRodney W. Grimes 		perror_reply(550, "rename");
2709ea022d16SRodney W. Grimes 	else
2710ea022d16SRodney W. Grimes 		ack("RNTO");
2711ea022d16SRodney W. Grimes }
2712ea022d16SRodney W. Grimes 
2713ea022d16SRodney W. Grimes static void
2714e4bc453cSWarner Losh dolog(struct sockaddr *who)
2715ea022d16SRodney W. Grimes {
27167cdd3cb7SYaroslav Tykhiy 	char who_name[NI_MAXHOST];
27174dd8b5abSYoshinobu Inoue 
27184dd8b5abSYoshinobu Inoue 	realhostname_sa(remotehost, sizeof(remotehost) - 1, who, who->sa_len);
271904683b2cSYaroslav Tykhiy 	remotehost[sizeof(remotehost) - 1] = 0;
27207cdd3cb7SYaroslav Tykhiy 	if (getnameinfo(who, who->sa_len,
27217cdd3cb7SYaroslav Tykhiy 		who_name, sizeof(who_name) - 1, NULL, 0, NI_NUMERICHOST))
27227cdd3cb7SYaroslav Tykhiy 			*who_name = 0;
27237cdd3cb7SYaroslav Tykhiy 	who_name[sizeof(who_name) - 1] = 0;
2724ea022d16SRodney W. Grimes 
2725ea022d16SRodney W. Grimes #ifdef SETPROCTITLE
2726ea4e54b9SDavid Nugent #ifdef VIRTUAL_HOSTING
2727ea4e54b9SDavid Nugent 	if (thishost != firsthost)
2728ea4e54b9SDavid Nugent 		snprintf(proctitle, sizeof(proctitle), "%s: connected (to %s)",
2729ea4e54b9SDavid Nugent 			 remotehost, hostname);
2730ea4e54b9SDavid Nugent 	else
2731ea4e54b9SDavid Nugent #endif
2732ea4e54b9SDavid Nugent 		snprintf(proctitle, sizeof(proctitle), "%s: connected",
2733ea4e54b9SDavid Nugent 			 remotehost);
2734b63e1fe2SPeter Wemm 	setproctitle("%s", proctitle);
2735ea022d16SRodney W. Grimes #endif /* SETPROCTITLE */
2736ea022d16SRodney W. Grimes 
2737ea4e54b9SDavid Nugent 	if (logging) {
2738ea4e54b9SDavid Nugent #ifdef VIRTUAL_HOSTING
2739ea4e54b9SDavid Nugent 		if (thishost != firsthost)
27407cdd3cb7SYaroslav Tykhiy 			syslog(LOG_INFO, "connection from %s (%s) to %s",
27417cdd3cb7SYaroslav Tykhiy 			       remotehost, who_name, hostname);
2742ea4e54b9SDavid Nugent 		else
2743ea4e54b9SDavid Nugent #endif
27447cdd3cb7SYaroslav Tykhiy 			syslog(LOG_INFO, "connection from %s (%s)",
27457cdd3cb7SYaroslav Tykhiy 			       remotehost, who_name);
2746ea022d16SRodney W. Grimes 	}
2747ea4e54b9SDavid Nugent }
2748ea022d16SRodney W. Grimes 
2749ea022d16SRodney W. Grimes /*
2750ea022d16SRodney W. Grimes  * Record logout in wtmp file
2751ea022d16SRodney W. Grimes  * and exit with supplied status.
2752ea022d16SRodney W. Grimes  */
2753ea022d16SRodney W. Grimes void
2754e4bc453cSWarner Losh dologout(int status)
2755ea022d16SRodney W. Grimes {
2756ea022d16SRodney W. Grimes 
27579f37b1a2SEd Schouten 	if (logged_in && dowtmp) {
275852e7ee74SYaroslav Tykhiy 		(void) seteuid(0);
27599f37b1a2SEd Schouten 		ftpd_logwtmp(wtmpid, NULL, NULL);
2760ea022d16SRodney W. Grimes 	}
2761ea022d16SRodney W. Grimes 	/* beware of flushing buffers after a SIGPIPE */
2762ea022d16SRodney W. Grimes 	_exit(status);
2763ea022d16SRodney W. Grimes }
2764ea022d16SRodney W. Grimes 
2765ea022d16SRodney W. Grimes static void
2766e4bc453cSWarner Losh sigurg(int signo)
2767ea022d16SRodney W. Grimes {
27684b82fc95SYaroslav Tykhiy 
27694b82fc95SYaroslav Tykhiy 	recvurg = 1;
27704b82fc95SYaroslav Tykhiy }
27714b82fc95SYaroslav Tykhiy 
27724b82fc95SYaroslav Tykhiy static void
27734cd51076SYaroslav Tykhiy maskurg(int flag)
27744cd51076SYaroslav Tykhiy {
27754cd51076SYaroslav Tykhiy 	int oerrno;
27764cd51076SYaroslav Tykhiy 	sigset_t sset;
27774cd51076SYaroslav Tykhiy 
27784cd51076SYaroslav Tykhiy 	if (!transflag) {
27794cd51076SYaroslav Tykhiy 		syslog(LOG_ERR, "Internal: maskurg() while no transfer");
27804cd51076SYaroslav Tykhiy 		return;
27814cd51076SYaroslav Tykhiy 	}
27824cd51076SYaroslav Tykhiy 	oerrno = errno;
27834cd51076SYaroslav Tykhiy 	sigemptyset(&sset);
27844cd51076SYaroslav Tykhiy 	sigaddset(&sset, SIGURG);
27854cd51076SYaroslav Tykhiy 	sigprocmask(flag ? SIG_BLOCK : SIG_UNBLOCK, &sset, NULL);
27864cd51076SYaroslav Tykhiy 	errno = oerrno;
27874cd51076SYaroslav Tykhiy }
27884cd51076SYaroslav Tykhiy 
27894cd51076SYaroslav Tykhiy static void
27904cd51076SYaroslav Tykhiy flagxfer(int flag)
27914cd51076SYaroslav Tykhiy {
27924cd51076SYaroslav Tykhiy 
27934cd51076SYaroslav Tykhiy 	if (flag) {
2794f9036ce6SYaroslav Tykhiy 		if (transflag)
2795f9036ce6SYaroslav Tykhiy 			syslog(LOG_ERR, "Internal: flagxfer(1): "
2796f9036ce6SYaroslav Tykhiy 					"transfer already under way");
27974cd51076SYaroslav Tykhiy 		transflag = 1;
279891ae7779SYaroslav Tykhiy 		maskurg(0);
279991ae7779SYaroslav Tykhiy 		recvurg = 0;
280091ae7779SYaroslav Tykhiy 	} else {
2801f9036ce6SYaroslav Tykhiy 		if (!transflag)
2802f9036ce6SYaroslav Tykhiy 			syslog(LOG_ERR, "Internal: flagxfer(0): "
2803f9036ce6SYaroslav Tykhiy 					"no active transfer");
280491ae7779SYaroslav Tykhiy 		maskurg(1);
28054cd51076SYaroslav Tykhiy 		transflag = 0;
28064cd51076SYaroslav Tykhiy 	}
280791ae7779SYaroslav Tykhiy }
28084cd51076SYaroslav Tykhiy 
28094cd51076SYaroslav Tykhiy /*
28104cd51076SYaroslav Tykhiy  * Returns 0 if OK to resume or -1 if abort requested.
28114cd51076SYaroslav Tykhiy  */
28124cd51076SYaroslav Tykhiy static int
2813e4bc453cSWarner Losh myoob(void)
28144b82fc95SYaroslav Tykhiy {
2815ea022d16SRodney W. Grimes 	char *cp;
2816f0b40b1cSColin Percival 	int ret;
2817ea022d16SRodney W. Grimes 
28184cd51076SYaroslav Tykhiy 	if (!transflag) {
28194cd51076SYaroslav Tykhiy 		syslog(LOG_ERR, "Internal: myoob() while no transfer");
28204cd51076SYaroslav Tykhiy 		return (0);
28214cd51076SYaroslav Tykhiy 	}
2822ea022d16SRodney W. Grimes 	cp = tmpline;
2823f0b40b1cSColin Percival 	ret = getline(cp, 7, stdin);
2824f0b40b1cSColin Percival 	if (ret == -1) {
2825ea022d16SRodney W. Grimes 		reply(221, "You could at least say goodbye.");
2826ea022d16SRodney W. Grimes 		dologout(0);
2827f0b40b1cSColin Percival 	} else if (ret == -2) {
2828f0b40b1cSColin Percival 		/* Ignore truncated command. */
2829f0b40b1cSColin Percival 		return (0);
2830ea022d16SRodney W. Grimes 	}
2831ea022d16SRodney W. Grimes 	upper(cp);
2832ea022d16SRodney W. Grimes 	if (strcmp(cp, "ABOR\r\n") == 0) {
2833ea022d16SRodney W. Grimes 		tmpline[0] = '\0';
2834ea022d16SRodney W. Grimes 		reply(426, "Transfer aborted. Data connection closed.");
283502c97492SYaroslav Tykhiy 		reply(226, "Abort successful.");
28364cd51076SYaroslav Tykhiy 		return (-1);
2837ea022d16SRodney W. Grimes 	}
2838ea022d16SRodney W. Grimes 	if (strcmp(cp, "STAT\r\n") == 0) {
28399db4bbf3SMichael Haro 		tmpline[0] = '\0';
28400e519c96SYaroslav Tykhiy 		if (file_size != -1)
284102c97492SYaroslav Tykhiy 			reply(213, "Status: %jd of %jd bytes transferred.",
2842a57e1ef0SYaroslav Tykhiy 				   (intmax_t)byte_count, (intmax_t)file_size);
2843ea022d16SRodney W. Grimes 		else
284402c97492SYaroslav Tykhiy 			reply(213, "Status: %jd bytes transferred.",
2845a57e1ef0SYaroslav Tykhiy 				   (intmax_t)byte_count);
2846ea022d16SRodney W. Grimes 	}
28474cd51076SYaroslav Tykhiy 	return (0);
2848ea022d16SRodney W. Grimes }
2849ea022d16SRodney W. Grimes 
2850ea022d16SRodney W. Grimes /*
2851ea022d16SRodney W. Grimes  * Note: a response of 425 is not mentioned as a possible response to
2852ea022d16SRodney W. Grimes  *	the PASV command in RFC959. However, it has been blessed as
2853ea022d16SRodney W. Grimes  *	a legitimate response by Jon Postel in a telephone conversation
2854ea022d16SRodney W. Grimes  *	with Rick Adams on 25 Jan 89.
2855ea022d16SRodney W. Grimes  */
2856ea022d16SRodney W. Grimes void
2857e4bc453cSWarner Losh passive(void)
2858ea022d16SRodney W. Grimes {
285978e3eed0SStefan Farfeleder 	socklen_t len;
286078e3eed0SStefan Farfeleder 	int on;
2861ea022d16SRodney W. Grimes 	char *p, *a;
2862ea022d16SRodney W. Grimes 
286361f891a6SPaul Traina 	if (pdata >= 0)		/* close old port if one set */
286461f891a6SPaul Traina 		close(pdata);
286561f891a6SPaul Traina 
28664dd8b5abSYoshinobu Inoue 	pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2867ea022d16SRodney W. Grimes 	if (pdata < 0) {
2868ea022d16SRodney W. Grimes 		perror_reply(425, "Can't open passive connection");
2869ea022d16SRodney W. Grimes 		return;
2870ea022d16SRodney W. Grimes 	}
28718af7c9a3SYaroslav Tykhiy 	on = 1;
28728af7c9a3SYaroslav Tykhiy 	if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
28738af7c9a3SYaroslav Tykhiy 		syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
28744c450ad7SPaul Traina 
287552e7ee74SYaroslav Tykhiy 	(void) seteuid(0);
287661f891a6SPaul Traina 
2877dacc9752SPaul Traina #ifdef IP_PORTRANGE
28784dd8b5abSYoshinobu Inoue 	if (ctrl_addr.su_family == AF_INET) {
28798af7c9a3SYaroslav Tykhiy 	    on = restricted_data_ports ? IP_PORTRANGE_HIGH
2880dacc9752SPaul Traina 				       : IP_PORTRANGE_DEFAULT;
2881dacc9752SPaul Traina 
288240e9d39eSPeter Wemm 	    if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
288357d4ef07SYaroslav Tykhiy 			    &on, sizeof(on)) < 0)
28844c450ad7SPaul Traina 		    goto pasv_error;
28854c450ad7SPaul Traina 	}
2886dacc9752SPaul Traina #endif
28872db39860SNick Sayer #ifdef IPV6_PORTRANGE
28882db39860SNick Sayer 	if (ctrl_addr.su_family == AF_INET6) {
28898af7c9a3SYaroslav Tykhiy 	    on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
28902db39860SNick Sayer 				       : IPV6_PORTRANGE_DEFAULT;
28912db39860SNick Sayer 
28922db39860SNick Sayer 	    if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
289357d4ef07SYaroslav Tykhiy 			    &on, sizeof(on)) < 0)
28942db39860SNick Sayer 		    goto pasv_error;
28952db39860SNick Sayer 	}
28962db39860SNick Sayer #endif
289740e9d39eSPeter Wemm 
2898ea022d16SRodney W. Grimes 	pasv_addr = ctrl_addr;
28994dd8b5abSYoshinobu Inoue 	pasv_addr.su_port = 0;
29004dd8b5abSYoshinobu Inoue 	if (bind(pdata, (struct sockaddr *)&pasv_addr, pasv_addr.su_len) < 0)
2901ea022d16SRodney W. Grimes 		goto pasv_error;
290261f891a6SPaul Traina 
290352e7ee74SYaroslav Tykhiy 	(void) seteuid(pw->pw_uid);
29044c450ad7SPaul Traina 
2905ea022d16SRodney W. Grimes 	len = sizeof(pasv_addr);
2906ea022d16SRodney W. Grimes 	if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2907ea022d16SRodney W. Grimes 		goto pasv_error;
2908ea022d16SRodney W. Grimes 	if (listen(pdata, 1) < 0)
2909ea022d16SRodney W. Grimes 		goto pasv_error;
29104dd8b5abSYoshinobu Inoue 	if (pasv_addr.su_family == AF_INET)
29114dd8b5abSYoshinobu Inoue 		a = (char *) &pasv_addr.su_sin.sin_addr;
29124dd8b5abSYoshinobu Inoue 	else if (pasv_addr.su_family == AF_INET6 &&
29134dd8b5abSYoshinobu Inoue 		 IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr))
29144dd8b5abSYoshinobu Inoue 		a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
29154dd8b5abSYoshinobu Inoue 	else
29164dd8b5abSYoshinobu Inoue 		goto pasv_error;
29174dd8b5abSYoshinobu Inoue 
29184dd8b5abSYoshinobu Inoue 	p = (char *) &pasv_addr.su_port;
2919ea022d16SRodney W. Grimes 
2920ea022d16SRodney W. Grimes #define UC(b) (((int) b) & 0xff)
2921ea022d16SRodney W. Grimes 
2922ea022d16SRodney W. Grimes 	reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
2923ea022d16SRodney W. Grimes 		UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
2924ea022d16SRodney W. Grimes 	return;
2925ea022d16SRodney W. Grimes 
2926ea022d16SRodney W. Grimes pasv_error:
292752e7ee74SYaroslav Tykhiy 	(void) seteuid(pw->pw_uid);
2928ea022d16SRodney W. Grimes 	(void) close(pdata);
2929ea022d16SRodney W. Grimes 	pdata = -1;
2930ea022d16SRodney W. Grimes 	perror_reply(425, "Can't open passive connection");
2931ea022d16SRodney W. Grimes 	return;
2932ea022d16SRodney W. Grimes }
2933ea022d16SRodney W. Grimes 
2934ea022d16SRodney W. Grimes /*
29354dd8b5abSYoshinobu Inoue  * Long Passive defined in RFC 1639.
29364dd8b5abSYoshinobu Inoue  *     228 Entering Long Passive Mode
29374dd8b5abSYoshinobu Inoue  *         (af, hal, h1, h2, h3,..., pal, p1, p2...)
29384dd8b5abSYoshinobu Inoue  */
29394dd8b5abSYoshinobu Inoue 
29404dd8b5abSYoshinobu Inoue void
2941e4bc453cSWarner Losh long_passive(char *cmd, int pf)
29424dd8b5abSYoshinobu Inoue {
294378e3eed0SStefan Farfeleder 	socklen_t len;
294478e3eed0SStefan Farfeleder 	int on;
29454dd8b5abSYoshinobu Inoue 	char *p, *a;
29464dd8b5abSYoshinobu Inoue 
29474dd8b5abSYoshinobu Inoue 	if (pdata >= 0)		/* close old port if one set */
29484dd8b5abSYoshinobu Inoue 		close(pdata);
29494dd8b5abSYoshinobu Inoue 
29504dd8b5abSYoshinobu Inoue 	if (pf != PF_UNSPEC) {
29514dd8b5abSYoshinobu Inoue 		if (ctrl_addr.su_family != pf) {
29524dd8b5abSYoshinobu Inoue 			switch (ctrl_addr.su_family) {
29534dd8b5abSYoshinobu Inoue 			case AF_INET:
29544dd8b5abSYoshinobu Inoue 				pf = 1;
29554dd8b5abSYoshinobu Inoue 				break;
29564dd8b5abSYoshinobu Inoue 			case AF_INET6:
29574dd8b5abSYoshinobu Inoue 				pf = 2;
29584dd8b5abSYoshinobu Inoue 				break;
29594dd8b5abSYoshinobu Inoue 			default:
29604dd8b5abSYoshinobu Inoue 				pf = 0;
29614dd8b5abSYoshinobu Inoue 				break;
29624dd8b5abSYoshinobu Inoue 			}
29634dd8b5abSYoshinobu Inoue 			/*
29644dd8b5abSYoshinobu Inoue 			 * XXX
29654dd8b5abSYoshinobu Inoue 			 * only EPRT/EPSV ready clients will understand this
29664dd8b5abSYoshinobu Inoue 			 */
29674dd8b5abSYoshinobu Inoue 			if (strcmp(cmd, "EPSV") == 0 && pf) {
29684dd8b5abSYoshinobu Inoue 				reply(522, "Network protocol mismatch, "
29694dd8b5abSYoshinobu Inoue 					"use (%d)", pf);
29704dd8b5abSYoshinobu Inoue 			} else
297102c97492SYaroslav Tykhiy 				reply(501, "Network protocol mismatch."); /*XXX*/
29724dd8b5abSYoshinobu Inoue 
29734dd8b5abSYoshinobu Inoue 			return;
29744dd8b5abSYoshinobu Inoue 		}
29754dd8b5abSYoshinobu Inoue 	}
29764dd8b5abSYoshinobu Inoue 
29774dd8b5abSYoshinobu Inoue 	pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
29784dd8b5abSYoshinobu Inoue 	if (pdata < 0) {
29794dd8b5abSYoshinobu Inoue 		perror_reply(425, "Can't open passive connection");
29804dd8b5abSYoshinobu Inoue 		return;
29814dd8b5abSYoshinobu Inoue 	}
29828af7c9a3SYaroslav Tykhiy 	on = 1;
29838af7c9a3SYaroslav Tykhiy 	if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
29848af7c9a3SYaroslav Tykhiy 		syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
29854dd8b5abSYoshinobu Inoue 
298652e7ee74SYaroslav Tykhiy 	(void) seteuid(0);
29874dd8b5abSYoshinobu Inoue 
29884dd8b5abSYoshinobu Inoue 	pasv_addr = ctrl_addr;
29894dd8b5abSYoshinobu Inoue 	pasv_addr.su_port = 0;
29904dd8b5abSYoshinobu Inoue 	len = pasv_addr.su_len;
29914dd8b5abSYoshinobu Inoue 
29922db39860SNick Sayer #ifdef IP_PORTRANGE
29932db39860SNick Sayer 	if (ctrl_addr.su_family == AF_INET) {
29948af7c9a3SYaroslav Tykhiy 	    on = restricted_data_ports ? IP_PORTRANGE_HIGH
29952db39860SNick Sayer 				       : IP_PORTRANGE_DEFAULT;
29962db39860SNick Sayer 
29972db39860SNick Sayer 	    if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
299857d4ef07SYaroslav Tykhiy 			    &on, sizeof(on)) < 0)
29992db39860SNick Sayer 		    goto pasv_error;
30002db39860SNick Sayer 	}
30012db39860SNick Sayer #endif
30022db39860SNick Sayer #ifdef IPV6_PORTRANGE
30032db39860SNick Sayer 	if (ctrl_addr.su_family == AF_INET6) {
30048af7c9a3SYaroslav Tykhiy 	    on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
30052db39860SNick Sayer 				       : IPV6_PORTRANGE_DEFAULT;
30062db39860SNick Sayer 
30072db39860SNick Sayer 	    if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
300857d4ef07SYaroslav Tykhiy 			    &on, sizeof(on)) < 0)
30092db39860SNick Sayer 		    goto pasv_error;
30102db39860SNick Sayer 	}
30112db39860SNick Sayer #endif
30122db39860SNick Sayer 
30134dd8b5abSYoshinobu Inoue 	if (bind(pdata, (struct sockaddr *)&pasv_addr, len) < 0)
30144dd8b5abSYoshinobu Inoue 		goto pasv_error;
30154dd8b5abSYoshinobu Inoue 
301652e7ee74SYaroslav Tykhiy 	(void) seteuid(pw->pw_uid);
30174dd8b5abSYoshinobu Inoue 
30184dd8b5abSYoshinobu Inoue 	if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
30194dd8b5abSYoshinobu Inoue 		goto pasv_error;
30204dd8b5abSYoshinobu Inoue 	if (listen(pdata, 1) < 0)
30214dd8b5abSYoshinobu Inoue 		goto pasv_error;
30224dd8b5abSYoshinobu Inoue 
30234dd8b5abSYoshinobu Inoue #define UC(b) (((int) b) & 0xff)
30244dd8b5abSYoshinobu Inoue 
30254dd8b5abSYoshinobu Inoue 	if (strcmp(cmd, "LPSV") == 0) {
30264dd8b5abSYoshinobu Inoue 		p = (char *)&pasv_addr.su_port;
30274dd8b5abSYoshinobu Inoue 		switch (pasv_addr.su_family) {
30284dd8b5abSYoshinobu Inoue 		case AF_INET:
30294dd8b5abSYoshinobu Inoue 			a = (char *) &pasv_addr.su_sin.sin_addr;
30304dd8b5abSYoshinobu Inoue 		v4_reply:
30314dd8b5abSYoshinobu Inoue 			reply(228,
30324dd8b5abSYoshinobu Inoue "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)",
30334dd8b5abSYoshinobu Inoue 			      4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
30344dd8b5abSYoshinobu Inoue 			      2, UC(p[0]), UC(p[1]));
30354dd8b5abSYoshinobu Inoue 			return;
30364dd8b5abSYoshinobu Inoue 		case AF_INET6:
30374dd8b5abSYoshinobu Inoue 			if (IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr)) {
30384dd8b5abSYoshinobu Inoue 				a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
30394dd8b5abSYoshinobu Inoue 				goto v4_reply;
30404dd8b5abSYoshinobu Inoue 			}
30414dd8b5abSYoshinobu Inoue 			a = (char *) &pasv_addr.su_sin6.sin6_addr;
30424dd8b5abSYoshinobu Inoue 			reply(228,
30434dd8b5abSYoshinobu Inoue "Entering Long Passive Mode "
30444dd8b5abSYoshinobu Inoue "(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)",
30454dd8b5abSYoshinobu Inoue 			      6, 16, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
30464dd8b5abSYoshinobu Inoue 			      UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]),
30474dd8b5abSYoshinobu Inoue 			      UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]),
30484dd8b5abSYoshinobu Inoue 			      UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]),
30494dd8b5abSYoshinobu Inoue 			      2, UC(p[0]), UC(p[1]));
30504dd8b5abSYoshinobu Inoue 			return;
30514dd8b5abSYoshinobu Inoue 		}
30524dd8b5abSYoshinobu Inoue 	} else if (strcmp(cmd, "EPSV") == 0) {
30534dd8b5abSYoshinobu Inoue 		switch (pasv_addr.su_family) {
30544dd8b5abSYoshinobu Inoue 		case AF_INET:
30554dd8b5abSYoshinobu Inoue 		case AF_INET6:
30564dd8b5abSYoshinobu Inoue 			reply(229, "Entering Extended Passive Mode (|||%d|)",
30574dd8b5abSYoshinobu Inoue 				ntohs(pasv_addr.su_port));
30584dd8b5abSYoshinobu Inoue 			return;
30594dd8b5abSYoshinobu Inoue 		}
30604dd8b5abSYoshinobu Inoue 	} else {
30614dd8b5abSYoshinobu Inoue 		/* more proper error code? */
30624dd8b5abSYoshinobu Inoue 	}
30634dd8b5abSYoshinobu Inoue 
30644dd8b5abSYoshinobu Inoue pasv_error:
306552e7ee74SYaroslav Tykhiy 	(void) seteuid(pw->pw_uid);
30664dd8b5abSYoshinobu Inoue 	(void) close(pdata);
30674dd8b5abSYoshinobu Inoue 	pdata = -1;
30684dd8b5abSYoshinobu Inoue 	perror_reply(425, "Can't open passive connection");
30694dd8b5abSYoshinobu Inoue 	return;
30704dd8b5abSYoshinobu Inoue }
30714dd8b5abSYoshinobu Inoue 
30724dd8b5abSYoshinobu Inoue /*
3073a117c345SYaroslav Tykhiy  * Generate unique name for file with basename "local"
3074a117c345SYaroslav Tykhiy  * and open the file in order to avoid possible races.
3075a117c345SYaroslav Tykhiy  * Try "local" first, then "local.1", "local.2" etc, up to "local.99".
3076a117c345SYaroslav Tykhiy  * Return descriptor to the file, set "name" to its name.
3077a117c345SYaroslav Tykhiy  *
3078ea022d16SRodney W. Grimes  * Generates failure reply on error.
3079ea022d16SRodney W. Grimes  */
3080a117c345SYaroslav Tykhiy static int
3081a117c345SYaroslav Tykhiy guniquefd(char *local, char **name)
3082ea022d16SRodney W. Grimes {
3083ea022d16SRodney W. Grimes 	static char new[MAXPATHLEN];
3084ea022d16SRodney W. Grimes 	struct stat st;
3085ea022d16SRodney W. Grimes 	char *cp;
3086a117c345SYaroslav Tykhiy 	int count;
3087a117c345SYaroslav Tykhiy 	int fd;
3088ea022d16SRodney W. Grimes 
3089ea022d16SRodney W. Grimes 	cp = strrchr(local, '/');
3090ea022d16SRodney W. Grimes 	if (cp)
3091ea022d16SRodney W. Grimes 		*cp = '\0';
3092ea022d16SRodney W. Grimes 	if (stat(cp ? local : ".", &st) < 0) {
3093ea022d16SRodney W. Grimes 		perror_reply(553, cp ? local : ".");
3094a117c345SYaroslav Tykhiy 		return (-1);
3095ea022d16SRodney W. Grimes 	}
3096a117c345SYaroslav Tykhiy 	if (cp) {
3097a117c345SYaroslav Tykhiy 		/*
3098a117c345SYaroslav Tykhiy 		 * Let not overwrite dirname with counter suffix.
3099a117c345SYaroslav Tykhiy 		 * -4 is for /nn\0
3100a117c345SYaroslav Tykhiy 		 * In this extreme case dot won't be put in front of suffix.
3101a117c345SYaroslav Tykhiy 		 */
3102a117c345SYaroslav Tykhiy 		if (strlen(local) > sizeof(new) - 4) {
310302c97492SYaroslav Tykhiy 			reply(553, "Pathname too long.");
3104a117c345SYaroslav Tykhiy 			return (-1);
3105a117c345SYaroslav Tykhiy 		}
3106ea022d16SRodney W. Grimes 		*cp = '/';
3107a117c345SYaroslav Tykhiy 	}
3108e760ef2cSWarner Losh 	/* -4 is for the .nn<null> we put on the end below */
3109e760ef2cSWarner Losh 	(void) snprintf(new, sizeof(new) - 4, "%s", local);
3110ea022d16SRodney W. Grimes 	cp = new + strlen(new);
3111a117c345SYaroslav Tykhiy 	/*
3112a117c345SYaroslav Tykhiy 	 * Don't generate dotfile unless requested explicitly.
3113a117c345SYaroslav Tykhiy 	 * This covers the case when basename gets truncated off
3114a117c345SYaroslav Tykhiy 	 * by buffer size.
3115a117c345SYaroslav Tykhiy 	 */
3116a117c345SYaroslav Tykhiy 	if (cp > new && cp[-1] != '/')
3117ea022d16SRodney W. Grimes 		*cp++ = '.';
3118a117c345SYaroslav Tykhiy 	for (count = 0; count < 100; count++) {
3119a117c345SYaroslav Tykhiy 		/* At count 0 try unmodified name */
3120a117c345SYaroslav Tykhiy 		if (count)
3121ea022d16SRodney W. Grimes 			(void)sprintf(cp, "%d", count);
3122a117c345SYaroslav Tykhiy 		if ((fd = open(count ? new : local,
3123a117c345SYaroslav Tykhiy 		    O_RDWR | O_CREAT | O_EXCL, 0666)) >= 0) {
3124a117c345SYaroslav Tykhiy 			*name = count ? new : local;
3125a117c345SYaroslav Tykhiy 			return (fd);
3126a117c345SYaroslav Tykhiy 		}
312788b70721SYaroslav Tykhiy 		if (errno != EEXIST) {
312850618d61SYaroslav Tykhiy 			perror_reply(553, count ? new : local);
312988b70721SYaroslav Tykhiy 			return (-1);
313088b70721SYaroslav Tykhiy 		}
3131ea022d16SRodney W. Grimes 	}
3132ea022d16SRodney W. Grimes 	reply(452, "Unique file name cannot be created.");
3133a117c345SYaroslav Tykhiy 	return (-1);
3134ea022d16SRodney W. Grimes }
3135ea022d16SRodney W. Grimes 
3136ea022d16SRodney W. Grimes /*
3137ea022d16SRodney W. Grimes  * Format and send reply containing system error number.
3138ea022d16SRodney W. Grimes  */
3139ea022d16SRodney W. Grimes void
3140e4bc453cSWarner Losh perror_reply(int code, char *string)
3141ea022d16SRodney W. Grimes {
3142ea022d16SRodney W. Grimes 
3143ea022d16SRodney W. Grimes 	reply(code, "%s: %s.", string, strerror(errno));
3144ea022d16SRodney W. Grimes }
3145ea022d16SRodney W. Grimes 
3146ea022d16SRodney W. Grimes static char *onefile[] = {
3147ea022d16SRodney W. Grimes 	"",
3148ea022d16SRodney W. Grimes 	0
3149ea022d16SRodney W. Grimes };
3150ea022d16SRodney W. Grimes 
3151ea022d16SRodney W. Grimes void
3152e4bc453cSWarner Losh send_file_list(char *whichf)
3153ea022d16SRodney W. Grimes {
3154ea022d16SRodney W. Grimes 	struct stat st;
3155ea022d16SRodney W. Grimes 	DIR *dirp = NULL;
3156ea022d16SRodney W. Grimes 	struct dirent *dir;
3157ea022d16SRodney W. Grimes 	FILE *dout = NULL;
3158ea022d16SRodney W. Grimes 	char **dirlist, *dirname;
3159ea022d16SRodney W. Grimes 	int simple = 0;
3160ea022d16SRodney W. Grimes 	int freeglob = 0;
3161ea022d16SRodney W. Grimes 	glob_t gl;
3162ea022d16SRodney W. Grimes 
3163ea022d16SRodney W. Grimes 	if (strpbrk(whichf, "~{[*?") != NULL) {
316412da320bSMike Heffner 		int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
3165ea022d16SRodney W. Grimes 
3166ea022d16SRodney W. Grimes 		memset(&gl, 0, sizeof(gl));
31676d10cb2fSJonathan Lemon 		gl.gl_matchc = MAXGLOBARGS;
316875dc5f1aSMike Heffner 		flags |= GLOB_LIMIT;
3169ea022d16SRodney W. Grimes 		freeglob = 1;
3170ea022d16SRodney W. Grimes 		if (glob(whichf, flags, 0, &gl)) {
317102c97492SYaroslav Tykhiy 			reply(550, "No matching files found.");
3172ea022d16SRodney W. Grimes 			goto out;
3173ea022d16SRodney W. Grimes 		} else if (gl.gl_pathc == 0) {
3174ea022d16SRodney W. Grimes 			errno = ENOENT;
3175ea022d16SRodney W. Grimes 			perror_reply(550, whichf);
3176ea022d16SRodney W. Grimes 			goto out;
3177ea022d16SRodney W. Grimes 		}
3178ea022d16SRodney W. Grimes 		dirlist = gl.gl_pathv;
3179ea022d16SRodney W. Grimes 	} else {
3180ea022d16SRodney W. Grimes 		onefile[0] = whichf;
3181ea022d16SRodney W. Grimes 		dirlist = onefile;
3182ea022d16SRodney W. Grimes 		simple = 1;
3183ea022d16SRodney W. Grimes 	}
3184ea022d16SRodney W. Grimes 
31859aca17cbSMark Murray 	while ((dirname = *dirlist++)) {
3186ea022d16SRodney W. Grimes 		if (stat(dirname, &st) < 0) {
3187ea022d16SRodney W. Grimes 			/*
3188ea022d16SRodney W. Grimes 			 * If user typed "ls -l", etc, and the client
3189ea022d16SRodney W. Grimes 			 * used NLST, do what the user meant.
3190ea022d16SRodney W. Grimes 			 */
3191ea022d16SRodney W. Grimes 			if (dirname[0] == '-' && *dirlist == NULL &&
31924cd51076SYaroslav Tykhiy 			    dout == NULL)
3193af85d782SDavid Nugent 				retrieve(_PATH_LS " %s", dirname);
31944cd51076SYaroslav Tykhiy 			else
3195ea022d16SRodney W. Grimes 				perror_reply(550, whichf);
3196ea022d16SRodney W. Grimes 			goto out;
3197ea022d16SRodney W. Grimes 		}
3198ea022d16SRodney W. Grimes 
3199ea022d16SRodney W. Grimes 		if (S_ISREG(st.st_mode)) {
3200ea022d16SRodney W. Grimes 			if (dout == NULL) {
32010e519c96SYaroslav Tykhiy 				dout = dataconn("file list", -1, "w");
3202ea022d16SRodney W. Grimes 				if (dout == NULL)
3203ea022d16SRodney W. Grimes 					goto out;
32044cd51076SYaroslav Tykhiy 				STARTXFER;
3205ea022d16SRodney W. Grimes 			}
32064cd51076SYaroslav Tykhiy 			START_UNSAFE;
3207ea022d16SRodney W. Grimes 			fprintf(dout, "%s%s\n", dirname,
3208ea022d16SRodney W. Grimes 				type == TYPE_A ? "\r" : "");
32094cd51076SYaroslav Tykhiy 			END_UNSAFE;
32104cd51076SYaroslav Tykhiy 			if (ferror(dout))
32114cd51076SYaroslav Tykhiy 				goto data_err;
32124cd51076SYaroslav Tykhiy 			byte_count += strlen(dirname) +
32134cd51076SYaroslav Tykhiy 				      (type == TYPE_A ? 2 : 1);
32144cd51076SYaroslav Tykhiy 			CHECKOOB(goto abrt);
3215ea022d16SRodney W. Grimes 			continue;
3216ea022d16SRodney W. Grimes 		} else if (!S_ISDIR(st.st_mode))
3217ea022d16SRodney W. Grimes 			continue;
3218ea022d16SRodney W. Grimes 
3219ea022d16SRodney W. Grimes 		if ((dirp = opendir(dirname)) == NULL)
3220ea022d16SRodney W. Grimes 			continue;
3221ea022d16SRodney W. Grimes 
3222ea022d16SRodney W. Grimes 		while ((dir = readdir(dirp)) != NULL) {
3223ea022d16SRodney W. Grimes 			char nbuf[MAXPATHLEN];
3224ea022d16SRodney W. Grimes 
32254cd51076SYaroslav Tykhiy 			CHECKOOB(goto abrt);
32264b82fc95SYaroslav Tykhiy 
3227ea022d16SRodney W. Grimes 			if (dir->d_name[0] == '.' && dir->d_namlen == 1)
3228ea022d16SRodney W. Grimes 				continue;
3229ea022d16SRodney W. Grimes 			if (dir->d_name[0] == '.' && dir->d_name[1] == '.' &&
3230ea022d16SRodney W. Grimes 			    dir->d_namlen == 2)
3231ea022d16SRodney W. Grimes 				continue;
3232ea022d16SRodney W. Grimes 
3233e760ef2cSWarner Losh 			snprintf(nbuf, sizeof(nbuf),
3234e760ef2cSWarner Losh 				"%s/%s", dirname, dir->d_name);
3235ea022d16SRodney W. Grimes 
3236ea022d16SRodney W. Grimes 			/*
3237ea022d16SRodney W. Grimes 			 * We have to do a stat to insure it's
3238ea022d16SRodney W. Grimes 			 * not a directory or special file.
3239ea022d16SRodney W. Grimes 			 */
3240ea022d16SRodney W. Grimes 			if (simple || (stat(nbuf, &st) == 0 &&
3241ea022d16SRodney W. Grimes 			    S_ISREG(st.st_mode))) {
3242ea022d16SRodney W. Grimes 				if (dout == NULL) {
32430e519c96SYaroslav Tykhiy 					dout = dataconn("file list", -1, "w");
3244ea022d16SRodney W. Grimes 					if (dout == NULL)
3245ea022d16SRodney W. Grimes 						goto out;
32464cd51076SYaroslav Tykhiy 					STARTXFER;
3247ea022d16SRodney W. Grimes 				}
32484cd51076SYaroslav Tykhiy 				START_UNSAFE;
3249ea022d16SRodney W. Grimes 				if (nbuf[0] == '.' && nbuf[1] == '/')
3250ea022d16SRodney W. Grimes 					fprintf(dout, "%s%s\n", &nbuf[2],
3251ea022d16SRodney W. Grimes 						type == TYPE_A ? "\r" : "");
3252ea022d16SRodney W. Grimes 				else
3253ea022d16SRodney W. Grimes 					fprintf(dout, "%s%s\n", nbuf,
3254ea022d16SRodney W. Grimes 						type == TYPE_A ? "\r" : "");
32554cd51076SYaroslav Tykhiy 				END_UNSAFE;
32564cd51076SYaroslav Tykhiy 				if (ferror(dout))
32574cd51076SYaroslav Tykhiy 					goto data_err;
32584cd51076SYaroslav Tykhiy 				byte_count += strlen(nbuf) +
32594cd51076SYaroslav Tykhiy 					      (type == TYPE_A ? 2 : 1);
32604cd51076SYaroslav Tykhiy 				CHECKOOB(goto abrt);
3261ea022d16SRodney W. Grimes 			}
3262ea022d16SRodney W. Grimes 		}
3263ea022d16SRodney W. Grimes 		(void) closedir(dirp);
32644cd51076SYaroslav Tykhiy 		dirp = NULL;
3265ea022d16SRodney W. Grimes 	}
3266ea022d16SRodney W. Grimes 
3267ea022d16SRodney W. Grimes 	if (dout == NULL)
3268ea022d16SRodney W. Grimes 		reply(550, "No files found.");
32694cd51076SYaroslav Tykhiy 	else if (ferror(dout))
32704cd51076SYaroslav Tykhiy data_err:	perror_reply(550, "Data connection");
3271ea022d16SRodney W. Grimes 	else
3272ea022d16SRodney W. Grimes 		reply(226, "Transfer complete.");
32734cd51076SYaroslav Tykhiy out:
32744cd51076SYaroslav Tykhiy 	if (dout) {
32754cd51076SYaroslav Tykhiy 		ENDXFER;
32764cd51076SYaroslav Tykhiy abrt:
3277ea022d16SRodney W. Grimes 		(void) fclose(dout);
3278ea022d16SRodney W. Grimes 		data = -1;
3279ea022d16SRodney W. Grimes 		pdata = -1;
32804cd51076SYaroslav Tykhiy 	}
32814cd51076SYaroslav Tykhiy 	if (dirp)
32824cd51076SYaroslav Tykhiy 		(void) closedir(dirp);
3283ea022d16SRodney W. Grimes 	if (freeglob) {
3284ea022d16SRodney W. Grimes 		freeglob = 0;
3285ea022d16SRodney W. Grimes 		globfree(&gl);
3286ea022d16SRodney W. Grimes 	}
3287ea022d16SRodney W. Grimes }
3288ea022d16SRodney W. Grimes 
3289cf09a206SDavid Greenman void
3290e4bc453cSWarner Losh reapchild(int signo)
3291cf09a206SDavid Greenman {
3292de9b6c03SYaroslav Tykhiy 	while (waitpid(-1, NULL, WNOHANG) > 0);
3293cf09a206SDavid Greenman }
3294cf09a206SDavid Greenman 
3295b63e1fe2SPeter Wemm #ifdef OLD_SETPROCTITLE
3296ea022d16SRodney W. Grimes /*
3297ea022d16SRodney W. Grimes  * Clobber argv so ps will show what we're doing.  (Stolen from sendmail.)
3298ea022d16SRodney W. Grimes  * Warning, since this is usually started from inetd.conf, it often doesn't
3299ea022d16SRodney W. Grimes  * have much of an environment or arglist to overwrite.
3300ea022d16SRodney W. Grimes  */
3301ea022d16SRodney W. Grimes void
3302ea022d16SRodney W. Grimes setproctitle(const char *fmt, ...)
3303ea022d16SRodney W. Grimes {
3304ea022d16SRodney W. Grimes 	int i;
3305ea022d16SRodney W. Grimes 	va_list ap;
3306ea022d16SRodney W. Grimes 	char *p, *bp, ch;
3307ea022d16SRodney W. Grimes 	char buf[LINE_MAX];
3308ea022d16SRodney W. Grimes 
3309ea022d16SRodney W. Grimes 	va_start(ap, fmt);
3310ea022d16SRodney W. Grimes 	(void)vsnprintf(buf, sizeof(buf), fmt, ap);
3311ea022d16SRodney W. Grimes 
3312ea022d16SRodney W. Grimes 	/* make ps print our process name */
3313ea022d16SRodney W. Grimes 	p = Argv[0];
3314ea022d16SRodney W. Grimes 	*p++ = '-';
3315ea022d16SRodney W. Grimes 
3316ea022d16SRodney W. Grimes 	i = strlen(buf);
3317ea022d16SRodney W. Grimes 	if (i > LastArgv - p - 2) {
3318ea022d16SRodney W. Grimes 		i = LastArgv - p - 2;
3319ea022d16SRodney W. Grimes 		buf[i] = '\0';
3320ea022d16SRodney W. Grimes 	}
3321ea022d16SRodney W. Grimes 	bp = buf;
3322ea022d16SRodney W. Grimes 	while (ch = *bp++)
3323ea022d16SRodney W. Grimes 		if (ch != '\n' && ch != '\r')
3324ea022d16SRodney W. Grimes 			*p++ = ch;
3325ea022d16SRodney W. Grimes 	while (p < LastArgv)
3326ea022d16SRodney W. Grimes 		*p++ = ' ';
3327ea022d16SRodney W. Grimes }
3328b63e1fe2SPeter Wemm #endif /* OLD_SETPROCTITLE */
33293eb568f2SGuido van Rooij 
333061f891a6SPaul Traina static void
33316b2dee6bSYaroslav Tykhiy appendf(char **strp, char *fmt, ...)
33326b2dee6bSYaroslav Tykhiy {
33336b2dee6bSYaroslav Tykhiy 	va_list ap;
33346b2dee6bSYaroslav Tykhiy 	char *ostr, *p;
33356b2dee6bSYaroslav Tykhiy 
33366b2dee6bSYaroslav Tykhiy 	va_start(ap, fmt);
33376b2dee6bSYaroslav Tykhiy 	vasprintf(&p, fmt, ap);
33386b2dee6bSYaroslav Tykhiy 	va_end(ap);
33396b2dee6bSYaroslav Tykhiy 	if (p == NULL)
33406b2dee6bSYaroslav Tykhiy 		fatalerror("Ran out of memory.");
33416b2dee6bSYaroslav Tykhiy 	if (*strp == NULL)
33426b2dee6bSYaroslav Tykhiy 		*strp = p;
33436b2dee6bSYaroslav Tykhiy 	else {
33446b2dee6bSYaroslav Tykhiy 		ostr = *strp;
33456b2dee6bSYaroslav Tykhiy 		asprintf(strp, "%s%s", ostr, p);
33466b2dee6bSYaroslav Tykhiy 		if (*strp == NULL)
33476b2dee6bSYaroslav Tykhiy 			fatalerror("Ran out of memory.");
33486b2dee6bSYaroslav Tykhiy 		free(ostr);
33496b2dee6bSYaroslav Tykhiy 	}
33506b2dee6bSYaroslav Tykhiy }
33516b2dee6bSYaroslav Tykhiy 
33526b2dee6bSYaroslav Tykhiy static void
33536b2dee6bSYaroslav Tykhiy logcmd(char *cmd, char *file1, char *file2, off_t cnt)
33546b2dee6bSYaroslav Tykhiy {
33556b2dee6bSYaroslav Tykhiy 	char *msg = NULL;
33566b2dee6bSYaroslav Tykhiy 	char wd[MAXPATHLEN + 1];
33576b2dee6bSYaroslav Tykhiy 
33586b2dee6bSYaroslav Tykhiy 	if (logging <= 1)
33596b2dee6bSYaroslav Tykhiy 		return;
3360e897216fSYaroslav Tykhiy 
33616b2dee6bSYaroslav Tykhiy 	if (getcwd(wd, sizeof(wd) - 1) == NULL)
33626b2dee6bSYaroslav Tykhiy 		strcpy(wd, strerror(errno));
33636b2dee6bSYaroslav Tykhiy 
33646b2dee6bSYaroslav Tykhiy 	appendf(&msg, "%s", cmd);
33656b2dee6bSYaroslav Tykhiy 	if (file1)
33666b2dee6bSYaroslav Tykhiy 		appendf(&msg, " %s", file1);
33676b2dee6bSYaroslav Tykhiy 	if (file2)
33686b2dee6bSYaroslav Tykhiy 		appendf(&msg, " %s", file2);
33696b2dee6bSYaroslav Tykhiy 	if (cnt >= 0)
33706b2dee6bSYaroslav Tykhiy 		appendf(&msg, " = %jd bytes", (intmax_t)cnt);
3371e897216fSYaroslav Tykhiy 	appendf(&msg, " (wd: %s", wd);
3372215a9f9dSYaroslav Tykhiy 	if (guest || dochroot)
3373e897216fSYaroslav Tykhiy 		appendf(&msg, "; chrooted");
3374e897216fSYaroslav Tykhiy 	appendf(&msg, ")");
33756b2dee6bSYaroslav Tykhiy 	syslog(LOG_INFO, "%s", msg);
33766b2dee6bSYaroslav Tykhiy 	free(msg);
33776b2dee6bSYaroslav Tykhiy }
33786b2dee6bSYaroslav Tykhiy 
33796b2dee6bSYaroslav Tykhiy static void
3380e4bc453cSWarner Losh logxfer(char *name, off_t size, time_t start)
33813eb568f2SGuido van Rooij {
33828c1c21f2SYaroslav Tykhiy 	char buf[MAXPATHLEN + 1024];
33833eb568f2SGuido van Rooij 	char path[MAXPATHLEN + 1];
3384158a00b2SJohn Birrell 	time_t now;
33853eb568f2SGuido van Rooij 
33868c1c21f2SYaroslav Tykhiy 	if (statfd >= 0) {
33873eb568f2SGuido van Rooij 		time(&now);
33888c1c21f2SYaroslav Tykhiy 		if (realpath(name, path) == NULL) {
33898c1c21f2SYaroslav Tykhiy 			syslog(LOG_NOTICE, "realpath failed on %s: %m", path);
33908c1c21f2SYaroslav Tykhiy 			return;
33918c1c21f2SYaroslav Tykhiy 		}
33928c1c21f2SYaroslav Tykhiy 		snprintf(buf, sizeof(buf), "%.20s!%s!%s!%s!%jd!%ld\n",
33933eb568f2SGuido van Rooij 			ctime(&now)+4, ident, remotehost,
33948c1c21f2SYaroslav Tykhiy 			path, (intmax_t)size,
3395e4a71114SAndrey A. Chernov 			(long)(now - start + (now == start)));
33963eb568f2SGuido van Rooij 		write(statfd, buf, strlen(buf));
33973eb568f2SGuido van Rooij 	}
33983eb568f2SGuido van Rooij }
3399e4648f05SYaroslav Tykhiy 
3400e4648f05SYaroslav Tykhiy static char *
3401e4648f05SYaroslav Tykhiy doublequote(char *s)
3402e4648f05SYaroslav Tykhiy {
3403e4648f05SYaroslav Tykhiy 	int n;
3404e4648f05SYaroslav Tykhiy 	char *p, *s2;
3405e4648f05SYaroslav Tykhiy 
3406e4648f05SYaroslav Tykhiy 	for (p = s, n = 0; *p; p++)
3407e4648f05SYaroslav Tykhiy 		if (*p == '"')
3408e4648f05SYaroslav Tykhiy 			n++;
3409e4648f05SYaroslav Tykhiy 
3410e4648f05SYaroslav Tykhiy 	if ((s2 = malloc(p - s + n + 1)) == NULL)
3411e4648f05SYaroslav Tykhiy 		return (NULL);
3412e4648f05SYaroslav Tykhiy 
3413e4648f05SYaroslav Tykhiy 	for (p = s2; *s; s++, p++) {
3414e4648f05SYaroslav Tykhiy 		if ((*p = *s) == '"')
3415e4648f05SYaroslav Tykhiy 			*(++p) = '"';
3416e4648f05SYaroslav Tykhiy 	}
3417e4648f05SYaroslav Tykhiy 	*p = '\0';
3418e4648f05SYaroslav Tykhiy 
3419e4648f05SYaroslav Tykhiy 	return (s2);
3420e4648f05SYaroslav Tykhiy }
3421206fe568SHajimu UMEMOTO 
3422206fe568SHajimu UMEMOTO /* setup server socket for specified address family */
3423206fe568SHajimu UMEMOTO /* if af is PF_UNSPEC more than one socket may be returned */
3424206fe568SHajimu UMEMOTO /* the returned list is dynamically allocated, so caller needs to free it */
3425206fe568SHajimu UMEMOTO static int *
3426206fe568SHajimu UMEMOTO socksetup(int af, char *bindname, const char *bindport)
3427206fe568SHajimu UMEMOTO {
3428206fe568SHajimu UMEMOTO 	struct addrinfo hints, *res, *r;
3429206fe568SHajimu UMEMOTO 	int error, maxs, *s, *socks;
3430206fe568SHajimu UMEMOTO 	const int on = 1;
3431206fe568SHajimu UMEMOTO 
3432206fe568SHajimu UMEMOTO 	memset(&hints, 0, sizeof(hints));
3433206fe568SHajimu UMEMOTO 	hints.ai_flags = AI_PASSIVE;
3434206fe568SHajimu UMEMOTO 	hints.ai_family = af;
3435206fe568SHajimu UMEMOTO 	hints.ai_socktype = SOCK_STREAM;
3436206fe568SHajimu UMEMOTO 	error = getaddrinfo(bindname, bindport, &hints, &res);
3437206fe568SHajimu UMEMOTO 	if (error) {
3438206fe568SHajimu UMEMOTO 		syslog(LOG_ERR, "%s", gai_strerror(error));
3439206fe568SHajimu UMEMOTO 		if (error == EAI_SYSTEM)
3440206fe568SHajimu UMEMOTO 			syslog(LOG_ERR, "%s", strerror(errno));
3441206fe568SHajimu UMEMOTO 		return NULL;
3442206fe568SHajimu UMEMOTO 	}
3443206fe568SHajimu UMEMOTO 
3444206fe568SHajimu UMEMOTO 	/* Count max number of sockets we may open */
3445206fe568SHajimu UMEMOTO 	for (maxs = 0, r = res; r; r = r->ai_next, maxs++)
3446206fe568SHajimu UMEMOTO 		;
3447206fe568SHajimu UMEMOTO 	socks = malloc((maxs + 1) * sizeof(int));
3448206fe568SHajimu UMEMOTO 	if (!socks) {
3449206fe568SHajimu UMEMOTO 		freeaddrinfo(res);
3450206fe568SHajimu UMEMOTO 		syslog(LOG_ERR, "couldn't allocate memory for sockets");
3451206fe568SHajimu UMEMOTO 		return NULL;
3452206fe568SHajimu UMEMOTO 	}
3453206fe568SHajimu UMEMOTO 
3454206fe568SHajimu UMEMOTO 	*socks = 0;   /* num of sockets counter at start of array */
3455206fe568SHajimu UMEMOTO 	s = socks + 1;
3456206fe568SHajimu UMEMOTO 	for (r = res; r; r = r->ai_next) {
3457206fe568SHajimu UMEMOTO 		*s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
3458206fe568SHajimu UMEMOTO 		if (*s < 0) {
3459206fe568SHajimu UMEMOTO 			syslog(LOG_DEBUG, "control socket: %m");
3460206fe568SHajimu UMEMOTO 			continue;
3461206fe568SHajimu UMEMOTO 		}
3462206fe568SHajimu UMEMOTO 		if (setsockopt(*s, SOL_SOCKET, SO_REUSEADDR,
3463206fe568SHajimu UMEMOTO 		    &on, sizeof(on)) < 0)
3464206fe568SHajimu UMEMOTO 			syslog(LOG_WARNING,
3465206fe568SHajimu UMEMOTO 			    "control setsockopt (SO_REUSEADDR): %m");
3466206fe568SHajimu UMEMOTO 		if (r->ai_family == AF_INET6) {
3467206fe568SHajimu UMEMOTO 			if (setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY,
3468206fe568SHajimu UMEMOTO 			    &on, sizeof(on)) < 0)
3469206fe568SHajimu UMEMOTO 				syslog(LOG_WARNING,
3470206fe568SHajimu UMEMOTO 				    "control setsockopt (IPV6_V6ONLY): %m");
3471206fe568SHajimu UMEMOTO 		}
3472206fe568SHajimu UMEMOTO 		if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
3473206fe568SHajimu UMEMOTO 			syslog(LOG_DEBUG, "control bind: %m");
3474206fe568SHajimu UMEMOTO 			close(*s);
3475206fe568SHajimu UMEMOTO 			continue;
3476206fe568SHajimu UMEMOTO 		}
3477206fe568SHajimu UMEMOTO 		(*socks)++;
3478206fe568SHajimu UMEMOTO 		s++;
3479206fe568SHajimu UMEMOTO 	}
3480206fe568SHajimu UMEMOTO 
3481206fe568SHajimu UMEMOTO 	if (res)
3482206fe568SHajimu UMEMOTO 		freeaddrinfo(res);
3483206fe568SHajimu UMEMOTO 
3484206fe568SHajimu UMEMOTO 	if (*socks == 0) {
3485206fe568SHajimu UMEMOTO 		syslog(LOG_ERR, "control socket: Couldn't bind to any socket");
3486206fe568SHajimu UMEMOTO 		free(socks);
3487206fe568SHajimu UMEMOTO 		return NULL;
3488206fe568SHajimu UMEMOTO 	}
3489206fe568SHajimu UMEMOTO 	return(socks);
3490206fe568SHajimu UMEMOTO }
3491