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