1 /* $NetBSD: tftp.c,v 1.4 1997/09/17 16:57:07 drochner Exp $ */
5 * Matthias Drochner. All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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.
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.
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
38 * Simple TFTP implementation for libsa.
40 * - socket descriptor (int) at dev->d_opendata, dev stored at
41 * open_file->f_devdata
42 * - server host IP in global rootip
45 * - lseek only with SEEK_SET or SEEK_CUR
46 * - no big time differences between transfers (<tftp timeout)
49 #include <sys/types.h>
51 #include <netinet/in.h>
52 #include <netinet/udp.h>
53 #include <netinet/in_systm.h>
54 #include <arpa/tftp.h>
58 #include <bootstrap.h>
66 struct tftprecv_extra;
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 *);
78 struct fs_ops tftp_fsops = {
81 .fo_close = tftp_close,
83 .fo_write = null_write,
86 .fo_preload = tftp_preload,
87 .fo_readdir = null_readdir
90 static int tftpport = 2000;
91 static int is_open = 0;
94 * The legacy TFTP_BLKSIZE value was SEGSIZE(512).
95 * TFTP_REQUESTED_BLKSIZE of 1428 is (Ethernet MTU, less the TFTP, UDP and
98 #define TFTP_REQUESTED_BLKSIZE 1428
101 * Choose a blksize big enough so we can test with Ethernet
102 * Jumbo frames in the future.
104 #define TFTP_MAX_BLKSIZE 9008
108 struct iodesc *iodesc;
109 int currblock; /* contents of lastdata */
110 int islastblock:1; /* flag */
111 int tries:4; /* number of read attempts */
114 char *path; /* saved for re-requests */
115 unsigned int tftp_blksize;
116 unsigned long tftp_tsize;
118 struct tftphdr *tftp_hdr;
123 struct tftprecv_extra {
124 struct tftp_handle *tftp_handle;
125 unsigned short rtype; /* Received type */
128 #define TFTP_MAX_ERRCODE EOPTNEG
129 static const int tftperrors[TFTP_MAX_ERRCODE + 1] = {
138 EINVAL, /* Option negotiation failed. */
141 static int tftp_getnextblock(struct tftp_handle *h);
143 /* send error message back. */
145 tftp_senderr(struct tftp_handle *h, u_short errcode, const char *msg)
148 u_char header[HEADER_SIZE];
150 u_char space[63]; /* +1 from t */
151 } __packed __aligned(4) wbuf;
156 if (len > sizeof(wbuf.space))
157 len = sizeof(wbuf.space);
159 wbuf.t.th_opcode = htons((u_short)ERROR);
160 wbuf.t.th_code = htons(errcode);
162 wtail = wbuf.t.th_msg;
163 bcopy(msg, wtail, len);
167 sendudp(h->iodesc, &wbuf.t, wtail - (char *)&wbuf.t);
171 tftp_sendack(struct tftp_handle *h, u_short block)
174 u_char header[HEADER_SIZE];
176 } __packed __aligned(4) wbuf;
179 wbuf.t.th_opcode = htons((u_short)ACK);
180 wtail = (char *)&wbuf.t.th_block;
181 wbuf.t.th_block = htons(block);
184 sendudp(h->iodesc, &wbuf.t, wtail - (char *)&wbuf.t);
188 recvtftp(struct iodesc *d, void **pkt, void **payload, time_t tleft,
191 struct tftprecv_extra *extra;
192 struct tftp_handle *h;
200 h = extra->tftp_handle;
202 len = readudp(d, &ptr, (void **)&t, tleft);
209 extra->rtype = ntohs(t->th_opcode);
210 switch (ntohs(t->th_opcode)) {
214 if (htons(t->th_block) < (u_short)d->xid) {
216 * Apparently our ACK was missed, re-send.
218 tftp_sendack(h, htons(t->th_block));
222 if (htons(t->th_block) != (u_short)d->xid) {
224 * Packet from the future, drop this.
231 * First data packet from new port.
234 uh = (struct udphdr *)t - 1;
235 d->destport = uh->uh_sport;
237 got = len - (t->th_data - (char *)t);
243 tftp_error = ntohs(t->th_code);
244 if ((unsigned)tftp_error > TFTP_MAX_ERRCODE) {
245 printf("illegal tftp error %d\n", tftp_error);
249 printf("tftp-error %d\n", tftp_error);
251 errno = tftperrors[tftp_error];
254 /* If we got a NAK return 0, it's usually a directory */
263 * Unexpected OACK. TFTP transfer already in progress.
272 * Remember which port this OACK came from, because we need
273 * to send the ACK or errors back to it.
275 uh = (struct udphdr *)t - 1;
276 d->destport = uh->uh_sport;
278 /* Parse options ACK-ed by the server. */
279 tftp_oack_len = len - sizeof(t->th_opcode);
280 if (tftp_parse_oack(h, t->th_u.tu_stuff, tftp_oack_len) != 0) {
281 tftp_senderr(h, EOPTNEG, "Malformed OACK");
292 printf("tftp type %d not handled\n", ntohs(t->th_opcode));
299 /* send request, expect first block (or error) */
301 tftp_makereq(struct tftp_handle *h)
304 u_char header[HEADER_SIZE];
306 u_char space[FNAME_SIZE + 6];
307 } __packed __aligned(4) wbuf;
308 struct tftprecv_extra recv_extra;
314 char *tftp_blksize = NULL;
318 * Allow overriding default TFTP block size by setting
319 * a tftp.blksize environment variable.
321 if ((tftp_blksize = getenv("tftp.blksize")) != NULL) {
322 tftp_set_blksize(h, tftp_blksize);
325 wbuf.t.th_opcode = htons((u_short)RRQ);
326 wtail = wbuf.t.th_stuff;
328 #ifdef TFTP_PREPEND_PATH
329 if (l > FNAME_SIZE - (sizeof(TFTP_PREPEND_PATH) - 1))
330 return (ENAMETOOLONG);
331 bcopy(TFTP_PREPEND_PATH, wtail, sizeof(TFTP_PREPEND_PATH) - 1);
332 wtail += sizeof(TFTP_PREPEND_PATH) - 1;
335 return (ENAMETOOLONG);
337 bcopy(h->path, wtail, l + 1);
339 bcopy("octet", wtail, 6);
341 bcopy("blksize", wtail, 8);
343 blksize_l = sprintf(wtail, "%d", h->tftp_blksize);
344 wtail += blksize_l + 1;
345 bcopy("tsize", wtail, 6);
347 bcopy("0", wtail, 2);
350 h->iodesc->myport = htons(tftpport + (getsecs() & 0x3ff));
351 h->iodesc->destport = htons(IPPORT_TFTP);
352 h->iodesc->xid = 1; /* expected block */
359 recv_extra.tftp_handle = h;
360 res = sendrecv(h->iodesc, &sendudp, &wbuf.t, wtail - (char *)&wbuf.t,
361 &recvtftp, &pkt, (void **)&t, &recv_extra);
371 if (recv_extra.rtype == OACK)
372 return (tftp_getnextblock(h));
374 /* Server ignored our blksize request, revert to TFTP default. */
375 h->tftp_blksize = SEGSIZE;
377 switch (recv_extra.rtype) {
382 if (res < h->tftp_blksize) {
383 h->islastblock = 1; /* very short file */
384 tftp_sendack(h, h->currblock);
385 h->lastacksent = true;
396 /* ack block, expect next */
398 tftp_getnextblock(struct tftp_handle *h)
401 u_char header[HEADER_SIZE];
403 } __packed __aligned(4) wbuf;
404 struct tftprecv_extra recv_extra;
410 wbuf.t.th_opcode = htons((u_short)ACK);
411 wtail = (char *)&wbuf.t.th_block;
412 wbuf.t.th_block = htons((u_short)h->currblock);
415 h->iodesc->xid = h->currblock + 1; /* expected block */
418 recv_extra.tftp_handle = h;
419 res = sendrecv(h->iodesc, &sendudp, &wbuf.t, wtail - (char *)&wbuf.t,
420 &recvtftp, &pkt, (void **)&t, &recv_extra);
422 if (res == -1) { /* 0 is OK! */
432 if (res < h->tftp_blksize)
433 h->islastblock = 1; /* EOF */
435 if (h->islastblock == 1) {
436 /* Send an ACK for the last block */
437 wbuf.t.th_block = htons((u_short)h->currblock);
438 sendudp(h->iodesc, &wbuf.t, wtail - (char *)&wbuf.t);
445 tftp_open(const char *path, struct open_file *f)
448 struct tftp_handle *tftpfile;
452 const char *extraslash;
454 if (netproto != NET_TFTP)
457 if (f->f_dev->dv_type != DEVT_NET)
463 tftpfile = calloc(1, sizeof(*tftpfile));
467 tftpfile->tftp_blksize = TFTP_REQUESTED_BLKSIZE;
469 tftpfile->iodesc = io = socktodesc(*(int *)(dev->d_opendata));
477 pathsize = (strlen(rootpath) + 1 + strlen(path) + 1) * sizeof(char);
478 tftpfile->path = malloc(pathsize);
479 if (tftpfile->path == NULL) {
483 if (rootpath[strlen(rootpath) - 1] == '/' || path[0] == '/')
487 res = snprintf(tftpfile->path, pathsize, "%s%s%s",
488 rootpath, extraslash, path);
489 if (res < 0 || res > pathsize) {
490 free(tftpfile->path);
495 res = tftp_makereq(tftpfile);
498 free(tftpfile->path);
503 f->f_fsdata = tftpfile;
509 tftp_read(struct open_file *f, void *addr, size_t size,
510 size_t *resid /* out */)
512 struct tftp_handle *tftpfile;
518 tftpfile = f->f_fsdata;
520 /* Make sure we will not read past file end */
521 if (tftpfile->tftp_tsize > 0 &&
522 tftpfile->off + size > tftpfile->tftp_tsize) {
523 size = tftpfile->tftp_tsize - tftpfile->off;
526 if (tftpfile->tftp_cache != NULL) {
527 bcopy(tftpfile->tftp_cache + tftpfile->off,
530 addr = (char *)addr + size;
531 tftpfile->off += size;
537 int needblock, count;
541 needblock = tftpfile->off / tftpfile->tftp_blksize + 1;
543 if (tftpfile->currblock > needblock) { /* seek backwards */
544 tftp_senderr(tftpfile, 0, "No error: read aborted");
545 rc = tftp_makereq(tftpfile);
550 while (tftpfile->currblock < needblock) {
552 rc = tftp_getnextblock(tftpfile);
553 if (rc) { /* no answer */
555 printf("tftp: read error\n");
557 if (tftpfile->tries > TFTP_TRIES) {
561 tftp_makereq(tftpfile);
564 if (tftpfile->islastblock)
568 if (tftpfile->currblock == needblock) {
569 int offinblock, inbuffer;
571 offinblock = tftpfile->off % tftpfile->tftp_blksize;
573 inbuffer = tftpfile->validsize - offinblock;
576 printf("tftp: invalid offset %d\n",
581 count = (size < inbuffer ? size : inbuffer);
582 bcopy(tftpfile->tftp_hdr->th_data + offinblock,
585 addr = (char *)addr + count;
586 tftpfile->off += count;
590 if ((tftpfile->islastblock) && (count == inbuffer))
594 printf("tftp: block %d not found\n", needblock);
608 tftp_close(struct open_file *f)
610 struct tftp_handle *tftpfile;
611 tftpfile = f->f_fsdata;
613 if (tftpfile->lastacksent == false)
614 tftp_senderr(tftpfile, 0, "No error: file closed");
617 free(tftpfile->path);
619 free(tftpfile->tftp_cache);
627 tftp_stat(struct open_file *f, struct stat *sb)
629 struct tftp_handle *tftpfile;
630 tftpfile = f->f_fsdata;
632 sb->st_mode = 0444 | S_IFREG;
636 sb->st_size = tftpfile->tftp_tsize;
641 tftp_seek(struct open_file *f, off_t offset, int where)
643 struct tftp_handle *tftpfile;
644 tftpfile = f->f_fsdata;
648 tftpfile->off = offset;
651 tftpfile->off += offset;
657 return (tftpfile->off);
661 tftp_preload(struct open_file *f)
663 struct tftp_handle *tftpfile;
670 tftpfile = f->f_fsdata;
671 cache = malloc(sizeof(char) * tftpfile->tftp_tsize);
673 printf("Couldn't allocate %ju bytes for preload caching"
674 ", disabling caching\n",
675 (uintmax_t)sizeof(char) * tftpfile->tftp_tsize);
681 printf("Preloading %s ", tftpfile->path);
683 if (tftpfile->currblock == 1)
684 bcopy(tftpfile->tftp_hdr->th_data,
686 tftpfile->validsize);
688 tftpfile->currblock = 0;
690 while (tftpfile->islastblock == 0) {
692 rc = tftp_getnextblock(tftpfile);
695 printf("Got TFTP error %d, disabling caching\n", rc);
698 bcopy(tftpfile->tftp_hdr->th_data,
699 cache + (tftpfile->tftp_blksize * (tftpfile->currblock - 1)),
700 tftpfile->validsize);
704 printf("\nPreloaded %s (%ju bytes) during %jd seconds\n",
705 tftpfile->path, (intmax_t)tftpfile->tftp_tsize,
706 (intmax_t)end - start);
709 tftpfile->tftp_cache = cache;
714 tftp_set_blksize(struct tftp_handle *h, const char *str)
720 if (h == NULL || str == NULL)
724 (unsigned int)strtol(str, &endptr, 0);
727 * Only accept blksize value if it is numeric.
728 * RFC2348 specifies that acceptable values are 8-65464.
729 * Let's choose a limit less than MAXRSPACE.
731 if (*endptr == '\0' && new_blksize >= 8 &&
732 new_blksize <= TFTP_MAX_BLKSIZE) {
733 h->tftp_blksize = new_blksize;
741 * In RFC2347, the TFTP Option Acknowledgement package (OACK)
742 * is used to acknowledge a client's option negotiation request.
743 * The format of an OACK packet is:
744 * +-------+---~~---+---+---~~---+---+---~~---+---+---~~---+---+
745 * | opc | opt1 | 0 | value1 | 0 | optN | 0 | valueN | 0 |
746 * +-------+---~~---+---+---~~---+---+---~~---+---+---~~---+---+
749 * The opcode field contains a 6, for Option Acknowledgment.
752 * The first option acknowledgment, copied from the original
756 * The acknowledged value associated with the first option. If
757 * and how this value may differ from the original request is
758 * detailed in the specification for the option.
761 * The final option/value acknowledgment pair.
764 tftp_parse_oack(struct tftp_handle *h, char *buf, size_t len)
767 * We parse the OACK strings into an array
768 * of name-value pairs.
770 char *tftp_options[128] = { 0 };
774 int blksize_is_set = 0;
777 unsigned int orig_blksize;
779 while (option_idx < 128 && i < len) {
780 if (buf[i] == '\0') {
782 tftp_options[option_idx] = val;
790 /* Save the block size we requested for sanity check later. */
791 orig_blksize = h->tftp_blksize;
794 * Parse individual TFTP options.
795 * * "blksize" is specified in RFC2348.
796 * * "tsize" is specified in RFC2349.
798 for (i = 0; i < option_idx; i += 2) {
799 if (strcasecmp(tftp_options[i], "blksize") == 0) {
800 if (i + 1 < option_idx)
802 tftp_set_blksize(h, tftp_options[i + 1]);
803 } else if (strcasecmp(tftp_options[i], "tsize") == 0) {
804 if (i + 1 < option_idx)
805 tsize = strtol(tftp_options[i + 1], NULL, 10);
807 h->tftp_tsize = tsize;
810 * Do not allow any options we did not expect to be
813 printf("unexpected tftp option '%s'\n",
819 if (!blksize_is_set) {
821 * If TFTP blksize was not set, try defaulting
822 * to the legacy TFTP blksize of SEGSIZE(512)
824 h->tftp_blksize = SEGSIZE;
825 } else if (h->tftp_blksize > orig_blksize) {
827 * Server should not be proposing block sizes that
828 * exceed what we said we can handle.
830 printf("unexpected blksize %u\n", h->tftp_blksize);
835 printf("tftp_blksize: %u\n", h->tftp_blksize);
836 printf("tftp_tsize: %lu\n", h->tftp_tsize);