ftpd.c revision 1.33
1/*	$OpenBSD: ftpd.c,v 1.33 1997/03/25 22:47:10 millert Exp $	*/
2/*	$NetBSD: ftpd.c,v 1.15 1995/06/03 22:46:47 mycroft Exp $	*/
3
4/*
5 * Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994
6 *	The Regents of the University of California.  All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 * 3. All advertising materials mentioning features or use of this software
17 *    must display the following acknowledgement:
18 *	This product includes software developed by the University of
19 *	California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 *    may be used to endorse or promote products derived from this software
22 *    without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
35 */
36
37#ifndef lint
38static char copyright[] =
39"@(#) Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994\n\
40	The Regents of the University of California.  All rights reserved.\n";
41#endif /* not lint */
42
43#ifndef lint
44#if 0
45static char sccsid[] = "@(#)ftpd.c	8.4 (Berkeley) 4/16/94";
46#else
47static char rcsid[] = "$NetBSD: ftpd.c,v 1.15 1995/06/03 22:46:47 mycroft Exp $";
48#endif
49#endif /* not lint */
50
51/*
52 * FTP server.
53 */
54#include <sys/param.h>
55#include <sys/stat.h>
56#include <sys/ioctl.h>
57#include <sys/socket.h>
58#include <sys/wait.h>
59#include <sys/mman.h>
60
61#include <netinet/in.h>
62#include <netinet/in_systm.h>
63#include <netinet/ip.h>
64#include <netinet/tcp.h>
65
66#define	FTP_NAMES
67#include <arpa/ftp.h>
68#include <arpa/inet.h>
69#include <arpa/telnet.h>
70
71#include <ctype.h>
72#include <dirent.h>
73#include <err.h>
74#include <errno.h>
75#include <fcntl.h>
76#include <glob.h>
77#include <limits.h>
78#include <netdb.h>
79#include <pwd.h>
80#include <setjmp.h>
81#include <signal.h>
82#include <stdio.h>
83#include <stdlib.h>
84#include <string.h>
85#include <syslog.h>
86#include <time.h>
87#include <vis.h>
88#include <unistd.h>
89#include <utmp.h>
90
91#include "pathnames.h"
92#include "extern.h"
93
94#if __STDC__
95#include <stdarg.h>
96#else
97#include <varargs.h>
98#endif
99
100static char version[] = "Version 6.2/OpenBSD";
101
102extern	off_t restart_point;
103extern	char cbuf[];
104
105struct	sockaddr_in server_addr;
106struct	sockaddr_in ctrl_addr;
107struct	sockaddr_in data_source;
108struct	sockaddr_in data_dest;
109struct	sockaddr_in his_addr;
110struct	sockaddr_in pasv_addr;
111
112int	daemon_mode = 0;
113int	data;
114jmp_buf	errcatch, urgcatch;
115int	logged_in;
116struct	passwd *pw;
117int	debug = 0;
118int	timeout = 900;    /* timeout after 15 minutes of inactivity */
119int	maxtimeout = 7200;/* don't allow idle time to be set beyond 2 hours */
120int	logging;
121int	high_data_ports = 0;
122int	anon_only = 0;
123int	multihome = 0;
124int	guest;
125int	stats;
126int	statfd = -1;
127int	dochroot;
128int	type;
129int	form;
130int	stru;			/* avoid C keyword */
131int	mode;
132int	doutmp = 0;		/* update utmp file */
133int	usedefault = 1;		/* for data transfers */
134int	pdata = -1;		/* for passive mode */
135sig_atomic_t transflag;
136off_t	file_size;
137off_t	byte_count;
138#if !defined(CMASK) || CMASK == 0
139#undef CMASK
140#define CMASK 027
141#endif
142int	defumask = CMASK;		/* default umask value */
143char	tmpline[7];
144char	hostname[MAXHOSTNAMELEN];
145char	remotehost[MAXHOSTNAMELEN];
146char	dhostname[MAXHOSTNAMELEN];
147char	*guestpw;
148static char ttyline[20];
149char	*tty = ttyline;		/* for klogin */
150static struct utmp utmp;	/* for utmp */
151
152#if defined(KERBEROS)
153int	notickets = 1;
154char	*krbtkfile_env = NULL;
155#endif
156
157char	*ident = NULL;
158
159
160/*
161 * Timeout intervals for retrying connections
162 * to hosts that don't accept PORT cmds.  This
163 * is a kludge, but given the problems with TCP...
164 */
165#define	SWAITMAX	90	/* wait at most 90 seconds */
166#define	SWAITINT	5	/* interval between retries */
167
168int	swaitmax = SWAITMAX;
169int	swaitint = SWAITINT;
170
171#ifdef HASSETPROCTITLE
172char	proctitle[BUFSIZ];	/* initial part of title */
173#endif /* HASSETPROCTITLE */
174
175#define LOGCMD(cmd, file) \
176	if (logging > 1) \
177	    syslog(LOG_INFO,"%s %s%s", cmd, \
178		*(file) == '/' ? "" : curdir(), file);
179#define LOGCMD2(cmd, file1, file2) \
180	 if (logging > 1) \
181	    syslog(LOG_INFO,"%s %s%s %s%s", cmd, \
182		*(file1) == '/' ? "" : curdir(), file1, \
183		*(file2) == '/' ? "" : curdir(), file2);
184#define LOGBYTES(cmd, file, cnt) \
185	if (logging > 1) { \
186		if (cnt == (off_t)-1) \
187		    syslog(LOG_INFO,"%s %s%s", cmd, \
188			*(file) == '/' ? "" : curdir(), file); \
189		else \
190		    syslog(LOG_INFO, "%s %s%s = %qd bytes", \
191			cmd, (*(file) == '/') ? "" : curdir(), file, cnt); \
192	}
193
194static void	 ack __P((char *));
195static void	 myoob __P((int));
196static int	 checkuser __P((char *, char *));
197static FILE	*dataconn __P((char *, off_t, char *));
198static void	 dolog __P((struct sockaddr_in *));
199static char	*curdir __P((void));
200static void	 end_login __P((void));
201static FILE	*getdatasock __P((char *));
202static int	guniquefd __P((char *, char **));
203static void	 lostconn __P((int));
204static void	 sigquit __P((int));
205static int	 receive_data __P((FILE *, FILE *));
206static void	 send_data __P((FILE *, FILE *, off_t, off_t, int));
207static struct passwd *
208		 sgetpwnam __P((char *));
209static char	*sgetsave __P((char *));
210static void	 reapchild __P((int));
211
212void	 logxfer __P((char *, off_t, time_t));
213
214static char *
215curdir()
216{
217	static char path[MAXPATHLEN+1+1];	/* path + '/' + '\0' */
218
219	if (getcwd(path, sizeof(path)-2) == NULL)
220		return ("");
221	if (path[1] != '\0')		/* special case for root dir. */
222		strcat(path, "/");
223	/* For guest account, skip / since it's chrooted */
224	return (guest ? path+1 : path);
225}
226
227int
228main(argc, argv, envp)
229	int argc;
230	char *argv[];
231	char **envp;
232{
233	int addrlen, ch, on = 1, tos;
234	char *cp, line[LINE_MAX];
235	FILE *fd;
236	char *argstr = "AdDhlMSt:T:u:Uv";
237	struct hostent *hp;
238
239	tzset();	/* in case no timezone database in ~ftp */
240
241	/* set this here so klogin can use it... */
242	(void)snprintf(ttyline, sizeof(ttyline), "ftp%d", getpid());
243
244	while ((ch = getopt(argc, argv, argstr)) != -1) {
245		switch (ch) {
246		case 'A':
247			anon_only = 1;
248			break;
249
250		case 'd':
251			debug = 1;
252			break;
253
254		case 'D':
255			daemon_mode = 1;
256			break;
257
258		case 'h':
259			high_data_ports = 1;
260			break;
261
262		case 'l':
263			logging++;	/* > 1 == extra logging */
264			break;
265
266		case 'M':
267			multihome = 1;
268			break;
269
270		case 'S':
271			stats = 1;
272			break;
273
274		case 't':
275			timeout = atoi(optarg);
276			if (maxtimeout < timeout)
277				maxtimeout = timeout;
278			break;
279
280		case 'T':
281			maxtimeout = atoi(optarg);
282			if (timeout > maxtimeout)
283				timeout = maxtimeout;
284			break;
285
286		case 'u':
287		    {
288			long val = 0;
289
290			val = strtol(optarg, &optarg, 8);
291			if (*optarg != '\0' || val < 0)
292				warnx("bad value for -u");
293			else
294				defumask = val;
295			break;
296		    }
297
298		case 'U':
299			doutmp = 1;
300			break;
301
302		case 'v':
303			debug = 1;
304			break;
305
306		default:
307			warnx("unknown flag -%c ignored", optopt);
308			break;
309		}
310	}
311
312	(void) freopen(_PATH_DEVNULL, "w", stderr);
313
314	/*
315	 * LOG_NDELAY sets up the logging connection immediately,
316	 * necessary for anonymous ftp's that chroot and can't do it later.
317	 */
318	openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
319
320	if (daemon_mode) {
321		int ctl_sock, fd;
322		struct servent *sv;
323
324		/*
325		 * Detach from parent.
326		 */
327		if (daemon(1, 1) < 0) {
328			syslog(LOG_ERR, "failed to become a daemon");
329			exit(1);
330		}
331		(void) signal(SIGCHLD, reapchild);
332		/*
333		 * Get port number for ftp/tcp.
334		 */
335		sv = getservbyname("ftp", "tcp");
336		if (sv == NULL) {
337			syslog(LOG_ERR, "getservbyname for ftp failed");
338			exit(1);
339		}
340		/*
341		 * Open a socket, bind it to the FTP port, and start
342		 * listening.
343		 */
344		ctl_sock = socket(AF_INET, SOCK_STREAM, 0);
345		if (ctl_sock < 0) {
346			syslog(LOG_ERR, "control socket: %m");
347			exit(1);
348		}
349		if (setsockopt(ctl_sock, SOL_SOCKET, SO_REUSEADDR,
350		    (char *)&on, sizeof(on)) < 0)
351			syslog(LOG_ERR, "control setsockopt: %m");;
352		server_addr.sin_family = AF_INET;
353		server_addr.sin_addr.s_addr = INADDR_ANY;
354		server_addr.sin_port = sv->s_port;
355		if (bind(ctl_sock, (struct sockaddr *)&server_addr,
356			 sizeof(server_addr))) {
357			syslog(LOG_ERR, "control bind: %m");
358			exit(1);
359		}
360		if (listen(ctl_sock, 32) < 0) {
361			syslog(LOG_ERR, "control listen: %m");
362			exit(1);
363		}
364		/*
365		 * Loop forever accepting connection requests and forking off
366		 * children to handle them.
367		 */
368		while (1) {
369			addrlen = sizeof(his_addr);
370			fd = accept(ctl_sock, (struct sockaddr *)&his_addr,
371				    &addrlen);
372			if (fork() == 0) {
373				/* child */
374				(void) dup2(fd, 0);
375				(void) dup2(fd, 1);
376				close(ctl_sock);
377				break;
378			}
379			close(fd);
380		}
381	} else {
382		addrlen = sizeof(his_addr);
383		if (getpeername(0, (struct sockaddr *)&his_addr,
384			        &addrlen) < 0) {
385			syslog(LOG_ERR, "getpeername (%s): %m", argv[0]);
386			exit(1);
387		}
388	}
389
390	(void) signal(SIGHUP, sigquit);
391	(void) signal(SIGINT, sigquit);
392	(void) signal(SIGQUIT, sigquit);
393	(void) signal(SIGTERM, sigquit);
394	(void) signal(SIGPIPE, lostconn);
395	(void) signal(SIGCHLD, SIG_IGN);
396	if ((long)signal(SIGURG, myoob) < 0)
397		syslog(LOG_ERR, "signal: %m");
398
399	addrlen = sizeof(ctrl_addr);
400	if (getsockname(0, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) {
401		syslog(LOG_ERR, "getsockname (%s): %m", argv[0]);
402		exit(1);
403	}
404#ifdef IP_TOS
405	tos = IPTOS_LOWDELAY;
406	if (setsockopt(0, IPPROTO_IP, IP_TOS, (char *)&tos, sizeof(int)) < 0)
407		syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
408#endif
409	data_source.sin_port = htons(ntohs(ctrl_addr.sin_port) - 1);
410
411	/* Try to handle urgent data inline */
412#ifdef SO_OOBINLINE
413	if (setsockopt(0, SOL_SOCKET, SO_OOBINLINE, (char *)&on, sizeof(on)) < 0)
414		syslog(LOG_ERR, "setsockopt: %m");
415#endif
416
417#ifdef	F_SETOWN
418	if (fcntl(fileno(stdin), F_SETOWN, getpid()) == -1)
419		syslog(LOG_ERR, "fcntl F_SETOWN: %m");
420#endif
421	dolog(&his_addr);
422	/*
423	 * Set up default state
424	 */
425	data = -1;
426	type = TYPE_A;
427	form = FORM_N;
428	stru = STRU_F;
429	mode = MODE_S;
430	tmpline[0] = '\0';
431
432	/* If logins are disabled, print out the message. */
433	if ((fd = fopen(_PATH_NOLOGIN,"r")) != NULL) {
434		while (fgets(line, sizeof(line), fd) != NULL) {
435			if ((cp = strchr(line, '\n')) != NULL)
436				*cp = '\0';
437			lreply(530, "%s", line);
438		}
439		(void) fflush(stdout);
440		(void) fclose(fd);
441		reply(530, "System not available.");
442		exit(0);
443	}
444	if ((fd = fopen(_PATH_FTPWELCOME, "r")) != NULL) {
445		while (fgets(line, sizeof(line), fd) != NULL) {
446			if ((cp = strchr(line, '\n')) != NULL)
447				*cp = '\0';
448			lreply(220, "%s", line);
449		}
450		(void) fflush(stdout);
451		(void) fclose(fd);
452		/* reply(220,) must follow */
453	}
454	(void) gethostname(hostname, sizeof(hostname));
455
456	/* Make sure hostname is fully qualified. */
457	hp = gethostbyname(hostname);
458	if (hp != NULL)
459		strcpy (hostname, hp->h_name);
460
461	if (multihome) {
462		hp = gethostbyaddr((char *) &ctrl_addr.sin_addr,
463				   sizeof (struct in_addr), AF_INET);
464		if (hp != NULL) {
465			strcpy (dhostname, hp->h_name);
466		} else {
467			/* Default. */
468			strcpy (dhostname, inet_ntoa(ctrl_addr.sin_addr));
469		}
470	}
471
472	reply(220, "%s FTP server (%s) ready.",
473	      (multihome ? dhostname : hostname), version);
474	(void) setjmp(errcatch);
475	for (;;)
476		(void) yyparse();
477	/* NOTREACHED */
478}
479
480/*
481 * Signal handlers.
482 */
483
484static void
485lostconn(signo)
486	int signo;
487{
488
489	if (debug)
490		syslog(LOG_DEBUG, "lost connection");
491	dologout(-1);
492}
493
494static void
495sigquit(signo)
496	int signo;
497{
498	syslog(LOG_ERR, "got signal %s", strsignal(signo));
499
500	dologout(-1);
501}
502
503/*
504 * Helper function for sgetpwnam().
505 */
506static char *
507sgetsave(s)
508	char *s;
509{
510	char *new = malloc((unsigned) strlen(s) + 1);
511
512	if (new == NULL) {
513		perror_reply(421, "Local resource failure: malloc");
514		dologout(1);
515		/* NOTREACHED */
516	}
517	(void) strcpy(new, s);
518	return (new);
519}
520
521/*
522 * Save the result of a getpwnam.  Used for USER command, since
523 * the data returned must not be clobbered by any other command
524 * (e.g., globbing).
525 */
526static struct passwd *
527sgetpwnam(name)
528	char *name;
529{
530	static struct passwd save;
531	struct passwd *p;
532
533	if ((p = getpwnam(name)) == NULL)
534		return (p);
535	if (save.pw_name) {
536		free(save.pw_name);
537		memset(save.pw_passwd, 0, strlen(save.pw_passwd));
538		free(save.pw_passwd);
539		free(save.pw_gecos);
540		free(save.pw_dir);
541		free(save.pw_shell);
542	}
543	save = *p;
544	save.pw_name = sgetsave(p->pw_name);
545	save.pw_passwd = sgetsave(p->pw_passwd);
546	save.pw_gecos = sgetsave(p->pw_gecos);
547	save.pw_dir = sgetsave(p->pw_dir);
548	save.pw_shell = sgetsave(p->pw_shell);
549	return (&save);
550}
551
552static int login_attempts;	/* number of failed login attempts */
553static int askpasswd;		/* had user command, ask for passwd */
554static char curname[16];	/* current USER name */
555
556/*
557 * USER command.
558 * Sets global passwd pointer pw if named account exists and is acceptable;
559 * sets askpasswd if a PASS command is expected.  If logged in previously,
560 * need to reset state.  If name is "ftp" or "anonymous", the name is not in
561 * _PATH_FTPUSERS, and ftp account exists, set guest and pw, then just return.
562 * If account doesn't exist, ask for passwd anyway.  Otherwise, check user
563 * requesting login privileges.  Disallow anyone who does not have a standard
564 * shell as returned by getusershell().  Disallow anyone mentioned in the file
565 * _PATH_FTPUSERS to allow people such as root and uucp to be avoided.
566 */
567void
568user(name)
569	char *name;
570{
571	char *cp, *shell;
572
573	if (logged_in) {
574		if (guest) {
575			reply(530, "Can't change user from guest login.");
576			return;
577		} else if (dochroot) {
578			reply(530, "Can't change user from chroot user.");
579			return;
580		}
581		end_login();
582	}
583
584	guest = 0;
585	if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) {
586		if (checkuser(_PATH_FTPUSERS, "ftp") ||
587		    checkuser(_PATH_FTPUSERS, "anonymous"))
588			reply(530, "User %s access denied.", name);
589		else if ((pw = sgetpwnam("ftp")) != NULL) {
590			guest = 1;
591			askpasswd = 1;
592			reply(331,
593			    "Guest login ok, type your name as password.");
594		} else
595			reply(530, "User %s unknown.", name);
596		if (!askpasswd && logging)
597			syslog(LOG_NOTICE,
598			    "ANONYMOUS FTP LOGIN REFUSED FROM %s", remotehost);
599		return;
600	}
601	if (anon_only != 0) {
602		reply(530, "Sorry, only anonymous ftp allowed.");
603		return;
604	}
605
606	if (pw = sgetpwnam(name)) {
607		if ((shell = pw->pw_shell) == NULL || *shell == 0)
608			shell = _PATH_BSHELL;
609		while ((cp = getusershell()) != NULL)
610			if (strcmp(cp, shell) == 0)
611				break;
612		endusershell();
613
614		if (cp == NULL || checkuser(_PATH_FTPUSERS, name)) {
615			reply(530, "User %s access denied.", name);
616			if (logging)
617				syslog(LOG_NOTICE,
618				    "FTP LOGIN REFUSED FROM %s, %s",
619				    remotehost, name);
620			pw = (struct passwd *) NULL;
621			return;
622		}
623	}
624	if (logging) {
625		strncpy(curname, name, sizeof(curname)-1);
626		curname[sizeof(curname)-1] = '\0';
627	}
628#ifdef SKEY
629	if (!skey_haskey(name)) {
630		char *myskey, *skey_keyinfo __P((char *name));
631
632		myskey = skey_keyinfo(name);
633		reply(331, "Password [ %s ] for %s required.",
634		    myskey ? myskey : "error getting challenge", name);
635	} else
636#endif
637		reply(331, "Password required for %s.", name);
638
639	askpasswd = 1;
640	/*
641	 * Delay before reading passwd after first failed
642	 * attempt to slow down passwd-guessing programs.
643	 */
644	if (login_attempts)
645		sleep((unsigned) login_attempts);
646}
647
648/*
649 * Check if a user is in the file "fname"
650 */
651static int
652checkuser(fname, name)
653	char *fname;
654	char *name;
655{
656	FILE *fd;
657	int found = 0;
658	char *p, line[BUFSIZ];
659
660	if ((fd = fopen(fname, "r")) != NULL) {
661		while (fgets(line, sizeof(line), fd) != NULL)
662			if ((p = strchr(line, '\n')) != NULL) {
663				*p = '\0';
664				if (line[0] == '#')
665					continue;
666				if (strcmp(line, name) == 0) {
667					found = 1;
668					break;
669				}
670			}
671		(void) fclose(fd);
672	}
673	return (found);
674}
675
676/*
677 * Terminate login as previous user, if any, resetting state;
678 * used when USER command is given or login fails.
679 */
680static void
681end_login()
682{
683	sigset_t allsigs;
684	sigfillset (&allsigs);
685	sigprocmask (SIG_BLOCK, &allsigs, NULL);
686	(void) seteuid((uid_t)0);
687	if (logged_in) {
688		logwtmp(ttyline, "", "");
689		if (doutmp)
690			logout(utmp.ut_line);
691	}
692	pw = NULL;
693	logged_in = 0;
694	guest = 0;
695	dochroot = 0;
696}
697
698void
699pass(passwd)
700	char *passwd;
701{
702	int rval;
703	FILE *fd;
704	static char homedir[MAXPATHLEN];
705	char rootdir[MAXPATHLEN];
706	sigset_t allsigs;
707
708	if (logged_in || askpasswd == 0) {
709		reply(503, "Login with USER first.");
710		return;
711	}
712	askpasswd = 0;
713	if (!guest) {		/* "ftp" is only account allowed no password */
714		if (pw == NULL) {
715			rval = 1;	/* failure below */
716			goto skip;
717		}
718#if defined(KERBEROS)
719		rval = klogin(pw, "", hostname, passwd);
720		if (rval == 0)
721			goto skip;
722#endif
723#ifdef SKEY
724		if (skey_haskey(pw->pw_name) == 0 &&
725		   (skey_passcheck(pw->pw_name, passwd) != -1)) {
726			rval = 0;
727			goto skip;
728		}
729#endif
730		/* the strcmp does not catch null passwords! */
731		if (pw == NULL || *pw->pw_passwd == '\0' ||
732		    strcmp(crypt(passwd, (pw ? pw->pw_passwd : "xx")), pw->pw_passwd)) {
733			rval = 1;	 /* failure */
734			goto skip;
735		}
736		rval = 0;
737
738skip:
739		/*
740		 * If rval == 1, the user failed the authentication check
741		 * above.  If rval == 0, either Kerberos or local authentication
742		 * succeeded.
743		 */
744		if (rval) {
745			reply(530, "Login incorrect.");
746			if (logging)
747				syslog(LOG_NOTICE,
748				    "FTP LOGIN FAILED FROM %s, %s",
749				    remotehost, curname);
750			pw = NULL;
751			if (login_attempts++ >= 5) {
752				syslog(LOG_NOTICE,
753				    "repeated login failures from %s",
754				    remotehost);
755				exit(0);
756			}
757			return;
758		}
759	} else {
760		/* Save anonymous' password. */
761		guestpw = strdup(passwd);
762		if (guestpw == (char *)NULL)
763			fatal("Out of memory");
764	}
765	login_attempts = 0;		/* this time successful */
766	if (setegid((gid_t)pw->pw_gid) < 0) {
767		reply(550, "Can't set gid.");
768		return;
769	}
770	(void) initgroups(pw->pw_name, pw->pw_gid);
771
772	/* open wtmp before chroot */
773	logwtmp(ttyline, pw->pw_name, remotehost);
774
775	/* open utmp before chroot */
776	if (doutmp) {
777		memset((void *)&utmp, 0, sizeof(utmp));
778		(void)time(&utmp.ut_time);
779		(void)strncpy(utmp.ut_name, pw->pw_name, sizeof(utmp.ut_name));
780		(void)strncpy(utmp.ut_host, remotehost, sizeof(utmp.ut_host));
781		(void)strncpy(utmp.ut_line, ttyline, sizeof(utmp.ut_line));
782		login(&utmp);
783	}
784
785	/* open stats file before chroot */
786	if (guest && (stats == 1) && (statfd < 0))
787		if ((statfd = open(_PATH_FTPDSTATFILE, O_WRONLY|O_APPEND)) < 0)
788			stats = 0;
789
790	logged_in = 1;
791
792	dochroot = checkuser(_PATH_FTPCHROOT, pw->pw_name);
793	if (guest || dochroot) {
794		if (multihome) {
795			struct stat ts;
796
797			/* Compute root directory. */
798			snprintf (rootdir, sizeof(rootdir), "%s/%s",
799				  pw->pw_dir, dhostname);
800			if (stat(rootdir, &ts) < 0) {
801				snprintf (rootdir, sizeof(rootdir), "%s/%s",
802					  pw->pw_dir, hostname);
803			}
804		} else
805			strcpy (rootdir, pw->pw_dir);
806	}
807	if (guest) {
808		/*
809		 * We MUST do a chdir() after the chroot. Otherwise
810		 * the old current directory will be accessible as "."
811		 * outside the new root!
812		 */
813		if (chroot(rootdir) < 0 || chdir("/") < 0) {
814			reply(550, "Can't set guest privileges.");
815			goto bad;
816		}
817		strcpy(pw->pw_dir, "/");
818		setenv("HOME", "/", 1);
819	} else if (dochroot) {
820		if (chroot(rootdir) < 0 || chdir("/") < 0) {
821			reply(550, "Can't change root.");
822			goto bad;
823		}
824		strcpy(pw->pw_dir, "/");
825		setenv("HOME", "/", 1);
826	} else if (chdir(pw->pw_dir) < 0) {
827		if (chdir("/") < 0) {
828			reply(530, "User %s: can't change directory to %s.",
829			    pw->pw_name, pw->pw_dir);
830			goto bad;
831		} else
832			lreply(230, "No directory! Logging in with home=/");
833	}
834	if (seteuid((uid_t)pw->pw_uid) < 0) {
835		reply(550, "Can't set uid.");
836		goto bad;
837	}
838	sigfillset(&allsigs);
839	sigprocmask(SIG_UNBLOCK,&allsigs,NULL);
840
841	/*
842	 * Set home directory so that use of ~ (tilde) works correctly.
843	 */
844	if (getcwd(homedir, MAXPATHLEN) != NULL)
845		setenv("HOME", homedir, 1);
846
847	/*
848	 * Display a login message, if it exists.
849	 * N.B. reply(230,) must follow the message.
850	 */
851	if ((fd = fopen(_PATH_FTPLOGINMESG, "r")) != NULL) {
852		char *cp, line[LINE_MAX];
853
854		while (fgets(line, sizeof(line), fd) != NULL) {
855			if ((cp = strchr(line, '\n')) != NULL)
856				*cp = '\0';
857			lreply(230, "%s", line);
858		}
859		(void) fflush(stdout);
860		(void) fclose(fd);
861	}
862	if (guest) {
863		if (ident != NULL)
864			free(ident);
865		ident = strdup(passwd);
866		if (ident == (char *)NULL)
867			fatal("Ran out of memory.");
868		reply(230, "Guest login ok, access restrictions apply.");
869#ifdef HASSETPROCTITLE
870		snprintf(proctitle, sizeof(proctitle),
871		    "%s: anonymous/%.*s", remotehost,
872		    sizeof(proctitle) - sizeof(remotehost) -
873		    sizeof(": anonymous/"), passwd);
874		setproctitle(proctitle);
875#endif /* HASSETPROCTITLE */
876		if (logging)
877			syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s, %s",
878			    remotehost, passwd);
879	} else {
880		reply(230, "User %s logged in.", pw->pw_name);
881#ifdef HASSETPROCTITLE
882		snprintf(proctitle, sizeof(proctitle),
883		    "%s: %s", remotehost, pw->pw_name);
884		setproctitle(proctitle);
885#endif /* HASSETPROCTITLE */
886		if (logging)
887			syslog(LOG_INFO, "FTP LOGIN FROM %s as %s",
888			    remotehost, pw->pw_name);
889	}
890	(void) umask(defumask);
891	return;
892bad:
893	/* Forget all about it... */
894	end_login();
895}
896
897void
898retrieve(cmd, name)
899	char *cmd, *name;
900{
901	FILE *fin, *dout;
902	struct stat st;
903	int (*closefunc) __P((FILE *));
904	time_t start;
905
906	if (cmd == 0) {
907		fin = fopen(name, "r"), closefunc = fclose;
908		st.st_size = 0;
909	} else {
910		char line[BUFSIZ];
911
912		(void) snprintf(line, sizeof(line), cmd, name);
913		name = line;
914		fin = ftpd_popen(line, "r"), closefunc = ftpd_pclose;
915		st.st_size = -1;
916		st.st_blksize = BUFSIZ;
917	}
918	if (fin == NULL) {
919		if (errno != 0) {
920			perror_reply(550, name);
921			if (cmd == 0) {
922				LOGCMD("get", name);
923			}
924		}
925		return;
926	}
927	byte_count = -1;
928	if (cmd == 0 && (fstat(fileno(fin), &st) < 0 || !S_ISREG(st.st_mode))) {
929		reply(550, "%s: not a plain file.", name);
930		goto done;
931	}
932	if (restart_point) {
933		if (type == TYPE_A) {
934			off_t i, n;
935			int c;
936
937			n = restart_point;
938			i = 0;
939			while (i++ < n) {
940				if ((c=getc(fin)) == EOF) {
941					perror_reply(550, name);
942					goto done;
943				}
944				if (c == '\n')
945					i++;
946			}
947		} else if (lseek(fileno(fin), restart_point, L_SET) < 0) {
948			perror_reply(550, name);
949			goto done;
950		}
951	}
952	dout = dataconn(name, st.st_size, "w");
953	if (dout == NULL)
954		goto done;
955	time(&start);
956	send_data(fin, dout, st.st_blksize, st.st_size,
957		  (restart_point == 0 && cmd == 0 && S_ISREG(st.st_mode)));
958	if ((cmd == 0) && stats)
959		logxfer(name, st.st_size, start);
960	(void) fclose(dout);
961	data = -1;
962	pdata = -1;
963done:
964	if (cmd == 0)
965		LOGBYTES("get", name, byte_count);
966	(*closefunc)(fin);
967}
968
969void
970store(name, mode, unique)
971	char *name, *mode;
972	int unique;
973{
974	FILE *fout, *din;
975	int (*closefunc) __P((FILE *));
976	struct stat st;
977	int fd;
978
979	if (unique && stat(name, &st) == 0) {
980		char *nam;
981
982		fd = guniquefd(name, &nam);
983		if (fd == -1) {
984			LOGCMD(*mode == 'w' ? "put" : "append", name);
985			return;
986		}
987		name = nam;
988		if (restart_point)
989			mode = "r+";
990		fout = fdopen(fd, mode);
991	} else
992		fout = fopen(name, mode);
993
994	closefunc = fclose;
995	if (fout == NULL) {
996		perror_reply(553, name);
997		LOGCMD(*mode == 'w' ? "put" : "append", name);
998		return;
999	}
1000	byte_count = -1;
1001	if (restart_point) {
1002		if (type == TYPE_A) {
1003			off_t i, n;
1004			int c;
1005
1006			n = restart_point;
1007			i = 0;
1008			while (i++ < n) {
1009				if ((c=getc(fout)) == EOF) {
1010					perror_reply(550, name);
1011					goto done;
1012				}
1013				if (c == '\n')
1014					i++;
1015			}
1016			/*
1017			 * We must do this seek to "current" position
1018			 * because we are changing from reading to
1019			 * writing.
1020			 */
1021			if (fseek(fout, 0L, L_INCR) < 0) {
1022				perror_reply(550, name);
1023				goto done;
1024			}
1025		} else if (lseek(fileno(fout), restart_point, L_SET) < 0) {
1026			perror_reply(550, name);
1027			goto done;
1028		}
1029	}
1030	din = dataconn(name, (off_t)-1, "r");
1031	if (din == NULL)
1032		goto done;
1033	if (receive_data(din, fout) == 0) {
1034		if (unique)
1035			reply(226, "Transfer complete (unique file name:%s).",
1036			    name);
1037		else
1038			reply(226, "Transfer complete.");
1039	}
1040	(void) fclose(din);
1041	data = -1;
1042	pdata = -1;
1043done:
1044	LOGBYTES(*mode == 'w' ? "put" : "append", name, byte_count);
1045	(*closefunc)(fout);
1046}
1047
1048static FILE *
1049getdatasock(mode)
1050	char *mode;
1051{
1052	int on = 1, s, t, tries;
1053	sigset_t allsigs;
1054
1055	if (data >= 0)
1056		return (fdopen(data, mode));
1057	sigfillset(&allsigs);
1058	sigprocmask (SIG_BLOCK, &allsigs, NULL);
1059	(void) seteuid((uid_t)0);
1060	s = socket(AF_INET, SOCK_STREAM, 0);
1061	if (s < 0)
1062		goto bad;
1063	if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
1064	    (char *) &on, sizeof(on)) < 0)
1065		goto bad;
1066	/* anchor socket to avoid multi-homing problems */
1067	data_source.sin_len = sizeof(struct sockaddr_in);
1068	data_source.sin_family = AF_INET;
1069	data_source.sin_addr = ctrl_addr.sin_addr;
1070	for (tries = 1; ; tries++) {
1071		if (bind(s, (struct sockaddr *)&data_source,
1072		    sizeof(data_source)) >= 0)
1073			break;
1074		if (errno != EADDRINUSE || tries > 10)
1075			goto bad;
1076		sleep(tries);
1077	}
1078	(void) seteuid((uid_t)pw->pw_uid);
1079	sigfillset(&allsigs);
1080	sigprocmask (SIG_UNBLOCK, &allsigs, NULL);
1081
1082#ifdef IP_TOS
1083	on = IPTOS_THROUGHPUT;
1084	if (setsockopt(s, IPPROTO_IP, IP_TOS, (char *)&on, sizeof(int)) < 0)
1085		syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
1086#endif
1087#ifdef TCP_NOPUSH
1088	/*
1089	 * Turn off push flag to keep sender TCP from sending short packets
1090	 * at the boundaries of each write().  Should probably do a SO_SNDBUF
1091	 * to set the send buffer size as well, but that may not be desirable
1092	 * in heavy-load situations.
1093	 */
1094	on = 1;
1095	if (setsockopt(s, IPPROTO_TCP, TCP_NOPUSH, (char *)&on, sizeof on) < 0)
1096		syslog(LOG_WARNING, "setsockopt (TCP_NOPUSH): %m");
1097#endif
1098#ifdef SO_SNDBUF
1099	on = 65536;
1100	if (setsockopt(s, SOL_SOCKET, SO_SNDBUF, (char *)&on, sizeof on) < 0)
1101		syslog(LOG_WARNING, "setsockopt (SO_SNDBUF): %m");
1102#endif
1103
1104	return (fdopen(s, mode));
1105bad:
1106	/* Return the real value of errno (close may change it) */
1107	t = errno;
1108	(void) seteuid((uid_t)pw->pw_uid);
1109	sigfillset (&allsigs);
1110	sigprocmask (SIG_UNBLOCK, &allsigs, NULL);
1111	(void) close(s);
1112	errno = t;
1113	return (NULL);
1114}
1115
1116static FILE *
1117dataconn(name, size, mode)
1118	char *name;
1119	off_t size;
1120	char *mode;
1121{
1122	char sizebuf[32];
1123	FILE *file;
1124	int retry = 0, tos;
1125
1126	file_size = size;
1127	byte_count = 0;
1128	if (size != (off_t) -1) {
1129		(void) snprintf(sizebuf, sizeof(sizebuf), " (%qd bytes)",
1130				size);
1131	} else
1132		sizebuf[0] = '\0';
1133	if (pdata >= 0) {
1134		struct sockaddr_in from;
1135		int s, fromlen = sizeof(from);
1136
1137		signal (SIGALRM, toolong);
1138		(void) alarm ((unsigned) timeout);
1139		s = accept(pdata, (struct sockaddr *)&from, &fromlen);
1140		(void) alarm (0);
1141		if (s < 0) {
1142			reply(425, "Can't open data connection.");
1143			(void) close(pdata);
1144			pdata = -1;
1145			return (NULL);
1146		}
1147		if (ntohs(from.sin_port) < IPPORT_RESERVED) {
1148			perror_reply(425, "Can't build data connection");
1149			(void) close(pdata);
1150			(void) close(s);
1151			pdata = -1;
1152			return (NULL);
1153		}
1154		if (from.sin_addr.s_addr != his_addr.sin_addr.s_addr) {
1155			perror_reply(435, "Can't build data connection");
1156			(void) close(pdata);
1157			(void) close(s);
1158			pdata = -1;
1159			return (NULL);
1160		}
1161		(void) close(pdata);
1162		pdata = s;
1163#ifdef IP_TOS
1164		tos = IPTOS_THROUGHPUT;
1165		(void) setsockopt(s, IPPROTO_IP, IP_TOS, (char *)&tos,
1166		    sizeof(int));
1167#endif
1168		reply(150, "Opening %s mode data connection for '%s'%s.",
1169		     type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1170		return (fdopen(pdata, mode));
1171	}
1172	if (data >= 0) {
1173		reply(125, "Using existing data connection for '%s'%s.",
1174		    name, sizebuf);
1175		usedefault = 1;
1176		return (fdopen(data, mode));
1177	}
1178	if (usedefault)
1179		data_dest = his_addr;
1180	usedefault = 1;
1181	file = getdatasock(mode);
1182	if (file == NULL) {
1183		reply(425, "Can't create data socket (%s,%d): %s.",
1184		    inet_ntoa(data_source.sin_addr),
1185		    ntohs(data_source.sin_port), strerror(errno));
1186		return (NULL);
1187	}
1188	data = fileno(file);
1189
1190	/*
1191	 * attempt to connect to reserved port on client machine;
1192	 * this looks like an attack
1193	 */
1194	if (ntohs(data_dest.sin_port) < IPPORT_RESERVED) {
1195		perror_reply(425, "Can't build data connection");
1196		(void) fclose(file);
1197		data = -1;
1198		return NULL;
1199	}
1200	if (data_dest.sin_addr.s_addr != his_addr.sin_addr.s_addr) {
1201		perror_reply(435, "Can't build data connection");
1202		(void) fclose(file);
1203		data = -1;
1204		return NULL;
1205	}
1206	while (connect(data, (struct sockaddr *)&data_dest,
1207	    sizeof(data_dest)) < 0) {
1208		if (errno == EADDRINUSE && retry < swaitmax) {
1209			sleep((unsigned) swaitint);
1210			retry += swaitint;
1211			continue;
1212		}
1213		perror_reply(425, "Can't build data connection");
1214		(void) fclose(file);
1215		data = -1;
1216		return (NULL);
1217	}
1218	reply(150, "Opening %s mode data connection for '%s'%s.",
1219	     type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1220	return (file);
1221}
1222
1223/*
1224 * Tranfer the contents of "instr" to "outstr" peer using the appropriate
1225 * encapsulation of the data subject to Mode, Structure, and Type.
1226 *
1227 * NB: Form isn't handled.
1228 */
1229static void
1230send_data(instr, outstr, blksize, filesize, isreg)
1231	FILE *instr, *outstr;
1232	off_t blksize;
1233	off_t filesize;
1234	int isreg;
1235{
1236	int c, cnt, filefd, netfd;
1237	char *buf, *bp;
1238	size_t len;
1239
1240	transflag++;
1241	if (setjmp(urgcatch)) {
1242		transflag = 0;
1243		return;
1244	}
1245	switch (type) {
1246
1247	case TYPE_A:
1248		while ((c = getc(instr)) != EOF) {
1249			byte_count++;
1250			if (c == '\n') {
1251				if (ferror(outstr))
1252					goto data_err;
1253				(void) putc('\r', outstr);
1254			}
1255			(void) putc(c, outstr);
1256		}
1257		fflush(outstr);
1258		transflag = 0;
1259		if (ferror(instr))
1260			goto file_err;
1261		if (ferror(outstr))
1262			goto data_err;
1263		reply(226, "Transfer complete.");
1264		return;
1265
1266	case TYPE_I:
1267	case TYPE_L:
1268		/*
1269		 * isreg is only set if we are not doing restart and we
1270		 * are sending a regular file
1271		 */
1272		netfd = fileno(outstr);
1273		filefd = fileno(instr);
1274
1275		if (isreg && filesize < (off_t)16 * 1024 * 1024) {
1276			buf = mmap(0, filesize, PROT_READ, MAP_SHARED, filefd,
1277				   (off_t)0);
1278			if (!buf) {
1279				syslog(LOG_WARNING, "mmap(%lu): %m",
1280				       (unsigned long)filesize);
1281				goto oldway;
1282			}
1283			bp = buf;
1284			len = filesize;
1285			do {
1286				cnt = write(netfd, bp, len);
1287				len -= cnt;
1288				bp += cnt;
1289				if (cnt > 0) byte_count += cnt;
1290			} while(cnt > 0 && len > 0);
1291
1292			transflag = 0;
1293			munmap(buf, (size_t)filesize);
1294			if (cnt < 0)
1295				goto data_err;
1296			reply(226, "Transfer complete.");
1297			return;
1298		}
1299
1300oldway:
1301		if ((buf = malloc((u_int)blksize)) == NULL) {
1302			transflag = 0;
1303			perror_reply(451, "Local resource failure: malloc");
1304			return;
1305		}
1306
1307		while ((cnt = read(filefd, buf, (u_int)blksize)) > 0 &&
1308		    write(netfd, buf, cnt) == cnt)
1309			byte_count += cnt;
1310		transflag = 0;
1311		(void)free(buf);
1312		if (cnt != 0) {
1313			if (cnt < 0)
1314				goto file_err;
1315			goto data_err;
1316		}
1317		reply(226, "Transfer complete.");
1318		return;
1319	default:
1320		transflag = 0;
1321		reply(550, "Unimplemented TYPE %d in send_data", type);
1322		return;
1323	}
1324
1325data_err:
1326	transflag = 0;
1327	perror_reply(426, "Data connection");
1328	return;
1329
1330file_err:
1331	transflag = 0;
1332	perror_reply(551, "Error on input file");
1333}
1334
1335/*
1336 * Transfer data from peer to "outstr" using the appropriate encapulation of
1337 * the data subject to Mode, Structure, and Type.
1338 *
1339 * N.B.: Form isn't handled.
1340 */
1341static int
1342receive_data(instr, outstr)
1343	FILE *instr, *outstr;
1344{
1345	int c;
1346	int cnt, bare_lfs = 0;
1347	char buf[BUFSIZ];
1348
1349	transflag++;
1350	if (setjmp(urgcatch)) {
1351		transflag = 0;
1352		return (-1);
1353	}
1354	switch (type) {
1355
1356	case TYPE_I:
1357	case TYPE_L:
1358		while ((cnt = read(fileno(instr), buf, sizeof(buf))) > 0) {
1359			if (write(fileno(outstr), buf, cnt) != cnt)
1360				goto file_err;
1361			byte_count += cnt;
1362		}
1363		if (cnt < 0)
1364			goto data_err;
1365		transflag = 0;
1366		return (0);
1367
1368	case TYPE_E:
1369		reply(553, "TYPE E not implemented.");
1370		transflag = 0;
1371		return (-1);
1372
1373	case TYPE_A:
1374		while ((c = getc(instr)) != EOF) {
1375			byte_count++;
1376			if (c == '\n')
1377				bare_lfs++;
1378			while (c == '\r') {
1379				if (ferror(outstr))
1380					goto data_err;
1381				if ((c = getc(instr)) != '\n') {
1382					(void) putc ('\r', outstr);
1383					if (c == '\0' || c == EOF)
1384						goto contin2;
1385				}
1386			}
1387			(void) putc(c, outstr);
1388	contin2:	;
1389		}
1390		fflush(outstr);
1391		if (ferror(instr))
1392			goto data_err;
1393		if (ferror(outstr))
1394			goto file_err;
1395		transflag = 0;
1396		if (bare_lfs) {
1397			lreply(226,
1398		"WARNING! %d bare linefeeds received in ASCII mode",
1399			    bare_lfs);
1400		(void)printf("   File may not have transferred correctly.\r\n");
1401		}
1402		return (0);
1403	default:
1404		reply(550, "Unimplemented TYPE %d in receive_data", type);
1405		transflag = 0;
1406		return (-1);
1407	}
1408
1409data_err:
1410	transflag = 0;
1411	perror_reply(426, "Data Connection");
1412	return (-1);
1413
1414file_err:
1415	transflag = 0;
1416	perror_reply(452, "Error writing file");
1417	return (-1);
1418}
1419
1420void
1421statfilecmd(filename)
1422	char *filename;
1423{
1424	FILE *fin;
1425	int c;
1426	char line[LINE_MAX];
1427
1428	(void)snprintf(line, sizeof(line), "/bin/ls -lgA %s", filename);
1429	fin = ftpd_popen(line, "r");
1430	lreply(211, "status of %s:", filename);
1431	while ((c = getc(fin)) != EOF) {
1432		if (c == '\n') {
1433			if (ferror(stdout)){
1434				perror_reply(421, "control connection");
1435				(void) ftpd_pclose(fin);
1436				dologout(1);
1437				/* NOTREACHED */
1438			}
1439			if (ferror(fin)) {
1440				perror_reply(551, filename);
1441				(void) ftpd_pclose(fin);
1442				return;
1443			}
1444			(void) putc('\r', stdout);
1445		}
1446		(void) putc(c, stdout);
1447	}
1448	(void) ftpd_pclose(fin);
1449	reply(211, "End of Status");
1450}
1451
1452void
1453statcmd()
1454{
1455	struct sockaddr_in *sin;
1456	u_char *a, *p;
1457
1458	lreply(211, "%s FTP server status:", hostname, version);
1459	printf("     %s\r\n", version);
1460	printf("     Connected to %s", remotehost);
1461	if (!isdigit(remotehost[0]))
1462		printf(" (%s)", inet_ntoa(his_addr.sin_addr));
1463	printf("\r\n");
1464	if (logged_in) {
1465		if (guest)
1466			printf("     Logged in anonymously\r\n");
1467		else
1468			printf("     Logged in as %s\r\n", pw->pw_name);
1469	} else if (askpasswd)
1470		printf("     Waiting for password\r\n");
1471	else
1472		printf("     Waiting for user name\r\n");
1473	printf("     TYPE: %s", typenames[type]);
1474	if (type == TYPE_A || type == TYPE_E)
1475		printf(", FORM: %s", formnames[form]);
1476	if (type == TYPE_L)
1477#if NBBY == 8
1478		printf(" %d", NBBY);
1479#else
1480		printf(" %d", bytesize);	/* need definition! */
1481#endif
1482	printf("; STRUcture: %s; transfer MODE: %s\r\n",
1483	    strunames[stru], modenames[mode]);
1484	if (data != -1)
1485		printf("     Data connection open\r\n");
1486	else if (pdata != -1) {
1487		printf("     in Passive mode");
1488		sin = &pasv_addr;
1489		goto printaddr;
1490	} else if (usedefault == 0) {
1491		printf("     PORT");
1492		sin = &data_dest;
1493printaddr:
1494		a = (u_char *) &sin->sin_addr;
1495		p = (u_char *) &sin->sin_port;
1496#define UC(b) (((int) b) & 0xff)
1497		printf(" (%d,%d,%d,%d,%d,%d)\r\n", UC(a[0]),
1498			UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
1499#undef UC
1500	} else
1501		printf("     No data connection\r\n");
1502	reply(211, "End of status");
1503}
1504
1505void
1506fatal(s)
1507	char *s;
1508{
1509
1510	reply(451, "Error in server: %s\n", s);
1511	reply(221, "Closing connection due to server error.");
1512	dologout(0);
1513	/* NOTREACHED */
1514}
1515
1516void
1517#if __STDC__
1518reply(int n, const char *fmt, ...)
1519#else
1520reply(n, fmt, va_alist)
1521	int n;
1522	char *fmt;
1523        va_dcl
1524#endif
1525{
1526	va_list ap;
1527#if __STDC__
1528	va_start(ap, fmt);
1529#else
1530	va_start(ap);
1531#endif
1532	(void)printf("%d ", n);
1533	(void)vprintf(fmt, ap);
1534	(void)printf("\r\n");
1535	(void)fflush(stdout);
1536	if (debug) {
1537		syslog(LOG_DEBUG, "<--- %d ", n);
1538		vsyslog(LOG_DEBUG, fmt, ap);
1539	}
1540}
1541
1542void
1543#if __STDC__
1544lreply(int n, const char *fmt, ...)
1545#else
1546lreply(n, fmt, va_alist)
1547	int n;
1548	char *fmt;
1549        va_dcl
1550#endif
1551{
1552	va_list ap;
1553#if __STDC__
1554	va_start(ap, fmt);
1555#else
1556	va_start(ap);
1557#endif
1558	(void)printf("%d- ", n);
1559	(void)vprintf(fmt, ap);
1560	(void)printf("\r\n");
1561	(void)fflush(stdout);
1562	if (debug) {
1563		syslog(LOG_DEBUG, "<--- %d- ", n);
1564		vsyslog(LOG_DEBUG, fmt, ap);
1565	}
1566}
1567
1568static void
1569ack(s)
1570	char *s;
1571{
1572
1573	reply(250, "%s command successful.", s);
1574}
1575
1576void
1577nack(s)
1578	char *s;
1579{
1580
1581	reply(502, "%s command not implemented.", s);
1582}
1583
1584/* ARGSUSED */
1585void
1586yyerror(s)
1587	char *s;
1588{
1589	char *cp;
1590
1591	if (cp = strchr(cbuf,'\n'))
1592		*cp = '\0';
1593	reply(500, "'%s': command not understood.", cbuf);
1594}
1595
1596void
1597delete(name)
1598	char *name;
1599{
1600	struct stat st;
1601
1602	LOGCMD("delete", name);
1603	if (stat(name, &st) < 0) {
1604		perror_reply(550, name);
1605		return;
1606	}
1607	if ((st.st_mode&S_IFMT) == S_IFDIR) {
1608		if (rmdir(name) < 0) {
1609			perror_reply(550, name);
1610			return;
1611		}
1612		goto done;
1613	}
1614	if (unlink(name) < 0) {
1615		perror_reply(550, name);
1616		return;
1617	}
1618done:
1619	ack("DELE");
1620}
1621
1622void
1623cwd(path)
1624	char *path;
1625{
1626	FILE *message;
1627
1628	if (chdir(path) < 0)
1629		perror_reply(550, path);
1630	else {
1631		if ((message = fopen(_PATH_CWDMESG, "r")) != NULL) {
1632			char *cp, line[LINE_MAX];
1633
1634			while (fgets(line, sizeof(line), message) != NULL) {
1635				if ((cp = strchr(line, '\n')) != NULL)
1636					*cp = '\0';
1637				lreply(250, "%s", line);
1638			}
1639			(void) fflush(stdout);
1640			(void) fclose(message);
1641		}
1642		ack("CWD");
1643	}
1644}
1645
1646void
1647makedir(name)
1648	char *name;
1649{
1650
1651	LOGCMD("mkdir", name);
1652	if (mkdir(name, 0777) < 0)
1653		perror_reply(550, name);
1654	else
1655		reply(257, "MKD command successful.");
1656}
1657
1658void
1659removedir(name)
1660	char *name;
1661{
1662
1663	LOGCMD("rmdir", name);
1664	if (rmdir(name) < 0)
1665		perror_reply(550, name);
1666	else
1667		ack("RMD");
1668}
1669
1670void
1671pwd()
1672{
1673	char path[MAXPATHLEN + 1];
1674
1675	if (getwd(path) == (char *)NULL)
1676		reply(550, "%s.", path);
1677	else
1678		reply(257, "\"%s\" is current directory.", path);
1679}
1680
1681char *
1682renamefrom(name)
1683	char *name;
1684{
1685	struct stat st;
1686
1687	if (stat(name, &st) < 0) {
1688		perror_reply(550, name);
1689		return ((char *)0);
1690	}
1691	reply(350, "File exists, ready for destination name");
1692	return (name);
1693}
1694
1695void
1696renamecmd(from, to)
1697	char *from, *to;
1698{
1699
1700	LOGCMD2("rename", from, to);
1701	if (rename(from, to) < 0)
1702		perror_reply(550, "rename");
1703	else
1704		ack("RNTO");
1705}
1706
1707static void
1708dolog(sin)
1709	struct sockaddr_in *sin;
1710{
1711	struct hostent *hp = gethostbyaddr((char *)&sin->sin_addr,
1712		sizeof(struct in_addr), AF_INET);
1713
1714	if (hp)
1715		(void) strncpy(remotehost, hp->h_name, sizeof(remotehost)-1);
1716	else
1717		(void) strncpy(remotehost, inet_ntoa(sin->sin_addr),
1718		    sizeof(remotehost)-1);
1719	remotehost[sizeof(remotehost)-1] = '\0';
1720#ifdef HASSETPROCTITLE
1721	snprintf(proctitle, sizeof(proctitle), "%s: connected", remotehost);
1722	setproctitle(proctitle);
1723#endif /* HASSETPROCTITLE */
1724
1725	if (logging)
1726		syslog(LOG_INFO, "connection from %s", remotehost);
1727}
1728
1729/*
1730 * Record logout in wtmp file
1731 * and exit with supplied status.
1732 */
1733void
1734dologout(status)
1735	int status;
1736{
1737	sigset_t allsigs;
1738
1739	transflag = 0;
1740
1741	if (logged_in) {
1742		sigfillset(&allsigs);
1743		sigprocmask(SIG_BLOCK, &allsigs, NULL);
1744		(void) seteuid((uid_t)0);
1745		logwtmp(ttyline, "", "");
1746		if (doutmp)
1747			logout(utmp.ut_line);
1748#if defined(KERBEROS)
1749		if (!notickets && krbtkfile_env)
1750			unlink(krbtkfile_env);
1751#endif
1752	}
1753	/* beware of flushing buffers after a SIGPIPE */
1754	_exit(status);
1755}
1756
1757static void
1758myoob(signo)
1759	int signo;
1760{
1761	char *cp;
1762
1763	/* only process if transfer occurring */
1764	if (!transflag)
1765		return;
1766	cp = tmpline;
1767	if (getline(cp, 7, stdin) == NULL) {
1768		reply(221, "You could at least say goodbye.");
1769		dologout(0);
1770	}
1771	upper(cp);
1772	if (strcmp(cp, "ABOR\r\n") == 0) {
1773		tmpline[0] = '\0';
1774		reply(426, "Transfer aborted. Data connection closed.");
1775		reply(226, "Abort successful");
1776		longjmp(urgcatch, 1);
1777	}
1778	if (strcmp(cp, "STAT\r\n") == 0) {
1779		if (file_size != (off_t) -1)
1780			reply(213, "Status: %qd of %qd bytes transferred",
1781			    byte_count, file_size);
1782		else
1783			reply(213, "Status: %qd bytes transferred", byte_count);
1784	}
1785}
1786
1787/*
1788 * Note: a response of 425 is not mentioned as a possible response to
1789 *	the PASV command in RFC959. However, it has been blessed as
1790 *	a legitimate response by Jon Postel in a telephone conversation
1791 *	with Rick Adams on 25 Jan 89.
1792 */
1793void
1794passive()
1795{
1796	int len, on;
1797	u_short port;
1798	char *p, *a;
1799
1800	if (pw == NULL) {
1801		reply(530, "Please login with USER and PASS");
1802		return;
1803	}
1804	if (pdata >= 0)
1805		close(pdata);
1806	pdata = socket(AF_INET, SOCK_STREAM, 0);
1807	if (pdata < 0) {
1808		perror_reply(425, "Can't open passive connection");
1809		return;
1810	}
1811
1812#ifdef IP_PORTRANGE
1813	on = high_data_ports ? IP_PORTRANGE_HIGH : IP_PORTRANGE_DEFAULT;
1814	if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
1815		       (char *)&on, sizeof(on)) < 0)
1816		goto pasv_error;
1817#endif
1818
1819	pasv_addr = ctrl_addr;
1820	pasv_addr.sin_port = 0;
1821	if (bind(pdata, (struct sockaddr *)&pasv_addr,
1822		 sizeof(pasv_addr)) < 0)
1823		goto pasv_error;
1824
1825	len = sizeof(pasv_addr);
1826	if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
1827		goto pasv_error;
1828	if (listen(pdata, 1) < 0)
1829		goto pasv_error;
1830	a = (char *) &pasv_addr.sin_addr;
1831	p = (char *) &pasv_addr.sin_port;
1832
1833#define UC(b) (((int) b) & 0xff)
1834
1835	reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
1836		UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
1837	return;
1838
1839pasv_error:
1840	(void) close(pdata);
1841	pdata = -1;
1842	perror_reply(425, "Can't open passive connection");
1843	return;
1844}
1845
1846/*
1847 * Generate unique name for file with basename "local".
1848 * The file named "local" is already known to exist.
1849 * Generates failure reply on error.
1850 */
1851static int
1852guniquefd(local, nam)
1853	char *local;
1854	char **nam;
1855{
1856	static char new[MAXPATHLEN];
1857	struct stat st;
1858	int count, len, fd;
1859	char *cp;
1860
1861	cp = strrchr(local, '/');
1862	if (cp)
1863		*cp = '\0';
1864	if (stat(cp ? local : ".", &st) < 0) {
1865		perror_reply(553, cp ? local : ".");
1866		return (-1);
1867	}
1868	if (cp)
1869		*cp = '/';
1870	(void) strncpy(new, local, sizeof(new)-1);
1871	new[sizeof(new)-1] = '\0';
1872	len = strlen(new);
1873	if (len+2+1 >= sizeof(new)-1)
1874		return (-1);
1875	cp = new + len;
1876	*cp++ = '.';
1877	for (count = 1; count < 100; count++) {
1878		(void)snprintf(cp, sizeof(new) - (cp - new), "%d", count);
1879		fd = open(new, O_RDWR|O_CREAT|O_EXCL, 0666);
1880		if (fd == -1)
1881			continue;
1882		if (nam)
1883			*nam = new;
1884		return (fd);
1885	}
1886	reply(452, "Unique file name cannot be created.");
1887	return (-1);
1888}
1889
1890/*
1891 * Format and send reply containing system error number.
1892 */
1893void
1894perror_reply(code, string)
1895	int code;
1896	char *string;
1897{
1898
1899	reply(code, "%s: %s.", string, strerror(errno));
1900}
1901
1902static char *onefile[] = {
1903	"",
1904	0
1905};
1906
1907void
1908send_file_list(whichf)
1909	char *whichf;
1910{
1911	struct stat st;
1912	DIR *dirp = NULL;
1913	struct dirent *dir;
1914	FILE *dout = NULL;
1915	char **dirlist, *dirname;
1916	int simple = 0;
1917	int freeglob = 0;
1918	glob_t gl;
1919
1920	if (strpbrk(whichf, "~{[*?") != NULL) {
1921		int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_QUOTE|GLOB_TILDE;
1922
1923		memset(&gl, 0, sizeof(gl));
1924		freeglob = 1;
1925		if (glob(whichf, flags, 0, &gl)) {
1926			reply(550, "not found");
1927			goto out;
1928		} else if (gl.gl_pathc == 0) {
1929			errno = ENOENT;
1930			perror_reply(550, whichf);
1931			goto out;
1932		}
1933		dirlist = gl.gl_pathv;
1934	} else {
1935		onefile[0] = whichf;
1936		dirlist = onefile;
1937		simple = 1;
1938	}
1939
1940	if (setjmp(urgcatch)) {
1941		transflag = 0;
1942		goto out;
1943	}
1944	while (dirname = *dirlist++) {
1945		if (stat(dirname, &st) < 0) {
1946			/*
1947			 * If user typed "ls -l", etc, and the client
1948			 * used NLST, do what the user meant.
1949			 */
1950			if (dirname[0] == '-' && *dirlist == NULL &&
1951			    transflag == 0) {
1952				retrieve("/bin/ls %s", dirname);
1953				goto out;
1954			}
1955			perror_reply(550, whichf);
1956			if (dout != NULL) {
1957				(void) fclose(dout);
1958				transflag = 0;
1959				data = -1;
1960				pdata = -1;
1961			}
1962			goto out;
1963		}
1964
1965		if (S_ISREG(st.st_mode)) {
1966			if (dout == NULL) {
1967				dout = dataconn("file list", (off_t)-1, "w");
1968				if (dout == NULL)
1969					goto out;
1970				transflag++;
1971			}
1972			fprintf(dout, "%s%s\n", dirname,
1973				type == TYPE_A ? "\r" : "");
1974			byte_count += strlen(dirname) + 1;
1975			continue;
1976		} else if (!S_ISDIR(st.st_mode))
1977			continue;
1978
1979		if ((dirp = opendir(dirname)) == NULL)
1980			continue;
1981
1982		while ((dir = readdir(dirp)) != NULL) {
1983			char nbuf[MAXPATHLEN];
1984
1985			if (dir->d_name[0] == '.' && dir->d_namlen == 1)
1986				continue;
1987			if (dir->d_name[0] == '.' && dir->d_name[1] == '.' &&
1988			    dir->d_namlen == 2)
1989				continue;
1990
1991			snprintf(nbuf, sizeof(nbuf), "%s/%s", dirname,
1992				 dir->d_name);
1993
1994			/*
1995			 * We have to do a stat to insure it's
1996			 * not a directory or special file.
1997			 */
1998			if (simple || (stat(nbuf, &st) == 0 &&
1999			    S_ISREG(st.st_mode))) {
2000				if (dout == NULL) {
2001					dout = dataconn("file list", (off_t)-1,
2002						"w");
2003					if (dout == NULL)
2004						goto out;
2005					transflag++;
2006				}
2007				if (nbuf[0] == '.' && nbuf[1] == '/')
2008					fprintf(dout, "%s%s\n", &nbuf[2],
2009						type == TYPE_A ? "\r" : "");
2010				else
2011					fprintf(dout, "%s%s\n", nbuf,
2012						type == TYPE_A ? "\r" : "");
2013				byte_count += strlen(nbuf) + 1;
2014			}
2015		}
2016		(void) closedir(dirp);
2017	}
2018
2019	if (dout == NULL)
2020		reply(550, "No files found.");
2021	else if (ferror(dout) != 0)
2022		perror_reply(550, "Data connection");
2023	else
2024		reply(226, "Transfer complete.");
2025
2026	transflag = 0;
2027	if (dout != NULL)
2028		(void) fclose(dout);
2029	data = -1;
2030	pdata = -1;
2031out:
2032	if (freeglob) {
2033		freeglob = 0;
2034		globfree(&gl);
2035	}
2036}
2037
2038static void
2039reapchild(signo)
2040	int signo;
2041{
2042	while (wait3(NULL, WNOHANG, NULL) > 0);
2043}
2044
2045void
2046logxfer(name, size, start)
2047	char *name;
2048	off_t size;
2049	time_t start;
2050{
2051	char buf[2048];
2052	char path[MAXPATHLEN];
2053	char vremotehost[MAXHOSTNAMELEN*4], vpath[MAXPATHLEN*4];
2054	char *vname, *vpw;
2055	time_t now;
2056
2057	if ((statfd >= 0) && (getcwd(path, sizeof(path)) != NULL)) {
2058		time(&now);
2059
2060		vname = (char *)malloc(strlen(name)*4+1);
2061		if (vname == NULL)
2062			return;
2063		vpw = (char *)malloc(strlen((guest) ? guestpw : pw->pw_name)*4+1);
2064		if (vpw == NULL) {
2065			free(vname);
2066			return;
2067		}
2068
2069		strvis(vremotehost, remotehost, VIS_SAFE|VIS_NOSLASH);
2070		strvis(vpath, path, VIS_SAFE|VIS_NOSLASH);
2071		strvis(vname, name, VIS_SAFE|VIS_NOSLASH);
2072		strvis(vpw, (guest) ? guestpw : pw->pw_name, VIS_SAFE|VIS_NOSLASH);
2073
2074		snprintf(buf, sizeof(buf),
2075			 "%.24s %d %s %qd %s/%s %c %s %c %c %s ftp %d %s %s\n",
2076			 ctime(&now), now - start + (now == start),
2077			 vremotehost, size, vpath, vname,
2078			 ((type == TYPE_A) ? 'a' : 'b'), "*" /* none yet */,
2079			 'o', ((guest) ? 'a' : 'r'),
2080			 vpw, 0 /* none yet */,
2081			 ((guest) ? "*" : pw->pw_name), dhostname);
2082		write(statfd, buf, strlen(buf));
2083		free(vname);
2084		free(vpw);
2085	}
2086}
2087