xref: /freebsd-13.1/stand/libsa/tftp.c (revision d37a33f5)
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 open_file->f_devdata
41  *  - server host IP in global rootip
42  * Restrictions:
43  *  - read only
44  *  - lseek only with SEEK_SET or SEEK_CUR
45  *  - no big time differences between transfers (<tftp timeout)
46  */
47 
48 #include <sys/types.h>
49 #include <sys/stat.h>
50 #include <netinet/in.h>
51 #include <netinet/udp.h>
52 #include <netinet/in_systm.h>
53 #include <arpa/tftp.h>
54 
55 #include <string.h>
56 
57 #include <bootstrap.h>
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
tftp_senderr(struct tftp_handle * h,u_short errcode,const char * msg)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
tftp_sendack(struct tftp_handle * h,u_short block)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
recvtftp(struct iodesc * d,void ** pkt,void ** payload,time_t tleft,void * recv_extra)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
tftp_makereq(struct tftp_handle * h)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
tftp_getnextblock(struct tftp_handle * h)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
tftp_open(const char * path,struct open_file * f)444 tftp_open(const char *path, struct open_file *f)
445 {
446 	struct tftp_handle *tftpfile;
447 	struct iodesc	*io;
448 	int		res;
449 	size_t		pathsize;
450 	const char	*extraslash;
451 
452 	if (netproto != NET_TFTP)
453 		return (EINVAL);
454 
455 	if (f->f_dev->dv_type != DEVT_NET)
456 		return (EINVAL);
457 
458 	if (is_open)
459 		return (EBUSY);
460 
461 	tftpfile = calloc(1, sizeof(*tftpfile));
462 	if (!tftpfile)
463 		return (ENOMEM);
464 
465 	tftpfile->tftp_blksize = TFTP_REQUESTED_BLKSIZE;
466 	tftpfile->iodesc = io = socktodesc(*(int *)(f->f_devdata));
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
tftp_read(struct open_file * f,void * addr,size_t size,size_t * resid)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
tftp_close(struct open_file * f)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
tftp_stat(struct open_file * f,struct stat * sb)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
tftp_seek(struct open_file * f,off_t offset,int where)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
tftp_preload(struct open_file * f)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
tftp_set_blksize(struct tftp_handle * h,const char * str)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
tftp_parse_oack(struct tftp_handle * h,char * buf,size_t len)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