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