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