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