xref: /original-bsd/libexec/ftpd/ftpd.c (revision 7717c4d4)
1 /*
2  * Copyright (c) 1985, 1988 Regents of the University of California.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms are permitted
6  * provided that the above copyright notice and this paragraph are
7  * duplicated in all such forms and that any documentation,
8  * advertising materials, and other materials related to such
9  * distribution and use acknowledge that the software was developed
10  * by the University of California, Berkeley.  The name of the
11  * University may not be used to endorse or promote products derived
12  * from this software without specific prior written permission.
13  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
14  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
15  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
16  */
17 
18 #ifndef lint
19 char copyright[] =
20 "@(#) Copyright (c) 1985, 1988 Regents of the University of California.\n\
21  All rights reserved.\n";
22 #endif /* not lint */
23 
24 #ifndef lint
25 static char sccsid[] = "@(#)ftpd.c	5.32	(Berkeley) 02/20/90";
26 #endif /* not lint */
27 
28 /*
29  * FTP server.
30  */
31 #include <sys/param.h>
32 #include <sys/stat.h>
33 #include <sys/ioctl.h>
34 #include <sys/socket.h>
35 #include <sys/file.h>
36 #include <sys/wait.h>
37 #include <sys/dir.h>
38 
39 #include <netinet/in.h>
40 
41 #define	FTP_NAMES
42 #include <arpa/ftp.h>
43 #include <arpa/inet.h>
44 #include <arpa/telnet.h>
45 
46 #include <ctype.h>
47 #include <stdio.h>
48 #include <signal.h>
49 #include <pwd.h>
50 #include <setjmp.h>
51 #include <netdb.h>
52 #include <errno.h>
53 #include <strings.h>
54 #include <syslog.h>
55 #include <varargs.h>
56 #include "pathnames.h"
57 
58 /*
59  * File containing login names
60  * NOT to be used on this machine.
61  * Commonly used to disallow uucp.
62  */
63 extern	int errno;
64 extern	char *sys_errlist[];
65 extern	int sys_nerr;
66 extern	char *crypt();
67 extern	char version[];
68 extern	char *home;		/* pointer to home directory for glob */
69 extern	FILE *ftpd_popen(), *fopen(), *freopen();
70 extern	int  ftpd_pclose(), fclose();
71 extern	char *getline();
72 extern	char cbuf[];
73 extern	off_t restart_point;
74 
75 struct	sockaddr_in ctrl_addr;
76 struct	sockaddr_in data_source;
77 struct	sockaddr_in data_dest;
78 struct	sockaddr_in his_addr;
79 struct	sockaddr_in pasv_addr;
80 
81 int	data;
82 jmp_buf	errcatch, urgcatch;
83 int	logged_in;
84 struct	passwd *pw;
85 int	debug;
86 int	timeout = 900;    /* timeout after 15 minutes of inactivity */
87 int	maxtimeout = 7200;/* don't allow idle time to be set beyond 2 hours */
88 int	logging;
89 int	guest;
90 int	type;
91 int	form;
92 int	stru;			/* avoid C keyword */
93 int	mode;
94 int	usedefault = 1;		/* for data transfers */
95 int	pdata = -1;		/* for passive mode */
96 int	transflag;
97 off_t	file_size;
98 off_t	byte_count;
99 #if !defined(CMASK) || CMASK == 0
100 #undef CMASK
101 #define CMASK 027
102 #endif
103 int	defumask = CMASK;		/* default umask value */
104 char	tmpline[7];
105 char	hostname[MAXHOSTNAMELEN];
106 char	remotehost[MAXHOSTNAMELEN];
107 
108 /*
109  * Timeout intervals for retrying connections
110  * to hosts that don't accept PORT cmds.  This
111  * is a kludge, but given the problems with TCP...
112  */
113 #define	SWAITMAX	90	/* wait at most 90 seconds */
114 #define	SWAITINT	5	/* interval between retries */
115 
116 int	swaitmax = SWAITMAX;
117 int	swaitint = SWAITINT;
118 
119 int	lostconn();
120 int	myoob();
121 FILE	*getdatasock(), *dataconn();
122 
123 #ifdef SETPROCTITLE
124 char	**Argv = NULL;		/* pointer to argument vector */
125 char	*LastArgv = NULL;	/* end of argv */
126 char	proctitle[BUFSIZ];	/* initial part of title */
127 #endif /* SETPROCTITLE */
128 
129 main(argc, argv, envp)
130 	int argc;
131 	char *argv[];
132 	char **envp;
133 {
134 	int addrlen, on = 1;
135 	char *cp;
136 
137 	addrlen = sizeof (his_addr);
138 	if (getpeername(0, (struct sockaddr *)&his_addr, &addrlen) < 0) {
139 		syslog(LOG_ERR, "getpeername (%s): %m",argv[0]);
140 		exit(1);
141 	}
142 	addrlen = sizeof (ctrl_addr);
143 	if (getsockname(0, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) {
144 		syslog(LOG_ERR, "getsockname (%s): %m",argv[0]);
145 		exit(1);
146 	}
147 	data_source.sin_port = htons(ntohs(ctrl_addr.sin_port) - 1);
148 	debug = 0;
149 	openlog("ftpd", LOG_PID, LOG_DAEMON);
150 #ifdef SETPROCTITLE
151 	/*
152 	 *  Save start and extent of argv for setproctitle.
153 	 */
154 	Argv = argv;
155 	while (*envp)
156 		envp++;
157 	LastArgv = envp[-1] + strlen(envp[-1]);
158 #endif /* SETPROCTITLE */
159 
160 	argc--, argv++;
161 	while (argc > 0 && *argv[0] == '-') {
162 		for (cp = &argv[0][1]; *cp; cp++) switch (*cp) {
163 
164 		case 'v':
165 			debug = 1;
166 			break;
167 
168 		case 'd':
169 			debug = 1;
170 			break;
171 
172 		case 'l':
173 			logging = 1;
174 			break;
175 
176 		case 't':
177 			timeout = atoi(++cp);
178 			if (maxtimeout < timeout)
179 				maxtimeout = timeout;
180 			goto nextopt;
181 
182 		case 'T':
183 			maxtimeout = atoi(++cp);
184 			if (timeout > maxtimeout)
185 				timeout = maxtimeout;
186 			goto nextopt;
187 
188 		case 'u':
189 		    {
190 			int val = 0;
191 
192 			while (*++cp && *cp >= '0' && *cp <= '9')
193 				val = val*8 + *cp - '0';
194 			if (*cp)
195 				fprintf(stderr, "ftpd: Bad value for -u\n");
196 			else
197 				defumask = val;
198 			goto nextopt;
199 		    }
200 
201 		default:
202 			fprintf(stderr, "ftpd: Unknown flag -%c ignored.\n",
203 			     *cp);
204 			break;
205 		}
206 nextopt:
207 		argc--, argv++;
208 	}
209 	(void) freopen(_PATH_DEVNULL, "w", stderr);
210 	(void) signal(SIGPIPE, lostconn);
211 	(void) signal(SIGCHLD, SIG_IGN);
212 	if ((int)signal(SIGURG, myoob) < 0)
213 		syslog(LOG_ERR, "signal: %m");
214 
215 	/* Try to handle urgent data inline */
216 #ifdef SO_OOBINLINE
217 	if (setsockopt(0, SOL_SOCKET, SO_OOBINLINE, (char *)&on, sizeof(on)) < 0)
218 		syslog(LOG_ERR, "setsockopt: %m");
219 #endif
220 
221 #ifdef	F_SETOWN
222 	if (fcntl(fileno(stdin), F_SETOWN, getpid()) == -1)
223 		syslog(LOG_ERR, "fcntl F_SETOWN: %m");
224 #endif
225 	dolog(&his_addr);
226 	/*
227 	 * Set up default state
228 	 */
229 	data = -1;
230 	type = TYPE_A;
231 	form = FORM_N;
232 	stru = STRU_F;
233 	mode = MODE_S;
234 	tmpline[0] = '\0';
235 	(void) gethostname(hostname, sizeof (hostname));
236 	reply(220, "%s FTP server (%s) ready.", hostname, version);
237 	(void) setjmp(errcatch);
238 	for (;;)
239 		(void) yyparse();
240 	/* NOTREACHED */
241 }
242 
243 lostconn()
244 {
245 
246 	if (debug)
247 		syslog(LOG_DEBUG, "lost connection");
248 	dologout(-1);
249 }
250 
251 static char ttyline[20];
252 
253 /*
254  * Helper function for sgetpwnam().
255  */
256 char *
257 sgetsave(s)
258 	char *s;
259 {
260 	char *malloc();
261 	char *new = malloc((unsigned) strlen(s) + 1);
262 
263 	if (new == NULL) {
264 		perror_reply(421, "Local resource failure: malloc");
265 		dologout(1);
266 		/* NOTREACHED */
267 	}
268 	(void) strcpy(new, s);
269 	return (new);
270 }
271 
272 /*
273  * Save the result of a getpwnam.  Used for USER command, since
274  * the data returned must not be clobbered by any other command
275  * (e.g., globbing).
276  */
277 struct passwd *
278 sgetpwnam(name)
279 	char *name;
280 {
281 	static struct passwd save;
282 	register struct passwd *p;
283 	char *sgetsave();
284 
285 	if ((p = getpwnam(name)) == NULL)
286 		return (p);
287 	if (save.pw_name) {
288 		free(save.pw_name);
289 		free(save.pw_passwd);
290 		free(save.pw_gecos);
291 		free(save.pw_dir);
292 		free(save.pw_shell);
293 	}
294 	save = *p;
295 	save.pw_name = sgetsave(p->pw_name);
296 	save.pw_passwd = sgetsave(p->pw_passwd);
297 	save.pw_gecos = sgetsave(p->pw_gecos);
298 	save.pw_dir = sgetsave(p->pw_dir);
299 	save.pw_shell = sgetsave(p->pw_shell);
300 	return (&save);
301 }
302 
303 int login_attempts;		/* number of failed login attempts */
304 int askpasswd;			/* had user command, ask for passwd */
305 
306 /*
307  * USER command.
308  * Sets global passwd pointer pw if named account exists
309  * and is acceptable; sets askpasswd if a PASS command is
310  * expected. If logged in previously, need to reset state.
311  * If name is "ftp" or "anonymous", the name is not in /etc/ftpusers,
312  * and ftp account exists, set guest and pw, then just return.
313  * If account doesn't exist, ask for passwd anyway.
314  * Otherwise, check user requesting login privileges.
315  * Disallow anyone who does not have a standard
316  * shell as returned by getusershell().
317  * Disallow anyone mentioned in the file _PATH_FTPUSERS
318  * to allow people such as root and uucp to be avoided.
319  */
320 user(name)
321 	char *name;
322 {
323 	register char *cp;
324 	char *shell;
325 	char *getusershell();
326 
327 	if (logged_in) {
328 		if (guest) {
329 			reply(530, "Can't change user from guest login.");
330 			return;
331 		}
332 		end_login();
333 	}
334 
335 	guest = 0;
336 	if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) {
337 		if (checkuser("ftp") || checkuser("anonymous"))
338 			reply(530, "User %s access denied.", name);
339 		else if ((pw = sgetpwnam("ftp")) != NULL) {
340 			guest = 1;
341 			askpasswd = 1;
342 			reply(331, "Guest login ok, send ident as password.");
343 		} else
344 			reply(530, "User %s unknown.", name);
345 		return;
346 	}
347 	if (pw = sgetpwnam(name)) {
348 		if ((shell = pw->pw_shell) == NULL || *shell == 0)
349 			shell = _PATH_BSHELL;
350 		while ((cp = getusershell()) != NULL)
351 			if (strcmp(cp, shell) == 0)
352 				break;
353 		endusershell();
354 		if (cp == NULL || checkuser(name)) {
355 			reply(530, "User %s access denied.", name);
356 			if (logging)
357 				syslog(LOG_NOTICE,
358 				    "FTP LOGIN REFUSED FROM %s, %s",
359 				    remotehost, name);
360 			pw = (struct passwd *) NULL;
361 			return;
362 		}
363 	}
364 	reply(331, "Password required for %s.", name);
365 	askpasswd = 1;
366 	/*
367 	 * Delay before reading passwd after first failed
368 	 * attempt to slow down passwd-guessing programs.
369 	 */
370 	if (login_attempts)
371 		sleep((unsigned) login_attempts);
372 }
373 
374 /*
375  * Check if a user is in the file _PATH_FTPUSERS
376  */
377 checkuser(name)
378 	char *name;
379 {
380 	FILE *fd;
381 	char line[BUFSIZ], *cp;
382 
383 	if ((fd = fopen(_PATH_FTPUSERS, "r")) != NULL) {
384 		while (fgets(line, sizeof (line), fd) != NULL) {
385 			if ((cp = index(line, '\n')) != NULL)
386 				*cp = '\0';
387 			if (strcmp(line, name) == 0)
388 				return (1);
389 		}
390 		(void) fclose(fd);
391 	}
392 	return (0);
393 }
394 
395 /*
396  * Terminate login as previous user, if any, resetting state;
397  * used when USER command is given or login fails.
398  */
399 end_login()
400 {
401 
402 	(void) seteuid((uid_t)0);
403 	if (logged_in)
404 		logwtmp(ttyline, "", "");
405 	pw = NULL;
406 	logged_in = 0;
407 	guest = 0;
408 }
409 
410 pass(passwd)
411 	char *passwd;
412 {
413 	char *xpasswd, *salt;
414 
415 	if (logged_in || askpasswd == 0) {
416 		reply(503, "Login with USER first.");
417 		return;
418 	}
419 	askpasswd = 0;
420 	if (!guest) {		/* "ftp" is only account allowed no password */
421 		if (pw == NULL)
422 			salt = "xx";
423 		else
424 			salt = pw->pw_passwd;
425 		xpasswd = crypt(passwd, salt);
426 		/* The strcmp does not catch null passwords! */
427 		if (pw == NULL || *pw->pw_passwd == '\0' ||
428 		    strcmp(xpasswd, pw->pw_passwd)) {
429 			reply(530, "Login incorrect.");
430 			pw = NULL;
431 			if (login_attempts++ >= 5) {
432 				syslog(LOG_NOTICE,
433 				    "repeated login failures from %s",
434 				    remotehost);
435 				exit(0);
436 			}
437 			return;
438 		}
439 	}
440 	login_attempts = 0;		/* this time successful */
441 	(void) setegid((gid_t)pw->pw_gid);
442 	(void) initgroups(pw->pw_name, pw->pw_gid);
443 
444 	/* open wtmp before chroot */
445 	(void)sprintf(ttyline, "ftp%d", getpid());
446 	logwtmp(ttyline, pw->pw_name, remotehost);
447 	logged_in = 1;
448 
449 	if (guest) {
450 		/*
451 		 * We MUST do a chdir() after the chroot. Otherwise
452 		 * the old current directory will be accessible as "."
453 		 * outside the new root!
454 		 */
455 		if (chroot(pw->pw_dir) < 0 || chdir("/") < 0) {
456 			reply(550, "Can't set guest privileges.");
457 			goto bad;
458 		}
459 	} else if (chdir(pw->pw_dir) < 0) {
460 		if (chdir("/") < 0) {
461 			reply(530, "User %s: can't change directory to %s.",
462 			    pw->pw_name, pw->pw_dir);
463 			goto bad;
464 		} else
465 			lreply(230, "No directory! Logging in with home=/");
466 	}
467 	if (seteuid((uid_t)pw->pw_uid) < 0) {
468 		reply(550, "Can't set uid.");
469 		goto bad;
470 	}
471 	if (guest) {
472 		reply(230, "Guest login ok, access restrictions apply.");
473 #ifdef SETPROCTITLE
474 		sprintf(proctitle, "%s: anonymous/%.*s", remotehost,
475 		    sizeof(proctitle) - sizeof(remotehost) -
476 		    sizeof(": anonymous/"), passwd);
477 		setproctitle(proctitle);
478 #endif /* SETPROCTITLE */
479 		if (logging)
480 			syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s, %s",
481 			    remotehost, passwd);
482 	} else {
483 		reply(230, "User %s logged in.", pw->pw_name);
484 #ifdef SETPROCTITLE
485 		sprintf(proctitle, "%s: %s", remotehost, pw->pw_name);
486 		setproctitle(proctitle);
487 #endif /* SETPROCTITLE */
488 		if (logging)
489 			syslog(LOG_INFO, "FTP LOGIN FROM %s, %s",
490 			    remotehost, pw->pw_name);
491 	}
492 	home = pw->pw_dir;		/* home dir for globbing */
493 	(void) umask(defumask);
494 	return;
495 bad:
496 	/* Forget all about it... */
497 	end_login();
498 }
499 
500 retrieve(cmd, name)
501 	char *cmd, *name;
502 {
503 	FILE *fin, *dout;
504 	struct stat st;
505 	int (*closefunc)();
506 
507 	if (cmd == 0) {
508 		fin = fopen(name, "r"), closefunc = fclose;
509 		st.st_size = 0;
510 	} else {
511 		char line[BUFSIZ];
512 
513 		(void) sprintf(line, cmd, name), name = line;
514 		fin = ftpd_popen(line, "r"), closefunc = ftpd_pclose;
515 		st.st_size = -1;
516 		st.st_blksize = BUFSIZ;
517 	}
518 	if (fin == NULL) {
519 		if (errno != 0)
520 			perror_reply(550, name);
521 		return;
522 	}
523 	if (cmd == 0 &&
524 	    (fstat(fileno(fin), &st) < 0 || (st.st_mode&S_IFMT) != S_IFREG)) {
525 		reply(550, "%s: not a plain file.", name);
526 		goto done;
527 	}
528 	if (restart_point) {
529 		if (type == TYPE_A) {
530 			register int i, n, c;
531 
532 			n = restart_point;
533 			i = 0;
534 			while (i++ < n) {
535 				if ((c=getc(fin)) == EOF) {
536 					perror_reply(550, name);
537 					goto done;
538 				}
539 				if (c == '\n')
540 					i++;
541 			}
542 		} else if (lseek(fileno(fin), restart_point, L_SET) < 0) {
543 			perror_reply(550, name);
544 			goto done;
545 		}
546 	}
547 	dout = dataconn(name, st.st_size, "w");
548 	if (dout == NULL)
549 		goto done;
550 	send_data(fin, dout, st.st_blksize);
551 	(void) fclose(dout);
552 	data = -1;
553 	pdata = -1;
554 done:
555 	(*closefunc)(fin);
556 }
557 
558 store(name, mode, unique)
559 	char *name, *mode;
560 	int unique;
561 {
562 	FILE *fout, *din;
563 	struct stat st;
564 	int (*closefunc)();
565 	char *gunique();
566 
567 	if (unique && stat(name, &st) == 0 &&
568 	    (name = gunique(name)) == NULL)
569 		return;
570 
571 	if (restart_point)
572 		mode = "r+w";
573 	fout = fopen(name, mode);
574 	closefunc = fclose;
575 	if (fout == NULL) {
576 		perror_reply(553, name);
577 		return;
578 	}
579 	if (restart_point) {
580 		if (type == TYPE_A) {
581 			register int i, n, c;
582 
583 			n = restart_point;
584 			i = 0;
585 			while (i++ < n) {
586 				if ((c=getc(fout)) == EOF) {
587 					perror_reply(550, name);
588 					goto done;
589 				}
590 				if (c == '\n')
591 					i++;
592 			}
593 			/*
594 			 * We must do this seek to "current" position
595 			 * because we are changing from reading to
596 			 * writing.
597 			 */
598 			if (fseek(fout, 0L, L_INCR) < 0) {
599 				perror_reply(550, name);
600 				goto done;
601 			}
602 		} else if (lseek(fileno(fout), restart_point, L_SET) < 0) {
603 			perror_reply(550, name);
604 			goto done;
605 		}
606 	}
607 	din = dataconn(name, (off_t)-1, "r");
608 	if (din == NULL)
609 		goto done;
610 	if (receive_data(din, fout) == 0) {
611 		if (unique)
612 			reply(226, "Transfer complete (unique file name:%s).",
613 			    name);
614 		else
615 			reply(226, "Transfer complete.");
616 	}
617 	(void) fclose(din);
618 	data = -1;
619 	pdata = -1;
620 done:
621 	(*closefunc)(fout);
622 }
623 
624 FILE *
625 getdatasock(mode)
626 	char *mode;
627 {
628 	int s, on = 1, tries;
629 
630 	if (data >= 0)
631 		return (fdopen(data, mode));
632 	s = socket(AF_INET, SOCK_STREAM, 0);
633 	if (s < 0)
634 		return (NULL);
635 	(void) seteuid((uid_t)0);
636 	if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
637 	    (char *) &on, sizeof (on)) < 0)
638 		goto bad;
639 	/* anchor socket to avoid multi-homing problems */
640 	data_source.sin_family = AF_INET;
641 	data_source.sin_addr = ctrl_addr.sin_addr;
642 	for (tries = 1; ; tries++) {
643 		if (bind(s, (struct sockaddr *)&data_source,
644 		    sizeof (data_source)) >= 0)
645 			break;
646 		if (errno != EADDRINUSE || tries > 10)
647 			goto bad;
648 		sleep(tries);
649 	}
650 	(void) seteuid((uid_t)pw->pw_uid);
651 	return (fdopen(s, mode));
652 bad:
653 	(void) seteuid((uid_t)pw->pw_uid);
654 	(void) close(s);
655 	return (NULL);
656 }
657 
658 FILE *
659 dataconn(name, size, mode)
660 	char *name;
661 	off_t size;
662 	char *mode;
663 {
664 	char sizebuf[32];
665 	FILE *file;
666 	int retry = 0;
667 
668 	file_size = size;
669 	byte_count = 0;
670 	if (size != (off_t) -1)
671 		(void) sprintf (sizebuf, " (%ld bytes)", size);
672 	else
673 		(void) strcpy(sizebuf, "");
674 	if (pdata >= 0) {
675 		struct sockaddr_in from;
676 		int s, fromlen = sizeof(from);
677 
678 		s = accept(pdata, (struct sockaddr *)&from, &fromlen);
679 		if (s < 0) {
680 			reply(425, "Can't open data connection.");
681 			(void) close(pdata);
682 			pdata = -1;
683 			return(NULL);
684 		}
685 		(void) close(pdata);
686 		pdata = s;
687 		reply(150, "Opening %s mode data connection for %s%s.",
688 		     type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
689 		return(fdopen(pdata, mode));
690 	}
691 	if (data >= 0) {
692 		reply(125, "Using existing data connection for %s%s.",
693 		    name, sizebuf);
694 		usedefault = 1;
695 		return (fdopen(data, mode));
696 	}
697 	if (usedefault)
698 		data_dest = his_addr;
699 	usedefault = 1;
700 	file = getdatasock(mode);
701 	if (file == NULL) {
702 		reply(425, "Can't create data socket (%s,%d): %s.",
703 		    inet_ntoa(data_source.sin_addr),
704 		    ntohs(data_source.sin_port),
705 		    errno < sys_nerr ? sys_errlist[errno] : "unknown error");
706 		return (NULL);
707 	}
708 	data = fileno(file);
709 	while (connect(data, (struct sockaddr *)&data_dest,
710 	    sizeof (data_dest)) < 0) {
711 		if (errno == EADDRINUSE && retry < swaitmax) {
712 			sleep((unsigned) swaitint);
713 			retry += swaitint;
714 			continue;
715 		}
716 		perror_reply(425, "Can't build data connection");
717 		(void) fclose(file);
718 		data = -1;
719 		return (NULL);
720 	}
721 	reply(150, "Opening %s mode data connection for %s%s.",
722 	     type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
723 	return (file);
724 }
725 
726 /*
727  * Tranfer the contents of "instr" to
728  * "outstr" peer using the appropriate
729  * encapsulation of the data subject
730  * to Mode, Structure, and Type.
731  *
732  * NB: Form isn't handled.
733  */
734 send_data(instr, outstr, blksize)
735 	FILE *instr, *outstr;
736 	off_t blksize;
737 {
738 	register int c, cnt;
739 	register char *buf;
740 	int netfd, filefd;
741 
742 	transflag++;
743 	if (setjmp(urgcatch)) {
744 		transflag = 0;
745 		return;
746 	}
747 	switch (type) {
748 
749 	case TYPE_A:
750 		while ((c = getc(instr)) != EOF) {
751 			byte_count++;
752 			if (c == '\n') {
753 				if (ferror(outstr))
754 					goto data_err;
755 				(void) putc('\r', outstr);
756 			}
757 			(void) putc(c, outstr);
758 		}
759 		fflush(outstr);
760 		transflag = 0;
761 		if (ferror(instr))
762 			goto file_err;
763 		if (ferror(outstr))
764 			goto data_err;
765 		reply(226, "Transfer complete.");
766 		return;
767 
768 	case TYPE_I:
769 	case TYPE_L:
770 		if ((buf = malloc((u_int)blksize)) == NULL) {
771 			transflag = 0;
772 			perror_reply(451, "Local resource failure: malloc");
773 			return;
774 		}
775 		netfd = fileno(outstr);
776 		filefd = fileno(instr);
777 		while ((cnt = read(filefd, buf, (u_int)blksize)) > 0 &&
778 		    write(netfd, buf, cnt) == cnt)
779 			byte_count += cnt;
780 		transflag = 0;
781 		(void)free(buf);
782 		if (cnt != 0) {
783 			if (cnt < 0)
784 				goto file_err;
785 			goto data_err;
786 		}
787 		reply(226, "Transfer complete.");
788 		return;
789 	default:
790 		transflag = 0;
791 		reply(550, "Unimplemented TYPE %d in send_data", type);
792 		return;
793 	}
794 
795 data_err:
796 	transflag = 0;
797 	perror_reply(426, "Data connection");
798 	return;
799 
800 file_err:
801 	transflag = 0;
802 	perror_reply(551, "Error on input file");
803 }
804 
805 /*
806  * Transfer data from peer to
807  * "outstr" using the appropriate
808  * encapulation of the data subject
809  * to Mode, Structure, and Type.
810  *
811  * N.B.: Form isn't handled.
812  */
813 receive_data(instr, outstr)
814 	FILE *instr, *outstr;
815 {
816 	register int c;
817 	int cnt, bare_lfs = 0;
818 	char buf[BUFSIZ];
819 
820 	transflag++;
821 	if (setjmp(urgcatch)) {
822 		transflag = 0;
823 		return (-1);
824 	}
825 	switch (type) {
826 
827 	case TYPE_I:
828 	case TYPE_L:
829 		while ((cnt = read(fileno(instr), buf, sizeof buf)) > 0) {
830 			if (write(fileno(outstr), buf, cnt) != cnt)
831 				goto file_err;
832 			byte_count += cnt;
833 		}
834 		if (cnt < 0)
835 			goto data_err;
836 		transflag = 0;
837 		return (0);
838 
839 	case TYPE_E:
840 		reply(553, "TYPE E not implemented.");
841 		transflag = 0;
842 		return (-1);
843 
844 	case TYPE_A:
845 		while ((c = getc(instr)) != EOF) {
846 			byte_count++;
847 			if (c == '\n')
848 				bare_lfs++;
849 			while (c == '\r') {
850 				if (ferror(outstr))
851 					goto data_err;
852 				if ((c = getc(instr)) != '\n') {
853 					(void) putc ('\r', outstr);
854 					if (c == '\0' || c == EOF)
855 						goto contin2;
856 				}
857 			}
858 			(void) putc(c, outstr);
859 	contin2:	;
860 		}
861 		fflush(outstr);
862 		if (ferror(instr))
863 			goto data_err;
864 		if (ferror(outstr))
865 			goto file_err;
866 		transflag = 0;
867 		if (bare_lfs) {
868 			lreply(230, "WARNING! %d bare linefeeds received in ASCII mode", bare_lfs);
869 			printf("   File may not have transferred correctly.\r\n");
870 		}
871 		return (0);
872 	default:
873 		reply(550, "Unimplemented TYPE %d in receive_data", type);
874 		transflag = 0;
875 		return (-1);
876 	}
877 
878 data_err:
879 	transflag = 0;
880 	perror_reply(426, "Data Connection");
881 	return (-1);
882 
883 file_err:
884 	transflag = 0;
885 	perror_reply(452, "Error writing file");
886 	return (-1);
887 }
888 
889 statfilecmd(filename)
890 	char *filename;
891 {
892 	char line[BUFSIZ];
893 	FILE *fin;
894 	int c;
895 
896 	(void) sprintf(line, "/bin/ls -lgA %s", filename);
897 	fin = ftpd_popen(line, "r");
898 	lreply(211, "status of %s:", filename);
899 	while ((c = getc(fin)) != EOF) {
900 		if (c == '\n') {
901 			if (ferror(stdout)){
902 				perror_reply(421, "control connection");
903 				(void) ftpd_pclose(fin);
904 				dologout(1);
905 				/* NOTREACHED */
906 			}
907 			if (ferror(fin)) {
908 				perror_reply(551, filename);
909 				(void) ftpd_pclose(fin);
910 				return;
911 			}
912 			(void) putc('\r', stdout);
913 		}
914 		(void) putc(c, stdout);
915 	}
916 	(void) ftpd_pclose(fin);
917 	reply(211, "End of Status");
918 }
919 
920 statcmd()
921 {
922 	struct sockaddr_in *sin;
923 	u_char *a, *p;
924 
925 	lreply(211, "%s FTP server status:", hostname, version);
926 	printf("     %s\r\n", version);
927 	printf("     Connected to %s", remotehost);
928 	if (!isdigit(remotehost[0]))
929 		printf(" (%s)", inet_ntoa(his_addr.sin_addr));
930 	printf("\r\n");
931 	if (logged_in) {
932 		if (guest)
933 			printf("     Logged in anonymously\r\n");
934 		else
935 			printf("     Logged in as %s\r\n", pw->pw_name);
936 	} else if (askpasswd)
937 		printf("     Waiting for password\r\n");
938 	else
939 		printf("     Waiting for user name\r\n");
940 	printf("     TYPE: %s", typenames[type]);
941 	if (type == TYPE_A || type == TYPE_E)
942 		printf(", FORM: %s", formnames[form]);
943 	if (type == TYPE_L)
944 #if NBBY == 8
945 		printf(" %d", NBBY);
946 #else
947 		printf(" %d", bytesize);	/* need definition! */
948 #endif
949 	printf("; STRUcture: %s; transfer MODE: %s\r\n",
950 	    strunames[stru], modenames[mode]);
951 	if (data != -1)
952 		printf("     Data connection open\r\n");
953 	else if (pdata != -1) {
954 		printf("     in Passive mode");
955 		sin = &pasv_addr;
956 		goto printaddr;
957 	} else if (usedefault == 0) {
958 		printf("     PORT");
959 		sin = &data_dest;
960 printaddr:
961 		a = (u_char *) &sin->sin_addr;
962 		p = (u_char *) &sin->sin_port;
963 #define UC(b) (((int) b) & 0xff)
964 		printf(" (%d,%d,%d,%d,%d,%d)\r\n", UC(a[0]),
965 			UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
966 #undef UC
967 	} else
968 		printf("     No data connection\r\n");
969 	reply(211, "End of status");
970 }
971 
972 fatal(s)
973 	char *s;
974 {
975 	reply(451, "Error in server: %s\n", s);
976 	reply(221, "Closing connection due to server error.");
977 	dologout(0);
978 	/* NOTREACHED */
979 }
980 
981 /* VARARGS2 */
982 reply(n, fmt, p0, p1, p2, p3, p4, p5)
983 	int n;
984 	char *fmt;
985 {
986 	printf("%d ", n);
987 	printf(fmt, p0, p1, p2, p3, p4, p5);
988 	printf("\r\n");
989 	(void)fflush(stdout);
990 	if (debug) {
991 		syslog(LOG_DEBUG, "<--- %d ", n);
992 		syslog(LOG_DEBUG, fmt, p0, p1, p2, p3, p4, p5);
993 }
994 }
995 
996 /* VARARGS2 */
997 lreply(n, fmt, p0, p1, p2, p3, p4, p5)
998 	int n;
999 	char *fmt;
1000 {
1001 	printf("%d- ", n);
1002 	printf(fmt, p0, p1, p2, p3, p4, p5);
1003 	printf("\r\n");
1004 	(void)fflush(stdout);
1005 	if (debug) {
1006 		syslog(LOG_DEBUG, "<--- %d- ", n);
1007 		syslog(LOG_DEBUG, fmt, p0, p1, p2, p3, p4, p5);
1008 	}
1009 }
1010 
1011 ack(s)
1012 	char *s;
1013 {
1014 	reply(250, "%s command successful.", s);
1015 }
1016 
1017 nack(s)
1018 	char *s;
1019 {
1020 	reply(502, "%s command not implemented.", s);
1021 }
1022 
1023 /* ARGSUSED */
1024 yyerror(s)
1025 	char *s;
1026 {
1027 	char *cp;
1028 
1029 	if (cp = index(cbuf,'\n'))
1030 		*cp = '\0';
1031 	reply(500, "'%s': command not understood.", cbuf);
1032 }
1033 
1034 delete(name)
1035 	char *name;
1036 {
1037 	struct stat st;
1038 
1039 	if (stat(name, &st) < 0) {
1040 		perror_reply(550, name);
1041 		return;
1042 	}
1043 	if ((st.st_mode&S_IFMT) == S_IFDIR) {
1044 		if (rmdir(name) < 0) {
1045 			perror_reply(550, name);
1046 			return;
1047 		}
1048 		goto done;
1049 	}
1050 	if (unlink(name) < 0) {
1051 		perror_reply(550, name);
1052 		return;
1053 	}
1054 done:
1055 	ack("DELE");
1056 }
1057 
1058 cwd(path)
1059 	char *path;
1060 {
1061 	if (chdir(path) < 0)
1062 		perror_reply(550, path);
1063 	else
1064 		ack("CWD");
1065 }
1066 
1067 makedir(name)
1068 	char *name;
1069 {
1070 	if (mkdir(name, 0777) < 0)
1071 		perror_reply(550, name);
1072 	else
1073 		reply(257, "MKD command successful.");
1074 }
1075 
1076 removedir(name)
1077 	char *name;
1078 {
1079 	if (rmdir(name) < 0)
1080 		perror_reply(550, name);
1081 	else
1082 		ack("RMD");
1083 }
1084 
1085 pwd()
1086 {
1087 	char path[MAXPATHLEN + 1];
1088 	extern char *getwd();
1089 
1090 	if (getwd(path) == (char *)NULL)
1091 		reply(550, "%s.", path);
1092 	else
1093 		reply(257, "\"%s\" is current directory.", path);
1094 }
1095 
1096 char *
1097 renamefrom(name)
1098 	char *name;
1099 {
1100 	struct stat st;
1101 
1102 	if (stat(name, &st) < 0) {
1103 		perror_reply(550, name);
1104 		return ((char *)0);
1105 	}
1106 	reply(350, "File exists, ready for destination name");
1107 	return (name);
1108 }
1109 
1110 renamecmd(from, to)
1111 	char *from, *to;
1112 {
1113 	if (rename(from, to) < 0)
1114 		perror_reply(550, "rename");
1115 	else
1116 		ack("RNTO");
1117 }
1118 
1119 dolog(sin)
1120 	struct sockaddr_in *sin;
1121 {
1122 	struct hostent *hp = gethostbyaddr((char *)&sin->sin_addr,
1123 		sizeof (struct in_addr), AF_INET);
1124 	time_t t, time();
1125 	extern char *ctime();
1126 
1127 	if (hp)
1128 		(void) strncpy(remotehost, hp->h_name, sizeof (remotehost));
1129 	else
1130 		(void) strncpy(remotehost, inet_ntoa(sin->sin_addr),
1131 		    sizeof (remotehost));
1132 #ifdef SETPROCTITLE
1133 	sprintf(proctitle, "%s: connected", remotehost);
1134 	setproctitle(proctitle);
1135 #endif /* SETPROCTITLE */
1136 
1137 	if (logging) {
1138 		t = time((time_t *) 0);
1139 		syslog(LOG_INFO, "connection from %s at %s",
1140 		    remotehost, ctime(&t));
1141 	}
1142 }
1143 
1144 /*
1145  * Record logout in wtmp file
1146  * and exit with supplied status.
1147  */
1148 dologout(status)
1149 	int status;
1150 {
1151 	if (logged_in) {
1152 		(void) seteuid((uid_t)0);
1153 		logwtmp(ttyline, "", "");
1154 	}
1155 	/* beware of flushing buffers after a SIGPIPE */
1156 	_exit(status);
1157 }
1158 
1159 myoob()
1160 {
1161 	char *cp;
1162 
1163 	/* only process if transfer occurring */
1164 	if (!transflag)
1165 		return;
1166 	cp = tmpline;
1167 	if (getline(cp, 7, stdin) == NULL) {
1168 		reply(221, "You could at least say goodbye.");
1169 		dologout(0);
1170 	}
1171 	upper(cp);
1172 	if (strcmp(cp, "ABOR\r\n") == 0) {
1173 		tmpline[0] = '\0';
1174 		reply(426, "Transfer aborted. Data connection closed.");
1175 		reply(226, "Abort successful");
1176 		longjmp(urgcatch, 1);
1177 	}
1178 	if (strcmp(cp, "STAT\r\n") == 0) {
1179 		if (file_size != (off_t) -1)
1180 			reply(213, "Status: %lu of %lu bytes transferred",
1181 			    byte_count, file_size);
1182 		else
1183 			reply(213, "Status: %lu bytes transferred", byte_count);
1184 	}
1185 }
1186 
1187 /*
1188  * Note: a response of 425 is not mentioned as a possible response to
1189  * 	the PASV command in RFC959. However, it has been blessed as
1190  * 	a legitimate response by Jon Postel in a telephone conversation
1191  *	with Rick Adams on 25 Jan 89.
1192  */
1193 passive()
1194 {
1195 	int len;
1196 	register char *p, *a;
1197 
1198 	pdata = socket(AF_INET, SOCK_STREAM, 0);
1199 	if (pdata < 0) {
1200 		perror_reply(425, "Can't open passive connection");
1201 		return;
1202 	}
1203 	pasv_addr = ctrl_addr;
1204 	pasv_addr.sin_port = 0;
1205 	(void) seteuid((uid_t)0);
1206 	if (bind(pdata, (struct sockaddr *)&pasv_addr, sizeof(pasv_addr)) < 0) {
1207 		(void) seteuid((uid_t)pw->pw_uid);
1208 		goto pasv_error;
1209 	}
1210 	(void) seteuid((uid_t)pw->pw_uid);
1211 	len = sizeof(pasv_addr);
1212 	if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
1213 		goto pasv_error;
1214 	if (listen(pdata, 1) < 0)
1215 		goto pasv_error;
1216 	a = (char *) &pasv_addr.sin_addr;
1217 	p = (char *) &pasv_addr.sin_port;
1218 
1219 #define UC(b) (((int) b) & 0xff)
1220 
1221 	reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
1222 		UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
1223 	return;
1224 
1225 pasv_error:
1226 	(void) close(pdata);
1227 	pdata = -1;
1228 	perror_reply(425, "Can't open passive connection");
1229 	return;
1230 }
1231 
1232 /*
1233  * Generate unique name for file with basename "local".
1234  * The file named "local" is already known to exist.
1235  * Generates failure reply on error.
1236  */
1237 char *
1238 gunique(local)
1239 	char *local;
1240 {
1241 	static char new[MAXPATHLEN];
1242 	struct stat st;
1243 	char *cp = rindex(local, '/');
1244 	int count = 0;
1245 
1246 	if (cp)
1247 		*cp = '\0';
1248 	if (stat(cp ? local : ".", &st) < 0) {
1249 		perror_reply(553, cp ? local : ".");
1250 		return((char *) 0);
1251 	}
1252 	if (cp)
1253 		*cp = '/';
1254 	(void) strcpy(new, local);
1255 	cp = new + strlen(new);
1256 	*cp++ = '.';
1257 	for (count = 1; count < 100; count++) {
1258 		(void) sprintf(cp, "%d", count);
1259 		if (stat(new, &st) < 0)
1260 			return(new);
1261 	}
1262 	reply(452, "Unique file name cannot be created.");
1263 	return((char *) 0);
1264 }
1265 
1266 /*
1267  * Format and send reply containing system error number.
1268  */
1269 perror_reply(code, string)
1270 	int code;
1271 	char *string;
1272 {
1273 	if (errno < sys_nerr)
1274 		reply(code, "%s: %s.", string, sys_errlist[errno]);
1275 	else
1276 		reply(code, "%s: unknown error %d.", string, errno);
1277 }
1278 
1279 static char *onefile[] = {
1280 	"",
1281 	0
1282 };
1283 
1284 send_file_list(whichfiles)
1285 	char *whichfiles;
1286 {
1287 	struct stat st;
1288 	DIR *dirp = NULL;
1289 	struct direct *dir;
1290 	FILE *dout = NULL;
1291 	register char **dirlist, *dirname;
1292 	int simple = 0;
1293 	char *strpbrk();
1294 
1295 	if (strpbrk(whichfiles, "~{[*?") != NULL) {
1296 		extern char **glob(), *globerr;
1297 
1298 		globerr = NULL;
1299 		dirlist = glob(whichfiles);
1300 		if (globerr != NULL) {
1301 			reply(550, globerr);
1302 			return;
1303 		} else if (dirlist == NULL) {
1304 			errno = ENOENT;
1305 			perror_reply(550, whichfiles);
1306 			return;
1307 		}
1308 	} else {
1309 		onefile[0] = whichfiles;
1310 		dirlist = onefile;
1311 		simple = 1;
1312 	}
1313 
1314 	if (setjmp(urgcatch)) {
1315 		transflag = 0;
1316 		return;
1317 	}
1318 	while (dirname = *dirlist++) {
1319 		if (stat(dirname, &st) < 0) {
1320 			/*
1321 			 * If user typed "ls -l", etc, and the client
1322 			 * used NLST, do what the user meant.
1323 			 */
1324 			if (dirname[0] == '-' && *dirlist == NULL &&
1325 			    transflag == 0) {
1326 				retrieve("/bin/ls %s", dirname);
1327 				return;
1328 			}
1329 			perror_reply(550, whichfiles);
1330 			if (dout != NULL) {
1331 				(void) fclose(dout);
1332 				transflag = 0;
1333 				data = -1;
1334 				pdata = -1;
1335 			}
1336 			return;
1337 		}
1338 
1339 		if ((st.st_mode&S_IFMT) == S_IFREG) {
1340 			if (dout == NULL) {
1341 				dout = dataconn("file list", (off_t)-1, "w");
1342 				if (dout == NULL)
1343 					return;
1344 				transflag++;
1345 			}
1346 			fprintf(dout, "%s%s\n", dirname,
1347 				type == TYPE_A ? "\r" : "");
1348 			byte_count += strlen(dirname) + 1;
1349 			continue;
1350 		} else if ((st.st_mode&S_IFMT) != S_IFDIR)
1351 			continue;
1352 
1353 		if ((dirp = opendir(dirname)) == NULL)
1354 			continue;
1355 
1356 		while ((dir = readdir(dirp)) != NULL) {
1357 			char nbuf[MAXPATHLEN];
1358 
1359 			if (dir->d_name[0] == '.' && dir->d_namlen == 1)
1360 				continue;
1361 			if (dir->d_name[0] == '.' && dir->d_name[1] == '.' &&
1362 			    dir->d_namlen == 2)
1363 				continue;
1364 
1365 			sprintf(nbuf, "%s/%s", dirname, dir->d_name);
1366 
1367 			/*
1368 			 * We have to do a stat to insure it's
1369 			 * not a directory or special file.
1370 			 */
1371 			if (simple || (stat(nbuf, &st) == 0 &&
1372 			    (st.st_mode&S_IFMT) == S_IFREG)) {
1373 				if (dout == NULL) {
1374 					dout = dataconn("file list", (off_t)-1,
1375 						"w");
1376 					if (dout == NULL)
1377 						return;
1378 					transflag++;
1379 				}
1380 				if (nbuf[0] == '.' && nbuf[1] == '/')
1381 					fprintf(dout, "%s%s\n", &nbuf[2],
1382 						type == TYPE_A ? "\r" : "");
1383 				else
1384 					fprintf(dout, "%s%s\n", nbuf,
1385 						type == TYPE_A ? "\r" : "");
1386 				byte_count += strlen(nbuf) + 1;
1387 			}
1388 		}
1389 		(void) closedir(dirp);
1390 	}
1391 
1392 	if (dout == NULL)
1393 		reply(550, "No files found.");
1394 	else if (ferror(dout) != 0)
1395 		perror_reply(550, "Data connection");
1396 	else
1397 		reply(226, "Transfer complete.");
1398 
1399 	transflag = 0;
1400 	if (dout != NULL)
1401 		(void) fclose(dout);
1402 	data = -1;
1403 	pdata = -1;
1404 }
1405 
1406 #ifdef SETPROCTITLE
1407 /*
1408  * clobber argv so ps will show what we're doing.
1409  * (stolen from sendmail)
1410  * warning, since this is usually started from inetd.conf, it
1411  * often doesn't have much of an environment or arglist to overwrite.
1412  */
1413 
1414 /*VARARGS1*/
1415 setproctitle(fmt, a, b, c)
1416 char *fmt;
1417 {
1418 	register char *p, *bp, ch;
1419 	register int i;
1420 	char buf[BUFSIZ];
1421 
1422 	(void) sprintf(buf, fmt, a, b, c);
1423 
1424 	/* make ps print our process name */
1425 	p = Argv[0];
1426 	*p++ = '-';
1427 
1428 	i = strlen(buf);
1429 	if (i > LastArgv - p - 2) {
1430 		i = LastArgv - p - 2;
1431 		buf[i] = '\0';
1432 	}
1433 	bp = buf;
1434 	while (ch = *bp++)
1435 		if (ch != '\n' && ch != '\r')
1436 			*p++ = ch;
1437 	while (p < LastArgv)
1438 		*p++ = ' ';
1439 }
1440 #endif /* SETPROCTITLE */
1441