xref: /csrg-svn/libexec/ftpd/ftpd.c (revision 40155)
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.31	(Berkeley) 02/19/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 	FILE *fd;
325 	char *shell;
326 	char line[BUFSIZ], *getusershell();
327 
328 	if (logged_in) {
329 		if (guest) {
330 			reply(530, "Can't change user from guest login.");
331 			return;
332 		}
333 		end_login();
334 	}
335 
336 	guest = 0;
337 	if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) {
338 		if (!checkuser("ftp") || !checkuser("anonymous"))
339 			reply(530, "User %s access denied.", name);
340 		else if ((pw = sgetpwnam("ftp")) != NULL) {
341 			guest = 1;
342 			askpasswd = 1;
343 			reply(331, "Guest login ok, send ident as password.");
344 		} else
345 			reply(530, "User %s unknown.", name);
346 		return;
347 	}
348 	if (pw = sgetpwnam(name)) {
349 		if ((shell = pw->pw_shell) == NULL || *shell == 0)
350 			shell = _PATH_BSHELL;
351 		while ((cp = getusershell()) != NULL)
352 			if (strcmp(cp, shell) == 0)
353 				break;
354 		endusershell();
355 		if (cp == NULL) {
356 			reply(530, "User %s access denied.", name);
357 			if (logging)
358 				syslog(LOG_NOTICE,
359 				    "FTP LOGIN REFUSED FROM %s, %s",
360 				    remotehost, name);
361 			pw = (struct passwd *) NULL;
362 			return;
363 		}
364 		if ((fd = fopen(_PATH_FTPUSERS, "r")) != NULL) {
365 		    while (fgets(line, sizeof (line), fd) != NULL) {
366 			if ((cp = index(line, '\n')) != NULL)
367 				*cp = '\0';
368 			if (strcmp(line, name) == 0) {
369 				reply(530, "User %s access denied.", name);
370 				if (logging)
371 					syslog(LOG_NOTICE,
372 					    "FTP LOGIN REFUSED FROM %s, %s",
373 					    remotehost, name);
374 				pw = (struct passwd *) NULL;
375 				(void) fclose(fd);
376 				return;
377 			}
378 		    }
379 		    (void) fclose(fd);
380 		}
381 	}
382 	reply(331, "Password required for %s.", name);
383 	askpasswd = 1;
384 	/*
385 	 * Delay before reading passwd after first failed
386 	 * attempt to slow down passwd-guessing programs.
387 	 */
388 	if (login_attempts)
389 		sleep((unsigned) login_attempts);
390 }
391 
392 /*
393  * Terminate login as previous user, if any, resetting state;
394  * used when USER command is given or login fails.
395  */
396 end_login()
397 {
398 
399 	(void) seteuid((uid_t)0);
400 	if (logged_in)
401 		logwtmp(ttyline, "", "");
402 	pw = NULL;
403 	logged_in = 0;
404 	guest = 0;
405 }
406 
407 pass(passwd)
408 	char *passwd;
409 {
410 	char *xpasswd, *salt;
411 
412 	if (logged_in || askpasswd == 0) {
413 		reply(503, "Login with USER first.");
414 		return;
415 	}
416 	askpasswd = 0;
417 	if (!guest) {		/* "ftp" is only account allowed no password */
418 		if (pw == NULL)
419 			salt = "xx";
420 		else
421 			salt = pw->pw_passwd;
422 		xpasswd = crypt(passwd, salt);
423 		/* The strcmp does not catch null passwords! */
424 		if (pw == NULL || *pw->pw_passwd == '\0' ||
425 		    strcmp(xpasswd, pw->pw_passwd)) {
426 			reply(530, "Login incorrect.");
427 			pw = NULL;
428 			if (login_attempts++ >= 5) {
429 				syslog(LOG_NOTICE,
430 				    "repeated login failures from %s",
431 				    remotehost);
432 				exit(0);
433 			}
434 			return;
435 		}
436 	}
437 	login_attempts = 0;		/* this time successful */
438 	(void) setegid((gid_t)pw->pw_gid);
439 	(void) initgroups(pw->pw_name, pw->pw_gid);
440 
441 	/* open wtmp before chroot */
442 	(void)sprintf(ttyline, "ftp%d", getpid());
443 	logwtmp(ttyline, pw->pw_name, remotehost);
444 	logged_in = 1;
445 
446 	if (guest) {
447 		/*
448 		 * We MUST do a chdir() after the chroot. Otherwise
449 		 * the old current directory will be accessible as "."
450 		 * outside the new root!
451 		 */
452 		if (chroot(pw->pw_dir) < 0 || chdir("/") < 0) {
453 			reply(550, "Can't set guest privileges.");
454 			goto bad;
455 		}
456 	} else if (chdir(pw->pw_dir) < 0) {
457 		if (chdir("/") < 0) {
458 			reply(530, "User %s: can't change directory to %s.",
459 			    pw->pw_name, pw->pw_dir);
460 			goto bad;
461 		} else
462 			lreply(230, "No directory! Logging in with home=/");
463 	}
464 	if (seteuid((uid_t)pw->pw_uid) < 0) {
465 		reply(550, "Can't set uid.");
466 		goto bad;
467 	}
468 	if (guest) {
469 		reply(230, "Guest login ok, access restrictions apply.");
470 #ifdef SETPROCTITLE
471 		sprintf(proctitle, "%s: anonymous/%.*s", remotehost,
472 		    sizeof(proctitle) - sizeof(remotehost) -
473 		    sizeof(": anonymous/"), passwd);
474 		setproctitle(proctitle);
475 #endif /* SETPROCTITLE */
476 		if (logging)
477 			syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s, %s",
478 			    remotehost, passwd);
479 	} else {
480 		reply(230, "User %s logged in.", pw->pw_name);
481 #ifdef SETPROCTITLE
482 		sprintf(proctitle, "%s: %s", remotehost, pw->pw_name);
483 		setproctitle(proctitle);
484 #endif /* SETPROCTITLE */
485 		if (logging)
486 			syslog(LOG_INFO, "FTP LOGIN FROM %s, %s",
487 			    remotehost, pw->pw_name);
488 	}
489 	home = pw->pw_dir;		/* home dir for globbing */
490 	(void) umask(defumask);
491 	return;
492 bad:
493 	/* Forget all about it... */
494 	end_login();
495 }
496 
497 retrieve(cmd, name)
498 	char *cmd, *name;
499 {
500 	FILE *fin, *dout;
501 	struct stat st;
502 	int (*closefunc)();
503 
504 	if (cmd == 0) {
505 		fin = fopen(name, "r"), closefunc = fclose;
506 		st.st_size = 0;
507 	} else {
508 		char line[BUFSIZ];
509 
510 		(void) sprintf(line, cmd, name), name = line;
511 		fin = ftpd_popen(line, "r"), closefunc = ftpd_pclose;
512 		st.st_size = -1;
513 		st.st_blksize = BUFSIZ;
514 	}
515 	if (fin == NULL) {
516 		if (errno != 0)
517 			perror_reply(550, name);
518 		return;
519 	}
520 	if (cmd == 0 &&
521 	    (fstat(fileno(fin), &st) < 0 || (st.st_mode&S_IFMT) != S_IFREG)) {
522 		reply(550, "%s: not a plain file.", name);
523 		goto done;
524 	}
525 	if (restart_point) {
526 		if (type == TYPE_A) {
527 			register int i, n, c;
528 
529 			n = restart_point;
530 			i = 0;
531 			while (i++ < n) {
532 				if ((c=getc(fin)) == EOF) {
533 					perror_reply(550, name);
534 					goto done;
535 				}
536 				if (c == '\n')
537 					i++;
538 			}
539 		} else if (lseek(fileno(fin), restart_point, L_SET) < 0) {
540 			perror_reply(550, name);
541 			goto done;
542 		}
543 	}
544 	dout = dataconn(name, st.st_size, "w");
545 	if (dout == NULL)
546 		goto done;
547 	send_data(fin, dout, st.st_blksize);
548 	(void) fclose(dout);
549 	data = -1;
550 	pdata = -1;
551 done:
552 	(*closefunc)(fin);
553 }
554 
555 store(name, mode, unique)
556 	char *name, *mode;
557 	int unique;
558 {
559 	FILE *fout, *din;
560 	struct stat st;
561 	int (*closefunc)();
562 	char *gunique();
563 
564 	if (unique && stat(name, &st) == 0 &&
565 	    (name = gunique(name)) == NULL)
566 		return;
567 
568 	if (restart_point)
569 		mode = "r+w";
570 	fout = fopen(name, mode);
571 	closefunc = fclose;
572 	if (fout == NULL) {
573 		perror_reply(553, name);
574 		return;
575 	}
576 	if (restart_point) {
577 		if (type == TYPE_A) {
578 			register int i, n, c;
579 
580 			n = restart_point;
581 			i = 0;
582 			while (i++ < n) {
583 				if ((c=getc(fout)) == EOF) {
584 					perror_reply(550, name);
585 					goto done;
586 				}
587 				if (c == '\n')
588 					i++;
589 			}
590 			/*
591 			 * We must do this seek to "current" position
592 			 * because we are changing from reading to
593 			 * writing.
594 			 */
595 			if (fseek(fout, 0L, L_INCR) < 0) {
596 				perror_reply(550, name);
597 				goto done;
598 			}
599 		} else if (lseek(fileno(fout), restart_point, L_SET) < 0) {
600 			perror_reply(550, name);
601 			goto done;
602 		}
603 	}
604 	din = dataconn(name, (off_t)-1, "r");
605 	if (din == NULL)
606 		goto done;
607 	if (receive_data(din, fout) == 0) {
608 		if (unique)
609 			reply(226, "Transfer complete (unique file name:%s).",
610 			    name);
611 		else
612 			reply(226, "Transfer complete.");
613 	}
614 	(void) fclose(din);
615 	data = -1;
616 	pdata = -1;
617 done:
618 	(*closefunc)(fout);
619 }
620 
621 FILE *
622 getdatasock(mode)
623 	char *mode;
624 {
625 	int s, on = 1, tries;
626 
627 	if (data >= 0)
628 		return (fdopen(data, mode));
629 	s = socket(AF_INET, SOCK_STREAM, 0);
630 	if (s < 0)
631 		return (NULL);
632 	(void) seteuid((uid_t)0);
633 	if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
634 	    (char *) &on, sizeof (on)) < 0)
635 		goto bad;
636 	/* anchor socket to avoid multi-homing problems */
637 	data_source.sin_family = AF_INET;
638 	data_source.sin_addr = ctrl_addr.sin_addr;
639 	for (tries = 1; ; tries++) {
640 		if (bind(s, (struct sockaddr *)&data_source,
641 		    sizeof (data_source)) >= 0)
642 			break;
643 		if (errno != EADDRINUSE || tries > 10)
644 			goto bad;
645 		sleep(tries);
646 	}
647 	(void) seteuid((uid_t)pw->pw_uid);
648 	return (fdopen(s, mode));
649 bad:
650 	(void) seteuid((uid_t)pw->pw_uid);
651 	(void) close(s);
652 	return (NULL);
653 }
654 
655 FILE *
656 dataconn(name, size, mode)
657 	char *name;
658 	off_t size;
659 	char *mode;
660 {
661 	char sizebuf[32];
662 	FILE *file;
663 	int retry = 0;
664 
665 	file_size = size;
666 	byte_count = 0;
667 	if (size != (off_t) -1)
668 		(void) sprintf (sizebuf, " (%ld bytes)", size);
669 	else
670 		(void) strcpy(sizebuf, "");
671 	if (pdata >= 0) {
672 		struct sockaddr_in from;
673 		int s, fromlen = sizeof(from);
674 
675 		s = accept(pdata, (struct sockaddr *)&from, &fromlen);
676 		if (s < 0) {
677 			reply(425, "Can't open data connection.");
678 			(void) close(pdata);
679 			pdata = -1;
680 			return(NULL);
681 		}
682 		(void) close(pdata);
683 		pdata = s;
684 		reply(150, "Opening %s mode data connection for %s%s.",
685 		     type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
686 		return(fdopen(pdata, mode));
687 	}
688 	if (data >= 0) {
689 		reply(125, "Using existing data connection for %s%s.",
690 		    name, sizebuf);
691 		usedefault = 1;
692 		return (fdopen(data, mode));
693 	}
694 	if (usedefault)
695 		data_dest = his_addr;
696 	usedefault = 1;
697 	file = getdatasock(mode);
698 	if (file == NULL) {
699 		reply(425, "Can't create data socket (%s,%d): %s.",
700 		    inet_ntoa(data_source.sin_addr),
701 		    ntohs(data_source.sin_port),
702 		    errno < sys_nerr ? sys_errlist[errno] : "unknown error");
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 	if (errno < sys_nerr)
1271 		reply(code, "%s: %s.", string, sys_errlist[errno]);
1272 	else
1273 		reply(code, "%s: unknown error %d.", string, errno);
1274 }
1275 
1276 static char *onefile[] = {
1277 	"",
1278 	0
1279 };
1280 
1281 send_file_list(whichfiles)
1282 	char *whichfiles;
1283 {
1284 	struct stat st;
1285 	DIR *dirp = NULL;
1286 	struct direct *dir;
1287 	FILE *dout = NULL;
1288 	register char **dirlist, *dirname;
1289 	int simple = 0;
1290 	char *strpbrk();
1291 
1292 	if (strpbrk(whichfiles, "~{[*?") != NULL) {
1293 		extern char **glob(), *globerr;
1294 
1295 		globerr = NULL;
1296 		dirlist = glob(whichfiles);
1297 		if (globerr != NULL) {
1298 			reply(550, globerr);
1299 			return;
1300 		} else if (dirlist == NULL) {
1301 			errno = ENOENT;
1302 			perror_reply(550, whichfiles);
1303 			return;
1304 		}
1305 	} else {
1306 		onefile[0] = whichfiles;
1307 		dirlist = onefile;
1308 		simple = 1;
1309 	}
1310 
1311 	if (setjmp(urgcatch)) {
1312 		transflag = 0;
1313 		return;
1314 	}
1315 	while (dirname = *dirlist++) {
1316 		if (stat(dirname, &st) < 0) {
1317 			/*
1318 			 * If user typed "ls -l", etc, and the client
1319 			 * used NLST, do what the user meant.
1320 			 */
1321 			if (dirname[0] == '-' && *dirlist == NULL &&
1322 			    transflag == 0) {
1323 				retrieve("/bin/ls %s", dirname);
1324 				return;
1325 			}
1326 			perror_reply(550, whichfiles);
1327 			if (dout != NULL) {
1328 				(void) fclose(dout);
1329 				transflag = 0;
1330 				data = -1;
1331 				pdata = -1;
1332 			}
1333 			return;
1334 		}
1335 
1336 		if ((st.st_mode&S_IFMT) == S_IFREG) {
1337 			if (dout == NULL) {
1338 				dout = dataconn("file list", (off_t)-1, "w");
1339 				if (dout == NULL)
1340 					return;
1341 				transflag++;
1342 			}
1343 			fprintf(dout, "%s%s\n", dirname,
1344 				type == TYPE_A ? "\r" : "");
1345 			byte_count += strlen(dirname) + 1;
1346 			continue;
1347 		} else if ((st.st_mode&S_IFMT) != S_IFDIR)
1348 			continue;
1349 
1350 		if ((dirp = opendir(dirname)) == NULL)
1351 			continue;
1352 
1353 		while ((dir = readdir(dirp)) != NULL) {
1354 			char nbuf[MAXPATHLEN];
1355 
1356 			if (dir->d_name[0] == '.' && dir->d_namlen == 1)
1357 				continue;
1358 			if (dir->d_name[0] == '.' && dir->d_name[1] == '.' &&
1359 			    dir->d_namlen == 2)
1360 				continue;
1361 
1362 			sprintf(nbuf, "%s/%s", dirname, dir->d_name);
1363 
1364 			/*
1365 			 * We have to do a stat to insure it's
1366 			 * not a directory or special file.
1367 			 */
1368 			if (simple || (stat(nbuf, &st) == 0 &&
1369 			    (st.st_mode&S_IFMT) == S_IFREG)) {
1370 				if (dout == NULL) {
1371 					dout = dataconn("file list", (off_t)-1,
1372 						"w");
1373 					if (dout == NULL)
1374 						return;
1375 					transflag++;
1376 				}
1377 				if (nbuf[0] == '.' && nbuf[1] == '/')
1378 					fprintf(dout, "%s%s\n", &nbuf[2],
1379 						type == TYPE_A ? "\r" : "");
1380 				else
1381 					fprintf(dout, "%s%s\n", nbuf,
1382 						type == TYPE_A ? "\r" : "");
1383 				byte_count += strlen(nbuf) + 1;
1384 			}
1385 		}
1386 		(void) closedir(dirp);
1387 	}
1388 
1389 	if (dout == NULL)
1390 		reply(550, "No files found.");
1391 	else if (ferror(dout) != 0)
1392 		perror_reply(550, "Data connection");
1393 	else
1394 		reply(226, "Transfer complete.");
1395 
1396 	transflag = 0;
1397 	if (dout != NULL)
1398 		(void) fclose(dout);
1399 	data = -1;
1400 	pdata = -1;
1401 }
1402 
1403 #ifdef SETPROCTITLE
1404 /*
1405  * clobber argv so ps will show what we're doing.
1406  * (stolen from sendmail)
1407  * warning, since this is usually started from inetd.conf, it
1408  * often doesn't have much of an environment or arglist to overwrite.
1409  */
1410 
1411 /*VARARGS1*/
1412 setproctitle(fmt, a, b, c)
1413 char *fmt;
1414 {
1415 	register char *p, *bp, ch;
1416 	register int i;
1417 	char buf[BUFSIZ];
1418 
1419 	(void) sprintf(buf, fmt, a, b, c);
1420 
1421 	/* make ps print our process name */
1422 	p = Argv[0];
1423 	*p++ = '-';
1424 
1425 	i = strlen(buf);
1426 	if (i > LastArgv - p - 2) {
1427 		i = LastArgv - p - 2;
1428 		buf[i] = '\0';
1429 	}
1430 	bp = buf;
1431 	while (ch = *bp++)
1432 		if (ch != '\n' && ch != '\r')
1433 			*p++ = ch;
1434 	while (p < LastArgv)
1435 		*p++ = ' ';
1436 }
1437 #endif /* SETPROCTITLE */
1438