xref: /netbsd/libexec/tftpd/tftpd.c (revision bf9ec67e)
1 /*	$NetBSD: tftpd.c,v 1.24 2001/10/09 18:46:18 christos 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. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *	This product includes software developed by the University of
18  *	California, Berkeley and its contributors.
19  * 4. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 
36 #include <sys/cdefs.h>
37 #ifndef lint
38 __COPYRIGHT("@(#) Copyright (c) 1983, 1993\n\
39 	The Regents of the University of California.  All rights reserved.\n");
40 #if 0
41 static char sccsid[] = "@(#)tftpd.c	8.1 (Berkeley) 6/4/93";
42 #else
43 __RCSID("$NetBSD: tftpd.c,v 1.24 2001/10/09 18:46:18 christos Exp $");
44 #endif
45 #endif /* not lint */
46 
47 /*
48  * Trivial file transfer protocol server.
49  *
50  * This version includes many modifications by Jim Guyton
51  * <guyton@rand-unix>.
52  */
53 
54 #include <sys/param.h>
55 #include <sys/ioctl.h>
56 #include <sys/stat.h>
57 #include <sys/socket.h>
58 
59 #include <netinet/in.h>
60 #include <arpa/tftp.h>
61 #include <arpa/inet.h>
62 
63 #include <ctype.h>
64 #include <errno.h>
65 #include <fcntl.h>
66 #include <fcntl.h>
67 #include <grp.h>
68 #include <netdb.h>
69 #include <pwd.h>
70 #include <setjmp.h>
71 #include <signal.h>
72 #include <signal.h>
73 #include <stdio.h>
74 #include <stdlib.h>
75 #include <string.h>
76 #include <syslog.h>
77 #include <unistd.h>
78 
79 #include "tftpsubs.h"
80 
81 #define	DEFAULTUSER	"nobody"
82 
83 #define	TIMEOUT		5
84 
85 int	peer;
86 int	rexmtval = TIMEOUT;
87 int	maxtimeout = 5*TIMEOUT;
88 
89 #define	PKTSIZE	SEGSIZE+4
90 char	buf[PKTSIZE];
91 char	ackbuf[PKTSIZE];
92 struct	sockaddr_storage from;
93 int	fromlen;
94 int	debug;
95 
96 /*
97  * Null-terminated directory prefix list for absolute pathname requests and
98  * search list for relative pathname requests.
99  *
100  * MAXDIRS should be at least as large as the number of arguments that
101  * inetd allows (currently 20).
102  */
103 #define MAXDIRS	20
104 static struct dirlist {
105 	char	*name;
106 	int	len;
107 } dirs[MAXDIRS+1];
108 static int	suppress_naks;
109 static int	logging;
110 static int	secure;
111 static char	*securedir;
112 
113 struct formats;
114 
115 static const char *errtomsg(int);
116 static void	 nak(int);
117 static void	 tftp(struct tftphdr *, int);
118 static void	 usage(void);
119 static char	*verifyhost(struct sockaddr *);
120 void	justquit(int);
121 int	main(int, char **);
122 void	recvfile(struct formats *);
123 void	sendfile(struct formats *);
124 void	timer(int);
125 static const char *opcode(int);
126 int	validate_access(char **, int);
127 
128 struct formats {
129 	const char	*f_mode;
130 	int		(*f_validate)(char **, int);
131 	void		(*f_send)(struct formats *);
132 	void		(*f_recv)(struct formats *);
133 	int		f_convert;
134 } formats[] = {
135 	{ "netascii",	validate_access,	sendfile,	recvfile, 1 },
136 	{ "octet",	validate_access,	sendfile,	recvfile, 0 },
137 	{ 0 }
138 };
139 
140 static void
141 usage(void)
142 {
143 
144 	syslog(LOG_ERR,
145     "Usage: %s [-dln] [-u user] [-g group] [-s directory] [directory ...]",
146 		    getprogname());
147 	exit(1);
148 }
149 
150 int
151 main(int argc, char *argv[])
152 {
153 	struct sockaddr_storage me;
154 	struct passwd	*pwent;
155 	struct group	*grent;
156 	struct tftphdr	*tp;
157 	char		*tgtuser, *tgtgroup, *ep;
158 	int	n, ch, on, fd;
159 	int	len;
160 	uid_t	curuid, tgtuid;
161 	gid_t	curgid, tgtgid;
162 	long	nid;
163 
164 	n = 0;
165 	fd = 0;
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 	tp = (struct tftphdr *)buf;
391 	tp->th_opcode = ntohs(tp->th_opcode);
392 	if (tp->th_opcode == RRQ || tp->th_opcode == WRQ)
393 		tftp(tp, n);
394 	exit(1);
395 }
396 
397 /*
398  * Handle initial connection protocol.
399  */
400 static void
401 tftp(struct tftphdr *tp, int size)
402 {
403 	struct formats *pf;
404 	char	*cp;
405 	char	*filename, *mode;
406 	int	 first, ecode;
407 
408 	first = 1;
409 	mode = NULL;
410 
411 	filename = cp = tp->th_stuff;
412 again:
413 	while (cp < buf + size) {
414 		if (*cp == '\0')
415 			break;
416 		cp++;
417 	}
418 	if (*cp != '\0') {
419 		nak(EBADOP);
420 		exit(1);
421 	}
422 	if (first) {
423 		mode = ++cp;
424 		first = 0;
425 		goto again;
426 	}
427 	for (cp = mode; *cp; cp++)
428 		if (isupper(*cp))
429 			*cp = tolower(*cp);
430 	for (pf = formats; pf->f_mode; pf++)
431 		if (strcmp(pf->f_mode, mode) == 0)
432 			break;
433 	if (pf->f_mode == 0) {
434 		nak(EBADOP);
435 		exit(1);
436 	}
437 	ecode = (*pf->f_validate)(&filename, tp->th_opcode);
438 	if (logging) {
439 		syslog(LOG_INFO, "%s: %s request for %s: %s",
440 			verifyhost((struct sockaddr *)&from),
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  */
473 int
474 validate_access(char **filep, int mode)
475 {
476 	struct stat	 stbuf;
477 	struct dirlist	*dirp;
478 	static char	 pathname[MAXPATHLEN];
479 	char		*filename;
480 	int		 fd;
481 
482 	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 (!S_ISREG(stbuf.st_mode))
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 		/*
519 		 * Relative file name: search the approved locations for it.
520 		 */
521 
522 		if (!strncmp(filename, "../", 3))
523 			return (EACCESS);
524 
525 		/*
526 		 * Find the first file that exists in any of the directories,
527 		 * check access on it.
528 		 */
529 		if (dirs[0].name != NULL) {
530 			for (dirp = dirs; dirp->name != NULL; dirp++) {
531 				snprintf(pathname, sizeof pathname, "%s/%s",
532 				    dirp->name, filename);
533 				if (stat(pathname, &stbuf) == 0 &&
534 				    (stbuf.st_mode & S_IFMT) == S_IFREG) {
535 					break;
536 				}
537 			}
538 			if (dirp->name == NULL)
539 				return (ENOTFOUND);
540 			if (mode == RRQ && !(stbuf.st_mode & S_IROTH))
541 				return (EACCESS);
542 			if (mode == WRQ && !(stbuf.st_mode & S_IWOTH))
543 				return (EACCESS);
544 			*filep = filename = pathname;
545 		} else {
546 			/*
547 			 * If there's no directory list, take our cue from the
548 			 * absolute file request check above (*filename == '/'),
549 			 * and allow access to anything.
550 			 */
551 			if (stat(filename, &stbuf) < 0)
552 				return (errno == ENOENT ? ENOTFOUND : EACCESS);
553 			if (!S_ISREG(stbuf.st_mode))
554 				return (ENOTFOUND);
555 			if (mode == RRQ) {
556 				if ((stbuf.st_mode & S_IROTH) == 0)
557 					return (EACCESS);
558 			} else {
559 				if ((stbuf.st_mode & S_IWOTH) == 0)
560 					return (EACCESS);
561 			}
562 			*filep = filename;
563 		}
564 	}
565 	fd = open(filename, mode == RRQ ? O_RDONLY : O_WRONLY | O_TRUNC);
566 	if (fd < 0)
567 		return (errno + 100);
568 	file = fdopen(fd, (mode == RRQ)? "r":"w");
569 	if (file == NULL) {
570 		close(fd);
571 		return (errno + 100);
572 	}
573 	return (0);
574 }
575 
576 int	timeout;
577 jmp_buf	timeoutbuf;
578 
579 void
580 timer(int dummy)
581 {
582 
583 	timeout += rexmtval;
584 	if (timeout >= maxtimeout)
585 		exit(1);
586 	longjmp(timeoutbuf, 1);
587 }
588 
589 static const char *
590 opcode(int code)
591 {
592 	static char buf[64];
593 
594 	switch (code) {
595 	case RRQ:
596 		return "RRQ";
597 	case WRQ:
598 		return "WRQ";
599 	case DATA:
600 		return "DATA";
601 	case ACK:
602 		return "ACK";
603 	case ERROR:
604 		return "ERROR";
605 	default:
606 		(void)snprintf(buf, sizeof(buf), "*code %d*", code);
607 		return buf;
608 	}
609 }
610 
611 /*
612  * Send the requested file.
613  */
614 void
615 sendfile(struct formats *pf)
616 {
617 	volatile unsigned int block;
618 	struct tftphdr	*dp;
619 	struct tftphdr	*ap;    /* ack packet */
620 	int		 size, n;
621 
622 	signal(SIGALRM, timer);
623 	dp = r_init();
624 	ap = (struct tftphdr *)ackbuf;
625 	block = 1;
626 	do {
627 		size = readit(file, &dp, pf->f_convert);
628 		if (size < 0) {
629 			nak(errno + 100);
630 			goto abort;
631 		}
632 		dp->th_opcode = htons((u_short)DATA);
633 		dp->th_block = htons((u_short)block);
634 		timeout = 0;
635 		(void)setjmp(timeoutbuf);
636 
637 send_data:
638 		if (debug)
639 			syslog(LOG_DEBUG, "Send DATA %u", block);
640 		if (send(peer, dp, size + 4, 0) != size + 4) {
641 			syslog(LOG_ERR, "tftpd: write: %m");
642 			goto abort;
643 		}
644 		read_ahead(file, pf->f_convert);
645 		for ( ; ; ) {
646 			alarm(rexmtval);        /* read the ack */
647 			n = recv(peer, ackbuf, sizeof (ackbuf), 0);
648 			alarm(0);
649 			if (n < 0) {
650 				syslog(LOG_ERR, "tftpd: read: %m");
651 				goto abort;
652 			}
653 			ap->th_opcode = ntohs((u_short)ap->th_opcode);
654 			ap->th_block = ntohs((u_short)ap->th_block);
655 			switch (ap->th_opcode) {
656 			case ERROR:
657 				goto abort;
658 
659 			case ACK:
660 				if (ap->th_block == block)
661 					goto done;
662 				if (debug)
663 					syslog(LOG_DEBUG, "Resync ACK %u != %u",
664 					    (unsigned int)ap->th_block, block);
665 				/* Re-synchronize with the other side */
666 				(void) synchnet(peer);
667 				if (ap->th_block == (block -1))
668 					goto send_data;
669 			default:
670 				syslog(LOG_INFO, "Received %s in sendfile\n",
671 				    opcode(dp->th_opcode));
672 			}
673 
674 		}
675 done:
676 		if (debug)
677 			syslog(LOG_DEBUG, "Received ACK for block %u", block);
678 		block++;
679 	} while (size == SEGSIZE);
680 abort:
681 	(void) fclose(file);
682 }
683 
684 void
685 justquit(int dummy)
686 {
687 
688 	exit(0);
689 }
690 
691 /*
692  * Receive a file.
693  */
694 void
695 recvfile(struct formats *pf)
696 {
697 	volatile unsigned int block;
698 	struct tftphdr	*dp;
699 	struct tftphdr	*ap;    /* ack buffer */
700 	int		 n, size;
701 
702 	signal(SIGALRM, timer);
703 	dp = w_init();
704 	ap = (struct tftphdr *)ackbuf;
705 	block = 0;
706 	do {
707 		timeout = 0;
708 		ap->th_opcode = htons((u_short)ACK);
709 		ap->th_block = htons((u_short)block);
710 		if (debug)
711 			syslog(LOG_DEBUG, "Sending ACK for block %u\n", block);
712 		block++;
713 		(void) setjmp(timeoutbuf);
714 send_ack:
715 		if (send(peer, ackbuf, 4, 0) != 4) {
716 			syslog(LOG_ERR, "tftpd: write: %m");
717 			goto abort;
718 		}
719 		write_behind(file, pf->f_convert);
720 		for ( ; ; ) {
721 			alarm(rexmtval);
722 			n = recv(peer, dp, PKTSIZE, 0);
723 			alarm(0);
724 			if (n < 0) {            /* really? */
725 				syslog(LOG_ERR, "tftpd: read: %m");
726 				goto abort;
727 			}
728 			dp->th_opcode = ntohs((u_short)dp->th_opcode);
729 			dp->th_block = ntohs((u_short)dp->th_block);
730 			if (debug)
731 				syslog(LOG_DEBUG, "Received %s for block %u",
732 				    opcode(dp->th_opcode),
733 				    (unsigned int)dp->th_block);
734 
735 			switch (dp->th_opcode) {
736 			case ERROR:
737 				goto abort;
738 			case DATA:
739 				if (dp->th_block == block)
740 					goto done;   /* normal */
741 				if (debug)
742 					syslog(LOG_DEBUG, "Resync %u != %u",
743 					    (unsigned int)dp->th_block, block);
744 				/* Re-synchronize with the other side */
745 				(void) synchnet(peer);
746 				if (dp->th_block == (block-1))
747 					goto send_ack;          /* rexmit */
748 				break;
749 			default:
750 				syslog(LOG_INFO, "Received %s in recvfile\n",
751 				    opcode(dp->th_opcode));
752 				break;
753 			}
754 		}
755 done:
756 		if (debug)
757 			syslog(LOG_DEBUG, "Got block %u", block);
758 		/*  size = write(file, dp->th_data, n - 4); */
759 		size = writeit(file, &dp, n - 4, pf->f_convert);
760 		if (size != (n-4)) {                    /* ahem */
761 			if (size < 0) nak(errno + 100);
762 			else nak(ENOSPACE);
763 			goto abort;
764 		}
765 	} while (size == SEGSIZE);
766 	write_behind(file, pf->f_convert);
767 	(void) fclose(file);            /* close data file */
768 
769 	ap->th_opcode = htons((u_short)ACK);    /* send the "final" ack */
770 	ap->th_block = htons((u_short)(block));
771 	if (debug)
772 		syslog(LOG_DEBUG, "Send final ACK %u", block);
773 	(void) send(peer, ackbuf, 4, 0);
774 
775 	signal(SIGALRM, justquit);      /* just quit on timeout */
776 	alarm(rexmtval);
777 	n = recv(peer, buf, sizeof (buf), 0); /* normally times out and quits */
778 	alarm(0);
779 	if (n >= 4 &&                   /* if read some data */
780 	    dp->th_opcode == DATA &&    /* and got a data block */
781 	    block == dp->th_block) {	/* then my last ack was lost */
782 		(void) send(peer, ackbuf, 4, 0);     /* resend final ack */
783 	}
784 abort:
785 	return;
786 }
787 
788 const struct errmsg {
789 	int		 e_code;
790 	const char	*e_msg;
791 } errmsgs[] = {
792 	{ EUNDEF,	"Undefined error code" },
793 	{ ENOTFOUND,	"File not found" },
794 	{ EACCESS,	"Access violation" },
795 	{ ENOSPACE,	"Disk full or allocation exceeded" },
796 	{ EBADOP,	"Illegal TFTP operation" },
797 	{ EBADID,	"Unknown transfer ID" },
798 	{ EEXISTS,	"File already exists" },
799 	{ ENOUSER,	"No such user" },
800 	{ -1,		0 }
801 };
802 
803 static const char *
804 errtomsg(int error)
805 {
806 	static char ebuf[20];
807 	const struct errmsg *pe;
808 
809 	if (error == 0)
810 		return ("success");
811 	for (pe = errmsgs; pe->e_code >= 0; pe++)
812 		if (pe->e_code == error)
813 			return (pe->e_msg);
814 	snprintf(ebuf, sizeof(ebuf), "error %d", error);
815 	return (ebuf);
816 }
817 
818 /*
819  * Send a nak packet (error message).
820  * Error code passed in is one of the
821  * standard TFTP codes, or a UNIX errno
822  * offset by 100.
823  */
824 static void
825 nak(int error)
826 {
827 	const struct errmsg *pe;
828 	struct tftphdr *tp;
829 	int	length;
830 	size_t	msglen;
831 
832 	tp = (struct tftphdr *)buf;
833 	tp->th_opcode = htons((u_short)ERROR);
834 	msglen = sizeof(buf) - (&tp->th_msg[0] - buf);
835 	for (pe = errmsgs; pe->e_code >= 0; pe++)
836 		if (pe->e_code == error)
837 			break;
838 	if (pe->e_code < 0) {
839 		tp->th_code = EUNDEF;   /* set 'undef' errorcode */
840 		strlcpy(tp->th_msg, strerror(error - 100), msglen);
841 	} else {
842 		tp->th_code = htons((u_short)error);
843 		strlcpy(tp->th_msg, pe->e_msg, msglen);
844 	}
845 	if (debug)
846 		syslog(LOG_DEBUG, "Send NACK %s", tp->th_msg);
847 	length = strlen(tp->th_msg);
848 	msglen = &tp->th_msg[length + 1] - buf;
849 	if (send(peer, buf, msglen, 0) != msglen)
850 		syslog(LOG_ERR, "nak: %m");
851 }
852 
853 static char *
854 verifyhost(struct sockaddr *fromp)
855 {
856 	static char hbuf[MAXHOSTNAMELEN];
857 
858 	if (getnameinfo(fromp, fromp->sa_len, hbuf, sizeof(hbuf), NULL, 0, 0))
859 		strlcpy(hbuf, "?", sizeof(hbuf));
860 	return (hbuf);
861 }
862