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