ftpd.c revision 1.26
1/*	$OpenBSD: ftpd.c,v 1.26 1996/12/07 09:00:22 bitblt 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.1/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 char	*gunique __P((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)) != EOF) {
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
684	(void) seteuid((uid_t)0);
685	if (logged_in) {
686		logwtmp(ttyline, "", "");
687		if (doutmp)
688			logout(utmp.ut_line);
689	}
690	pw = NULL;
691	logged_in = 0;
692	guest = 0;
693	dochroot = 0;
694}
695
696void
697pass(passwd)
698	char *passwd;
699{
700	int rval;
701	FILE *fd;
702	static char homedir[MAXPATHLEN];
703	char rootdir[MAXPATHLEN];
704
705	if (logged_in || askpasswd == 0) {
706		reply(503, "Login with USER first.");
707		return;
708	}
709	askpasswd = 0;
710	if (!guest) {		/* "ftp" is only account allowed no password */
711		if (pw == NULL) {
712			rval = 1;	/* failure below */
713			goto skip;
714		}
715#if defined(KERBEROS)
716		rval = klogin(pw, "", hostname, passwd);
717		if (rval == 0)
718			goto skip;
719#endif
720#ifdef SKEY
721		if (skey_haskey(pw->pw_name) == 0 &&
722		   (skey_passcheck(pw->pw_name, passwd) != -1)) {
723			rval = 0;
724			goto skip;
725		}
726#endif
727		/* the strcmp does not catch null passwords! */
728		if (pw == NULL || *pw->pw_passwd == '\0' ||
729		    strcmp(crypt(passwd, (pw ? pw->pw_passwd : "xx")), pw->pw_passwd)) {
730			rval = 1;	 /* failure */
731			goto skip;
732		}
733		rval = 0;
734
735skip:
736		/*
737		 * If rval == 1, the user failed the authentication check
738		 * above.  If rval == 0, either Kerberos or local authentication
739		 * succeeded.
740		 */
741		if (rval) {
742			reply(530, "Login incorrect.");
743			if (logging)
744				syslog(LOG_NOTICE,
745				    "FTP LOGIN FAILED FROM %s, %s",
746				    remotehost, curname);
747			pw = NULL;
748			if (login_attempts++ >= 5) {
749				syslog(LOG_NOTICE,
750				    "repeated login failures from %s",
751				    remotehost);
752				exit(0);
753			}
754			return;
755		}
756	} else {
757		/* Save anonymous' password. */
758		guestpw = strdup(passwd);
759		if (guestpw == (char *)NULL)
760			fatal("Out of memory");
761	}
762	login_attempts = 0;		/* this time successful */
763	if (setegid((gid_t)pw->pw_gid) < 0) {
764		reply(550, "Can't set gid.");
765		return;
766	}
767	(void) initgroups(pw->pw_name, pw->pw_gid);
768
769	/* open wtmp before chroot */
770	logwtmp(ttyline, pw->pw_name, remotehost);
771
772	/* open utmp before chroot */
773	if (doutmp) {
774		memset((void *)&utmp, 0, sizeof(utmp));
775		(void)time(&utmp.ut_time);
776		(void)strncpy(utmp.ut_name, pw->pw_name, sizeof(utmp.ut_name));
777		(void)strncpy(utmp.ut_host, remotehost, sizeof(utmp.ut_host));
778		(void)strncpy(utmp.ut_line, ttyline, sizeof(utmp.ut_line));
779		login(&utmp);
780	}
781
782	/* open stats file before chroot */
783	if (guest && (stats == 1) && (statfd < 0))
784		if ((statfd = open(_PATH_FTPDSTATFILE, O_WRONLY|O_APPEND)) < 0)
785			stats = 0;
786
787	logged_in = 1;
788
789	dochroot = checkuser(_PATH_FTPCHROOT, pw->pw_name);
790	if (guest || dochroot) {
791		if (multihome) {
792			struct stat ts;
793
794			/* Compute root directory. */
795			snprintf (rootdir, sizeof(rootdir), "%s/%s",
796				  pw->pw_dir, dhostname);
797			if (stat(rootdir, &ts) < 0) {
798				snprintf (rootdir, sizeof(rootdir), "%s/%s",
799					  pw->pw_dir, hostname);
800			}
801		} else
802			strcpy (rootdir, pw->pw_dir);
803	}
804	if (guest) {
805		/*
806		 * We MUST do a chdir() after the chroot. Otherwise
807		 * the old current directory will be accessible as "."
808		 * outside the new root!
809		 */
810		if (chroot(rootdir) < 0 || chdir("/") < 0) {
811			reply(550, "Can't set guest privileges.");
812			goto bad;
813		}
814		strcpy(pw->pw_dir, "/");
815		setenv("HOME", "/", 1);
816	} else if (dochroot) {
817		if (chroot(rootdir) < 0 || chdir("/") < 0) {
818			reply(550, "Can't change root.");
819			goto bad;
820		}
821		strcpy(pw->pw_dir, "/");
822		setenv("HOME", "/", 1);
823	} else if (chdir(pw->pw_dir) < 0) {
824		if (chdir("/") < 0) {
825			reply(530, "User %s: can't change directory to %s.",
826			    pw->pw_name, pw->pw_dir);
827			goto bad;
828		} else
829			lreply(230, "No directory! Logging in with home=/");
830	}
831	if (seteuid((uid_t)pw->pw_uid) < 0) {
832		reply(550, "Can't set uid.");
833		goto bad;
834	}
835
836	/*
837	 * Set home directory so that use of ~ (tilde) works correctly.
838	 */
839	if (getcwd(homedir, MAXPATHLEN) != NULL)
840		setenv("HOME", homedir, 1);
841
842	/*
843	 * Display a login message, if it exists.
844	 * N.B. reply(230,) must follow the message.
845	 */
846	if ((fd = fopen(_PATH_FTPLOGINMESG, "r")) != NULL) {
847		char *cp, line[LINE_MAX];
848
849		while (fgets(line, sizeof(line), fd) != NULL) {
850			if ((cp = strchr(line, '\n')) != NULL)
851				*cp = '\0';
852			lreply(230, "%s", line);
853		}
854		(void) fflush(stdout);
855		(void) fclose(fd);
856	}
857	if (guest) {
858		if (ident != NULL)
859			free(ident);
860		ident = strdup(passwd);
861		if (ident == (char *)NULL)
862			fatal("Ran out of memory.");
863		reply(230, "Guest login ok, access restrictions apply.");
864#ifdef HASSETPROCTITLE
865		snprintf(proctitle, sizeof(proctitle),
866		    "%s: anonymous/%.*s", remotehost,
867		    sizeof(proctitle) - sizeof(remotehost) -
868		    sizeof(": anonymous/"), passwd);
869		setproctitle(proctitle);
870#endif /* HASSETPROCTITLE */
871		if (logging)
872			syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s, %s",
873			    remotehost, passwd);
874	} else {
875		reply(230, "User %s logged in.", pw->pw_name);
876#ifdef HASSETPROCTITLE
877		snprintf(proctitle, sizeof(proctitle),
878		    "%s: %s", remotehost, pw->pw_name);
879		setproctitle(proctitle);
880#endif /* HASSETPROCTITLE */
881		if (logging)
882			syslog(LOG_INFO, "FTP LOGIN FROM %s as %s",
883			    remotehost, pw->pw_name);
884	}
885	(void) umask(defumask);
886	return;
887bad:
888	/* Forget all about it... */
889	end_login();
890}
891
892void
893retrieve(cmd, name)
894	char *cmd, *name;
895{
896	FILE *fin, *dout;
897	struct stat st;
898	int (*closefunc) __P((FILE *));
899	time_t start;
900
901	if (cmd == 0) {
902		fin = fopen(name, "r"), closefunc = fclose;
903		st.st_size = 0;
904	} else {
905		char line[BUFSIZ];
906
907		(void) snprintf(line, sizeof(line), cmd, name);
908		name = line;
909		fin = ftpd_popen(line, "r"), closefunc = ftpd_pclose;
910		st.st_size = -1;
911		st.st_blksize = BUFSIZ;
912	}
913	if (fin == NULL) {
914		if (errno != 0) {
915			perror_reply(550, name);
916			if (cmd == 0) {
917				LOGCMD("get", name);
918			}
919		}
920		return;
921	}
922	byte_count = -1;
923	if (cmd == 0 && (fstat(fileno(fin), &st) < 0 || !S_ISREG(st.st_mode))) {
924		reply(550, "%s: not a plain file.", name);
925		goto done;
926	}
927	if (restart_point) {
928		if (type == TYPE_A) {
929			off_t i, n;
930			int c;
931
932			n = restart_point;
933			i = 0;
934			while (i++ < n) {
935				if ((c=getc(fin)) == EOF) {
936					perror_reply(550, name);
937					goto done;
938				}
939				if (c == '\n')
940					i++;
941			}
942		} else if (lseek(fileno(fin), restart_point, L_SET) < 0) {
943			perror_reply(550, name);
944			goto done;
945		}
946	}
947	dout = dataconn(name, st.st_size, "w");
948	if (dout == NULL)
949		goto done;
950	time(&start);
951	send_data(fin, dout, st.st_blksize, st.st_size,
952		  (restart_point == 0 && cmd == 0 && S_ISREG(st.st_mode)));
953	if ((cmd == 0) && stats)
954		logxfer(name, st.st_size, start);
955	(void) fclose(dout);
956	data = -1;
957	pdata = -1;
958done:
959	if (cmd == 0)
960		LOGBYTES("get", name, byte_count);
961	(*closefunc)(fin);
962}
963
964void
965store(name, mode, unique)
966	char *name, *mode;
967	int unique;
968{
969	FILE *fout, *din;
970	struct stat st;
971	int (*closefunc) __P((FILE *));
972
973	if (unique && stat(name, &st) == 0 &&
974	    (name = gunique(name)) == NULL) {
975		LOGCMD(*mode == 'w' ? "put" : "append", name);
976		return;
977	}
978
979	if (restart_point)
980		mode = "r+";
981	fout = fopen(name, mode);
982	closefunc = fclose;
983	if (fout == NULL) {
984		perror_reply(553, name);
985		LOGCMD(*mode == 'w' ? "put" : "append", name);
986		return;
987	}
988	byte_count = -1;
989	if (restart_point) {
990		if (type == TYPE_A) {
991			off_t i, n;
992			int c;
993
994			n = restart_point;
995			i = 0;
996			while (i++ < n) {
997				if ((c=getc(fout)) == EOF) {
998					perror_reply(550, name);
999					goto done;
1000				}
1001				if (c == '\n')
1002					i++;
1003			}
1004			/*
1005			 * We must do this seek to "current" position
1006			 * because we are changing from reading to
1007			 * writing.
1008			 */
1009			if (fseek(fout, 0L, L_INCR) < 0) {
1010				perror_reply(550, name);
1011				goto done;
1012			}
1013		} else if (lseek(fileno(fout), restart_point, L_SET) < 0) {
1014			perror_reply(550, name);
1015			goto done;
1016		}
1017	}
1018	din = dataconn(name, (off_t)-1, "r");
1019	if (din == NULL)
1020		goto done;
1021	if (receive_data(din, fout) == 0) {
1022		if (unique)
1023			reply(226, "Transfer complete (unique file name:%s).",
1024			    name);
1025		else
1026			reply(226, "Transfer complete.");
1027	}
1028	(void) fclose(din);
1029	data = -1;
1030	pdata = -1;
1031done:
1032	LOGBYTES(*mode == 'w' ? "put" : "append", name, byte_count);
1033	(*closefunc)(fout);
1034}
1035
1036static FILE *
1037getdatasock(mode)
1038	char *mode;
1039{
1040	int on = 1, s, t, tries;
1041
1042	if (data >= 0)
1043		return (fdopen(data, mode));
1044	(void) seteuid((uid_t)0);
1045	s = socket(AF_INET, SOCK_STREAM, 0);
1046	if (s < 0)
1047		goto bad;
1048	if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
1049	    (char *) &on, sizeof(on)) < 0)
1050		goto bad;
1051	/* anchor socket to avoid multi-homing problems */
1052	data_source.sin_len = sizeof(struct sockaddr_in);
1053	data_source.sin_family = AF_INET;
1054	data_source.sin_addr = ctrl_addr.sin_addr;
1055	for (tries = 1; ; tries++) {
1056		if (bind(s, (struct sockaddr *)&data_source,
1057		    sizeof(data_source)) >= 0)
1058			break;
1059		if (errno != EADDRINUSE || tries > 10)
1060			goto bad;
1061		sleep(tries);
1062	}
1063	(void) seteuid((uid_t)pw->pw_uid);
1064#ifdef IP_TOS
1065	on = IPTOS_THROUGHPUT;
1066	if (setsockopt(s, IPPROTO_IP, IP_TOS, (char *)&on, sizeof(int)) < 0)
1067		syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
1068#endif
1069#ifdef TCP_NOPUSH
1070	/*
1071	 * Turn off push flag to keep sender TCP from sending short packets
1072	 * at the boundaries of each write().  Should probably do a SO_SNDBUF
1073	 * to set the send buffer size as well, but that may not be desirable
1074	 * in heavy-load situations.
1075	 */
1076	on = 1;
1077	if (setsockopt(s, IPPROTO_TCP, TCP_NOPUSH, (char *)&on, sizeof on) < 0)
1078		syslog(LOG_WARNING, "setsockopt (TCP_NOPUSH): %m");
1079#endif
1080#ifdef SO_SNDBUF
1081	on = 65536;
1082	if (setsockopt(s, SOL_SOCKET, SO_SNDBUF, (char *)&on, sizeof on) < 0)
1083		syslog(LOG_WARNING, "setsockopt (SO_SNDBUF): %m");
1084#endif
1085
1086	return (fdopen(s, mode));
1087bad:
1088	/* Return the real value of errno (close may change it) */
1089	t = errno;
1090	(void) seteuid((uid_t)pw->pw_uid);
1091	(void) close(s);
1092	errno = t;
1093	return (NULL);
1094}
1095
1096static FILE *
1097dataconn(name, size, mode)
1098	char *name;
1099	off_t size;
1100	char *mode;
1101{
1102	char sizebuf[32];
1103	FILE *file;
1104	int retry = 0, tos;
1105
1106	file_size = size;
1107	byte_count = 0;
1108	if (size != (off_t) -1) {
1109		(void) snprintf(sizebuf, sizeof(sizebuf), " (%qd bytes)",
1110				size);
1111	} else
1112		sizebuf[0] = '\0';
1113	if (pdata >= 0) {
1114		struct sockaddr_in from;
1115		int s, fromlen = sizeof(from);
1116
1117		signal (SIGALRM, toolong);
1118		(void) alarm ((unsigned) timeout);
1119		s = accept(pdata, (struct sockaddr *)&from, &fromlen);
1120		(void) alarm (0);
1121		if (s < 0) {
1122			reply(425, "Can't open data connection.");
1123			(void) close(pdata);
1124			pdata = -1;
1125			return (NULL);
1126		}
1127		if (ntohs(from.sin_port) < IPPORT_RESERVED) {
1128			perror_reply(425, "Can't build data connection");
1129			(void) close(pdata);
1130			(void) close(s);
1131			pdata = -1;
1132			return (NULL);
1133		}
1134		if (from.sin_addr.s_addr != his_addr.sin_addr.s_addr) {
1135			perror_reply(435, "Can't build data connection");
1136			(void) close(pdata);
1137			(void) close(s);
1138			pdata = -1;
1139			return (NULL);
1140		}
1141		(void) close(pdata);
1142		pdata = s;
1143#ifdef IP_TOS
1144		tos = IPTOS_THROUGHPUT;
1145		(void) setsockopt(s, IPPROTO_IP, IP_TOS, (char *)&tos,
1146		    sizeof(int));
1147#endif
1148		reply(150, "Opening %s mode data connection for '%s'%s.",
1149		     type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1150		return (fdopen(pdata, mode));
1151	}
1152	if (data >= 0) {
1153		reply(125, "Using existing data connection for '%s'%s.",
1154		    name, sizebuf);
1155		usedefault = 1;
1156		return (fdopen(data, mode));
1157	}
1158	if (usedefault)
1159		data_dest = his_addr;
1160	usedefault = 1;
1161	file = getdatasock(mode);
1162	if (file == NULL) {
1163		reply(425, "Can't create data socket (%s,%d): %s.",
1164		    inet_ntoa(data_source.sin_addr),
1165		    ntohs(data_source.sin_port), strerror(errno));
1166		return (NULL);
1167	}
1168	data = fileno(file);
1169
1170	/*
1171	 * attempt to connect to reserved port on client machine;
1172	 * this looks like an attack
1173	 */
1174	if (ntohs(data_dest.sin_port) < IPPORT_RESERVED) {
1175		perror_reply(425, "Can't build data connection");
1176		(void) fclose(file);
1177		data = -1;
1178		return NULL;
1179	}
1180	if (data_dest.sin_addr.s_addr != his_addr.sin_addr.s_addr) {
1181		perror_reply(435, "Can't build data connection");
1182		(void) fclose(file);
1183		data = -1;
1184		return NULL;
1185	}
1186	while (connect(data, (struct sockaddr *)&data_dest,
1187	    sizeof(data_dest)) < 0) {
1188		if (errno == EADDRINUSE && retry < swaitmax) {
1189			sleep((unsigned) swaitint);
1190			retry += swaitint;
1191			continue;
1192		}
1193		perror_reply(425, "Can't build data connection");
1194		(void) fclose(file);
1195		data = -1;
1196		return (NULL);
1197	}
1198	reply(150, "Opening %s mode data connection for '%s'%s.",
1199	     type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1200	return (file);
1201}
1202
1203/*
1204 * Tranfer the contents of "instr" to "outstr" peer using the appropriate
1205 * encapsulation of the data subject to Mode, Structure, and Type.
1206 *
1207 * NB: Form isn't handled.
1208 */
1209static void
1210send_data(instr, outstr, blksize, filesize, isreg)
1211	FILE *instr, *outstr;
1212	off_t blksize;
1213	off_t filesize;
1214	int isreg;
1215{
1216	int c, cnt, filefd, netfd;
1217	char *buf, *bp;
1218	size_t len;
1219
1220	transflag++;
1221	if (setjmp(urgcatch)) {
1222		transflag = 0;
1223		return;
1224	}
1225	switch (type) {
1226
1227	case TYPE_A:
1228		while ((c = getc(instr)) != EOF) {
1229			byte_count++;
1230			if (c == '\n') {
1231				if (ferror(outstr))
1232					goto data_err;
1233				(void) putc('\r', outstr);
1234			}
1235			(void) putc(c, outstr);
1236		}
1237		fflush(outstr);
1238		transflag = 0;
1239		if (ferror(instr))
1240			goto file_err;
1241		if (ferror(outstr))
1242			goto data_err;
1243		reply(226, "Transfer complete.");
1244		return;
1245
1246	case TYPE_I:
1247	case TYPE_L:
1248		/*
1249		 * isreg is only set if we are not doing restart and we
1250		 * are sending a regular file
1251		 */
1252		netfd = fileno(outstr);
1253		filefd = fileno(instr);
1254
1255		if (isreg && filesize < (off_t)16 * 1024 * 1024) {
1256			buf = mmap(0, filesize, PROT_READ, MAP_SHARED, filefd,
1257				   (off_t)0);
1258			if (!buf) {
1259				syslog(LOG_WARNING, "mmap(%lu): %m",
1260				       (unsigned long)filesize);
1261				goto oldway;
1262			}
1263			bp = buf;
1264			len = filesize;
1265			do {
1266				cnt = write(netfd, bp, len);
1267				len -= cnt;
1268				bp += cnt;
1269				if (cnt > 0) byte_count += cnt;
1270			} while(cnt > 0 && len > 0);
1271
1272			transflag = 0;
1273			munmap(buf, (size_t)filesize);
1274			if (cnt < 0)
1275				goto data_err;
1276			reply(226, "Transfer complete.");
1277			return;
1278		}
1279
1280oldway:
1281		if ((buf = malloc((u_int)blksize)) == NULL) {
1282			transflag = 0;
1283			perror_reply(451, "Local resource failure: malloc");
1284			return;
1285		}
1286
1287		while ((cnt = read(filefd, buf, (u_int)blksize)) > 0 &&
1288		    write(netfd, buf, cnt) == cnt)
1289			byte_count += cnt;
1290		transflag = 0;
1291		(void)free(buf);
1292		if (cnt != 0) {
1293			if (cnt < 0)
1294				goto file_err;
1295			goto data_err;
1296		}
1297		reply(226, "Transfer complete.");
1298		return;
1299	default:
1300		transflag = 0;
1301		reply(550, "Unimplemented TYPE %d in send_data", type);
1302		return;
1303	}
1304
1305data_err:
1306	transflag = 0;
1307	perror_reply(426, "Data connection");
1308	return;
1309
1310file_err:
1311	transflag = 0;
1312	perror_reply(551, "Error on input file");
1313}
1314
1315/*
1316 * Transfer data from peer to "outstr" using the appropriate encapulation of
1317 * the data subject to Mode, Structure, and Type.
1318 *
1319 * N.B.: Form isn't handled.
1320 */
1321static int
1322receive_data(instr, outstr)
1323	FILE *instr, *outstr;
1324{
1325	int c;
1326	int cnt, bare_lfs = 0;
1327	char buf[BUFSIZ];
1328
1329	transflag++;
1330	if (setjmp(urgcatch)) {
1331		transflag = 0;
1332		return (-1);
1333	}
1334	switch (type) {
1335
1336	case TYPE_I:
1337	case TYPE_L:
1338		while ((cnt = read(fileno(instr), buf, sizeof(buf))) > 0) {
1339			if (write(fileno(outstr), buf, cnt) != cnt)
1340				goto file_err;
1341			byte_count += cnt;
1342		}
1343		if (cnt < 0)
1344			goto data_err;
1345		transflag = 0;
1346		return (0);
1347
1348	case TYPE_E:
1349		reply(553, "TYPE E not implemented.");
1350		transflag = 0;
1351		return (-1);
1352
1353	case TYPE_A:
1354		while ((c = getc(instr)) != EOF) {
1355			byte_count++;
1356			if (c == '\n')
1357				bare_lfs++;
1358			while (c == '\r') {
1359				if (ferror(outstr))
1360					goto data_err;
1361				if ((c = getc(instr)) != '\n') {
1362					(void) putc ('\r', outstr);
1363					if (c == '\0' || c == EOF)
1364						goto contin2;
1365				}
1366			}
1367			(void) putc(c, outstr);
1368	contin2:	;
1369		}
1370		fflush(outstr);
1371		if (ferror(instr))
1372			goto data_err;
1373		if (ferror(outstr))
1374			goto file_err;
1375		transflag = 0;
1376		if (bare_lfs) {
1377			lreply(226,
1378		"WARNING! %d bare linefeeds received in ASCII mode",
1379			    bare_lfs);
1380		(void)printf("   File may not have transferred correctly.\r\n");
1381		}
1382		return (0);
1383	default:
1384		reply(550, "Unimplemented TYPE %d in receive_data", type);
1385		transflag = 0;
1386		return (-1);
1387	}
1388
1389data_err:
1390	transflag = 0;
1391	perror_reply(426, "Data Connection");
1392	return (-1);
1393
1394file_err:
1395	transflag = 0;
1396	perror_reply(452, "Error writing file");
1397	return (-1);
1398}
1399
1400void
1401statfilecmd(filename)
1402	char *filename;
1403{
1404	FILE *fin;
1405	int c;
1406	char line[LINE_MAX];
1407
1408	(void)snprintf(line, sizeof(line), "/bin/ls -lgA %s", filename);
1409	fin = ftpd_popen(line, "r");
1410	lreply(211, "status of %s:", filename);
1411	while ((c = getc(fin)) != EOF) {
1412		if (c == '\n') {
1413			if (ferror(stdout)){
1414				perror_reply(421, "control connection");
1415				(void) ftpd_pclose(fin);
1416				dologout(1);
1417				/* NOTREACHED */
1418			}
1419			if (ferror(fin)) {
1420				perror_reply(551, filename);
1421				(void) ftpd_pclose(fin);
1422				return;
1423			}
1424			(void) putc('\r', stdout);
1425		}
1426		(void) putc(c, stdout);
1427	}
1428	(void) ftpd_pclose(fin);
1429	reply(211, "End of Status");
1430}
1431
1432void
1433statcmd()
1434{
1435	struct sockaddr_in *sin;
1436	u_char *a, *p;
1437
1438	lreply(211, "%s FTP server status:", hostname, version);
1439	printf("     %s\r\n", version);
1440	printf("     Connected to %s", remotehost);
1441	if (!isdigit(remotehost[0]))
1442		printf(" (%s)", inet_ntoa(his_addr.sin_addr));
1443	printf("\r\n");
1444	if (logged_in) {
1445		if (guest)
1446			printf("     Logged in anonymously\r\n");
1447		else
1448			printf("     Logged in as %s\r\n", pw->pw_name);
1449	} else if (askpasswd)
1450		printf("     Waiting for password\r\n");
1451	else
1452		printf("     Waiting for user name\r\n");
1453	printf("     TYPE: %s", typenames[type]);
1454	if (type == TYPE_A || type == TYPE_E)
1455		printf(", FORM: %s", formnames[form]);
1456	if (type == TYPE_L)
1457#if NBBY == 8
1458		printf(" %d", NBBY);
1459#else
1460		printf(" %d", bytesize);	/* need definition! */
1461#endif
1462	printf("; STRUcture: %s; transfer MODE: %s\r\n",
1463	    strunames[stru], modenames[mode]);
1464	if (data != -1)
1465		printf("     Data connection open\r\n");
1466	else if (pdata != -1) {
1467		printf("     in Passive mode");
1468		sin = &pasv_addr;
1469		goto printaddr;
1470	} else if (usedefault == 0) {
1471		printf("     PORT");
1472		sin = &data_dest;
1473printaddr:
1474		a = (u_char *) &sin->sin_addr;
1475		p = (u_char *) &sin->sin_port;
1476#define UC(b) (((int) b) & 0xff)
1477		printf(" (%d,%d,%d,%d,%d,%d)\r\n", UC(a[0]),
1478			UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
1479#undef UC
1480	} else
1481		printf("     No data connection\r\n");
1482	reply(211, "End of status");
1483}
1484
1485void
1486fatal(s)
1487	char *s;
1488{
1489
1490	reply(451, "Error in server: %s\n", s);
1491	reply(221, "Closing connection due to server error.");
1492	dologout(0);
1493	/* NOTREACHED */
1494}
1495
1496void
1497#if __STDC__
1498reply(int n, const char *fmt, ...)
1499#else
1500reply(n, fmt, va_alist)
1501	int n;
1502	char *fmt;
1503        va_dcl
1504#endif
1505{
1506	va_list ap;
1507#if __STDC__
1508	va_start(ap, fmt);
1509#else
1510	va_start(ap);
1511#endif
1512	(void)printf("%d ", n);
1513	(void)vprintf(fmt, ap);
1514	(void)printf("\r\n");
1515	(void)fflush(stdout);
1516	if (debug) {
1517		syslog(LOG_DEBUG, "<--- %d ", n);
1518		vsyslog(LOG_DEBUG, fmt, ap);
1519	}
1520}
1521
1522void
1523#if __STDC__
1524lreply(int n, const char *fmt, ...)
1525#else
1526lreply(n, fmt, va_alist)
1527	int n;
1528	char *fmt;
1529        va_dcl
1530#endif
1531{
1532	va_list ap;
1533#if __STDC__
1534	va_start(ap, fmt);
1535#else
1536	va_start(ap);
1537#endif
1538	(void)printf("%d- ", n);
1539	(void)vprintf(fmt, ap);
1540	(void)printf("\r\n");
1541	(void)fflush(stdout);
1542	if (debug) {
1543		syslog(LOG_DEBUG, "<--- %d- ", n);
1544		vsyslog(LOG_DEBUG, fmt, ap);
1545	}
1546}
1547
1548static void
1549ack(s)
1550	char *s;
1551{
1552
1553	reply(250, "%s command successful.", s);
1554}
1555
1556void
1557nack(s)
1558	char *s;
1559{
1560
1561	reply(502, "%s command not implemented.", s);
1562}
1563
1564/* ARGSUSED */
1565void
1566yyerror(s)
1567	char *s;
1568{
1569	char *cp;
1570
1571	if (cp = strchr(cbuf,'\n'))
1572		*cp = '\0';
1573	reply(500, "'%s': command not understood.", cbuf);
1574}
1575
1576void
1577delete(name)
1578	char *name;
1579{
1580	struct stat st;
1581
1582	LOGCMD("delete", name);
1583	if (stat(name, &st) < 0) {
1584		perror_reply(550, name);
1585		return;
1586	}
1587	if ((st.st_mode&S_IFMT) == S_IFDIR) {
1588		if (rmdir(name) < 0) {
1589			perror_reply(550, name);
1590			return;
1591		}
1592		goto done;
1593	}
1594	if (unlink(name) < 0) {
1595		perror_reply(550, name);
1596		return;
1597	}
1598done:
1599	ack("DELE");
1600}
1601
1602void
1603cwd(path)
1604	char *path;
1605{
1606
1607	if (chdir(path) < 0)
1608		perror_reply(550, path);
1609	else
1610		ack("CWD");
1611}
1612
1613void
1614makedir(name)
1615	char *name;
1616{
1617
1618	LOGCMD("mkdir", name);
1619	if (mkdir(name, 0777) < 0)
1620		perror_reply(550, name);
1621	else
1622		reply(257, "MKD command successful.");
1623}
1624
1625void
1626removedir(name)
1627	char *name;
1628{
1629
1630	LOGCMD("rmdir", name);
1631	if (rmdir(name) < 0)
1632		perror_reply(550, name);
1633	else
1634		ack("RMD");
1635}
1636
1637void
1638pwd()
1639{
1640	char path[MAXPATHLEN + 1];
1641
1642	if (getwd(path) == (char *)NULL)
1643		reply(550, "%s.", path);
1644	else
1645		reply(257, "\"%s\" is current directory.", path);
1646}
1647
1648char *
1649renamefrom(name)
1650	char *name;
1651{
1652	struct stat st;
1653
1654	if (stat(name, &st) < 0) {
1655		perror_reply(550, name);
1656		return ((char *)0);
1657	}
1658	reply(350, "File exists, ready for destination name");
1659	return (name);
1660}
1661
1662void
1663renamecmd(from, to)
1664	char *from, *to;
1665{
1666
1667	LOGCMD2("rename", from, to);
1668	if (rename(from, to) < 0)
1669		perror_reply(550, "rename");
1670	else
1671		ack("RNTO");
1672}
1673
1674static void
1675dolog(sin)
1676	struct sockaddr_in *sin;
1677{
1678	struct hostent *hp = gethostbyaddr((char *)&sin->sin_addr,
1679		sizeof(struct in_addr), AF_INET);
1680
1681	if (hp)
1682		(void) strncpy(remotehost, hp->h_name, sizeof(remotehost)-1);
1683	else
1684		(void) strncpy(remotehost, inet_ntoa(sin->sin_addr),
1685		    sizeof(remotehost)-1);
1686	remotehost[sizeof(remotehost)-1] = '\0';
1687#ifdef HASSETPROCTITLE
1688	snprintf(proctitle, sizeof(proctitle), "%s: connected", remotehost);
1689	setproctitle(proctitle);
1690#endif /* HASSETPROCTITLE */
1691
1692	if (logging)
1693		syslog(LOG_INFO, "connection from %s", remotehost);
1694}
1695
1696/*
1697 * Record logout in wtmp file
1698 * and exit with supplied status.
1699 */
1700void
1701dologout(status)
1702	int status;
1703{
1704
1705	if (logged_in) {
1706		(void) seteuid((uid_t)0);
1707		logwtmp(ttyline, "", "");
1708		if (doutmp)
1709			logout(utmp.ut_line);
1710#if defined(KERBEROS)
1711		if (!notickets && krbtkfile_env)
1712			unlink(krbtkfile_env);
1713#endif
1714	}
1715	/* beware of flushing buffers after a SIGPIPE */
1716	_exit(status);
1717}
1718
1719static void
1720myoob(signo)
1721	int signo;
1722{
1723	char *cp;
1724
1725	/* only process if transfer occurring */
1726	if (!transflag)
1727		return;
1728	cp = tmpline;
1729	if (getline(cp, 7, stdin) == NULL) {
1730		reply(221, "You could at least say goodbye.");
1731		dologout(0);
1732	}
1733	upper(cp);
1734	if (strcmp(cp, "ABOR\r\n") == 0) {
1735		tmpline[0] = '\0';
1736		reply(426, "Transfer aborted. Data connection closed.");
1737		reply(226, "Abort successful");
1738		longjmp(urgcatch, 1);
1739	}
1740	if (strcmp(cp, "STAT\r\n") == 0) {
1741		if (file_size != (off_t) -1)
1742			reply(213, "Status: %qd of %qd bytes transferred",
1743			    byte_count, file_size);
1744		else
1745			reply(213, "Status: %qd bytes transferred", byte_count);
1746	}
1747}
1748
1749/*
1750 * Note: a response of 425 is not mentioned as a possible response to
1751 *	the PASV command in RFC959. However, it has been blessed as
1752 *	a legitimate response by Jon Postel in a telephone conversation
1753 *	with Rick Adams on 25 Jan 89.
1754 */
1755void
1756passive()
1757{
1758	int len, on;
1759	u_short port;
1760	char *p, *a;
1761
1762	if (pw == NULL) {
1763		reply(530, "Please login with USER and PASS");
1764		return;
1765	}
1766	if (pdata >= 0)
1767		close(pdata);
1768	pdata = socket(AF_INET, SOCK_STREAM, 0);
1769	if (pdata < 0) {
1770		perror_reply(425, "Can't open passive connection");
1771		return;
1772	}
1773
1774#ifdef IP_PORTRANGE
1775	on = high_data_ports ? IP_PORTRANGE_HIGH : IP_PORTRANGE_DEFAULT;
1776	if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
1777		       (char *)&on, sizeof(on)) < 0)
1778		goto pasv_error;
1779#endif
1780
1781	pasv_addr = ctrl_addr;
1782	pasv_addr.sin_port = 0;
1783	if (bind(pdata, (struct sockaddr *)&pasv_addr,
1784		 sizeof(pasv_addr)) < 0)
1785		goto pasv_error;
1786
1787	len = sizeof(pasv_addr);
1788	if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
1789		goto pasv_error;
1790	if (listen(pdata, 1) < 0)
1791		goto pasv_error;
1792	a = (char *) &pasv_addr.sin_addr;
1793	p = (char *) &pasv_addr.sin_port;
1794
1795#define UC(b) (((int) b) & 0xff)
1796
1797	reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
1798		UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
1799	return;
1800
1801pasv_error:
1802	(void) close(pdata);
1803	pdata = -1;
1804	perror_reply(425, "Can't open passive connection");
1805	return;
1806}
1807
1808/*
1809 * Generate unique name for file with basename "local".
1810 * The file named "local" is already known to exist.
1811 * Generates failure reply on error.
1812 */
1813static char *
1814gunique(local)
1815	char *local;
1816{
1817	static char new[MAXPATHLEN];
1818	struct stat st;
1819	int count, len;
1820	char *cp;
1821
1822	cp = strrchr(local, '/');
1823	if (cp)
1824		*cp = '\0';
1825	if (stat(cp ? local : ".", &st) < 0) {
1826		perror_reply(553, cp ? local : ".");
1827		return ((char *) 0);
1828	}
1829	if (cp)
1830		*cp = '/';
1831	(void) strncpy(new, local, sizeof(new)-1);
1832	new[sizeof(new)-1] = '\0';
1833	len = strlen(new);
1834	if (len+2+1 >= sizeof(new)-1)
1835		return (NULL);
1836	cp = new + len;
1837	*cp++ = '.';
1838	for (count = 1; count < 100; count++) {
1839		(void)snprintf(cp, sizeof(new) - (cp - new), "%d", count);
1840		if (stat(new, &st) < 0)
1841			return (new);
1842	}
1843	reply(452, "Unique file name cannot be created.");
1844	return (NULL);
1845}
1846
1847/*
1848 * Format and send reply containing system error number.
1849 */
1850void
1851perror_reply(code, string)
1852	int code;
1853	char *string;
1854{
1855
1856	reply(code, "%s: %s.", string, strerror(errno));
1857}
1858
1859static char *onefile[] = {
1860	"",
1861	0
1862};
1863
1864void
1865send_file_list(whichf)
1866	char *whichf;
1867{
1868	struct stat st;
1869	DIR *dirp = NULL;
1870	struct dirent *dir;
1871	FILE *dout = NULL;
1872	char **dirlist, *dirname;
1873	int simple = 0;
1874	int freeglob = 0;
1875	glob_t gl;
1876
1877	if (strpbrk(whichf, "~{[*?") != NULL) {
1878		int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_QUOTE|GLOB_TILDE;
1879
1880		memset(&gl, 0, sizeof(gl));
1881		freeglob = 1;
1882		if (glob(whichf, flags, 0, &gl)) {
1883			reply(550, "not found");
1884			goto out;
1885		} else if (gl.gl_pathc == 0) {
1886			errno = ENOENT;
1887			perror_reply(550, whichf);
1888			goto out;
1889		}
1890		dirlist = gl.gl_pathv;
1891	} else {
1892		onefile[0] = whichf;
1893		dirlist = onefile;
1894		simple = 1;
1895	}
1896
1897	if (setjmp(urgcatch)) {
1898		transflag = 0;
1899		goto out;
1900	}
1901	while (dirname = *dirlist++) {
1902		if (stat(dirname, &st) < 0) {
1903			/*
1904			 * If user typed "ls -l", etc, and the client
1905			 * used NLST, do what the user meant.
1906			 */
1907			if (dirname[0] == '-' && *dirlist == NULL &&
1908			    transflag == 0) {
1909				retrieve("/bin/ls %s", dirname);
1910				goto out;
1911			}
1912			perror_reply(550, whichf);
1913			if (dout != NULL) {
1914				(void) fclose(dout);
1915				transflag = 0;
1916				data = -1;
1917				pdata = -1;
1918			}
1919			goto out;
1920		}
1921
1922		if (S_ISREG(st.st_mode)) {
1923			if (dout == NULL) {
1924				dout = dataconn("file list", (off_t)-1, "w");
1925				if (dout == NULL)
1926					goto out;
1927				transflag++;
1928			}
1929			fprintf(dout, "%s%s\n", dirname,
1930				type == TYPE_A ? "\r" : "");
1931			byte_count += strlen(dirname) + 1;
1932			continue;
1933		} else if (!S_ISDIR(st.st_mode))
1934			continue;
1935
1936		if ((dirp = opendir(dirname)) == NULL)
1937			continue;
1938
1939		while ((dir = readdir(dirp)) != NULL) {
1940			char nbuf[MAXPATHLEN];
1941
1942			if (dir->d_name[0] == '.' && dir->d_namlen == 1)
1943				continue;
1944			if (dir->d_name[0] == '.' && dir->d_name[1] == '.' &&
1945			    dir->d_namlen == 2)
1946				continue;
1947
1948			snprintf(nbuf, sizeof(nbuf), "%s/%s", dirname,
1949				 dir->d_name);
1950
1951			/*
1952			 * We have to do a stat to insure it's
1953			 * not a directory or special file.
1954			 */
1955			if (simple || (stat(nbuf, &st) == 0 &&
1956			    S_ISREG(st.st_mode))) {
1957				if (dout == NULL) {
1958					dout = dataconn("file list", (off_t)-1,
1959						"w");
1960					if (dout == NULL)
1961						goto out;
1962					transflag++;
1963				}
1964				if (nbuf[0] == '.' && nbuf[1] == '/')
1965					fprintf(dout, "%s%s\n", &nbuf[2],
1966						type == TYPE_A ? "\r" : "");
1967				else
1968					fprintf(dout, "%s%s\n", nbuf,
1969						type == TYPE_A ? "\r" : "");
1970				byte_count += strlen(nbuf) + 1;
1971			}
1972		}
1973		(void) closedir(dirp);
1974	}
1975
1976	if (dout == NULL)
1977		reply(550, "No files found.");
1978	else if (ferror(dout) != 0)
1979		perror_reply(550, "Data connection");
1980	else
1981		reply(226, "Transfer complete.");
1982
1983	transflag = 0;
1984	if (dout != NULL)
1985		(void) fclose(dout);
1986	data = -1;
1987	pdata = -1;
1988out:
1989	if (freeglob) {
1990		freeglob = 0;
1991		globfree(&gl);
1992	}
1993}
1994
1995static void
1996reapchild(signo)
1997	int signo;
1998{
1999	while (wait3(NULL, WNOHANG, NULL) > 0);
2000}
2001
2002void
2003logxfer(name, size, start)
2004	char *name;
2005	off_t size;
2006	time_t start;
2007{
2008	char buf[2048];
2009	char path[MAXPATHLEN];
2010	char vremotehost[MAXHOSTNAMELEN*4], vpath[MAXPATHLEN*4];
2011	char *vname, *vpw;
2012	time_t now;
2013
2014	if ((statfd >= 0) && (getcwd(path, sizeof(path)) != NULL)) {
2015		time(&now);
2016
2017		vname = (char *)malloc(strlen(name)*4+1);
2018		if (vname == NULL)
2019			return;
2020		vpw = (char *)malloc(strlen((guest) ? guestpw : pw->pw_name)*4+1);
2021		if (vpw == NULL) {
2022			free(vname);
2023			return;
2024		}
2025
2026		strvis(vremotehost, remotehost, VIS_SAFE|VIS_NOSLASH);
2027		strvis(vpath, path, VIS_SAFE|VIS_NOSLASH);
2028		strvis(vname, name, VIS_SAFE|VIS_NOSLASH);
2029		strvis(vpw, (guest) ? guestpw : pw->pw_name, VIS_SAFE|VIS_NOSLASH);
2030
2031		snprintf(buf, sizeof(buf),
2032			 "%.24s %d %s %qd %s/%s %c %s %c %c %s ftp %d %s %s\n",
2033			 ctime(&now), now - start + (now == start),
2034			 vremotehost, size, vpath, vname,
2035			 ((type == TYPE_A) ? 'a' : 'b'), "*" /* none yet */,
2036			 'o', ((guest) ? 'a' : 'r'),
2037			 vpw, 0 /* none yet */,
2038			 ((guest) ? "*" : pw->pw_name), dhostname);
2039		write(statfd, buf, strlen(buf));
2040		free(vname);
2041		free(vpw);
2042	}
2043}
2044