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