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>
65 struct tftprecv_extra;
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 *);
77 struct fs_ops tftp_fsops = {
80 .fo_close = tftp_close,
82 .fo_write = null_write,
85 .fo_preload = tftp_preload,
86 .fo_readdir = null_readdir
89 static int tftpport = 2000;
90 static int is_open = 0;
93 * The legacy TFTP_BLKSIZE value was SEGSIZE(512).
94 * TFTP_REQUESTED_BLKSIZE of 1428 is (Ethernet MTU, less the TFTP, UDP and
97 #define TFTP_REQUESTED_BLKSIZE 1428
100 * Choose a blksize big enough so we can test with Ethernet
101 * Jumbo frames in the future.
103 #define TFTP_MAX_BLKSIZE 9008
107 struct iodesc *iodesc;
108 int currblock; /* contents of lastdata */
109 int islastblock:1; /* flag */
110 int tries:4; /* number of read attempts */
113 char *path; /* saved for re-requests */
114 unsigned int tftp_blksize;
115 unsigned long tftp_tsize;
117 struct tftphdr *tftp_hdr;
122 struct tftprecv_extra {
123 struct tftp_handle *tftp_handle;
124 unsigned short rtype; /* Received type */
127 #define TFTP_MAX_ERRCODE EOPTNEG
128 static const int tftperrors[TFTP_MAX_ERRCODE + 1] = {
137 EINVAL, /* Option negotiation failed. */
140 static int tftp_getnextblock(struct tftp_handle *h);
142 /* send error message back. */
144 tftp_senderr(struct tftp_handle *h, u_short errcode, const char *msg)
147 u_char header[HEADER_SIZE];
149 u_char space[63]; /* +1 from t */
150 } __packed __aligned(4) wbuf;
155 if (len > sizeof(wbuf.space))
156 len = sizeof(wbuf.space);
158 wbuf.t.th_opcode = htons((u_short)ERROR);
159 wbuf.t.th_code = htons(errcode);
161 wtail = wbuf.t.th_msg;
162 bcopy(msg, wtail, len);
166 sendudp(h->iodesc, &wbuf.t, wtail - (char *)&wbuf.t);
170 tftp_sendack(struct tftp_handle *h, u_short block)
173 u_char header[HEADER_SIZE];
175 } __packed __aligned(4) wbuf;
178 wbuf.t.th_opcode = htons((u_short)ACK);
179 wtail = (char *)&wbuf.t.th_block;
180 wbuf.t.th_block = htons(block);
183 sendudp(h->iodesc, &wbuf.t, wtail - (char *)&wbuf.t);
187 recvtftp(struct iodesc *d, void **pkt, void **payload, time_t tleft,
190 struct tftprecv_extra *extra;
191 struct tftp_handle *h;
199 h = extra->tftp_handle;
201 len = readudp(d, &ptr, (void **)&t, tleft);
208 extra->rtype = ntohs(t->th_opcode);
209 switch (ntohs(t->th_opcode)) {
213 if (htons(t->th_block) < (u_short)d->xid) {
215 * Apparently our ACK was missed, re-send.
217 tftp_sendack(h, htons(t->th_block));
221 if (htons(t->th_block) != (u_short)d->xid) {
223 * Packet from the future, drop this.
230 * First data packet from new port.
233 uh = (struct udphdr *)t - 1;
234 d->destport = uh->uh_sport;
236 got = len - (t->th_data - (char *)t);
242 tftp_error = ntohs(t->th_code);
243 if ((unsigned)tftp_error > TFTP_MAX_ERRCODE) {
244 printf("illegal tftp error %d\n", tftp_error);
248 printf("tftp-error %d\n", tftp_error);
250 errno = tftperrors[tftp_error];
253 /* If we got a NAK return 0, it's usually a directory */
262 * Unexpected OACK. TFTP transfer already in progress.
271 * Remember which port this OACK came from, because we need
272 * to send the ACK or errors back to it.
274 uh = (struct udphdr *)t - 1;
275 d->destport = uh->uh_sport;
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");
291 printf("tftp type %d not handled\n", ntohs(t->th_opcode));
298 /* send request, expect first block (or error) */
300 tftp_makereq(struct tftp_handle *h)
303 u_char header[HEADER_SIZE];
305 u_char space[FNAME_SIZE + 6];
306 } __packed __aligned(4) wbuf;
307 struct tftprecv_extra recv_extra;
313 char *tftp_blksize = NULL;
317 * Allow overriding default TFTP block size by setting
318 * a tftp.blksize environment variable.
320 if ((tftp_blksize = getenv("tftp.blksize")) != NULL) {
321 tftp_set_blksize(h, tftp_blksize);
324 wbuf.t.th_opcode = htons((u_short)RRQ);
325 wtail = wbuf.t.th_stuff;
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;
334 return (ENAMETOOLONG);
336 bcopy(h->path, wtail, l + 1);
338 bcopy("octet", wtail, 6);
340 bcopy("blksize", wtail, 8);
342 blksize_l = sprintf(wtail, "%d", h->tftp_blksize);
343 wtail += blksize_l + 1;
344 bcopy("tsize", wtail, 6);
346 bcopy("0", wtail, 2);
349 h->iodesc->myport = htons(tftpport + (getsecs() & 0x3ff));
350 h->iodesc->destport = htons(IPPORT_TFTP);
351 h->iodesc->xid = 1; /* expected block */
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);
370 if (recv_extra.rtype == OACK)
371 return (tftp_getnextblock(h));
373 /* Server ignored our blksize request, revert to TFTP default. */
374 h->tftp_blksize = SEGSIZE;
376 switch (recv_extra.rtype) {
381 if (res < h->tftp_blksize) {
382 h->islastblock = 1; /* very short file */
383 tftp_sendack(h, h->currblock);
384 h->lastacksent = true;
395 /* ack block, expect next */
397 tftp_getnextblock(struct tftp_handle *h)
400 u_char header[HEADER_SIZE];
402 } __packed __aligned(4) wbuf;
403 struct tftprecv_extra recv_extra;
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);
414 h->iodesc->xid = h->currblock + 1; /* expected block */
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);
421 if (res == -1) { /* 0 is OK! */
431 if (res < h->tftp_blksize)
432 h->islastblock = 1; /* EOF */
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);
444 tftp_open(const char *path, struct open_file *f)
447 struct tftp_handle *tftpfile;
451 const char *extraslash;
453 if (netproto != NET_TFTP)
456 if (f->f_dev->dv_type != DEVT_NET)
462 tftpfile = calloc(1, sizeof(*tftpfile));
466 tftpfile->tftp_blksize = TFTP_REQUESTED_BLKSIZE;
468 tftpfile->iodesc = io = socktodesc(*(int *)(dev->d_opendata));
476 pathsize = (strlen(rootpath) + 1 + strlen(path) + 1) * sizeof(char);
477 tftpfile->path = malloc(pathsize);
478 if (tftpfile->path == NULL) {
482 if (rootpath[strlen(rootpath) - 1] == '/' || path[0] == '/')
486 res = snprintf(tftpfile->path, pathsize, "%s%s%s",
487 rootpath, extraslash, path);
488 if (res < 0 || res > pathsize) {
489 free(tftpfile->path);
494 res = tftp_makereq(tftpfile);
497 free(tftpfile->path);
502 f->f_fsdata = tftpfile;
508 tftp_read(struct open_file *f, void *addr, size_t size,
509 size_t *resid /* out */)
511 struct tftp_handle *tftpfile;
517 tftpfile = f->f_fsdata;
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;
525 if (tftpfile->tftp_cache != NULL) {
526 bcopy(tftpfile->tftp_cache + tftpfile->off,
529 addr = (char *)addr + size;
530 tftpfile->off += size;
536 int needblock, count;
540 needblock = tftpfile->off / tftpfile->tftp_blksize + 1;
542 if (tftpfile->currblock > needblock) { /* seek backwards */
543 tftp_senderr(tftpfile, 0, "No error: read aborted");
544 rc = tftp_makereq(tftpfile);
549 while (tftpfile->currblock < needblock) {
551 rc = tftp_getnextblock(tftpfile);
552 if (rc) { /* no answer */
554 printf("tftp: read error\n");
556 if (tftpfile->tries > TFTP_TRIES) {
560 tftp_makereq(tftpfile);
563 if (tftpfile->islastblock)
567 if (tftpfile->currblock == needblock) {
568 int offinblock, inbuffer;
570 offinblock = tftpfile->off % tftpfile->tftp_blksize;
572 inbuffer = tftpfile->validsize - offinblock;
575 printf("tftp: invalid offset %d\n",
580 count = (size < inbuffer ? size : inbuffer);
581 bcopy(tftpfile->tftp_hdr->th_data + offinblock,
584 addr = (char *)addr + count;
585 tftpfile->off += count;
589 if ((tftpfile->islastblock) && (count == inbuffer))
593 printf("tftp: block %d not found\n", needblock);
607 tftp_close(struct open_file *f)
609 struct tftp_handle *tftpfile;
610 tftpfile = f->f_fsdata;
612 if (tftpfile->lastacksent == false)
613 tftp_senderr(tftpfile, 0, "No error: file closed");
616 free(tftpfile->path);
618 free(tftpfile->tftp_cache);
626 tftp_stat(struct open_file *f, struct stat *sb)
628 struct tftp_handle *tftpfile;
629 tftpfile = f->f_fsdata;
631 sb->st_mode = 0444 | S_IFREG;
635 sb->st_size = tftpfile->tftp_tsize;
640 tftp_seek(struct open_file *f, off_t offset, int where)
642 struct tftp_handle *tftpfile;
643 tftpfile = f->f_fsdata;
647 tftpfile->off = offset;
650 tftpfile->off += offset;
656 return (tftpfile->off);
660 tftp_preload(struct open_file *f)
662 struct tftp_handle *tftpfile;
669 tftpfile = f->f_fsdata;
670 cache = malloc(sizeof(char) * tftpfile->tftp_tsize);
672 printf("Couldn't allocate %ju bytes for preload caching"
673 ", disabling caching\n",
674 (uintmax_t)sizeof(char) * tftpfile->tftp_tsize);
680 printf("Preloading %s ", tftpfile->path);
682 if (tftpfile->currblock == 1)
683 bcopy(tftpfile->tftp_hdr->th_data,
685 tftpfile->validsize);
687 tftpfile->currblock = 0;
689 while (tftpfile->islastblock == 0) {
691 rc = tftp_getnextblock(tftpfile);
694 printf("Got TFTP error %d, disabling caching\n", rc);
697 bcopy(tftpfile->tftp_hdr->th_data,
698 cache + (tftpfile->tftp_blksize * (tftpfile->currblock - 1)),
699 tftpfile->validsize);
703 printf("\nPreloaded %s (%ju bytes) during %jd seconds\n",
704 tftpfile->path, (intmax_t)tftpfile->tftp_tsize,
705 (intmax_t)end - start);
708 tftpfile->tftp_cache = cache;
713 tftp_set_blksize(struct tftp_handle *h, const char *str)
719 if (h == NULL || str == NULL)
723 (unsigned int)strtol(str, &endptr, 0);
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.
730 if (*endptr == '\0' && new_blksize >= 8 &&
731 new_blksize <= TFTP_MAX_BLKSIZE) {
732 h->tftp_blksize = new_blksize;
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 * +-------+---~~---+---+---~~---+---+---~~---+---+---~~---+---+
748 * The opcode field contains a 6, for Option Acknowledgment.
751 * The first option acknowledgment, copied from the original
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.
760 * The final option/value acknowledgment pair.
763 tftp_parse_oack(struct tftp_handle *h, char *buf, size_t len)
766 * We parse the OACK strings into an array
767 * of name-value pairs.
769 char *tftp_options[128] = { 0 };
773 int blksize_is_set = 0;
776 unsigned int orig_blksize;
778 while (option_idx < 128 && i < len) {
779 if (buf[i] == '\0') {
781 tftp_options[option_idx] = val;
789 /* Save the block size we requested for sanity check later. */
790 orig_blksize = h->tftp_blksize;
793 * Parse individual TFTP options.
794 * * "blksize" is specified in RFC2348.
795 * * "tsize" is specified in RFC2349.
797 for (i = 0; i < option_idx; i += 2) {
798 if (strcasecmp(tftp_options[i], "blksize") == 0) {
799 if (i + 1 < option_idx)
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);
806 h->tftp_tsize = tsize;
809 * Do not allow any options we did not expect to be
812 printf("unexpected tftp option '%s'\n",
818 if (!blksize_is_set) {
820 * If TFTP blksize was not set, try defaulting
821 * to the legacy TFTP blksize of SEGSIZE(512)
823 h->tftp_blksize = SEGSIZE;
824 } else if (h->tftp_blksize > orig_blksize) {
826 * Server should not be proposing block sizes that
827 * exceed what we said we can handle.
829 printf("unexpected blksize %u\n", h->tftp_blksize);
834 printf("tftp_blksize: %u\n", h->tftp_blksize);
835 printf("tftp_tsize: %lu\n", h->tftp_tsize);