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