xref: /freebsd/libexec/ftpd/ftpd.c (revision f0b40b1c97b2efe9f22af5d63ec6c62c55804a43)
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.
13ea022d16SRodney W. Grimes  * 3. All advertising materials mentioning features or use of this software
14ea022d16SRodney W. Grimes  *    must display the following acknowledgement:
15ea022d16SRodney W. Grimes  *	This product includes software developed by the University of
16ea022d16SRodney W. Grimes  *	California, Berkeley and its contributors.
17ea022d16SRodney W. Grimes  * 4. Neither the name of the University nor the names of its contributors
18ea022d16SRodney W. Grimes  *    may be used to endorse or promote products derived from this software
19ea022d16SRodney W. Grimes  *    without specific prior written permission.
20ea022d16SRodney W. Grimes  *
21ea022d16SRodney W. Grimes  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22ea022d16SRodney W. Grimes  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23ea022d16SRodney W. Grimes  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24ea022d16SRodney W. Grimes  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25ea022d16SRodney W. Grimes  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26ea022d16SRodney W. Grimes  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27ea022d16SRodney W. Grimes  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28ea022d16SRodney W. Grimes  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29ea022d16SRodney W. Grimes  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30ea022d16SRodney W. Grimes  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31ea022d16SRodney W. Grimes  * SUCH DAMAGE.
32ea022d16SRodney W. Grimes  */
33ea022d16SRodney W. Grimes 
349aca17cbSMark Murray #if 0
35ea022d16SRodney W. Grimes #ifndef lint
36ea022d16SRodney W. Grimes static char copyright[] =
37ea022d16SRodney W. Grimes "@(#) Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994\n\
38ea022d16SRodney W. Grimes 	The Regents of the University of California.  All rights reserved.\n";
39ea022d16SRodney W. Grimes #endif /* not lint */
409aca17cbSMark Murray #endif
41ea022d16SRodney W. Grimes 
42ea022d16SRodney W. Grimes #ifndef lint
43e02897faSPhilippe Charnier #if 0
44ea022d16SRodney W. Grimes static char sccsid[] = "@(#)ftpd.c	8.4 (Berkeley) 4/16/94";
459aca17cbSMark Murray #endif
46e02897faSPhilippe Charnier #endif /* not lint */
47ea022d16SRodney W. Grimes 
480c4b401fSYaroslav Tykhiy #include <sys/cdefs.h>
490c4b401fSYaroslav Tykhiy __FBSDID("$FreeBSD$");
500c4b401fSYaroslav Tykhiy 
51ea022d16SRodney W. Grimes /*
52ea022d16SRodney W. Grimes  * FTP server.
53ea022d16SRodney W. Grimes  */
54ea022d16SRodney W. Grimes #include <sys/param.h>
55ea022d16SRodney W. Grimes #include <sys/ioctl.h>
569fc5823aSGarrett Wollman #include <sys/mman.h>
57eb2fc780SGarrett Wollman #include <sys/socket.h>
58eb2fc780SGarrett Wollman #include <sys/stat.h>
59eb2fc780SGarrett Wollman #include <sys/time.h>
60eb2fc780SGarrett Wollman #include <sys/wait.h>
61ea022d16SRodney W. Grimes 
62ea022d16SRodney W. Grimes #include <netinet/in.h>
63ea022d16SRodney W. Grimes #include <netinet/in_systm.h>
64ea022d16SRodney W. Grimes #include <netinet/ip.h>
659fc5823aSGarrett Wollman #include <netinet/tcp.h>
66ea022d16SRodney W. Grimes 
67ea022d16SRodney W. Grimes #define	FTP_NAMES
68ea022d16SRodney W. Grimes #include <arpa/ftp.h>
69ea022d16SRodney W. Grimes #include <arpa/inet.h>
70ea022d16SRodney W. Grimes #include <arpa/telnet.h>
71ea022d16SRodney W. Grimes 
72ea022d16SRodney W. Grimes #include <ctype.h>
73ea022d16SRodney W. Grimes #include <dirent.h>
74ea022d16SRodney W. Grimes #include <err.h>
75ea022d16SRodney W. Grimes #include <errno.h>
76ea022d16SRodney W. Grimes #include <fcntl.h>
77ea022d16SRodney W. Grimes #include <glob.h>
78ea022d16SRodney W. Grimes #include <limits.h>
79ea022d16SRodney W. Grimes #include <netdb.h>
80ea022d16SRodney W. Grimes #include <pwd.h>
8131fea7b8SDavid Nugent #include <grp.h>
8247499ecdSAndrey A. Chernov #include <opie.h>
83ea022d16SRodney W. Grimes #include <signal.h>
84a57e1ef0SYaroslav Tykhiy #include <stdint.h>
85ea022d16SRodney W. Grimes #include <stdio.h>
86ea022d16SRodney W. Grimes #include <stdlib.h>
87ea022d16SRodney W. Grimes #include <string.h>
88ea022d16SRodney W. Grimes #include <syslog.h>
89ea022d16SRodney W. Grimes #include <time.h>
90ea022d16SRodney W. Grimes #include <unistd.h>
91b63e1fe2SPeter Wemm #include <libutil.h>
92b071c689SDavid Nugent #ifdef	LOGIN_CAP
93b071c689SDavid Nugent #include <login_cap.h>
94b071c689SDavid Nugent #endif
95ea022d16SRodney W. Grimes 
965bc9d93dSMark Murray #ifdef USE_PAM
976c9134c0SMark Murray #include <security/pam_appl.h>
986c9134c0SMark Murray #endif
996c9134c0SMark Murray 
100ea022d16SRodney W. Grimes #include "pathnames.h"
101ea022d16SRodney W. Grimes #include "extern.h"
102ea022d16SRodney W. Grimes 
103ea022d16SRodney W. Grimes #include <stdarg.h>
104ea022d16SRodney W. Grimes 
105af85d782SDavid Nugent static char version[] = "Version 6.00LS";
106af85d782SDavid Nugent #undef main
107ea022d16SRodney W. Grimes 
108ea022d16SRodney W. Grimes extern	off_t restart_point;
109ea022d16SRodney W. Grimes extern	char cbuf[];
110ea022d16SRodney W. Grimes 
1114dd8b5abSYoshinobu Inoue union sockunion ctrl_addr;
1124dd8b5abSYoshinobu Inoue union sockunion data_source;
1134dd8b5abSYoshinobu Inoue union sockunion data_dest;
1144dd8b5abSYoshinobu Inoue union sockunion his_addr;
1154dd8b5abSYoshinobu Inoue union sockunion pasv_addr;
116ea022d16SRodney W. Grimes 
117cf09a206SDavid Greenman int	daemon_mode;
118ea022d16SRodney W. Grimes int	data;
11963591ba5SYaroslav Tykhiy int	dataport;
120c152df28SYaroslav Tykhiy int	hostinfo = 1;	/* print host-specific info in messages */
121ea022d16SRodney W. Grimes int	logged_in;
122ea022d16SRodney W. Grimes struct	passwd *pw;
123ce9287fcSYaroslav Tykhiy char	*homedir;
124618b0bbaSMark Murray int	ftpdebug;
125ea022d16SRodney W. Grimes int	timeout = 900;    /* timeout after 15 minutes of inactivity */
126ea022d16SRodney W. Grimes int	maxtimeout = 7200;/* don't allow idle time to be set beyond 2 hours */
127ea022d16SRodney W. Grimes int	logging;
1284c450ad7SPaul Traina int	restricted_data_ports = 1;
129a5a4544eSPaul Traina int	paranoid = 1;	  /* be extra careful about security */
1305a392aecSTorsten Blum int	anon_only = 0;    /* Only anonymous ftp allowed */
1312ea42282SYaroslav Tykhiy int	assumeutf8 = 0;   /* Assume that server file names are in UTF-8 */
132ea022d16SRodney W. Grimes int	guest;
133a5a4544eSPaul Traina int	dochroot;
134215a9f9dSYaroslav Tykhiy char	*chrootdir;
1355d7e0128SYaroslav Tykhiy int	dowtmp = 1;
1363eb568f2SGuido van Rooij int	stats;
1373eb568f2SGuido van Rooij int	statfd = -1;
138ea022d16SRodney W. Grimes int	type;
139ea022d16SRodney W. Grimes int	form;
140ea022d16SRodney W. Grimes int	stru;			/* avoid C keyword */
141ea022d16SRodney W. Grimes int	mode;
142ea022d16SRodney W. Grimes int	usedefault = 1;		/* for data transfers */
143ea022d16SRodney W. Grimes int	pdata = -1;		/* for passive mode */
144a4b77a2aSPoul-Henning Kamp int	readonly = 0;		/* Server is in readonly mode.	*/
145a4b77a2aSPoul-Henning Kamp int	noepsv = 0;		/* EPSV command is disabled.	*/
14662513e76SNik Clayton int	noretr = 0;		/* RETR command is disabled.	*/
1471cc9f0bbSSheldon Hearn int	noguestretr = 0;	/* RETR command is disabled for anon users. */
148d186bb12SMatthew N. Dodd int	noguestmkd = 0;		/* MKD command is disabled for anon users. */
149a117c345SYaroslav Tykhiy int	noguestmod = 1;		/* anon users may not modify existing files. */
15062513e76SNik Clayton 
151ea022d16SRodney W. Grimes off_t	file_size;
152ea022d16SRodney W. Grimes off_t	byte_count;
153ea022d16SRodney W. Grimes #if !defined(CMASK) || CMASK == 0
154ea022d16SRodney W. Grimes #undef CMASK
155ea022d16SRodney W. Grimes #define CMASK 027
156ea022d16SRodney W. Grimes #endif
157ea022d16SRodney W. Grimes int	defumask = CMASK;		/* default umask value */
158ea022d16SRodney W. Grimes char	tmpline[7];
159ea4e54b9SDavid Nugent char	*hostname;
160ad442344SDima Dorfman int	epsvall = 0;
161ad442344SDima Dorfman 
1620512556aSDavid Nugent #ifdef VIRTUAL_HOSTING
163ea4e54b9SDavid Nugent char	*ftpuser;
164ea4e54b9SDavid Nugent 
165ea4e54b9SDavid Nugent static struct ftphost {
166ea4e54b9SDavid Nugent 	struct ftphost	*next;
167f38c6cadSYoshinobu Inoue 	struct addrinfo *hostinfo;
168ea4e54b9SDavid Nugent 	char		*hostname;
169ea4e54b9SDavid Nugent 	char		*anonuser;
170ea4e54b9SDavid Nugent 	char		*statfile;
171ea4e54b9SDavid Nugent 	char		*welcome;
172ea4e54b9SDavid Nugent 	char		*loginmsg;
173ea4e54b9SDavid Nugent } *thishost, *firsthost;
174ea4e54b9SDavid Nugent 
175ea4e54b9SDavid Nugent #endif
17604683b2cSYaroslav Tykhiy char	remotehost[NI_MAXHOST];
1773eb568f2SGuido van Rooij char	*ident = NULL;
178a5a4544eSPaul Traina 
179a5a4544eSPaul Traina static char	ttyline[20];
180a5a4544eSPaul Traina char		*tty = ttyline;		/* for klogin */
181a5a4544eSPaul Traina 
1825bc9d93dSMark Murray #ifdef USE_PAM
183e4bc453cSWarner Losh static int	auth_pam(struct passwd**, const char*);
1845bc9d93dSMark Murray pam_handle_t	*pamh = NULL;
18547499ecdSAndrey A. Chernov #endif
186fa1746c9SMark Murray 
187fa1746c9SMark Murray static struct opie	opiedata;
188fa1746c9SMark Murray static char		opieprompt[OPIE_CHALLENGE_MAX+1];
18947499ecdSAndrey A. Chernov static int		pwok;
1909aca17cbSMark Murray 
191125b9635SYaroslav Tykhiy char	*pid_file = NULL; /* means default location to pidfile(3) */
192105a3c98SJulian Elischer 
193ea022d16SRodney W. Grimes /*
1946d10cb2fSJonathan Lemon  * Limit number of pathnames that glob can return.
1956d10cb2fSJonathan Lemon  * A limit of 0 indicates the number of pathnames is unlimited.
1966d10cb2fSJonathan Lemon  */
1976d10cb2fSJonathan Lemon #define MAXGLOBARGS	16384
1986d10cb2fSJonathan Lemon #
1996d10cb2fSJonathan Lemon 
2006d10cb2fSJonathan Lemon /*
201ea022d16SRodney W. Grimes  * Timeout intervals for retrying connections
202ea022d16SRodney W. Grimes  * to hosts that don't accept PORT cmds.  This
203ea022d16SRodney W. Grimes  * is a kludge, but given the problems with TCP...
204ea022d16SRodney W. Grimes  */
205ea022d16SRodney W. Grimes #define	SWAITMAX	90	/* wait at most 90 seconds */
206ea022d16SRodney W. Grimes #define	SWAITINT	5	/* interval between retries */
207ea022d16SRodney W. Grimes 
208ea022d16SRodney W. Grimes int	swaitmax = SWAITMAX;
209ea022d16SRodney W. Grimes int	swaitint = SWAITINT;
210ea022d16SRodney W. Grimes 
211ea022d16SRodney W. Grimes #ifdef SETPROCTITLE
212b63e1fe2SPeter Wemm #ifdef OLD_SETPROCTITLE
213ea022d16SRodney W. Grimes char	**Argv = NULL;		/* pointer to argument vector */
214ea022d16SRodney W. Grimes char	*LastArgv = NULL;	/* end of argv */
215b63e1fe2SPeter Wemm #endif /* OLD_SETPROCTITLE */
216ea022d16SRodney W. Grimes char	proctitle[LINE_MAX];	/* initial part of title */
217ea022d16SRodney W. Grimes #endif /* SETPROCTITLE */
218ea022d16SRodney W. Grimes 
2196b2dee6bSYaroslav Tykhiy #define LOGCMD(cmd, file)		logcmd((cmd), (file), NULL, -1)
2206b2dee6bSYaroslav Tykhiy #define LOGCMD2(cmd, file1, file2)	logcmd((cmd), (file1), (file2), -1)
2216b2dee6bSYaroslav Tykhiy #define LOGBYTES(cmd, file, cnt)	logcmd((cmd), (file), NULL, (cnt))
222ea022d16SRodney W. Grimes 
2234cd51076SYaroslav Tykhiy static	volatile sig_atomic_t recvurg;
2244cd51076SYaroslav Tykhiy static	int transflag;		/* NB: for debugging only */
2254cd51076SYaroslav Tykhiy 
2264cd51076SYaroslav Tykhiy #define STARTXFER	flagxfer(1)
2274cd51076SYaroslav Tykhiy #define ENDXFER		flagxfer(0)
2284cd51076SYaroslav Tykhiy 
2294cd51076SYaroslav Tykhiy #define START_UNSAFE	maskurg(1)
2304cd51076SYaroslav Tykhiy #define END_UNSAFE	maskurg(0)
2314cd51076SYaroslav Tykhiy 
2324cd51076SYaroslav Tykhiy /* It's OK to put an `else' clause after this macro. */
2334cd51076SYaroslav Tykhiy #define CHECKOOB(action)						\
2344cd51076SYaroslav Tykhiy 	if (recvurg) {							\
2354cd51076SYaroslav Tykhiy 		recvurg = 0;						\
2364cd51076SYaroslav Tykhiy 		if (myoob()) {						\
2374cd51076SYaroslav Tykhiy 			ENDXFER;					\
2384cd51076SYaroslav Tykhiy 			action;						\
2394cd51076SYaroslav Tykhiy 		}							\
2404cd51076SYaroslav Tykhiy 	}
2414cd51076SYaroslav Tykhiy 
242ea4e54b9SDavid Nugent #ifdef VIRTUAL_HOSTING
2432c9fd5f2SHajimu UMEMOTO static void	 inithosts(int);
244e4bc453cSWarner Losh static void	 selecthost(union sockunion *);
245ea4e54b9SDavid Nugent #endif
246e4bc453cSWarner Losh static void	 ack(char *);
247e4bc453cSWarner Losh static void	 sigurg(int);
2484cd51076SYaroslav Tykhiy static void	 maskurg(int);
2494cd51076SYaroslav Tykhiy static void	 flagxfer(int);
2504cd51076SYaroslav Tykhiy static int	 myoob(void);
2518657b576SYaroslav Tykhiy static int	 checkuser(char *, char *, int, char **);
252e4bc453cSWarner Losh static FILE	*dataconn(char *, off_t, char *);
253e4bc453cSWarner Losh static void	 dolog(struct sockaddr *);
254e4bc453cSWarner Losh static void	 end_login(void);
255e4bc453cSWarner Losh static FILE	*getdatasock(char *);
256a117c345SYaroslav Tykhiy static int	 guniquefd(char *, char **);
257e4bc453cSWarner Losh static void	 lostconn(int);
258e4bc453cSWarner Losh static void	 sigquit(int);
259e4bc453cSWarner Losh static int	 receive_data(FILE *, FILE *);
2606e4b0a55SYaroslav Tykhiy static int	 send_data(FILE *, FILE *, size_t, off_t, int);
261ea022d16SRodney W. Grimes static struct passwd *
262e4bc453cSWarner Losh 		 sgetpwnam(char *);
263e4bc453cSWarner Losh static char	*sgetsave(char *);
264e4bc453cSWarner Losh static void	 reapchild(int);
265eb5b2bb3SYaroslav Tykhiy static void	 appendf(char **, char *, ...) __printflike(2, 3);
2666b2dee6bSYaroslav Tykhiy static void	 logcmd(char *, char *, char *, off_t);
267e4bc453cSWarner Losh static void      logxfer(char *, off_t, time_t);
268e4648f05SYaroslav Tykhiy static char	*doublequote(char *);
269206fe568SHajimu UMEMOTO static int	*socksetup(int, char *, const char *);
270ea022d16SRodney W. Grimes 
271ea022d16SRodney W. Grimes int
272e4bc453cSWarner Losh main(int argc, char *argv[], char **envp)
273ea022d16SRodney W. Grimes {
27478e3eed0SStefan Farfeleder 	socklen_t addrlen;
27578e3eed0SStefan Farfeleder 	int ch, on = 1, tos;
276ea022d16SRodney W. Grimes 	char *cp, line[LINE_MAX];
277ea022d16SRodney W. Grimes 	FILE *fd;
2784dd8b5abSYoshinobu Inoue 	char	*bindname = NULL;
27963591ba5SYaroslav Tykhiy 	const char *bindport = "ftp";
2804dd8b5abSYoshinobu Inoue 	int	family = AF_UNSPEC;
2814b82fc95SYaroslav Tykhiy 	struct sigaction sa;
282ea022d16SRodney W. Grimes 
28334d1ba5cSAndrey A. Chernov 	tzset();		/* in case no timezone database in ~ftp */
2844b82fc95SYaroslav Tykhiy 	sigemptyset(&sa.sa_mask);
2854b82fc95SYaroslav Tykhiy 	sa.sa_flags = SA_RESTART;
28634d1ba5cSAndrey A. Chernov 
287b63e1fe2SPeter Wemm #ifdef OLD_SETPROCTITLE
288ea022d16SRodney W. Grimes 	/*
289ea022d16SRodney W. Grimes 	 *  Save start and extent of argv for setproctitle.
290ea022d16SRodney W. Grimes 	 */
291ea022d16SRodney W. Grimes 	Argv = argv;
292ea022d16SRodney W. Grimes 	while (*envp)
293ea022d16SRodney W. Grimes 		envp++;
294ea022d16SRodney W. Grimes 	LastArgv = envp[-1] + strlen(envp[-1]);
295b63e1fe2SPeter Wemm #endif /* OLD_SETPROCTITLE */
296ea022d16SRodney W. Grimes 
2976c98f401SYaroslav Tykhiy 	/*
2986c98f401SYaroslav Tykhiy 	 * Prevent diagnostic messages from appearing on stderr.
2996c98f401SYaroslav Tykhiy 	 * We run as a daemon or from inetd; in both cases, there's
3006c98f401SYaroslav Tykhiy 	 * more reason in logging to syslog.
3016c98f401SYaroslav Tykhiy 	 */
3026c98f401SYaroslav Tykhiy 	(void) freopen(_PATH_DEVNULL, "w", stderr);
3036c98f401SYaroslav Tykhiy 	opterr = 0;
3046c98f401SYaroslav Tykhiy 
3056c98f401SYaroslav Tykhiy 	/*
3066c98f401SYaroslav Tykhiy 	 * LOG_NDELAY sets up the logging connection immediately,
3076c98f401SYaroslav Tykhiy 	 * necessary for anonymous ftp's that chroot and can't do it later.
3086c98f401SYaroslav Tykhiy 	 */
3096c98f401SYaroslav Tykhiy 	openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
3103eb568f2SGuido van Rooij 
311c152df28SYaroslav Tykhiy 	while ((ch = getopt(argc, argv,
3122ea42282SYaroslav Tykhiy 	                    "468a:AdDEhlmMoOp:P:rRSt:T:u:UvW")) != -1) {
313ea022d16SRodney W. Grimes 		switch (ch) {
3140e063efeSYaroslav Tykhiy 		case '4':
315206fe568SHajimu UMEMOTO 			family = (family == AF_INET6) ? AF_UNSPEC : AF_INET;
3160e063efeSYaroslav Tykhiy 			break;
3170e063efeSYaroslav Tykhiy 
3180e063efeSYaroslav Tykhiy 		case '6':
319206fe568SHajimu UMEMOTO 			family = (family == AF_INET) ? AF_UNSPEC : AF_INET6;
3200e063efeSYaroslav Tykhiy 			break;
3210e063efeSYaroslav Tykhiy 
3222ea42282SYaroslav Tykhiy 		case '8':
3232ea42282SYaroslav Tykhiy 			assumeutf8 = 1;
3242ea42282SYaroslav Tykhiy 			break;
3252ea42282SYaroslav Tykhiy 
3260e063efeSYaroslav Tykhiy 		case 'a':
3270e063efeSYaroslav Tykhiy 			bindname = optarg;
3280e063efeSYaroslav Tykhiy 			break;
3290e063efeSYaroslav Tykhiy 
3300e063efeSYaroslav Tykhiy 		case 'A':
3310e063efeSYaroslav Tykhiy 			anon_only = 1;
332cf09a206SDavid Greenman 			break;
333cf09a206SDavid Greenman 
334ea022d16SRodney W. Grimes 		case 'd':
335618b0bbaSMark Murray 			ftpdebug++;
336ea022d16SRodney W. Grimes 			break;
337ea022d16SRodney W. Grimes 
3380e063efeSYaroslav Tykhiy 		case 'D':
3390e063efeSYaroslav Tykhiy 			daemon_mode++;
3400e063efeSYaroslav Tykhiy 			break;
3410e063efeSYaroslav Tykhiy 
342a4b77a2aSPoul-Henning Kamp 		case 'E':
343a4b77a2aSPoul-Henning Kamp 			noepsv = 1;
344a4b77a2aSPoul-Henning Kamp 			break;
345a4b77a2aSPoul-Henning Kamp 
346c152df28SYaroslav Tykhiy 		case 'h':
347c152df28SYaroslav Tykhiy 			hostinfo = 0;
348c152df28SYaroslav Tykhiy 			break;
349c152df28SYaroslav Tykhiy 
350ea022d16SRodney W. Grimes 		case 'l':
351ea022d16SRodney W. Grimes 			logging++;	/* > 1 == extra logging */
352ea022d16SRodney W. Grimes 			break;
353ea022d16SRodney W. Grimes 
354a117c345SYaroslav Tykhiy 		case 'm':
355a117c345SYaroslav Tykhiy 			noguestmod = 0;
356a117c345SYaroslav Tykhiy 			break;
357a117c345SYaroslav Tykhiy 
3580e063efeSYaroslav Tykhiy 		case 'M':
3590e063efeSYaroslav Tykhiy 			noguestmkd = 1;
3600e063efeSYaroslav Tykhiy 			break;
3610e063efeSYaroslav Tykhiy 
3620e063efeSYaroslav Tykhiy 		case 'o':
3630e063efeSYaroslav Tykhiy 			noretr = 1;
3640e063efeSYaroslav Tykhiy 			break;
3650e063efeSYaroslav Tykhiy 
3660e063efeSYaroslav Tykhiy 		case 'O':
3670e063efeSYaroslav Tykhiy 			noguestretr = 1;
3680e063efeSYaroslav Tykhiy 			break;
3690e063efeSYaroslav Tykhiy 
3700e063efeSYaroslav Tykhiy 		case 'p':
3710e063efeSYaroslav Tykhiy 			pid_file = optarg;
3720e063efeSYaroslav Tykhiy 			break;
3730e063efeSYaroslav Tykhiy 
37463591ba5SYaroslav Tykhiy 		case 'P':
37563591ba5SYaroslav Tykhiy 			bindport = optarg;
37663591ba5SYaroslav Tykhiy 			break;
37763591ba5SYaroslav Tykhiy 
378a4b77a2aSPoul-Henning Kamp 		case 'r':
379a4b77a2aSPoul-Henning Kamp 			readonly = 1;
380a4b77a2aSPoul-Henning Kamp 			break;
381a4b77a2aSPoul-Henning Kamp 
382a5a4544eSPaul Traina 		case 'R':
383a5a4544eSPaul Traina 			paranoid = 0;
384a5a4544eSPaul Traina 			break;
385a5a4544eSPaul Traina 
386a5a4544eSPaul Traina 		case 'S':
387a5a4544eSPaul Traina 			stats++;
388a5a4544eSPaul Traina 			break;
389a5a4544eSPaul Traina 
390ea022d16SRodney W. Grimes 		case 't':
391ea022d16SRodney W. Grimes 			timeout = atoi(optarg);
392ea022d16SRodney W. Grimes 			if (maxtimeout < timeout)
393ea022d16SRodney W. Grimes 				maxtimeout = timeout;
394ea022d16SRodney W. Grimes 			break;
395a5a4544eSPaul Traina 
3960e063efeSYaroslav Tykhiy 		case 'T':
3970e063efeSYaroslav Tykhiy 			maxtimeout = atoi(optarg);
3980e063efeSYaroslav Tykhiy 			if (timeout > maxtimeout)
3990e063efeSYaroslav Tykhiy 				timeout = maxtimeout;
400105a3c98SJulian Elischer 			break;
401105a3c98SJulian Elischer 
402ea022d16SRodney W. Grimes 		case 'u':
403ea022d16SRodney W. Grimes 		    {
404ea022d16SRodney W. Grimes 			long val = 0;
405ea022d16SRodney W. Grimes 
406ea022d16SRodney W. Grimes 			val = strtol(optarg, &optarg, 8);
407ea022d16SRodney W. Grimes 			if (*optarg != '\0' || val < 0)
4086c98f401SYaroslav Tykhiy 				syslog(LOG_WARNING, "bad value for -u");
409ea022d16SRodney W. Grimes 			else
410ea022d16SRodney W. Grimes 				defumask = val;
411ea022d16SRodney W. Grimes 			break;
412ea022d16SRodney W. Grimes 		    }
4130e063efeSYaroslav Tykhiy 		case 'U':
4140e063efeSYaroslav Tykhiy 			restricted_data_ports = 0;
4155a392aecSTorsten Blum 			break;
416ea022d16SRodney W. Grimes 
417ea022d16SRodney W. Grimes 		case 'v':
41893bd9dc5SYaroslav Tykhiy 			ftpdebug++;
419ea022d16SRodney W. Grimes 			break;
420ea022d16SRodney W. Grimes 
4215d7e0128SYaroslav Tykhiy 		case 'W':
4225d7e0128SYaroslav Tykhiy 			dowtmp = 0;
4235d7e0128SYaroslav Tykhiy 			break;
4245d7e0128SYaroslav Tykhiy 
425ea022d16SRodney W. Grimes 		default:
4266c98f401SYaroslav Tykhiy 			syslog(LOG_WARNING, "unknown flag -%c ignored", optopt);
427ea022d16SRodney W. Grimes 			break;
428ea022d16SRodney W. Grimes 		}
429ea022d16SRodney W. Grimes 	}
430cf09a206SDavid Greenman 
431cf09a206SDavid Greenman 	if (daemon_mode) {
432206fe568SHajimu UMEMOTO 		int *ctl_sock, fd, maxfd = -1, nfds, i;
433206fe568SHajimu UMEMOTO 		fd_set defreadfds, readfds;
434206fe568SHajimu UMEMOTO 		pid_t pid;
435125b9635SYaroslav Tykhiy 		struct pidfh *pfh;
436125b9635SYaroslav Tykhiy 
437125b9635SYaroslav Tykhiy 		if ((pfh = pidfile_open(pid_file, 0600, &pid)) == NULL) {
438125b9635SYaroslav Tykhiy 			if (errno == EEXIST) {
439125b9635SYaroslav Tykhiy 				syslog(LOG_ERR, "%s already running, pid %d",
440125b9635SYaroslav Tykhiy 				       getprogname(), (int)pid);
441125b9635SYaroslav Tykhiy 				exit(1);
442125b9635SYaroslav Tykhiy 			}
443125b9635SYaroslav Tykhiy 			syslog(LOG_WARNING, "pidfile_open: %m");
444125b9635SYaroslav Tykhiy 		}
445cf09a206SDavid Greenman 
446cf09a206SDavid Greenman 		/*
447cf09a206SDavid Greenman 		 * Detach from parent.
448cf09a206SDavid Greenman 		 */
449cf09a206SDavid Greenman 		if (daemon(1, 1) < 0) {
450cf09a206SDavid Greenman 			syslog(LOG_ERR, "failed to become a daemon");
451cf09a206SDavid Greenman 			exit(1);
452cf09a206SDavid Greenman 		}
453125b9635SYaroslav Tykhiy 
454125b9635SYaroslav Tykhiy 		if (pfh != NULL && pidfile_write(pfh) == -1)
455125b9635SYaroslav Tykhiy 			syslog(LOG_WARNING, "pidfile_write: %m");
456125b9635SYaroslav Tykhiy 
4574b82fc95SYaroslav Tykhiy 		sa.sa_handler = reapchild;
4584b82fc95SYaroslav Tykhiy 		(void)sigaction(SIGCHLD, &sa, NULL);
4594dd8b5abSYoshinobu Inoue 
4602c9fd5f2SHajimu UMEMOTO #ifdef VIRTUAL_HOSTING
4612c9fd5f2SHajimu UMEMOTO 		inithosts(family);
4622c9fd5f2SHajimu UMEMOTO #endif
4632c9fd5f2SHajimu UMEMOTO 
464cf09a206SDavid Greenman 		/*
465cf09a206SDavid Greenman 		 * Open a socket, bind it to the FTP port, and start
466cf09a206SDavid Greenman 		 * listening.
467cf09a206SDavid Greenman 		 */
468206fe568SHajimu UMEMOTO 		ctl_sock = socksetup(family, bindname, bindport);
469206fe568SHajimu UMEMOTO 		if (ctl_sock == NULL)
470cf09a206SDavid Greenman 			exit(1);
471206fe568SHajimu UMEMOTO 
472206fe568SHajimu UMEMOTO 		FD_ZERO(&defreadfds);
473206fe568SHajimu UMEMOTO 		for (i = 1; i <= *ctl_sock; i++) {
474206fe568SHajimu UMEMOTO 			FD_SET(ctl_sock[i], &defreadfds);
475206fe568SHajimu UMEMOTO 			if (listen(ctl_sock[i], 32) < 0) {
476cf09a206SDavid Greenman 				syslog(LOG_ERR, "control listen: %m");
477cf09a206SDavid Greenman 				exit(1);
478cf09a206SDavid Greenman 			}
479206fe568SHajimu UMEMOTO 			if (maxfd < ctl_sock[i])
480206fe568SHajimu UMEMOTO 				maxfd = ctl_sock[i];
481206fe568SHajimu UMEMOTO 		}
482206fe568SHajimu UMEMOTO 
483cf09a206SDavid Greenman 		/*
484cf09a206SDavid Greenman 		 * Loop forever accepting connection requests and forking off
485cf09a206SDavid Greenman 		 * children to handle them.
486cf09a206SDavid Greenman 		 */
487cf09a206SDavid Greenman 		while (1) {
488206fe568SHajimu UMEMOTO 			FD_COPY(&defreadfds, &readfds);
489206fe568SHajimu UMEMOTO 			nfds = select(maxfd + 1, &readfds, NULL, NULL, 0);
490206fe568SHajimu UMEMOTO 			if (nfds <= 0) {
491206fe568SHajimu UMEMOTO 				if (nfds < 0 && errno != EINTR)
492206fe568SHajimu UMEMOTO 					syslog(LOG_WARNING, "select: %m");
493206fe568SHajimu UMEMOTO 				continue;
494206fe568SHajimu UMEMOTO 			}
495206fe568SHajimu UMEMOTO 
496206fe568SHajimu UMEMOTO 			pid = -1;
497206fe568SHajimu UMEMOTO                         for (i = 1; i <= *ctl_sock; i++)
498206fe568SHajimu UMEMOTO 				if (FD_ISSET(ctl_sock[i], &readfds)) {
499206fe568SHajimu UMEMOTO 					addrlen = sizeof(his_addr);
500206fe568SHajimu UMEMOTO 					fd = accept(ctl_sock[i],
501206fe568SHajimu UMEMOTO 					    (struct sockaddr *)&his_addr,
502206fe568SHajimu UMEMOTO 					    &addrlen);
503a599a64aSYaroslav Tykhiy 					if (fd == -1) {
504a599a64aSYaroslav Tykhiy 						syslog(LOG_WARNING,
505a599a64aSYaroslav Tykhiy 						       "accept: %m");
506a599a64aSYaroslav Tykhiy 						continue;
507cf09a206SDavid Greenman 					}
508a599a64aSYaroslav Tykhiy 					switch (pid = fork()) {
509a599a64aSYaroslav Tykhiy 					case 0:
5108eb0508fSYaroslav Tykhiy 						/* child */
5118eb0508fSYaroslav Tykhiy 						(void) dup2(fd, 0);
5128eb0508fSYaroslav Tykhiy 						(void) dup2(fd, 1);
513a599a64aSYaroslav Tykhiy 						(void) close(fd);
514a599a64aSYaroslav Tykhiy 						for (i = 1; i <= *ctl_sock; i++)
5158eb0508fSYaroslav Tykhiy 							close(ctl_sock[i]);
516125b9635SYaroslav Tykhiy 						if (pfh != NULL)
517125b9635SYaroslav Tykhiy 							pidfile_close(pfh);
518a599a64aSYaroslav Tykhiy 						goto gotchild;
519a599a64aSYaroslav Tykhiy 					case -1:
520a599a64aSYaroslav Tykhiy 						syslog(LOG_WARNING, "fork: %m");
521a599a64aSYaroslav Tykhiy 						/* FALLTHROUGH */
522a599a64aSYaroslav Tykhiy 					default:
523a599a64aSYaroslav Tykhiy 						close(fd);
524a599a64aSYaroslav Tykhiy 					}
525206fe568SHajimu UMEMOTO 				}
526125b9635SYaroslav Tykhiy 		}
527cf09a206SDavid Greenman 	} else {
528cf09a206SDavid Greenman 		addrlen = sizeof(his_addr);
529cf09a206SDavid Greenman 		if (getpeername(0, (struct sockaddr *)&his_addr, &addrlen) < 0) {
530cf09a206SDavid Greenman 			syslog(LOG_ERR, "getpeername (%s): %m",argv[0]);
531cf09a206SDavid Greenman 			exit(1);
532cf09a206SDavid Greenman 		}
5332c9fd5f2SHajimu UMEMOTO 
5342c9fd5f2SHajimu UMEMOTO #ifdef VIRTUAL_HOSTING
5352c9fd5f2SHajimu UMEMOTO 		if (his_addr.su_family == AF_INET6 &&
5362c9fd5f2SHajimu UMEMOTO 		    IN6_IS_ADDR_V4MAPPED(&his_addr.su_sin6.sin6_addr))
5372c9fd5f2SHajimu UMEMOTO 			family = AF_INET;
5382c9fd5f2SHajimu UMEMOTO 		else
5392c9fd5f2SHajimu UMEMOTO 			family = his_addr.su_family;
5402c9fd5f2SHajimu UMEMOTO 		inithosts(family);
5412c9fd5f2SHajimu UMEMOTO #endif
542cf09a206SDavid Greenman 	}
543cf09a206SDavid Greenman 
544a599a64aSYaroslav Tykhiy gotchild:
5454b82fc95SYaroslav Tykhiy 	sa.sa_handler = SIG_DFL;
5464b82fc95SYaroslav Tykhiy 	(void)sigaction(SIGCHLD, &sa, NULL);
5474b82fc95SYaroslav Tykhiy 
5484b82fc95SYaroslav Tykhiy 	sa.sa_handler = sigurg;
5494b82fc95SYaroslav Tykhiy 	sa.sa_flags = 0;		/* don't restart syscalls for SIGURG */
5504b82fc95SYaroslav Tykhiy 	(void)sigaction(SIGURG, &sa, NULL);
5514b82fc95SYaroslav Tykhiy 
5524b82fc95SYaroslav Tykhiy 	sigfillset(&sa.sa_mask);	/* block all signals in handler */
5534b82fc95SYaroslav Tykhiy 	sa.sa_flags = SA_RESTART;
5544b82fc95SYaroslav Tykhiy 	sa.sa_handler = sigquit;
5554b82fc95SYaroslav Tykhiy 	(void)sigaction(SIGHUP, &sa, NULL);
5564b82fc95SYaroslav Tykhiy 	(void)sigaction(SIGINT, &sa, NULL);
5574b82fc95SYaroslav Tykhiy 	(void)sigaction(SIGQUIT, &sa, NULL);
5584b82fc95SYaroslav Tykhiy 	(void)sigaction(SIGTERM, &sa, NULL);
5594b82fc95SYaroslav Tykhiy 
5604b82fc95SYaroslav Tykhiy 	sa.sa_handler = lostconn;
5614b82fc95SYaroslav Tykhiy 	(void)sigaction(SIGPIPE, &sa, NULL);
562ea022d16SRodney W. Grimes 
563cf09a206SDavid Greenman 	addrlen = sizeof(ctrl_addr);
564cf09a206SDavid Greenman 	if (getsockname(0, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) {
565cf09a206SDavid Greenman 		syslog(LOG_ERR, "getsockname (%s): %m",argv[0]);
566cf09a206SDavid Greenman 		exit(1);
567cf09a206SDavid Greenman 	}
56863591ba5SYaroslav Tykhiy 	dataport = ntohs(ctrl_addr.su_port) - 1; /* as per RFC 959 */
569ea4e54b9SDavid Nugent #ifdef VIRTUAL_HOSTING
570ea4e54b9SDavid Nugent 	/* select our identity from virtual host table */
5714dd8b5abSYoshinobu Inoue 	selecthost(&ctrl_addr);
572ea4e54b9SDavid Nugent #endif
573cf09a206SDavid Greenman #ifdef IP_TOS
5744dd8b5abSYoshinobu Inoue 	if (ctrl_addr.su_family == AF_INET)
5754dd8b5abSYoshinobu Inoue       {
576cf09a206SDavid Greenman 	tos = IPTOS_LOWDELAY;
57757d4ef07SYaroslav Tykhiy 	if (setsockopt(0, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
578406d1ae9SYaroslav Tykhiy 		syslog(LOG_WARNING, "control setsockopt (IP_TOS): %m");
5794dd8b5abSYoshinobu Inoue       }
580cf09a206SDavid Greenman #endif
581dadb9fb3SDavid Greenman 	/*
582dadb9fb3SDavid Greenman 	 * Disable Nagle on the control channel so that we don't have to wait
583dadb9fb3SDavid Greenman 	 * for peer's ACK before issuing our next reply.
584dadb9fb3SDavid Greenman 	 */
585dadb9fb3SDavid Greenman 	if (setsockopt(0, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) < 0)
586406d1ae9SYaroslav Tykhiy 		syslog(LOG_WARNING, "control setsockopt (TCP_NODELAY): %m");
587dadb9fb3SDavid Greenman 
5884dd8b5abSYoshinobu Inoue 	data_source.su_port = htons(ntohs(ctrl_addr.su_port) - 1);
589cf09a206SDavid Greenman 
590a5a4544eSPaul Traina 	/* set this here so klogin can use it... */
591e760ef2cSWarner Losh 	(void)snprintf(ttyline, sizeof(ttyline), "ftp%d", getpid());
592a5a4544eSPaul Traina 
593ea022d16SRodney W. Grimes 	/* Try to handle urgent data inline */
594ea022d16SRodney W. Grimes #ifdef SO_OOBINLINE
59557d4ef07SYaroslav Tykhiy 	if (setsockopt(0, SOL_SOCKET, SO_OOBINLINE, &on, sizeof(on)) < 0)
596406d1ae9SYaroslav Tykhiy 		syslog(LOG_WARNING, "control setsockopt (SO_OOBINLINE): %m");
597ea022d16SRodney W. Grimes #endif
598ea022d16SRodney W. Grimes 
599ea022d16SRodney W. Grimes #ifdef	F_SETOWN
600ea022d16SRodney W. Grimes 	if (fcntl(fileno(stdin), F_SETOWN, getpid()) == -1)
601ea022d16SRodney W. Grimes 		syslog(LOG_ERR, "fcntl F_SETOWN: %m");
602ea022d16SRodney W. Grimes #endif
6034dd8b5abSYoshinobu Inoue 	dolog((struct sockaddr *)&his_addr);
604ea022d16SRodney W. Grimes 	/*
605ea022d16SRodney W. Grimes 	 * Set up default state
606ea022d16SRodney W. Grimes 	 */
607ea022d16SRodney W. Grimes 	data = -1;
608ea022d16SRodney W. Grimes 	type = TYPE_A;
609ea022d16SRodney W. Grimes 	form = FORM_N;
610ea022d16SRodney W. Grimes 	stru = STRU_F;
611ea022d16SRodney W. Grimes 	mode = MODE_S;
612ea022d16SRodney W. Grimes 	tmpline[0] = '\0';
613ea022d16SRodney W. Grimes 
614ea022d16SRodney W. Grimes 	/* If logins are disabled, print out the message. */
615ea022d16SRodney W. Grimes 	if ((fd = fopen(_PATH_NOLOGIN,"r")) != NULL) {
616ea022d16SRodney W. Grimes 		while (fgets(line, sizeof(line), fd) != NULL) {
617ea022d16SRodney W. Grimes 			if ((cp = strchr(line, '\n')) != NULL)
618ea022d16SRodney W. Grimes 				*cp = '\0';
619ea022d16SRodney W. Grimes 			lreply(530, "%s", line);
620ea022d16SRodney W. Grimes 		}
621ea022d16SRodney W. Grimes 		(void) fflush(stdout);
622ea022d16SRodney W. Grimes 		(void) fclose(fd);
623ea022d16SRodney W. Grimes 		reply(530, "System not available.");
624ea022d16SRodney W. Grimes 		exit(0);
625ea022d16SRodney W. Grimes 	}
626ea4e54b9SDavid Nugent #ifdef VIRTUAL_HOSTING
62763047c6fSDavid E. O'Brien 	fd = fopen(thishost->welcome, "r");
628ea4e54b9SDavid Nugent #else
62963047c6fSDavid E. O'Brien 	fd = fopen(_PATH_FTPWELCOME, "r");
630ea4e54b9SDavid Nugent #endif
63163047c6fSDavid E. O'Brien 	if (fd != NULL) {
632ea022d16SRodney W. Grimes 		while (fgets(line, sizeof(line), fd) != NULL) {
633ea022d16SRodney W. Grimes 			if ((cp = strchr(line, '\n')) != NULL)
634ea022d16SRodney W. Grimes 				*cp = '\0';
635ea022d16SRodney W. Grimes 			lreply(220, "%s", line);
636ea022d16SRodney W. Grimes 		}
637ea022d16SRodney W. Grimes 		(void) fflush(stdout);
638ea022d16SRodney W. Grimes 		(void) fclose(fd);
639ea022d16SRodney W. Grimes 		/* reply(220,) must follow */
640ea022d16SRodney W. Grimes 	}
641ea4e54b9SDavid Nugent #ifndef VIRTUAL_HOSTING
6420512556aSDavid Nugent 	if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
643618b0bbaSMark Murray 		fatalerror("Ran out of memory.");
64404683b2cSYaroslav Tykhiy 	if (gethostname(hostname, MAXHOSTNAMELEN - 1) < 0)
64504683b2cSYaroslav Tykhiy 		hostname[0] = '\0';
6469e9a43bdSBrian Somers 	hostname[MAXHOSTNAMELEN - 1] = '\0';
647ea4e54b9SDavid Nugent #endif
648c152df28SYaroslav Tykhiy 	if (hostinfo)
649ea022d16SRodney W. Grimes 		reply(220, "%s FTP server (%s) ready.", hostname, version);
650c152df28SYaroslav Tykhiy 	else
651c152df28SYaroslav Tykhiy 		reply(220, "FTP server ready.");
652ea022d16SRodney W. Grimes 	for (;;)
653ea022d16SRodney W. Grimes 		(void) yyparse();
654ea022d16SRodney W. Grimes 	/* NOTREACHED */
655ea022d16SRodney W. Grimes }
656ea022d16SRodney W. Grimes 
657ea022d16SRodney W. Grimes static void
658e4bc453cSWarner Losh lostconn(int signo)
659ea022d16SRodney W. Grimes {
660ea022d16SRodney W. Grimes 
661618b0bbaSMark Murray 	if (ftpdebug)
662ea022d16SRodney W. Grimes 		syslog(LOG_DEBUG, "lost connection");
663e02897faSPhilippe Charnier 	dologout(1);
664ea022d16SRodney W. Grimes }
665ea022d16SRodney W. Grimes 
6664b82fc95SYaroslav Tykhiy static void
667e4bc453cSWarner Losh sigquit(int signo)
6684b82fc95SYaroslav Tykhiy {
6694b82fc95SYaroslav Tykhiy 
6704b82fc95SYaroslav Tykhiy 	syslog(LOG_ERR, "got signal %d", signo);
6714b82fc95SYaroslav Tykhiy 	dologout(1);
6724b82fc95SYaroslav Tykhiy }
6734b82fc95SYaroslav Tykhiy 
674ea4e54b9SDavid Nugent #ifdef VIRTUAL_HOSTING
675ea4e54b9SDavid Nugent /*
676ea4e54b9SDavid Nugent  * read in virtual host tables (if they exist)
677ea4e54b9SDavid Nugent  */
678ea4e54b9SDavid Nugent 
679ea4e54b9SDavid Nugent static void
6802c9fd5f2SHajimu UMEMOTO inithosts(int family)
681ea4e54b9SDavid Nugent {
68255b54aa7SYaroslav Tykhiy 	int insert;
683737d08f3SYaroslav Tykhiy 	size_t len;
684ea4e54b9SDavid Nugent 	FILE *fp;
685737d08f3SYaroslav Tykhiy 	char *cp, *mp, *line;
686737d08f3SYaroslav Tykhiy 	char *hostname;
68755b54aa7SYaroslav Tykhiy 	char *vhost, *anonuser, *statfile, *welcome, *loginmsg;
688ea4e54b9SDavid Nugent 	struct ftphost *hrp, *lhrp;
6894dd8b5abSYoshinobu Inoue 	struct addrinfo hints, *res, *ai;
690ea4e54b9SDavid Nugent 
691ea4e54b9SDavid Nugent 	/*
692ea4e54b9SDavid Nugent 	 * Fill in the default host information
693ea4e54b9SDavid Nugent 	 */
694737d08f3SYaroslav Tykhiy 	if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
695618b0bbaSMark Murray 		fatalerror("Ran out of memory.");
69604683b2cSYaroslav Tykhiy 	if (gethostname(hostname, MAXHOSTNAMELEN - 1) < 0)
697737d08f3SYaroslav Tykhiy 		hostname[0] = '\0';
698737d08f3SYaroslav Tykhiy 	hostname[MAXHOSTNAMELEN - 1] = '\0';
699737d08f3SYaroslav Tykhiy 	if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
700737d08f3SYaroslav Tykhiy 		fatalerror("Ran out of memory.");
701737d08f3SYaroslav Tykhiy 	hrp->hostname = hostname;
702f38c6cadSYoshinobu Inoue 	hrp->hostinfo = NULL;
7034dd8b5abSYoshinobu Inoue 
7044dd8b5abSYoshinobu Inoue 	memset(&hints, 0, sizeof(hints));
7052c9fd5f2SHajimu UMEMOTO 	hints.ai_flags = AI_PASSIVE;
7062c9fd5f2SHajimu UMEMOTO 	hints.ai_family = family;
7072c9fd5f2SHajimu UMEMOTO 	hints.ai_socktype = SOCK_STREAM;
708b1d8d5cdSYaroslav Tykhiy 	if (getaddrinfo(hrp->hostname, NULL, &hints, &res) == 0)
709f38c6cadSYoshinobu Inoue 		hrp->hostinfo = res;
710ea4e54b9SDavid Nugent 	hrp->statfile = _PATH_FTPDSTATFILE;
711ea4e54b9SDavid Nugent 	hrp->welcome  = _PATH_FTPWELCOME;
712ea4e54b9SDavid Nugent 	hrp->loginmsg = _PATH_FTPLOGINMESG;
713ea4e54b9SDavid Nugent 	hrp->anonuser = "ftp";
714ea4e54b9SDavid Nugent 	hrp->next = NULL;
715ea4e54b9SDavid Nugent 	thishost = firsthost = lhrp = hrp;
716ea4e54b9SDavid Nugent 	if ((fp = fopen(_PATH_FTPHOSTS, "r")) != NULL) {
717ec009cf0SYaroslav Tykhiy 		int addrsize, gothost;
7184dd8b5abSYoshinobu Inoue 		void *addr;
7194dd8b5abSYoshinobu Inoue 		struct hostent *hp;
7204dd8b5abSYoshinobu Inoue 
721737d08f3SYaroslav Tykhiy 		while ((line = fgetln(fp, &len)) != NULL) {
7224dd8b5abSYoshinobu Inoue 			int	i, hp_error;
723ea4e54b9SDavid Nugent 
724737d08f3SYaroslav Tykhiy 			/* skip comments */
725737d08f3SYaroslav Tykhiy 			if (line[0] == '#')
726ea4e54b9SDavid Nugent 				continue;
727737d08f3SYaroslav Tykhiy 			if (line[len - 1] == '\n') {
728737d08f3SYaroslav Tykhiy 				line[len - 1] = '\0';
729737d08f3SYaroslav Tykhiy 				mp = NULL;
730737d08f3SYaroslav Tykhiy 			} else {
731737d08f3SYaroslav Tykhiy 				if ((mp = malloc(len + 1)) == NULL)
732737d08f3SYaroslav Tykhiy 					fatalerror("Ran out of memory.");
733737d08f3SYaroslav Tykhiy 				memcpy(mp, line, len);
734737d08f3SYaroslav Tykhiy 				mp[len] = '\0';
735737d08f3SYaroslav Tykhiy 				line = mp;
736ea4e54b9SDavid Nugent 			}
737ea4e54b9SDavid Nugent 			cp = strtok(line, " \t");
738737d08f3SYaroslav Tykhiy 			/* skip empty lines */
739737d08f3SYaroslav Tykhiy 			if (cp == NULL)
740737d08f3SYaroslav Tykhiy 				goto nextline;
74155b54aa7SYaroslav Tykhiy 			vhost = cp;
74255b54aa7SYaroslav Tykhiy 
74355b54aa7SYaroslav Tykhiy 			/* set defaults */
74455b54aa7SYaroslav Tykhiy 			anonuser = "ftp";
74555b54aa7SYaroslav Tykhiy 			statfile = _PATH_FTPDSTATFILE;
74655b54aa7SYaroslav Tykhiy 			welcome  = _PATH_FTPWELCOME;
74755b54aa7SYaroslav Tykhiy 			loginmsg = _PATH_FTPLOGINMESG;
74855b54aa7SYaroslav Tykhiy 
74955b54aa7SYaroslav Tykhiy 			/*
75055b54aa7SYaroslav Tykhiy 			 * Preparse the line so we can use its info
75155b54aa7SYaroslav Tykhiy 			 * for all the addresses associated with
75255b54aa7SYaroslav Tykhiy 			 * the virtual host name.
75355b54aa7SYaroslav Tykhiy 			 * Field 0, the virtual host name, is special:
75455b54aa7SYaroslav Tykhiy 			 * it's already parsed off and will be strdup'ed
75555b54aa7SYaroslav Tykhiy 			 * later, after we know its canonical form.
75655b54aa7SYaroslav Tykhiy 			 */
75755b54aa7SYaroslav Tykhiy 			for (i = 1; i < 5 && (cp = strtok(NULL, " \t")); i++)
75855b54aa7SYaroslav Tykhiy 				if (*cp != '-' && (cp = strdup(cp)))
75955b54aa7SYaroslav Tykhiy 					switch (i) {
76055b54aa7SYaroslav Tykhiy 					case 1:	/* anon user permissions */
76155b54aa7SYaroslav Tykhiy 						anonuser = cp;
76255b54aa7SYaroslav Tykhiy 						break;
76355b54aa7SYaroslav Tykhiy 					case 2: /* statistics file */
76455b54aa7SYaroslav Tykhiy 						statfile = cp;
76555b54aa7SYaroslav Tykhiy 						break;
76655b54aa7SYaroslav Tykhiy 					case 3: /* welcome message */
76755b54aa7SYaroslav Tykhiy 						welcome  = cp;
76855b54aa7SYaroslav Tykhiy 						break;
76955b54aa7SYaroslav Tykhiy 					case 4: /* login message */
77055b54aa7SYaroslav Tykhiy 						loginmsg = cp;
77155b54aa7SYaroslav Tykhiy 						break;
77255b54aa7SYaroslav Tykhiy 					default: /* programming error */
77355b54aa7SYaroslav Tykhiy 						abort();
77455b54aa7SYaroslav Tykhiy 						/* NOTREACHED */
77555b54aa7SYaroslav Tykhiy 					}
7764dd8b5abSYoshinobu Inoue 
7774dd8b5abSYoshinobu Inoue 			hints.ai_flags = AI_PASSIVE;
7782c9fd5f2SHajimu UMEMOTO 			hints.ai_family = family;
7792c9fd5f2SHajimu UMEMOTO 			hints.ai_socktype = SOCK_STREAM;
780b1d8d5cdSYaroslav Tykhiy 			if (getaddrinfo(vhost, NULL, &hints, &res) != 0)
781737d08f3SYaroslav Tykhiy 				goto nextline;
7824dd8b5abSYoshinobu Inoue 			for (ai = res; ai != NULL && ai->ai_addr != NULL;
783b535a9bfSDavid Nugent 			     ai = ai->ai_next) {
7844dd8b5abSYoshinobu Inoue 
785b535a9bfSDavid Nugent 			gothost = 0;
786ea4e54b9SDavid Nugent 			for (hrp = firsthost; hrp != NULL; hrp = hrp->next) {
787f38c6cadSYoshinobu Inoue 				struct addrinfo *hi;
788f38c6cadSYoshinobu Inoue 
789f38c6cadSYoshinobu Inoue 				for (hi = hrp->hostinfo; hi != NULL;
790f38c6cadSYoshinobu Inoue 				     hi = hi->ai_next)
791f38c6cadSYoshinobu Inoue 					if (hi->ai_addrlen == ai->ai_addrlen &&
792f38c6cadSYoshinobu Inoue 					    memcmp(hi->ai_addr,
7934dd8b5abSYoshinobu Inoue 						   ai->ai_addr,
794b535a9bfSDavid Nugent 						   ai->ai_addr->sa_len) == 0) {
795b535a9bfSDavid Nugent 						gothost++;
796b535a9bfSDavid Nugent 						break;
797b535a9bfSDavid Nugent 					}
798b535a9bfSDavid Nugent 				if (gothost)
799ea4e54b9SDavid Nugent 					break;
800ea4e54b9SDavid Nugent 			}
801ea4e54b9SDavid Nugent 			if (hrp == NULL) {
802ea4e54b9SDavid Nugent 				if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
803737d08f3SYaroslav Tykhiy 					goto nextline;
804b1d8d5cdSYaroslav Tykhiy 				hrp->hostname = NULL;
80555b54aa7SYaroslav Tykhiy 				insert = 1;
806f2fe752dSYaroslav Tykhiy 			} else {
8071f75c13eSYaroslav Tykhiy 				if (hrp->hostinfo && hrp->hostinfo != res)
808b1d8d5cdSYaroslav Tykhiy 					freeaddrinfo(hrp->hostinfo);
809f2fe752dSYaroslav Tykhiy 				insert = 0; /* host already in the chain */
810f2fe752dSYaroslav Tykhiy 			}
811f38c6cadSYoshinobu Inoue 			hrp->hostinfo = res;
812f38c6cadSYoshinobu Inoue 
813ea4e54b9SDavid Nugent 			/*
814ea4e54b9SDavid Nugent 			 * determine hostname to use.
8154dd8b5abSYoshinobu Inoue 			 * force defined name if there is a valid alias
816ea4e54b9SDavid Nugent 			 * otherwise fallback to primary hostname
817ea4e54b9SDavid Nugent 			 */
8184dd8b5abSYoshinobu Inoue 			/* XXX: getaddrinfo() can't do alias check */
819f38c6cadSYoshinobu Inoue 			switch(hrp->hostinfo->ai_family) {
8204dd8b5abSYoshinobu Inoue 			case AF_INET:
8214b4cc4c6SYaroslav Tykhiy 				addr = &((struct sockaddr_in *)hrp->hostinfo->ai_addr)->sin_addr;
8224b4cc4c6SYaroslav Tykhiy 				addrsize = sizeof(struct in_addr);
8234dd8b5abSYoshinobu Inoue 				break;
8244dd8b5abSYoshinobu Inoue 			case AF_INET6:
8254b4cc4c6SYaroslav Tykhiy 				addr = &((struct sockaddr_in6 *)hrp->hostinfo->ai_addr)->sin6_addr;
8264b4cc4c6SYaroslav Tykhiy 				addrsize = sizeof(struct in6_addr);
8274dd8b5abSYoshinobu Inoue 				break;
8284dd8b5abSYoshinobu Inoue 			default:
8294dd8b5abSYoshinobu Inoue 				/* should not reach here */
830f38c6cadSYoshinobu Inoue 				freeaddrinfo(hrp->hostinfo);
831f2fe752dSYaroslav Tykhiy 				if (insert)
832f2fe752dSYaroslav Tykhiy 					free(hrp); /*not in chain, can free*/
833f2fe752dSYaroslav Tykhiy 				else
834f2fe752dSYaroslav Tykhiy 					hrp->hostinfo = NULL; /*mark as blank*/
835737d08f3SYaroslav Tykhiy 				goto nextline;
8364dd8b5abSYoshinobu Inoue 				/* NOTREACHED */
8374dd8b5abSYoshinobu Inoue 			}
83857d4ef07SYaroslav Tykhiy 			if ((hp = getipnodebyaddr(addr, addrsize,
839f38c6cadSYoshinobu Inoue 						  hrp->hostinfo->ai_family,
8404dd8b5abSYoshinobu Inoue 						  &hp_error)) != NULL) {
84155b54aa7SYaroslav Tykhiy 				if (strcmp(vhost, hp->h_name) != 0) {
842ea4e54b9SDavid Nugent 					if (hp->h_aliases == NULL)
84355b54aa7SYaroslav Tykhiy 						vhost = hp->h_name;
844ea4e54b9SDavid Nugent 					else {
845ea4e54b9SDavid Nugent 						i = 0;
846ea4e54b9SDavid Nugent 						while (hp->h_aliases[i] &&
84755b54aa7SYaroslav Tykhiy 						       strcmp(vhost, hp->h_aliases[i]) != 0)
848ea4e54b9SDavid Nugent 							++i;
849ea4e54b9SDavid Nugent 						if (hp->h_aliases[i] == NULL)
85055b54aa7SYaroslav Tykhiy 							vhost = hp->h_name;
851ea4e54b9SDavid Nugent 					}
852ea4e54b9SDavid Nugent 				}
853ea4e54b9SDavid Nugent 			}
854b1d8d5cdSYaroslav Tykhiy 			if (hrp->hostname &&
855b1d8d5cdSYaroslav Tykhiy 			    strcmp(hrp->hostname, vhost) != 0) {
856b1d8d5cdSYaroslav Tykhiy 				free(hrp->hostname);
857b1d8d5cdSYaroslav Tykhiy 				hrp->hostname = NULL;
858b1d8d5cdSYaroslav Tykhiy 			}
859b1d8d5cdSYaroslav Tykhiy 			if (hrp->hostname == NULL &&
860f2fe752dSYaroslav Tykhiy 			    (hrp->hostname = strdup(vhost)) == NULL) {
861f2fe752dSYaroslav Tykhiy 				freeaddrinfo(hrp->hostinfo);
862f2fe752dSYaroslav Tykhiy 				hrp->hostinfo = NULL; /* mark as blank */
863f2fe752dSYaroslav Tykhiy 				if (hp)
864f2fe752dSYaroslav Tykhiy 					freehostent(hp);
86555b54aa7SYaroslav Tykhiy 				goto nextline;
866f2fe752dSYaroslav Tykhiy 			}
86755b54aa7SYaroslav Tykhiy 			hrp->anonuser = anonuser;
86855b54aa7SYaroslav Tykhiy 			hrp->statfile = statfile;
86955b54aa7SYaroslav Tykhiy 			hrp->welcome  = welcome;
87055b54aa7SYaroslav Tykhiy 			hrp->loginmsg = loginmsg;
87155b54aa7SYaroslav Tykhiy 			if (insert) {
87255b54aa7SYaroslav Tykhiy 				hrp->next  = NULL;
87355b54aa7SYaroslav Tykhiy 				lhrp->next = hrp;
87455b54aa7SYaroslav Tykhiy 				lhrp = hrp;
87555b54aa7SYaroslav Tykhiy 			}
876233c0f66SYaroslav Tykhiy 			if (hp)
8774dd8b5abSYoshinobu Inoue 				freehostent(hp);
8784dd8b5abSYoshinobu Inoue 		      }
879737d08f3SYaroslav Tykhiy nextline:
880737d08f3SYaroslav Tykhiy 			if (mp)
881737d08f3SYaroslav Tykhiy 				free(mp);
882ea4e54b9SDavid Nugent 		}
883ea4e54b9SDavid Nugent 		(void) fclose(fp);
884ea4e54b9SDavid Nugent 	}
885ea4e54b9SDavid Nugent }
886ea4e54b9SDavid Nugent 
887ea4e54b9SDavid Nugent static void
888e4bc453cSWarner Losh selecthost(union sockunion *su)
889ea4e54b9SDavid Nugent {
890ea4e54b9SDavid Nugent 	struct ftphost	*hrp;
8914dd8b5abSYoshinobu Inoue 	u_int16_t port;
8924dd8b5abSYoshinobu Inoue #ifdef INET6
8934dd8b5abSYoshinobu Inoue 	struct in6_addr *mapped_in6 = NULL;
8944dd8b5abSYoshinobu Inoue #endif
895f38c6cadSYoshinobu Inoue 	struct addrinfo *hi;
8964dd8b5abSYoshinobu Inoue 
8974dd8b5abSYoshinobu Inoue #ifdef INET6
8984dd8b5abSYoshinobu Inoue 	/*
8994dd8b5abSYoshinobu Inoue 	 * XXX IPv4 mapped IPv6 addr consideraton,
9004dd8b5abSYoshinobu Inoue 	 * specified in rfc2373.
9014dd8b5abSYoshinobu Inoue 	 */
9024dd8b5abSYoshinobu Inoue 	if (su->su_family == AF_INET6 &&
9034dd8b5abSYoshinobu Inoue 	    IN6_IS_ADDR_V4MAPPED(&su->su_sin6.sin6_addr))
9044dd8b5abSYoshinobu Inoue 		mapped_in6 = &su->su_sin6.sin6_addr;
9054dd8b5abSYoshinobu Inoue #endif
906ea4e54b9SDavid Nugent 
907ea4e54b9SDavid Nugent 	hrp = thishost = firsthost;	/* default */
9084dd8b5abSYoshinobu Inoue 	port = su->su_port;
9094dd8b5abSYoshinobu Inoue 	su->su_port = 0;
910ea4e54b9SDavid Nugent 	while (hrp != NULL) {
911b535a9bfSDavid Nugent 	    for (hi = hrp->hostinfo; hi != NULL; hi = hi->ai_next) {
912f38c6cadSYoshinobu Inoue 		if (memcmp(su, hi->ai_addr, hi->ai_addrlen) == 0) {
913ea4e54b9SDavid Nugent 			thishost = hrp;
914ebd83647SYaroslav Tykhiy 			goto found;
915ea4e54b9SDavid Nugent 		}
9164dd8b5abSYoshinobu Inoue #ifdef INET6
9174dd8b5abSYoshinobu Inoue 		/* XXX IPv4 mapped IPv6 addr consideraton */
918f38c6cadSYoshinobu Inoue 		if (hi->ai_addr->sa_family == AF_INET && mapped_in6 != NULL &&
9194dd8b5abSYoshinobu Inoue 		    (memcmp(&mapped_in6->s6_addr[12],
920f38c6cadSYoshinobu Inoue 			    &((struct sockaddr_in *)hi->ai_addr)->sin_addr,
9214dd8b5abSYoshinobu Inoue 			    sizeof(struct in_addr)) == 0)) {
9224dd8b5abSYoshinobu Inoue 			thishost = hrp;
923ebd83647SYaroslav Tykhiy 			goto found;
9244dd8b5abSYoshinobu Inoue 		}
9254dd8b5abSYoshinobu Inoue #endif
926f38c6cadSYoshinobu Inoue 	    }
927ea4e54b9SDavid Nugent 	    hrp = hrp->next;
928ea4e54b9SDavid Nugent 	}
929ebd83647SYaroslav Tykhiy found:
9304dd8b5abSYoshinobu Inoue 	su->su_port = port;
931ea4e54b9SDavid Nugent 	/* setup static variables as appropriate */
932ea4e54b9SDavid Nugent 	hostname = thishost->hostname;
933ea4e54b9SDavid Nugent 	ftpuser = thishost->anonuser;
934ea4e54b9SDavid Nugent }
935ea4e54b9SDavid Nugent #endif
936ea4e54b9SDavid Nugent 
937ea022d16SRodney W. Grimes /*
938ea022d16SRodney W. Grimes  * Helper function for sgetpwnam().
939ea022d16SRodney W. Grimes  */
940ea022d16SRodney W. Grimes static char *
941e4bc453cSWarner Losh sgetsave(char *s)
942ea022d16SRodney W. Grimes {
943e3765043SYaroslav Tykhiy 	char *new = malloc(strlen(s) + 1);
944ea022d16SRodney W. Grimes 
945ea022d16SRodney W. Grimes 	if (new == NULL) {
94602c97492SYaroslav Tykhiy 		reply(421, "Ran out of memory.");
947ea022d16SRodney W. Grimes 		dologout(1);
948ea022d16SRodney W. Grimes 		/* NOTREACHED */
949ea022d16SRodney W. Grimes 	}
950ea022d16SRodney W. Grimes 	(void) strcpy(new, s);
951ea022d16SRodney W. Grimes 	return (new);
952ea022d16SRodney W. Grimes }
953ea022d16SRodney W. Grimes 
954ea022d16SRodney W. Grimes /*
955ea022d16SRodney W. Grimes  * Save the result of a getpwnam.  Used for USER command, since
956ea022d16SRodney W. Grimes  * the data returned must not be clobbered by any other command
957ea022d16SRodney W. Grimes  * (e.g., globbing).
958c29b9b47SYaroslav Tykhiy  * NB: The data returned by sgetpwnam() will remain valid until
959c29b9b47SYaroslav Tykhiy  * the next call to this function.  Its difference from getpwnam()
960c29b9b47SYaroslav Tykhiy  * is that sgetpwnam() is known to be called from ftpd code only.
961ea022d16SRodney W. Grimes  */
962ea022d16SRodney W. Grimes static struct passwd *
963e4bc453cSWarner Losh sgetpwnam(char *name)
964ea022d16SRodney W. Grimes {
965ea022d16SRodney W. Grimes 	static struct passwd save;
966ea022d16SRodney W. Grimes 	struct passwd *p;
967ea022d16SRodney W. Grimes 
968ea022d16SRodney W. Grimes 	if ((p = getpwnam(name)) == NULL)
969ea022d16SRodney W. Grimes 		return (p);
970ea022d16SRodney W. Grimes 	if (save.pw_name) {
971ea022d16SRodney W. Grimes 		free(save.pw_name);
972ea022d16SRodney W. Grimes 		free(save.pw_passwd);
973ea022d16SRodney W. Grimes 		free(save.pw_gecos);
974ea022d16SRodney W. Grimes 		free(save.pw_dir);
975ea022d16SRodney W. Grimes 		free(save.pw_shell);
976ea022d16SRodney W. Grimes 	}
977ea022d16SRodney W. Grimes 	save = *p;
978ea022d16SRodney W. Grimes 	save.pw_name = sgetsave(p->pw_name);
979ea022d16SRodney W. Grimes 	save.pw_passwd = sgetsave(p->pw_passwd);
980ea022d16SRodney W. Grimes 	save.pw_gecos = sgetsave(p->pw_gecos);
981ea022d16SRodney W. Grimes 	save.pw_dir = sgetsave(p->pw_dir);
982ea022d16SRodney W. Grimes 	save.pw_shell = sgetsave(p->pw_shell);
983ea022d16SRodney W. Grimes 	return (&save);
984ea022d16SRodney W. Grimes }
985ea022d16SRodney W. Grimes 
986ea022d16SRodney W. Grimes static int login_attempts;	/* number of failed login attempts */
987ea022d16SRodney W. Grimes static int askpasswd;		/* had user command, ask for passwd */
98890906a46SSheldon Hearn static char curname[MAXLOGNAME];	/* current USER name */
989ea022d16SRodney W. Grimes 
990ea022d16SRodney W. Grimes /*
991ea022d16SRodney W. Grimes  * USER command.
992ea022d16SRodney W. Grimes  * Sets global passwd pointer pw if named account exists and is acceptable;
993ea022d16SRodney W. Grimes  * sets askpasswd if a PASS command is expected.  If logged in previously,
994ea022d16SRodney W. Grimes  * need to reset state.  If name is "ftp" or "anonymous", the name is not in
995ea022d16SRodney W. Grimes  * _PATH_FTPUSERS, and ftp account exists, set guest and pw, then just return.
996ea022d16SRodney W. Grimes  * If account doesn't exist, ask for passwd anyway.  Otherwise, check user
997ea022d16SRodney W. Grimes  * requesting login privileges.  Disallow anyone who does not have a standard
998ea022d16SRodney W. Grimes  * shell as returned by getusershell().  Disallow anyone mentioned in the file
999ea022d16SRodney W. Grimes  * _PATH_FTPUSERS to allow people such as root and uucp to be avoided.
1000ea022d16SRodney W. Grimes  */
1001ea022d16SRodney W. Grimes void
1002e4bc453cSWarner Losh user(char *name)
1003ea022d16SRodney W. Grimes {
1004ea022d16SRodney W. Grimes 	char *cp, *shell;
1005ea022d16SRodney W. Grimes 
1006ea022d16SRodney W. Grimes 	if (logged_in) {
1007ea022d16SRodney W. Grimes 		if (guest) {
1008ea022d16SRodney W. Grimes 			reply(530, "Can't change user from guest login.");
1009ea022d16SRodney W. Grimes 			return;
1010a5a4544eSPaul Traina 		} else if (dochroot) {
1011a5a4544eSPaul Traina 			reply(530, "Can't change user from chroot user.");
1012a5a4544eSPaul Traina 			return;
1013ea022d16SRodney W. Grimes 		}
1014ea022d16SRodney W. Grimes 		end_login();
1015ea022d16SRodney W. Grimes 	}
1016ea022d16SRodney W. Grimes 
1017ea022d16SRodney W. Grimes 	guest = 0;
101863047c6fSDavid E. O'Brien #ifdef VIRTUAL_HOSTING
101963047c6fSDavid E. O'Brien 	pw = sgetpwnam(thishost->anonuser);
102063047c6fSDavid E. O'Brien #else
102163047c6fSDavid E. O'Brien 	pw = sgetpwnam("ftp");
102263047c6fSDavid E. O'Brien #endif
1023ea022d16SRodney W. Grimes 	if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) {
10248657b576SYaroslav Tykhiy 		if (checkuser(_PATH_FTPUSERS, "ftp", 0, NULL) ||
10258657b576SYaroslav Tykhiy 		    checkuser(_PATH_FTPUSERS, "anonymous", 0, NULL))
1026ea022d16SRodney W. Grimes 			reply(530, "User %s access denied.", name);
102763047c6fSDavid E. O'Brien 		else if (pw != NULL) {
1028ea022d16SRodney W. Grimes 			guest = 1;
1029ea022d16SRodney W. Grimes 			askpasswd = 1;
1030ea022d16SRodney W. Grimes 			reply(331,
10312c60c54cSPaul Traina 			"Guest login ok, send your email address as password.");
1032ea022d16SRodney W. Grimes 		} else
1033ea022d16SRodney W. Grimes 			reply(530, "User %s unknown.", name);
1034ea022d16SRodney W. Grimes 		if (!askpasswd && logging)
1035ea022d16SRodney W. Grimes 			syslog(LOG_NOTICE,
1036ea022d16SRodney W. Grimes 			    "ANONYMOUS FTP LOGIN REFUSED FROM %s", remotehost);
1037ea022d16SRodney W. Grimes 		return;
1038ea022d16SRodney W. Grimes 	}
10395a392aecSTorsten Blum 	if (anon_only != 0) {
10405a392aecSTorsten Blum 		reply(530, "Sorry, only anonymous ftp allowed.");
10415a392aecSTorsten Blum 		return;
10425a392aecSTorsten Blum 	}
10435a392aecSTorsten Blum 
10449aca17cbSMark Murray 	if ((pw = sgetpwnam(name))) {
1045ea022d16SRodney W. Grimes 		if ((shell = pw->pw_shell) == NULL || *shell == 0)
1046ea022d16SRodney W. Grimes 			shell = _PATH_BSHELL;
1047c433c9daSPhilippe Charnier 		setusershell();
1048ea022d16SRodney W. Grimes 		while ((cp = getusershell()) != NULL)
1049ea022d16SRodney W. Grimes 			if (strcmp(cp, shell) == 0)
1050ea022d16SRodney W. Grimes 				break;
1051ea022d16SRodney W. Grimes 		endusershell();
1052ea022d16SRodney W. Grimes 
10538657b576SYaroslav Tykhiy 		if (cp == NULL || checkuser(_PATH_FTPUSERS, name, 1, NULL)) {
1054ea022d16SRodney W. Grimes 			reply(530, "User %s access denied.", name);
1055ea022d16SRodney W. Grimes 			if (logging)
1056ea022d16SRodney W. Grimes 				syslog(LOG_NOTICE,
1057ea022d16SRodney W. Grimes 				    "FTP LOGIN REFUSED FROM %s, %s",
1058ea022d16SRodney W. Grimes 				    remotehost, name);
10597e295315SYaroslav Tykhiy 			pw = NULL;
1060ea022d16SRodney W. Grimes 			return;
1061ea022d16SRodney W. Grimes 		}
1062ea022d16SRodney W. Grimes 	}
1063ea022d16SRodney W. Grimes 	if (logging)
1064ea022d16SRodney W. Grimes 		strncpy(curname, name, sizeof(curname)-1);
106547499ecdSAndrey A. Chernov 
106647499ecdSAndrey A. Chernov 	pwok = 0;
1067fa1746c9SMark Murray #ifdef USE_PAM
1068fa1746c9SMark Murray 	/* XXX Kluge! The conversation mechanism needs to be fixed. */
1069726040deSGuido van Rooij #endif
107047499ecdSAndrey A. Chernov 	if (opiechallenge(&opiedata, name, opieprompt) == 0) {
107147499ecdSAndrey A. Chernov 		pwok = (pw != NULL) &&
107247499ecdSAndrey A. Chernov 		       opieaccessfile(remotehost) &&
107347499ecdSAndrey A. Chernov 		       opiealways(pw->pw_dir);
107447499ecdSAndrey A. Chernov 		reply(331, "Response to %s %s for %s.",
107547499ecdSAndrey A. Chernov 		      opieprompt, pwok ? "requested" : "required", name);
107647499ecdSAndrey A. Chernov 	} else {
107747499ecdSAndrey A. Chernov 		pwok = 1;
107847499ecdSAndrey A. Chernov 		reply(331, "Password required for %s.", name);
107947499ecdSAndrey A. Chernov 	}
1080ea022d16SRodney W. Grimes 	askpasswd = 1;
1081ea022d16SRodney W. Grimes 	/*
1082ea022d16SRodney W. Grimes 	 * Delay before reading passwd after first failed
1083ea022d16SRodney W. Grimes 	 * attempt to slow down passwd-guessing programs.
1084ea022d16SRodney W. Grimes 	 */
1085ea022d16SRodney W. Grimes 	if (login_attempts)
1086e3765043SYaroslav Tykhiy 		sleep(login_attempts);
1087ea022d16SRodney W. Grimes }
1088ea022d16SRodney W. Grimes 
1089ea022d16SRodney W. Grimes /*
10908657b576SYaroslav Tykhiy  * Check if a user is in the file "fname",
10918657b576SYaroslav Tykhiy  * return a pointer to a malloc'd string with the rest
10928657b576SYaroslav Tykhiy  * of the matching line in "residue" if not NULL.
1093ea022d16SRodney W. Grimes  */
1094ea022d16SRodney W. Grimes static int
10958657b576SYaroslav Tykhiy checkuser(char *fname, char *name, int pwset, char **residue)
1096ea022d16SRodney W. Grimes {
1097ea022d16SRodney W. Grimes 	FILE *fd;
1098ea022d16SRodney W. Grimes 	int found = 0;
1099737d08f3SYaroslav Tykhiy 	size_t len;
1100737d08f3SYaroslav Tykhiy 	char *line, *mp, *p;
1101ea022d16SRodney W. Grimes 
1102a5a4544eSPaul Traina 	if ((fd = fopen(fname, "r")) != NULL) {
1103737d08f3SYaroslav Tykhiy 		while (!found && (line = fgetln(fd, &len)) != NULL) {
1104737d08f3SYaroslav Tykhiy 			/* skip comments */
1105ea022d16SRodney W. Grimes 			if (line[0] == '#')
1106ea022d16SRodney W. Grimes 				continue;
1107737d08f3SYaroslav Tykhiy 			if (line[len - 1] == '\n') {
1108737d08f3SYaroslav Tykhiy 				line[len - 1] = '\0';
1109737d08f3SYaroslav Tykhiy 				mp = NULL;
1110737d08f3SYaroslav Tykhiy 			} else {
1111737d08f3SYaroslav Tykhiy 				if ((mp = malloc(len + 1)) == NULL)
1112737d08f3SYaroslav Tykhiy 					fatalerror("Ran out of memory.");
1113737d08f3SYaroslav Tykhiy 				memcpy(mp, line, len);
1114737d08f3SYaroslav Tykhiy 				mp[len] = '\0';
1115737d08f3SYaroslav Tykhiy 				line = mp;
1116737d08f3SYaroslav Tykhiy 			}
1117737d08f3SYaroslav Tykhiy 			/* avoid possible leading and trailing whitespace */
1118737d08f3SYaroslav Tykhiy 			p = strtok(line, " \t");
1119737d08f3SYaroslav Tykhiy 			/* skip empty lines */
1120737d08f3SYaroslav Tykhiy 			if (p == NULL)
1121737d08f3SYaroslav Tykhiy 				goto nextline;
112231fea7b8SDavid Nugent 			/*
112331fea7b8SDavid Nugent 			 * if first chr is '@', check group membership
112431fea7b8SDavid Nugent 			 */
1125737d08f3SYaroslav Tykhiy 			if (p[0] == '@') {
112631fea7b8SDavid Nugent 				int i = 0;
112731fea7b8SDavid Nugent 				struct group *grp;
112831fea7b8SDavid Nugent 
11298657b576SYaroslav Tykhiy 				if (p[1] == '\0') /* single @ matches anyone */
11308657b576SYaroslav Tykhiy 					found = 1;
11318657b576SYaroslav Tykhiy 				else {
1132737d08f3SYaroslav Tykhiy 					if ((grp = getgrnam(p+1)) == NULL)
1133737d08f3SYaroslav Tykhiy 						goto nextline;
11347edcb936SSteve Price 					/*
11357edcb936SSteve Price 					 * Check user's default group
11367edcb936SSteve Price 					 */
11377edcb936SSteve Price 					if (pwset && grp->gr_gid == pw->pw_gid)
11387edcb936SSteve Price 						found = 1;
11397edcb936SSteve Price 					/*
11407edcb936SSteve Price 					 * Check supplementary groups
11417edcb936SSteve Price 					 */
114231fea7b8SDavid Nugent 					while (!found && grp->gr_mem[i])
114331fea7b8SDavid Nugent 						found = strcmp(name,
114431fea7b8SDavid Nugent 							grp->gr_mem[i++])
114531fea7b8SDavid Nugent 							== 0;
1146ea022d16SRodney W. Grimes 				}
11478657b576SYaroslav Tykhiy 			}
114831fea7b8SDavid Nugent 			/*
114931fea7b8SDavid Nugent 			 * Otherwise, just check for username match
115031fea7b8SDavid Nugent 			 */
115131fea7b8SDavid Nugent 			else
1152737d08f3SYaroslav Tykhiy 				found = strcmp(p, name) == 0;
11538657b576SYaroslav Tykhiy 			/*
11548657b576SYaroslav Tykhiy 			 * Save the rest of line to "residue" if matched
11558657b576SYaroslav Tykhiy 			 */
11568657b576SYaroslav Tykhiy 			if (found && residue) {
11570ba71e24SYaroslav Tykhiy 				if ((p = strtok(NULL, "")) != NULL)
11580ba71e24SYaroslav Tykhiy 					p += strspn(p, " \t");
11590ba71e24SYaroslav Tykhiy 				if (p && *p) {
11608657b576SYaroslav Tykhiy 				 	if ((*residue = strdup(p)) == NULL)
11618657b576SYaroslav Tykhiy 						fatalerror("Ran out of memory.");
11628657b576SYaroslav Tykhiy 				} else
11638657b576SYaroslav Tykhiy 					*residue = NULL;
11648657b576SYaroslav Tykhiy 			}
1165737d08f3SYaroslav Tykhiy nextline:
1166737d08f3SYaroslav Tykhiy 			if (mp)
1167737d08f3SYaroslav Tykhiy 				free(mp);
1168ea022d16SRodney W. Grimes 		}
1169ea022d16SRodney W. Grimes 		(void) fclose(fd);
1170ea022d16SRodney W. Grimes 	}
1171ea022d16SRodney W. Grimes 	return (found);
1172ea022d16SRodney W. Grimes }
1173ea022d16SRodney W. Grimes 
1174ea022d16SRodney W. Grimes /*
1175ea022d16SRodney W. Grimes  * Terminate login as previous user, if any, resetting state;
1176ea022d16SRodney W. Grimes  * used when USER command is given or login fails.
1177ea022d16SRodney W. Grimes  */
1178ea022d16SRodney W. Grimes static void
1179e4bc453cSWarner Losh end_login(void)
1180ea022d16SRodney W. Grimes {
11815bc9d93dSMark Murray #ifdef USE_PAM
11825bc9d93dSMark Murray 	int e;
11835bc9d93dSMark Murray #endif
1184ea022d16SRodney W. Grimes 
118552e7ee74SYaroslav Tykhiy 	(void) seteuid(0);
11865d7e0128SYaroslav Tykhiy 	if (logged_in && dowtmp)
118746948173SHajimu UMEMOTO 		ftpd_logwtmp(ttyline, "", NULL);
1188ea022d16SRodney W. Grimes 	pw = NULL;
1189b071c689SDavid Nugent #ifdef	LOGIN_CAP
119052e7ee74SYaroslav Tykhiy 	setusercontext(NULL, getpwuid(0), 0,
1191d9e2c424SRobert Watson 		       LOGIN_SETPRIORITY|LOGIN_SETRESOURCES|LOGIN_SETUMASK|
1192d9e2c424SRobert Watson 		       LOGIN_SETMAC);
1193b071c689SDavid Nugent #endif
11945bc9d93dSMark Murray #ifdef USE_PAM
1195de45162dSYaroslav Tykhiy 	if (pamh) {
11965bc9d93dSMark Murray 		if ((e = pam_setcred(pamh, PAM_DELETE_CRED)) != PAM_SUCCESS)
11975bc9d93dSMark Murray 			syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e));
11985bc9d93dSMark Murray 		if ((e = pam_close_session(pamh,0)) != PAM_SUCCESS)
11995bc9d93dSMark Murray 			syslog(LOG_ERR, "pam_close_session: %s", pam_strerror(pamh, e));
12005bc9d93dSMark Murray 		if ((e = pam_end(pamh, e)) != PAM_SUCCESS)
12015bc9d93dSMark Murray 			syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
12025bc9d93dSMark Murray 		pamh = NULL;
1203de45162dSYaroslav Tykhiy 	}
12045bc9d93dSMark Murray #endif
1205ea022d16SRodney W. Grimes 	logged_in = 0;
1206ea022d16SRodney W. Grimes 	guest = 0;
1207a5a4544eSPaul Traina 	dochroot = 0;
1208ea022d16SRodney W. Grimes }
1209ea022d16SRodney W. Grimes 
12105bc9d93dSMark Murray #ifdef USE_PAM
12116c9134c0SMark Murray 
12126c9134c0SMark Murray /*
12136c9134c0SMark Murray  * the following code is stolen from imap-uw PAM authentication module and
12146c9134c0SMark Murray  * login.c
12156c9134c0SMark Murray  */
12166c9134c0SMark Murray #define COPY_STRING(s) (s ? strdup(s) : NULL)
12176c9134c0SMark Murray 
12186c9134c0SMark Murray struct cred_t {
12196c9134c0SMark Murray 	const char *uname;		/* user name */
12206c9134c0SMark Murray 	const char *pass;		/* password */
12216c9134c0SMark Murray };
12226c9134c0SMark Murray typedef struct cred_t cred_t;
12236c9134c0SMark Murray 
12246c9134c0SMark Murray static int
12256c9134c0SMark Murray auth_conv(int num_msg, const struct pam_message **msg,
12266c9134c0SMark Murray 	  struct pam_response **resp, void *appdata)
12276c9134c0SMark Murray {
12286c9134c0SMark Murray 	int i;
12296c9134c0SMark Murray 	cred_t *cred = (cred_t *) appdata;
123060769b19SDag-Erling Smørgrav 	struct pam_response *reply;
123160769b19SDag-Erling Smørgrav 
123260769b19SDag-Erling Smørgrav 	reply = calloc(num_msg, sizeof *reply);
123360769b19SDag-Erling Smørgrav 	if (reply == NULL)
123460769b19SDag-Erling Smørgrav 		return PAM_BUF_ERR;
12356c9134c0SMark Murray 
12366c9134c0SMark Murray 	for (i = 0; i < num_msg; i++) {
12376c9134c0SMark Murray 		switch (msg[i]->msg_style) {
12386c9134c0SMark Murray 		case PAM_PROMPT_ECHO_ON:	/* assume want user name */
12396c9134c0SMark Murray 			reply[i].resp_retcode = PAM_SUCCESS;
12406c9134c0SMark Murray 			reply[i].resp = COPY_STRING(cred->uname);
12416c9134c0SMark Murray 			/* PAM frees resp. */
12426c9134c0SMark Murray 			break;
12436c9134c0SMark Murray 		case PAM_PROMPT_ECHO_OFF:	/* assume want password */
12446c9134c0SMark Murray 			reply[i].resp_retcode = PAM_SUCCESS;
12456c9134c0SMark Murray 			reply[i].resp = COPY_STRING(cred->pass);
12466c9134c0SMark Murray 			/* PAM frees resp. */
12476c9134c0SMark Murray 			break;
12486c9134c0SMark Murray 		case PAM_TEXT_INFO:
12496c9134c0SMark Murray 		case PAM_ERROR_MSG:
12506c9134c0SMark Murray 			reply[i].resp_retcode = PAM_SUCCESS;
12516c9134c0SMark Murray 			reply[i].resp = NULL;
12526c9134c0SMark Murray 			break;
12536c9134c0SMark Murray 		default:			/* unknown message style */
12546c9134c0SMark Murray 			free(reply);
12556c9134c0SMark Murray 			return PAM_CONV_ERR;
12566c9134c0SMark Murray 		}
12576c9134c0SMark Murray 	}
12586c9134c0SMark Murray 
12596c9134c0SMark Murray 	*resp = reply;
12606c9134c0SMark Murray 	return PAM_SUCCESS;
12616c9134c0SMark Murray }
12626c9134c0SMark Murray 
12636c9134c0SMark Murray /*
12646c9134c0SMark Murray  * Attempt to authenticate the user using PAM.  Returns 0 if the user is
12656c9134c0SMark Murray  * authenticated, or 1 if not authenticated.  If some sort of PAM system
12666c9134c0SMark Murray  * error occurs (e.g., the "/etc/pam.conf" file is missing) then this
12676c9134c0SMark Murray  * function returns -1.  This can be used as an indication that we should
12686c9134c0SMark Murray  * fall back to a different authentication mechanism.
12696c9134c0SMark Murray  */
12706c9134c0SMark Murray static int
12716c9134c0SMark Murray auth_pam(struct passwd **ppw, const char *pass)
12726c9134c0SMark Murray {
12736c9134c0SMark Murray 	const char *tmpl_user;
12746c9134c0SMark Murray 	const void *item;
12756c9134c0SMark Murray 	int rval;
12766c9134c0SMark Murray 	int e;
12776c9134c0SMark Murray 	cred_t auth_cred = { (*ppw)->pw_name, pass };
12786c9134c0SMark Murray 	struct pam_conv conv = { &auth_conv, &auth_cred };
12796c9134c0SMark Murray 
12806c9134c0SMark Murray 	e = pam_start("ftpd", (*ppw)->pw_name, &conv, &pamh);
12816c9134c0SMark Murray 	if (e != PAM_SUCCESS) {
1282545ea864SYaroslav Tykhiy 		/*
1283545ea864SYaroslav Tykhiy 		 * In OpenPAM, it's OK to pass NULL to pam_strerror()
1284545ea864SYaroslav Tykhiy 		 * if context creation has failed in the first place.
1285545ea864SYaroslav Tykhiy 		 */
1286545ea864SYaroslav Tykhiy 		syslog(LOG_ERR, "pam_start: %s", pam_strerror(NULL, e));
12876c9134c0SMark Murray 		return -1;
12886c9134c0SMark Murray 	}
12896c9134c0SMark Murray 
1290ea413ab7SGuido van Rooij 	e = pam_set_item(pamh, PAM_RHOST, remotehost);
1291ea413ab7SGuido van Rooij 	if (e != PAM_SUCCESS) {
1292ea413ab7SGuido van Rooij 		syslog(LOG_ERR, "pam_set_item(PAM_RHOST): %s",
1293ea413ab7SGuido van Rooij 			pam_strerror(pamh, e));
1294de45162dSYaroslav Tykhiy 		if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
1295de45162dSYaroslav Tykhiy 			syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1296de45162dSYaroslav Tykhiy 		}
1297de45162dSYaroslav Tykhiy 		pamh = NULL;
1298ea413ab7SGuido van Rooij 		return -1;
1299ea413ab7SGuido van Rooij 	}
1300ea413ab7SGuido van Rooij 
13016c9134c0SMark Murray 	e = pam_authenticate(pamh, 0);
13026c9134c0SMark Murray 	switch (e) {
13036c9134c0SMark Murray 	case PAM_SUCCESS:
13046c9134c0SMark Murray 		/*
13056c9134c0SMark Murray 		 * With PAM we support the concept of a "template"
13066c9134c0SMark Murray 		 * user.  The user enters a login name which is
13076c9134c0SMark Murray 		 * authenticated by PAM, usually via a remote service
13086c9134c0SMark Murray 		 * such as RADIUS or TACACS+.  If authentication
13096c9134c0SMark Murray 		 * succeeds, a different but related "template" name
13106c9134c0SMark Murray 		 * is used for setting the credentials, shell, and
13116c9134c0SMark Murray 		 * home directory.  The name the user enters need only
13126c9134c0SMark Murray 		 * exist on the remote authentication server, but the
13136c9134c0SMark Murray 		 * template name must be present in the local password
13146c9134c0SMark Murray 		 * database.
13156c9134c0SMark Murray 		 *
13166c9134c0SMark Murray 		 * This is supported by two various mechanisms in the
13176c9134c0SMark Murray 		 * individual modules.  However, from the application's
13186c9134c0SMark Murray 		 * point of view, the template user is always passed
13196c9134c0SMark Murray 		 * back as a changed value of the PAM_USER item.
13206c9134c0SMark Murray 		 */
13216c9134c0SMark Murray 		if ((e = pam_get_item(pamh, PAM_USER, &item)) ==
13226c9134c0SMark Murray 		    PAM_SUCCESS) {
13236c9134c0SMark Murray 			tmpl_user = (const char *) item;
13246c9134c0SMark Murray 			if (strcmp((*ppw)->pw_name, tmpl_user) != 0)
13256c9134c0SMark Murray 				*ppw = getpwnam(tmpl_user);
13266c9134c0SMark Murray 		} else
13276c9134c0SMark Murray 			syslog(LOG_ERR, "Couldn't get PAM_USER: %s",
13286c9134c0SMark Murray 			    pam_strerror(pamh, e));
13296c9134c0SMark Murray 		rval = 0;
13306c9134c0SMark Murray 		break;
13316c9134c0SMark Murray 
13326c9134c0SMark Murray 	case PAM_AUTH_ERR:
13336c9134c0SMark Murray 	case PAM_USER_UNKNOWN:
13346c9134c0SMark Murray 	case PAM_MAXTRIES:
13356c9134c0SMark Murray 		rval = 1;
13366c9134c0SMark Murray 		break;
13376c9134c0SMark Murray 
13386c9134c0SMark Murray 	default:
13395bc9d93dSMark Murray 		syslog(LOG_ERR, "pam_authenticate: %s", pam_strerror(pamh, e));
13406c9134c0SMark Murray 		rval = -1;
13416c9134c0SMark Murray 		break;
13426c9134c0SMark Murray 	}
13436c9134c0SMark Murray 
13445bc9d93dSMark Murray 	if (rval == 0) {
13455bc9d93dSMark Murray 		e = pam_acct_mgmt(pamh, 0);
13465bc9d93dSMark Murray 		if (e != PAM_SUCCESS) {
13474cbc4ad6SYaroslav Tykhiy 			syslog(LOG_ERR, "pam_acct_mgmt: %s",
13484cbc4ad6SYaroslav Tykhiy 						pam_strerror(pamh, e));
13495bc9d93dSMark Murray 			rval = 1;
13505bc9d93dSMark Murray 		}
13515bc9d93dSMark Murray 	}
13525bc9d93dSMark Murray 
13535bc9d93dSMark Murray 	if (rval != 0) {
13546c9134c0SMark Murray 		if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
13556c9134c0SMark Murray 			syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
13565bc9d93dSMark Murray 		}
13575bc9d93dSMark Murray 		pamh = NULL;
13586c9134c0SMark Murray 	}
13596c9134c0SMark Murray 	return rval;
13606c9134c0SMark Murray }
13616c9134c0SMark Murray 
13625bc9d93dSMark Murray #endif /* USE_PAM */
13636c9134c0SMark Murray 
1364ea022d16SRodney W. Grimes void
1365e4bc453cSWarner Losh pass(char *passwd)
1366ea022d16SRodney W. Grimes {
1367a5a4544eSPaul Traina 	int rval;
1368ea022d16SRodney W. Grimes 	FILE *fd;
1369b071c689SDavid Nugent #ifdef	LOGIN_CAP
1370b071c689SDavid Nugent 	login_cap_t *lc = NULL;
1371b071c689SDavid Nugent #endif
13725bc9d93dSMark Murray #ifdef USE_PAM
13735bc9d93dSMark Murray 	int e;
13745bc9d93dSMark Murray #endif
1375341e476eSYaroslav Tykhiy 	char *residue = NULL;
137647499ecdSAndrey A. Chernov 	char *xpasswd;
1377ea022d16SRodney W. Grimes 
1378ea022d16SRodney W. Grimes 	if (logged_in || askpasswd == 0) {
1379ea022d16SRodney W. Grimes 		reply(503, "Login with USER first.");
1380ea022d16SRodney W. Grimes 		return;
1381ea022d16SRodney W. Grimes 	}
1382ea022d16SRodney W. Grimes 	askpasswd = 0;
1383ea022d16SRodney W. Grimes 	if (!guest) {		/* "ftp" is only account allowed no password */
1384a5a4544eSPaul Traina 		if (pw == NULL) {
1385a5a4544eSPaul Traina 			rval = 1;	/* failure below */
1386a5a4544eSPaul Traina 			goto skip;
1387a5a4544eSPaul Traina 		}
13885bc9d93dSMark Murray #ifdef USE_PAM
13896c9134c0SMark Murray 		rval = auth_pam(&pw, passwd);
1390f650a124SAndrey A. Chernov 		if (rval >= 0) {
1391f650a124SAndrey A. Chernov 			opieunlock();
1392a5a4544eSPaul Traina 			goto skip;
1393f650a124SAndrey A. Chernov 		}
1394f650a124SAndrey A. Chernov #endif
139547499ecdSAndrey A. Chernov 		if (opieverify(&opiedata, passwd) == 0)
139647499ecdSAndrey A. Chernov 			xpasswd = pw->pw_passwd;
1397f650a124SAndrey A. Chernov 		else if (pwok) {
139847499ecdSAndrey A. Chernov 			xpasswd = crypt(passwd, pw->pw_passwd);
1399f650a124SAndrey A. Chernov 			if (passwd[0] == '\0' && pw->pw_passwd[0] != '\0')
1400f650a124SAndrey A. Chernov 				xpasswd = ":";
1401f650a124SAndrey A. Chernov 		} else {
140247499ecdSAndrey A. Chernov 			rval = 1;
140347499ecdSAndrey A. Chernov 			goto skip;
140447499ecdSAndrey A. Chernov 		}
140547499ecdSAndrey A. Chernov 		rval = strcmp(pw->pw_passwd, xpasswd);
1406f650a124SAndrey A. Chernov 		if (pw->pw_expire && time(NULL) >= pw->pw_expire)
1407a5a4544eSPaul Traina 			rval = 1;	/* failure */
1408a5a4544eSPaul Traina skip:
1409a5a4544eSPaul Traina 		/*
1410a5a4544eSPaul Traina 		 * If rval == 1, the user failed the authentication check
14116c9134c0SMark Murray 		 * above.  If rval == 0, either PAM or local authentication
1412a5a4544eSPaul Traina 		 * succeeded.
1413a5a4544eSPaul Traina 		 */
1414a5a4544eSPaul Traina 		if (rval) {
1415ea022d16SRodney W. Grimes 			reply(530, "Login incorrect.");
1416b8939f6fSYaroslav Tykhiy 			if (logging) {
1417ea022d16SRodney W. Grimes 				syslog(LOG_NOTICE,
1418b8939f6fSYaroslav Tykhiy 				    "FTP LOGIN FAILED FROM %s",
1419b8939f6fSYaroslav Tykhiy 				    remotehost);
1420b8939f6fSYaroslav Tykhiy 				syslog(LOG_AUTHPRIV | LOG_NOTICE,
1421ea022d16SRodney W. Grimes 				    "FTP LOGIN FAILED FROM %s, %s",
1422ea022d16SRodney W. Grimes 				    remotehost, curname);
1423b8939f6fSYaroslav Tykhiy 			}
1424ea022d16SRodney W. Grimes 			pw = NULL;
1425ea022d16SRodney W. Grimes 			if (login_attempts++ >= 5) {
1426ea022d16SRodney W. Grimes 				syslog(LOG_NOTICE,
1427ea022d16SRodney W. Grimes 				    "repeated login failures from %s",
1428ea022d16SRodney W. Grimes 				    remotehost);
1429ea022d16SRodney W. Grimes 				exit(0);
1430ea022d16SRodney W. Grimes 			}
1431ea022d16SRodney W. Grimes 			return;
1432ea022d16SRodney W. Grimes 		}
1433ea022d16SRodney W. Grimes 	}
1434ea022d16SRodney W. Grimes 	login_attempts = 0;		/* this time successful */
1435c4536e21SYaroslav Tykhiy 	if (setegid(pw->pw_gid) < 0) {
1436ea022d16SRodney W. Grimes 		reply(550, "Can't set gid.");
1437ea022d16SRodney W. Grimes 		return;
1438ea022d16SRodney W. Grimes 	}
1439b071c689SDavid Nugent 	/* May be overridden by login.conf */
1440b071c689SDavid Nugent 	(void) umask(defumask);
1441b071c689SDavid Nugent #ifdef	LOGIN_CAP
14425d0bfe39SDavid Nugent 	if ((lc = login_getpwclass(pw)) != NULL) {
144304683b2cSYaroslav Tykhiy 		char	remote_ip[NI_MAXHOST];
1444b071c689SDavid Nugent 
144504683b2cSYaroslav Tykhiy 		if (getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
14464dd8b5abSYoshinobu Inoue 			remote_ip, sizeof(remote_ip) - 1, NULL, 0,
144704683b2cSYaroslav Tykhiy 			NI_NUMERICHOST))
144804683b2cSYaroslav Tykhiy 				*remote_ip = 0;
1449b071c689SDavid Nugent 		remote_ip[sizeof(remote_ip) - 1] = 0;
1450b071c689SDavid Nugent 		if (!auth_hostok(lc, remotehost, remote_ip)) {
1451b071c689SDavid Nugent 			syslog(LOG_INFO|LOG_AUTH,
1452b071c689SDavid Nugent 			    "FTP LOGIN FAILED (HOST) as %s: permission denied.",
1453b071c689SDavid Nugent 			    pw->pw_name);
14544a3e5acdSYaroslav Tykhiy 			reply(530, "Permission denied.");
1455b071c689SDavid Nugent 			pw = NULL;
1456b071c689SDavid Nugent 			return;
1457b071c689SDavid Nugent 		}
1458b071c689SDavid Nugent 		if (!auth_timeok(lc, time(NULL))) {
14594a3e5acdSYaroslav Tykhiy 			reply(530, "Login not available right now.");
1460b071c689SDavid Nugent 			pw = NULL;
1461b071c689SDavid Nugent 			return;
1462b071c689SDavid Nugent 		}
1463b071c689SDavid Nugent 	}
146452e7ee74SYaroslav Tykhiy 	setusercontext(lc, pw, 0,
1465e6fa0d43SDag-Erling Smørgrav 		LOGIN_SETLOGIN|LOGIN_SETGROUP|LOGIN_SETPRIORITY|
1466d9e2c424SRobert Watson 		LOGIN_SETRESOURCES|LOGIN_SETUMASK|LOGIN_SETMAC);
1467b071c689SDavid Nugent #else
1468e6fa0d43SDag-Erling Smørgrav 	setlogin(pw->pw_name);
1469ea022d16SRodney W. Grimes 	(void) initgroups(pw->pw_name, pw->pw_gid);
1470b071c689SDavid Nugent #endif
1471ea022d16SRodney W. Grimes 
14725bc9d93dSMark Murray #ifdef USE_PAM
14735bc9d93dSMark Murray 	if (pamh) {
14745bc9d93dSMark Murray 		if ((e = pam_open_session(pamh, 0)) != PAM_SUCCESS) {
14755bc9d93dSMark Murray 			syslog(LOG_ERR, "pam_open_session: %s", pam_strerror(pamh, e));
14765bc9d93dSMark Murray 		} else if ((e = pam_setcred(pamh, PAM_ESTABLISH_CRED)) != PAM_SUCCESS) {
14775bc9d93dSMark Murray 			syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e));
14785bc9d93dSMark Murray 		}
14795bc9d93dSMark Murray 	}
14805bc9d93dSMark Murray #endif
14815bc9d93dSMark Murray 
1482ea022d16SRodney W. Grimes 	/* open wtmp before chroot */
14835d7e0128SYaroslav Tykhiy 	if (dowtmp)
14845d7e0128SYaroslav Tykhiy 		ftpd_logwtmp(ttyline, pw->pw_name,
14855d7e0128SYaroslav Tykhiy 		    (struct sockaddr *)&his_addr);
1486ea022d16SRodney W. Grimes 	logged_in = 1;
1487ea022d16SRodney W. Grimes 
1488a5a4544eSPaul Traina 	if (guest && stats && statfd < 0)
1489ea4e54b9SDavid Nugent #ifdef VIRTUAL_HOSTING
149063047c6fSDavid E. O'Brien 		statfd = open(thishost->statfile, O_WRONLY|O_APPEND);
1491ea4e54b9SDavid Nugent #else
149263047c6fSDavid E. O'Brien 		statfd = open(_PATH_FTPDSTATFILE, O_WRONLY|O_APPEND);
1493ea4e54b9SDavid Nugent #endif
149463047c6fSDavid E. O'Brien 		if (statfd < 0)
14953eb568f2SGuido van Rooij 			stats = 0;
14963eb568f2SGuido van Rooij 
1497b071c689SDavid Nugent 	dochroot =
1498341e476eSYaroslav Tykhiy 		checkuser(_PATH_FTPCHROOT, pw->pw_name, 1, &residue)
1499b071c689SDavid Nugent #ifdef	LOGIN_CAP	/* Allow login.conf configuration as well */
15008657b576SYaroslav Tykhiy 		|| login_getcapbool(lc, "ftp-chroot", 0)
1501b071c689SDavid Nugent #endif
15028657b576SYaroslav Tykhiy 	;
1503ce9287fcSYaroslav Tykhiy 	chrootdir = NULL;
1504ea022d16SRodney W. Grimes 	/*
1505ce9287fcSYaroslav Tykhiy 	 * For a chrooted local user,
1506ce9287fcSYaroslav Tykhiy 	 * a) see whether ftpchroot(5) specifies a chroot directory,
1507ce9287fcSYaroslav Tykhiy 	 * b) extract the directory pathname from the line,
1508ce9287fcSYaroslav Tykhiy 	 * c) expand it to the absolute pathname if necessary.
1509ea022d16SRodney W. Grimes 	 */
1510ce9287fcSYaroslav Tykhiy 	if (dochroot && residue &&
151139bce482SYaroslav Tykhiy 	    (chrootdir = strtok(residue, " \t")) != NULL) {
151239bce482SYaroslav Tykhiy 		if (chrootdir[0] != '/')
1513341e476eSYaroslav Tykhiy 			asprintf(&chrootdir, "%s/%s", pw->pw_dir, chrootdir);
151439bce482SYaroslav Tykhiy 		else
1515215a9f9dSYaroslav Tykhiy 			chrootdir = strdup(chrootdir); /* make it permanent */
1516341e476eSYaroslav Tykhiy 		if (chrootdir == NULL)
15178657b576SYaroslav Tykhiy 			fatalerror("Ran out of memory.");
15188657b576SYaroslav Tykhiy 	}
1519ce9287fcSYaroslav Tykhiy 	if (guest || dochroot) {
1520ce9287fcSYaroslav Tykhiy 		/*
1521ce9287fcSYaroslav Tykhiy 		 * If no chroot directory set yet, use the login directory.
1522ce9287fcSYaroslav Tykhiy 		 * Copy it so it can be modified while pw->pw_dir stays intact.
1523ce9287fcSYaroslav Tykhiy 		 */
1524ce9287fcSYaroslav Tykhiy 		if (chrootdir == NULL &&
1525ce9287fcSYaroslav Tykhiy 		    (chrootdir = strdup(pw->pw_dir)) == NULL)
1526ce9287fcSYaroslav Tykhiy 			fatalerror("Ran out of memory.");
1527ce9287fcSYaroslav Tykhiy 		/*
1528ce9287fcSYaroslav Tykhiy 		 * Check for the "/chroot/./home" syntax,
1529ce9287fcSYaroslav Tykhiy 		 * separate the chroot and home directory pathnames.
1530ce9287fcSYaroslav Tykhiy 		 */
1531ce9287fcSYaroslav Tykhiy 		if ((homedir = strstr(chrootdir, "/./")) != NULL) {
1532ce9287fcSYaroslav Tykhiy 			*(homedir++) = '\0';	/* wipe '/' */
1533ce9287fcSYaroslav Tykhiy 			homedir++;		/* skip '.' */
1534ce9287fcSYaroslav Tykhiy 		} else {
1535ce9287fcSYaroslav Tykhiy 			/*
1536ce9287fcSYaroslav Tykhiy 			 * We MUST do a chdir() after the chroot. Otherwise
1537ce9287fcSYaroslav Tykhiy 			 * the old current directory will be accessible as "."
1538ce9287fcSYaroslav Tykhiy 			 * outside the new root!
1539ce9287fcSYaroslav Tykhiy 			 */
1540ce9287fcSYaroslav Tykhiy 			homedir = "/";
1541ce9287fcSYaroslav Tykhiy 		}
1542ce9287fcSYaroslav Tykhiy 		/*
1543ce9287fcSYaroslav Tykhiy 		 * Finally, do chroot()
1544ce9287fcSYaroslav Tykhiy 		 */
1545ce9287fcSYaroslav Tykhiy 		if (chroot(chrootdir) < 0) {
1546a5a4544eSPaul Traina 			reply(550, "Can't change root.");
1547a5a4544eSPaul Traina 			goto bad;
1548a5a4544eSPaul Traina 		}
1549ce9287fcSYaroslav Tykhiy 	} else	/* real user w/o chroot */
1550ce9287fcSYaroslav Tykhiy 		homedir = pw->pw_dir;
1551ce9287fcSYaroslav Tykhiy 	/*
1552ce9287fcSYaroslav Tykhiy 	 * Set euid *before* doing chdir() so
1553ce9287fcSYaroslav Tykhiy 	 * a) the user won't be carried to a directory that he couldn't reach
1554ce9287fcSYaroslav Tykhiy 	 *    on his own due to no permission to upper path components,
1555ce9287fcSYaroslav Tykhiy 	 * b) NFS mounted homedirs w/restrictive permissions will be accessible
1556ce9287fcSYaroslav Tykhiy 	 *    (uid 0 has no root power over NFS if not mapped explicitly.)
1557ce9287fcSYaroslav Tykhiy 	 */
155852e7ee74SYaroslav Tykhiy 	if (seteuid(pw->pw_uid) < 0) {
1559ea022d16SRodney W. Grimes 		reply(550, "Can't set uid.");
1560ea022d16SRodney W. Grimes 		goto bad;
1561ea022d16SRodney W. Grimes 	}
1562ce9287fcSYaroslav Tykhiy 	if (chdir(homedir) < 0) {
1563ce9287fcSYaroslav Tykhiy 		if (guest || dochroot) {
1564ce9287fcSYaroslav Tykhiy 			reply(550, "Can't change to base directory.");
1565ce9287fcSYaroslav Tykhiy 			goto bad;
1566ce9287fcSYaroslav Tykhiy 		} else {
1567ce9287fcSYaroslav Tykhiy 			if (chdir("/") < 0) {
1568ce9287fcSYaroslav Tykhiy 				reply(550, "Root is inaccessible.");
1569ce9287fcSYaroslav Tykhiy 				goto bad;
1570ce9287fcSYaroslav Tykhiy 			}
157102c97492SYaroslav Tykhiy 			lreply(230, "No directory! Logging in with home=/.");
1572ce9287fcSYaroslav Tykhiy 		}
1573ce9287fcSYaroslav Tykhiy 	}
157482c76939SDavid Greenman 
157582c76939SDavid Greenman 	/*
1576ea022d16SRodney W. Grimes 	 * Display a login message, if it exists.
1577ea022d16SRodney W. Grimes 	 * N.B. reply(230,) must follow the message.
1578ea022d16SRodney W. Grimes 	 */
1579ea4e54b9SDavid Nugent #ifdef VIRTUAL_HOSTING
158063047c6fSDavid E. O'Brien 	fd = fopen(thishost->loginmsg, "r");
1581ea4e54b9SDavid Nugent #else
158263047c6fSDavid E. O'Brien 	fd = fopen(_PATH_FTPLOGINMESG, "r");
1583ea4e54b9SDavid Nugent #endif
158463047c6fSDavid E. O'Brien 	if (fd != NULL) {
1585ea022d16SRodney W. Grimes 		char *cp, line[LINE_MAX];
1586ea022d16SRodney W. Grimes 
1587ea022d16SRodney W. Grimes 		while (fgets(line, sizeof(line), fd) != NULL) {
1588ea022d16SRodney W. Grimes 			if ((cp = strchr(line, '\n')) != NULL)
1589ea022d16SRodney W. Grimes 				*cp = '\0';
1590ea022d16SRodney W. Grimes 			lreply(230, "%s", line);
1591ea022d16SRodney W. Grimes 		}
1592ea022d16SRodney W. Grimes 		(void) fflush(stdout);
1593ea022d16SRodney W. Grimes 		(void) fclose(fd);
1594ea022d16SRodney W. Grimes 	}
1595ea022d16SRodney W. Grimes 	if (guest) {
15963eb568f2SGuido van Rooij 		if (ident != NULL)
15973eb568f2SGuido van Rooij 			free(ident);
159861f891a6SPaul Traina 		ident = strdup(passwd);
159961f891a6SPaul Traina 		if (ident == NULL)
1600618b0bbaSMark Murray 			fatalerror("Ran out of memory.");
160161f891a6SPaul Traina 
1602ea022d16SRodney W. Grimes 		reply(230, "Guest login ok, access restrictions apply.");
1603ea022d16SRodney W. Grimes #ifdef SETPROCTITLE
1604ea4e54b9SDavid Nugent #ifdef VIRTUAL_HOSTING
1605ea4e54b9SDavid Nugent 		if (thishost != firsthost)
1606ea4e54b9SDavid Nugent 			snprintf(proctitle, sizeof(proctitle),
1607b3a0a7cdSMike Heffner 				 "%s: anonymous(%s)/%s", remotehost, hostname,
1608b3a0a7cdSMike Heffner 				 passwd);
1609ea4e54b9SDavid Nugent 		else
1610ea4e54b9SDavid Nugent #endif
1611ea022d16SRodney W. Grimes 			snprintf(proctitle, sizeof(proctitle),
1612b3a0a7cdSMike Heffner 				 "%s: anonymous/%s", remotehost, passwd);
1613b63e1fe2SPeter Wemm 		setproctitle("%s", proctitle);
1614ea022d16SRodney W. Grimes #endif /* SETPROCTITLE */
1615ea022d16SRodney W. Grimes 		if (logging)
1616ea022d16SRodney W. Grimes 			syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s, %s",
1617ea022d16SRodney W. Grimes 			    remotehost, passwd);
1618ea022d16SRodney W. Grimes 	} else {
16193401a71fSDaniel O'Callaghan 		if (dochroot)
162011342ab1SYaroslav Tykhiy 			reply(230, "User %s logged in, "
162111342ab1SYaroslav Tykhiy 				   "access restrictions apply.", pw->pw_name);
16223401a71fSDaniel O'Callaghan 		else
1623ea022d16SRodney W. Grimes 			reply(230, "User %s logged in.", pw->pw_name);
16243401a71fSDaniel O'Callaghan 
1625ea022d16SRodney W. Grimes #ifdef SETPROCTITLE
1626ea022d16SRodney W. Grimes 		snprintf(proctitle, sizeof(proctitle),
16277a29d7daSYaroslav Tykhiy 			 "%s: user/%s", remotehost, pw->pw_name);
1628b63e1fe2SPeter Wemm 		setproctitle("%s", proctitle);
1629ea022d16SRodney W. Grimes #endif /* SETPROCTITLE */
1630ea022d16SRodney W. Grimes 		if (logging)
1631ea022d16SRodney W. Grimes 			syslog(LOG_INFO, "FTP LOGIN FROM %s as %s",
1632ea022d16SRodney W. Grimes 			    remotehost, pw->pw_name);
1633ea022d16SRodney W. Grimes 	}
1634220223fdSYaroslav Tykhiy 	if (logging && (guest || dochroot))
1635e897216fSYaroslav Tykhiy 		syslog(LOG_INFO, "session root changed to %s", chrootdir);
1636b071c689SDavid Nugent #ifdef	LOGIN_CAP
1637b071c689SDavid Nugent 	login_close(lc);
1638b071c689SDavid Nugent #endif
1639ce9287fcSYaroslav Tykhiy 	if (residue)
1640ce9287fcSYaroslav Tykhiy 		free(residue);
1641ea022d16SRodney W. Grimes 	return;
1642ea022d16SRodney W. Grimes bad:
1643ea022d16SRodney W. Grimes 	/* Forget all about it... */
1644b071c689SDavid Nugent #ifdef	LOGIN_CAP
1645b071c689SDavid Nugent 	login_close(lc);
1646b071c689SDavid Nugent #endif
1647ce9287fcSYaroslav Tykhiy 	if (residue)
1648ce9287fcSYaroslav Tykhiy 		free(residue);
1649ea022d16SRodney W. Grimes 	end_login();
1650ea022d16SRodney W. Grimes }
1651ea022d16SRodney W. Grimes 
1652ea022d16SRodney W. Grimes void
1653e4bc453cSWarner Losh retrieve(char *cmd, char *name)
1654ea022d16SRodney W. Grimes {
1655ea022d16SRodney W. Grimes 	FILE *fin, *dout;
1656ea022d16SRodney W. Grimes 	struct stat st;
1657e4bc453cSWarner Losh 	int (*closefunc)(FILE *);
1658158a00b2SJohn Birrell 	time_t start;
1659ea022d16SRodney W. Grimes 
1660ea022d16SRodney W. Grimes 	if (cmd == 0) {
1661ea022d16SRodney W. Grimes 		fin = fopen(name, "r"), closefunc = fclose;
1662ea022d16SRodney W. Grimes 		st.st_size = 0;
1663ea022d16SRodney W. Grimes 	} else {
1664ea022d16SRodney W. Grimes 		char line[BUFSIZ];
1665ea022d16SRodney W. Grimes 
1666e760ef2cSWarner Losh 		(void) snprintf(line, sizeof(line), cmd, name), name = line;
1667ea022d16SRodney W. Grimes 		fin = ftpd_popen(line, "r"), closefunc = ftpd_pclose;
1668ea022d16SRodney W. Grimes 		st.st_size = -1;
1669ea022d16SRodney W. Grimes 		st.st_blksize = BUFSIZ;
1670ea022d16SRodney W. Grimes 	}
1671ea022d16SRodney W. Grimes 	if (fin == NULL) {
1672ea022d16SRodney W. Grimes 		if (errno != 0) {
1673ea022d16SRodney W. Grimes 			perror_reply(550, name);
1674ea022d16SRodney W. Grimes 			if (cmd == 0) {
1675ea022d16SRodney W. Grimes 				LOGCMD("get", name);
1676ea022d16SRodney W. Grimes 			}
1677ea022d16SRodney W. Grimes 		}
1678ea022d16SRodney W. Grimes 		return;
1679ea022d16SRodney W. Grimes 	}
1680ea022d16SRodney W. Grimes 	byte_count = -1;
1681ea701226SYaroslav Tykhiy 	if (cmd == 0) {
1682ea701226SYaroslav Tykhiy 		if (fstat(fileno(fin), &st) < 0) {
1683ea701226SYaroslav Tykhiy 			perror_reply(550, name);
1684ea701226SYaroslav Tykhiy 			goto done;
1685ea701226SYaroslav Tykhiy 		}
1686ea701226SYaroslav Tykhiy 		if (!S_ISREG(st.st_mode)) {
168710e89104SYaroslav Tykhiy 			/*
168810e89104SYaroslav Tykhiy 			 * Never sending a raw directory is a workaround
168910e89104SYaroslav Tykhiy 			 * for buggy clients that will attempt to RETR
169010e89104SYaroslav Tykhiy 			 * a directory before listing it, e.g., Mozilla.
169110e89104SYaroslav Tykhiy 			 * Preventing a guest from getting irregular files
169210e89104SYaroslav Tykhiy 			 * is a simple security measure.
169310e89104SYaroslav Tykhiy 			 */
169410e89104SYaroslav Tykhiy 			if (S_ISDIR(st.st_mode) || guest) {
1695ea022d16SRodney W. Grimes 				reply(550, "%s: not a plain file.", name);
1696ea022d16SRodney W. Grimes 				goto done;
1697ea022d16SRodney W. Grimes 			}
1698ea701226SYaroslav Tykhiy 			st.st_size = -1;
1699ea701226SYaroslav Tykhiy 			/* st.st_blksize is set for all descriptor types */
1700ea701226SYaroslav Tykhiy 		}
1701ea701226SYaroslav Tykhiy 	}
1702ea022d16SRodney W. Grimes 	if (restart_point) {
1703ea022d16SRodney W. Grimes 		if (type == TYPE_A) {
1704ea022d16SRodney W. Grimes 			off_t i, n;
1705ea022d16SRodney W. Grimes 			int c;
1706ea022d16SRodney W. Grimes 
1707ea022d16SRodney W. Grimes 			n = restart_point;
1708ea022d16SRodney W. Grimes 			i = 0;
1709ea022d16SRodney W. Grimes 			while (i++ < n) {
1710ea022d16SRodney W. Grimes 				if ((c=getc(fin)) == EOF) {
1711ea022d16SRodney W. Grimes 					perror_reply(550, name);
1712ea022d16SRodney W. Grimes 					goto done;
1713ea022d16SRodney W. Grimes 				}
1714ea022d16SRodney W. Grimes 				if (c == '\n')
1715ea022d16SRodney W. Grimes 					i++;
1716ea022d16SRodney W. Grimes 			}
1717ea022d16SRodney W. Grimes 		} else if (lseek(fileno(fin), restart_point, L_SET) < 0) {
1718ea022d16SRodney W. Grimes 			perror_reply(550, name);
1719ea022d16SRodney W. Grimes 			goto done;
1720ea022d16SRodney W. Grimes 		}
1721ea022d16SRodney W. Grimes 	}
1722ea022d16SRodney W. Grimes 	dout = dataconn(name, st.st_size, "w");
1723ea022d16SRodney W. Grimes 	if (dout == NULL)
1724ea022d16SRodney W. Grimes 		goto done;
17253eb568f2SGuido van Rooij 	time(&start);
17269fc5823aSGarrett Wollman 	send_data(fin, dout, st.st_blksize, st.st_size,
17279fc5823aSGarrett Wollman 		  restart_point == 0 && cmd == 0 && S_ISREG(st.st_mode));
1728c999732bSYaroslav Tykhiy 	if (cmd == 0 && guest && stats && byte_count > 0)
1729c999732bSYaroslav Tykhiy 		logxfer(name, byte_count, start);
1730ea022d16SRodney W. Grimes 	(void) fclose(dout);
1731ea022d16SRodney W. Grimes 	data = -1;
1732ea022d16SRodney W. Grimes 	pdata = -1;
1733ea022d16SRodney W. Grimes done:
1734ea022d16SRodney W. Grimes 	if (cmd == 0)
1735ea022d16SRodney W. Grimes 		LOGBYTES("get", name, byte_count);
1736ea022d16SRodney W. Grimes 	(*closefunc)(fin);
1737ea022d16SRodney W. Grimes }
1738ea022d16SRodney W. Grimes 
1739ea022d16SRodney W. Grimes void
1740e4bc453cSWarner Losh store(char *name, char *mode, int unique)
1741ea022d16SRodney W. Grimes {
1742a117c345SYaroslav Tykhiy 	int fd;
1743ea022d16SRodney W. Grimes 	FILE *fout, *din;
1744e4bc453cSWarner Losh 	int (*closefunc)(FILE *);
1745ea022d16SRodney W. Grimes 
1746a117c345SYaroslav Tykhiy 	if (*mode == 'a') {		/* APPE */
1747a117c345SYaroslav Tykhiy 		if (unique) {
1748a117c345SYaroslav Tykhiy 			/* Programming error */
1749a117c345SYaroslav Tykhiy 			syslog(LOG_ERR, "Internal: unique flag to APPE");
1750a117c345SYaroslav Tykhiy 			unique = 0;
1751a117c345SYaroslav Tykhiy 		}
1752a117c345SYaroslav Tykhiy 		if (guest && noguestmod) {
175302c97492SYaroslav Tykhiy 			reply(550, "Appending to existing file denied.");
1754a117c345SYaroslav Tykhiy 			goto err;
1755a117c345SYaroslav Tykhiy 		}
1756a117c345SYaroslav Tykhiy 		restart_point = 0;	/* not affected by preceding REST */
1757a117c345SYaroslav Tykhiy 	}
1758a117c345SYaroslav Tykhiy 	if (unique)			/* STOU overrides REST */
1759a117c345SYaroslav Tykhiy 		restart_point = 0;
1760a117c345SYaroslav Tykhiy 	if (guest && noguestmod) {
1761a117c345SYaroslav Tykhiy 		if (restart_point) {	/* guest STOR w/REST */
176202c97492SYaroslav Tykhiy 			reply(550, "Modifying existing file denied.");
1763a117c345SYaroslav Tykhiy 			goto err;
1764a117c345SYaroslav Tykhiy 		} else			/* treat guest STOR as STOU */
1765a117c345SYaroslav Tykhiy 			unique = 1;
1766ea022d16SRodney W. Grimes 	}
1767ea022d16SRodney W. Grimes 
1768ea022d16SRodney W. Grimes 	if (restart_point)
1769a117c345SYaroslav Tykhiy 		mode = "r+";	/* so ASCII manual seek can work */
1770a117c345SYaroslav Tykhiy 	if (unique) {
1771a117c345SYaroslav Tykhiy 		if ((fd = guniquefd(name, &name)) < 0)
1772a117c345SYaroslav Tykhiy 			goto err;
1773a117c345SYaroslav Tykhiy 		fout = fdopen(fd, mode);
1774a117c345SYaroslav Tykhiy 	} else
1775ea022d16SRodney W. Grimes 		fout = fopen(name, mode);
1776ea022d16SRodney W. Grimes 	closefunc = fclose;
1777ea022d16SRodney W. Grimes 	if (fout == NULL) {
1778ea022d16SRodney W. Grimes 		perror_reply(553, name);
1779a117c345SYaroslav Tykhiy 		goto err;
1780ea022d16SRodney W. Grimes 	}
1781ea022d16SRodney W. Grimes 	byte_count = -1;
1782ea022d16SRodney W. Grimes 	if (restart_point) {
1783ea022d16SRodney W. Grimes 		if (type == TYPE_A) {
1784ea022d16SRodney W. Grimes 			off_t i, n;
1785ea022d16SRodney W. Grimes 			int c;
1786ea022d16SRodney W. Grimes 
1787ea022d16SRodney W. Grimes 			n = restart_point;
1788ea022d16SRodney W. Grimes 			i = 0;
1789ea022d16SRodney W. Grimes 			while (i++ < n) {
1790ea022d16SRodney W. Grimes 				if ((c=getc(fout)) == EOF) {
1791ea022d16SRodney W. Grimes 					perror_reply(550, name);
1792ea022d16SRodney W. Grimes 					goto done;
1793ea022d16SRodney W. Grimes 				}
1794ea022d16SRodney W. Grimes 				if (c == '\n')
1795ea022d16SRodney W. Grimes 					i++;
1796ea022d16SRodney W. Grimes 			}
1797ea022d16SRodney W. Grimes 			/*
1798ea022d16SRodney W. Grimes 			 * We must do this seek to "current" position
1799ea022d16SRodney W. Grimes 			 * because we are changing from reading to
1800ea022d16SRodney W. Grimes 			 * writing.
1801ea022d16SRodney W. Grimes 			 */
18020e519c96SYaroslav Tykhiy 			if (fseeko(fout, 0, SEEK_CUR) < 0) {
1803ea022d16SRodney W. Grimes 				perror_reply(550, name);
1804ea022d16SRodney W. Grimes 				goto done;
1805ea022d16SRodney W. Grimes 			}
1806ea022d16SRodney W. Grimes 		} else if (lseek(fileno(fout), restart_point, L_SET) < 0) {
1807ea022d16SRodney W. Grimes 			perror_reply(550, name);
1808ea022d16SRodney W. Grimes 			goto done;
1809ea022d16SRodney W. Grimes 		}
1810ea022d16SRodney W. Grimes 	}
18110e519c96SYaroslav Tykhiy 	din = dataconn(name, -1, "r");
1812ea022d16SRodney W. Grimes 	if (din == NULL)
1813ea022d16SRodney W. Grimes 		goto done;
1814ea022d16SRodney W. Grimes 	if (receive_data(din, fout) == 0) {
1815ea022d16SRodney W. Grimes 		if (unique)
1816ea022d16SRodney W. Grimes 			reply(226, "Transfer complete (unique file name:%s).",
1817ea022d16SRodney W. Grimes 			    name);
1818ea022d16SRodney W. Grimes 		else
1819ea022d16SRodney W. Grimes 			reply(226, "Transfer complete.");
1820ea022d16SRodney W. Grimes 	}
1821ea022d16SRodney W. Grimes 	(void) fclose(din);
1822ea022d16SRodney W. Grimes 	data = -1;
1823ea022d16SRodney W. Grimes 	pdata = -1;
1824ea022d16SRodney W. Grimes done:
18257c20f337SYaroslav Tykhiy 	LOGBYTES(*mode == 'a' ? "append" : "put", name, byte_count);
1826ea022d16SRodney W. Grimes 	(*closefunc)(fout);
1827a117c345SYaroslav Tykhiy 	return;
1828a117c345SYaroslav Tykhiy err:
1829a117c345SYaroslav Tykhiy 	LOGCMD(*mode == 'a' ? "append" : "put" , name);
1830a117c345SYaroslav Tykhiy 	return;
1831ea022d16SRodney W. Grimes }
1832ea022d16SRodney W. Grimes 
1833ea022d16SRodney W. Grimes static FILE *
1834e4bc453cSWarner Losh getdatasock(char *mode)
1835ea022d16SRodney W. Grimes {
1836ea022d16SRodney W. Grimes 	int on = 1, s, t, tries;
1837ea022d16SRodney W. Grimes 
1838ea022d16SRodney W. Grimes 	if (data >= 0)
1839ea022d16SRodney W. Grimes 		return (fdopen(data, mode));
18404dd8b5abSYoshinobu Inoue 
18414dd8b5abSYoshinobu Inoue 	s = socket(data_dest.su_family, SOCK_STREAM, 0);
1842ea022d16SRodney W. Grimes 	if (s < 0)
1843ea022d16SRodney W. Grimes 		goto bad;
184457d4ef07SYaroslav Tykhiy 	if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
1845406d1ae9SYaroslav Tykhiy 		syslog(LOG_WARNING, "data setsockopt (SO_REUSEADDR): %m");
1846ea022d16SRodney W. Grimes 	/* anchor socket to avoid multi-homing problems */
18474dd8b5abSYoshinobu Inoue 	data_source = ctrl_addr;
184863591ba5SYaroslav Tykhiy 	data_source.su_port = htons(dataport);
184952e7ee74SYaroslav Tykhiy 	(void) seteuid(0);
1850ea022d16SRodney W. Grimes 	for (tries = 1; ; tries++) {
18519ec7612aSYaroslav Tykhiy 		/*
18529ec7612aSYaroslav Tykhiy 		 * We should loop here since it's possible that
18539ec7612aSYaroslav Tykhiy 		 * another ftpd instance has passed this point and is
18549ec7612aSYaroslav Tykhiy 		 * trying to open a data connection in active mode now.
18559ec7612aSYaroslav Tykhiy 		 * Until the other connection is opened, we'll be getting
18569ec7612aSYaroslav Tykhiy 		 * EADDRINUSE because no SOCK_STREAM sockets in the system
18579ec7612aSYaroslav Tykhiy 		 * can share both local and remote addresses, localIP:20
18589ec7612aSYaroslav Tykhiy 		 * and *:* in this case.
18599ec7612aSYaroslav Tykhiy 		 */
1860ea022d16SRodney W. Grimes 		if (bind(s, (struct sockaddr *)&data_source,
18614dd8b5abSYoshinobu Inoue 		    data_source.su_len) >= 0)
1862ea022d16SRodney W. Grimes 			break;
1863ea022d16SRodney W. Grimes 		if (errno != EADDRINUSE || tries > 10)
1864ea022d16SRodney W. Grimes 			goto bad;
1865ea022d16SRodney W. Grimes 		sleep(tries);
1866ea022d16SRodney W. Grimes 	}
186752e7ee74SYaroslav Tykhiy 	(void) seteuid(pw->pw_uid);
1868ea022d16SRodney W. Grimes #ifdef IP_TOS
18694dd8b5abSYoshinobu Inoue 	if (data_source.su_family == AF_INET)
18704dd8b5abSYoshinobu Inoue       {
1871ea022d16SRodney W. Grimes 	on = IPTOS_THROUGHPUT;
187257d4ef07SYaroslav Tykhiy 	if (setsockopt(s, IPPROTO_IP, IP_TOS, &on, sizeof(int)) < 0)
1873406d1ae9SYaroslav Tykhiy 		syslog(LOG_WARNING, "data setsockopt (IP_TOS): %m");
18744dd8b5abSYoshinobu Inoue       }
1875ea022d16SRodney W. Grimes #endif
18769fc5823aSGarrett Wollman #ifdef TCP_NOPUSH
18779fc5823aSGarrett Wollman 	/*
18789fc5823aSGarrett Wollman 	 * Turn off push flag to keep sender TCP from sending short packets
187932072720SYaroslav Tykhiy 	 * at the boundaries of each write().
18809fc5823aSGarrett Wollman 	 */
18819fc5823aSGarrett Wollman 	on = 1;
188257d4ef07SYaroslav Tykhiy 	if (setsockopt(s, IPPROTO_TCP, TCP_NOPUSH, &on, sizeof on) < 0)
1883406d1ae9SYaroslav Tykhiy 		syslog(LOG_WARNING, "data setsockopt (TCP_NOPUSH): %m");
18849fc5823aSGarrett Wollman #endif
1885ea022d16SRodney W. Grimes 	return (fdopen(s, mode));
1886ea022d16SRodney W. Grimes bad:
1887ea022d16SRodney W. Grimes 	/* Return the real value of errno (close may change it) */
1888ea022d16SRodney W. Grimes 	t = errno;
188952e7ee74SYaroslav Tykhiy 	(void) seteuid(pw->pw_uid);
1890ea022d16SRodney W. Grimes 	(void) close(s);
1891ea022d16SRodney W. Grimes 	errno = t;
1892ea022d16SRodney W. Grimes 	return (NULL);
1893ea022d16SRodney W. Grimes }
1894ea022d16SRodney W. Grimes 
1895ea022d16SRodney W. Grimes static FILE *
1896e4bc453cSWarner Losh dataconn(char *name, off_t size, char *mode)
1897ea022d16SRodney W. Grimes {
1898ea022d16SRodney W. Grimes 	char sizebuf[32];
1899ea022d16SRodney W. Grimes 	FILE *file;
1900e5094456SCrist J. Clark 	int retry = 0, tos, conerrno;
1901ea022d16SRodney W. Grimes 
1902ea022d16SRodney W. Grimes 	file_size = size;
1903ea022d16SRodney W. Grimes 	byte_count = 0;
19040e519c96SYaroslav Tykhiy 	if (size != -1)
1905a57e1ef0SYaroslav Tykhiy 		(void) snprintf(sizebuf, sizeof(sizebuf),
1906a57e1ef0SYaroslav Tykhiy 				" (%jd bytes)", (intmax_t)size);
1907ea022d16SRodney W. Grimes 	else
1908e760ef2cSWarner Losh 		*sizebuf = '\0';
1909ea022d16SRodney W. Grimes 	if (pdata >= 0) {
19104dd8b5abSYoshinobu Inoue 		union sockunion from;
191178e3eed0SStefan Farfeleder 		socklen_t fromlen = ctrl_addr.su_len;
191278e3eed0SStefan Farfeleder 		int flags, s;
1913d6ed3c37SGuido van Rooij 		struct timeval timeout;
1914d6ed3c37SGuido van Rooij 		fd_set set;
1915ea022d16SRodney W. Grimes 
1916d6ed3c37SGuido van Rooij 		FD_ZERO(&set);
1917d6ed3c37SGuido van Rooij 		FD_SET(pdata, &set);
1918d6ed3c37SGuido van Rooij 
1919d6ed3c37SGuido van Rooij 		timeout.tv_usec = 0;
1920d6ed3c37SGuido van Rooij 		timeout.tv_sec = 120;
1921d6ed3c37SGuido van Rooij 
19224cd48bacSYaroslav Tykhiy 		/*
19234cd48bacSYaroslav Tykhiy 		 * Granted a socket is in the blocking I/O mode,
19244cd48bacSYaroslav Tykhiy 		 * accept() will block after a successful select()
19254cd48bacSYaroslav Tykhiy 		 * if the selected connection dies in between.
19264cd48bacSYaroslav Tykhiy 		 * Therefore set the non-blocking I/O flag here.
19274cd48bacSYaroslav Tykhiy 		 */
19284cd48bacSYaroslav Tykhiy 		if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
19294cd48bacSYaroslav Tykhiy 		    fcntl(pdata, F_SETFL, flags | O_NONBLOCK) == -1)
19304cd48bacSYaroslav Tykhiy 			goto pdata_err;
1931aa5a9d3fSYaroslav Tykhiy 		if (select(pdata+1, &set, NULL, NULL, &timeout) <= 0 ||
19324cd48bacSYaroslav Tykhiy 		    (s = accept(pdata, (struct sockaddr *) &from, &fromlen)) < 0)
19334cd48bacSYaroslav Tykhiy 			goto pdata_err;
1934ea022d16SRodney W. Grimes 		(void) close(pdata);
1935ea022d16SRodney W. Grimes 		pdata = s;
19364cd48bacSYaroslav Tykhiy 		/*
1937f6daca0dSYaroslav Tykhiy 		 * Unset the inherited non-blocking I/O flag
1938f6daca0dSYaroslav Tykhiy 		 * on the child socket so stdio can work on it.
19394cd48bacSYaroslav Tykhiy 		 */
19404cd48bacSYaroslav Tykhiy 		if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
19414cd48bacSYaroslav Tykhiy 		    fcntl(pdata, F_SETFL, flags & ~O_NONBLOCK) == -1)
19424cd48bacSYaroslav Tykhiy 			goto pdata_err;
1943ea022d16SRodney W. Grimes #ifdef IP_TOS
19444dd8b5abSYoshinobu Inoue 		if (from.su_family == AF_INET)
19454dd8b5abSYoshinobu Inoue 	      {
1946a5a4544eSPaul Traina 		tos = IPTOS_THROUGHPUT;
194757d4ef07SYaroslav Tykhiy 		if (setsockopt(s, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
1948406d1ae9SYaroslav Tykhiy 			syslog(LOG_WARNING, "pdata setsockopt (IP_TOS): %m");
19494dd8b5abSYoshinobu Inoue 	      }
1950ea022d16SRodney W. Grimes #endif
1951ea022d16SRodney W. Grimes 		reply(150, "Opening %s mode data connection for '%s'%s.",
1952ea022d16SRodney W. Grimes 		     type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1953ea022d16SRodney W. Grimes 		return (fdopen(pdata, mode));
19544cd48bacSYaroslav Tykhiy pdata_err:
19554cd48bacSYaroslav Tykhiy 		reply(425, "Can't open data connection.");
19564cd48bacSYaroslav Tykhiy 		(void) close(pdata);
19574cd48bacSYaroslav Tykhiy 		pdata = -1;
19584cd48bacSYaroslav Tykhiy 		return (NULL);
1959ea022d16SRodney W. Grimes 	}
1960ea022d16SRodney W. Grimes 	if (data >= 0) {
1961ea022d16SRodney W. Grimes 		reply(125, "Using existing data connection for '%s'%s.",
1962ea022d16SRodney W. Grimes 		    name, sizebuf);
1963ea022d16SRodney W. Grimes 		usedefault = 1;
1964ea022d16SRodney W. Grimes 		return (fdopen(data, mode));
1965ea022d16SRodney W. Grimes 	}
1966ea022d16SRodney W. Grimes 	if (usedefault)
1967ea022d16SRodney W. Grimes 		data_dest = his_addr;
1968ea022d16SRodney W. Grimes 	usedefault = 1;
1969e5094456SCrist J. Clark 	do {
1970ea022d16SRodney W. Grimes 		file = getdatasock(mode);
1971ea022d16SRodney W. Grimes 		if (file == NULL) {
197204683b2cSYaroslav Tykhiy 			char hostbuf[NI_MAXHOST], portbuf[NI_MAXSERV];
197304683b2cSYaroslav Tykhiy 
197404683b2cSYaroslav Tykhiy 			if (getnameinfo((struct sockaddr *)&data_source,
197504683b2cSYaroslav Tykhiy 				data_source.su_len,
197604683b2cSYaroslav Tykhiy 				hostbuf, sizeof(hostbuf) - 1,
197704683b2cSYaroslav Tykhiy 				portbuf, sizeof(portbuf) - 1,
197804683b2cSYaroslav Tykhiy 				NI_NUMERICHOST|NI_NUMERICSERV))
197904683b2cSYaroslav Tykhiy 					*hostbuf = *portbuf = 0;
198004683b2cSYaroslav Tykhiy 			hostbuf[sizeof(hostbuf) - 1] = 0;
198104683b2cSYaroslav Tykhiy 			portbuf[sizeof(portbuf) - 1] = 0;
19824dd8b5abSYoshinobu Inoue 			reply(425, "Can't create data socket (%s,%s): %s.",
19834dd8b5abSYoshinobu Inoue 				hostbuf, portbuf, strerror(errno));
1984ea022d16SRodney W. Grimes 			return (NULL);
1985ea022d16SRodney W. Grimes 		}
1986ea022d16SRodney W. Grimes 		data = fileno(file);
1987e5094456SCrist J. Clark 		conerrno = 0;
1988e5094456SCrist J. Clark 		if (connect(data, (struct sockaddr *)&data_dest,
1989e5094456SCrist J. Clark 		    data_dest.su_len) == 0)
1990e5094456SCrist J. Clark 			break;
1991e5094456SCrist J. Clark 		conerrno = errno;
1992ea022d16SRodney W. Grimes 		(void) fclose(file);
1993ea022d16SRodney W. Grimes 		data = -1;
1994e5094456SCrist J. Clark 		if (conerrno == EADDRINUSE) {
1995e3765043SYaroslav Tykhiy 			sleep(swaitint);
1996e5094456SCrist J. Clark 			retry += swaitint;
1997e5094456SCrist J. Clark 		} else {
1998e5094456SCrist J. Clark 			break;
1999e5094456SCrist J. Clark 		}
2000e5094456SCrist J. Clark 	} while (retry <= swaitmax);
2001e5094456SCrist J. Clark 	if (conerrno != 0) {
200282c03024SYaroslav Tykhiy 		reply(425, "Can't build data connection: %s.",
200382c03024SYaroslav Tykhiy 			   strerror(conerrno));
2004ea022d16SRodney W. Grimes 		return (NULL);
2005ea022d16SRodney W. Grimes 	}
2006ea022d16SRodney W. Grimes 	reply(150, "Opening %s mode data connection for '%s'%s.",
2007ea022d16SRodney W. Grimes 	     type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
2008ea022d16SRodney W. Grimes 	return (file);
2009ea022d16SRodney W. Grimes }
2010ea022d16SRodney W. Grimes 
2011ea022d16SRodney W. Grimes /*
20124cd51076SYaroslav Tykhiy  * A helper macro to avoid code duplication
20134cd51076SYaroslav Tykhiy  * in send_data() and receive_data().
20144cd51076SYaroslav Tykhiy  *
20154cd51076SYaroslav Tykhiy  * XXX We have to block SIGURG during putc() because BSD stdio
20164cd51076SYaroslav Tykhiy  * is unable to restart interrupted write operations and hence
20174cd51076SYaroslav Tykhiy  * the entire buffer contents will be lost as soon as a write()
20184cd51076SYaroslav Tykhiy  * call indicates EINTR to stdio.
20194cd51076SYaroslav Tykhiy  */
20204cd51076SYaroslav Tykhiy #define FTPD_PUTC(ch, file, label)					\
20214cd51076SYaroslav Tykhiy 	do {								\
20224cd51076SYaroslav Tykhiy 		int ret;						\
20234cd51076SYaroslav Tykhiy 									\
20244cd51076SYaroslav Tykhiy 		do {							\
20254cd51076SYaroslav Tykhiy 			START_UNSAFE;					\
20264cd51076SYaroslav Tykhiy 			ret = putc((ch), (file));			\
20274cd51076SYaroslav Tykhiy 			END_UNSAFE;					\
20284cd51076SYaroslav Tykhiy 			CHECKOOB(return (-1))				\
20294cd51076SYaroslav Tykhiy 			else if (ferror(file))				\
20304cd51076SYaroslav Tykhiy 				goto label;				\
20314cd51076SYaroslav Tykhiy 			clearerr(file);					\
20324cd51076SYaroslav Tykhiy 		} while (ret == EOF);					\
20334cd51076SYaroslav Tykhiy 	} while (0)
20344cd51076SYaroslav Tykhiy 
20354cd51076SYaroslav Tykhiy /*
2036ea022d16SRodney W. Grimes  * Tranfer the contents of "instr" to "outstr" peer using the appropriate
20379fc5823aSGarrett Wollman  * encapsulation of the data subject to Mode, Structure, and Type.
2038ea022d16SRodney W. Grimes  *
2039ea022d16SRodney W. Grimes  * NB: Form isn't handled.
2040ea022d16SRodney W. Grimes  */
20414b82fc95SYaroslav Tykhiy static int
20426e4b0a55SYaroslav Tykhiy send_data(FILE *instr, FILE *outstr, size_t blksize, off_t filesize, int isreg)
2043ea022d16SRodney W. Grimes {
2044db1c2da3SYaroslav Tykhiy 	int c, cp, filefd, netfd;
2045f6f0c4b9SDan Moschuk 	char *buf;
2046ea022d16SRodney W. Grimes 
20474cd51076SYaroslav Tykhiy 	STARTXFER;
20484cd51076SYaroslav Tykhiy 
2049ea022d16SRodney W. Grimes 	switch (type) {
2050ea022d16SRodney W. Grimes 
2051ea022d16SRodney W. Grimes 	case TYPE_A:
20524cd51076SYaroslav Tykhiy 		cp = EOF;
20534cd51076SYaroslav Tykhiy 		for (;;) {
20544cd51076SYaroslav Tykhiy 			c = getc(instr);
20554cd51076SYaroslav Tykhiy 			CHECKOOB(return (-1))
20564cd51076SYaroslav Tykhiy 			else if (c == EOF && ferror(instr))
20574cd51076SYaroslav Tykhiy 				goto file_err;
20584cd51076SYaroslav Tykhiy 			if (c == EOF) {
20594cd51076SYaroslav Tykhiy 				if (ferror(instr)) {	/* resume after OOB */
20604cd51076SYaroslav Tykhiy 					clearerr(instr);
20614cd51076SYaroslav Tykhiy 					continue;
2062ea022d16SRodney W. Grimes 				}
20634cd51076SYaroslav Tykhiy 				if (feof(instr))	/* EOF */
20644cd51076SYaroslav Tykhiy 					break;
20654cd51076SYaroslav Tykhiy 				syslog(LOG_ERR, "Internal: impossible condition"
20664cd51076SYaroslav Tykhiy 						" on file after getc()");
20674cd51076SYaroslav Tykhiy 				goto file_err;
20684cd51076SYaroslav Tykhiy 			}
20694cd51076SYaroslav Tykhiy 			if (c == '\n' && cp != '\r') {
20704cd51076SYaroslav Tykhiy 				FTPD_PUTC('\r', outstr, data_err);
20714cd51076SYaroslav Tykhiy 				byte_count++;
20724cd51076SYaroslav Tykhiy 			}
20734cd51076SYaroslav Tykhiy 			FTPD_PUTC(c, outstr, data_err);
20744cd51076SYaroslav Tykhiy 			byte_count++;
2075db1c2da3SYaroslav Tykhiy 			cp = c;
2076ea022d16SRodney W. Grimes 		}
20774cd51076SYaroslav Tykhiy #ifdef notyet	/* BSD stdio isn't ready for that */
20784cd51076SYaroslav Tykhiy 		while (fflush(outstr) == EOF) {
20794cd51076SYaroslav Tykhiy 			CHECKOOB(return (-1))
20804cd51076SYaroslav Tykhiy 			else
2081ea022d16SRodney W. Grimes 				goto data_err;
20824cd51076SYaroslav Tykhiy 			clearerr(outstr);
20834cd51076SYaroslav Tykhiy 		}
20844cd51076SYaroslav Tykhiy 		ENDXFER;
20854cd51076SYaroslav Tykhiy #else
20864cd51076SYaroslav Tykhiy 		ENDXFER;
20874cd51076SYaroslav Tykhiy 		if (fflush(outstr) == EOF)
20884cd51076SYaroslav Tykhiy 			goto data_err;
20894cd51076SYaroslav Tykhiy #endif
2090ea022d16SRodney W. Grimes 		reply(226, "Transfer complete.");
20914b82fc95SYaroslav Tykhiy 		return (0);
2092ea022d16SRodney W. Grimes 
2093ea022d16SRodney W. Grimes 	case TYPE_I:
2094ea022d16SRodney W. Grimes 	case TYPE_L:
20959fc5823aSGarrett Wollman 		/*
20969fc5823aSGarrett Wollman 		 * isreg is only set if we are not doing restart and we
20979fc5823aSGarrett Wollman 		 * are sending a regular file
20989fc5823aSGarrett Wollman 		 */
20999fc5823aSGarrett Wollman 		netfd = fileno(outstr);
21009fc5823aSGarrett Wollman 		filefd = fileno(instr);
21019fc5823aSGarrett Wollman 
2102f6f0c4b9SDan Moschuk 		if (isreg) {
21032e22b914SYaroslav Tykhiy 			char *msg = "Transfer complete.";
21044cd51076SYaroslav Tykhiy 			off_t cnt, offset;
2105f6f0c4b9SDan Moschuk 			int err;
2106f6f0c4b9SDan Moschuk 
21072f492fc8SYaroslav Tykhiy 			cnt = offset = 0;
2108f6f0c4b9SDan Moschuk 
21092f492fc8SYaroslav Tykhiy 			while (filesize > 0) {
2110492f1d9cSMaxim Konovalov 				err = sendfile(filefd, netfd, offset, 0,
21117e295315SYaroslav Tykhiy 					       NULL, &cnt, 0);
21123af48c42SMaxim Konovalov 				/*
21133af48c42SMaxim Konovalov 				 * Calculate byte_count before OOB processing.
21143af48c42SMaxim Konovalov 				 * It can be used in myoob() later.
21153af48c42SMaxim Konovalov 				 */
21163af48c42SMaxim Konovalov 				byte_count += cnt;
2117f6f0c4b9SDan Moschuk 				offset += cnt;
2118492f1d9cSMaxim Konovalov 				filesize -= cnt;
21194cd51076SYaroslav Tykhiy 				CHECKOOB(return (-1))
21204cd51076SYaroslav Tykhiy 				else if (err == -1) {
21214cd51076SYaroslav Tykhiy 					if (errno != EINTR &&
21224cd51076SYaroslav Tykhiy 					    cnt == 0 && offset == 0)
2123f6f0c4b9SDan Moschuk 						goto oldway;
21249fc5823aSGarrett Wollman 					goto data_err;
2125f6f0c4b9SDan Moschuk 				}
21264cd51076SYaroslav Tykhiy 				if (err == -1)	/* resume after OOB */
21274cd51076SYaroslav Tykhiy 					continue;
21282e22b914SYaroslav Tykhiy 				/*
21292e22b914SYaroslav Tykhiy 				 * We hit the EOF prematurely.
21302e22b914SYaroslav Tykhiy 				 * Perhaps the file was externally truncated.
21312e22b914SYaroslav Tykhiy 				 */
21322e22b914SYaroslav Tykhiy 				if (cnt == 0) {
21332e22b914SYaroslav Tykhiy 					msg = "Transfer finished due to "
21342e22b914SYaroslav Tykhiy 					      "premature end of file.";
21352e22b914SYaroslav Tykhiy 					break;
21362e22b914SYaroslav Tykhiy 				}
2137f6f0c4b9SDan Moschuk 			}
21384cd51076SYaroslav Tykhiy 			ENDXFER;
21392e22b914SYaroslav Tykhiy 			reply(226, msg);
21404b82fc95SYaroslav Tykhiy 			return (0);
21419fc5823aSGarrett Wollman 		}
21429fc5823aSGarrett Wollman 
21439fc5823aSGarrett Wollman oldway:
2144e3765043SYaroslav Tykhiy 		if ((buf = malloc(blksize)) == NULL) {
21454cd51076SYaroslav Tykhiy 			ENDXFER;
214602c97492SYaroslav Tykhiy 			reply(451, "Ran out of memory.");
21474b82fc95SYaroslav Tykhiy 			return (-1);
2148ea022d16SRodney W. Grimes 		}
21499fc5823aSGarrett Wollman 
21504cd51076SYaroslav Tykhiy 		for (;;) {
21514cd51076SYaroslav Tykhiy 			int cnt, len;
21524cd51076SYaroslav Tykhiy 			char *bp;
21534cd51076SYaroslav Tykhiy 
21544cd51076SYaroslav Tykhiy 			cnt = read(filefd, buf, blksize);
21554cd51076SYaroslav Tykhiy 			CHECKOOB(free(buf); return (-1))
21564cd51076SYaroslav Tykhiy 			else if (cnt < 0) {
21578efc8b18SYaroslav Tykhiy 				free(buf);
2158ea022d16SRodney W. Grimes 				goto file_err;
21594cd51076SYaroslav Tykhiy 			}
21604cd51076SYaroslav Tykhiy 			if (cnt < 0)	/* resume after OOB */
21614cd51076SYaroslav Tykhiy 				continue;
21624cd51076SYaroslav Tykhiy 			if (cnt == 0)	/* EOF */
21634cd51076SYaroslav Tykhiy 				break;
21644cd51076SYaroslav Tykhiy 			for (len = cnt, bp = buf; len > 0;) {
21654cd51076SYaroslav Tykhiy 				cnt = write(netfd, bp, len);
21664cd51076SYaroslav Tykhiy 				CHECKOOB(free(buf); return (-1))
21674cd51076SYaroslav Tykhiy 				else if (cnt < 0) {
21684cd51076SYaroslav Tykhiy 					free(buf);
2169ea022d16SRodney W. Grimes 					goto data_err;
2170ea022d16SRodney W. Grimes 				}
21714cd51076SYaroslav Tykhiy 				if (cnt <= 0)
21724cd51076SYaroslav Tykhiy 					continue;
21734cd51076SYaroslav Tykhiy 				len -= cnt;
21744cd51076SYaroslav Tykhiy 				bp += cnt;
21754cd51076SYaroslav Tykhiy 				byte_count += cnt;
21764cd51076SYaroslav Tykhiy 			}
21774cd51076SYaroslav Tykhiy 		}
21784cd51076SYaroslav Tykhiy 		ENDXFER;
21794cd51076SYaroslav Tykhiy 		free(buf);
2180ea022d16SRodney W. Grimes 		reply(226, "Transfer complete.");
21814b82fc95SYaroslav Tykhiy 		return (0);
2182ea022d16SRodney W. Grimes 	default:
21834cd51076SYaroslav Tykhiy 		ENDXFER;
218402c97492SYaroslav Tykhiy 		reply(550, "Unimplemented TYPE %d in send_data.", type);
21854b82fc95SYaroslav Tykhiy 		return (-1);
2186ea022d16SRodney W. Grimes 	}
2187ea022d16SRodney W. Grimes 
2188ea022d16SRodney W. Grimes data_err:
21894cd51076SYaroslav Tykhiy 	ENDXFER;
2190ea022d16SRodney W. Grimes 	perror_reply(426, "Data connection");
21914b82fc95SYaroslav Tykhiy 	return (-1);
2192ea022d16SRodney W. Grimes 
2193ea022d16SRodney W. Grimes file_err:
21944cd51076SYaroslav Tykhiy 	ENDXFER;
2195ea022d16SRodney W. Grimes 	perror_reply(551, "Error on input file");
21964b82fc95SYaroslav Tykhiy 	return (-1);
2197ea022d16SRodney W. Grimes }
2198ea022d16SRodney W. Grimes 
2199ea022d16SRodney W. Grimes /*
2200ea022d16SRodney W. Grimes  * Transfer data from peer to "outstr" using the appropriate encapulation of
2201ea022d16SRodney W. Grimes  * the data subject to Mode, Structure, and Type.
2202ea022d16SRodney W. Grimes  *
2203ea022d16SRodney W. Grimes  * N.B.: Form isn't handled.
2204ea022d16SRodney W. Grimes  */
2205ea022d16SRodney W. Grimes static int
2206e4bc453cSWarner Losh receive_data(FILE *instr, FILE *outstr)
2207ea022d16SRodney W. Grimes {
22084cd51076SYaroslav Tykhiy 	int c, cp;
22094cd51076SYaroslav Tykhiy 	int bare_lfs = 0;
2210ea022d16SRodney W. Grimes 
22114cd51076SYaroslav Tykhiy 	STARTXFER;
221261f891a6SPaul Traina 
2213ea022d16SRodney W. Grimes 	switch (type) {
2214ea022d16SRodney W. Grimes 
2215ea022d16SRodney W. Grimes 	case TYPE_I:
2216ea022d16SRodney W. Grimes 	case TYPE_L:
22174cd51076SYaroslav Tykhiy 		for (;;) {
22184cd51076SYaroslav Tykhiy 			int cnt, len;
22194cd51076SYaroslav Tykhiy 			char *bp;
22204cd51076SYaroslav Tykhiy 			char buf[BUFSIZ];
22214cd51076SYaroslav Tykhiy 
22224cd51076SYaroslav Tykhiy 			cnt = read(fileno(instr), buf, sizeof(buf));
22234cd51076SYaroslav Tykhiy 			CHECKOOB(return (-1))
22244cd51076SYaroslav Tykhiy 			else if (cnt < 0)
22254cd51076SYaroslav Tykhiy 				goto data_err;
22264cd51076SYaroslav Tykhiy 			if (cnt < 0)	/* resume after OOB */
22274cd51076SYaroslav Tykhiy 				continue;
22284cd51076SYaroslav Tykhiy 			if (cnt == 0)	/* EOF */
22294cd51076SYaroslav Tykhiy 				break;
22304cd51076SYaroslav Tykhiy 			for (len = cnt, bp = buf; len > 0;) {
22314cd51076SYaroslav Tykhiy 				cnt = write(fileno(outstr), bp, len);
22324cd51076SYaroslav Tykhiy 				CHECKOOB(return (-1))
22334cd51076SYaroslav Tykhiy 				else if (cnt < 0)
2234ea022d16SRodney W. Grimes 					goto file_err;
22354cd51076SYaroslav Tykhiy 				if (cnt <= 0)
22364cd51076SYaroslav Tykhiy 					continue;
22374cd51076SYaroslav Tykhiy 				len -= cnt;
22384cd51076SYaroslav Tykhiy 				bp += cnt;
2239ea022d16SRodney W. Grimes 				byte_count += cnt;
2240ea022d16SRodney W. Grimes 			}
22414cd51076SYaroslav Tykhiy 		}
22424cd51076SYaroslav Tykhiy 		ENDXFER;
2243ea022d16SRodney W. Grimes 		return (0);
2244ea022d16SRodney W. Grimes 
2245ea022d16SRodney W. Grimes 	case TYPE_E:
22464cd51076SYaroslav Tykhiy 		ENDXFER;
2247ea022d16SRodney W. Grimes 		reply(553, "TYPE E not implemented.");
2248ea022d16SRodney W. Grimes 		return (-1);
2249ea022d16SRodney W. Grimes 
2250ea022d16SRodney W. Grimes 	case TYPE_A:
22514cd51076SYaroslav Tykhiy 		cp = EOF;
22524cd51076SYaroslav Tykhiy 		for (;;) {
22534cd51076SYaroslav Tykhiy 			c = getc(instr);
22544cd51076SYaroslav Tykhiy 			CHECKOOB(return (-1))
22554cd51076SYaroslav Tykhiy 			else if (c == EOF && ferror(instr))
22564cd51076SYaroslav Tykhiy 				goto data_err;
22574cd51076SYaroslav Tykhiy 			if (c == EOF && ferror(instr)) { /* resume after OOB */
22584cd51076SYaroslav Tykhiy 				clearerr(instr);
22594cd51076SYaroslav Tykhiy 				continue;
22604cd51076SYaroslav Tykhiy 			}
22614cd51076SYaroslav Tykhiy 
22624cd51076SYaroslav Tykhiy 			if (cp == '\r') {
22634cd51076SYaroslav Tykhiy 				if (c != '\n')
22644cd51076SYaroslav Tykhiy 					FTPD_PUTC('\r', outstr, file_err);
22654cd51076SYaroslav Tykhiy 			} else
2266ea022d16SRodney W. Grimes 				if (c == '\n')
2267ea022d16SRodney W. Grimes 					bare_lfs++;
22684cd51076SYaroslav Tykhiy 			if (c == '\r') {
22694cd51076SYaroslav Tykhiy 				byte_count++;
22704cd51076SYaroslav Tykhiy 				cp = c;
22714cd51076SYaroslav Tykhiy 				continue;
22724cd51076SYaroslav Tykhiy 			}
22734cd51076SYaroslav Tykhiy 
22744cd51076SYaroslav Tykhiy 			/* Check for EOF here in order not to lose last \r. */
22754cd51076SYaroslav Tykhiy 			if (c == EOF) {
22764cd51076SYaroslav Tykhiy 				if (feof(instr))	/* EOF */
22774cd51076SYaroslav Tykhiy 					break;
22784cd51076SYaroslav Tykhiy 				syslog(LOG_ERR, "Internal: impossible condition"
22794cd51076SYaroslav Tykhiy 						" on data stream after getc()");
2280ea022d16SRodney W. Grimes 				goto data_err;
2281ea022d16SRodney W. Grimes 			}
22824cd51076SYaroslav Tykhiy 
22834cd51076SYaroslav Tykhiy 			byte_count++;
22844cd51076SYaroslav Tykhiy 			FTPD_PUTC(c, outstr, file_err);
22854cd51076SYaroslav Tykhiy 			cp = c;
2286ea022d16SRodney W. Grimes 		}
22874cd51076SYaroslav Tykhiy #ifdef notyet	/* BSD stdio isn't ready for that */
22884cd51076SYaroslav Tykhiy 		while (fflush(outstr) == EOF) {
22894cd51076SYaroslav Tykhiy 			CHECKOOB(return (-1))
22904cd51076SYaroslav Tykhiy 			else
2291ea022d16SRodney W. Grimes 				goto file_err;
22924cd51076SYaroslav Tykhiy 			clearerr(outstr);
22934cd51076SYaroslav Tykhiy 		}
22944cd51076SYaroslav Tykhiy 		ENDXFER;
22954cd51076SYaroslav Tykhiy #else
22964cd51076SYaroslav Tykhiy 		ENDXFER;
22974cd51076SYaroslav Tykhiy 		if (fflush(outstr) == EOF)
22984cd51076SYaroslav Tykhiy 			goto file_err;
22994cd51076SYaroslav Tykhiy #endif
2300ea022d16SRodney W. Grimes 		if (bare_lfs) {
2301ea022d16SRodney W. Grimes 			lreply(226,
230202c97492SYaroslav Tykhiy 		"WARNING! %d bare linefeeds received in ASCII mode.",
2303ea022d16SRodney W. Grimes 			    bare_lfs);
2304ea022d16SRodney W. Grimes 		(void)printf("   File may not have transferred correctly.\r\n");
2305ea022d16SRodney W. Grimes 		}
2306ea022d16SRodney W. Grimes 		return (0);
2307ea022d16SRodney W. Grimes 	default:
23084cd51076SYaroslav Tykhiy 		ENDXFER;
230902c97492SYaroslav Tykhiy 		reply(550, "Unimplemented TYPE %d in receive_data.", type);
2310ea022d16SRodney W. Grimes 		return (-1);
2311ea022d16SRodney W. Grimes 	}
2312ea022d16SRodney W. Grimes 
2313ea022d16SRodney W. Grimes data_err:
23144cd51076SYaroslav Tykhiy 	ENDXFER;
231502c97492SYaroslav Tykhiy 	perror_reply(426, "Data connection");
2316ea022d16SRodney W. Grimes 	return (-1);
2317ea022d16SRodney W. Grimes 
2318ea022d16SRodney W. Grimes file_err:
23194cd51076SYaroslav Tykhiy 	ENDXFER;
232002c97492SYaroslav Tykhiy 	perror_reply(452, "Error writing to file");
2321ea022d16SRodney W. Grimes 	return (-1);
2322ea022d16SRodney W. Grimes }
2323ea022d16SRodney W. Grimes 
2324ea022d16SRodney W. Grimes void
2325e4bc453cSWarner Losh statfilecmd(char *filename)
2326ea022d16SRodney W. Grimes {
2327ea022d16SRodney W. Grimes 	FILE *fin;
2328f8a581a0SYaroslav Tykhiy 	int atstart;
232941c57b48SYaroslav Tykhiy 	int c, code;
2330ea022d16SRodney W. Grimes 	char line[LINE_MAX];
233141c57b48SYaroslav Tykhiy 	struct stat st;
2332ea022d16SRodney W. Grimes 
233341c57b48SYaroslav Tykhiy 	code = lstat(filename, &st) == 0 && S_ISDIR(st.st_mode) ? 212 : 213;
2334af85d782SDavid Nugent 	(void)snprintf(line, sizeof(line), _PATH_LS " -lgA %s", filename);
2335ea022d16SRodney W. Grimes 	fin = ftpd_popen(line, "r");
23363b48b877SYaroslav Tykhiy 	lreply(code, "Status of %s:", filename);
2337f8a581a0SYaroslav Tykhiy 	atstart = 1;
2338ea022d16SRodney W. Grimes 	while ((c = getc(fin)) != EOF) {
2339ea022d16SRodney W. Grimes 		if (c == '\n') {
2340ea022d16SRodney W. Grimes 			if (ferror(stdout)){
234102c97492SYaroslav Tykhiy 				perror_reply(421, "Control connection");
2342ea022d16SRodney W. Grimes 				(void) ftpd_pclose(fin);
2343ea022d16SRodney W. Grimes 				dologout(1);
2344ea022d16SRodney W. Grimes 				/* NOTREACHED */
2345ea022d16SRodney W. Grimes 			}
2346ea022d16SRodney W. Grimes 			if (ferror(fin)) {
2347ea022d16SRodney W. Grimes 				perror_reply(551, filename);
2348ea022d16SRodney W. Grimes 				(void) ftpd_pclose(fin);
2349ea022d16SRodney W. Grimes 				return;
2350ea022d16SRodney W. Grimes 			}
2351ea022d16SRodney W. Grimes 			(void) putc('\r', stdout);
2352ea022d16SRodney W. Grimes 		}
2353f8a581a0SYaroslav Tykhiy 		/*
2354f8a581a0SYaroslav Tykhiy 		 * RFC 959 says neutral text should be prepended before
2355f8a581a0SYaroslav Tykhiy 		 * a leading 3-digit number followed by whitespace, but
2356f8a581a0SYaroslav Tykhiy 		 * many ftp clients can be confused by any leading digits,
2357f8a581a0SYaroslav Tykhiy 		 * as a matter of fact.
2358f8a581a0SYaroslav Tykhiy 		 */
2359f8a581a0SYaroslav Tykhiy 		if (atstart && isdigit(c))
2360f8a581a0SYaroslav Tykhiy 			(void) putc(' ', stdout);
2361ea022d16SRodney W. Grimes 		(void) putc(c, stdout);
2362f8a581a0SYaroslav Tykhiy 		atstart = (c == '\n');
2363ea022d16SRodney W. Grimes 	}
2364ea022d16SRodney W. Grimes 	(void) ftpd_pclose(fin);
236502c97492SYaroslav Tykhiy 	reply(code, "End of status.");
2366ea022d16SRodney W. Grimes }
2367ea022d16SRodney W. Grimes 
2368ea022d16SRodney W. Grimes void
2369e4bc453cSWarner Losh statcmd(void)
2370ea022d16SRodney W. Grimes {
23714dd8b5abSYoshinobu Inoue 	union sockunion *su;
2372ea022d16SRodney W. Grimes 	u_char *a, *p;
2373b0f06defSHajimu UMEMOTO 	char hname[NI_MAXHOST];
23744dd8b5abSYoshinobu Inoue 	int ispassive;
2375ea022d16SRodney W. Grimes 
2376c152df28SYaroslav Tykhiy 	if (hostinfo) {
2377a23f61bcSYaroslav Tykhiy 		lreply(211, "%s FTP server status:", hostname);
2378ea022d16SRodney W. Grimes 		printf("     %s\r\n", version);
2379c152df28SYaroslav Tykhiy 	} else
2380c152df28SYaroslav Tykhiy 		lreply(211, "FTP server status:");
2381ea022d16SRodney W. Grimes 	printf("     Connected to %s", remotehost);
23824dd8b5abSYoshinobu Inoue 	if (!getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
2383b0f06defSHajimu UMEMOTO 			 hname, sizeof(hname) - 1, NULL, 0, NI_NUMERICHOST)) {
238404683b2cSYaroslav Tykhiy 		hname[sizeof(hname) - 1] = 0;
23854dd8b5abSYoshinobu Inoue 		if (strcmp(hname, remotehost) != 0)
23864dd8b5abSYoshinobu Inoue 			printf(" (%s)", hname);
23874dd8b5abSYoshinobu Inoue 	}
2388ea022d16SRodney W. Grimes 	printf("\r\n");
2389ea022d16SRodney W. Grimes 	if (logged_in) {
2390ea022d16SRodney W. Grimes 		if (guest)
2391ea022d16SRodney W. Grimes 			printf("     Logged in anonymously\r\n");
2392ea022d16SRodney W. Grimes 		else
2393ea022d16SRodney W. Grimes 			printf("     Logged in as %s\r\n", pw->pw_name);
2394ea022d16SRodney W. Grimes 	} else if (askpasswd)
2395ea022d16SRodney W. Grimes 		printf("     Waiting for password\r\n");
2396ea022d16SRodney W. Grimes 	else
2397ea022d16SRodney W. Grimes 		printf("     Waiting for user name\r\n");
2398ea022d16SRodney W. Grimes 	printf("     TYPE: %s", typenames[type]);
2399ea022d16SRodney W. Grimes 	if (type == TYPE_A || type == TYPE_E)
2400ea022d16SRodney W. Grimes 		printf(", FORM: %s", formnames[form]);
2401ea022d16SRodney W. Grimes 	if (type == TYPE_L)
240289fdc4e1SMike Barcroft #if CHAR_BIT == 8
240389fdc4e1SMike Barcroft 		printf(" %d", CHAR_BIT);
2404ea022d16SRodney W. Grimes #else
2405ea022d16SRodney W. Grimes 		printf(" %d", bytesize);	/* need definition! */
2406ea022d16SRodney W. Grimes #endif
2407ea022d16SRodney W. Grimes 	printf("; STRUcture: %s; transfer MODE: %s\r\n",
2408ea022d16SRodney W. Grimes 	    strunames[stru], modenames[mode]);
2409ea022d16SRodney W. Grimes 	if (data != -1)
2410ea022d16SRodney W. Grimes 		printf("     Data connection open\r\n");
2411ea022d16SRodney W. Grimes 	else if (pdata != -1) {
24124dd8b5abSYoshinobu Inoue 		ispassive = 1;
24134dd8b5abSYoshinobu Inoue 		su = &pasv_addr;
2414ea022d16SRodney W. Grimes 		goto printaddr;
2415ea022d16SRodney W. Grimes 	} else if (usedefault == 0) {
24164dd8b5abSYoshinobu Inoue 		ispassive = 0;
24174dd8b5abSYoshinobu Inoue 		su = &data_dest;
2418ea022d16SRodney W. Grimes printaddr:
2419ea022d16SRodney W. Grimes #define UC(b) (((int) b) & 0xff)
24204dd8b5abSYoshinobu Inoue 		if (epsvall) {
24214dd8b5abSYoshinobu Inoue 			printf("     EPSV only mode (EPSV ALL)\r\n");
24224dd8b5abSYoshinobu Inoue 			goto epsvonly;
24234dd8b5abSYoshinobu Inoue 		}
24244dd8b5abSYoshinobu Inoue 
24254dd8b5abSYoshinobu Inoue 		/* PORT/PASV */
24264dd8b5abSYoshinobu Inoue 		if (su->su_family == AF_INET) {
24274dd8b5abSYoshinobu Inoue 			a = (u_char *) &su->su_sin.sin_addr;
24284dd8b5abSYoshinobu Inoue 			p = (u_char *) &su->su_sin.sin_port;
24294dd8b5abSYoshinobu Inoue 			printf("     %s (%d,%d,%d,%d,%d,%d)\r\n",
24304dd8b5abSYoshinobu Inoue 				ispassive ? "PASV" : "PORT",
24314dd8b5abSYoshinobu Inoue 				UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
24324dd8b5abSYoshinobu Inoue 				UC(p[0]), UC(p[1]));
24334dd8b5abSYoshinobu Inoue 		}
24344dd8b5abSYoshinobu Inoue 
24354dd8b5abSYoshinobu Inoue 		/* LPRT/LPSV */
24364dd8b5abSYoshinobu Inoue 	    {
24374dd8b5abSYoshinobu Inoue 		int alen, af, i;
24384dd8b5abSYoshinobu Inoue 
24394dd8b5abSYoshinobu Inoue 		switch (su->su_family) {
24404dd8b5abSYoshinobu Inoue 		case AF_INET:
24414dd8b5abSYoshinobu Inoue 			a = (u_char *) &su->su_sin.sin_addr;
24424dd8b5abSYoshinobu Inoue 			p = (u_char *) &su->su_sin.sin_port;
24434dd8b5abSYoshinobu Inoue 			alen = sizeof(su->su_sin.sin_addr);
24444dd8b5abSYoshinobu Inoue 			af = 4;
24454dd8b5abSYoshinobu Inoue 			break;
24464dd8b5abSYoshinobu Inoue 		case AF_INET6:
24474dd8b5abSYoshinobu Inoue 			a = (u_char *) &su->su_sin6.sin6_addr;
24484dd8b5abSYoshinobu Inoue 			p = (u_char *) &su->su_sin6.sin6_port;
24494dd8b5abSYoshinobu Inoue 			alen = sizeof(su->su_sin6.sin6_addr);
24504dd8b5abSYoshinobu Inoue 			af = 6;
24514dd8b5abSYoshinobu Inoue 			break;
24524dd8b5abSYoshinobu Inoue 		default:
24534dd8b5abSYoshinobu Inoue 			af = 0;
24544dd8b5abSYoshinobu Inoue 			break;
24554dd8b5abSYoshinobu Inoue 		}
24564dd8b5abSYoshinobu Inoue 		if (af) {
24574dd8b5abSYoshinobu Inoue 			printf("     %s (%d,%d,", ispassive ? "LPSV" : "LPRT",
24584dd8b5abSYoshinobu Inoue 				af, alen);
24594dd8b5abSYoshinobu Inoue 			for (i = 0; i < alen; i++)
24604dd8b5abSYoshinobu Inoue 				printf("%d,", UC(a[i]));
24614dd8b5abSYoshinobu Inoue 			printf("%d,%d,%d)\r\n", 2, UC(p[0]), UC(p[1]));
24624dd8b5abSYoshinobu Inoue 		}
24634dd8b5abSYoshinobu Inoue 	    }
24644dd8b5abSYoshinobu Inoue 
24654dd8b5abSYoshinobu Inoue epsvonly:;
24664dd8b5abSYoshinobu Inoue 		/* EPRT/EPSV */
24674dd8b5abSYoshinobu Inoue 	    {
24684dd8b5abSYoshinobu Inoue 		int af;
24694dd8b5abSYoshinobu Inoue 
24704dd8b5abSYoshinobu Inoue 		switch (su->su_family) {
24714dd8b5abSYoshinobu Inoue 		case AF_INET:
24724dd8b5abSYoshinobu Inoue 			af = 1;
24734dd8b5abSYoshinobu Inoue 			break;
24744dd8b5abSYoshinobu Inoue 		case AF_INET6:
24754dd8b5abSYoshinobu Inoue 			af = 2;
24764dd8b5abSYoshinobu Inoue 			break;
24774dd8b5abSYoshinobu Inoue 		default:
24784dd8b5abSYoshinobu Inoue 			af = 0;
24794dd8b5abSYoshinobu Inoue 			break;
24804dd8b5abSYoshinobu Inoue 		}
24814dd8b5abSYoshinobu Inoue 		if (af) {
2482b0f06defSHajimu UMEMOTO 			union sockunion tmp;
2483b0f06defSHajimu UMEMOTO 
2484b0f06defSHajimu UMEMOTO 			tmp = *su;
2485b0f06defSHajimu UMEMOTO 			if (tmp.su_family == AF_INET6)
2486b0f06defSHajimu UMEMOTO 				tmp.su_sin6.sin6_scope_id = 0;
2487b0f06defSHajimu UMEMOTO 			if (!getnameinfo((struct sockaddr *)&tmp, tmp.su_len,
24884dd8b5abSYoshinobu Inoue 					hname, sizeof(hname) - 1, NULL, 0,
24894dd8b5abSYoshinobu Inoue 					NI_NUMERICHOST)) {
249004683b2cSYaroslav Tykhiy 				hname[sizeof(hname) - 1] = 0;
24914dd8b5abSYoshinobu Inoue 				printf("     %s |%d|%s|%d|\r\n",
24924dd8b5abSYoshinobu Inoue 					ispassive ? "EPSV" : "EPRT",
2493b0f06defSHajimu UMEMOTO 					af, hname, htons(tmp.su_port));
24944dd8b5abSYoshinobu Inoue 			}
24954dd8b5abSYoshinobu Inoue 		}
24964dd8b5abSYoshinobu Inoue 	    }
2497ea022d16SRodney W. Grimes #undef UC
2498ea022d16SRodney W. Grimes 	} else
2499ea022d16SRodney W. Grimes 		printf("     No data connection\r\n");
250002c97492SYaroslav Tykhiy 	reply(211, "End of status.");
2501ea022d16SRodney W. Grimes }
2502ea022d16SRodney W. Grimes 
2503ea022d16SRodney W. Grimes void
2504e4bc453cSWarner Losh fatalerror(char *s)
2505ea022d16SRodney W. Grimes {
2506ea022d16SRodney W. Grimes 
25074a3e5acdSYaroslav Tykhiy 	reply(451, "Error in server: %s", s);
2508ea022d16SRodney W. Grimes 	reply(221, "Closing connection due to server error.");
2509ea022d16SRodney W. Grimes 	dologout(0);
2510ea022d16SRodney W. Grimes 	/* NOTREACHED */
2511ea022d16SRodney W. Grimes }
2512ea022d16SRodney W. Grimes 
2513ea022d16SRodney W. Grimes void
2514ea022d16SRodney W. Grimes reply(int n, const char *fmt, ...)
2515ea022d16SRodney W. Grimes {
2516ea022d16SRodney W. Grimes 	va_list ap;
2517e4bc453cSWarner Losh 
2518ea022d16SRodney W. Grimes 	(void)printf("%d ", n);
25199cbb335cSTim J. Robbins 	va_start(ap, fmt);
2520ea022d16SRodney W. Grimes 	(void)vprintf(fmt, ap);
25219cbb335cSTim J. Robbins 	va_end(ap);
2522ea022d16SRodney W. Grimes 	(void)printf("\r\n");
2523ea022d16SRodney W. Grimes 	(void)fflush(stdout);
2524618b0bbaSMark Murray 	if (ftpdebug) {
2525ea022d16SRodney W. Grimes 		syslog(LOG_DEBUG, "<--- %d ", n);
25269cbb335cSTim J. Robbins 		va_start(ap, fmt);
2527ea022d16SRodney W. Grimes 		vsyslog(LOG_DEBUG, fmt, ap);
25289cbb335cSTim J. Robbins 		va_end(ap);
2529ea022d16SRodney W. Grimes 	}
2530ea022d16SRodney W. Grimes }
2531ea022d16SRodney W. Grimes 
2532ea022d16SRodney W. Grimes void
2533ea022d16SRodney W. Grimes lreply(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 static void
2552e4bc453cSWarner Losh ack(char *s)
2553ea022d16SRodney W. Grimes {
2554ea022d16SRodney W. Grimes 
2555ea022d16SRodney W. Grimes 	reply(250, "%s command successful.", s);
2556ea022d16SRodney W. Grimes }
2557ea022d16SRodney W. Grimes 
2558ea022d16SRodney W. Grimes void
2559e4bc453cSWarner Losh nack(char *s)
2560ea022d16SRodney W. Grimes {
2561ea022d16SRodney W. Grimes 
2562ea022d16SRodney W. Grimes 	reply(502, "%s command not implemented.", s);
2563ea022d16SRodney W. Grimes }
2564ea022d16SRodney W. Grimes 
2565ea022d16SRodney W. Grimes /* ARGSUSED */
2566ea022d16SRodney W. Grimes void
2567e4bc453cSWarner Losh yyerror(char *s)
2568ea022d16SRodney W. Grimes {
2569ea022d16SRodney W. Grimes 	char *cp;
2570ea022d16SRodney W. Grimes 
25719aca17cbSMark Murray 	if ((cp = strchr(cbuf,'\n')))
2572ea022d16SRodney W. Grimes 		*cp = '\0';
257302c97492SYaroslav Tykhiy 	reply(500, "%s: command not understood.", cbuf);
2574ea022d16SRodney W. Grimes }
2575ea022d16SRodney W. Grimes 
2576ea022d16SRodney W. Grimes void
2577e4bc453cSWarner Losh delete(char *name)
2578ea022d16SRodney W. Grimes {
2579ea022d16SRodney W. Grimes 	struct stat st;
2580ea022d16SRodney W. Grimes 
2581ea022d16SRodney W. Grimes 	LOGCMD("delete", name);
25821b0e12d7SYaroslav Tykhiy 	if (lstat(name, &st) < 0) {
2583ea022d16SRodney W. Grimes 		perror_reply(550, name);
2584ea022d16SRodney W. Grimes 		return;
2585ea022d16SRodney W. Grimes 	}
2586ac4f2391SYaroslav Tykhiy 	if (S_ISDIR(st.st_mode)) {
2587ea022d16SRodney W. Grimes 		if (rmdir(name) < 0) {
2588ea022d16SRodney W. Grimes 			perror_reply(550, name);
2589ea022d16SRodney W. Grimes 			return;
2590ea022d16SRodney W. Grimes 		}
2591ea022d16SRodney W. Grimes 		goto done;
2592ea022d16SRodney W. Grimes 	}
25933f8b9cfeSYaroslav Tykhiy 	if (guest && noguestmod) {
259402c97492SYaroslav Tykhiy 		reply(550, "Operation not permitted.");
25953f8b9cfeSYaroslav Tykhiy 		return;
25963f8b9cfeSYaroslav Tykhiy 	}
25973f8b9cfeSYaroslav Tykhiy 	if (unlink(name) < 0) {
2598ea022d16SRodney W. Grimes 		perror_reply(550, name);
2599ea022d16SRodney W. Grimes 		return;
2600ea022d16SRodney W. Grimes 	}
2601ea022d16SRodney W. Grimes done:
2602ea022d16SRodney W. Grimes 	ack("DELE");
2603ea022d16SRodney W. Grimes }
2604ea022d16SRodney W. Grimes 
2605ea022d16SRodney W. Grimes void
2606e4bc453cSWarner Losh cwd(char *path)
2607ea022d16SRodney W. Grimes {
2608ea022d16SRodney W. Grimes 
2609ea022d16SRodney W. Grimes 	if (chdir(path) < 0)
2610ea022d16SRodney W. Grimes 		perror_reply(550, path);
2611ea022d16SRodney W. Grimes 	else
2612ea022d16SRodney W. Grimes 		ack("CWD");
2613ea022d16SRodney W. Grimes }
2614ea022d16SRodney W. Grimes 
2615ea022d16SRodney W. Grimes void
2616e4bc453cSWarner Losh makedir(char *name)
2617ea022d16SRodney W. Grimes {
26182b748987SYaroslav Tykhiy 	char *s;
2619ea022d16SRodney W. Grimes 
2620ea022d16SRodney W. Grimes 	LOGCMD("mkdir", name);
2621d186bb12SMatthew N. Dodd 	if (guest && noguestmkd)
2622405e2987SYaroslav Tykhiy 		reply(550, "Operation not permitted.");
2623d186bb12SMatthew N. Dodd 	else if (mkdir(name, 0777) < 0)
2624ea022d16SRodney W. Grimes 		perror_reply(550, name);
26252b748987SYaroslav Tykhiy 	else {
26262b748987SYaroslav Tykhiy 		if ((s = doublequote(name)) == NULL)
26272b748987SYaroslav Tykhiy 			fatalerror("Ran out of memory.");
26282b748987SYaroslav Tykhiy 		reply(257, "\"%s\" directory created.", s);
26292b748987SYaroslav Tykhiy 		free(s);
26302b748987SYaroslav Tykhiy 	}
2631ea022d16SRodney W. Grimes }
2632ea022d16SRodney W. Grimes 
2633ea022d16SRodney W. Grimes void
2634e4bc453cSWarner Losh removedir(char *name)
2635ea022d16SRodney W. Grimes {
2636ea022d16SRodney W. Grimes 
2637ea022d16SRodney W. Grimes 	LOGCMD("rmdir", name);
2638ea022d16SRodney W. Grimes 	if (rmdir(name) < 0)
2639ea022d16SRodney W. Grimes 		perror_reply(550, name);
2640ea022d16SRodney W. Grimes 	else
2641ea022d16SRodney W. Grimes 		ack("RMD");
2642ea022d16SRodney W. Grimes }
2643ea022d16SRodney W. Grimes 
2644ea022d16SRodney W. Grimes void
2645e4bc453cSWarner Losh pwd(void)
2646ea022d16SRodney W. Grimes {
2647e4648f05SYaroslav Tykhiy 	char *s, path[MAXPATHLEN + 1];
2648ea022d16SRodney W. Grimes 
2649de9b6c03SYaroslav Tykhiy 	if (getcwd(path, sizeof(path)) == NULL)
265075933089SYaroslav Tykhiy 		perror_reply(550, "Get current directory");
2651e4648f05SYaroslav Tykhiy 	else {
2652e4648f05SYaroslav Tykhiy 		if ((s = doublequote(path)) == NULL)
2653e4648f05SYaroslav Tykhiy 			fatalerror("Ran out of memory.");
2654e4648f05SYaroslav Tykhiy 		reply(257, "\"%s\" is current directory.", s);
2655e4648f05SYaroslav Tykhiy 		free(s);
2656e4648f05SYaroslav Tykhiy 	}
2657ea022d16SRodney W. Grimes }
2658ea022d16SRodney W. Grimes 
2659ea022d16SRodney W. Grimes char *
2660e4bc453cSWarner Losh renamefrom(char *name)
2661ea022d16SRodney W. Grimes {
2662ea022d16SRodney W. Grimes 	struct stat st;
2663ea022d16SRodney W. Grimes 
2664b943b3c4SYaroslav Tykhiy 	if (guest && noguestmod) {
266502c97492SYaroslav Tykhiy 		reply(550, "Operation not permitted.");
2666b943b3c4SYaroslav Tykhiy 		return (NULL);
2667b943b3c4SYaroslav Tykhiy 	}
26681b0e12d7SYaroslav Tykhiy 	if (lstat(name, &st) < 0) {
2669ea022d16SRodney W. Grimes 		perror_reply(550, name);
2670385f9bf0SYaroslav Tykhiy 		return (NULL);
2671ea022d16SRodney W. Grimes 	}
267202c97492SYaroslav Tykhiy 	reply(350, "File exists, ready for destination name.");
2673ea022d16SRodney W. Grimes 	return (name);
2674ea022d16SRodney W. Grimes }
2675ea022d16SRodney W. Grimes 
2676ea022d16SRodney W. Grimes void
2677e4bc453cSWarner Losh renamecmd(char *from, char *to)
2678ea022d16SRodney W. Grimes {
267961f891a6SPaul Traina 	struct stat st;
2680ea022d16SRodney W. Grimes 
2681ea022d16SRodney W. Grimes 	LOGCMD2("rename", from, to);
268261f891a6SPaul Traina 
268361f891a6SPaul Traina 	if (guest && (stat(to, &st) == 0)) {
268402c97492SYaroslav Tykhiy 		reply(550, "%s: permission denied.", to);
268561f891a6SPaul Traina 		return;
268661f891a6SPaul Traina 	}
268761f891a6SPaul Traina 
2688ea022d16SRodney W. Grimes 	if (rename(from, to) < 0)
2689ea022d16SRodney W. Grimes 		perror_reply(550, "rename");
2690ea022d16SRodney W. Grimes 	else
2691ea022d16SRodney W. Grimes 		ack("RNTO");
2692ea022d16SRodney W. Grimes }
2693ea022d16SRodney W. Grimes 
2694ea022d16SRodney W. Grimes static void
2695e4bc453cSWarner Losh dolog(struct sockaddr *who)
2696ea022d16SRodney W. Grimes {
26977cdd3cb7SYaroslav Tykhiy 	char who_name[NI_MAXHOST];
26984dd8b5abSYoshinobu Inoue 
26994dd8b5abSYoshinobu Inoue 	realhostname_sa(remotehost, sizeof(remotehost) - 1, who, who->sa_len);
270004683b2cSYaroslav Tykhiy 	remotehost[sizeof(remotehost) - 1] = 0;
27017cdd3cb7SYaroslav Tykhiy 	if (getnameinfo(who, who->sa_len,
27027cdd3cb7SYaroslav Tykhiy 		who_name, sizeof(who_name) - 1, NULL, 0, NI_NUMERICHOST))
27037cdd3cb7SYaroslav Tykhiy 			*who_name = 0;
27047cdd3cb7SYaroslav Tykhiy 	who_name[sizeof(who_name) - 1] = 0;
2705ea022d16SRodney W. Grimes 
2706ea022d16SRodney W. Grimes #ifdef SETPROCTITLE
2707ea4e54b9SDavid Nugent #ifdef VIRTUAL_HOSTING
2708ea4e54b9SDavid Nugent 	if (thishost != firsthost)
2709ea4e54b9SDavid Nugent 		snprintf(proctitle, sizeof(proctitle), "%s: connected (to %s)",
2710ea4e54b9SDavid Nugent 			 remotehost, hostname);
2711ea4e54b9SDavid Nugent 	else
2712ea4e54b9SDavid Nugent #endif
2713ea4e54b9SDavid Nugent 		snprintf(proctitle, sizeof(proctitle), "%s: connected",
2714ea4e54b9SDavid Nugent 			 remotehost);
2715b63e1fe2SPeter Wemm 	setproctitle("%s", proctitle);
2716ea022d16SRodney W. Grimes #endif /* SETPROCTITLE */
2717ea022d16SRodney W. Grimes 
2718ea4e54b9SDavid Nugent 	if (logging) {
2719ea4e54b9SDavid Nugent #ifdef VIRTUAL_HOSTING
2720ea4e54b9SDavid Nugent 		if (thishost != firsthost)
27217cdd3cb7SYaroslav Tykhiy 			syslog(LOG_INFO, "connection from %s (%s) to %s",
27227cdd3cb7SYaroslav Tykhiy 			       remotehost, who_name, hostname);
2723ea4e54b9SDavid Nugent 		else
2724ea4e54b9SDavid Nugent #endif
27257cdd3cb7SYaroslav Tykhiy 			syslog(LOG_INFO, "connection from %s (%s)",
27267cdd3cb7SYaroslav Tykhiy 			       remotehost, who_name);
2727ea022d16SRodney W. Grimes 	}
2728ea4e54b9SDavid Nugent }
2729ea022d16SRodney W. Grimes 
2730ea022d16SRodney W. Grimes /*
2731ea022d16SRodney W. Grimes  * Record logout in wtmp file
2732ea022d16SRodney W. Grimes  * and exit with supplied status.
2733ea022d16SRodney W. Grimes  */
2734ea022d16SRodney W. Grimes void
2735e4bc453cSWarner Losh dologout(int status)
2736ea022d16SRodney W. Grimes {
2737ea022d16SRodney W. Grimes 
27385d7e0128SYaroslav Tykhiy 	if (logged_in && dowtmp) {
273952e7ee74SYaroslav Tykhiy 		(void) seteuid(0);
274046948173SHajimu UMEMOTO 		ftpd_logwtmp(ttyline, "", NULL);
2741ea022d16SRodney W. Grimes 	}
2742ea022d16SRodney W. Grimes 	/* beware of flushing buffers after a SIGPIPE */
2743ea022d16SRodney W. Grimes 	_exit(status);
2744ea022d16SRodney W. Grimes }
2745ea022d16SRodney W. Grimes 
2746ea022d16SRodney W. Grimes static void
2747e4bc453cSWarner Losh sigurg(int signo)
2748ea022d16SRodney W. Grimes {
27494b82fc95SYaroslav Tykhiy 
27504b82fc95SYaroslav Tykhiy 	recvurg = 1;
27514b82fc95SYaroslav Tykhiy }
27524b82fc95SYaroslav Tykhiy 
27534b82fc95SYaroslav Tykhiy static void
27544cd51076SYaroslav Tykhiy maskurg(int flag)
27554cd51076SYaroslav Tykhiy {
27564cd51076SYaroslav Tykhiy 	int oerrno;
27574cd51076SYaroslav Tykhiy 	sigset_t sset;
27584cd51076SYaroslav Tykhiy 
27594cd51076SYaroslav Tykhiy 	if (!transflag) {
27604cd51076SYaroslav Tykhiy 		syslog(LOG_ERR, "Internal: maskurg() while no transfer");
27614cd51076SYaroslav Tykhiy 		return;
27624cd51076SYaroslav Tykhiy 	}
27634cd51076SYaroslav Tykhiy 	oerrno = errno;
27644cd51076SYaroslav Tykhiy 	sigemptyset(&sset);
27654cd51076SYaroslav Tykhiy 	sigaddset(&sset, SIGURG);
27664cd51076SYaroslav Tykhiy 	sigprocmask(flag ? SIG_BLOCK : SIG_UNBLOCK, &sset, NULL);
27674cd51076SYaroslav Tykhiy 	errno = oerrno;
27684cd51076SYaroslav Tykhiy }
27694cd51076SYaroslav Tykhiy 
27704cd51076SYaroslav Tykhiy static void
27714cd51076SYaroslav Tykhiy flagxfer(int flag)
27724cd51076SYaroslav Tykhiy {
27734cd51076SYaroslav Tykhiy 
27744cd51076SYaroslav Tykhiy 	if (flag) {
2775f9036ce6SYaroslav Tykhiy 		if (transflag)
2776f9036ce6SYaroslav Tykhiy 			syslog(LOG_ERR, "Internal: flagxfer(1): "
2777f9036ce6SYaroslav Tykhiy 					"transfer already under way");
27784cd51076SYaroslav Tykhiy 		transflag = 1;
277991ae7779SYaroslav Tykhiy 		maskurg(0);
278091ae7779SYaroslav Tykhiy 		recvurg = 0;
278191ae7779SYaroslav Tykhiy 	} else {
2782f9036ce6SYaroslav Tykhiy 		if (!transflag)
2783f9036ce6SYaroslav Tykhiy 			syslog(LOG_ERR, "Internal: flagxfer(0): "
2784f9036ce6SYaroslav Tykhiy 					"no active transfer");
278591ae7779SYaroslav Tykhiy 		maskurg(1);
27864cd51076SYaroslav Tykhiy 		transflag = 0;
27874cd51076SYaroslav Tykhiy 	}
278891ae7779SYaroslav Tykhiy }
27894cd51076SYaroslav Tykhiy 
27904cd51076SYaroslav Tykhiy /*
27914cd51076SYaroslav Tykhiy  * Returns 0 if OK to resume or -1 if abort requested.
27924cd51076SYaroslav Tykhiy  */
27934cd51076SYaroslav Tykhiy static int
2794e4bc453cSWarner Losh myoob(void)
27954b82fc95SYaroslav Tykhiy {
2796ea022d16SRodney W. Grimes 	char *cp;
2797f0b40b1cSColin Percival 	int ret;
2798ea022d16SRodney W. Grimes 
27994cd51076SYaroslav Tykhiy 	if (!transflag) {
28004cd51076SYaroslav Tykhiy 		syslog(LOG_ERR, "Internal: myoob() while no transfer");
28014cd51076SYaroslav Tykhiy 		return (0);
28024cd51076SYaroslav Tykhiy 	}
2803ea022d16SRodney W. Grimes 	cp = tmpline;
2804f0b40b1cSColin Percival 	ret = getline(cp, 7, stdin);
2805f0b40b1cSColin Percival 	if (ret == -1) {
2806ea022d16SRodney W. Grimes 		reply(221, "You could at least say goodbye.");
2807ea022d16SRodney W. Grimes 		dologout(0);
2808f0b40b1cSColin Percival 	} else if (ret == -2) {
2809f0b40b1cSColin Percival 		/* Ignore truncated command. */
2810f0b40b1cSColin Percival 		return (0);
2811ea022d16SRodney W. Grimes 	}
2812ea022d16SRodney W. Grimes 	upper(cp);
2813ea022d16SRodney W. Grimes 	if (strcmp(cp, "ABOR\r\n") == 0) {
2814ea022d16SRodney W. Grimes 		tmpline[0] = '\0';
2815ea022d16SRodney W. Grimes 		reply(426, "Transfer aborted. Data connection closed.");
281602c97492SYaroslav Tykhiy 		reply(226, "Abort successful.");
28174cd51076SYaroslav Tykhiy 		return (-1);
2818ea022d16SRodney W. Grimes 	}
2819ea022d16SRodney W. Grimes 	if (strcmp(cp, "STAT\r\n") == 0) {
28209db4bbf3SMichael Haro 		tmpline[0] = '\0';
28210e519c96SYaroslav Tykhiy 		if (file_size != -1)
282202c97492SYaroslav Tykhiy 			reply(213, "Status: %jd of %jd bytes transferred.",
2823a57e1ef0SYaroslav Tykhiy 				   (intmax_t)byte_count, (intmax_t)file_size);
2824ea022d16SRodney W. Grimes 		else
282502c97492SYaroslav Tykhiy 			reply(213, "Status: %jd bytes transferred.",
2826a57e1ef0SYaroslav Tykhiy 				   (intmax_t)byte_count);
2827ea022d16SRodney W. Grimes 	}
28284cd51076SYaroslav Tykhiy 	return (0);
2829ea022d16SRodney W. Grimes }
2830ea022d16SRodney W. Grimes 
2831ea022d16SRodney W. Grimes /*
2832ea022d16SRodney W. Grimes  * Note: a response of 425 is not mentioned as a possible response to
2833ea022d16SRodney W. Grimes  *	the PASV command in RFC959. However, it has been blessed as
2834ea022d16SRodney W. Grimes  *	a legitimate response by Jon Postel in a telephone conversation
2835ea022d16SRodney W. Grimes  *	with Rick Adams on 25 Jan 89.
2836ea022d16SRodney W. Grimes  */
2837ea022d16SRodney W. Grimes void
2838e4bc453cSWarner Losh passive(void)
2839ea022d16SRodney W. Grimes {
284078e3eed0SStefan Farfeleder 	socklen_t len;
284178e3eed0SStefan Farfeleder 	int on;
2842ea022d16SRodney W. Grimes 	char *p, *a;
2843ea022d16SRodney W. Grimes 
284461f891a6SPaul Traina 	if (pdata >= 0)		/* close old port if one set */
284561f891a6SPaul Traina 		close(pdata);
284661f891a6SPaul Traina 
28474dd8b5abSYoshinobu Inoue 	pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2848ea022d16SRodney W. Grimes 	if (pdata < 0) {
2849ea022d16SRodney W. Grimes 		perror_reply(425, "Can't open passive connection");
2850ea022d16SRodney W. Grimes 		return;
2851ea022d16SRodney W. Grimes 	}
28528af7c9a3SYaroslav Tykhiy 	on = 1;
28538af7c9a3SYaroslav Tykhiy 	if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
28548af7c9a3SYaroslav Tykhiy 		syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
28554c450ad7SPaul Traina 
285652e7ee74SYaroslav Tykhiy 	(void) seteuid(0);
285761f891a6SPaul Traina 
2858dacc9752SPaul Traina #ifdef IP_PORTRANGE
28594dd8b5abSYoshinobu Inoue 	if (ctrl_addr.su_family == AF_INET) {
28608af7c9a3SYaroslav Tykhiy 	    on = restricted_data_ports ? IP_PORTRANGE_HIGH
2861dacc9752SPaul Traina 				       : IP_PORTRANGE_DEFAULT;
2862dacc9752SPaul Traina 
286340e9d39eSPeter Wemm 	    if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
286457d4ef07SYaroslav Tykhiy 			    &on, sizeof(on)) < 0)
28654c450ad7SPaul Traina 		    goto pasv_error;
28664c450ad7SPaul Traina 	}
2867dacc9752SPaul Traina #endif
28682db39860SNick Sayer #ifdef IPV6_PORTRANGE
28692db39860SNick Sayer 	if (ctrl_addr.su_family == AF_INET6) {
28708af7c9a3SYaroslav Tykhiy 	    on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
28712db39860SNick Sayer 				       : IPV6_PORTRANGE_DEFAULT;
28722db39860SNick Sayer 
28732db39860SNick Sayer 	    if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
287457d4ef07SYaroslav Tykhiy 			    &on, sizeof(on)) < 0)
28752db39860SNick Sayer 		    goto pasv_error;
28762db39860SNick Sayer 	}
28772db39860SNick Sayer #endif
287840e9d39eSPeter Wemm 
2879ea022d16SRodney W. Grimes 	pasv_addr = ctrl_addr;
28804dd8b5abSYoshinobu Inoue 	pasv_addr.su_port = 0;
28814dd8b5abSYoshinobu Inoue 	if (bind(pdata, (struct sockaddr *)&pasv_addr, pasv_addr.su_len) < 0)
2882ea022d16SRodney W. Grimes 		goto pasv_error;
288361f891a6SPaul Traina 
288452e7ee74SYaroslav Tykhiy 	(void) seteuid(pw->pw_uid);
28854c450ad7SPaul Traina 
2886ea022d16SRodney W. Grimes 	len = sizeof(pasv_addr);
2887ea022d16SRodney W. Grimes 	if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2888ea022d16SRodney W. Grimes 		goto pasv_error;
2889ea022d16SRodney W. Grimes 	if (listen(pdata, 1) < 0)
2890ea022d16SRodney W. Grimes 		goto pasv_error;
28914dd8b5abSYoshinobu Inoue 	if (pasv_addr.su_family == AF_INET)
28924dd8b5abSYoshinobu Inoue 		a = (char *) &pasv_addr.su_sin.sin_addr;
28934dd8b5abSYoshinobu Inoue 	else if (pasv_addr.su_family == AF_INET6 &&
28944dd8b5abSYoshinobu Inoue 		 IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr))
28954dd8b5abSYoshinobu Inoue 		a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
28964dd8b5abSYoshinobu Inoue 	else
28974dd8b5abSYoshinobu Inoue 		goto pasv_error;
28984dd8b5abSYoshinobu Inoue 
28994dd8b5abSYoshinobu Inoue 	p = (char *) &pasv_addr.su_port;
2900ea022d16SRodney W. Grimes 
2901ea022d16SRodney W. Grimes #define UC(b) (((int) b) & 0xff)
2902ea022d16SRodney W. Grimes 
2903ea022d16SRodney W. Grimes 	reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
2904ea022d16SRodney W. Grimes 		UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
2905ea022d16SRodney W. Grimes 	return;
2906ea022d16SRodney W. Grimes 
2907ea022d16SRodney W. Grimes pasv_error:
290852e7ee74SYaroslav Tykhiy 	(void) seteuid(pw->pw_uid);
2909ea022d16SRodney W. Grimes 	(void) close(pdata);
2910ea022d16SRodney W. Grimes 	pdata = -1;
2911ea022d16SRodney W. Grimes 	perror_reply(425, "Can't open passive connection");
2912ea022d16SRodney W. Grimes 	return;
2913ea022d16SRodney W. Grimes }
2914ea022d16SRodney W. Grimes 
2915ea022d16SRodney W. Grimes /*
29164dd8b5abSYoshinobu Inoue  * Long Passive defined in RFC 1639.
29174dd8b5abSYoshinobu Inoue  *     228 Entering Long Passive Mode
29184dd8b5abSYoshinobu Inoue  *         (af, hal, h1, h2, h3,..., pal, p1, p2...)
29194dd8b5abSYoshinobu Inoue  */
29204dd8b5abSYoshinobu Inoue 
29214dd8b5abSYoshinobu Inoue void
2922e4bc453cSWarner Losh long_passive(char *cmd, int pf)
29234dd8b5abSYoshinobu Inoue {
292478e3eed0SStefan Farfeleder 	socklen_t len;
292578e3eed0SStefan Farfeleder 	int on;
29264dd8b5abSYoshinobu Inoue 	char *p, *a;
29274dd8b5abSYoshinobu Inoue 
29284dd8b5abSYoshinobu Inoue 	if (pdata >= 0)		/* close old port if one set */
29294dd8b5abSYoshinobu Inoue 		close(pdata);
29304dd8b5abSYoshinobu Inoue 
29314dd8b5abSYoshinobu Inoue 	if (pf != PF_UNSPEC) {
29324dd8b5abSYoshinobu Inoue 		if (ctrl_addr.su_family != pf) {
29334dd8b5abSYoshinobu Inoue 			switch (ctrl_addr.su_family) {
29344dd8b5abSYoshinobu Inoue 			case AF_INET:
29354dd8b5abSYoshinobu Inoue 				pf = 1;
29364dd8b5abSYoshinobu Inoue 				break;
29374dd8b5abSYoshinobu Inoue 			case AF_INET6:
29384dd8b5abSYoshinobu Inoue 				pf = 2;
29394dd8b5abSYoshinobu Inoue 				break;
29404dd8b5abSYoshinobu Inoue 			default:
29414dd8b5abSYoshinobu Inoue 				pf = 0;
29424dd8b5abSYoshinobu Inoue 				break;
29434dd8b5abSYoshinobu Inoue 			}
29444dd8b5abSYoshinobu Inoue 			/*
29454dd8b5abSYoshinobu Inoue 			 * XXX
29464dd8b5abSYoshinobu Inoue 			 * only EPRT/EPSV ready clients will understand this
29474dd8b5abSYoshinobu Inoue 			 */
29484dd8b5abSYoshinobu Inoue 			if (strcmp(cmd, "EPSV") == 0 && pf) {
29494dd8b5abSYoshinobu Inoue 				reply(522, "Network protocol mismatch, "
29504dd8b5abSYoshinobu Inoue 					"use (%d)", pf);
29514dd8b5abSYoshinobu Inoue 			} else
295202c97492SYaroslav Tykhiy 				reply(501, "Network protocol mismatch."); /*XXX*/
29534dd8b5abSYoshinobu Inoue 
29544dd8b5abSYoshinobu Inoue 			return;
29554dd8b5abSYoshinobu Inoue 		}
29564dd8b5abSYoshinobu Inoue 	}
29574dd8b5abSYoshinobu Inoue 
29584dd8b5abSYoshinobu Inoue 	pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
29594dd8b5abSYoshinobu Inoue 	if (pdata < 0) {
29604dd8b5abSYoshinobu Inoue 		perror_reply(425, "Can't open passive connection");
29614dd8b5abSYoshinobu Inoue 		return;
29624dd8b5abSYoshinobu Inoue 	}
29638af7c9a3SYaroslav Tykhiy 	on = 1;
29648af7c9a3SYaroslav Tykhiy 	if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
29658af7c9a3SYaroslav Tykhiy 		syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
29664dd8b5abSYoshinobu Inoue 
296752e7ee74SYaroslav Tykhiy 	(void) seteuid(0);
29684dd8b5abSYoshinobu Inoue 
29694dd8b5abSYoshinobu Inoue 	pasv_addr = ctrl_addr;
29704dd8b5abSYoshinobu Inoue 	pasv_addr.su_port = 0;
29714dd8b5abSYoshinobu Inoue 	len = pasv_addr.su_len;
29724dd8b5abSYoshinobu Inoue 
29732db39860SNick Sayer #ifdef IP_PORTRANGE
29742db39860SNick Sayer 	if (ctrl_addr.su_family == AF_INET) {
29758af7c9a3SYaroslav Tykhiy 	    on = restricted_data_ports ? IP_PORTRANGE_HIGH
29762db39860SNick Sayer 				       : IP_PORTRANGE_DEFAULT;
29772db39860SNick Sayer 
29782db39860SNick Sayer 	    if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
297957d4ef07SYaroslav Tykhiy 			    &on, sizeof(on)) < 0)
29802db39860SNick Sayer 		    goto pasv_error;
29812db39860SNick Sayer 	}
29822db39860SNick Sayer #endif
29832db39860SNick Sayer #ifdef IPV6_PORTRANGE
29842db39860SNick Sayer 	if (ctrl_addr.su_family == AF_INET6) {
29858af7c9a3SYaroslav Tykhiy 	    on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
29862db39860SNick Sayer 				       : IPV6_PORTRANGE_DEFAULT;
29872db39860SNick Sayer 
29882db39860SNick Sayer 	    if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
298957d4ef07SYaroslav Tykhiy 			    &on, sizeof(on)) < 0)
29902db39860SNick Sayer 		    goto pasv_error;
29912db39860SNick Sayer 	}
29922db39860SNick Sayer #endif
29932db39860SNick Sayer 
29944dd8b5abSYoshinobu Inoue 	if (bind(pdata, (struct sockaddr *)&pasv_addr, len) < 0)
29954dd8b5abSYoshinobu Inoue 		goto pasv_error;
29964dd8b5abSYoshinobu Inoue 
299752e7ee74SYaroslav Tykhiy 	(void) seteuid(pw->pw_uid);
29984dd8b5abSYoshinobu Inoue 
29994dd8b5abSYoshinobu Inoue 	if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
30004dd8b5abSYoshinobu Inoue 		goto pasv_error;
30014dd8b5abSYoshinobu Inoue 	if (listen(pdata, 1) < 0)
30024dd8b5abSYoshinobu Inoue 		goto pasv_error;
30034dd8b5abSYoshinobu Inoue 
30044dd8b5abSYoshinobu Inoue #define UC(b) (((int) b) & 0xff)
30054dd8b5abSYoshinobu Inoue 
30064dd8b5abSYoshinobu Inoue 	if (strcmp(cmd, "LPSV") == 0) {
30074dd8b5abSYoshinobu Inoue 		p = (char *)&pasv_addr.su_port;
30084dd8b5abSYoshinobu Inoue 		switch (pasv_addr.su_family) {
30094dd8b5abSYoshinobu Inoue 		case AF_INET:
30104dd8b5abSYoshinobu Inoue 			a = (char *) &pasv_addr.su_sin.sin_addr;
30114dd8b5abSYoshinobu Inoue 		v4_reply:
30124dd8b5abSYoshinobu Inoue 			reply(228,
30134dd8b5abSYoshinobu Inoue "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)",
30144dd8b5abSYoshinobu Inoue 			      4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
30154dd8b5abSYoshinobu Inoue 			      2, UC(p[0]), UC(p[1]));
30164dd8b5abSYoshinobu Inoue 			return;
30174dd8b5abSYoshinobu Inoue 		case AF_INET6:
30184dd8b5abSYoshinobu Inoue 			if (IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr)) {
30194dd8b5abSYoshinobu Inoue 				a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
30204dd8b5abSYoshinobu Inoue 				goto v4_reply;
30214dd8b5abSYoshinobu Inoue 			}
30224dd8b5abSYoshinobu Inoue 			a = (char *) &pasv_addr.su_sin6.sin6_addr;
30234dd8b5abSYoshinobu Inoue 			reply(228,
30244dd8b5abSYoshinobu Inoue "Entering Long Passive Mode "
30254dd8b5abSYoshinobu Inoue "(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)",
30264dd8b5abSYoshinobu Inoue 			      6, 16, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
30274dd8b5abSYoshinobu Inoue 			      UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]),
30284dd8b5abSYoshinobu Inoue 			      UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]),
30294dd8b5abSYoshinobu Inoue 			      UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]),
30304dd8b5abSYoshinobu Inoue 			      2, UC(p[0]), UC(p[1]));
30314dd8b5abSYoshinobu Inoue 			return;
30324dd8b5abSYoshinobu Inoue 		}
30334dd8b5abSYoshinobu Inoue 	} else if (strcmp(cmd, "EPSV") == 0) {
30344dd8b5abSYoshinobu Inoue 		switch (pasv_addr.su_family) {
30354dd8b5abSYoshinobu Inoue 		case AF_INET:
30364dd8b5abSYoshinobu Inoue 		case AF_INET6:
30374dd8b5abSYoshinobu Inoue 			reply(229, "Entering Extended Passive Mode (|||%d|)",
30384dd8b5abSYoshinobu Inoue 				ntohs(pasv_addr.su_port));
30394dd8b5abSYoshinobu Inoue 			return;
30404dd8b5abSYoshinobu Inoue 		}
30414dd8b5abSYoshinobu Inoue 	} else {
30424dd8b5abSYoshinobu Inoue 		/* more proper error code? */
30434dd8b5abSYoshinobu Inoue 	}
30444dd8b5abSYoshinobu Inoue 
30454dd8b5abSYoshinobu Inoue pasv_error:
304652e7ee74SYaroslav Tykhiy 	(void) seteuid(pw->pw_uid);
30474dd8b5abSYoshinobu Inoue 	(void) close(pdata);
30484dd8b5abSYoshinobu Inoue 	pdata = -1;
30494dd8b5abSYoshinobu Inoue 	perror_reply(425, "Can't open passive connection");
30504dd8b5abSYoshinobu Inoue 	return;
30514dd8b5abSYoshinobu Inoue }
30524dd8b5abSYoshinobu Inoue 
30534dd8b5abSYoshinobu Inoue /*
3054a117c345SYaroslav Tykhiy  * Generate unique name for file with basename "local"
3055a117c345SYaroslav Tykhiy  * and open the file in order to avoid possible races.
3056a117c345SYaroslav Tykhiy  * Try "local" first, then "local.1", "local.2" etc, up to "local.99".
3057a117c345SYaroslav Tykhiy  * Return descriptor to the file, set "name" to its name.
3058a117c345SYaroslav Tykhiy  *
3059ea022d16SRodney W. Grimes  * Generates failure reply on error.
3060ea022d16SRodney W. Grimes  */
3061a117c345SYaroslav Tykhiy static int
3062a117c345SYaroslav Tykhiy guniquefd(char *local, char **name)
3063ea022d16SRodney W. Grimes {
3064ea022d16SRodney W. Grimes 	static char new[MAXPATHLEN];
3065ea022d16SRodney W. Grimes 	struct stat st;
3066ea022d16SRodney W. Grimes 	char *cp;
3067a117c345SYaroslav Tykhiy 	int count;
3068a117c345SYaroslav Tykhiy 	int fd;
3069ea022d16SRodney W. Grimes 
3070ea022d16SRodney W. Grimes 	cp = strrchr(local, '/');
3071ea022d16SRodney W. Grimes 	if (cp)
3072ea022d16SRodney W. Grimes 		*cp = '\0';
3073ea022d16SRodney W. Grimes 	if (stat(cp ? local : ".", &st) < 0) {
3074ea022d16SRodney W. Grimes 		perror_reply(553, cp ? local : ".");
3075a117c345SYaroslav Tykhiy 		return (-1);
3076ea022d16SRodney W. Grimes 	}
3077a117c345SYaroslav Tykhiy 	if (cp) {
3078a117c345SYaroslav Tykhiy 		/*
3079a117c345SYaroslav Tykhiy 		 * Let not overwrite dirname with counter suffix.
3080a117c345SYaroslav Tykhiy 		 * -4 is for /nn\0
3081a117c345SYaroslav Tykhiy 		 * In this extreme case dot won't be put in front of suffix.
3082a117c345SYaroslav Tykhiy 		 */
3083a117c345SYaroslav Tykhiy 		if (strlen(local) > sizeof(new) - 4) {
308402c97492SYaroslav Tykhiy 			reply(553, "Pathname too long.");
3085a117c345SYaroslav Tykhiy 			return (-1);
3086a117c345SYaroslav Tykhiy 		}
3087ea022d16SRodney W. Grimes 		*cp = '/';
3088a117c345SYaroslav Tykhiy 	}
3089e760ef2cSWarner Losh 	/* -4 is for the .nn<null> we put on the end below */
3090e760ef2cSWarner Losh 	(void) snprintf(new, sizeof(new) - 4, "%s", local);
3091ea022d16SRodney W. Grimes 	cp = new + strlen(new);
3092a117c345SYaroslav Tykhiy 	/*
3093a117c345SYaroslav Tykhiy 	 * Don't generate dotfile unless requested explicitly.
3094a117c345SYaroslav Tykhiy 	 * This covers the case when basename gets truncated off
3095a117c345SYaroslav Tykhiy 	 * by buffer size.
3096a117c345SYaroslav Tykhiy 	 */
3097a117c345SYaroslav Tykhiy 	if (cp > new && cp[-1] != '/')
3098ea022d16SRodney W. Grimes 		*cp++ = '.';
3099a117c345SYaroslav Tykhiy 	for (count = 0; count < 100; count++) {
3100a117c345SYaroslav Tykhiy 		/* At count 0 try unmodified name */
3101a117c345SYaroslav Tykhiy 		if (count)
3102ea022d16SRodney W. Grimes 			(void)sprintf(cp, "%d", count);
3103a117c345SYaroslav Tykhiy 		if ((fd = open(count ? new : local,
3104a117c345SYaroslav Tykhiy 		    O_RDWR | O_CREAT | O_EXCL, 0666)) >= 0) {
3105a117c345SYaroslav Tykhiy 			*name = count ? new : local;
3106a117c345SYaroslav Tykhiy 			return (fd);
3107a117c345SYaroslav Tykhiy 		}
310888b70721SYaroslav Tykhiy 		if (errno != EEXIST) {
310950618d61SYaroslav Tykhiy 			perror_reply(553, count ? new : local);
311088b70721SYaroslav Tykhiy 			return (-1);
311188b70721SYaroslav Tykhiy 		}
3112ea022d16SRodney W. Grimes 	}
3113ea022d16SRodney W. Grimes 	reply(452, "Unique file name cannot be created.");
3114a117c345SYaroslav Tykhiy 	return (-1);
3115ea022d16SRodney W. Grimes }
3116ea022d16SRodney W. Grimes 
3117ea022d16SRodney W. Grimes /*
3118ea022d16SRodney W. Grimes  * Format and send reply containing system error number.
3119ea022d16SRodney W. Grimes  */
3120ea022d16SRodney W. Grimes void
3121e4bc453cSWarner Losh perror_reply(int code, char *string)
3122ea022d16SRodney W. Grimes {
3123ea022d16SRodney W. Grimes 
3124ea022d16SRodney W. Grimes 	reply(code, "%s: %s.", string, strerror(errno));
3125ea022d16SRodney W. Grimes }
3126ea022d16SRodney W. Grimes 
3127ea022d16SRodney W. Grimes static char *onefile[] = {
3128ea022d16SRodney W. Grimes 	"",
3129ea022d16SRodney W. Grimes 	0
3130ea022d16SRodney W. Grimes };
3131ea022d16SRodney W. Grimes 
3132ea022d16SRodney W. Grimes void
3133e4bc453cSWarner Losh send_file_list(char *whichf)
3134ea022d16SRodney W. Grimes {
3135ea022d16SRodney W. Grimes 	struct stat st;
3136ea022d16SRodney W. Grimes 	DIR *dirp = NULL;
3137ea022d16SRodney W. Grimes 	struct dirent *dir;
3138ea022d16SRodney W. Grimes 	FILE *dout = NULL;
3139ea022d16SRodney W. Grimes 	char **dirlist, *dirname;
3140ea022d16SRodney W. Grimes 	int simple = 0;
3141ea022d16SRodney W. Grimes 	int freeglob = 0;
3142ea022d16SRodney W. Grimes 	glob_t gl;
3143ea022d16SRodney W. Grimes 
3144ea022d16SRodney W. Grimes 	if (strpbrk(whichf, "~{[*?") != NULL) {
314512da320bSMike Heffner 		int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
3146ea022d16SRodney W. Grimes 
3147ea022d16SRodney W. Grimes 		memset(&gl, 0, sizeof(gl));
31486d10cb2fSJonathan Lemon 		gl.gl_matchc = MAXGLOBARGS;
314975dc5f1aSMike Heffner 		flags |= GLOB_LIMIT;
3150ea022d16SRodney W. Grimes 		freeglob = 1;
3151ea022d16SRodney W. Grimes 		if (glob(whichf, flags, 0, &gl)) {
315202c97492SYaroslav Tykhiy 			reply(550, "No matching files found.");
3153ea022d16SRodney W. Grimes 			goto out;
3154ea022d16SRodney W. Grimes 		} else if (gl.gl_pathc == 0) {
3155ea022d16SRodney W. Grimes 			errno = ENOENT;
3156ea022d16SRodney W. Grimes 			perror_reply(550, whichf);
3157ea022d16SRodney W. Grimes 			goto out;
3158ea022d16SRodney W. Grimes 		}
3159ea022d16SRodney W. Grimes 		dirlist = gl.gl_pathv;
3160ea022d16SRodney W. Grimes 	} else {
3161ea022d16SRodney W. Grimes 		onefile[0] = whichf;
3162ea022d16SRodney W. Grimes 		dirlist = onefile;
3163ea022d16SRodney W. Grimes 		simple = 1;
3164ea022d16SRodney W. Grimes 	}
3165ea022d16SRodney W. Grimes 
31669aca17cbSMark Murray 	while ((dirname = *dirlist++)) {
3167ea022d16SRodney W. Grimes 		if (stat(dirname, &st) < 0) {
3168ea022d16SRodney W. Grimes 			/*
3169ea022d16SRodney W. Grimes 			 * If user typed "ls -l", etc, and the client
3170ea022d16SRodney W. Grimes 			 * used NLST, do what the user meant.
3171ea022d16SRodney W. Grimes 			 */
3172ea022d16SRodney W. Grimes 			if (dirname[0] == '-' && *dirlist == NULL &&
31734cd51076SYaroslav Tykhiy 			    dout == NULL)
3174af85d782SDavid Nugent 				retrieve(_PATH_LS " %s", dirname);
31754cd51076SYaroslav Tykhiy 			else
3176ea022d16SRodney W. Grimes 				perror_reply(550, whichf);
3177ea022d16SRodney W. Grimes 			goto out;
3178ea022d16SRodney W. Grimes 		}
3179ea022d16SRodney W. Grimes 
3180ea022d16SRodney W. Grimes 		if (S_ISREG(st.st_mode)) {
3181ea022d16SRodney W. Grimes 			if (dout == NULL) {
31820e519c96SYaroslav Tykhiy 				dout = dataconn("file list", -1, "w");
3183ea022d16SRodney W. Grimes 				if (dout == NULL)
3184ea022d16SRodney W. Grimes 					goto out;
31854cd51076SYaroslav Tykhiy 				STARTXFER;
3186ea022d16SRodney W. Grimes 			}
31874cd51076SYaroslav Tykhiy 			START_UNSAFE;
3188ea022d16SRodney W. Grimes 			fprintf(dout, "%s%s\n", dirname,
3189ea022d16SRodney W. Grimes 				type == TYPE_A ? "\r" : "");
31904cd51076SYaroslav Tykhiy 			END_UNSAFE;
31914cd51076SYaroslav Tykhiy 			if (ferror(dout))
31924cd51076SYaroslav Tykhiy 				goto data_err;
31934cd51076SYaroslav Tykhiy 			byte_count += strlen(dirname) +
31944cd51076SYaroslav Tykhiy 				      (type == TYPE_A ? 2 : 1);
31954cd51076SYaroslav Tykhiy 			CHECKOOB(goto abrt);
3196ea022d16SRodney W. Grimes 			continue;
3197ea022d16SRodney W. Grimes 		} else if (!S_ISDIR(st.st_mode))
3198ea022d16SRodney W. Grimes 			continue;
3199ea022d16SRodney W. Grimes 
3200ea022d16SRodney W. Grimes 		if ((dirp = opendir(dirname)) == NULL)
3201ea022d16SRodney W. Grimes 			continue;
3202ea022d16SRodney W. Grimes 
3203ea022d16SRodney W. Grimes 		while ((dir = readdir(dirp)) != NULL) {
3204ea022d16SRodney W. Grimes 			char nbuf[MAXPATHLEN];
3205ea022d16SRodney W. Grimes 
32064cd51076SYaroslav Tykhiy 			CHECKOOB(goto abrt);
32074b82fc95SYaroslav Tykhiy 
3208ea022d16SRodney W. Grimes 			if (dir->d_name[0] == '.' && dir->d_namlen == 1)
3209ea022d16SRodney W. Grimes 				continue;
3210ea022d16SRodney W. Grimes 			if (dir->d_name[0] == '.' && dir->d_name[1] == '.' &&
3211ea022d16SRodney W. Grimes 			    dir->d_namlen == 2)
3212ea022d16SRodney W. Grimes 				continue;
3213ea022d16SRodney W. Grimes 
3214e760ef2cSWarner Losh 			snprintf(nbuf, sizeof(nbuf),
3215e760ef2cSWarner Losh 				"%s/%s", dirname, dir->d_name);
3216ea022d16SRodney W. Grimes 
3217ea022d16SRodney W. Grimes 			/*
3218ea022d16SRodney W. Grimes 			 * We have to do a stat to insure it's
3219ea022d16SRodney W. Grimes 			 * not a directory or special file.
3220ea022d16SRodney W. Grimes 			 */
3221ea022d16SRodney W. Grimes 			if (simple || (stat(nbuf, &st) == 0 &&
3222ea022d16SRodney W. Grimes 			    S_ISREG(st.st_mode))) {
3223ea022d16SRodney W. Grimes 				if (dout == NULL) {
32240e519c96SYaroslav Tykhiy 					dout = dataconn("file list", -1, "w");
3225ea022d16SRodney W. Grimes 					if (dout == NULL)
3226ea022d16SRodney W. Grimes 						goto out;
32274cd51076SYaroslav Tykhiy 					STARTXFER;
3228ea022d16SRodney W. Grimes 				}
32294cd51076SYaroslav Tykhiy 				START_UNSAFE;
3230ea022d16SRodney W. Grimes 				if (nbuf[0] == '.' && nbuf[1] == '/')
3231ea022d16SRodney W. Grimes 					fprintf(dout, "%s%s\n", &nbuf[2],
3232ea022d16SRodney W. Grimes 						type == TYPE_A ? "\r" : "");
3233ea022d16SRodney W. Grimes 				else
3234ea022d16SRodney W. Grimes 					fprintf(dout, "%s%s\n", nbuf,
3235ea022d16SRodney W. Grimes 						type == TYPE_A ? "\r" : "");
32364cd51076SYaroslav Tykhiy 				END_UNSAFE;
32374cd51076SYaroslav Tykhiy 				if (ferror(dout))
32384cd51076SYaroslav Tykhiy 					goto data_err;
32394cd51076SYaroslav Tykhiy 				byte_count += strlen(nbuf) +
32404cd51076SYaroslav Tykhiy 					      (type == TYPE_A ? 2 : 1);
32414cd51076SYaroslav Tykhiy 				CHECKOOB(goto abrt);
3242ea022d16SRodney W. Grimes 			}
3243ea022d16SRodney W. Grimes 		}
3244ea022d16SRodney W. Grimes 		(void) closedir(dirp);
32454cd51076SYaroslav Tykhiy 		dirp = NULL;
3246ea022d16SRodney W. Grimes 	}
3247ea022d16SRodney W. Grimes 
3248ea022d16SRodney W. Grimes 	if (dout == NULL)
3249ea022d16SRodney W. Grimes 		reply(550, "No files found.");
32504cd51076SYaroslav Tykhiy 	else if (ferror(dout))
32514cd51076SYaroslav Tykhiy data_err:	perror_reply(550, "Data connection");
3252ea022d16SRodney W. Grimes 	else
3253ea022d16SRodney W. Grimes 		reply(226, "Transfer complete.");
32544cd51076SYaroslav Tykhiy out:
32554cd51076SYaroslav Tykhiy 	if (dout) {
32564cd51076SYaroslav Tykhiy 		ENDXFER;
32574cd51076SYaroslav Tykhiy abrt:
3258ea022d16SRodney W. Grimes 		(void) fclose(dout);
3259ea022d16SRodney W. Grimes 		data = -1;
3260ea022d16SRodney W. Grimes 		pdata = -1;
32614cd51076SYaroslav Tykhiy 	}
32624cd51076SYaroslav Tykhiy 	if (dirp)
32634cd51076SYaroslav Tykhiy 		(void) closedir(dirp);
3264ea022d16SRodney W. Grimes 	if (freeglob) {
3265ea022d16SRodney W. Grimes 		freeglob = 0;
3266ea022d16SRodney W. Grimes 		globfree(&gl);
3267ea022d16SRodney W. Grimes 	}
3268ea022d16SRodney W. Grimes }
3269ea022d16SRodney W. Grimes 
3270cf09a206SDavid Greenman void
3271e4bc453cSWarner Losh reapchild(int signo)
3272cf09a206SDavid Greenman {
3273de9b6c03SYaroslav Tykhiy 	while (waitpid(-1, NULL, WNOHANG) > 0);
3274cf09a206SDavid Greenman }
3275cf09a206SDavid Greenman 
3276b63e1fe2SPeter Wemm #ifdef OLD_SETPROCTITLE
3277ea022d16SRodney W. Grimes /*
3278ea022d16SRodney W. Grimes  * Clobber argv so ps will show what we're doing.  (Stolen from sendmail.)
3279ea022d16SRodney W. Grimes  * Warning, since this is usually started from inetd.conf, it often doesn't
3280ea022d16SRodney W. Grimes  * have much of an environment or arglist to overwrite.
3281ea022d16SRodney W. Grimes  */
3282ea022d16SRodney W. Grimes void
3283ea022d16SRodney W. Grimes setproctitle(const char *fmt, ...)
3284ea022d16SRodney W. Grimes {
3285ea022d16SRodney W. Grimes 	int i;
3286ea022d16SRodney W. Grimes 	va_list ap;
3287ea022d16SRodney W. Grimes 	char *p, *bp, ch;
3288ea022d16SRodney W. Grimes 	char buf[LINE_MAX];
3289ea022d16SRodney W. Grimes 
3290ea022d16SRodney W. Grimes 	va_start(ap, fmt);
3291ea022d16SRodney W. Grimes 	(void)vsnprintf(buf, sizeof(buf), fmt, ap);
3292ea022d16SRodney W. Grimes 
3293ea022d16SRodney W. Grimes 	/* make ps print our process name */
3294ea022d16SRodney W. Grimes 	p = Argv[0];
3295ea022d16SRodney W. Grimes 	*p++ = '-';
3296ea022d16SRodney W. Grimes 
3297ea022d16SRodney W. Grimes 	i = strlen(buf);
3298ea022d16SRodney W. Grimes 	if (i > LastArgv - p - 2) {
3299ea022d16SRodney W. Grimes 		i = LastArgv - p - 2;
3300ea022d16SRodney W. Grimes 		buf[i] = '\0';
3301ea022d16SRodney W. Grimes 	}
3302ea022d16SRodney W. Grimes 	bp = buf;
3303ea022d16SRodney W. Grimes 	while (ch = *bp++)
3304ea022d16SRodney W. Grimes 		if (ch != '\n' && ch != '\r')
3305ea022d16SRodney W. Grimes 			*p++ = ch;
3306ea022d16SRodney W. Grimes 	while (p < LastArgv)
3307ea022d16SRodney W. Grimes 		*p++ = ' ';
3308ea022d16SRodney W. Grimes }
3309b63e1fe2SPeter Wemm #endif /* OLD_SETPROCTITLE */
33103eb568f2SGuido van Rooij 
331161f891a6SPaul Traina static void
33126b2dee6bSYaroslav Tykhiy appendf(char **strp, char *fmt, ...)
33136b2dee6bSYaroslav Tykhiy {
33146b2dee6bSYaroslav Tykhiy 	va_list ap;
33156b2dee6bSYaroslav Tykhiy 	char *ostr, *p;
33166b2dee6bSYaroslav Tykhiy 
33176b2dee6bSYaroslav Tykhiy 	va_start(ap, fmt);
33186b2dee6bSYaroslav Tykhiy 	vasprintf(&p, fmt, ap);
33196b2dee6bSYaroslav Tykhiy 	va_end(ap);
33206b2dee6bSYaroslav Tykhiy 	if (p == NULL)
33216b2dee6bSYaroslav Tykhiy 		fatalerror("Ran out of memory.");
33226b2dee6bSYaroslav Tykhiy 	if (*strp == NULL)
33236b2dee6bSYaroslav Tykhiy 		*strp = p;
33246b2dee6bSYaroslav Tykhiy 	else {
33256b2dee6bSYaroslav Tykhiy 		ostr = *strp;
33266b2dee6bSYaroslav Tykhiy 		asprintf(strp, "%s%s", ostr, p);
33276b2dee6bSYaroslav Tykhiy 		if (*strp == NULL)
33286b2dee6bSYaroslav Tykhiy 			fatalerror("Ran out of memory.");
33296b2dee6bSYaroslav Tykhiy 		free(ostr);
33306b2dee6bSYaroslav Tykhiy 	}
33316b2dee6bSYaroslav Tykhiy }
33326b2dee6bSYaroslav Tykhiy 
33336b2dee6bSYaroslav Tykhiy static void
33346b2dee6bSYaroslav Tykhiy logcmd(char *cmd, char *file1, char *file2, off_t cnt)
33356b2dee6bSYaroslav Tykhiy {
33366b2dee6bSYaroslav Tykhiy 	char *msg = NULL;
33376b2dee6bSYaroslav Tykhiy 	char wd[MAXPATHLEN + 1];
33386b2dee6bSYaroslav Tykhiy 
33396b2dee6bSYaroslav Tykhiy 	if (logging <= 1)
33406b2dee6bSYaroslav Tykhiy 		return;
3341e897216fSYaroslav Tykhiy 
33426b2dee6bSYaroslav Tykhiy 	if (getcwd(wd, sizeof(wd) - 1) == NULL)
33436b2dee6bSYaroslav Tykhiy 		strcpy(wd, strerror(errno));
33446b2dee6bSYaroslav Tykhiy 
33456b2dee6bSYaroslav Tykhiy 	appendf(&msg, "%s", cmd);
33466b2dee6bSYaroslav Tykhiy 	if (file1)
33476b2dee6bSYaroslav Tykhiy 		appendf(&msg, " %s", file1);
33486b2dee6bSYaroslav Tykhiy 	if (file2)
33496b2dee6bSYaroslav Tykhiy 		appendf(&msg, " %s", file2);
33506b2dee6bSYaroslav Tykhiy 	if (cnt >= 0)
33516b2dee6bSYaroslav Tykhiy 		appendf(&msg, " = %jd bytes", (intmax_t)cnt);
3352e897216fSYaroslav Tykhiy 	appendf(&msg, " (wd: %s", wd);
3353215a9f9dSYaroslav Tykhiy 	if (guest || dochroot)
3354e897216fSYaroslav Tykhiy 		appendf(&msg, "; chrooted");
3355e897216fSYaroslav Tykhiy 	appendf(&msg, ")");
33566b2dee6bSYaroslav Tykhiy 	syslog(LOG_INFO, "%s", msg);
33576b2dee6bSYaroslav Tykhiy 	free(msg);
33586b2dee6bSYaroslav Tykhiy }
33596b2dee6bSYaroslav Tykhiy 
33606b2dee6bSYaroslav Tykhiy static void
3361e4bc453cSWarner Losh logxfer(char *name, off_t size, time_t start)
33623eb568f2SGuido van Rooij {
33638c1c21f2SYaroslav Tykhiy 	char buf[MAXPATHLEN + 1024];
33643eb568f2SGuido van Rooij 	char path[MAXPATHLEN + 1];
3365158a00b2SJohn Birrell 	time_t now;
33663eb568f2SGuido van Rooij 
33678c1c21f2SYaroslav Tykhiy 	if (statfd >= 0) {
33683eb568f2SGuido van Rooij 		time(&now);
33698c1c21f2SYaroslav Tykhiy 		if (realpath(name, path) == NULL) {
33708c1c21f2SYaroslav Tykhiy 			syslog(LOG_NOTICE, "realpath failed on %s: %m", path);
33718c1c21f2SYaroslav Tykhiy 			return;
33728c1c21f2SYaroslav Tykhiy 		}
33738c1c21f2SYaroslav Tykhiy 		snprintf(buf, sizeof(buf), "%.20s!%s!%s!%s!%jd!%ld\n",
33743eb568f2SGuido van Rooij 			ctime(&now)+4, ident, remotehost,
33758c1c21f2SYaroslav Tykhiy 			path, (intmax_t)size,
3376e4a71114SAndrey A. Chernov 			(long)(now - start + (now == start)));
33773eb568f2SGuido van Rooij 		write(statfd, buf, strlen(buf));
33783eb568f2SGuido van Rooij 	}
33793eb568f2SGuido van Rooij }
3380e4648f05SYaroslav Tykhiy 
3381e4648f05SYaroslav Tykhiy static char *
3382e4648f05SYaroslav Tykhiy doublequote(char *s)
3383e4648f05SYaroslav Tykhiy {
3384e4648f05SYaroslav Tykhiy 	int n;
3385e4648f05SYaroslav Tykhiy 	char *p, *s2;
3386e4648f05SYaroslav Tykhiy 
3387e4648f05SYaroslav Tykhiy 	for (p = s, n = 0; *p; p++)
3388e4648f05SYaroslav Tykhiy 		if (*p == '"')
3389e4648f05SYaroslav Tykhiy 			n++;
3390e4648f05SYaroslav Tykhiy 
3391e4648f05SYaroslav Tykhiy 	if ((s2 = malloc(p - s + n + 1)) == NULL)
3392e4648f05SYaroslav Tykhiy 		return (NULL);
3393e4648f05SYaroslav Tykhiy 
3394e4648f05SYaroslav Tykhiy 	for (p = s2; *s; s++, p++) {
3395e4648f05SYaroslav Tykhiy 		if ((*p = *s) == '"')
3396e4648f05SYaroslav Tykhiy 			*(++p) = '"';
3397e4648f05SYaroslav Tykhiy 	}
3398e4648f05SYaroslav Tykhiy 	*p = '\0';
3399e4648f05SYaroslav Tykhiy 
3400e4648f05SYaroslav Tykhiy 	return (s2);
3401e4648f05SYaroslav Tykhiy }
3402206fe568SHajimu UMEMOTO 
3403206fe568SHajimu UMEMOTO /* setup server socket for specified address family */
3404206fe568SHajimu UMEMOTO /* if af is PF_UNSPEC more than one socket may be returned */
3405206fe568SHajimu UMEMOTO /* the returned list is dynamically allocated, so caller needs to free it */
3406206fe568SHajimu UMEMOTO static int *
3407206fe568SHajimu UMEMOTO socksetup(int af, char *bindname, const char *bindport)
3408206fe568SHajimu UMEMOTO {
3409206fe568SHajimu UMEMOTO 	struct addrinfo hints, *res, *r;
3410206fe568SHajimu UMEMOTO 	int error, maxs, *s, *socks;
3411206fe568SHajimu UMEMOTO 	const int on = 1;
3412206fe568SHajimu UMEMOTO 
3413206fe568SHajimu UMEMOTO 	memset(&hints, 0, sizeof(hints));
3414206fe568SHajimu UMEMOTO 	hints.ai_flags = AI_PASSIVE;
3415206fe568SHajimu UMEMOTO 	hints.ai_family = af;
3416206fe568SHajimu UMEMOTO 	hints.ai_socktype = SOCK_STREAM;
3417206fe568SHajimu UMEMOTO 	error = getaddrinfo(bindname, bindport, &hints, &res);
3418206fe568SHajimu UMEMOTO 	if (error) {
3419206fe568SHajimu UMEMOTO 		syslog(LOG_ERR, "%s", gai_strerror(error));
3420206fe568SHajimu UMEMOTO 		if (error == EAI_SYSTEM)
3421206fe568SHajimu UMEMOTO 			syslog(LOG_ERR, "%s", strerror(errno));
3422206fe568SHajimu UMEMOTO 		return NULL;
3423206fe568SHajimu UMEMOTO 	}
3424206fe568SHajimu UMEMOTO 
3425206fe568SHajimu UMEMOTO 	/* Count max number of sockets we may open */
3426206fe568SHajimu UMEMOTO 	for (maxs = 0, r = res; r; r = r->ai_next, maxs++)
3427206fe568SHajimu UMEMOTO 		;
3428206fe568SHajimu UMEMOTO 	socks = malloc((maxs + 1) * sizeof(int));
3429206fe568SHajimu UMEMOTO 	if (!socks) {
3430206fe568SHajimu UMEMOTO 		freeaddrinfo(res);
3431206fe568SHajimu UMEMOTO 		syslog(LOG_ERR, "couldn't allocate memory for sockets");
3432206fe568SHajimu UMEMOTO 		return NULL;
3433206fe568SHajimu UMEMOTO 	}
3434206fe568SHajimu UMEMOTO 
3435206fe568SHajimu UMEMOTO 	*socks = 0;   /* num of sockets counter at start of array */
3436206fe568SHajimu UMEMOTO 	s = socks + 1;
3437206fe568SHajimu UMEMOTO 	for (r = res; r; r = r->ai_next) {
3438206fe568SHajimu UMEMOTO 		*s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
3439206fe568SHajimu UMEMOTO 		if (*s < 0) {
3440206fe568SHajimu UMEMOTO 			syslog(LOG_DEBUG, "control socket: %m");
3441206fe568SHajimu UMEMOTO 			continue;
3442206fe568SHajimu UMEMOTO 		}
3443206fe568SHajimu UMEMOTO 		if (setsockopt(*s, SOL_SOCKET, SO_REUSEADDR,
3444206fe568SHajimu UMEMOTO 		    &on, sizeof(on)) < 0)
3445206fe568SHajimu UMEMOTO 			syslog(LOG_WARNING,
3446206fe568SHajimu UMEMOTO 			    "control setsockopt (SO_REUSEADDR): %m");
3447206fe568SHajimu UMEMOTO 		if (r->ai_family == AF_INET6) {
3448206fe568SHajimu UMEMOTO 			if (setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY,
3449206fe568SHajimu UMEMOTO 			    &on, sizeof(on)) < 0)
3450206fe568SHajimu UMEMOTO 				syslog(LOG_WARNING,
3451206fe568SHajimu UMEMOTO 				    "control setsockopt (IPV6_V6ONLY): %m");
3452206fe568SHajimu UMEMOTO 		}
3453206fe568SHajimu UMEMOTO 		if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
3454206fe568SHajimu UMEMOTO 			syslog(LOG_DEBUG, "control bind: %m");
3455206fe568SHajimu UMEMOTO 			close(*s);
3456206fe568SHajimu UMEMOTO 			continue;
3457206fe568SHajimu UMEMOTO 		}
3458206fe568SHajimu UMEMOTO 		(*socks)++;
3459206fe568SHajimu UMEMOTO 		s++;
3460206fe568SHajimu UMEMOTO 	}
3461206fe568SHajimu UMEMOTO 
3462206fe568SHajimu UMEMOTO 	if (res)
3463206fe568SHajimu UMEMOTO 		freeaddrinfo(res);
3464206fe568SHajimu UMEMOTO 
3465206fe568SHajimu UMEMOTO 	if (*socks == 0) {
3466206fe568SHajimu UMEMOTO 		syslog(LOG_ERR, "control socket: Couldn't bind to any socket");
3467206fe568SHajimu UMEMOTO 		free(socks);
3468206fe568SHajimu UMEMOTO 		return NULL;
3469206fe568SHajimu UMEMOTO 	}
3470206fe568SHajimu UMEMOTO 	return(socks);
3471206fe568SHajimu UMEMOTO }
3472