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 open_file->f_devdata
41 * - server host IP in global servip
44 * - lseek only with SEEK_SET or SEEK_CUR
45 * - no big time differences between transfers (<tftp timeout)
48 #include <sys/types.h>
50 #include <netinet/in.h>
51 #include <netinet/udp.h>
52 #include <netinet/in_systm.h>
53 #include <arpa/tftp.h>
64 struct tftprecv_extra;
66 static ssize_t recvtftp(struct iodesc *d, void **pkt, void **payload,
67 time_t tleft, void *recv_extra);
68 static int tftp_open(const char *path, struct open_file *f);
69 static int tftp_close(struct open_file *f);
70 static int tftp_parse_oack(struct tftp_handle *h, char *buf, size_t len);
71 static int tftp_read(struct open_file *f, void *buf, size_t size, size_t *resid);
72 static off_t tftp_seek(struct open_file *f, off_t offset, int where);
73 static int tftp_set_blksize(struct tftp_handle *h, const char *str);
74 static int tftp_stat(struct open_file *f, struct stat *sb);
76 struct fs_ops tftp_fsops = {
87 extern struct in_addr servip;
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
106 struct iodesc *iodesc;
107 int currblock; /* contents of lastdata */
108 int islastblock; /* flag */
111 char *path; /* saved for re-requests */
112 unsigned int tftp_blksize;
113 unsigned long tftp_tsize;
115 struct tftphdr *tftp_hdr;
118 struct tftprecv_extra {
119 struct tftp_handle *tftp_handle;
120 unsigned short rtype; /* Received type */
123 #define TFTP_MAX_ERRCODE EOPTNEG
124 static const int tftperrors[TFTP_MAX_ERRCODE + 1] = {
133 EINVAL, /* Option negotiation failed. */
136 static int tftp_getnextblock(struct tftp_handle *h);
138 /* send error message back. */
140 tftp_senderr(struct tftp_handle *h, u_short errcode, const char *msg)
143 u_char header[HEADER_SIZE];
145 u_char space[63]; /* +1 from t */
146 } __packed __aligned(4) wbuf;
151 if (len > sizeof(wbuf.space))
152 len = sizeof(wbuf.space);
154 wbuf.t.th_opcode = htons((u_short) ERROR);
155 wbuf.t.th_code = htons(errcode);
157 wtail = wbuf.t.th_msg;
158 bcopy(msg, wtail, len);
162 sendudp(h->iodesc, &wbuf.t, wtail - (char *) &wbuf.t);
166 tftp_sendack(struct tftp_handle *h, u_short block)
169 u_char header[HEADER_SIZE];
171 } __packed __aligned(4) wbuf;
174 wbuf.t.th_opcode = htons((u_short) ACK);
175 wtail = (char *) &wbuf.t.th_block;
176 wbuf.t.th_block = htons(block);
179 sendudp(h->iodesc, &wbuf.t, wtail - (char *) &wbuf.t);
183 recvtftp(struct iodesc *d, void **pkt, void **payload, time_t tleft,
186 struct tftprecv_extra *extra;
187 struct tftp_handle *h;
193 extra = (struct tftprecv_extra *)recv_extra;
194 h = extra->tftp_handle;
196 len = readudp(d, &ptr, (void **)&t, tleft);
203 extra->rtype = ntohs(t->th_opcode);
204 switch (ntohs(t->th_opcode)) {
208 if (htons(t->th_block) < (u_short) d->xid) {
210 * Apparently our ACK was missed, re-send.
212 tftp_sendack(h, htons(t->th_block));
216 if (htons(t->th_block) != (u_short) d->xid) {
218 * Packet from the future, drop this.
225 * First data packet from new port.
228 uh = (struct udphdr *) t - 1;
229 d->destport = uh->uh_sport;
231 got = len - (t->th_data - (char *)t);
237 if ((unsigned) ntohs(t->th_code) > TFTP_MAX_ERRCODE) {
238 printf("illegal tftp error %d\n", ntohs(t->th_code));
242 printf("tftp-error %d\n", ntohs(t->th_code));
244 errno = tftperrors[ntohs(t->th_code)];
253 * Unexpected OACK. TFTP transfer already in progress.
262 * Remember which port this OACK came from, because we need
263 * to send the ACK or errors back to it.
265 uh = (struct udphdr *) t - 1;
266 d->destport = uh->uh_sport;
268 /* Parse options ACK-ed by the server. */
269 tftp_oack_len = len - sizeof(t->th_opcode);
270 if (tftp_parse_oack(h, t->th_u.tu_stuff, tftp_oack_len) != 0) {
271 tftp_senderr(h, EOPTNEG, "Malformed OACK");
282 printf("tftp type %d not handled\n", ntohs(t->th_opcode));
289 /* send request, expect first block (or error) */
291 tftp_makereq(struct tftp_handle *h)
294 u_char header[HEADER_SIZE];
296 u_char space[FNAME_SIZE + 6];
297 } __packed __aligned(4) wbuf;
298 struct tftprecv_extra recv_extra;
304 char *tftp_blksize = NULL;
308 * Allow overriding default TFTP block size by setting
309 * a tftp.blksize environment variable.
311 if ((tftp_blksize = getenv("tftp.blksize")) != NULL) {
312 tftp_set_blksize(h, tftp_blksize);
315 wbuf.t.th_opcode = htons((u_short) RRQ);
316 wtail = wbuf.t.th_stuff;
318 #ifdef TFTP_PREPEND_PATH
319 if (l > FNAME_SIZE - (sizeof(TFTP_PREPEND_PATH) - 1))
320 return (ENAMETOOLONG);
321 bcopy(TFTP_PREPEND_PATH, wtail, sizeof(TFTP_PREPEND_PATH) - 1);
322 wtail += sizeof(TFTP_PREPEND_PATH) - 1;
325 return (ENAMETOOLONG);
327 bcopy(h->path, wtail, l + 1);
329 bcopy("octet", wtail, 6);
331 bcopy("blksize", wtail, 8);
333 blksize_l = sprintf(wtail, "%d", h->tftp_blksize);
334 wtail += blksize_l + 1;
335 bcopy("tsize", wtail, 6);
337 bcopy("0", wtail, 2);
340 /* h->iodesc->myport = htons(--tftpport); */
341 h->iodesc->myport = htons(tftpport + (getsecs() & 0x3ff));
342 h->iodesc->destport = htons(IPPORT_TFTP);
343 h->iodesc->xid = 1; /* expected block */
350 recv_extra.tftp_handle = h;
351 res = sendrecv(h->iodesc, &sendudp, &wbuf.t, wtail - (char *) &wbuf.t,
352 (void *)&recvtftp, &pkt, (void **)&t, &recv_extra);
362 if (recv_extra.rtype == OACK)
363 return (tftp_getnextblock(h));
365 /* Server ignored our blksize request, revert to TFTP default. */
366 h->tftp_blksize = SEGSIZE;
368 switch (recv_extra.rtype) {
373 if (res < h->tftp_blksize) {
374 h->islastblock = 1; /* very short file */
375 tftp_sendack(h, h->currblock);
386 /* ack block, expect next */
388 tftp_getnextblock(struct tftp_handle *h)
391 u_char header[HEADER_SIZE];
393 } __packed __aligned(4) wbuf;
394 struct tftprecv_extra recv_extra;
399 wbuf.t.th_opcode = htons((u_short) ACK);
400 wtail = (char *) &wbuf.t.th_block;
401 wbuf.t.th_block = htons((u_short) h->currblock);
404 h->iodesc->xid = h->currblock + 1; /* expected block */
407 recv_extra.tftp_handle = h;
408 res = sendrecv(h->iodesc, &sendudp, &wbuf.t, wtail - (char *) &wbuf.t,
409 (void *)&recvtftp, &pkt, (void **)&t, &recv_extra);
411 if (res == -1) { /* 0 is OK! */
421 if (res < h->tftp_blksize)
422 h->islastblock = 1; /* EOF */
424 if (h->islastblock == 1) {
425 /* Send an ACK for the last block */
426 wbuf.t.th_block = htons((u_short) h->currblock);
427 sendudp(h->iodesc, &wbuf.t, wtail - (char *)&wbuf.t);
434 tftp_open(const char *path, struct open_file *f)
436 struct tftp_handle *tftpfile;
440 const char *extraslash;
442 if (netproto != NET_TFTP)
445 if (f->f_dev->dv_type != DEVT_NET)
451 tftpfile = (struct tftp_handle *) malloc(sizeof(*tftpfile));
455 memset(tftpfile, 0, sizeof(*tftpfile));
456 tftpfile->tftp_blksize = TFTP_REQUESTED_BLKSIZE;
457 tftpfile->iodesc = io = socktodesc(*(int *) (f->f_devdata));
465 pathsize = (strlen(rootpath) + 1 + strlen(path) + 1) * sizeof(char);
466 tftpfile->path = malloc(pathsize);
467 if (tftpfile->path == NULL) {
471 if (rootpath[strlen(rootpath) - 1] == '/' || path[0] == '/')
475 res = snprintf(tftpfile->path, pathsize, "%s%s%s",
476 rootpath, extraslash, path);
477 if (res < 0 || res > pathsize) {
478 free(tftpfile->path);
483 res = tftp_makereq(tftpfile);
486 free(tftpfile->path);
491 f->f_fsdata = (void *) tftpfile;
497 tftp_read(struct open_file *f, void *addr, size_t size,
498 size_t *resid /* out */)
500 struct tftp_handle *tftpfile;
504 tftpfile = (struct tftp_handle *) f->f_fsdata;
507 int needblock, count;
511 needblock = tftpfile->off / tftpfile->tftp_blksize + 1;
513 if (tftpfile->currblock > needblock) { /* seek backwards */
514 tftp_senderr(tftpfile, 0, "No error: read aborted");
515 rc = tftp_makereq(tftpfile);
520 while (tftpfile->currblock < needblock) {
522 rc = tftp_getnextblock(tftpfile);
523 if (rc) { /* no answer */
525 printf("tftp: read error\n");
529 if (tftpfile->islastblock)
533 if (tftpfile->currblock == needblock) {
534 int offinblock, inbuffer;
536 offinblock = tftpfile->off % tftpfile->tftp_blksize;
538 inbuffer = tftpfile->validsize - offinblock;
541 printf("tftp: invalid offset %d\n",
546 count = (size < inbuffer ? size : inbuffer);
547 bcopy(tftpfile->tftp_hdr->th_data + offinblock,
550 addr = (char *)addr + count;
551 tftpfile->off += count;
554 if ((tftpfile->islastblock) && (count == inbuffer))
558 printf("tftp: block %d not found\n", needblock);
571 tftp_close(struct open_file *f)
573 struct tftp_handle *tftpfile;
574 tftpfile = (struct tftp_handle *) f->f_fsdata;
576 /* let it time out ... */
579 free(tftpfile->path);
588 tftp_stat(struct open_file *f, struct stat *sb)
590 struct tftp_handle *tftpfile;
591 tftpfile = (struct tftp_handle *) f->f_fsdata;
593 sb->st_mode = 0444 | S_IFREG;
597 sb->st_size = (off_t) tftpfile->tftp_tsize;
602 tftp_seek(struct open_file *f, off_t offset, int where)
604 struct tftp_handle *tftpfile;
605 tftpfile = (struct tftp_handle *) f->f_fsdata;
609 tftpfile->off = offset;
612 tftpfile->off += offset;
618 return (tftpfile->off);
622 tftp_set_blksize(struct tftp_handle *h, const char *str)
628 if (h == NULL || str == NULL)
632 (unsigned int)strtol(str, &endptr, 0);
635 * Only accept blksize value if it is numeric.
636 * RFC2348 specifies that acceptable values are 8-65464.
637 * Let's choose a limit less than MAXRSPACE.
639 if (*endptr == '\0' && new_blksize >= 8
640 && new_blksize <= TFTP_MAX_BLKSIZE) {
641 h->tftp_blksize = new_blksize;
649 * In RFC2347, the TFTP Option Acknowledgement package (OACK)
650 * is used to acknowledge a client's option negotiation request.
651 * The format of an OACK packet is:
652 * +-------+---~~---+---+---~~---+---+---~~---+---+---~~---+---+
653 * | opc | opt1 | 0 | value1 | 0 | optN | 0 | valueN | 0 |
654 * +-------+---~~---+---+---~~---+---+---~~---+---+---~~---+---+
657 * The opcode field contains a 6, for Option Acknowledgment.
660 * The first option acknowledgment, copied from the original
664 * The acknowledged value associated with the first option. If
665 * and how this value may differ from the original request is
666 * detailed in the specification for the option.
669 * The final option/value acknowledgment pair.
672 tftp_parse_oack(struct tftp_handle *h, char *buf, size_t len)
675 * We parse the OACK strings into an array
676 * of name-value pairs.
678 char *tftp_options[128] = { 0 };
682 int blksize_is_set = 0;
685 unsigned int orig_blksize;
687 while (option_idx < 128 && i < len) {
688 if (buf[i] == '\0') {
690 tftp_options[option_idx] = val;
698 /* Save the block size we requested for sanity check later. */
699 orig_blksize = h->tftp_blksize;
702 * Parse individual TFTP options.
703 * * "blksize" is specified in RFC2348.
704 * * "tsize" is specified in RFC2349.
706 for (i = 0; i < option_idx; i += 2) {
707 if (strcasecmp(tftp_options[i], "blksize") == 0) {
708 if (i + 1 < option_idx)
710 tftp_set_blksize(h, tftp_options[i + 1]);
711 } else if (strcasecmp(tftp_options[i], "tsize") == 0) {
712 if (i + 1 < option_idx)
713 tsize = strtol(tftp_options[i + 1], (char **)NULL, 10);
715 h->tftp_tsize = tsize;
717 /* Do not allow any options we did not expect to be ACKed. */
718 printf("unexpected tftp option '%s'\n", tftp_options[i]);
723 if (!blksize_is_set) {
725 * If TFTP blksize was not set, try defaulting
726 * to the legacy TFTP blksize of SEGSIZE(512)
728 h->tftp_blksize = SEGSIZE;
729 } else if (h->tftp_blksize > orig_blksize) {
731 * Server should not be proposing block sizes that
732 * exceed what we said we can handle.
734 printf("unexpected blksize %u\n", h->tftp_blksize);
739 printf("tftp_blksize: %u\n", h->tftp_blksize);
740 printf("tftp_tsize: %lu\n", h->tftp_tsize);