xref: /original-bsd/libexec/tftpd/tftpd.c (revision a51a1dd1)
1 /*
2  * Copyright (c) 1983, 1993 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) 1983, 1993 Regents of the University of California.\n\
11  All rights reserved.\n";
12 #endif /* not lint */
13 
14 #ifndef lint
15 static char sccsid[] = "@(#)tftpd.c	5.15 (Berkeley) 05/16/93";
16 #endif /* not lint */
17 
18 /*
19  * Trivial file transfer protocol server.
20  *
21  * This version includes many modifications by Jim Guyton
22  * <guyton@rand-unix>.
23  */
24 
25 #include <sys/param.h>
26 #include <sys/ioctl.h>
27 #include <sys/stat.h>
28 #include <sys/socket.h>
29 
30 #include <netinet/in.h>
31 #include <arpa/tftp.h>
32 #include <arpa/inet.h>
33 
34 #include <ctype.h>
35 #include <errno.h>
36 #include <fcntl.h>
37 #include <netdb.h>
38 #include <setjmp.h>
39 #include <signal.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <syslog.h>
44 #include <unistd.h>
45 
46 #include "tftpsubs.h"
47 #include "pathnames.h"
48 
49 #define	TIMEOUT		5
50 
51 int	peer;
52 int	rexmtval = TIMEOUT;
53 int	maxtimeout = 5*TIMEOUT;
54 
55 #define	PKTSIZE	SEGSIZE+4
56 char	buf[PKTSIZE];
57 char	ackbuf[PKTSIZE];
58 struct	sockaddr_in from;
59 int	fromlen;
60 
61 void	tftp __P((struct tftphdr *, int));
62 
63 /*
64  * Null-terminated directory prefix list for absolute pathname requests and
65  * search list for relative pathname requests.
66  *
67  * MAXDIRS should be at least as large as the number of arguments that
68  * inetd allows (currently 20).
69  */
70 #define MAXDIRS	20
71 static struct dirlist {
72 	char	*name;
73 	int	len;
74 } dirs[MAXDIRS+1];
75 static int	suppress_naks;
76 static int	logging;
77 
78 static char *errtomsg __P((int));
79 static void  nak __P((int));
80 static char *verifyhost __P((struct sockaddr_in *));
81 
82 int
83 main(argc, argv)
84 	int argc;
85 	char *argv[];
86 {
87 	register struct tftphdr *tp;
88 	register int n;
89 	int ch, on;
90 	struct sockaddr_in sin;
91 
92 	openlog("tftpd", LOG_PID, LOG_FTP);
93 	while ((ch = getopt(argc, argv, "ln")) != EOF) {
94 		switch (ch) {
95 		case 'l':
96 			logging = 1;
97 			break;
98 		case 'n':
99 			suppress_naks = 1;
100 			break;
101 		default:
102 			syslog(LOG_WARNING, "ignoring unknown option -%c", ch);
103 		}
104 	}
105 	if (optind < argc) {
106 		struct dirlist *dirp;
107 
108 		/* Get list of directory prefixes. Skip relative pathnames. */
109 		for (dirp = dirs; optind < argc && dirp < &dirs[MAXDIRS];
110 		     optind++) {
111 			if (argv[optind][0] == '/') {
112 				dirp->name = argv[optind];
113 				dirp->len  = strlen(dirp->name);
114 				dirp++;
115 			}
116 		}
117 	}
118 
119 	on = 1;
120 	if (ioctl(0, FIONBIO, &on) < 0) {
121 		syslog(LOG_ERR, "ioctl(FIONBIO): %m\n");
122 		exit(1);
123 	}
124 	fromlen = sizeof (from);
125 	n = recvfrom(0, buf, sizeof (buf), 0,
126 	    (struct sockaddr *)&from, &fromlen);
127 	if (n < 0) {
128 		syslog(LOG_ERR, "recvfrom: %m\n");
129 		exit(1);
130 	}
131 	/*
132 	 * Now that we have read the message out of the UDP
133 	 * socket, we fork and exit.  Thus, inetd will go back
134 	 * to listening to the tftp port, and the next request
135 	 * to come in will start up a new instance of tftpd.
136 	 *
137 	 * We do this so that inetd can run tftpd in "wait" mode.
138 	 * The problem with tftpd running in "nowait" mode is that
139 	 * inetd may get one or more successful "selects" on the
140 	 * tftp port before we do our receive, so more than one
141 	 * instance of tftpd may be started up.  Worse, if tftpd
142 	 * break before doing the above "recvfrom", inetd would
143 	 * spawn endless instances, clogging the system.
144 	 */
145 	{
146 		int pid;
147 		int i, j;
148 
149 		for (i = 1; i < 20; i++) {
150 		    pid = fork();
151 		    if (pid < 0) {
152 				sleep(i);
153 				/*
154 				 * flush out to most recently sent request.
155 				 *
156 				 * This may drop some request, but those
157 				 * will be resent by the clients when
158 				 * they timeout.  The positive effect of
159 				 * this flush is to (try to) prevent more
160 				 * than one tftpd being started up to service
161 				 * a single request from a single client.
162 				 */
163 				j = sizeof from;
164 				i = recvfrom(0, buf, sizeof (buf), 0,
165 				    (struct sockaddr *)&from, &j);
166 				if (i > 0) {
167 					n = i;
168 					fromlen = j;
169 				}
170 		    } else {
171 				break;
172 		    }
173 		}
174 		if (pid < 0) {
175 			syslog(LOG_ERR, "fork: %m\n");
176 			exit(1);
177 		} else if (pid != 0) {
178 			exit(0);
179 		}
180 	}
181 	from.sin_family = AF_INET;
182 	alarm(0);
183 	close(0);
184 	close(1);
185 	peer = socket(AF_INET, SOCK_DGRAM, 0);
186 	if (peer < 0) {
187 		syslog(LOG_ERR, "socket: %m\n");
188 		exit(1);
189 	}
190 	memset(&sin, 0, sizeof(sin));
191 	sin.sin_family = AF_INET;
192 	if (bind(peer, (struct sockaddr *)&sin, sizeof (sin)) < 0) {
193 		syslog(LOG_ERR, "bind: %m\n");
194 		exit(1);
195 	}
196 	if (connect(peer, (struct sockaddr *)&from, sizeof(from)) < 0) {
197 		syslog(LOG_ERR, "connect: %m\n");
198 		exit(1);
199 	}
200 	tp = (struct tftphdr *)buf;
201 	tp->th_opcode = ntohs(tp->th_opcode);
202 	if (tp->th_opcode == RRQ || tp->th_opcode == WRQ)
203 		tftp(tp, n);
204 	exit(1);
205 }
206 
207 struct formats;
208 int	validate_access __P((char **, int));
209 void	sendfile __P((struct formats *));
210 void	recvfile __P((struct formats *));
211 
212 struct formats {
213 	char	*f_mode;
214 	int	(*f_validate) __P((char **, int));
215 	void	(*f_send) __P((struct formats *));
216 	void	(*f_recv) __P((struct formats *));
217 	int	f_convert;
218 } formats[] = {
219 	{ "netascii",	validate_access,	sendfile,	recvfile, 1 },
220 	{ "octet",	validate_access,	sendfile,	recvfile, 0 },
221 #ifdef notdef
222 	{ "mail",	validate_user,		sendmail,	recvmail, 1 },
223 #endif
224 	{ 0 }
225 };
226 
227 /*
228  * Handle initial connection protocol.
229  */
230 void
231 tftp(tp, size)
232 	struct tftphdr *tp;
233 	int size;
234 {
235 	register char *cp;
236 	int first = 1, ecode;
237 	register struct formats *pf;
238 	char *filename, *mode;
239 
240 	filename = cp = tp->th_stuff;
241 again:
242 	while (cp < buf + size) {
243 		if (*cp == '\0')
244 			break;
245 		cp++;
246 	}
247 	if (*cp != '\0') {
248 		nak(EBADOP);
249 		exit(1);
250 	}
251 	if (first) {
252 		mode = ++cp;
253 		first = 0;
254 		goto again;
255 	}
256 	for (cp = mode; *cp; cp++)
257 		if (isupper(*cp))
258 			*cp = tolower(*cp);
259 	for (pf = formats; pf->f_mode; pf++)
260 		if (strcmp(pf->f_mode, mode) == 0)
261 			break;
262 	if (pf->f_mode == 0) {
263 		nak(EBADOP);
264 		exit(1);
265 	}
266 	ecode = (*pf->f_validate)(&filename, tp->th_opcode);
267 	if (logging) {
268 		syslog(LOG_INFO, "%s: %s request for %s: %s",
269 			verifyhost(&from),
270 			tp->th_opcode == WRQ ? "write" : "read",
271 			filename, errtomsg(ecode));
272 	}
273 	if (ecode) {
274 		/*
275 		 * Avoid storms of naks to a RRQ broadcast for a relative
276 		 * bootfile pathname from a diskless Sun.
277 		 */
278 		if (suppress_naks && *filename != '/' && ecode == ENOTFOUND)
279 			exit(0);
280 		nak(ecode);
281 		exit(1);
282 	}
283 	if (tp->th_opcode == WRQ)
284 		(*pf->f_recv)(pf);
285 	else
286 		(*pf->f_send)(pf);
287 	exit(0);
288 }
289 
290 
291 FILE *file;
292 
293 /*
294  * Validate file access.  Since we
295  * have no uid or gid, for now require
296  * file to exist and be publicly
297  * readable/writable.
298  * If we were invoked with arguments
299  * from inetd then the file must also be
300  * in one of the given directory prefixes.
301  * Note also, full path name must be
302  * given as we have no login directory.
303  */
304 int
305 validate_access(filep, mode)
306 	char **filep;
307 	int mode;
308 {
309 	struct stat stbuf;
310 	int	fd;
311 	struct dirlist *dirp;
312 	static char pathname[MAXPATHLEN];
313 	char *filename = *filep;
314 
315 	/*
316 	 * Prevent tricksters from getting around the directory restrictions
317 	 */
318 	if (strstr(filename, "/../"))
319 		return (EACCESS);
320 
321 	if (*filename == '/') {
322 		/*
323 		 * Allow the request if it's in one of the approved locations.
324 		 * Special case: check the null prefix ("/") by looking
325 		 * for length = 1 and relying on the arg. processing that
326 		 * it's a /.
327 		 */
328 		for (dirp = dirs; dirp->name != NULL; dirp++) {
329 			if (dirp->len == 1 ||
330 			    (!strncmp(filename, dirp->name, dirp->len) &&
331 			     filename[dirp->len] == '/'))
332 				    break;
333 		}
334 		/* If directory list is empty, allow access to any file */
335 		if (dirp->name == NULL && dirp != dirs)
336 			return (EACCESS);
337 		if (stat(filename, &stbuf) < 0)
338 			return (errno == ENOENT ? ENOTFOUND : EACCESS);
339 		if ((stbuf.st_mode & S_IFMT) != S_IFREG)
340 			return (ENOTFOUND);
341 		if (mode == RRQ) {
342 			if ((stbuf.st_mode & S_IROTH) == 0)
343 				return (EACCESS);
344 		} else {
345 			if ((stbuf.st_mode & S_IWOTH) == 0)
346 				return (EACCESS);
347 		}
348 	} else {
349 		int err;
350 
351 		/*
352 		 * Relative file name: search the approved locations for it.
353 		 * Don't allow write requests or ones that avoid directory
354 		 * restrictions.
355 		 */
356 
357 		if (mode != RRQ || !strncmp(filename, "../", 3))
358 			return (EACCESS);
359 
360 		/*
361 		 * If the file exists in one of the directories and isn't
362 		 * readable, continue looking. However, change the error code
363 		 * to give an indication that the file exists.
364 		 */
365 		err = ENOTFOUND;
366 		for (dirp = dirs; dirp->name != NULL; dirp++) {
367 			sprintf(pathname, "%s/%s", dirp->name, filename);
368 			if (stat(pathname, &stbuf) == 0 &&
369 			    (stbuf.st_mode & S_IFMT) == S_IFREG) {
370 				if ((stbuf.st_mode & S_IROTH) != 0) {
371 					break;
372 				}
373 				err = EACCESS;
374 			}
375 		}
376 		if (dirp->name == NULL)
377 			return (err);
378 		*filep = filename = pathname;
379 	}
380 	fd = open(filename, mode == RRQ ? 0 : 1);
381 	if (fd < 0)
382 		return (errno + 100);
383 	file = fdopen(fd, (mode == RRQ)? "r":"w");
384 	if (file == NULL) {
385 		return errno+100;
386 	}
387 	return (0);
388 }
389 
390 int	timeout;
391 jmp_buf	timeoutbuf;
392 
393 void
394 timer()
395 {
396 
397 	timeout += rexmtval;
398 	if (timeout >= maxtimeout)
399 		exit(1);
400 	longjmp(timeoutbuf, 1);
401 }
402 
403 /*
404  * Send the requested file.
405  */
406 void
407 sendfile(pf)
408 	struct formats *pf;
409 {
410 	struct tftphdr *dp, *r_init();
411 	register struct tftphdr *ap;    /* ack packet */
412 	register int size, n;
413 	volatile int block;
414 
415 	signal(SIGALRM, timer);
416 	dp = r_init();
417 	ap = (struct tftphdr *)ackbuf;
418 	block = 1;
419 	do {
420 		size = readit(file, &dp, pf->f_convert);
421 		if (size < 0) {
422 			nak(errno + 100);
423 			goto abort;
424 		}
425 		dp->th_opcode = htons((u_short)DATA);
426 		dp->th_block = htons((u_short)block);
427 		timeout = 0;
428 		(void)setjmp(timeoutbuf);
429 
430 send_data:
431 		if (send(peer, dp, size + 4, 0) != size + 4) {
432 			syslog(LOG_ERR, "tftpd: write: %m\n");
433 			goto abort;
434 		}
435 		read_ahead(file, pf->f_convert);
436 		for ( ; ; ) {
437 			alarm(rexmtval);        /* read the ack */
438 			n = recv(peer, ackbuf, sizeof (ackbuf), 0);
439 			alarm(0);
440 			if (n < 0) {
441 				syslog(LOG_ERR, "tftpd: read: %m\n");
442 				goto abort;
443 			}
444 			ap->th_opcode = ntohs((u_short)ap->th_opcode);
445 			ap->th_block = ntohs((u_short)ap->th_block);
446 
447 			if (ap->th_opcode == ERROR)
448 				goto abort;
449 
450 			if (ap->th_opcode == ACK) {
451 				if (ap->th_block == block)
452 					break;
453 				/* Re-synchronize with the other side */
454 				(void) synchnet(peer);
455 				if (ap->th_block == (block -1))
456 					goto send_data;
457 			}
458 
459 		}
460 		block++;
461 	} while (size == SEGSIZE);
462 abort:
463 	(void) fclose(file);
464 }
465 
466 void
467 justquit()
468 {
469 	exit(0);
470 }
471 
472 
473 /*
474  * Receive a file.
475  */
476 void
477 recvfile(pf)
478 	struct formats *pf;
479 {
480 	struct tftphdr *dp, *w_init();
481 	register struct tftphdr *ap;    /* ack buffer */
482 	register int n, size;
483 	volatile int block;
484 
485 	signal(SIGALRM, timer);
486 	dp = w_init();
487 	ap = (struct tftphdr *)ackbuf;
488 	block = 0;
489 	do {
490 		timeout = 0;
491 		ap->th_opcode = htons((u_short)ACK);
492 		ap->th_block = htons((u_short)block);
493 		block++;
494 		(void) setjmp(timeoutbuf);
495 send_ack:
496 		if (send(peer, ackbuf, 4, 0) != 4) {
497 			syslog(LOG_ERR, "tftpd: write: %m\n");
498 			goto abort;
499 		}
500 		write_behind(file, pf->f_convert);
501 		for ( ; ; ) {
502 			alarm(rexmtval);
503 			n = recv(peer, dp, PKTSIZE, 0);
504 			alarm(0);
505 			if (n < 0) {            /* really? */
506 				syslog(LOG_ERR, "tftpd: read: %m\n");
507 				goto abort;
508 			}
509 			dp->th_opcode = ntohs((u_short)dp->th_opcode);
510 			dp->th_block = ntohs((u_short)dp->th_block);
511 			if (dp->th_opcode == ERROR)
512 				goto abort;
513 			if (dp->th_opcode == DATA) {
514 				if (dp->th_block == block) {
515 					break;   /* normal */
516 				}
517 				/* Re-synchronize with the other side */
518 				(void) synchnet(peer);
519 				if (dp->th_block == (block-1))
520 					goto send_ack;          /* rexmit */
521 			}
522 		}
523 		/*  size = write(file, dp->th_data, n - 4); */
524 		size = writeit(file, &dp, n - 4, pf->f_convert);
525 		if (size != (n-4)) {                    /* ahem */
526 			if (size < 0) nak(errno + 100);
527 			else nak(ENOSPACE);
528 			goto abort;
529 		}
530 	} while (size == SEGSIZE);
531 	write_behind(file, pf->f_convert);
532 	(void) fclose(file);            /* close data file */
533 
534 	ap->th_opcode = htons((u_short)ACK);    /* send the "final" ack */
535 	ap->th_block = htons((u_short)(block));
536 	(void) send(peer, ackbuf, 4, 0);
537 
538 	signal(SIGALRM, justquit);      /* just quit on timeout */
539 	alarm(rexmtval);
540 	n = recv(peer, buf, sizeof (buf), 0); /* normally times out and quits */
541 	alarm(0);
542 	if (n >= 4 &&                   /* if read some data */
543 	    dp->th_opcode == DATA &&    /* and got a data block */
544 	    block == dp->th_block) {	/* then my last ack was lost */
545 		(void) send(peer, ackbuf, 4, 0);     /* resend final ack */
546 	}
547 abort:
548 	return;
549 }
550 
551 struct errmsg {
552 	int	e_code;
553 	char	*e_msg;
554 } errmsgs[] = {
555 	{ EUNDEF,	"Undefined error code" },
556 	{ ENOTFOUND,	"File not found" },
557 	{ EACCESS,	"Access violation" },
558 	{ ENOSPACE,	"Disk full or allocation exceeded" },
559 	{ EBADOP,	"Illegal TFTP operation" },
560 	{ EBADID,	"Unknown transfer ID" },
561 	{ EEXISTS,	"File already exists" },
562 	{ ENOUSER,	"No such user" },
563 	{ -1,		0 }
564 };
565 
566 static char *
567 errtomsg(error)
568 	int error;
569 {
570 	static char buf[20];
571 	register struct errmsg *pe;
572 	if (error == 0)
573 		return "success";
574 	for (pe = errmsgs; pe->e_code >= 0; pe++)
575 		if (pe->e_code == error)
576 			return pe->e_msg;
577 	sprintf(buf, "error %d", error);
578 	return buf;
579 }
580 
581 /*
582  * Send a nak packet (error message).
583  * Error code passed in is one of the
584  * standard TFTP codes, or a UNIX errno
585  * offset by 100.
586  */
587 static void
588 nak(error)
589 	int error;
590 {
591 	register struct tftphdr *tp;
592 	int length;
593 	register struct errmsg *pe;
594 
595 	tp = (struct tftphdr *)buf;
596 	tp->th_opcode = htons((u_short)ERROR);
597 	tp->th_code = htons((u_short)error);
598 	for (pe = errmsgs; pe->e_code >= 0; pe++)
599 		if (pe->e_code == error)
600 			break;
601 	if (pe->e_code < 0) {
602 		pe->e_msg = strerror(error - 100);
603 		tp->th_code = EUNDEF;   /* set 'undef' errorcode */
604 	}
605 	strcpy(tp->th_msg, pe->e_msg);
606 	length = strlen(pe->e_msg);
607 	tp->th_msg[length] = '\0';
608 	length += 5;
609 	if (send(peer, buf, length, 0) != length)
610 		syslog(LOG_ERR, "nak: %m\n");
611 }
612 
613 static char *
614 verifyhost(fromp)
615 	struct sockaddr_in *fromp;
616 {
617 	struct hostent *hp;
618 
619 	hp = gethostbyaddr((char *)&fromp->sin_addr, sizeof (fromp->sin_addr),
620 			    fromp->sin_family);
621 	if (hp)
622 		return hp->h_name;
623 	else
624 		return inet_ntoa(fromp->sin_addr);
625 }
626