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