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