xref: /netbsd-src/libexec/tftpd/tftpd.c (revision d48f14661dda8638fee055ba15d35bdfb29b9fa8)
1 /*	$NetBSD: tftpd.c,v 1.30 2006/05/09 20:18:07 mrg Exp $	*/
2 
3 /*
4  * Copyright (c) 1983, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #include <sys/cdefs.h>
33 #ifndef lint
34 __COPYRIGHT("@(#) Copyright (c) 1983, 1993\n\
35 	The Regents of the University of California.  All rights reserved.\n");
36 #if 0
37 static char sccsid[] = "@(#)tftpd.c	8.1 (Berkeley) 6/4/93";
38 #else
39 __RCSID("$NetBSD: tftpd.c,v 1.30 2006/05/09 20:18:07 mrg Exp $");
40 #endif
41 #endif /* not lint */
42 
43 /*
44  * Trivial file transfer protocol server.
45  *
46  * This version includes many modifications by Jim Guyton
47  * <guyton@rand-unix>.
48  */
49 
50 #include <sys/param.h>
51 #include <sys/ioctl.h>
52 #include <sys/stat.h>
53 #include <sys/socket.h>
54 
55 #include <netinet/in.h>
56 #include <arpa/tftp.h>
57 #include <arpa/inet.h>
58 
59 #include <ctype.h>
60 #include <errno.h>
61 #include <fcntl.h>
62 #include <grp.h>
63 #include <netdb.h>
64 #include <pwd.h>
65 #include <setjmp.h>
66 #include <signal.h>
67 #include <stdio.h>
68 #include <stdlib.h>
69 #include <string.h>
70 #include <syslog.h>
71 #include <time.h>
72 #include <unistd.h>
73 
74 #include "tftpsubs.h"
75 
76 #define	DEFAULTUSER	"nobody"
77 
78 #define	TIMEOUT		5
79 
80 int	peer;
81 int	rexmtval = TIMEOUT;
82 int	maxtimeout = 5*TIMEOUT;
83 
84 char	buf[MAXPKTSIZE];
85 char	ackbuf[PKTSIZE];
86 char	oackbuf[PKTSIZE];
87 struct	sockaddr_storage from;
88 socklen_t	fromlen;
89 int	debug;
90 
91 int	tftp_opt_tsize = 0;
92 int	tftp_blksize = SEGSIZE;
93 int	tftp_tsize = 0;
94 
95 /*
96  * Null-terminated directory prefix list for absolute pathname requests and
97  * search list for relative pathname requests.
98  *
99  * MAXDIRS should be at least as large as the number of arguments that
100  * inetd allows (currently 20).
101  */
102 #define MAXDIRS	20
103 static struct dirlist {
104 	char	*name;
105 	int	len;
106 } dirs[MAXDIRS+1];
107 static int	suppress_naks;
108 static int	logging;
109 static int	secure;
110 static char	*securedir;
111 
112 struct formats;
113 
114 static const char *errtomsg(int);
115 static void	 nak(int);
116 static void	 tftp(struct tftphdr *, int);
117 static void	 usage(void);
118 static char	*verifyhost(struct sockaddr *);
119 void	justquit(int);
120 int	main(int, char **);
121 void	recvfile(struct formats *, int, int);
122 void	sendfile(struct formats *, int, int);
123 void	timer(int);
124 static const char *opcode(int);
125 int	validate_access(char **, int);
126 
127 struct formats {
128 	const char	*f_mode;
129 	int		(*f_validate)(char **, int);
130 	void		(*f_send)(struct formats *, int, int);
131 	void		(*f_recv)(struct formats *, int, int);
132 	int		f_convert;
133 } formats[] = {
134 	{ "netascii",	validate_access,	sendfile,	recvfile, 1 },
135 	{ "octet",	validate_access,	sendfile,	recvfile, 0 },
136 	{ 0 }
137 };
138 
139 static void
140 usage(void)
141 {
142 
143 	syslog(LOG_ERR,
144     "Usage: %s [-dln] [-u user] [-g group] [-s directory] [directory ...]",
145 		    getprogname());
146 	exit(1);
147 }
148 
149 int
150 main(int argc, char *argv[])
151 {
152 	struct sockaddr_storage me;
153 	struct passwd	*pwent;
154 	struct group	*grent;
155 	struct tftphdr	*tp;
156 	char		*tgtuser, *tgtgroup, *ep;
157 	int	n, ch, on, fd;
158 	int	soopt;
159 	socklen_t len;
160 	uid_t	curuid, tgtuid;
161 	gid_t	curgid, tgtgid;
162 	long	nid;
163 
164 	n = 0;
165 	fd = 0;
166 	tzset();
167 	openlog("tftpd", LOG_PID | LOG_NDELAY, LOG_DAEMON);
168 	tgtuser = DEFAULTUSER;
169 	tgtgroup = NULL;
170 	curuid = getuid();
171 	curgid = getgid();
172 
173 	while ((ch = getopt(argc, argv, "dg:lns:u:")) != -1)
174 		switch (ch) {
175 		case 'd':
176 			debug++;
177 			break;
178 
179 		case 'g':
180 			tgtgroup = optarg;
181 			break;
182 
183 		case 'l':
184 			logging = 1;
185 			break;
186 
187 		case 'n':
188 			suppress_naks = 1;
189 			break;
190 
191 		case 's':
192 			secure = 1;
193 			securedir = optarg;
194 			break;
195 
196 		case 'u':
197 			tgtuser = optarg;
198 			break;
199 
200 		default:
201 			usage();
202 			break;
203 		}
204 
205 	if (optind < argc) {
206 		struct dirlist *dirp;
207 
208 		/* Get list of directory prefixes. Skip relative pathnames. */
209 		for (dirp = dirs; optind < argc && dirp < &dirs[MAXDIRS];
210 		     optind++) {
211 			if (argv[optind][0] == '/') {
212 				dirp->name = argv[optind];
213 				dirp->len  = strlen(dirp->name);
214 				dirp++;
215 			}
216 		}
217 	}
218 
219 	if (*tgtuser == '\0' || (tgtgroup != NULL && *tgtgroup == '\0'))
220 		usage();
221 
222 	nid = (strtol(tgtuser, &ep, 10));
223 	if (*ep == '\0') {
224 		if (nid > UID_MAX) {
225 			syslog(LOG_ERR, "uid %ld is too large", nid);
226 			exit(1);
227 		}
228 		pwent = getpwuid((uid_t)nid);
229 	} else
230 		pwent = getpwnam(tgtuser);
231 	if (pwent == NULL) {
232 		syslog(LOG_ERR, "unknown user `%s'", tgtuser);
233 		exit(1);
234 	}
235 	tgtuid = pwent->pw_uid;
236 	tgtgid = pwent->pw_gid;
237 
238 	if (tgtgroup != NULL) {
239 		nid = (strtol(tgtgroup, &ep, 10));
240 		if (*ep == '\0') {
241 			if (nid > GID_MAX) {
242 				syslog(LOG_ERR, "gid %ld is too large", nid);
243 				exit(1);
244 			}
245 			grent = getgrgid((gid_t)nid);
246 		} else
247 			grent = getgrnam(tgtgroup);
248 		if (grent != NULL)
249 			tgtgid = grent->gr_gid;
250 		else {
251 			syslog(LOG_ERR, "unknown group `%s'", tgtgroup);
252 			exit(1);
253 		}
254 	}
255 
256 	if (secure) {
257 		if (chdir(securedir) < 0) {
258 			syslog(LOG_ERR, "chdir %s: %m", securedir);
259 			exit(1);
260 		}
261 		if (chroot(".")) {
262 			syslog(LOG_ERR, "chroot: %m");
263 			exit(1);
264 		}
265 	}
266 
267 	if (logging)
268 		syslog(LOG_DEBUG, "running as user `%s' (%d), group `%s' (%d)",
269 		    tgtuser, tgtuid, tgtgroup ? tgtgroup : "(unspecified)",
270 		    tgtgid);
271 	if (curgid != tgtgid) {
272 		if (setgid(tgtgid)) {
273 			syslog(LOG_ERR, "setgid to %d: %m", (int)tgtgid);
274 			exit(1);
275 		}
276 		if (setgroups(0, NULL)) {
277 			syslog(LOG_ERR, "setgroups: %m");
278 			exit(1);
279 		}
280 	}
281 
282 	if (curuid != tgtuid) {
283 		if (setuid(tgtuid)) {
284 			syslog(LOG_ERR, "setuid to %d: %m", (int)tgtuid);
285 			exit(1);
286 		}
287 	}
288 
289 	on = 1;
290 	if (ioctl(fd, FIONBIO, &on) < 0) {
291 		syslog(LOG_ERR, "ioctl(FIONBIO): %m");
292 		exit(1);
293 	}
294 	fromlen = sizeof (from);
295 	n = recvfrom(fd, buf, sizeof (buf), 0,
296 	    (struct sockaddr *)&from, &fromlen);
297 	if (n < 0) {
298 		syslog(LOG_ERR, "recvfrom: %m");
299 		exit(1);
300 	}
301 	/*
302 	 * Now that we have read the message out of the UDP
303 	 * socket, we fork and exit.  Thus, inetd will go back
304 	 * to listening to the tftp port, and the next request
305 	 * to come in will start up a new instance of tftpd.
306 	 *
307 	 * We do this so that inetd can run tftpd in "wait" mode.
308 	 * The problem with tftpd running in "nowait" mode is that
309 	 * inetd may get one or more successful "selects" on the
310 	 * tftp port before we do our receive, so more than one
311 	 * instance of tftpd may be started up.  Worse, if tftpd
312 	 * break before doing the above "recvfrom", inetd would
313 	 * spawn endless instances, clogging the system.
314 	 */
315 	{
316 		int pid;
317 		int i;
318 		socklen_t j;
319 
320 		for (i = 1; i < 20; i++) {
321 		    pid = fork();
322 		    if (pid < 0) {
323 				sleep(i);
324 				/*
325 				 * flush out to most recently sent request.
326 				 *
327 				 * This may drop some request, but those
328 				 * will be resent by the clients when
329 				 * they timeout.  The positive effect of
330 				 * this flush is to (try to) prevent more
331 				 * than one tftpd being started up to service
332 				 * a single request from a single client.
333 				 */
334 				j = sizeof from;
335 				i = recvfrom(fd, buf, sizeof (buf), 0,
336 				    (struct sockaddr *)&from, &j);
337 				if (i > 0) {
338 					n = i;
339 					fromlen = j;
340 				}
341 		    } else {
342 				break;
343 		    }
344 		}
345 		if (pid < 0) {
346 			syslog(LOG_ERR, "fork: %m");
347 			exit(1);
348 		} else if (pid != 0) {
349 			exit(0);
350 		}
351 	}
352 
353 	/*
354 	 * remember what address this was sent to, so we can respond on the
355 	 * same interface
356 	 */
357 	len = sizeof(me);
358 	if (getsockname(fd, (struct sockaddr *)&me, &len) == 0) {
359 		switch (me.ss_family) {
360 		case AF_INET:
361 			((struct sockaddr_in *)&me)->sin_port = 0;
362 			break;
363 		case AF_INET6:
364 			((struct sockaddr_in6 *)&me)->sin6_port = 0;
365 			break;
366 		default:
367 			/* unsupported */
368 			break;
369 		}
370 	} else {
371 		memset(&me, 0, sizeof(me));
372 		me.ss_family = from.ss_family;
373 		me.ss_len = from.ss_len;
374 	}
375 
376 	alarm(0);
377 	close(fd);
378 	close(1);
379 	peer = socket(from.ss_family, SOCK_DGRAM, 0);
380 	if (peer < 0) {
381 		syslog(LOG_ERR, "socket: %m");
382 		exit(1);
383 	}
384 	if (bind(peer, (struct sockaddr *)&me, me.ss_len) < 0) {
385 		syslog(LOG_ERR, "bind: %m");
386 		exit(1);
387 	}
388 	if (connect(peer, (struct sockaddr *)&from, from.ss_len) < 0) {
389 		syslog(LOG_ERR, "connect: %m");
390 		exit(1);
391 	}
392 	soopt = 65536;	/* larger than we'll ever need */
393 	if (setsockopt(peer, SOL_SOCKET, SO_SNDBUF, (void *) &soopt, sizeof(soopt)) < 0) {
394 		syslog(LOG_ERR, "set SNDBUF: %m");
395 		exit(1);
396 	}
397 	if (setsockopt(peer, SOL_SOCKET, SO_RCVBUF, (void *) &soopt, sizeof(soopt)) < 0) {
398 		syslog(LOG_ERR, "set RCVBUF: %m");
399 		exit(1);
400 	}
401 
402 	tp = (struct tftphdr *)buf;
403 	tp->th_opcode = ntohs(tp->th_opcode);
404 	if (tp->th_opcode == RRQ || tp->th_opcode == WRQ)
405 		tftp(tp, n);
406 	exit(1);
407 }
408 
409 static int
410 blk_handler(struct tftphdr *tp, char *opt, char *val, char *ack,
411 	    int *ackl, int *ec)
412 {
413 	unsigned long bsize;
414 	char *endp;
415 	int l;
416 
417 	/*
418 	 * On these failures, we could just ignore the blocksize option.
419 	 * Perhaps that should be a command-line option.
420 	 */
421 	errno = 0;
422 	bsize = strtoul(val, &endp, 10);
423 	if ((bsize == ULONG_MAX && errno == ERANGE) || *endp) {
424 		syslog(LOG_NOTICE, "%s: %s request for %s: "
425 			"illegal value %s for blksize option",
426 			verifyhost((struct sockaddr *)&from),
427 			tp->th_opcode == WRQ ? "write" : "read",
428 			tp->th_stuff, val);
429 		return 0;
430 	}
431 	if (bsize < 8 || bsize > 65464) {
432 		syslog(LOG_NOTICE, "%s: %s request for %s: "
433 			"out of range value %s for blksize option",
434 			verifyhost((struct sockaddr *)&from),
435 			tp->th_opcode == WRQ ? "write" : "read",
436 			tp->th_stuff, val);
437 		return 0;
438 	}
439 
440 	tftp_blksize = bsize;
441 	strcpy(ack + *ackl, "blksize");
442 	*ackl += 8;
443 	l = sprintf(ack + *ackl, "%lu", bsize);
444 	*ackl += l + 1;
445 
446 	return 0;
447 }
448 
449 static int
450 timeout_handler(struct tftphdr *tp, char *opt, char *val, char *ack,
451 		int *ackl, int *ec)
452 {
453 	unsigned long tout;
454 	char *endp;
455 	int l;
456 
457 	errno = 0;
458 	tout = strtoul(val, &endp, 10);
459 	if ((tout == ULONG_MAX && errno == ERANGE) || *endp) {
460 		syslog(LOG_NOTICE, "%s: %s request for %s: "
461 			"illegal value %s for timeout option",
462 			verifyhost((struct sockaddr *)&from),
463 			tp->th_opcode == WRQ ? "write" : "read",
464 			tp->th_stuff, val);
465 		return 0;
466 	}
467 	if (tout < 1 || tout > 255) {
468 		syslog(LOG_NOTICE, "%s: %s request for %s: "
469 			"out of range value %s for timeout option",
470 			verifyhost((struct sockaddr *)&from),
471 			tp->th_opcode == WRQ ? "write" : "read",
472 			tp->th_stuff, val);
473 		return 0;
474 	}
475 
476 	rexmtval = tout;
477 	strcpy(ack + *ackl, "timeout");
478 	*ackl += 8;
479 	l = sprintf(ack + *ackl, "%lu", tout);
480 	*ackl += l + 1;
481 
482 	/*
483 	 * Arbitrarily pick a maximum timeout on a request to 3
484 	 * retransmissions if the interval timeout is more than
485 	 * one minute.  Longest possible timeout is therefore
486 	 * 3 * 255 - 1, or 764 seconds.
487 	 */
488 	if (rexmtval > 60) {
489 		maxtimeout = rexmtval * 3;
490 	} else {
491 		maxtimeout = rexmtval * 5;
492 	}
493 
494 	return 0;
495 }
496 
497 static int
498 tsize_handler(struct tftphdr *tp, char *opt, char *val, char *ack,
499 	      int *ackl, int *ec)
500 {
501 	unsigned long fsize;
502 	char *endp;
503 
504 	/*
505 	 * Maximum file even with extended tftp is 65535 blocks of
506 	 * length 65464, or 4290183240 octets (4784056 less than 2^32).
507 	 * unsigned long is at least 32 bits on all NetBSD archs.
508 	 */
509 
510 	errno = 0;
511 	fsize = strtoul(val, &endp, 10);
512 	if ((fsize == ULONG_MAX && errno == ERANGE) || *endp) {
513 		syslog(LOG_NOTICE, "%s: %s request for %s: "
514 			"illegal value %s for tsize option",
515 			verifyhost((struct sockaddr *)&from),
516 			tp->th_opcode == WRQ ? "write" : "read",
517 			tp->th_stuff, val);
518 		return 0;
519 	}
520 	if (fsize > (unsigned long) 65535 * 65464) {
521 		syslog(LOG_NOTICE, "%s: %s request for %s: "
522 			"out of range value %s for tsize option",
523 			verifyhost((struct sockaddr *)&from),
524 			tp->th_opcode == WRQ ? "write" : "read",
525 			tp->th_stuff, val);
526 		return 0;
527 	}
528 
529 	tftp_opt_tsize = 1;
530 	tftp_tsize = fsize;
531 	/*
532 	 * We will report this later -- either replying with the fsize (WRQ)
533 	 * or replying with the actual filesize (RRQ).
534 	 */
535 
536 	return 0;
537 }
538 
539 struct tftp_options {
540 	char *o_name;
541 	int (*o_handler)(struct tftphdr *, char *, char *, char *,
542 			 int *, int *);
543 } options[] = {
544 	{ "blksize", blk_handler },
545 	{ "timeout", timeout_handler },
546 	{ "tsize", tsize_handler },
547 	{ NULL, NULL }
548 };
549 
550 /*
551  * Get options for an extended tftp session.  Stuff the ones we
552  * recognize in oackbuf.
553  */
554 static int
555 get_options(struct tftphdr *tp, char *cp, int size, char *ackb,
556     int *alen, int *err)
557 {
558 	struct tftp_options *op;
559 	char *option, *value, *endp;
560 	int r, rv=0, ec=0;
561 
562 	endp = cp + size;
563 	while (cp < endp) {
564 		option = cp;
565 		while (*cp && cp < endp) {
566 			*cp = tolower((unsigned char)*cp);
567 			cp++;
568 		}
569 		if (*cp) {
570 			/* if we have garbage at the end, just ignore it */
571 			break;
572 		}
573 		cp++;	/* skip over NUL */
574 		value = cp;
575 		while (*cp && cp < endp) {
576 			cp++;
577 		}
578 		if (*cp) {
579 			/* if we have garbage at the end, just ignore it */
580 			break;
581 		}
582 		cp++;
583 		for (op = options; op->o_name; op++) {
584 			if (strcmp(op->o_name, option) == 0)
585 				break;
586 		}
587 		if (op->o_name) {
588 			r = op->o_handler(tp, option, value, ackb, alen, &ec);
589 			if (r < 0) {
590 				rv = -1;
591 				break;
592 			}
593 			rv++;
594 		} /* else ignore unknown options */
595 	}
596 
597 	if (rv < 0)
598 		*err = ec;
599 
600 	return rv;
601 }
602 
603 /*
604  * Handle initial connection protocol.
605  */
606 static void
607 tftp(struct tftphdr *tp, int size)
608 {
609 	struct formats *pf;
610 	char	*cp;
611 	char	*filename, *mode;
612 	int	 first, ecode, alen, etftp=0, r;
613 
614 	ecode = 0;	/* XXX gcc */
615 	first = 1;
616 	mode = NULL;
617 
618 	filename = cp = tp->th_stuff;
619 again:
620 	while (cp < buf + size) {
621 		if (*cp == '\0')
622 			break;
623 		cp++;
624 	}
625 	if (*cp != '\0') {
626 		nak(EBADOP);
627 		exit(1);
628 	}
629 	if (first) {
630 		mode = ++cp;
631 		first = 0;
632 		goto again;
633 	}
634 	for (cp = mode; *cp; cp++)
635 		*cp = tolower((unsigned char)*cp);
636 	for (pf = formats; pf->f_mode; pf++)
637 		if (strcmp(pf->f_mode, mode) == 0)
638 			break;
639 	if (pf->f_mode == 0) {
640 		nak(EBADOP);
641 		exit(1);
642 	}
643 	/*
644 	 * cp currently points to the NUL byte following the mode.
645 	 *
646 	 * If we have some valid options, then let's assume that we're
647 	 * now dealing with an extended tftp session.  Note that if we
648 	 * don't get any options, then we *must* assume that we do not
649 	 * have an extended tftp session.  If we get options, we fill
650 	 * in the ack buf to acknowledge them.  If we skip that, then
651 	 * the client *must* assume that we are not using an extended
652 	 * session.
653 	 */
654 	size -= (++cp - (char *) tp);
655 	if (size > 0 && *cp) {
656 		alen = 2; /* Skip over opcode */
657 		r = get_options(tp, cp, size, oackbuf, &alen, &ecode);
658 		if (r > 0) {
659 			etftp = 1;
660 		} else if (r < 0) {
661 			nak(ecode);
662 			exit(1);
663 		}
664 	}
665 	ecode = (*pf->f_validate)(&filename, tp->th_opcode);
666 	if (logging) {
667 		syslog(LOG_INFO, "%s: %s request for %s: %s",
668 			verifyhost((struct sockaddr *)&from),
669 			tp->th_opcode == WRQ ? "write" : "read",
670 			filename, errtomsg(ecode));
671 	}
672 	if (ecode) {
673 		/*
674 		 * Avoid storms of naks to a RRQ broadcast for a relative
675 		 * bootfile pathname from a diskless Sun.
676 		 */
677 		if (suppress_naks && *filename != '/' && ecode == ENOTFOUND)
678 			exit(0);
679 		nak(ecode);
680 		exit(1);
681 	}
682 
683 	if (etftp) {
684 		struct tftphdr *oack_h;
685 
686 		if (tftp_opt_tsize) {
687 			int l;
688 
689 			strcpy(oackbuf + alen, "tsize");
690 			alen += 6;
691 			l = sprintf(oackbuf + alen, "%u", tftp_tsize);
692 			alen += l + 1;
693 		}
694 		oack_h = (struct tftphdr *) oackbuf;
695 		oack_h->th_opcode = htons(OACK);
696 	}
697 
698 	if (tp->th_opcode == WRQ)
699 		(*pf->f_recv)(pf, etftp, alen);
700 	else
701 		(*pf->f_send)(pf, etftp, alen);
702 	exit(0);
703 }
704 
705 
706 FILE *file;
707 
708 /*
709  * Validate file access.  Since we
710  * have no uid or gid, for now require
711  * file to exist and be publicly
712  * readable/writable.
713  * If we were invoked with arguments
714  * from inetd then the file must also be
715  * in one of the given directory prefixes.
716  */
717 int
718 validate_access(char **filep, int mode)
719 {
720 	struct stat	 stbuf;
721 	struct dirlist	*dirp;
722 	static char	 pathname[MAXPATHLEN];
723 	char		*filename;
724 	int		 fd;
725 
726 	filename = *filep;
727 
728 	/*
729 	 * Prevent tricksters from getting around the directory restrictions
730 	 */
731 	if (strstr(filename, "/../"))
732 		return (EACCESS);
733 
734 	if (*filename == '/') {
735 		/*
736 		 * Allow the request if it's in one of the approved locations.
737 		 * Special case: check the null prefix ("/") by looking
738 		 * for length = 1 and relying on the arg. processing that
739 		 * it's a /.
740 		 */
741 		for (dirp = dirs; dirp->name != NULL; dirp++) {
742 			if (dirp->len == 1 ||
743 			    (!strncmp(filename, dirp->name, dirp->len) &&
744 			     filename[dirp->len] == '/'))
745 				    break;
746 		}
747 		/* If directory list is empty, allow access to any file */
748 		if (dirp->name == NULL && dirp != dirs)
749 			return (EACCESS);
750 		if (stat(filename, &stbuf) < 0)
751 			return (errno == ENOENT ? ENOTFOUND : EACCESS);
752 		if (!S_ISREG(stbuf.st_mode))
753 			return (ENOTFOUND);
754 		if (mode == RRQ) {
755 			if ((stbuf.st_mode & S_IROTH) == 0)
756 				return (EACCESS);
757 		} else {
758 			if ((stbuf.st_mode & S_IWOTH) == 0)
759 				return (EACCESS);
760 		}
761 	} else {
762 		/*
763 		 * Relative file name: search the approved locations for it.
764 		 */
765 
766 		if (!strncmp(filename, "../", 3))
767 			return (EACCESS);
768 
769 		/*
770 		 * Find the first file that exists in any of the directories,
771 		 * check access on it.
772 		 */
773 		if (dirs[0].name != NULL) {
774 			for (dirp = dirs; dirp->name != NULL; dirp++) {
775 				snprintf(pathname, sizeof pathname, "%s/%s",
776 				    dirp->name, filename);
777 				if (stat(pathname, &stbuf) == 0 &&
778 				    (stbuf.st_mode & S_IFMT) == S_IFREG) {
779 					break;
780 				}
781 			}
782 			if (dirp->name == NULL)
783 				return (ENOTFOUND);
784 			if (mode == RRQ && !(stbuf.st_mode & S_IROTH))
785 				return (EACCESS);
786 			if (mode == WRQ && !(stbuf.st_mode & S_IWOTH))
787 				return (EACCESS);
788 			*filep = filename = pathname;
789 		} else {
790 			/*
791 			 * If there's no directory list, take our cue from the
792 			 * absolute file request check above (*filename == '/'),
793 			 * and allow access to anything.
794 			 */
795 			if (stat(filename, &stbuf) < 0)
796 				return (errno == ENOENT ? ENOTFOUND : EACCESS);
797 			if (!S_ISREG(stbuf.st_mode))
798 				return (ENOTFOUND);
799 			if (mode == RRQ) {
800 				if ((stbuf.st_mode & S_IROTH) == 0)
801 					return (EACCESS);
802 			} else {
803 				if ((stbuf.st_mode & S_IWOTH) == 0)
804 					return (EACCESS);
805 			}
806 			*filep = filename;
807 		}
808 	}
809 
810 	if (tftp_opt_tsize && mode == RRQ)
811 		tftp_tsize = (unsigned long) stbuf.st_size;
812 
813 	fd = open(filename, mode == RRQ ? O_RDONLY : O_WRONLY | O_TRUNC);
814 	if (fd < 0)
815 		return (errno + 100);
816 	file = fdopen(fd, (mode == RRQ)? "r":"w");
817 	if (file == NULL) {
818 		close(fd);
819 		return (errno + 100);
820 	}
821 	return (0);
822 }
823 
824 int	timeout;
825 jmp_buf	timeoutbuf;
826 
827 void
828 timer(int dummy)
829 {
830 
831 	timeout += rexmtval;
832 	if (timeout >= maxtimeout)
833 		exit(1);
834 	longjmp(timeoutbuf, 1);
835 }
836 
837 static const char *
838 opcode(int code)
839 {
840 	static char buf[64];
841 
842 	switch (code) {
843 	case RRQ:
844 		return "RRQ";
845 	case WRQ:
846 		return "WRQ";
847 	case DATA:
848 		return "DATA";
849 	case ACK:
850 		return "ACK";
851 	case ERROR:
852 		return "ERROR";
853 	case OACK:
854 		return "OACK";
855 	default:
856 		(void)snprintf(buf, sizeof(buf), "*code %d*", code);
857 		return buf;
858 	}
859 }
860 
861 /*
862  * Send the requested file.
863  */
864 void
865 sendfile(struct formats *pf, int etftp, int acklength)
866 {
867 	volatile unsigned int block;
868 	struct tftphdr	*dp;
869 	struct tftphdr	*ap;    /* ack packet */
870 	int		 size, n;
871 
872 	signal(SIGALRM, timer);
873 	ap = (struct tftphdr *)ackbuf;
874 	if (etftp) {
875 		dp = (struct tftphdr *)oackbuf;
876 		size = acklength - 4;
877 		block = 0;
878 	} else {
879 		dp = r_init();
880 		size = 0;
881 		block = 1;
882 	}
883 
884 	do {
885 		if (block > 0) {
886 			size = readit(file, &dp, tftp_blksize, pf->f_convert);
887 			if (size < 0) {
888 				nak(errno + 100);
889 				goto abort;
890 			}
891 			dp->th_opcode = htons((u_short)DATA);
892 			dp->th_block = htons((u_short)block);
893 		}
894 		timeout = 0;
895 		(void)setjmp(timeoutbuf);
896 
897 send_data:
898 		if (!etftp && debug)
899 			syslog(LOG_DEBUG, "Send DATA %u", block);
900 		if ((n = send(peer, dp, size + 4, 0)) != size + 4) {
901 			syslog(LOG_ERR, "tftpd: write: %m");
902 			goto abort;
903 		}
904 		if (block)
905 			read_ahead(file, tftp_blksize, pf->f_convert);
906 		for ( ; ; ) {
907 			alarm(rexmtval);        /* read the ack */
908 			n = recv(peer, ackbuf, tftp_blksize, 0);
909 			alarm(0);
910 			if (n < 0) {
911 				syslog(LOG_ERR, "tftpd: read: %m");
912 				goto abort;
913 			}
914 			ap->th_opcode = ntohs((u_short)ap->th_opcode);
915 			ap->th_block = ntohs((u_short)ap->th_block);
916 			switch (ap->th_opcode) {
917 			case ERROR:
918 				goto abort;
919 
920 			case ACK:
921 				if (ap->th_block == 0) {
922 					etftp = 0;
923 					acklength = 0;
924 					dp = r_init();
925 					goto done;
926 				}
927 				if (ap->th_block == block)
928 					goto done;
929 				if (debug)
930 					syslog(LOG_DEBUG, "Resync ACK %u != %u",
931 					    (unsigned int)ap->th_block, block);
932 				/* Re-synchronize with the other side */
933 				(void) synchnet(peer, tftp_blksize);
934 				if (ap->th_block == (block -1))
935 					goto send_data;
936 			default:
937 				syslog(LOG_INFO, "Received %s in sendfile\n",
938 				    opcode(dp->th_opcode));
939 			}
940 
941 		}
942 done:
943 		if (debug)
944 			syslog(LOG_DEBUG, "Received ACK for block %u", block);
945 		block++;
946 	} while (size == tftp_blksize || block == 1);
947 abort:
948 	(void) fclose(file);
949 }
950 
951 void
952 justquit(int dummy)
953 {
954 
955 	exit(0);
956 }
957 
958 /*
959  * Receive a file.
960  */
961 void
962 recvfile(struct formats *pf, int etftp, int acklength)
963 {
964 	volatile unsigned int block;
965 	struct tftphdr	*dp;
966 	struct tftphdr	*ap;    /* ack buffer */
967 	int		 n, size;
968 
969 	signal(SIGALRM, timer);
970 	dp = w_init();
971 	ap = (struct tftphdr *)oackbuf;
972 	block = 0;
973 	do {
974 		timeout = 0;
975 		if (etftp == 0) {
976 			ap = (struct tftphdr *)ackbuf;
977 			ap->th_opcode = htons((u_short)ACK);
978 			ap->th_block = htons((u_short)block);
979 			acklength = 4;
980 		}
981 		if (debug)
982 			syslog(LOG_DEBUG, "Sending ACK for block %u\n", block);
983 		block++;
984 		(void) setjmp(timeoutbuf);
985 send_ack:
986 		if (send(peer, ap, acklength, 0) != acklength) {
987 			syslog(LOG_ERR, "tftpd: write: %m");
988 			goto abort;
989 		}
990 		write_behind(file, pf->f_convert);
991 		for ( ; ; ) {
992 			alarm(rexmtval);
993 			n = recv(peer, dp, tftp_blksize + 4, 0);
994 			alarm(0);
995 			if (n < 0) {            /* really? */
996 				syslog(LOG_ERR, "tftpd: read: %m");
997 				goto abort;
998 			}
999 			etftp = 0;
1000 			dp->th_opcode = ntohs((u_short)dp->th_opcode);
1001 			dp->th_block = ntohs((u_short)dp->th_block);
1002 			if (debug)
1003 				syslog(LOG_DEBUG, "Received %s for block %u",
1004 				    opcode(dp->th_opcode),
1005 				    (unsigned int)dp->th_block);
1006 
1007 			switch (dp->th_opcode) {
1008 			case ERROR:
1009 				goto abort;
1010 			case DATA:
1011 				if (dp->th_block == block)
1012 					goto done;   /* normal */
1013 				if (debug)
1014 					syslog(LOG_DEBUG, "Resync %u != %u",
1015 					    (unsigned int)dp->th_block, block);
1016 				/* Re-synchronize with the other side */
1017 				(void) synchnet(peer, tftp_blksize);
1018 				if (dp->th_block == (block-1))
1019 					goto send_ack;          /* rexmit */
1020 				break;
1021 			default:
1022 				syslog(LOG_INFO, "Received %s in recvfile\n",
1023 				    opcode(dp->th_opcode));
1024 				break;
1025 			}
1026 		}
1027 done:
1028 		if (debug)
1029 			syslog(LOG_DEBUG, "Got block %u", block);
1030 		/*  size = write(file, dp->th_data, n - 4); */
1031 		size = writeit(file, &dp, n - 4, pf->f_convert);
1032 		if (size != (n-4)) {                    /* ahem */
1033 			if (size < 0) nak(errno + 100);
1034 			else nak(ENOSPACE);
1035 			goto abort;
1036 		}
1037 	} while (size == tftp_blksize);
1038 	write_behind(file, pf->f_convert);
1039 	(void) fclose(file);            /* close data file */
1040 
1041 	ap->th_opcode = htons((u_short)ACK);    /* send the "final" ack */
1042 	ap->th_block = htons((u_short)(block));
1043 	if (debug)
1044 		syslog(LOG_DEBUG, "Send final ACK %u", block);
1045 	(void) send(peer, ackbuf, 4, 0);
1046 
1047 	signal(SIGALRM, justquit);      /* just quit on timeout */
1048 	alarm(rexmtval);
1049 	n = recv(peer, buf, sizeof (buf), 0); /* normally times out and quits */
1050 	alarm(0);
1051 	if (n >= 4 &&                   /* if read some data */
1052 	    dp->th_opcode == DATA &&    /* and got a data block */
1053 	    block == dp->th_block) {	/* then my last ack was lost */
1054 		(void) send(peer, ackbuf, 4, 0);     /* resend final ack */
1055 	}
1056 abort:
1057 	return;
1058 }
1059 
1060 const struct errmsg {
1061 	int		 e_code;
1062 	const char	*e_msg;
1063 } errmsgs[] = {
1064 	{ EUNDEF,	"Undefined error code" },
1065 	{ ENOTFOUND,	"File not found" },
1066 	{ EACCESS,	"Access violation" },
1067 	{ ENOSPACE,	"Disk full or allocation exceeded" },
1068 	{ EBADOP,	"Illegal TFTP operation" },
1069 	{ EBADID,	"Unknown transfer ID" },
1070 	{ EEXISTS,	"File already exists" },
1071 	{ ENOUSER,	"No such user" },
1072 	{ EOPTNEG,	"Option negotiation failed" },
1073 	{ -1,		0 }
1074 };
1075 
1076 static const char *
1077 errtomsg(int error)
1078 {
1079 	static char ebuf[20];
1080 	const struct errmsg *pe;
1081 
1082 	if (error == 0)
1083 		return ("success");
1084 	for (pe = errmsgs; pe->e_code >= 0; pe++)
1085 		if (pe->e_code == error)
1086 			return (pe->e_msg);
1087 	snprintf(ebuf, sizeof(ebuf), "error %d", error);
1088 	return (ebuf);
1089 }
1090 
1091 /*
1092  * Send a nak packet (error message).
1093  * Error code passed in is one of the
1094  * standard TFTP codes, or a UNIX errno
1095  * offset by 100.
1096  */
1097 static void
1098 nak(int error)
1099 {
1100 	const struct errmsg *pe;
1101 	struct tftphdr *tp;
1102 	int	length;
1103 	size_t	msglen;
1104 
1105 	tp = (struct tftphdr *)buf;
1106 	tp->th_opcode = htons((u_short)ERROR);
1107 	msglen = sizeof(buf) - (&tp->th_msg[0] - buf);
1108 	for (pe = errmsgs; pe->e_code >= 0; pe++)
1109 		if (pe->e_code == error)
1110 			break;
1111 	if (pe->e_code < 0) {
1112 		tp->th_code = EUNDEF;   /* set 'undef' errorcode */
1113 		strlcpy(tp->th_msg, strerror(error - 100), msglen);
1114 	} else {
1115 		tp->th_code = htons((u_short)error);
1116 		strlcpy(tp->th_msg, pe->e_msg, msglen);
1117 	}
1118 	if (debug)
1119 		syslog(LOG_DEBUG, "Send NACK %s", tp->th_msg);
1120 	length = strlen(tp->th_msg);
1121 	msglen = &tp->th_msg[length + 1] - buf;
1122 	if (send(peer, buf, msglen, 0) != msglen)
1123 		syslog(LOG_ERR, "nak: %m");
1124 }
1125 
1126 static char *
1127 verifyhost(struct sockaddr *fromp)
1128 {
1129 	static char hbuf[MAXHOSTNAMELEN];
1130 
1131 	if (getnameinfo(fromp, fromp->sa_len, hbuf, sizeof(hbuf), NULL, 0, 0))
1132 		strlcpy(hbuf, "?", sizeof(hbuf));
1133 	return (hbuf);
1134 }
1135