xref: /dragonfly/libexec/tftpd/tftpd.c (revision 655933d6)
1 /*
2  * Copyright (c) 1983, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  * @(#) Copyright (c) 1983, 1993 The Regents of the University of California.  All rights reserved.
30  * @(#)tftpd.c	8.1 (Berkeley) 6/4/93
31  * $FreeBSD: src/libexec/tftpd/tftpd.c,v 1.15.2.5 2003/04/06 19:42:56 dwmalone Exp $
32  */
33 
34 /*
35  * Trivial file transfer protocol server.
36  *
37  * This version includes many modifications by Jim Guyton
38  * <guyton@rand-unix>.
39  */
40 
41 #include <sys/param.h>
42 #include <sys/ioctl.h>
43 #include <sys/stat.h>
44 #include <sys/socket.h>
45 #include <sys/types.h>
46 
47 #include <netinet/in.h>
48 #include <arpa/tftp.h>
49 #include <arpa/inet.h>
50 
51 #include <ctype.h>
52 #include <errno.h>
53 #include <fcntl.h>
54 #include <libutil.h>
55 #include <netdb.h>
56 #include <pwd.h>
57 #include <setjmp.h>
58 #include <signal.h>
59 #include <stdio.h>
60 #include <stdlib.h>
61 #include <string.h>
62 #include <syslog.h>
63 #include <unistd.h>
64 
65 #include "tftpsubs.h"
66 
67 #define	TIMEOUT		5
68 #define	MAX_TIMEOUTS	5
69 
70 static int	peer;
71 static int	rexmtval = TIMEOUT;
72 static int	max_rexmtval = 2*TIMEOUT;
73 
74 #define	PKTSIZE	SEGSIZE+4
75 static char	buf[PKTSIZE];
76 static char	ackbuf[PKTSIZE];
77 static struct	sockaddr_storage from;
78 static int	fromlen;
79 
80 static void tftp(struct tftphdr *, int) __dead2;
81 static void unmappedaddr(struct sockaddr_in6 *);
82 
83 /*
84  * Null-terminated directory prefix list for absolute pathname requests and
85  * search list for relative pathname requests.
86  *
87  * MAXDIRS should be at least as large as the number of arguments that
88  * inetd allows (currently 20).
89  */
90 #define MAXDIRS	20
91 static struct dirlist {
92 	const char	*name;
93 	int	len;
94 } dirs[MAXDIRS+1];
95 static int	suppress_naks;
96 static int	logging;
97 static int	ipchroot;
98 
99 static const char *errtomsg(int);
100 static void  nak(int);
101 static void  oack(void);
102 
103 static void  timer(int);
104 static void  justquit(int);
105 
106 int
107 main(int argc, char *argv[])
108 {
109 	struct tftphdr *tp;
110 	int n;
111 	int ch, on;
112 	struct sockaddr_storage me;
113 	int len;
114 	char *chroot_dir = NULL;
115 	struct passwd *nobody;
116 	const char *chuser = "nobody";
117 
118 	openlog("tftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
119 	while ((ch = getopt(argc, argv, "cClns:u:")) != -1) {
120 		switch (ch) {
121 		case 'c':
122 			ipchroot = 1;
123 			break;
124 		case 'C':
125 			ipchroot = 2;
126 			break;
127 		case 'l':
128 			logging = 1;
129 			break;
130 		case 'n':
131 			suppress_naks = 1;
132 			break;
133 		case 's':
134 			chroot_dir = optarg;
135 			break;
136 		case 'u':
137 			chuser = optarg;
138 			break;
139 		default:
140 			syslog(LOG_WARNING, "ignoring unknown option -%c", ch);
141 		}
142 	}
143 	if (optind < argc) {
144 		struct dirlist *dirp;
145 
146 		/* Get list of directory prefixes. Skip relative pathnames. */
147 		for (dirp = dirs; optind < argc && dirp < &dirs[MAXDIRS];
148 		     optind++) {
149 			if (argv[optind][0] == '/') {
150 				dirp->name = argv[optind];
151 				dirp->len  = strlen(dirp->name);
152 				dirp++;
153 			}
154 		}
155 	}
156 	else if (chroot_dir) {
157 		dirs->name = "/";
158 		dirs->len = 1;
159 	}
160 	if (ipchroot && chroot_dir == NULL) {
161 		syslog(LOG_ERR, "-c requires -s");
162 		exit(1);
163 	}
164 
165 	on = 1;
166 	if (ioctl(0, FIONBIO, &on) < 0) {
167 		syslog(LOG_ERR, "ioctl(FIONBIO): %m");
168 		exit(1);
169 	}
170 	fromlen = sizeof (from);
171 	n = recvfrom(0, buf, sizeof (buf), 0,
172 	    (struct sockaddr *)&from, &fromlen);
173 	if (n < 0) {
174 		syslog(LOG_ERR, "recvfrom: %m");
175 		exit(1);
176 	}
177 	/*
178 	 * Now that we have read the message out of the UDP
179 	 * socket, we fork and exit.  Thus, inetd will go back
180 	 * to listening to the tftp port, and the next request
181 	 * to come in will start up a new instance of tftpd.
182 	 *
183 	 * We do this so that inetd can run tftpd in "wait" mode.
184 	 * The problem with tftpd running in "nowait" mode is that
185 	 * inetd may get one or more successful "selects" on the
186 	 * tftp port before we do our receive, so more than one
187 	 * instance of tftpd may be started up.  Worse, if tftpd
188 	 * break before doing the above "recvfrom", inetd would
189 	 * spawn endless instances, clogging the system.
190 	 */
191 	{
192 		int pid;
193 		int i, j;
194 
195 		for (i = 1; i < 20; i++) {
196 		    pid = fork();
197 		    if (pid < 0) {
198 				sleep(i);
199 				/*
200 				 * flush out to most recently sent request.
201 				 *
202 				 * This may drop some request, but those
203 				 * will be resent by the clients when
204 				 * they timeout.  The positive effect of
205 				 * this flush is to (try to) prevent more
206 				 * than one tftpd being started up to service
207 				 * a single request from a single client.
208 				 */
209 				j = sizeof from;
210 				i = recvfrom(0, buf, sizeof (buf), 0,
211 				    (struct sockaddr *)&from, &j);
212 				if (i > 0) {
213 					n = i;
214 					fromlen = j;
215 				}
216 		    } else {
217 				break;
218 		    }
219 		}
220 		if (pid < 0) {
221 			syslog(LOG_ERR, "fork: %m");
222 			exit(1);
223 		} else if (pid != 0) {
224 			exit(0);
225 		}
226 	}
227 
228 	/*
229 	 * Since we exit here, we should do that only after the above
230 	 * recvfrom to keep inetd from constantly forking should there
231 	 * be a problem.  See the above comment about system clogging.
232 	 */
233 	if (chroot_dir) {
234 		if (ipchroot) {
235 			char *tempchroot;
236 			struct stat sb;
237 			int statret;
238 			struct sockaddr_storage ss;
239 			char hbuf[NI_MAXHOST];
240 
241 			memcpy(&ss, &from, from.ss_len);
242 			unmappedaddr((struct sockaddr_in6 *)&ss);
243 			getnameinfo((struct sockaddr *)&ss, ss.ss_len,
244 				    hbuf, sizeof(hbuf), NULL, 0,
245 				    NI_NUMERICHOST | NI_WITHSCOPEID);
246 			asprintf(&tempchroot, "%s/%s", chroot_dir, hbuf);
247 			statret = stat(tempchroot, &sb);
248 			if ((sb.st_mode & S_IFDIR) &&
249 			    (statret == 0 || (statret == -1 && ipchroot == 1)))
250 				chroot_dir = tempchroot;
251 		}
252 		/* Must get this before chroot because /etc might go away */
253 		if ((nobody = getpwnam(chuser)) == NULL) {
254 			syslog(LOG_ERR, "%s: no such user", chuser);
255 			exit(1);
256 		}
257 		if (chroot(chroot_dir)) {
258 			syslog(LOG_ERR, "chroot: %s: %m", chroot_dir);
259 			exit(1);
260 		}
261 		chdir( "/" );
262 		setuid(nobody->pw_uid);
263 		setgroups(1, &nobody->pw_gid);
264 	}
265 
266 	len = sizeof(me);
267 	if (getsockname(0, (struct sockaddr *)&me, &len) == 0) {
268 		switch (me.ss_family) {
269 		case AF_INET:
270 			((struct sockaddr_in *)&me)->sin_port = 0;
271 			break;
272 		case AF_INET6:
273 			((struct sockaddr_in6 *)&me)->sin6_port = 0;
274 			break;
275 		default:
276 			/* unsupported */
277 			break;
278 		}
279 	} else {
280 		memset(&me, 0, sizeof(me));
281 		me.ss_family = from.ss_family;
282 		me.ss_len = from.ss_len;
283 	}
284 	alarm(0);
285 	close(0);
286 	close(1);
287 	peer = socket(from.ss_family, SOCK_DGRAM, 0);
288 	if (peer < 0) {
289 		syslog(LOG_ERR, "socket: %m");
290 		exit(1);
291 	}
292 	if (bind(peer, (struct sockaddr *)&me, me.ss_len) < 0) {
293 		syslog(LOG_ERR, "bind: %m");
294 		exit(1);
295 	}
296 	if (connect(peer, (struct sockaddr *)&from, from.ss_len) < 0) {
297 		syslog(LOG_ERR, "connect: %m");
298 		exit(1);
299 	}
300 	tp = (struct tftphdr *)buf;
301 	tp->th_opcode = ntohs(tp->th_opcode);
302 	if (tp->th_opcode == RRQ || tp->th_opcode == WRQ)
303 		tftp(tp, n);
304 	exit(1);
305 }
306 
307 struct formats;
308 static int	validate_access(char **, int);
309 static void	xmitfile(struct formats *);
310 static void	recvfile(struct formats *);
311 
312 static struct formats {
313 	const char	*f_mode;
314 	int	(*f_validate)(char **, int);
315 	void	(*f_send)(struct formats *);
316 	void	(*f_recv)(struct formats *);
317 	int	f_convert;
318 } formats[] = {
319 	{ "netascii",	validate_access,	xmitfile,	recvfile, 1 },
320 	{ "octet",	validate_access,	xmitfile,	recvfile, 0 },
321 #ifdef notdef
322 	{ "mail",	validate_user,		sendmail,	recvmail, 1 },
323 #endif
324 	{ 0,		NULL,			NULL,		NULL,	  0 }
325 };
326 
327 static struct options {
328 	const char	*o_type;
329 	char	*o_request;
330 	int	o_reply;	/* turn into union if need be */
331 } options[] = {
332 	{ "tsize",	NULL, 0 },		/* OPT_TSIZE */
333 	{ "timeout",	NULL, 0 },		/* OPT_TIMEOUT */
334 	{ NULL,		NULL, 0 }
335 };
336 
337 enum opt_enum {
338 	OPT_TSIZE = 0,
339 	OPT_TIMEOUT,
340 };
341 
342 /*
343  * Handle initial connection protocol.
344  */
345 static void
346 tftp(struct tftphdr *tp, int size)
347 {
348 	char *cp;
349 	size_t i;
350 	int first = 1, has_options = 0, ecode;
351 	struct formats *pf;
352 	char *filename, *mode = NULL, *option, *ccp;
353 	char fnbuf[MAXPATHLEN];
354 
355 	cp = tp->th_stuff;
356 again:
357 	while (cp < buf + size) {
358 		if (*cp == '\0')
359 			break;
360 		cp++;
361 	}
362 	if (*cp != '\0') {
363 		nak(EBADOP);
364 		exit(1);
365 	}
366 	i = cp - tp->th_stuff;
367 	if (i >= sizeof(fnbuf)) {
368 		nak(EBADOP);
369 		exit(1);
370 	}
371 	memcpy(fnbuf, tp->th_stuff, i);
372 	fnbuf[i] = '\0';
373 	filename = fnbuf;
374 	if (first) {
375 		mode = ++cp;
376 		first = 0;
377 		goto again;
378 	}
379 	for (cp = mode; *cp; cp++)
380 		if (isupper(*cp))
381 			*cp = tolower(*cp);
382 	for (pf = formats; pf->f_mode; pf++)
383 		if (strcmp(pf->f_mode, mode) == 0)
384 			break;
385 	if (pf->f_mode == NULL) {
386 		nak(EBADOP);
387 		exit(1);
388 	}
389 	while (++cp < buf + size) {
390 		for (i = 2, ccp = cp; i > 0; ccp++) {
391 			if (ccp >= buf + size) {
392 				/*
393 				 * Don't reject the request, just stop trying
394 				 * to parse the option and get on with it.
395 				 * Some Apple OpenFirmware versions have
396 				 * trailing garbage on the end of otherwise
397 				 * valid requests.
398 				 */
399 				goto option_fail;
400 			} else if (*ccp == '\0')
401 				i--;
402 		}
403 		for (option = cp; *cp; cp++)
404 			if (isupper(*cp))
405 				*cp = tolower(*cp);
406 		for (i = 0; options[i].o_type != NULL; i++)
407 			if (strcmp(option, options[i].o_type) == 0) {
408 				options[i].o_request = ++cp;
409 				has_options = 1;
410 			}
411 		cp = ccp-1;
412 	}
413 
414 option_fail:
415 	if (options[OPT_TIMEOUT].o_request) {
416 		int to = atoi(options[OPT_TIMEOUT].o_request);
417 		if (to < 1 || to > 255) {
418 			nak(EBADOP);
419 			exit(1);
420 		}
421 		else if (to <= max_rexmtval)
422 			options[OPT_TIMEOUT].o_reply = rexmtval = to;
423 		else
424 			options[OPT_TIMEOUT].o_request = NULL;
425 	}
426 
427 	ecode = (*pf->f_validate)(&filename, tp->th_opcode);
428 	if (has_options)
429 		oack();
430 	if (logging) {
431 		char hbuf[NI_MAXHOST];
432 
433 		getnameinfo((struct sockaddr *)&from, from.ss_len,
434 			    hbuf, sizeof(hbuf), NULL, 0,
435 			    NI_WITHSCOPEID);
436 		syslog(LOG_INFO, "%s: %s request for %s: %s", hbuf,
437 			tp->th_opcode == WRQ ? "write" : "read",
438 			filename, errtomsg(ecode));
439 	}
440 	if (ecode) {
441 		/*
442 		 * Avoid storms of naks to a RRQ broadcast for a relative
443 		 * bootfile pathname from a diskless Sun.
444 		 */
445 		if (suppress_naks && *filename != '/' && ecode == ENOTFOUND)
446 			exit(0);
447 		nak(ecode);
448 		exit(1);
449 	}
450 	if (tp->th_opcode == WRQ)
451 		(*pf->f_recv)(pf);
452 	else
453 		(*pf->f_send)(pf);
454 	exit(0);
455 }
456 
457 
458 static FILE *file;
459 
460 /*
461  * Validate file access.  Since we
462  * have no uid or gid, for now require
463  * file to exist and be publicly
464  * readable/writable.
465  * If we were invoked with arguments
466  * from inetd then the file must also be
467  * in one of the given directory prefixes.
468  * Note also, full path name must be
469  * given as we have no login directory.
470  */
471 static int
472 validate_access(char **filep, int mode)
473 {
474 	struct stat stbuf;
475 	int	fd;
476 	struct dirlist *dirp;
477 	static char pathname[MAXPATHLEN];
478 	char *filename = *filep;
479 
480 	/*
481 	 * Prevent tricksters from getting around the directory restrictions
482 	 */
483 	if (strstr(filename, "/../"))
484 		return (EACCESS);
485 
486 	if (*filename == '/') {
487 		/*
488 		 * Allow the request if it's in one of the approved locations.
489 		 * Special case: check the null prefix ("/") by looking
490 		 * for length = 1 and relying on the arg. processing that
491 		 * it's a /.
492 		 */
493 		for (dirp = dirs; dirp->name != NULL; dirp++) {
494 			if (dirp->len == 1 ||
495 			    (!strncmp(filename, dirp->name, dirp->len) &&
496 			     filename[dirp->len] == '/'))
497 				    break;
498 		}
499 		/* If directory list is empty, allow access to any file */
500 		if (dirp->name == NULL && dirp != dirs)
501 			return (EACCESS);
502 		if (stat(filename, &stbuf) < 0)
503 			return (errno == ENOENT ? ENOTFOUND : EACCESS);
504 		if ((stbuf.st_mode & S_IFMT) != S_IFREG)
505 			return (ENOTFOUND);
506 		if (mode == RRQ) {
507 			if ((stbuf.st_mode & S_IROTH) == 0)
508 				return (EACCESS);
509 		} else {
510 			if ((stbuf.st_mode & S_IWOTH) == 0)
511 				return (EACCESS);
512 		}
513 	} else {
514 		int err;
515 
516 		/*
517 		 * Relative file name: search the approved locations for it.
518 		 * Don't allow write requests that avoid directory
519 		 * restrictions.
520 		 */
521 
522 		if (!strncmp(filename, "../", 3))
523 			return (EACCESS);
524 
525 		/*
526 		 * If the file exists in one of the directories and isn't
527 		 * readable, continue looking. However, change the error code
528 		 * to give an indication that the file exists.
529 		 */
530 		err = ENOTFOUND;
531 		for (dirp = dirs; dirp->name != NULL; dirp++) {
532 			snprintf(pathname, sizeof(pathname), "%s/%s",
533 				dirp->name, filename);
534 			if (stat(pathname, &stbuf) == 0 &&
535 			    (stbuf.st_mode & S_IFMT) == S_IFREG) {
536 				if ((stbuf.st_mode & S_IROTH) != 0) {
537 					break;
538 				}
539 				err = EACCESS;
540 			}
541 		}
542 		if (dirp->name == NULL)
543 			return (err);
544 		*filep = filename = pathname;
545 	}
546 	if (options[OPT_TSIZE].o_request) {
547 		if (mode == RRQ)
548 			options[OPT_TSIZE].o_reply = stbuf.st_size;
549 		else
550 			/* XXX Allows writes of all sizes. */
551 			options[OPT_TSIZE].o_reply =
552 				atoi(options[OPT_TSIZE].o_request);
553 	}
554 	fd = open(filename, mode == RRQ ? O_RDONLY : O_WRONLY|O_TRUNC);
555 	if (fd < 0)
556 		return (errno + 100);
557 	file = fdopen(fd, (mode == RRQ)? "r":"w");
558 	if (file == NULL) {
559 		return errno+100;
560 	}
561 	return (0);
562 }
563 
564 static int	timeouts;
565 static jmp_buf	timeoutbuf;
566 
567 static void
568 timer(int sig __unused)
569 {
570 	if (++timeouts > MAX_TIMEOUTS)
571 		exit(1);
572 	longjmp(timeoutbuf, 1);
573 }
574 
575 /*
576  * Send the requested file.
577  */
578 static void
579 xmitfile(struct formats *pf)
580 {
581 	struct tftphdr *dp;
582 	struct tftphdr *ap;    /* ack packet */
583 	int size, n;
584 	volatile unsigned short block;
585 
586 	signal(SIGALRM, timer);
587 	dp = r_init();
588 	ap = (struct tftphdr *)ackbuf;
589 	block = 1;
590 	do {
591 		size = readit(file, &dp, pf->f_convert);
592 		if (size < 0) {
593 			nak(errno + 100);
594 			goto abort;
595 		}
596 		dp->th_opcode = htons((u_short)DATA);
597 		dp->th_block = htons((u_short)block);
598 		timeouts = 0;
599 		(void)setjmp(timeoutbuf);
600 
601 send_data:
602 		{
603 			int i, t = 1;
604 			for (i = 0; ; i++){
605 				if (send(peer, dp, size + 4, 0) != size + 4) {
606 					sleep(t);
607 					t = (t < 32) ? t<< 1 : t;
608 					if (i >= 12) {
609 						syslog(LOG_ERR, "write: %m");
610 						goto abort;
611 					}
612 				}
613 				break;
614 			}
615 		}
616 		read_ahead(file, pf->f_convert);
617 		for ( ; ; ) {
618 			alarm(rexmtval);        /* read the ack */
619 			n = recv(peer, ackbuf, sizeof (ackbuf), 0);
620 			alarm(0);
621 			if (n < 0) {
622 				syslog(LOG_ERR, "read: %m");
623 				goto abort;
624 			}
625 			ap->th_opcode = ntohs((u_short)ap->th_opcode);
626 			ap->th_block = ntohs((u_short)ap->th_block);
627 
628 			if (ap->th_opcode == ERROR)
629 				goto abort;
630 
631 			if (ap->th_opcode == ACK) {
632 				if (ap->th_block == block)
633 					break;
634 				/* Re-synchronize with the other side */
635 				(void) synchnet(peer);
636 				if (ap->th_block == (block -1))
637 					goto send_data;
638 			}
639 
640 		}
641 		block++;
642 	} while (size == SEGSIZE);
643 abort:
644 	(void) fclose(file);
645 }
646 
647 static void
648 justquit(int sig __unused)
649 {
650 	exit(0);
651 }
652 
653 
654 /*
655  * Receive a file.
656  */
657 static void
658 recvfile(struct formats *pf)
659 {
660 	struct tftphdr *dp;
661 	struct tftphdr *ap;    /* ack buffer */
662 	int n, size;
663 	volatile unsigned short block;
664 
665 	signal(SIGALRM, timer);
666 	dp = w_init();
667 	ap = (struct tftphdr *)ackbuf;
668 	block = 0;
669 	do {
670 		timeouts = 0;
671 		ap->th_opcode = htons((u_short)ACK);
672 		ap->th_block = htons((u_short)block);
673 		block++;
674 		(void) setjmp(timeoutbuf);
675 send_ack:
676 		if (send(peer, ackbuf, 4, 0) != 4) {
677 			syslog(LOG_ERR, "write: %m");
678 			goto abort;
679 		}
680 		write_behind(file, pf->f_convert);
681 		for ( ; ; ) {
682 			alarm(rexmtval);
683 			n = recv(peer, dp, PKTSIZE, 0);
684 			alarm(0);
685 			if (n < 0) {            /* really? */
686 				syslog(LOG_ERR, "read: %m");
687 				goto abort;
688 			}
689 			dp->th_opcode = ntohs((u_short)dp->th_opcode);
690 			dp->th_block = ntohs((u_short)dp->th_block);
691 			if (dp->th_opcode == ERROR)
692 				goto abort;
693 			if (dp->th_opcode == DATA) {
694 				if (dp->th_block == block) {
695 					break;   /* normal */
696 				}
697 				/* Re-synchronize with the other side */
698 				(void) synchnet(peer);
699 				if (dp->th_block == (block-1))
700 					goto send_ack;          /* rexmit */
701 			}
702 		}
703 		/*  size = write(file, dp->th_data, n - 4); */
704 		size = writeit(file, &dp, n - 4, pf->f_convert);
705 		if (size != (n-4)) {                    /* ahem */
706 			if (size < 0) nak(errno + 100);
707 			else nak(ENOSPACE);
708 			goto abort;
709 		}
710 	} while (size == SEGSIZE);
711 	write_behind(file, pf->f_convert);
712 	(void) fclose(file);            /* close data file */
713 
714 	ap->th_opcode = htons((u_short)ACK);    /* send the "final" ack */
715 	ap->th_block = htons((u_short)(block));
716 	(void) send(peer, ackbuf, 4, 0);
717 
718 	signal(SIGALRM, justquit);      /* just quit on timeout */
719 	alarm(rexmtval);
720 	n = recv(peer, buf, sizeof (buf), 0); /* normally times out and quits */
721 	alarm(0);
722 	if (n >= 4 &&                   /* if read some data */
723 	    dp->th_opcode == DATA &&    /* and got a data block */
724 	    block == dp->th_block) {	/* then my last ack was lost */
725 		(void) send(peer, ackbuf, 4, 0);     /* resend final ack */
726 	}
727 abort:
728 	return;
729 }
730 
731 static struct errmsg {
732 	int	e_code;
733 	const char	*e_msg;
734 } errmsgs[] = {
735 	{ EUNDEF,	"Undefined error code" },
736 	{ ENOTFOUND,	"File not found" },
737 	{ EACCESS,	"Access violation" },
738 	{ ENOSPACE,	"Disk full or allocation exceeded" },
739 	{ EBADOP,	"Illegal TFTP operation" },
740 	{ EBADID,	"Unknown transfer ID" },
741 	{ EEXISTS,	"File already exists" },
742 	{ ENOUSER,	"No such user" },
743 	{ EOPTNEG,	"Option negotiation" },
744 	{ -1,		0 }
745 };
746 
747 static const char *
748 errtomsg(int error)
749 {
750 	static char ebuf[20];
751 	struct errmsg *pe;
752 
753 	if (error == 0)
754 		return "success";
755 	for (pe = errmsgs; pe->e_code >= 0; pe++)
756 		if (pe->e_code == error)
757 			return pe->e_msg;
758 	snprintf(ebuf, sizeof(ebuf), "error %d", error);
759 	return ebuf;
760 }
761 
762 /*
763  * Send a nak packet (error message).
764  * Error code passed in is one of the
765  * standard TFTP codes, or a UNIX errno
766  * offset by 100.
767  */
768 static void
769 nak(int error)
770 {
771 	struct tftphdr *tp;
772 	int length;
773 	struct errmsg *pe;
774 
775 	tp = (struct tftphdr *)buf;
776 	tp->th_opcode = htons((u_short)ERROR);
777 	tp->th_code = htons((u_short)error);
778 	for (pe = errmsgs; pe->e_code >= 0; pe++)
779 		if (pe->e_code == error)
780 			break;
781 	if (pe->e_code < 0) {
782 		pe->e_msg = strerror(error - 100);
783 		tp->th_code = EUNDEF;   /* set 'undef' errorcode */
784 	}
785 	strcpy(tp->th_msg, pe->e_msg);
786 	length = strlen(pe->e_msg);
787 	tp->th_msg[length] = '\0';
788 	length += 5;
789 	if (send(peer, buf, length, 0) != length)
790 		syslog(LOG_ERR, "nak: %m");
791 }
792 
793 /* translate IPv4 mapped IPv6 address to IPv4 address */
794 static void
795 unmappedaddr(struct sockaddr_in6 *sin6)
796 {
797 	struct sockaddr_in *sin4;
798 	void *addr;
799 	int port;
800 
801 	if (sin6->sin6_family != AF_INET6 ||
802 	    !IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
803 		return;
804 	sin4 = (struct sockaddr_in *)sin6;
805 	addr = &sin6->sin6_addr.s6_addr[12];
806 	port = sin6->sin6_port;
807 	memset(sin4, 0, sizeof(struct sockaddr_in));
808 	sin4->sin_addr.s_addr = *(uint32_t *)addr;
809 	sin4->sin_port = port;
810 	sin4->sin_family = AF_INET;
811 	sin4->sin_len = sizeof(struct sockaddr_in);
812 }
813 
814 /*
815  * Send an oack packet (option acknowledgement).
816  */
817 static void
818 oack(void)
819 {
820 	struct tftphdr *tp, *ap;
821 	int size, i, n;
822 	char *bp;
823 
824 	tp = (struct tftphdr *)buf;
825 	bp = buf + 2;
826 	size = sizeof(buf) - 2;
827 	tp->th_opcode = htons((u_short)OACK);
828 	for (i = 0; options[i].o_type != NULL; i++) {
829 		if (options[i].o_request) {
830 			n = snprintf(bp, size, "%s%c%d", options[i].o_type,
831 				     0, options[i].o_reply);
832 			bp += n+1;
833 			size -= n+1;
834 			if (size < 0) {
835 				syslog(LOG_ERR, "oack: buffer overflow");
836 				exit(1);
837 			}
838 		}
839 	}
840 	size = bp - buf;
841 	ap = (struct tftphdr *)ackbuf;
842 	signal(SIGALRM, timer);
843 	timeouts = 0;
844 
845 	(void)setjmp(timeoutbuf);
846 	if (send(peer, buf, size, 0) != size) {
847 		syslog(LOG_INFO, "oack: %m");
848 		exit(1);
849 	}
850 
851 	for (;;) {
852 		alarm(rexmtval);
853 		n = recv(peer, ackbuf, sizeof (ackbuf), 0);
854 		alarm(0);
855 		if (n < 0) {
856 			syslog(LOG_ERR, "recv: %m");
857 			exit(1);
858 		}
859 		ap->th_opcode = ntohs((u_short)ap->th_opcode);
860 		ap->th_block = ntohs((u_short)ap->th_block);
861 		if (ap->th_opcode == ERROR)
862 			exit(1);
863 		if (ap->th_opcode == ACK && ap->th_block == 0)
864 			break;
865 	}
866 }
867