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