tftp.c revision 223124
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#include <sys/cdefs.h>
35__FBSDID("$FreeBSD: head/lib/libstand/tftp.c 223124 2011-06-15 22:13:22Z rodrigc $");
36
37/*
38 * Simple TFTP implementation for libsa.
39 * Assumes:
40 *  - socket descriptor (int) at open_file->f_devdata
41 *  - server host IP in global servip
42 * Restrictions:
43 *  - read only
44 *  - lseek only with SEEK_SET or SEEK_CUR
45 *  - no big time differences between transfers (<tftp timeout)
46 */
47
48#include <sys/types.h>
49#include <sys/stat.h>
50#include <netinet/in.h>
51#include <netinet/udp.h>
52#include <netinet/in_systm.h>
53#include <arpa/tftp.h>
54
55#include <string.h>
56
57#include "stand.h"
58#include "net.h"
59#include "netif.h"
60
61#include "tftp.h"
62
63struct tftp_handle;
64
65static int	tftp_open(const char *path, struct open_file *f);
66static int	tftp_close(struct open_file *f);
67static void	tftp_parse_oack(struct tftp_handle *h, char *buf, size_t len);
68static int	tftp_read(struct open_file *f, void *buf, size_t size, size_t *resid);
69static int	tftp_write(struct open_file *f, void *buf, size_t size, size_t *resid);
70static off_t	tftp_seek(struct open_file *f, off_t offset, int where);
71static int	tftp_set_blksize(struct tftp_handle *h, const char *str);
72static int	tftp_stat(struct open_file *f, struct stat *sb);
73static 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);
78
79struct fs_ops tftp_fsops = {
80	"tftp",
81	tftp_open,
82	tftp_close,
83	tftp_read,
84	tftp_write,
85	tftp_seek,
86	tftp_stat,
87	null_readdir
88};
89
90extern struct in_addr servip;
91
92static int      tftpport = 2000;
93static int	is_open = 0;
94
95/*
96 * The legacy TFTP_BLKSIZE value was 512.
97 * TFTP_REQUESTED_BLKSIZE of 1428 is (Ethernet MTU, less the TFTP, UDP and
98 * IP header lengths).
99 */
100#define TFTP_REQUESTED_BLKSIZE 1428
101
102/*
103 * Choose a blksize big enough so we can test with Ethernet
104 * Jumbo frames in the future.
105 */
106#define TFTP_MAX_BLKSIZE 9008
107
108struct tftp_handle {
109	struct iodesc  *iodesc;
110	int             currblock;	/* contents of lastdata */
111	int             islastblock;	/* flag */
112	int             validsize;
113	int             off;
114	char           *path;	/* saved for re-requests */
115	unsigned int	tftp_blksize;
116	unsigned long	tftp_tsize;
117	struct {
118		u_char header[HEADER_SIZE];
119		struct tftphdr t;
120		u_char space[TFTP_MAX_BLKSIZE];
121	} lastdata;
122};
123
124static int tftperrors[8] = {
125	0,			/* ??? */
126	ENOENT,
127	EPERM,
128	ENOSPC,
129	EINVAL,			/* ??? */
130	EINVAL,			/* ??? */
131	EEXIST,
132	EINVAL			/* ??? */
133};
134
135static ssize_t
136recvtftp(struct tftp_handle *h, void *pkt, ssize_t len, time_t tleft,
137    unsigned short *rtype)
138{
139	struct iodesc *d = h->iodesc;
140	struct tftphdr *t;
141
142	errno = 0;
143
144	len = readudp(d, pkt, len, tleft);
145
146	if (len < 4)
147		return (-1);
148
149	t = (struct tftphdr *) pkt;
150	*rtype = ntohs(t->th_opcode);
151	switch (ntohs(t->th_opcode)) {
152	case DATA: {
153		int got;
154
155		if (htons(t->th_block) != d->xid) {
156			/*
157			 * Expected block?
158			 */
159			return (-1);
160		}
161		if (d->xid == 1) {
162			/*
163			 * First data packet from new port.
164			 */
165			struct udphdr *uh;
166			uh = (struct udphdr *) pkt - 1;
167			d->destport = uh->uh_sport;
168		} /* else check uh_sport has not changed??? */
169		got = len - (t->th_data - (char *) t);
170		return got;
171	}
172	case ERROR:
173		if ((unsigned) ntohs(t->th_code) >= 8) {
174			printf("illegal tftp error %d\n", ntohs(t->th_code));
175			errno = EIO;
176		} else {
177#ifdef TFTP_DEBUG
178			printf("tftp-error %d\n", ntohs(t->th_code));
179#endif
180			errno = tftperrors[ntohs(t->th_code)];
181		}
182		return (-1);
183	case OACK: {
184		struct udphdr *uh;
185		int tftp_oack_len = len - sizeof(t->th_opcode);
186		tftp_parse_oack(h, t->th_u.tu_stuff, tftp_oack_len);
187		/*
188		 * Remember which port this OACK came from,
189		 * because we need to send the ACK back to it.
190		 */
191		uh = (struct udphdr *) pkt - 1;
192		d->destport = uh->uh_sport;
193		return (0);
194	}
195	default:
196#ifdef TFTP_DEBUG
197		printf("tftp type %d not handled\n", ntohs(t->th_opcode));
198#endif
199		return (-1);
200	}
201}
202
203/* send request, expect first block (or error) */
204static int
205tftp_makereq(struct tftp_handle *h)
206{
207	struct {
208		u_char header[HEADER_SIZE];
209		struct tftphdr  t;
210		u_char space[FNAME_SIZE + 6];
211	} wbuf;
212	char           *wtail;
213	int             l;
214	ssize_t         res;
215	struct tftphdr *t;
216	char *tftp_blksize = NULL;
217	int blksize_l;
218	unsigned short rtype = 0;
219
220	/*
221	 * Allow overriding default TFTP block size by setting
222	 * a tftp.blksize environment variable.
223	 */
224	if ((tftp_blksize = getenv("tftp.blksize")) != NULL) {
225		tftp_set_blksize(h, tftp_blksize);
226	}
227
228	wbuf.t.th_opcode = htons((u_short) RRQ);
229	wtail = wbuf.t.th_stuff;
230	l = strlen(h->path);
231	if (l > FNAME_SIZE)
232		return (ENAMETOOLONG);
233	bcopy(h->path, wtail, l + 1);
234	wtail += l + 1;
235	bcopy("octet", wtail, 6);
236	wtail += 6;
237	bcopy("blksize", wtail, 8);
238	wtail += 8;
239	blksize_l = sprintf(wtail, "%d", h->tftp_blksize);
240	wtail += blksize_l + 1;
241	bcopy("tsize", wtail, 6);
242	wtail += 6;
243	bcopy("0", wtail, 2);
244	wtail += 2;
245
246	t = &h->lastdata.t;
247
248	/* h->iodesc->myport = htons(--tftpport); */
249	h->iodesc->myport = htons(tftpport + (getsecs() & 0x3ff));
250	h->iodesc->destport = htons(IPPORT_TFTP);
251	h->iodesc->xid = 1;	/* expected block */
252
253	res = sendrecv_tftp(h, &sendudp, &wbuf.t, wtail - (char *) &wbuf.t,
254		       &recvtftp, t, sizeof(*t) + h->tftp_blksize, &rtype);
255
256	if (rtype == OACK) {
257		wbuf.t.th_opcode = htons((u_short)ACK);
258		wtail = (char *) &wbuf.t.th_block;
259		wbuf.t.th_block = htons(0);
260		wtail += 2;
261		rtype = 0;
262		res = sendrecv_tftp(h, &sendudp, &wbuf.t, wtail - (char *) &wbuf.t,
263			       &recvtftp, t, sizeof(*t) + h->tftp_blksize, &rtype);
264	}
265
266	switch (rtype) {
267		case DATA: {
268			h->currblock = 1;
269			h->validsize = res;
270			h->islastblock = 0;
271			if (res < h->tftp_blksize)
272				h->islastblock = 1;	/* very short file */
273			return (0);
274		}
275		case ERROR:
276		default:
277			return (errno);
278	}
279
280}
281
282/* ack block, expect next */
283static int
284tftp_getnextblock(struct tftp_handle *h)
285{
286	struct {
287		u_char header[HEADER_SIZE];
288		struct tftphdr t;
289	} wbuf;
290	char           *wtail;
291	int             res;
292	struct tftphdr *t;
293	unsigned short rtype = 0;
294	wbuf.t.th_opcode = htons((u_short) ACK);
295	wtail = (char *) &wbuf.t.th_block;
296	wbuf.t.th_block = htons((u_short) h->currblock);
297	wtail += 2;
298
299	t = &h->lastdata.t;
300
301	h->iodesc->xid = h->currblock + 1;	/* expected block */
302
303	res = sendrecv_tftp(h, &sendudp, &wbuf.t, wtail - (char *) &wbuf.t,
304		       &recvtftp, t, sizeof(*t) + h->tftp_blksize, &rtype);
305
306	if (res == -1)		/* 0 is OK! */
307		return (errno);
308
309	h->currblock++;
310	h->validsize = res;
311	if (res < h->tftp_blksize)
312		h->islastblock = 1;	/* EOF */
313
314	if (h->islastblock == 1) {
315		/* Send an ACK for the last block */
316		wbuf.t.th_block = htons((u_short) h->currblock);
317		sendudp(h->iodesc, &wbuf.t, wtail - (char *)&wbuf.t);
318	}
319
320	return (0);
321}
322
323static int
324tftp_open(const char *path, struct open_file *f)
325{
326	struct tftp_handle *tftpfile;
327	struct iodesc  *io;
328	int             res;
329
330#ifndef __i386__
331	if (strcmp(f->f_dev->dv_name, "net") != 0)
332		return (EINVAL);
333#endif
334
335	if (is_open)
336		return (EBUSY);
337
338	tftpfile = (struct tftp_handle *) malloc(sizeof(*tftpfile));
339	if (!tftpfile)
340		return (ENOMEM);
341
342	memset(tftpfile, 0, sizeof(*tftpfile));
343	tftpfile->tftp_blksize = TFTP_REQUESTED_BLKSIZE;
344	tftpfile->iodesc = io = socktodesc(*(int *) (f->f_devdata));
345	if (io == NULL)
346		return (EINVAL);
347
348	io->destip = servip;
349	tftpfile->off = 0;
350	tftpfile->path = strdup(path);
351	if (tftpfile->path == NULL) {
352	    free(tftpfile);
353	    return(ENOMEM);
354	}
355
356	res = tftp_makereq(tftpfile);
357
358	if (res) {
359		free(tftpfile->path);
360		free(tftpfile);
361		return (res);
362	}
363	f->f_fsdata = (void *) tftpfile;
364	is_open = 1;
365	return (0);
366}
367
368static int
369tftp_read(struct open_file *f, void *addr, size_t size,
370    size_t *resid /* out */)
371{
372	struct tftp_handle *tftpfile;
373	static int      tc = 0;
374	tftpfile = (struct tftp_handle *) f->f_fsdata;
375
376	while (size > 0) {
377		int needblock, count;
378
379		if (!(tc++ % 16))
380			twiddle();
381
382		needblock = tftpfile->off / tftpfile->tftp_blksize + 1;
383
384		if (tftpfile->currblock > needblock)	/* seek backwards */
385			tftp_makereq(tftpfile);	/* no error check, it worked
386						 * for open */
387
388		while (tftpfile->currblock < needblock) {
389			int res;
390
391			res = tftp_getnextblock(tftpfile);
392			if (res) {	/* no answer */
393#ifdef TFTP_DEBUG
394				printf("tftp: read error\n");
395#endif
396				return (res);
397			}
398			if (tftpfile->islastblock)
399				break;
400		}
401
402		if (tftpfile->currblock == needblock) {
403			int offinblock, inbuffer;
404
405			offinblock = tftpfile->off % tftpfile->tftp_blksize;
406
407			inbuffer = tftpfile->validsize - offinblock;
408			if (inbuffer < 0) {
409#ifdef TFTP_DEBUG
410				printf("tftp: invalid offset %d\n",
411				    tftpfile->off);
412#endif
413				return (EINVAL);
414			}
415			count = (size < inbuffer ? size : inbuffer);
416			bcopy(tftpfile->lastdata.t.th_data + offinblock,
417			    addr, count);
418
419			addr = (char *)addr + count;
420			tftpfile->off += count;
421			size -= count;
422
423			if ((tftpfile->islastblock) && (count == inbuffer))
424				break;	/* EOF */
425		} else {
426#ifdef TFTP_DEBUG
427			printf("tftp: block %d not found\n", needblock);
428#endif
429			return (EINVAL);
430		}
431
432	}
433
434	if (resid)
435		*resid = size;
436	return (0);
437}
438
439static int
440tftp_close(struct open_file *f)
441{
442	struct tftp_handle *tftpfile;
443	tftpfile = (struct tftp_handle *) f->f_fsdata;
444
445	/* let it time out ... */
446
447	if (tftpfile) {
448		free(tftpfile->path);
449		free(tftpfile);
450	}
451	is_open = 0;
452	return (0);
453}
454
455static int
456tftp_write(struct open_file *f __unused, void *start __unused, size_t size __unused,
457    size_t *resid __unused /* out */)
458{
459	return (EROFS);
460}
461
462static int
463tftp_stat(struct open_file *f, struct stat *sb)
464{
465	struct tftp_handle *tftpfile;
466	tftpfile = (struct tftp_handle *) f->f_fsdata;
467
468	sb->st_mode = 0444 | S_IFREG;
469	sb->st_nlink = 1;
470	sb->st_uid = 0;
471	sb->st_gid = 0;
472	sb->st_size = -1;
473	return (0);
474}
475
476static off_t
477tftp_seek(struct open_file *f, off_t offset, int where)
478{
479	struct tftp_handle *tftpfile;
480	tftpfile = (struct tftp_handle *) f->f_fsdata;
481
482	switch (where) {
483	case SEEK_SET:
484		tftpfile->off = offset;
485		break;
486	case SEEK_CUR:
487		tftpfile->off += offset;
488		break;
489	default:
490		errno = EOFFSET;
491		return (-1);
492	}
493	return (tftpfile->off);
494}
495
496static ssize_t
497sendrecv_tftp(struct tftp_handle *h,
498    ssize_t (*sproc)(struct iodesc *, void *, size_t),
499    void *sbuf, size_t ssize,
500    ssize_t (*rproc)(struct tftp_handle *, void *, ssize_t, time_t, unsigned short *),
501    void *rbuf, size_t rsize, unsigned short *rtype)
502{
503	struct iodesc *d = h->iodesc;
504	ssize_t cc;
505	time_t t, t1, tleft;
506
507#ifdef TFTP_DEBUG
508	if (debug)
509		printf("sendrecv: called\n");
510#endif
511
512	tleft = MINTMO;
513	t = t1 = getsecs();
514	for (;;) {
515		if ((getsecs() - t) > MAXTMO) {
516			errno = ETIMEDOUT;
517			return -1;
518		}
519
520		cc = (*sproc)(d, sbuf, ssize);
521		if (cc != -1 && cc < ssize)
522			panic("sendrecv: short write! (%zd < %zu)",
523			    cc, ssize);
524
525		if (cc == -1) {
526			/* Error on transmit; wait before retrying */
527			while ((getsecs() - t1) < tleft);
528			continue;
529		}
530
531recvnext:
532		/* Try to get a packet and process it. */
533		cc = (*rproc)(h, rbuf, rsize, tleft, rtype);
534		/* Return on data, EOF or real error. */
535		if (cc != -1 || errno != 0)
536			return (cc);
537		if ((getsecs() - t1) < tleft) {
538		    goto recvnext;
539		}
540
541		/* Timed out or didn't get the packet we're waiting for */
542		tleft += MINTMO;
543		if (tleft > (2 * MINTMO)) {
544			tleft = (2 * MINTMO);
545		}
546		t1 = getsecs();
547	}
548}
549
550static int
551tftp_set_blksize(struct tftp_handle *h, const char *str)
552{
553        char *endptr;
554	int new_blksize;
555	int ret = 0;
556
557	if (h == NULL || str == NULL)
558		return (ret);
559
560	new_blksize =
561	    (unsigned int)strtol(str, &endptr, 0);
562
563	/*
564	 * Only accept blksize value if it is numeric.
565	 * RFC2348 specifies that acceptable valuesare 8-65464
566	 * 8-65464 .  Let's choose a limit less than MAXRSPACE
567	*/
568	if (*endptr == '\0' && new_blksize >= 8
569	    && new_blksize <= TFTP_MAX_BLKSIZE) {
570		h->tftp_blksize = new_blksize;
571		ret = 1;
572	}
573
574	return (ret);
575}
576
577/*
578 * In RFC2347, the TFTP Option Acknowledgement package (OACK)
579 * is used to acknowledge a client's option negotiation request.
580 * The format of an OACK packet is:
581 *    +-------+---~~---+---+---~~---+---+---~~---+---+---~~---+---+
582 *    |  opc  |  opt1  | 0 | value1 | 0 |  optN  | 0 | valueN | 0 |
583 *    +-------+---~~---+---+---~~---+---+---~~---+---+---~~---+---+
584 *
585 *    opc
586 *       The opcode field contains a 6, for Option Acknowledgment.
587 *
588 *    opt1
589 *       The first option acknowledgment, copied from the original
590 *       request.
591 *
592 *    value1
593 *       The acknowledged value associated with the first option.  If
594 *       and how this value may differ from the original request is
595 *       detailed in the specification for the option.
596 *
597 *    optN, valueN
598 *       The final option/value acknowledgment pair.
599 */
600static void
601tftp_parse_oack(struct tftp_handle *h, char *buf, size_t len)
602{
603	/*
604	 *  We parse the OACK strings into an array
605	 *  of name-value pairs.
606	 *
607	 */
608	char *tftp_options[128] = { 0 };
609	char *val = buf;
610	int i = 0;
611	int option_idx = 0;
612	int blksize_is_set = 0;
613	int tsize = 0;
614
615
616	while ( option_idx < 128 && i < len ) {
617		 if (buf[i] == '\0') {
618		    if (&buf[i] > val) {
619		       tftp_options[option_idx] = val;
620		       val = &buf[i] + 1;
621		       ++option_idx;
622		    }
623		 }
624		 ++i;
625	}
626
627	/*
628	 * Parse individual TFTP options.
629	 *    * "blksize" is specified in RFC2348.
630	 *    * "tsize" is specified in RFC2349.
631	 */
632	for (i = 0; i < option_idx; i += 2) {
633	    if (strcasecmp(tftp_options[i], "blksize") == 0) {
634		if (i + 1 < option_idx) {
635			blksize_is_set =
636			    tftp_set_blksize(h, tftp_options[i + 1]);
637		}
638	    } else if (strcasecmp(tftp_options[i], "tsize") == 0) {
639		if (i + 1 < option_idx) {
640			tsize = strtol(tftp_options[i + 1], (char **)NULL, 10);
641		}
642	    }
643	}
644
645	if (!blksize_is_set) {
646		/*
647		 * If TFTP blksize was not set, try defaulting
648		 * to the legacy TFTP blksize of 512
649		 */
650		h->tftp_blksize = 512;
651	}
652
653#ifdef TFTP_DEBUG
654	printf("tftp_blksize: %u\n", h->tftp_blksize);
655	printf("tftp_tsize: %lu\n", h->tftp_tsize);
656#endif
657}
658