xref: /freebsd/stand/libsa/tftp.c (revision 2e3f49888ec8851bafb22011533217487764fdb0)
1 /*	$NetBSD: tftp.c,v 1.4 1997/09/17 16:57:07 drochner Exp $	 */
2 
3 /*
4  * Copyright (c) 1996
5  *	Matthias Drochner.  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 for the NetBSD Project
18  *	by Matthias Drochner.
19  * 4. The name of the author may not be used to endorse or promote products
20  *    derived from this software without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
23  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
24  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
25  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
27  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
31  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  */
33 
34 #include <sys/cdefs.h>
35 /*
36  * Simple TFTP implementation for libsa.
37  * Assumes:
38  *  - socket descriptor (int) at dev->d_opendata, dev stored at
39  *	open_file->f_devdata
40  *  - server host IP in global rootip
41  * Restrictions:
42  *  - read only
43  *  - lseek only with SEEK_SET or SEEK_CUR
44  *  - no big time differences between transfers (<tftp timeout)
45  */
46 
47 #include <sys/types.h>
48 #include <sys/stat.h>
49 #include <netinet/in.h>
50 #include <netinet/udp.h>
51 #include <netinet/in_systm.h>
52 #include <arpa/tftp.h>
53 
54 #include <string.h>
55 
56 #include "stand.h"
57 #include "net.h"
58 #include "netif.h"
59 
60 #include "tftp.h"
61 
62 struct tftp_handle;
63 struct tftprecv_extra;
64 
65 static ssize_t recvtftp(struct iodesc *, void **, void **, time_t, void *);
66 static int tftp_open(const char *, struct open_file *);
67 static int tftp_close(struct open_file *);
68 static int tftp_parse_oack(struct tftp_handle *, char *, size_t);
69 static int tftp_read(struct open_file *, void *, size_t, size_t *);
70 static off_t tftp_seek(struct open_file *, off_t, int);
71 static int tftp_set_blksize(struct tftp_handle *, const char *);
72 static int tftp_stat(struct open_file *, struct stat *);
73 static int tftp_preload(struct open_file *);
74 
75 struct fs_ops tftp_fsops = {
76 	.fs_name = "tftp",
77 	.fo_open = tftp_open,
78 	.fo_close = tftp_close,
79 	.fo_read = tftp_read,
80 	.fo_write = null_write,
81 	.fo_seek = tftp_seek,
82 	.fo_stat = tftp_stat,
83 	.fo_preload = tftp_preload,
84 	.fo_readdir = null_readdir
85 };
86 
87 static int	tftpport = 2000;
88 static int	is_open = 0;
89 
90 /*
91  * The legacy TFTP_BLKSIZE value was SEGSIZE(512).
92  * TFTP_REQUESTED_BLKSIZE of 1428 is (Ethernet MTU, less the TFTP, UDP and
93  * IP header lengths).
94  */
95 #define	TFTP_REQUESTED_BLKSIZE 1428
96 
97 /*
98  * Choose a blksize big enough so we can test with Ethernet
99  * Jumbo frames in the future.
100  */
101 #define	TFTP_MAX_BLKSIZE 9008
102 #define TFTP_TRIES 2
103 
104 struct tftp_handle {
105 	struct iodesc  *iodesc;
106 	int		currblock;	/* contents of lastdata */
107 	unsigned int	islastblock:1;	/* flag */
108 	unsigned int	tries:4;	/* number of read attempts */
109 	int		validsize;
110 	int		off;
111 	char		*path;	/* saved for re-requests */
112 	unsigned int	tftp_blksize;
113 	unsigned long	tftp_tsize;
114 	void		*pkt;
115 	struct tftphdr	*tftp_hdr;
116 	char		*tftp_cache;
117 	bool		lastacksent;
118 };
119 
120 struct tftprecv_extra {
121 	struct tftp_handle	*tftp_handle;
122 	unsigned short		rtype;		/* Received type */
123 };
124 
125 #define	TFTP_MAX_ERRCODE EOPTNEG
126 static const int tftperrors[TFTP_MAX_ERRCODE + 1] = {
127 	0,			/* NAK */
128 	ENOENT,
129 	EPERM,
130 	ENOSPC,
131 	EINVAL,			/* ??? */
132 	EINVAL,			/* ??? */
133 	EEXIST,
134 	EINVAL,			/* ??? */
135 	EINVAL,			/* Option negotiation failed. */
136 };
137 
138 static int  tftp_getnextblock(struct tftp_handle *h);
139 
140 /* send error message back. */
141 static void
142 tftp_senderr(struct tftp_handle *h, u_short errcode, const char *msg)
143 {
144 	struct {
145 		u_char header[HEADER_SIZE];
146 		struct tftphdr t;
147 		u_char space[63]; /* +1 from t */
148 	} __packed __aligned(4) wbuf;
149 	char *wtail;
150 	int len;
151 
152 	len = strlen(msg);
153 	if (len > sizeof(wbuf.space))
154 		len = sizeof(wbuf.space);
155 
156 	wbuf.t.th_opcode = htons((u_short)ERROR);
157 	wbuf.t.th_code = htons(errcode);
158 
159 	wtail = wbuf.t.th_msg;
160 	bcopy(msg, wtail, len);
161 	wtail[len] = '\0';
162 	wtail += len + 1;
163 
164 	sendudp(h->iodesc, &wbuf.t, wtail - (char *)&wbuf.t);
165 }
166 
167 static void
168 tftp_sendack(struct tftp_handle *h, u_short block)
169 {
170 	struct {
171 		u_char header[HEADER_SIZE];
172 		struct tftphdr  t;
173 	} __packed __aligned(4) wbuf;
174 	char *wtail;
175 
176 	wbuf.t.th_opcode = htons((u_short)ACK);
177 	wtail = (char *)&wbuf.t.th_block;
178 	wbuf.t.th_block = htons(block);
179 	wtail += 2;
180 
181 	sendudp(h->iodesc, &wbuf.t, wtail - (char *)&wbuf.t);
182 }
183 
184 static ssize_t
185 recvtftp(struct iodesc *d, void **pkt, void **payload, time_t tleft,
186     void *recv_extra)
187 {
188 	struct tftprecv_extra *extra;
189 	struct tftp_handle *h;
190 	struct tftphdr *t;
191 	void *ptr = NULL;
192 	ssize_t len;
193 	int tftp_error;
194 
195 	errno = 0;
196 	extra = recv_extra;
197 	h = extra->tftp_handle;
198 
199 	len = readudp(d, &ptr, (void **)&t, tleft);
200 
201 	if (len < 4) {
202 		free(ptr);
203 		return (-1);
204 	}
205 
206 	extra->rtype = ntohs(t->th_opcode);
207 	switch (ntohs(t->th_opcode)) {
208 	case DATA: {
209 		int got;
210 
211 		if (htons(t->th_block) < (u_short)d->xid) {
212 			/*
213 			 * Apparently our ACK was missed, re-send.
214 			 */
215 			tftp_sendack(h, htons(t->th_block));
216 			free(ptr);
217 			return (-1);
218 		}
219 		if (htons(t->th_block) != (u_short)d->xid) {
220 			/*
221 			 * Packet from the future, drop this.
222 			 */
223 			free(ptr);
224 			return (-1);
225 		}
226 		if (d->xid == 1) {
227 			/*
228 			 * First data packet from new port.
229 			 */
230 			struct udphdr *uh;
231 			uh = (struct udphdr *)t - 1;
232 			d->destport = uh->uh_sport;
233 		}
234 		got = len - (t->th_data - (char *)t);
235 		*pkt = ptr;
236 		*payload = t;
237 		return (got);
238 	}
239 	case ERROR:
240 		tftp_error = ntohs(t->th_code);
241 		if ((unsigned)tftp_error > TFTP_MAX_ERRCODE) {
242 			printf("illegal tftp error %d\n", tftp_error);
243 			errno = EIO;
244 		} else {
245 #ifdef TFTP_DEBUG
246 			printf("tftp-error %d\n", tftp_error);
247 #endif
248 			errno = tftperrors[tftp_error];
249 		}
250 		free(ptr);
251 		/* If we got a NAK return 0, it's usually a directory */
252 		if (tftp_error == 0)
253 			return (0);
254 		return (-1);
255 	case OACK: {
256 		struct udphdr *uh;
257 		int tftp_oack_len;
258 
259 		/*
260 		 * Unexpected OACK. TFTP transfer already in progress.
261 		 * Drop the pkt.
262 		 */
263 		if (d->xid != 1) {
264 			free(ptr);
265 			return (-1);
266 		}
267 
268 		/*
269 		 * Remember which port this OACK came from, because we need
270 		 * to send the ACK or errors back to it.
271 		 */
272 		uh = (struct udphdr *)t - 1;
273 		d->destport = uh->uh_sport;
274 
275 		/* Parse options ACK-ed by the server. */
276 		tftp_oack_len = len - sizeof(t->th_opcode);
277 		if (tftp_parse_oack(h, t->th_u.tu_stuff, tftp_oack_len) != 0) {
278 			tftp_senderr(h, EOPTNEG, "Malformed OACK");
279 			errno = EIO;
280 			free(ptr);
281 			return (-1);
282 		}
283 		*pkt = ptr;
284 		*payload = t;
285 		return (0);
286 	}
287 	default:
288 #ifdef TFTP_DEBUG
289 		printf("tftp type %d not handled\n", ntohs(t->th_opcode));
290 #endif
291 		free(ptr);
292 		return (-1);
293 	}
294 }
295 
296 /* send request, expect first block (or error) */
297 static int
298 tftp_makereq(struct tftp_handle *h)
299 {
300 	struct {
301 		u_char header[HEADER_SIZE];
302 		struct tftphdr  t;
303 		u_char space[FNAME_SIZE + 6];
304 	} __packed __aligned(4) wbuf;
305 	struct tftprecv_extra recv_extra;
306 	char *wtail;
307 	int l;
308 	ssize_t res;
309 	void *pkt;
310 	struct tftphdr *t;
311 	char *tftp_blksize = NULL;
312 	int blksize_l;
313 
314 	/*
315 	 * Allow overriding default TFTP block size by setting
316 	 * a tftp.blksize environment variable.
317 	 */
318 	if ((tftp_blksize = getenv("tftp.blksize")) != NULL) {
319 		tftp_set_blksize(h, tftp_blksize);
320 	}
321 
322 	wbuf.t.th_opcode = htons((u_short)RRQ);
323 	wtail = wbuf.t.th_stuff;
324 	l = strlen(h->path);
325 #ifdef TFTP_PREPEND_PATH
326 	if (l > FNAME_SIZE - (sizeof(TFTP_PREPEND_PATH) - 1))
327 		return (ENAMETOOLONG);
328 	bcopy(TFTP_PREPEND_PATH, wtail, sizeof(TFTP_PREPEND_PATH) - 1);
329 	wtail += sizeof(TFTP_PREPEND_PATH) - 1;
330 #else
331 	if (l > FNAME_SIZE)
332 		return (ENAMETOOLONG);
333 #endif
334 	bcopy(h->path, wtail, l + 1);
335 	wtail += l + 1;
336 	bcopy("octet", wtail, 6);
337 	wtail += 6;
338 	bcopy("blksize", wtail, 8);
339 	wtail += 8;
340 	blksize_l = sprintf(wtail, "%d", h->tftp_blksize);
341 	wtail += blksize_l + 1;
342 	bcopy("tsize", wtail, 6);
343 	wtail += 6;
344 	bcopy("0", wtail, 2);
345 	wtail += 2;
346 
347 	h->iodesc->myport = htons(tftpport + (getsecs() & 0x3ff));
348 	h->iodesc->destport = htons(IPPORT_TFTP);
349 	h->iodesc->xid = 1;	/* expected block */
350 
351 	h->currblock = 0;
352 	h->islastblock = 0;
353 	h->validsize = 0;
354 
355 	pkt = NULL;
356 	recv_extra.tftp_handle = h;
357 	res = sendrecv(h->iodesc, &sendudp, &wbuf.t, wtail - (char *)&wbuf.t,
358 	    &recvtftp, &pkt, (void **)&t, &recv_extra);
359 	if (res == -1) {
360 		free(pkt);
361 		return (errno);
362 	}
363 
364 	free(h->pkt);
365 	h->pkt = pkt;
366 	h->tftp_hdr = t;
367 
368 	if (recv_extra.rtype == OACK)
369 		return (tftp_getnextblock(h));
370 
371 	/* Server ignored our blksize request, revert to TFTP default. */
372 	h->tftp_blksize = SEGSIZE;
373 
374 	switch (recv_extra.rtype) {
375 		case DATA: {
376 			h->currblock = 1;
377 			h->validsize = res;
378 			h->islastblock = 0;
379 			if (res < h->tftp_blksize) {
380 				h->islastblock = 1;	/* very short file */
381 				tftp_sendack(h, h->currblock);
382 				h->lastacksent = true;
383 			}
384 			return (0);
385 		}
386 		case ERROR:
387 		default:
388 			return (errno);
389 	}
390 
391 }
392 
393 /* ack block, expect next */
394 static int
395 tftp_getnextblock(struct tftp_handle *h)
396 {
397 	struct {
398 		u_char header[HEADER_SIZE];
399 		struct tftphdr t;
400 	} __packed __aligned(4) wbuf;
401 	struct tftprecv_extra recv_extra;
402 	char *wtail;
403 	int res;
404 	void *pkt;
405 	struct tftphdr *t;
406 
407 	wbuf.t.th_opcode = htons((u_short)ACK);
408 	wtail = (char *)&wbuf.t.th_block;
409 	wbuf.t.th_block = htons((u_short)h->currblock);
410 	wtail += 2;
411 
412 	h->iodesc->xid = h->currblock + 1;	/* expected block */
413 
414 	pkt = NULL;
415 	recv_extra.tftp_handle = h;
416 	res = sendrecv(h->iodesc, &sendudp, &wbuf.t, wtail - (char *)&wbuf.t,
417 	    &recvtftp, &pkt, (void **)&t, &recv_extra);
418 
419 	if (res == -1) {		/* 0 is OK! */
420 		free(pkt);
421 		return (errno);
422 	}
423 
424 	free(h->pkt);
425 	h->pkt = pkt;
426 	h->tftp_hdr = t;
427 	h->currblock++;
428 	h->validsize = res;
429 	if (res < h->tftp_blksize)
430 		h->islastblock = 1;	/* EOF */
431 
432 	if (h->islastblock == 1) {
433 		/* Send an ACK for the last block */
434 		wbuf.t.th_block = htons((u_short)h->currblock);
435 		sendudp(h->iodesc, &wbuf.t, wtail - (char *)&wbuf.t);
436 	}
437 
438 	return (0);
439 }
440 
441 static int
442 tftp_open(const char *path, struct open_file *f)
443 {
444 	struct devdesc *dev;
445 	struct tftp_handle *tftpfile;
446 	struct iodesc	*io;
447 	int		res;
448 	size_t		pathsize;
449 	const char	*extraslash;
450 
451 	if (netproto != NET_TFTP)
452 		return (EINVAL);
453 
454 	if (f->f_dev->dv_type != DEVT_NET)
455 		return (EINVAL);
456 
457 	if (is_open)
458 		return (EBUSY);
459 
460 	tftpfile = calloc(1, sizeof(*tftpfile));
461 	if (!tftpfile)
462 		return (ENOMEM);
463 
464 	tftpfile->tftp_blksize = TFTP_REQUESTED_BLKSIZE;
465 	dev = f->f_devdata;
466 	tftpfile->iodesc = io = socktodesc(*(int *)(dev->d_opendata));
467 	if (io == NULL) {
468 		free(tftpfile);
469 		return (EINVAL);
470 	}
471 
472 	io->destip = rootip;
473 	tftpfile->off = 0;
474 	pathsize = (strlen(rootpath) + 1 + strlen(path) + 1) * sizeof(char);
475 	tftpfile->path = malloc(pathsize);
476 	if (tftpfile->path == NULL) {
477 		free(tftpfile);
478 		return (ENOMEM);
479 	}
480 	if (rootpath[strlen(rootpath) - 1] == '/' || path[0] == '/')
481 		extraslash = "";
482 	else
483 		extraslash = "/";
484 	res = snprintf(tftpfile->path, pathsize, "%s%s%s",
485 	    rootpath, extraslash, path);
486 	if (res < 0 || res > pathsize) {
487 		free(tftpfile->path);
488 		free(tftpfile);
489 		return (ENOMEM);
490 	}
491 
492 	res = tftp_makereq(tftpfile);
493 
494 	if (res) {
495 		free(tftpfile->path);
496 		free(tftpfile->pkt);
497 		free(tftpfile);
498 		return (res);
499 	}
500 	f->f_fsdata = tftpfile;
501 	is_open = 1;
502 	return (0);
503 }
504 
505 static int
506 tftp_read(struct open_file *f, void *addr, size_t size,
507     size_t *resid /* out */)
508 {
509 	struct tftp_handle *tftpfile;
510 	size_t res;
511 	int rc;
512 
513 	rc = 0;
514 	res = size;
515 	tftpfile = f->f_fsdata;
516 
517 	/* Make sure we will not read past file end */
518 	if (tftpfile->tftp_tsize > 0 &&
519 	    tftpfile->off + size > tftpfile->tftp_tsize) {
520 		size = tftpfile->tftp_tsize - tftpfile->off;
521 	}
522 
523 	if (tftpfile->tftp_cache != NULL) {
524 		bcopy(tftpfile->tftp_cache + tftpfile->off,
525 		    addr, size);
526 
527 		addr = (char *)addr + size;
528 		tftpfile->off += size;
529 		res -= size;
530 		goto out;
531 	}
532 
533 	while (size > 0) {
534 		int needblock, count;
535 
536 		twiddle(32);
537 
538 		needblock = tftpfile->off / tftpfile->tftp_blksize + 1;
539 
540 		if (tftpfile->currblock > needblock) {	/* seek backwards */
541 			tftp_senderr(tftpfile, 0, "No error: read aborted");
542 			rc = tftp_makereq(tftpfile);
543 			if (rc != 0)
544 				break;
545 		}
546 
547 		while (tftpfile->currblock < needblock) {
548 
549 			rc = tftp_getnextblock(tftpfile);
550 			if (rc) {	/* no answer */
551 #ifdef TFTP_DEBUG
552 				printf("tftp: read error\n");
553 #endif
554 				if (tftpfile->tries > TFTP_TRIES) {
555 					return (rc);
556 				} else {
557 					tftpfile->tries++;
558 					tftp_makereq(tftpfile);
559 				}
560 			}
561 			if (tftpfile->islastblock)
562 				break;
563 		}
564 
565 		if (tftpfile->currblock == needblock) {
566 			int offinblock, inbuffer;
567 
568 			offinblock = tftpfile->off % tftpfile->tftp_blksize;
569 
570 			inbuffer = tftpfile->validsize - offinblock;
571 			if (inbuffer < 0) {
572 #ifdef TFTP_DEBUG
573 				printf("tftp: invalid offset %d\n",
574 				    tftpfile->off);
575 #endif
576 				return (EINVAL);
577 			}
578 			count = (size < inbuffer ? size : inbuffer);
579 			bcopy(tftpfile->tftp_hdr->th_data + offinblock,
580 			    addr, count);
581 
582 			addr = (char *)addr + count;
583 			tftpfile->off += count;
584 			size -= count;
585 			res -= count;
586 
587 			if ((tftpfile->islastblock) && (count == inbuffer))
588 				break;	/* EOF */
589 		} else {
590 #ifdef TFTP_DEBUG
591 			printf("tftp: block %d not found\n", needblock);
592 #endif
593 			return (EINVAL);
594 		}
595 
596 	}
597 
598 out:
599 	if (resid != NULL)
600 		*resid = res;
601 	return (rc);
602 }
603 
604 static int
605 tftp_close(struct open_file *f)
606 {
607 	struct tftp_handle *tftpfile;
608 	tftpfile = f->f_fsdata;
609 
610 	if (tftpfile->lastacksent == false)
611 		tftp_senderr(tftpfile, 0, "No error: file closed");
612 
613 	if (tftpfile) {
614 		free(tftpfile->path);
615 		free(tftpfile->pkt);
616 		free(tftpfile->tftp_cache);
617 		free(tftpfile);
618 	}
619 	is_open = 0;
620 	return (0);
621 }
622 
623 static int
624 tftp_stat(struct open_file *f, struct stat *sb)
625 {
626 	struct tftp_handle *tftpfile;
627 	tftpfile = f->f_fsdata;
628 
629 	sb->st_mode = 0444 | S_IFREG;
630 	sb->st_nlink = 1;
631 	sb->st_uid = 0;
632 	sb->st_gid = 0;
633 	sb->st_size = tftpfile->tftp_tsize;
634 	return (0);
635 }
636 
637 static off_t
638 tftp_seek(struct open_file *f, off_t offset, int where)
639 {
640 	struct tftp_handle *tftpfile;
641 	tftpfile = f->f_fsdata;
642 
643 	switch (where) {
644 	case SEEK_SET:
645 		tftpfile->off = offset;
646 		break;
647 	case SEEK_CUR:
648 		tftpfile->off += offset;
649 		break;
650 	default:
651 		errno = EOFFSET;
652 		return (-1);
653 	}
654 	return (tftpfile->off);
655 }
656 
657 static int
658 tftp_preload(struct open_file *f)
659 {
660 	struct tftp_handle *tftpfile;
661 	char *cache;
662 	int rc;
663 #ifdef TFTP_DEBUG
664 	time_t start, end;
665 #endif
666 
667 	tftpfile = f->f_fsdata;
668 	cache = malloc(sizeof(char) * tftpfile->tftp_tsize);
669 	if (cache == NULL) {
670 		printf("Couldn't allocate %ju bytes for preload caching"
671 		    ", disabling caching\n",
672 		    (uintmax_t)sizeof(char) * tftpfile->tftp_tsize);
673 		return (-1);
674 	}
675 
676 #ifdef TFTP_DEBUG
677 	start = getsecs();
678 	printf("Preloading %s ", tftpfile->path);
679 #endif
680 	if (tftpfile->currblock == 1)
681 		bcopy(tftpfile->tftp_hdr->th_data,
682 		    cache,
683 		    tftpfile->validsize);
684 	else
685 		tftpfile->currblock = 0;
686 
687 	while (tftpfile->islastblock == 0) {
688 		twiddle(32);
689 		rc = tftp_getnextblock(tftpfile);
690 		if (rc) {
691 			free(cache);
692 			printf("Got TFTP error %d, disabling caching\n", rc);
693 			return (rc);
694 		}
695 		bcopy(tftpfile->tftp_hdr->th_data,
696 		    cache + (tftpfile->tftp_blksize * (tftpfile->currblock - 1)),
697 		    tftpfile->validsize);
698 	}
699 #ifdef TFTP_DEBUG
700 	end = getsecs();
701 	printf("\nPreloaded %s (%ju bytes) during %jd seconds\n",
702 	    tftpfile->path, (intmax_t)tftpfile->tftp_tsize,
703 	    (intmax_t)end - start);
704 #endif
705 
706 	tftpfile->tftp_cache = cache;
707 	return (0);
708 }
709 
710 static int
711 tftp_set_blksize(struct tftp_handle *h, const char *str)
712 {
713 	char *endptr;
714 	int new_blksize;
715 	int ret = 0;
716 
717 	if (h == NULL || str == NULL)
718 		return (ret);
719 
720 	new_blksize =
721 	    (unsigned int)strtol(str, &endptr, 0);
722 
723 	/*
724 	 * Only accept blksize value if it is numeric.
725 	 * RFC2348 specifies that acceptable values are 8-65464.
726 	 * Let's choose a limit less than MAXRSPACE.
727 	 */
728 	if (*endptr == '\0' && new_blksize >= 8 &&
729 	    new_blksize <= TFTP_MAX_BLKSIZE) {
730 		h->tftp_blksize = new_blksize;
731 		ret = 1;
732 	}
733 
734 	return (ret);
735 }
736 
737 /*
738  * In RFC2347, the TFTP Option Acknowledgement package (OACK)
739  * is used to acknowledge a client's option negotiation request.
740  * The format of an OACK packet is:
741  *    +-------+---~~---+---+---~~---+---+---~~---+---+---~~---+---+
742  *    |  opc  |  opt1  | 0 | value1 | 0 |  optN  | 0 | valueN | 0 |
743  *    +-------+---~~---+---+---~~---+---+---~~---+---+---~~---+---+
744  *
745  *    opc
746  *       The opcode field contains a 6, for Option Acknowledgment.
747  *
748  *    opt1
749  *       The first option acknowledgment, copied from the original
750  *       request.
751  *
752  *    value1
753  *       The acknowledged value associated with the first option.  If
754  *       and how this value may differ from the original request is
755  *       detailed in the specification for the option.
756  *
757  *    optN, valueN
758  *       The final option/value acknowledgment pair.
759  */
760 static int
761 tftp_parse_oack(struct tftp_handle *h, char *buf, size_t len)
762 {
763 	/*
764 	 *  We parse the OACK strings into an array
765 	 *  of name-value pairs.
766 	 */
767 	char *tftp_options[128] = { 0 };
768 	char *val = buf;
769 	int i = 0;
770 	int option_idx = 0;
771 	int blksize_is_set = 0;
772 	int tsize = 0;
773 
774 	unsigned int orig_blksize;
775 
776 	while (option_idx < 128 && i < len) {
777 		if (buf[i] == '\0') {
778 			if (&buf[i] > val) {
779 				tftp_options[option_idx] = val;
780 				val = &buf[i] + 1;
781 				++option_idx;
782 			}
783 		}
784 		++i;
785 	}
786 
787 	/* Save the block size we requested for sanity check later. */
788 	orig_blksize = h->tftp_blksize;
789 
790 	/*
791 	 * Parse individual TFTP options.
792 	 *    * "blksize" is specified in RFC2348.
793 	 *    * "tsize" is specified in RFC2349.
794 	 */
795 	for (i = 0; i < option_idx; i += 2) {
796 		if (strcasecmp(tftp_options[i], "blksize") == 0) {
797 			if (i + 1 < option_idx)
798 				blksize_is_set =
799 				    tftp_set_blksize(h, tftp_options[i + 1]);
800 		} else if (strcasecmp(tftp_options[i], "tsize") == 0) {
801 			if (i + 1 < option_idx)
802 				tsize = strtol(tftp_options[i + 1], NULL, 10);
803 			if (tsize != 0)
804 				h->tftp_tsize = tsize;
805 		} else {
806 			/*
807 			 * Do not allow any options we did not expect to be
808 			 * ACKed.
809 			 */
810 			printf("unexpected tftp option '%s'\n",
811 			    tftp_options[i]);
812 			return (-1);
813 		}
814 	}
815 
816 	if (!blksize_is_set) {
817 		/*
818 		 * If TFTP blksize was not set, try defaulting
819 		 * to the legacy TFTP blksize of SEGSIZE(512)
820 		 */
821 		h->tftp_blksize = SEGSIZE;
822 	} else if (h->tftp_blksize > orig_blksize) {
823 		/*
824 		 * Server should not be proposing block sizes that
825 		 * exceed what we said we can handle.
826 		 */
827 		printf("unexpected blksize %u\n", h->tftp_blksize);
828 		return (-1);
829 	}
830 
831 #ifdef TFTP_DEBUG
832 	printf("tftp_blksize: %u\n", h->tftp_blksize);
833 	printf("tftp_tsize: %lu\n", h->tftp_tsize);
834 #endif
835 	return (0);
836 }
837