xref: /titanic_51/usr/src/boot/lib/libstand/tftp.c (revision a01cd540d88e418b5c01fad14002e18c745c08be)
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 /*
37  * Simple TFTP implementation for libsa.
38  * Assumes:
39  *  - socket descriptor (int) at open_file->f_devdata
40  *  - server host IP in global servip
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 
64 static int	tftp_open(const char *path, struct open_file *f);
65 static int	tftp_close(struct open_file *f);
66 static int	tftp_parse_oack(struct tftp_handle *h, char *buf, size_t len);
67 static int	tftp_read(struct open_file *f, void *buf, size_t size, size_t *resid);
68 static int	tftp_write(struct open_file *f, void *buf, size_t size, size_t *resid);
69 static off_t	tftp_seek(struct open_file *f, off_t offset, int where);
70 static int	tftp_set_blksize(struct tftp_handle *h, const char *str);
71 static int	tftp_stat(struct open_file *f, struct stat *sb);
72 static ssize_t sendrecv_tftp(struct tftp_handle *h,
73     ssize_t (*sproc)(struct iodesc *, void *, size_t),
74     void *sbuf, size_t ssize,
75     ssize_t (*rproc)(struct tftp_handle *h, void **, void **, time_t, unsigned short *),
76     void **, void **, unsigned short *rtype);
77 
78 struct fs_ops tftp_fsops = {
79 	"tftp",
80 	tftp_open,
81 	tftp_close,
82 	tftp_read,
83 	tftp_write,
84 	tftp_seek,
85 	tftp_stat,
86 	null_readdir
87 };
88 
89 extern struct in_addr servip;
90 
91 static int      tftpport = 2000;
92 static int	is_open = 0;
93 
94 /*
95  * The legacy TFTP_BLKSIZE value was SEGSIZE(512).
96  * TFTP_REQUESTED_BLKSIZE of 1428 is (Ethernet MTU, less the TFTP, UDP and
97  * IP header lengths).
98  */
99 #define TFTP_REQUESTED_BLKSIZE 1428
100 
101 /*
102  * Choose a blksize big enough so we can test with Ethernet
103  * Jumbo frames in the future.
104  */
105 #define TFTP_MAX_BLKSIZE 9008
106 
107 struct tftp_handle {
108 	struct iodesc  *iodesc;
109 	int             currblock;	/* contents of lastdata */
110 	int             islastblock;	/* flag */
111 	int             validsize;
112 	int             off;
113 	char           *path;	/* saved for re-requests */
114 	unsigned int	tftp_blksize;
115 	unsigned long	tftp_tsize;
116 	void		*pkt;
117 	struct tftphdr	*tftp_hdr;
118 };
119 
120 #define	TFTP_MAX_ERRCODE EOPTNEG
121 static const int tftperrors[TFTP_MAX_ERRCODE + 1] = {
122 	0,			/* ??? */
123 	ENOENT,
124 	EPERM,
125 	ENOSPC,
126 	EINVAL,			/* ??? */
127 	EINVAL,			/* ??? */
128 	EEXIST,
129 	EINVAL,			/* ??? */
130 	EINVAL,			/* Option negotiation failed. */
131 };
132 
133 static int  tftp_getnextblock(struct tftp_handle *h);
134 
135 /* send error message back. */
136 static void
137 tftp_senderr(struct tftp_handle *h, u_short errcode, const char *msg)
138 {
139 	struct {
140 		u_char header[HEADER_SIZE];
141 		struct tftphdr  t;
142 		u_char space[63]; /* +1 from t */
143 	} __packed __aligned(4) wbuf;
144 	char           *wtail;
145 	int             len;
146 
147 	len = strlen(msg);
148 	if (len > sizeof(wbuf.space))
149 		len = sizeof(wbuf.space);
150 
151 	wbuf.t.th_opcode = htons((u_short) ERROR);
152 	wbuf.t.th_code   = htons(errcode);
153 
154 	wtail = wbuf.t.th_msg;
155 	bcopy(msg, wtail, len);
156 	wtail[len] = '\0';
157 	wtail += len + 1;
158 
159 	sendudp(h->iodesc, &wbuf.t, wtail - (char *) &wbuf.t);
160 }
161 
162 static void
163 tftp_sendack(struct tftp_handle *h)
164 {
165 	struct {
166 		u_char header[HEADER_SIZE];
167 		struct tftphdr  t;
168 	} __packed __aligned(4) wbuf;
169 	char           *wtail;
170 
171 	wbuf.t.th_opcode = htons((u_short) ACK);
172 	wtail = (char *) &wbuf.t.th_block;
173 	wbuf.t.th_block = htons((u_short) h->currblock);
174 	wtail += 2;
175 
176 	sendudp(h->iodesc, &wbuf.t, wtail - (char *) &wbuf.t);
177 }
178 
179 static ssize_t
180 recvtftp(struct tftp_handle *h, void **pkt, void **payload, time_t tleft,
181     unsigned short *rtype)
182 {
183 	struct iodesc *d = h->iodesc;
184 	struct tftphdr *t;
185 	void *ptr = NULL;
186 	ssize_t len;
187 
188 	errno = 0;
189 
190 	len = readudp(d, &ptr, (void **)&t, tleft);
191 
192 	if (len < 4) {
193 		free(ptr);
194 		return (-1);
195 	}
196 
197 	*rtype = ntohs(t->th_opcode);
198 	switch (ntohs(t->th_opcode)) {
199 	case DATA: {
200 		int got;
201 
202 		if (htons(t->th_block) != (u_short) d->xid) {
203 			/*
204 			 * Expected block?
205 			 */
206 			free(ptr);
207 			return (-1);
208 		}
209 		if (d->xid == 1) {
210 			/*
211 			 * First data packet from new port.
212 			 */
213 			struct udphdr *uh;
214 			uh = (struct udphdr *) t - 1;
215 			d->destport = uh->uh_sport;
216 		} /* else check uh_sport has not changed??? */
217 		got = len - (t->th_data - (char *)t);
218 		*pkt = ptr;
219 		*payload = t;
220 		return (got);
221 	}
222 	case ERROR:
223 		if ((unsigned) ntohs(t->th_code) > TFTP_MAX_ERRCODE) {
224 			printf("illegal tftp error %d\n", ntohs(t->th_code));
225 			errno = EIO;
226 		} else {
227 #ifdef TFTP_DEBUG
228 			printf("tftp-error %d\n", ntohs(t->th_code));
229 #endif
230 			errno = tftperrors[ntohs(t->th_code)];
231 		}
232 		free(ptr);
233 		return (-1);
234 	case OACK: {
235 		struct udphdr *uh;
236 		int tftp_oack_len;
237 
238 		/*
239 		 * Unexpected OACK. TFTP transfer already in progress.
240 		 * Drop the pkt.
241 		 */
242 		if (d->xid != 1) {
243 			free(ptr);
244 			return (-1);
245 		}
246 
247 		/*
248 		 * Remember which port this OACK came from, because we need
249 		 * to send the ACK or errors back to it.
250 		 */
251 		uh = (struct udphdr *) t - 1;
252 		d->destport = uh->uh_sport;
253 
254 		/* Parse options ACK-ed by the server. */
255 		tftp_oack_len = len - sizeof(t->th_opcode);
256 		if (tftp_parse_oack(h, t->th_u.tu_stuff, tftp_oack_len) != 0) {
257 			tftp_senderr(h, EOPTNEG, "Malformed OACK");
258 			errno = EIO;
259 			free(ptr);
260 			return (-1);
261 		}
262 		*pkt = ptr;
263 		*payload = t;
264 		return (0);
265 	}
266 	default:
267 #ifdef TFTP_DEBUG
268 		printf("tftp type %d not handled\n", ntohs(t->th_opcode));
269 #endif
270 		free(ptr);
271 		return (-1);
272 	}
273 }
274 
275 /* send request, expect first block (or error) */
276 static int
277 tftp_makereq(struct tftp_handle *h)
278 {
279 	struct {
280 		u_char header[HEADER_SIZE];
281 		struct tftphdr  t;
282 		u_char space[FNAME_SIZE + 6];
283 	} __packed __aligned(4) wbuf;
284 	char           *wtail;
285 	int             l;
286 	ssize_t         res;
287 	void *pkt;
288 	struct tftphdr *t;
289 	char *tftp_blksize = NULL;
290 	int blksize_l;
291 	unsigned short rtype = 0;
292 
293 	/*
294 	 * Allow overriding default TFTP block size by setting
295 	 * a tftp.blksize environment variable.
296 	 */
297 	if ((tftp_blksize = getenv("tftp.blksize")) != NULL) {
298 		tftp_set_blksize(h, tftp_blksize);
299 	}
300 
301 	wbuf.t.th_opcode = htons((u_short) RRQ);
302 	wtail = wbuf.t.th_stuff;
303 	l = strlen(h->path);
304 #ifdef TFTP_PREPEND_PATH
305 	if (l > FNAME_SIZE - (sizeof(TFTP_PREPEND_PATH) - 1))
306 		return (ENAMETOOLONG);
307 	bcopy(TFTP_PREPEND_PATH, wtail, sizeof(TFTP_PREPEND_PATH) - 1);
308 	wtail += sizeof(TFTP_PREPEND_PATH) - 1;
309 #else
310 	if (l > FNAME_SIZE)
311 		return (ENAMETOOLONG);
312 #endif
313 	bcopy(h->path, wtail, l + 1);
314 	wtail += l + 1;
315 	bcopy("octet", wtail, 6);
316 	wtail += 6;
317 	bcopy("blksize", wtail, 8);
318 	wtail += 8;
319 	blksize_l = sprintf(wtail, "%d", h->tftp_blksize);
320 	wtail += blksize_l + 1;
321 	bcopy("tsize", wtail, 6);
322 	wtail += 6;
323 	bcopy("0", wtail, 2);
324 	wtail += 2;
325 
326 	/* h->iodesc->myport = htons(--tftpport); */
327 	h->iodesc->myport = htons(tftpport + (getsecs() & 0x3ff));
328 	h->iodesc->destport = htons(IPPORT_TFTP);
329 	h->iodesc->xid = 1;	/* expected block */
330 
331 	h->currblock = 0;
332 	h->islastblock = 0;
333 	h->validsize = 0;
334 
335 	pkt = NULL;
336 	res = sendrecv_tftp(h, &sendudp, &wbuf.t, wtail - (char *) &wbuf.t,
337 		       &recvtftp, &pkt, (void **)&t, &rtype);
338 	if (res == -1) {
339 		free(pkt);
340 		return (errno);
341 	}
342 
343 	free(h->pkt);
344 	h->pkt = pkt;
345 	h->tftp_hdr = t;
346 
347 	if (rtype == OACK)
348 		return (tftp_getnextblock(h));
349 
350 	/* Server ignored our blksize request, revert to TFTP default. */
351 	h->tftp_blksize = SEGSIZE;
352 
353 	switch (rtype) {
354 		case DATA: {
355 			h->currblock = 1;
356 			h->validsize = res;
357 			h->islastblock = 0;
358 			if (res < h->tftp_blksize) {
359 				h->islastblock = 1;	/* very short file */
360 				tftp_sendack(h);
361 			}
362 			return (0);
363 		}
364 		case ERROR:
365 		default:
366 			return (errno);
367 	}
368 
369 }
370 
371 /* ack block, expect next */
372 static int
373 tftp_getnextblock(struct tftp_handle *h)
374 {
375 	struct {
376 		u_char header[HEADER_SIZE];
377 		struct tftphdr t;
378 	} __packed __aligned(4) wbuf;
379 	char           *wtail;
380 	int             res;
381 	void *pkt;
382 	struct tftphdr *t;
383 	unsigned short rtype = 0;
384 	wbuf.t.th_opcode = htons((u_short) ACK);
385 	wtail = (char *) &wbuf.t.th_block;
386 	wbuf.t.th_block = htons((u_short) h->currblock);
387 	wtail += 2;
388 
389 	h->iodesc->xid = h->currblock + 1;	/* expected block */
390 
391 	pkt = NULL;
392 	res = sendrecv_tftp(h, &sendudp, &wbuf.t, wtail - (char *) &wbuf.t,
393 		       &recvtftp, &pkt, (void **)&t, &rtype);
394 
395 	if (res == -1) {		/* 0 is OK! */
396 		free(pkt);
397 		return (errno);
398 	}
399 
400 	free(h->pkt);
401 	h->pkt = pkt;
402 	h->tftp_hdr = t;
403 	h->currblock++;
404 	h->validsize = res;
405 	if (res < h->tftp_blksize)
406 		h->islastblock = 1;	/* EOF */
407 
408 	if (h->islastblock == 1) {
409 		/* Send an ACK for the last block */
410 		wbuf.t.th_block = htons((u_short) h->currblock);
411 		sendudp(h->iodesc, &wbuf.t, wtail - (char *)&wbuf.t);
412 	}
413 
414 	return (0);
415 }
416 
417 static int
418 tftp_open(const char *path, struct open_file *f)
419 {
420 	struct tftp_handle *tftpfile;
421 	struct iodesc  *io;
422 	int             res;
423 	size_t          pathsize;
424 	const char     *extraslash;
425 
426 	if (netproto != NET_TFTP)
427 		return (EINVAL);
428 
429 	if (f->f_dev->dv_type != DEVT_NET)
430 		return (EINVAL);
431 
432 	if (is_open)
433 		return (EBUSY);
434 
435 	tftpfile = (struct tftp_handle *) malloc(sizeof(*tftpfile));
436 	if (!tftpfile)
437 		return (ENOMEM);
438 
439 	memset(tftpfile, 0, sizeof(*tftpfile));
440 	tftpfile->tftp_blksize = TFTP_REQUESTED_BLKSIZE;
441 	tftpfile->iodesc = io = socktodesc(*(int *) (f->f_devdata));
442 	if (io == NULL)
443 		return (EINVAL);
444 
445 	io->destip = servip;
446 	tftpfile->off = 0;
447 	pathsize = (strlen(rootpath) + 1 + strlen(path) + 1) * sizeof(char);
448 	tftpfile->path = malloc(pathsize);
449 	if (tftpfile->path == NULL) {
450 		free(tftpfile);
451 		return(ENOMEM);
452 	}
453 	if (rootpath[strlen(rootpath) - 1] == '/' || path[0] == '/')
454 		extraslash = "";
455 	else
456 		extraslash = "/";
457 	res = snprintf(tftpfile->path, pathsize, "%s%s%s",
458 	    rootpath, extraslash, path);
459 	if (res < 0 || res > pathsize) {
460 		free(tftpfile->path);
461 		free(tftpfile);
462 		return(ENOMEM);
463 	}
464 
465 	res = tftp_makereq(tftpfile);
466 
467 	if (res) {
468 		free(tftpfile->path);
469 		free(tftpfile->pkt);
470 		free(tftpfile);
471 		return (res);
472 	}
473 	f->f_fsdata = (void *) tftpfile;
474 	is_open = 1;
475 	return (0);
476 }
477 
478 static int
479 tftp_read(struct open_file *f, void *addr, size_t size,
480     size_t *resid /* out */)
481 {
482 	struct tftp_handle *tftpfile;
483 	tftpfile = (struct tftp_handle *) f->f_fsdata;
484 
485 	while (size > 0) {
486 		int needblock, count;
487 
488 		twiddle(32);
489 
490 		needblock = tftpfile->off / tftpfile->tftp_blksize + 1;
491 
492 		if (tftpfile->currblock > needblock) {	/* seek backwards */
493 			tftp_senderr(tftpfile, 0, "No error: read aborted");
494 			tftp_makereq(tftpfile);	/* no error check, it worked
495 						 * for open */
496 		}
497 
498 		while (tftpfile->currblock < needblock) {
499 			int res;
500 
501 			res = tftp_getnextblock(tftpfile);
502 			if (res) {	/* no answer */
503 #ifdef TFTP_DEBUG
504 				printf("tftp: read error\n");
505 #endif
506 				return (res);
507 			}
508 			if (tftpfile->islastblock)
509 				break;
510 		}
511 
512 		if (tftpfile->currblock == needblock) {
513 			int offinblock, inbuffer;
514 
515 			offinblock = tftpfile->off % tftpfile->tftp_blksize;
516 
517 			inbuffer = tftpfile->validsize - offinblock;
518 			if (inbuffer < 0) {
519 #ifdef TFTP_DEBUG
520 				printf("tftp: invalid offset %d\n",
521 				    tftpfile->off);
522 #endif
523 				return (EINVAL);
524 			}
525 			count = (size < inbuffer ? size : inbuffer);
526 			bcopy(tftpfile->tftp_hdr->th_data + offinblock,
527 			    addr, count);
528 
529 			addr = (char *)addr + count;
530 			tftpfile->off += count;
531 			size -= count;
532 
533 			if ((tftpfile->islastblock) && (count == inbuffer))
534 				break;	/* EOF */
535 		} else {
536 #ifdef TFTP_DEBUG
537 			printf("tftp: block %d not found\n", needblock);
538 #endif
539 			return (EINVAL);
540 		}
541 
542 	}
543 
544 	if (resid)
545 		*resid = size;
546 	return (0);
547 }
548 
549 static int
550 tftp_close(struct open_file *f)
551 {
552 	struct tftp_handle *tftpfile;
553 	tftpfile = (struct tftp_handle *) f->f_fsdata;
554 
555 	/* let it time out ... */
556 
557 	if (tftpfile) {
558 		free(tftpfile->path);
559 		free(tftpfile->pkt);
560 		free(tftpfile);
561 	}
562 	is_open = 0;
563 	return (0);
564 }
565 
566 static int
567 tftp_write(struct open_file *f __unused, void *start __unused, size_t size __unused,
568     size_t *resid __unused /* out */)
569 {
570 	return (EROFS);
571 }
572 
573 static int
574 tftp_stat(struct open_file *f, struct stat *sb)
575 {
576 	struct tftp_handle *tftpfile;
577 	tftpfile = (struct tftp_handle *) f->f_fsdata;
578 
579 	sb->st_mode = 0444 | S_IFREG;
580 	sb->st_nlink = 1;
581 	sb->st_uid = 0;
582 	sb->st_gid = 0;
583 	sb->st_size = (off_t) tftpfile->tftp_tsize;
584 	return (0);
585 }
586 
587 static off_t
588 tftp_seek(struct open_file *f, off_t offset, int where)
589 {
590 	struct tftp_handle *tftpfile;
591 	tftpfile = (struct tftp_handle *) f->f_fsdata;
592 
593 	switch (where) {
594 	case SEEK_SET:
595 		tftpfile->off = offset;
596 		break;
597 	case SEEK_CUR:
598 		tftpfile->off += offset;
599 		break;
600 	default:
601 		errno = EOFFSET;
602 		return (-1);
603 	}
604 	return (tftpfile->off);
605 }
606 
607 static ssize_t
608 sendrecv_tftp(struct tftp_handle *h,
609     ssize_t (*sproc)(struct iodesc *, void *, size_t),
610     void *sbuf, size_t ssize,
611     ssize_t (*rproc)(struct tftp_handle *, void **, void **, time_t,
612     unsigned short *),
613     void **pkt, void **payload, unsigned short *rtype)
614 {
615 	struct iodesc *d = h->iodesc;
616 	ssize_t cc;
617 	time_t t, t1, tleft;
618 
619 #ifdef TFTP_DEBUG
620 	if (debug)
621 		printf("sendrecv: called\n");
622 #endif
623 
624 	tleft = MINTMO;
625 	t = t1 = getsecs();
626 	for (;;) {
627 		if ((getsecs() - t) > MAXTMO) {
628 			errno = ETIMEDOUT;
629 			return -1;
630 		}
631 
632 		cc = (*sproc)(d, sbuf, ssize);
633 		if (cc != -1 && cc < ssize)
634 			panic("sendrecv: short write! (%zd < %zu)",
635 			    cc, ssize);
636 
637 		if (cc == -1) {
638 			/* Error on transmit; wait before retrying */
639 			while ((getsecs() - t1) < tleft);
640 			t1 = getsecs();
641 			continue;
642 		}
643 
644 		t = t1 = getsecs();
645 recvnext:
646 		if ((getsecs() - t) > MAXTMO) {
647 			errno = ETIMEDOUT;
648 			return (-1);
649 		}
650 		/* Try to get a packet and process it. */
651 		cc = (*rproc)(h, pkt, payload, tleft, rtype);
652 		/* Return on data, EOF or real error. */
653 		if (cc != -1 || (errno != 0 && errno != ETIMEDOUT))
654 			return (cc);
655 		if ((getsecs() - t1) < tleft) {
656 		    goto recvnext;
657 		}
658 
659 		/* Timed out or didn't get the packet we're waiting for */
660 		tleft += MINTMO;
661 		if (tleft > (2 * MINTMO)) {
662 			tleft = (2 * MINTMO);
663 		}
664 		t1 = getsecs();
665 	}
666 }
667 
668 static int
669 tftp_set_blksize(struct tftp_handle *h, const char *str)
670 {
671         char *endptr;
672 	int new_blksize;
673 	int ret = 0;
674 
675 	if (h == NULL || str == NULL)
676 		return (ret);
677 
678 	new_blksize =
679 	    (unsigned int)strtol(str, &endptr, 0);
680 
681 	/*
682 	 * Only accept blksize value if it is numeric.
683 	 * RFC2348 specifies that acceptable values are 8-65464.
684 	 * Let's choose a limit less than MAXRSPACE.
685 	 */
686 	if (*endptr == '\0' && new_blksize >= 8
687 	    && new_blksize <= TFTP_MAX_BLKSIZE) {
688 		h->tftp_blksize = new_blksize;
689 		ret = 1;
690 	}
691 
692 	return (ret);
693 }
694 
695 /*
696  * In RFC2347, the TFTP Option Acknowledgement package (OACK)
697  * is used to acknowledge a client's option negotiation request.
698  * The format of an OACK packet is:
699  *    +-------+---~~---+---+---~~---+---+---~~---+---+---~~---+---+
700  *    |  opc  |  opt1  | 0 | value1 | 0 |  optN  | 0 | valueN | 0 |
701  *    +-------+---~~---+---+---~~---+---+---~~---+---+---~~---+---+
702  *
703  *    opc
704  *       The opcode field contains a 6, for Option Acknowledgment.
705  *
706  *    opt1
707  *       The first option acknowledgment, copied from the original
708  *       request.
709  *
710  *    value1
711  *       The acknowledged value associated with the first option.  If
712  *       and how this value may differ from the original request is
713  *       detailed in the specification for the option.
714  *
715  *    optN, valueN
716  *       The final option/value acknowledgment pair.
717  */
718 static int
719 tftp_parse_oack(struct tftp_handle *h, char *buf, size_t len)
720 {
721 	/*
722 	 *  We parse the OACK strings into an array
723 	 *  of name-value pairs.
724 	 */
725 	char *tftp_options[128] = { 0 };
726 	char *val = buf;
727 	int i = 0;
728 	int option_idx = 0;
729 	int blksize_is_set = 0;
730 	int tsize = 0;
731 
732 	unsigned int orig_blksize;
733 
734 	while (option_idx < 128 && i < len) {
735 		if (buf[i] == '\0') {
736 			if (&buf[i] > val) {
737 				tftp_options[option_idx] = val;
738 				val = &buf[i] + 1;
739 				++option_idx;
740 			}
741 		}
742 		++i;
743 	}
744 
745 	/* Save the block size we requested for sanity check later. */
746 	orig_blksize = h->tftp_blksize;
747 
748 	/*
749 	 * Parse individual TFTP options.
750 	 *    * "blksize" is specified in RFC2348.
751 	 *    * "tsize" is specified in RFC2349.
752 	 */
753 	for (i = 0; i < option_idx; i += 2) {
754 	    if (strcasecmp(tftp_options[i], "blksize") == 0) {
755 		if (i + 1 < option_idx)
756 			blksize_is_set =
757 			    tftp_set_blksize(h, tftp_options[i + 1]);
758 	    } else if (strcasecmp(tftp_options[i], "tsize") == 0) {
759 		if (i + 1 < option_idx)
760 			tsize = strtol(tftp_options[i + 1], (char **)NULL, 10);
761 		if (tsize != 0)
762 			h->tftp_tsize = tsize;
763 	    } else {
764 		/* Do not allow any options we did not expect to be ACKed. */
765 		printf("unexpected tftp option '%s'\n", tftp_options[i]);
766 		return (-1);
767 	    }
768 	}
769 
770 	if (!blksize_is_set) {
771 		/*
772 		 * If TFTP blksize was not set, try defaulting
773 		 * to the legacy TFTP blksize of SEGSIZE(512)
774 		 */
775 		h->tftp_blksize = SEGSIZE;
776 	} else if (h->tftp_blksize > orig_blksize) {
777 		/*
778 		 * Server should not be proposing block sizes that
779 		 * exceed what we said we can handle.
780 		 */
781 		printf("unexpected blksize %u\n", h->tftp_blksize);
782 		return (-1);
783 	}
784 
785 #ifdef TFTP_DEBUG
786 	printf("tftp_blksize: %u\n", h->tftp_blksize);
787 	printf("tftp_tsize: %lu\n", h->tftp_tsize);
788 #endif
789 	return 0;
790 }
791