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>
65 static int tftp_open(const char *path, struct open_file *f);
66 static int tftp_close(struct open_file *f);
67 static int tftp_parse_oack(struct tftp_handle *h, char *buf, size_t len);
68 static int tftp_read(struct open_file *f, void *buf, size_t size, size_t *resid);
69 static int tftp_write(struct open_file *f, void *buf, size_t size, size_t *resid);
70 static off_t tftp_seek(struct open_file *f, off_t offset, int where);
71 static int tftp_set_blksize(struct tftp_handle *h, const char *str);
72 static int tftp_stat(struct open_file *f, struct stat *sb);
73 static ssize_t sendrecv_tftp(struct tftp_handle *h,
74 ssize_t (*sproc)(struct iodesc *, void *, size_t),
75 void *sbuf, size_t ssize,
76 ssize_t (*rproc)(struct tftp_handle *h, void *, ssize_t, time_t, unsigned short *),
77 void *rbuf, size_t rsize, unsigned short *rtype);
79 struct fs_ops tftp_fsops = {
90 extern struct in_addr servip;
92 static int tftpport = 2000;
93 static int is_open = 0;
96 * The legacy TFTP_BLKSIZE value was SEGSIZE(512).
97 * TFTP_REQUESTED_BLKSIZE of 1428 is (Ethernet MTU, less the TFTP, UDP and
100 #define TFTP_REQUESTED_BLKSIZE 1428
103 * Choose a blksize big enough so we can test with Ethernet
104 * Jumbo frames in the future.
106 #define TFTP_MAX_BLKSIZE 9008
109 struct iodesc *iodesc;
110 int currblock; /* contents of lastdata */
111 int islastblock; /* flag */
114 char *path; /* saved for re-requests */
115 unsigned int tftp_blksize;
116 unsigned long tftp_tsize;
118 u_char header[HEADER_SIZE];
120 u_char space[TFTP_MAX_BLKSIZE];
121 } __packed __aligned(4) lastdata;
124 #define TFTP_MAX_ERRCODE EOPTNEG
125 static const int tftperrors[TFTP_MAX_ERRCODE + 1] = {
134 EINVAL, /* Option negotiation failed. */
137 static int tftp_getnextblock(struct tftp_handle *h);
139 /* send error message back. */
141 tftp_senderr(struct tftp_handle *h, u_short errcode, const char *msg)
144 u_char header[HEADER_SIZE];
146 u_char space[63]; /* +1 from t */
147 } __packed __aligned(4) wbuf;
152 if (len > sizeof(wbuf.space))
153 len = sizeof(wbuf.space);
155 wbuf.t.th_opcode = htons((u_short) ERROR);
156 wbuf.t.th_code = htons(errcode);
158 wtail = wbuf.t.th_msg;
159 bcopy(msg, wtail, len);
163 sendudp(h->iodesc, &wbuf.t, wtail - (char *) &wbuf.t);
167 tftp_sendack(struct tftp_handle *h)
170 u_char header[HEADER_SIZE];
172 } __packed __aligned(4) wbuf;
175 wbuf.t.th_opcode = htons((u_short) ACK);
176 wtail = (char *) &wbuf.t.th_block;
177 wbuf.t.th_block = htons((u_short) h->currblock);
180 sendudp(h->iodesc, &wbuf.t, wtail - (char *) &wbuf.t);
184 recvtftp(struct tftp_handle *h, void *pkt, ssize_t len, time_t tleft,
185 unsigned short *rtype)
187 struct iodesc *d = h->iodesc;
192 len = readudp(d, pkt, len, tleft);
197 t = (struct tftphdr *) pkt;
198 *rtype = ntohs(t->th_opcode);
199 switch (ntohs(t->th_opcode)) {
203 if (htons(t->th_block) != d->xid) {
211 * First data packet from new port.
214 uh = (struct udphdr *) pkt - 1;
215 d->destport = uh->uh_sport;
216 } /* else check uh_sport has not changed??? */
217 got = len - (t->th_data - (char *) t);
221 if ((unsigned) ntohs(t->th_code) > TFTP_MAX_ERRCODE) {
222 printf("illegal tftp error %d\n", ntohs(t->th_code));
226 printf("tftp-error %d\n", ntohs(t->th_code));
228 errno = tftperrors[ntohs(t->th_code)];
236 * Unexpected OACK. TFTP transfer already in progress.
244 * Remember which port this OACK came from, because we need
245 * to send the ACK or errors back to it.
247 uh = (struct udphdr *) pkt - 1;
248 d->destport = uh->uh_sport;
250 /* Parse options ACK-ed by the server. */
251 tftp_oack_len = len - sizeof(t->th_opcode);
252 if (tftp_parse_oack(h, t->th_u.tu_stuff, tftp_oack_len) != 0) {
253 tftp_senderr(h, EOPTNEG, "Malformed OACK");
261 printf("tftp type %d not handled\n", ntohs(t->th_opcode));
267 /* send request, expect first block (or error) */
269 tftp_makereq(struct tftp_handle *h)
272 u_char header[HEADER_SIZE];
274 u_char space[FNAME_SIZE + 6];
275 } __packed __aligned(4) wbuf;
280 char *tftp_blksize = NULL;
282 unsigned short rtype = 0;
285 * Allow overriding default TFTP block size by setting
286 * a tftp.blksize environment variable.
288 if ((tftp_blksize = getenv("tftp.blksize")) != NULL) {
289 tftp_set_blksize(h, tftp_blksize);
292 wbuf.t.th_opcode = htons((u_short) RRQ);
293 wtail = wbuf.t.th_stuff;
296 return (ENAMETOOLONG);
297 bcopy(h->path, wtail, l + 1);
299 bcopy("octet", wtail, 6);
301 bcopy("blksize", wtail, 8);
303 blksize_l = sprintf(wtail, "%d", h->tftp_blksize);
304 wtail += blksize_l + 1;
305 bcopy("tsize", wtail, 6);
307 bcopy("0", wtail, 2);
312 /* h->iodesc->myport = htons(--tftpport); */
313 h->iodesc->myport = htons(tftpport + (getsecs() & 0x3ff));
314 h->iodesc->destport = htons(IPPORT_TFTP);
315 h->iodesc->xid = 1; /* expected block */
321 res = sendrecv_tftp(h, &sendudp, &wbuf.t, wtail - (char *) &wbuf.t,
322 &recvtftp, t, sizeof(*t) + h->tftp_blksize, &rtype);
325 return (tftp_getnextblock(h));
327 /* Server ignored our blksize request, revert to TFTP default. */
328 h->tftp_blksize = SEGSIZE;
335 if (res < h->tftp_blksize) {
336 h->islastblock = 1; /* very short file */
348 /* ack block, expect next */
350 tftp_getnextblock(struct tftp_handle *h)
353 u_char header[HEADER_SIZE];
355 } __packed __aligned(4) wbuf;
359 unsigned short rtype = 0;
360 wbuf.t.th_opcode = htons((u_short) ACK);
361 wtail = (char *) &wbuf.t.th_block;
362 wbuf.t.th_block = htons((u_short) h->currblock);
367 h->iodesc->xid = h->currblock + 1; /* expected block */
369 res = sendrecv_tftp(h, &sendudp, &wbuf.t, wtail - (char *) &wbuf.t,
370 &recvtftp, t, sizeof(*t) + h->tftp_blksize, &rtype);
372 if (res == -1) /* 0 is OK! */
377 if (res < h->tftp_blksize)
378 h->islastblock = 1; /* EOF */
380 if (h->islastblock == 1) {
381 /* Send an ACK for the last block */
382 wbuf.t.th_block = htons((u_short) h->currblock);
383 sendudp(h->iodesc, &wbuf.t, wtail - (char *)&wbuf.t);
390 tftp_open(const char *path, struct open_file *f)
392 struct tftp_handle *tftpfile;
397 if (strcmp(f->f_dev->dv_name, "net") != 0)
404 tftpfile = (struct tftp_handle *) malloc(sizeof(*tftpfile));
408 memset(tftpfile, 0, sizeof(*tftpfile));
409 tftpfile->tftp_blksize = TFTP_REQUESTED_BLKSIZE;
410 tftpfile->iodesc = io = socktodesc(*(int *) (f->f_devdata));
416 tftpfile->path = strdup(path);
417 if (tftpfile->path == NULL) {
422 res = tftp_makereq(tftpfile);
425 free(tftpfile->path);
429 f->f_fsdata = (void *) tftpfile;
435 tftp_read(struct open_file *f, void *addr, size_t size,
436 size_t *resid /* out */)
438 struct tftp_handle *tftpfile;
440 tftpfile = (struct tftp_handle *) f->f_fsdata;
443 int needblock, count;
448 needblock = tftpfile->off / tftpfile->tftp_blksize + 1;
450 if (tftpfile->currblock > needblock) { /* seek backwards */
451 tftp_senderr(tftpfile, 0, "No error: read aborted");
452 tftp_makereq(tftpfile); /* no error check, it worked
456 while (tftpfile->currblock < needblock) {
459 res = tftp_getnextblock(tftpfile);
460 if (res) { /* no answer */
462 printf("tftp: read error\n");
466 if (tftpfile->islastblock)
470 if (tftpfile->currblock == needblock) {
471 int offinblock, inbuffer;
473 offinblock = tftpfile->off % tftpfile->tftp_blksize;
475 inbuffer = tftpfile->validsize - offinblock;
478 printf("tftp: invalid offset %d\n",
483 count = (size < inbuffer ? size : inbuffer);
484 bcopy(tftpfile->lastdata.t.th_data + offinblock,
487 addr = (char *)addr + count;
488 tftpfile->off += count;
491 if ((tftpfile->islastblock) && (count == inbuffer))
495 printf("tftp: block %d not found\n", needblock);
508 tftp_close(struct open_file *f)
510 struct tftp_handle *tftpfile;
511 tftpfile = (struct tftp_handle *) f->f_fsdata;
513 /* let it time out ... */
516 free(tftpfile->path);
524 tftp_write(struct open_file *f __unused, void *start __unused, size_t size __unused,
525 size_t *resid __unused /* out */)
531 tftp_stat(struct open_file *f, struct stat *sb)
533 struct tftp_handle *tftpfile;
534 tftpfile = (struct tftp_handle *) f->f_fsdata;
536 sb->st_mode = 0444 | S_IFREG;
545 tftp_seek(struct open_file *f, off_t offset, int where)
547 struct tftp_handle *tftpfile;
548 tftpfile = (struct tftp_handle *) f->f_fsdata;
552 tftpfile->off = offset;
555 tftpfile->off += offset;
561 return (tftpfile->off);
565 sendrecv_tftp(struct tftp_handle *h,
566 ssize_t (*sproc)(struct iodesc *, void *, size_t),
567 void *sbuf, size_t ssize,
568 ssize_t (*rproc)(struct tftp_handle *, void *, ssize_t, time_t, unsigned short *),
569 void *rbuf, size_t rsize, unsigned short *rtype)
571 struct iodesc *d = h->iodesc;
577 printf("sendrecv: called\n");
583 if ((getsecs() - t) > MAXTMO) {
588 cc = (*sproc)(d, sbuf, ssize);
589 if (cc != -1 && cc < ssize)
590 panic("sendrecv: short write! (%zd < %zu)",
594 /* Error on transmit; wait before retrying */
595 while ((getsecs() - t1) < tleft);
600 /* Try to get a packet and process it. */
601 cc = (*rproc)(h, rbuf, rsize, tleft, rtype);
602 /* Return on data, EOF or real error. */
603 if (cc != -1 || errno != 0)
605 if ((getsecs() - t1) < tleft) {
609 /* Timed out or didn't get the packet we're waiting for */
611 if (tleft > (2 * MINTMO)) {
612 tleft = (2 * MINTMO);
619 tftp_set_blksize(struct tftp_handle *h, const char *str)
625 if (h == NULL || str == NULL)
629 (unsigned int)strtol(str, &endptr, 0);
632 * Only accept blksize value if it is numeric.
633 * RFC2348 specifies that acceptable values are 8-65464.
634 * Let's choose a limit less than MAXRSPACE.
636 if (*endptr == '\0' && new_blksize >= 8
637 && new_blksize <= TFTP_MAX_BLKSIZE) {
638 h->tftp_blksize = new_blksize;
646 * In RFC2347, the TFTP Option Acknowledgement package (OACK)
647 * is used to acknowledge a client's option negotiation request.
648 * The format of an OACK packet is:
649 * +-------+---~~---+---+---~~---+---+---~~---+---+---~~---+---+
650 * | opc | opt1 | 0 | value1 | 0 | optN | 0 | valueN | 0 |
651 * +-------+---~~---+---+---~~---+---+---~~---+---+---~~---+---+
654 * The opcode field contains a 6, for Option Acknowledgment.
657 * The first option acknowledgment, copied from the original
661 * The acknowledged value associated with the first option. If
662 * and how this value may differ from the original request is
663 * detailed in the specification for the option.
666 * The final option/value acknowledgment pair.
669 tftp_parse_oack(struct tftp_handle *h, char *buf, size_t len)
672 * We parse the OACK strings into an array
673 * of name-value pairs.
675 char *tftp_options[128] = { 0 };
679 int blksize_is_set = 0;
682 unsigned int orig_blksize;
684 while (option_idx < 128 && i < len) {
685 if (buf[i] == '\0') {
687 tftp_options[option_idx] = val;
695 /* Save the block size we requested for sanity check later. */
696 orig_blksize = h->tftp_blksize;
699 * Parse individual TFTP options.
700 * * "blksize" is specified in RFC2348.
701 * * "tsize" is specified in RFC2349.
703 for (i = 0; i < option_idx; i += 2) {
704 if (strcasecmp(tftp_options[i], "blksize") == 0) {
705 if (i + 1 < option_idx)
707 tftp_set_blksize(h, tftp_options[i + 1]);
708 } else if (strcasecmp(tftp_options[i], "tsize") == 0) {
709 if (i + 1 < option_idx)
710 tsize = strtol(tftp_options[i + 1], (char **)NULL, 10);
712 /* Do not allow any options we did not expect to be ACKed. */
713 printf("unexpected tftp option '%s'\n", tftp_options[i]);
718 if (!blksize_is_set) {
720 * If TFTP blksize was not set, try defaulting
721 * to the legacy TFTP blksize of SEGSIZE(512)
723 h->tftp_blksize = SEGSIZE;
724 } else if (h->tftp_blksize > orig_blksize) {
726 * Server should not be proposing block sizes that
727 * exceed what we said we can handle.
729 printf("unexpected blksize %u\n", h->tftp_blksize);
734 printf("tftp_blksize: %u\n", h->tftp_blksize);
735 printf("tftp_tsize: %lu\n", h->tftp_tsize);