1 /*
2  * Copyright (C) 2006 Michael Brown <mbrown@fensystems.co.uk>.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License as
6  * published by the Free Software Foundation; either version 2 of the
7  * License, or any later version.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17  * 02110-1301, USA.
18  *
19  * You can also choose to distribute this program under the terms of
20  * the Unmodified Binary Distribution Licence (as given in the file
21  * COPYING.UBDL), provided that you have satisfied its requirements.
22  */
23 
24 FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL );
25 
26 #include <stdint.h>
27 #include <stdlib.h>
28 #include <stdio.h>
29 #include <string.h>
30 #include <strings.h>
31 #include <byteswap.h>
32 #include <errno.h>
33 #include <assert.h>
34 #include <ipxe/refcnt.h>
35 #include <ipxe/iobuf.h>
36 #include <ipxe/xfer.h>
37 #include <ipxe/open.h>
38 #include <ipxe/uri.h>
39 #include <ipxe/tcpip.h>
40 #include <ipxe/retry.h>
41 #include <ipxe/features.h>
42 #include <ipxe/bitmap.h>
43 #include <ipxe/settings.h>
44 #include <ipxe/dhcp.h>
45 #include <ipxe/uri.h>
46 #include <ipxe/tftp.h>
47 
48 /** @file
49  *
50  * TFTP protocol
51  *
52  */
53 
54 FEATURE ( FEATURE_PROTOCOL, "TFTP", DHCP_EB_FEATURE_TFTP, 1 );
55 
56 /* TFTP-specific error codes */
57 #define EINVAL_BLKSIZE 	__einfo_error ( EINFO_EINVAL_BLKSIZE )
58 #define EINFO_EINVAL_BLKSIZE __einfo_uniqify \
59 	( EINFO_EINVAL, 0x01, "Invalid blksize" )
60 #define EINVAL_TSIZE __einfo_error ( EINFO_EINVAL_TSIZE )
61 #define EINFO_EINVAL_TSIZE __einfo_uniqify \
62 	( EINFO_EINVAL, 0x02, "Invalid tsize" )
63 #define EINVAL_MC_NO_PORT __einfo_error ( EINFO_EINVAL_MC_NO_PORT )
64 #define EINFO_EINVAL_MC_NO_PORT __einfo_uniqify \
65 	( EINFO_EINVAL, 0x03, "Missing multicast port" )
66 #define EINVAL_MC_NO_MC __einfo_error ( EINFO_EINVAL_MC_NO_MC )
67 #define EINFO_EINVAL_MC_NO_MC __einfo_uniqify \
68 	( EINFO_EINVAL, 0x04, "Missing multicast mc" )
69 #define EINVAL_MC_INVALID_MC __einfo_error ( EINFO_EINVAL_MC_INVALID_MC )
70 #define EINFO_EINVAL_MC_INVALID_MC __einfo_uniqify \
71 	( EINFO_EINVAL, 0x05, "Missing multicast IP" )
72 #define EINVAL_MC_INVALID_IP __einfo_error ( EINFO_EINVAL_MC_INVALID_IP )
73 #define EINFO_EINVAL_MC_INVALID_IP __einfo_uniqify \
74 	( EINFO_EINVAL, 0x06, "Invalid multicast IP" )
75 #define EINVAL_MC_INVALID_PORT __einfo_error ( EINFO_EINVAL_MC_INVALID_PORT )
76 #define EINFO_EINVAL_MC_INVALID_PORT __einfo_uniqify \
77 	( EINFO_EINVAL, 0x07, "Invalid multicast port" )
78 
79 /**
80  * A TFTP request
81  *
82  * This data structure holds the state for an ongoing TFTP transfer.
83  */
84 struct tftp_request {
85 	/** Reference count */
86 	struct refcnt refcnt;
87 	/** Data transfer interface */
88 	struct interface xfer;
89 
90 	/** URI being fetched */
91 	struct uri *uri;
92 	/** Transport layer interface */
93 	struct interface socket;
94 	/** Multicast transport layer interface */
95 	struct interface mc_socket;
96 
97 	/** Data block size
98 	 *
99 	 * This is the "blksize" option negotiated with the TFTP
100 	 * server.  (If the TFTP server does not support TFTP options,
101 	 * this will default to 512).
102 	 */
103 	unsigned int blksize;
104 	/** File size
105 	 *
106 	 * This is the value returned in the "tsize" option from the
107 	 * TFTP server.  If the TFTP server does not support the
108 	 * "tsize" option, this value will be zero.
109 	 */
110 	unsigned long tsize;
111 
112 	/** Server port
113 	 *
114 	 * This is the port to which RRQ packets are sent.
115 	 */
116 	unsigned int port;
117 	/** Peer address
118 	 *
119 	 * The peer address is determined by the first response
120 	 * received to the TFTP RRQ.
121 	 */
122 	struct sockaddr_tcpip peer;
123 	/** Request flags */
124 	unsigned int flags;
125 	/** MTFTP timeout count */
126 	unsigned int mtftp_timeouts;
127 
128 	/** Block bitmap */
129 	struct bitmap bitmap;
130 	/** Maximum known length
131 	 *
132 	 * We don't always know the file length in advance.  In
133 	 * particular, if the TFTP server doesn't support the tsize
134 	 * option, or we are using MTFTP, then we don't know the file
135 	 * length until we see the end-of-file block (which, in the
136 	 * case of MTFTP, may not be the last block we see).
137 	 *
138 	 * This value is updated whenever we obtain information about
139 	 * the file length.
140 	 */
141 	size_t filesize;
142 	/** Retransmission timer */
143 	struct retry_timer timer;
144 };
145 
146 /** TFTP request flags */
147 enum {
148 	/** Send ACK packets */
149 	TFTP_FL_SEND_ACK = 0x0001,
150 	/** Request blksize and tsize options */
151 	TFTP_FL_RRQ_SIZES = 0x0002,
152 	/** Request multicast option */
153 	TFTP_FL_RRQ_MULTICAST = 0x0004,
154 	/** Perform MTFTP recovery on timeout */
155 	TFTP_FL_MTFTP_RECOVERY = 0x0008,
156 };
157 
158 /** Maximum number of MTFTP open requests before falling back to TFTP */
159 #define MTFTP_MAX_TIMEOUTS 3
160 
161 /**
162  * Free TFTP request
163  *
164  * @v refcnt		Reference counter
165  */
tftp_free(struct refcnt * refcnt)166 static void tftp_free ( struct refcnt *refcnt ) {
167 	struct tftp_request *tftp =
168 		container_of ( refcnt, struct tftp_request, refcnt );
169 
170 	uri_put ( tftp->uri );
171 	bitmap_free ( &tftp->bitmap );
172 	free ( tftp );
173 }
174 
175 /**
176  * Mark TFTP request as complete
177  *
178  * @v tftp		TFTP connection
179  * @v rc		Return status code
180  */
tftp_done(struct tftp_request * tftp,int rc)181 static void tftp_done ( struct tftp_request *tftp, int rc ) {
182 
183 	DBGC ( tftp, "TFTP %p finished with status %d (%s)\n",
184 	       tftp, rc, strerror ( rc ) );
185 
186 	/* Stop the retry timer */
187 	stop_timer ( &tftp->timer );
188 
189 	/* Close all data transfer interfaces */
190 	intf_shutdown ( &tftp->socket, rc );
191 	intf_shutdown ( &tftp->mc_socket, rc );
192 	intf_shutdown ( &tftp->xfer, rc );
193 }
194 
195 /**
196  * Reopen TFTP socket
197  *
198  * @v tftp		TFTP connection
199  * @ret rc		Return status code
200  */
tftp_reopen(struct tftp_request * tftp)201 static int tftp_reopen ( struct tftp_request *tftp ) {
202 	struct sockaddr_tcpip server;
203 	int rc;
204 
205 	/* Close socket */
206 	intf_restart ( &tftp->socket, 0 );
207 
208 	/* Disable ACK sending. */
209 	tftp->flags &= ~TFTP_FL_SEND_ACK;
210 
211 	/* Reset peer address */
212 	memset ( &tftp->peer, 0, sizeof ( tftp->peer ) );
213 
214 	/* Open socket */
215 	memset ( &server, 0, sizeof ( server ) );
216 	server.st_port = htons ( tftp->port );
217 	if ( ( rc = xfer_open_named_socket ( &tftp->socket, SOCK_DGRAM,
218 					     ( struct sockaddr * ) &server,
219 					     tftp->uri->host, NULL ) ) != 0 ) {
220 		DBGC ( tftp, "TFTP %p could not open socket: %s\n",
221 		       tftp, strerror ( rc ) );
222 		return rc;
223 	}
224 
225 	return 0;
226 }
227 
228 /**
229  * Reopen TFTP multicast socket
230  *
231  * @v tftp		TFTP connection
232  * @v local		Local socket address
233  * @ret rc		Return status code
234  */
tftp_reopen_mc(struct tftp_request * tftp,struct sockaddr * local)235 static int tftp_reopen_mc ( struct tftp_request *tftp,
236 			    struct sockaddr *local ) {
237 	int rc;
238 
239 	/* Close multicast socket */
240 	intf_restart ( &tftp->mc_socket, 0 );
241 
242 	/* Open multicast socket.  We never send via this socket, so
243 	 * use the local address as the peer address (since the peer
244 	 * address cannot be NULL).
245 	 */
246 	if ( ( rc = xfer_open_socket ( &tftp->mc_socket, SOCK_DGRAM,
247 				       local, local ) ) != 0 ) {
248 		DBGC ( tftp, "TFTP %p could not open multicast "
249 		       "socket: %s\n", tftp, strerror ( rc ) );
250 		return rc;
251 	}
252 
253 	return 0;
254 }
255 
256 /**
257  * Presize TFTP receive buffers and block bitmap
258  *
259  * @v tftp		TFTP connection
260  * @v filesize		Known minimum file size
261  * @ret rc		Return status code
262  */
tftp_presize(struct tftp_request * tftp,size_t filesize)263 static int tftp_presize ( struct tftp_request *tftp, size_t filesize ) {
264 	unsigned int num_blocks;
265 	int rc;
266 
267 	/* Do nothing if we are already large enough */
268 	if ( filesize <= tftp->filesize )
269 		return 0;
270 
271 	/* Record filesize */
272 	tftp->filesize = filesize;
273 
274 	/* Notify recipient of file size */
275 	xfer_seek ( &tftp->xfer, filesize );
276 	xfer_seek ( &tftp->xfer, 0 );
277 
278 	/* Calculate expected number of blocks.  Note that files whose
279 	 * length is an exact multiple of the blocksize will have a
280 	 * trailing zero-length block, which must be included.
281 	 */
282 	if ( tftp->blksize == 0 )
283 		return -EINVAL;
284 	num_blocks = ( ( filesize / tftp->blksize ) + 1 );
285 	if ( ( rc = bitmap_resize ( &tftp->bitmap, num_blocks ) ) != 0 ) {
286 		DBGC ( tftp, "TFTP %p could not resize bitmap to %d blocks: "
287 		       "%s\n", tftp, num_blocks, strerror ( rc ) );
288 		return rc;
289 	}
290 
291 	return 0;
292 }
293 
294 /**
295  * MTFTP multicast receive address
296  *
297  * This is treated as a global configuration parameter.
298  */
299 static struct sockaddr_in tftp_mtftp_socket = {
300 	.sin_family = AF_INET,
301 	.sin_addr.s_addr = htonl ( 0xefff0101 ),
302 	.sin_port = htons ( 3001 ),
303 };
304 
305 /**
306  * Set MTFTP multicast address
307  *
308  * @v address		Multicast IPv4 address
309  */
tftp_set_mtftp_address(struct in_addr address)310 void tftp_set_mtftp_address ( struct in_addr address ) {
311 	tftp_mtftp_socket.sin_addr = address;
312 }
313 
314 /**
315  * Set MTFTP multicast port
316  *
317  * @v port		Multicast port
318  */
tftp_set_mtftp_port(unsigned int port)319 void tftp_set_mtftp_port ( unsigned int port ) {
320 	tftp_mtftp_socket.sin_port = htons ( port );
321 }
322 
323 /**
324  * Transmit RRQ
325  *
326  * @v tftp		TFTP connection
327  * @ret rc		Return status code
328  */
tftp_send_rrq(struct tftp_request * tftp)329 static int tftp_send_rrq ( struct tftp_request *tftp ) {
330 	const char *path = ( tftp->uri->path + 1 /* skip '/' */ );
331 	struct tftp_rrq *rrq;
332 	size_t len;
333 	struct io_buffer *iobuf;
334 	size_t blksize;
335 
336 	DBGC ( tftp, "TFTP %p requesting \"%s\"\n", tftp, path );
337 
338 	/* Allocate buffer */
339 	len = ( sizeof ( *rrq ) + strlen ( path ) + 1 /* NUL */
340 		+ 5 + 1 /* "octet" + NUL */
341 		+ 7 + 1 + 5 + 1 /* "blksize" + NUL + ddddd + NUL */
342 		+ 5 + 1 + 1 + 1 /* "tsize" + NUL + "0" + NUL */
343 		+ 9 + 1 + 1 /* "multicast" + NUL + NUL */ );
344 	iobuf = xfer_alloc_iob ( &tftp->socket, len );
345 	if ( ! iobuf )
346 		return -ENOMEM;
347 
348 	/* Determine block size */
349 	blksize = xfer_window ( &tftp->xfer );
350 	if ( blksize > TFTP_MAX_BLKSIZE )
351 		blksize = TFTP_MAX_BLKSIZE;
352 
353 	/* Build request */
354 	rrq = iob_put ( iobuf, sizeof ( *rrq ) );
355 	rrq->opcode = htons ( TFTP_RRQ );
356 	iob_put ( iobuf, snprintf ( iobuf->tail, iob_tailroom ( iobuf ),
357 				    "%s%coctet", path, 0 ) + 1 );
358 	if ( tftp->flags & TFTP_FL_RRQ_SIZES ) {
359 		iob_put ( iobuf, snprintf ( iobuf->tail,
360 					    iob_tailroom ( iobuf ),
361 					    "blksize%c%zd%ctsize%c0",
362 					    0, blksize, 0, 0 ) + 1 );
363 	}
364 	if ( tftp->flags & TFTP_FL_RRQ_MULTICAST ) {
365 		iob_put ( iobuf, snprintf ( iobuf->tail,
366 					    iob_tailroom ( iobuf ),
367 					    "multicast%c", 0 ) + 1 );
368 	}
369 
370 	/* RRQ always goes to the address specified in the initial
371 	 * xfer_open() call
372 	 */
373 	return xfer_deliver_iob ( &tftp->socket, iobuf );
374 }
375 
376 /**
377  * Transmit ACK
378  *
379  * @v tftp		TFTP connection
380  * @ret rc		Return status code
381  */
tftp_send_ack(struct tftp_request * tftp)382 static int tftp_send_ack ( struct tftp_request *tftp ) {
383 	struct tftp_ack *ack;
384 	struct io_buffer *iobuf;
385 	struct xfer_metadata meta = {
386 		.dest = ( struct sockaddr * ) &tftp->peer,
387 	};
388 	unsigned int block;
389 
390 	/* Determine next required block number */
391 	block = bitmap_first_gap ( &tftp->bitmap );
392 	DBGC2 ( tftp, "TFTP %p sending ACK for block %d\n", tftp, block );
393 
394 	/* Allocate buffer */
395 	iobuf = xfer_alloc_iob ( &tftp->socket, sizeof ( *ack ) );
396 	if ( ! iobuf )
397 		return -ENOMEM;
398 
399 	/* Build ACK */
400 	ack = iob_put ( iobuf, sizeof ( *ack ) );
401 	ack->opcode = htons ( TFTP_ACK );
402 	ack->block = htons ( block );
403 
404 	/* ACK always goes to the peer recorded from the RRQ response */
405 	return xfer_deliver ( &tftp->socket, iobuf, &meta );
406 }
407 
408 /**
409  * Transmit ERROR (Abort)
410  *
411  * @v tftp		TFTP connection
412  * @v errcode		TFTP error code
413  * @v errmsg		Error message string
414  * @ret rc		Return status code
415  */
tftp_send_error(struct tftp_request * tftp,int errcode,const char * errmsg)416 static int tftp_send_error ( struct tftp_request *tftp, int errcode,
417 			     const char *errmsg ) {
418 	struct tftp_error *err;
419 	struct io_buffer *iobuf;
420 	struct xfer_metadata meta = {
421 		.dest = ( struct sockaddr * ) &tftp->peer,
422 	};
423 	size_t msglen;
424 
425 	DBGC2 ( tftp, "TFTP %p sending ERROR %d: %s\n", tftp, errcode,
426 		errmsg );
427 
428 	/* Allocate buffer */
429 	msglen = sizeof ( *err ) + strlen ( errmsg ) + 1 /* NUL */;
430 	iobuf = xfer_alloc_iob ( &tftp->socket, msglen );
431 	if ( ! iobuf )
432 		return -ENOMEM;
433 
434 	/* Build ERROR */
435 	err = iob_put ( iobuf, msglen );
436 	err->opcode = htons ( TFTP_ERROR );
437 	err->errcode = htons ( errcode );
438 	strcpy ( err->errmsg, errmsg );
439 
440 	/* ERR always goes to the peer recorded from the RRQ response */
441 	return xfer_deliver ( &tftp->socket, iobuf, &meta );
442 }
443 
444 /**
445  * Transmit next relevant packet
446  *
447  * @v tftp		TFTP connection
448  * @ret rc		Return status code
449  */
tftp_send_packet(struct tftp_request * tftp)450 static int tftp_send_packet ( struct tftp_request *tftp ) {
451 
452 	/* Update retransmission timer.  While name resolution takes place the
453 	 * window is zero.  Avoid unnecessary delay after name resolution
454 	 * completes by retrying immediately.
455 	 */
456 	stop_timer ( &tftp->timer );
457 	if ( xfer_window ( &tftp->socket ) ) {
458 		start_timer ( &tftp->timer );
459 	} else {
460 		start_timer_nodelay ( &tftp->timer );
461 	}
462 
463 	/* Send RRQ or ACK as appropriate */
464 	if ( ! tftp->peer.st_family ) {
465 		return tftp_send_rrq ( tftp );
466 	} else {
467 		if ( tftp->flags & TFTP_FL_SEND_ACK ) {
468 			return tftp_send_ack ( tftp );
469 		} else {
470 			return 0;
471 		}
472 	}
473 }
474 
475 /**
476  * Handle TFTP retransmission timer expiry
477  *
478  * @v timer		Retry timer
479  * @v fail		Failure indicator
480  */
tftp_timer_expired(struct retry_timer * timer,int fail)481 static void tftp_timer_expired ( struct retry_timer *timer, int fail ) {
482 	struct tftp_request *tftp =
483 		container_of ( timer, struct tftp_request, timer );
484 	int rc;
485 
486 	/* If we are doing MTFTP, attempt the various recovery strategies */
487 	if ( tftp->flags & TFTP_FL_MTFTP_RECOVERY ) {
488 		if ( tftp->peer.st_family ) {
489 			/* If we have received any response from the server,
490 			 * try resending the RRQ to restart the download.
491 			 */
492 			DBGC ( tftp, "TFTP %p attempting reopen\n", tftp );
493 			if ( ( rc = tftp_reopen ( tftp ) ) != 0 )
494 				goto err;
495 		} else {
496 			/* Fall back to plain TFTP after several attempts */
497 			tftp->mtftp_timeouts++;
498 			DBGC ( tftp, "TFTP %p timeout %d waiting for MTFTP "
499 			       "open\n", tftp, tftp->mtftp_timeouts );
500 
501 			if ( tftp->mtftp_timeouts > MTFTP_MAX_TIMEOUTS ) {
502 				DBGC ( tftp, "TFTP %p falling back to plain "
503 				       "TFTP\n", tftp );
504 				tftp->flags = TFTP_FL_RRQ_SIZES;
505 
506 				/* Close multicast socket */
507 				intf_restart ( &tftp->mc_socket, 0 );
508 
509 				/* Reset retry timer */
510 				start_timer_nodelay ( &tftp->timer );
511 
512 				/* The blocksize may change: discard
513 				 * the block bitmap
514 				 */
515 				bitmap_free ( &tftp->bitmap );
516 				memset ( &tftp->bitmap, 0,
517 					 sizeof ( tftp->bitmap ) );
518 
519 				/* Reopen on standard TFTP port */
520 				tftp->port = TFTP_PORT;
521 				if ( ( rc = tftp_reopen ( tftp ) ) != 0 )
522 					goto err;
523 			}
524 		}
525 	} else {
526 		/* Not doing MTFTP (or have fallen back to plain
527 		 * TFTP); fail as per normal.
528 		 */
529 		if ( fail ) {
530 			rc = -ETIMEDOUT;
531 			goto err;
532 		}
533 	}
534 	tftp_send_packet ( tftp );
535 	return;
536 
537  err:
538 	tftp_done ( tftp, rc );
539 }
540 
541 /**
542  * Process TFTP "blksize" option
543  *
544  * @v tftp		TFTP connection
545  * @v value		Option value
546  * @ret rc		Return status code
547  */
tftp_process_blksize(struct tftp_request * tftp,const char * value)548 static int tftp_process_blksize ( struct tftp_request *tftp,
549 				  const char *value ) {
550 	char *end;
551 
552 	tftp->blksize = strtoul ( value, &end, 10 );
553 	if ( *end ) {
554 		DBGC ( tftp, "TFTP %p got invalid blksize \"%s\"\n",
555 		       tftp, value );
556 		return -EINVAL_BLKSIZE;
557 	}
558 	DBGC ( tftp, "TFTP %p blksize=%d\n", tftp, tftp->blksize );
559 
560 	return 0;
561 }
562 
563 /**
564  * Process TFTP "tsize" option
565  *
566  * @v tftp		TFTP connection
567  * @v value		Option value
568  * @ret rc		Return status code
569  */
tftp_process_tsize(struct tftp_request * tftp,const char * value)570 static int tftp_process_tsize ( struct tftp_request *tftp,
571 				const char *value ) {
572 	char *end;
573 
574 	tftp->tsize = strtoul ( value, &end, 10 );
575 	if ( *end ) {
576 		DBGC ( tftp, "TFTP %p got invalid tsize \"%s\"\n",
577 		       tftp, value );
578 		return -EINVAL_TSIZE;
579 	}
580 	DBGC ( tftp, "TFTP %p tsize=%ld\n", tftp, tftp->tsize );
581 
582 	return 0;
583 }
584 
585 /**
586  * Process TFTP "multicast" option
587  *
588  * @v tftp		TFTP connection
589  * @v value		Option value
590  * @ret rc		Return status code
591  */
tftp_process_multicast(struct tftp_request * tftp,const char * value)592 static int tftp_process_multicast ( struct tftp_request *tftp,
593 				    const char *value ) {
594 	union {
595 		struct sockaddr sa;
596 		struct sockaddr_in sin;
597 	} socket;
598 	char buf[ strlen ( value ) + 1 ];
599 	char *addr;
600 	char *port;
601 	char *port_end;
602 	char *mc;
603 	char *mc_end;
604 	int rc;
605 
606 	/* Split value into "addr,port,mc" fields */
607 	memcpy ( buf, value, sizeof ( buf ) );
608 	addr = buf;
609 	port = strchr ( addr, ',' );
610 	if ( ! port ) {
611 		DBGC ( tftp, "TFTP %p multicast missing port,mc\n", tftp );
612 		return -EINVAL_MC_NO_PORT;
613 	}
614 	*(port++) = '\0';
615 	mc = strchr ( port, ',' );
616 	if ( ! mc ) {
617 		DBGC ( tftp, "TFTP %p multicast missing mc\n", tftp );
618 		return -EINVAL_MC_NO_MC;
619 	}
620 	*(mc++) = '\0';
621 
622 	/* Parse parameters */
623 	if ( strtoul ( mc, &mc_end, 0 ) == 0 )
624 		tftp->flags &= ~TFTP_FL_SEND_ACK;
625 	if ( *mc_end ) {
626 		DBGC ( tftp, "TFTP %p multicast invalid mc %s\n", tftp, mc );
627 		return -EINVAL_MC_INVALID_MC;
628 	}
629 	DBGC ( tftp, "TFTP %p is%s the master client\n",
630 	       tftp, ( ( tftp->flags & TFTP_FL_SEND_ACK ) ? "" : " not" ) );
631 	if ( *addr && *port ) {
632 		socket.sin.sin_family = AF_INET;
633 		if ( inet_aton ( addr, &socket.sin.sin_addr ) == 0 ) {
634 			DBGC ( tftp, "TFTP %p multicast invalid IP address "
635 			       "%s\n", tftp, addr );
636 			return -EINVAL_MC_INVALID_IP;
637 		}
638 		DBGC ( tftp, "TFTP %p multicast IP address %s\n",
639 		       tftp, inet_ntoa ( socket.sin.sin_addr ) );
640 		socket.sin.sin_port = htons ( strtoul ( port, &port_end, 0 ) );
641 		if ( *port_end ) {
642 			DBGC ( tftp, "TFTP %p multicast invalid port %s\n",
643 			       tftp, port );
644 			return -EINVAL_MC_INVALID_PORT;
645 		}
646 		DBGC ( tftp, "TFTP %p multicast port %d\n",
647 		       tftp, ntohs ( socket.sin.sin_port ) );
648 		if ( ( rc = tftp_reopen_mc ( tftp, &socket.sa ) ) != 0 )
649 			return rc;
650 	}
651 
652 	return 0;
653 }
654 
655 /** A TFTP option */
656 struct tftp_option {
657 	/** Option name */
658 	const char *name;
659 	/** Option processor
660 	 *
661 	 * @v tftp	TFTP connection
662 	 * @v value	Option value
663 	 * @ret rc	Return status code
664 	 */
665 	int ( * process ) ( struct tftp_request *tftp, const char *value );
666 };
667 
668 /** Recognised TFTP options */
669 static struct tftp_option tftp_options[] = {
670 	{ "blksize", tftp_process_blksize },
671 	{ "tsize", tftp_process_tsize },
672 	{ "multicast", tftp_process_multicast },
673 	{ NULL, NULL }
674 };
675 
676 /**
677  * Process TFTP option
678  *
679  * @v tftp		TFTP connection
680  * @v name		Option name
681  * @v value		Option value
682  * @ret rc		Return status code
683  */
tftp_process_option(struct tftp_request * tftp,const char * name,const char * value)684 static int tftp_process_option ( struct tftp_request *tftp,
685 				 const char *name, const char *value ) {
686 	struct tftp_option *option;
687 
688 	for ( option = tftp_options ; option->name ; option++ ) {
689 		if ( strcasecmp ( name, option->name ) == 0 )
690 			return option->process ( tftp, value );
691 	}
692 
693 	DBGC ( tftp, "TFTP %p received unknown option \"%s\" = \"%s\"\n",
694 	       tftp, name, value );
695 
696 	/* Unknown options should be silently ignored */
697 	return 0;
698 }
699 
700 /**
701  * Receive OACK
702  *
703  * @v tftp		TFTP connection
704  * @v buf		Temporary data buffer
705  * @v len		Length of temporary data buffer
706  * @ret rc		Return status code
707  */
tftp_rx_oack(struct tftp_request * tftp,void * buf,size_t len)708 static int tftp_rx_oack ( struct tftp_request *tftp, void *buf, size_t len ) {
709 	struct tftp_oack *oack = buf;
710 	char *end = buf + len;
711 	char *name;
712 	char *value;
713 	char *next;
714 	int rc = 0;
715 
716 	/* Sanity check */
717 	if ( len < sizeof ( *oack ) ) {
718 		DBGC ( tftp, "TFTP %p received underlength OACK packet "
719 		       "length %zd\n", tftp, len );
720 		rc = -EINVAL;
721 		goto done;
722 	}
723 
724 	/* Process each option in turn */
725 	for ( name = oack->data ; name < end ; name = next ) {
726 
727 		/* Parse option name and value
728 		 *
729 		 * We treat parsing errors as non-fatal, because there
730 		 * exists at least one TFTP server (IBM Tivoli PXE
731 		 * Server 5.1.0.3) that has been observed to send
732 		 * malformed OACKs containing trailing garbage bytes.
733 		 */
734 		value = ( name + strnlen ( name, ( end - name ) ) + 1 );
735 		if ( value > end ) {
736 			DBGC ( tftp, "TFTP %p received OACK with malformed "
737 			       "option name:\n", tftp );
738 			DBGC_HD ( tftp, oack, len );
739 			break;
740 		}
741 		if ( value == end ) {
742 			DBGC ( tftp, "TFTP %p received OACK missing value "
743 			       "for option \"%s\"\n", tftp, name );
744 			DBGC_HD ( tftp, oack, len );
745 			break;
746 		}
747 		next = ( value + strnlen ( value, ( end - value ) ) + 1 );
748 		if ( next > end ) {
749 			DBGC ( tftp, "TFTP %p received OACK with malformed "
750 			       "value for option \"%s\":\n", tftp, name );
751 			DBGC_HD ( tftp, oack, len );
752 			break;
753 		}
754 
755 		/* Process option */
756 		if ( ( rc = tftp_process_option ( tftp, name, value ) ) != 0 )
757 			goto done;
758 	}
759 
760 	/* Process tsize information, if available */
761 	if ( tftp->tsize ) {
762 		if ( ( rc = tftp_presize ( tftp, tftp->tsize ) ) != 0 )
763 			goto done;
764 	}
765 
766 	/* Request next data block */
767 	tftp_send_packet ( tftp );
768 
769  done:
770 	if ( rc )
771 		tftp_done ( tftp, rc );
772 	return rc;
773 }
774 
775 /**
776  * Receive DATA
777  *
778  * @v tftp		TFTP connection
779  * @v iobuf		I/O buffer
780  * @ret rc		Return status code
781  *
782  * Takes ownership of I/O buffer.
783  */
tftp_rx_data(struct tftp_request * tftp,struct io_buffer * iobuf)784 static int tftp_rx_data ( struct tftp_request *tftp,
785 			  struct io_buffer *iobuf ) {
786 	struct tftp_data *data = iobuf->data;
787 	struct xfer_metadata meta;
788 	unsigned int block;
789 	off_t offset;
790 	size_t data_len;
791 	int rc;
792 
793 	/* Sanity check */
794 	if ( iob_len ( iobuf ) < sizeof ( *data ) ) {
795 		DBGC ( tftp, "TFTP %p received underlength DATA packet "
796 		       "length %zd\n", tftp, iob_len ( iobuf ) );
797 		rc = -EINVAL;
798 		goto done;
799 	}
800 
801 	/* Calculate block number */
802 	block = ( ( bitmap_first_gap ( &tftp->bitmap ) + 1 ) & ~0xffff );
803 	if ( data->block == 0 && block == 0 ) {
804 		DBGC ( tftp, "TFTP %p received data block 0\n", tftp );
805 		rc = -EINVAL;
806 		goto done;
807 	}
808 	block += ( ntohs ( data->block ) - 1 );
809 
810 	/* Extract data */
811 	offset = ( block * tftp->blksize );
812 	iob_pull ( iobuf, sizeof ( *data ) );
813 	data_len = iob_len ( iobuf );
814 	if ( data_len > tftp->blksize ) {
815 		DBGC ( tftp, "TFTP %p received overlength DATA packet "
816 		       "length %zd\n", tftp, data_len );
817 		rc = -EINVAL;
818 		goto done;
819 	}
820 
821 	/* Deliver data */
822 	memset ( &meta, 0, sizeof ( meta ) );
823 	meta.flags = XFER_FL_ABS_OFFSET;
824 	meta.offset = offset;
825 	if ( ( rc = xfer_deliver ( &tftp->xfer, iob_disown ( iobuf ),
826 				   &meta ) ) != 0 ) {
827 		DBGC ( tftp, "TFTP %p could not deliver data: %s\n",
828 		       tftp, strerror ( rc ) );
829 		goto done;
830 	}
831 
832 	/* Ensure block bitmap is ready */
833 	if ( ( rc = tftp_presize ( tftp, ( offset + data_len ) ) ) != 0 )
834 		goto done;
835 
836 	/* Mark block as received */
837 	bitmap_set ( &tftp->bitmap, block );
838 
839 	/* Acknowledge block */
840 	tftp_send_packet ( tftp );
841 
842 	/* If all blocks have been received, finish. */
843 	if ( bitmap_full ( &tftp->bitmap ) )
844 		tftp_done ( tftp, 0 );
845 
846  done:
847 	free_iob ( iobuf );
848 	if ( rc )
849 		tftp_done ( tftp, rc );
850 	return rc;
851 }
852 
853 /**
854  * Convert TFTP error code to return status code
855  *
856  * @v errcode		TFTP error code
857  * @ret rc		Return status code
858  */
tftp_errcode_to_rc(unsigned int errcode)859 static int tftp_errcode_to_rc ( unsigned int errcode ) {
860 	switch ( errcode ) {
861 	case TFTP_ERR_FILE_NOT_FOUND:	return -ENOENT;
862 	case TFTP_ERR_ACCESS_DENIED:	return -EACCES;
863 	case TFTP_ERR_ILLEGAL_OP:	return -ENOTTY;
864 	default:			return -ENOTSUP;
865 	}
866 }
867 
868 /**
869  * Receive ERROR
870  *
871  * @v tftp		TFTP connection
872  * @v buf		Temporary data buffer
873  * @v len		Length of temporary data buffer
874  * @ret rc		Return status code
875  */
tftp_rx_error(struct tftp_request * tftp,void * buf,size_t len)876 static int tftp_rx_error ( struct tftp_request *tftp, void *buf, size_t len ) {
877 	struct tftp_error *error = buf;
878 	int rc;
879 
880 	/* Sanity check */
881 	if ( len < sizeof ( *error ) ) {
882 		DBGC ( tftp, "TFTP %p received underlength ERROR packet "
883 		       "length %zd\n", tftp, len );
884 		return -EINVAL;
885 	}
886 
887 	DBGC ( tftp, "TFTP %p received ERROR packet with code %d, message "
888 	       "\"%s\"\n", tftp, ntohs ( error->errcode ), error->errmsg );
889 
890 	/* Determine final operation result */
891 	rc = tftp_errcode_to_rc ( ntohs ( error->errcode ) );
892 
893 	/* Close TFTP request */
894 	tftp_done ( tftp, rc );
895 
896 	return 0;
897 }
898 
899 /**
900  * Receive new data
901  *
902  * @v tftp		TFTP connection
903  * @v iobuf		I/O buffer
904  * @v meta		Transfer metadata
905  * @ret rc		Return status code
906  */
tftp_rx(struct tftp_request * tftp,struct io_buffer * iobuf,struct xfer_metadata * meta)907 static int tftp_rx ( struct tftp_request *tftp,
908 		     struct io_buffer *iobuf,
909 		     struct xfer_metadata *meta ) {
910 	struct sockaddr_tcpip *st_src;
911 	struct tftp_common *common = iobuf->data;
912 	size_t len = iob_len ( iobuf );
913 	int rc = -EINVAL;
914 
915 	/* Sanity checks */
916 	if ( len < sizeof ( *common ) ) {
917 		DBGC ( tftp, "TFTP %p received underlength packet length "
918 		       "%zd\n", tftp, len );
919 		goto done;
920 	}
921 	if ( ! meta->src ) {
922 		DBGC ( tftp, "TFTP %p received packet without source port\n",
923 		       tftp );
924 		goto done;
925 	}
926 
927 	/* Filter by TID.  Set TID on first response received */
928 	st_src = ( struct sockaddr_tcpip * ) meta->src;
929 	if ( ! tftp->peer.st_family ) {
930 		memcpy ( &tftp->peer, st_src, sizeof ( tftp->peer ) );
931 		DBGC ( tftp, "TFTP %p using remote port %d\n", tftp,
932 		       ntohs ( tftp->peer.st_port ) );
933 	} else if ( memcmp ( &tftp->peer, st_src,
934 			     sizeof ( tftp->peer ) ) != 0 ) {
935 		DBGC ( tftp, "TFTP %p received packet from wrong source (got "
936 		       "%d, wanted %d)\n", tftp, ntohs ( st_src->st_port ),
937 		       ntohs ( tftp->peer.st_port ) );
938 		goto done;
939 	}
940 
941 	switch ( common->opcode ) {
942 	case htons ( TFTP_OACK ):
943 		rc = tftp_rx_oack ( tftp, iobuf->data, len );
944 		break;
945 	case htons ( TFTP_DATA ):
946 		rc = tftp_rx_data ( tftp, iob_disown ( iobuf ) );
947 		break;
948 	case htons ( TFTP_ERROR ):
949 		rc = tftp_rx_error ( tftp, iobuf->data, len );
950 		break;
951 	default:
952 		DBGC ( tftp, "TFTP %p received strange packet type %d\n",
953 		       tftp, ntohs ( common->opcode ) );
954 		break;
955 	};
956 
957  done:
958 	free_iob ( iobuf );
959 	return rc;
960 }
961 
962 /**
963  * Receive new data via socket
964  *
965  * @v tftp		TFTP connection
966  * @v iobuf		I/O buffer
967  * @v meta		Transfer metadata
968  * @ret rc		Return status code
969  */
tftp_socket_deliver(struct tftp_request * tftp,struct io_buffer * iobuf,struct xfer_metadata * meta)970 static int tftp_socket_deliver ( struct tftp_request *tftp,
971 				 struct io_buffer *iobuf,
972 				 struct xfer_metadata *meta ) {
973 
974 	/* Enable sending ACKs when we receive a unicast packet.  This
975 	 * covers three cases:
976 	 *
977 	 * 1. Standard TFTP; we should always send ACKs, and will
978 	 *    always receive a unicast packet before we need to send the
979 	 *    first ACK.
980 	 *
981 	 * 2. RFC2090 multicast TFTP; the only unicast packets we will
982          *    receive are the OACKs; enable sending ACKs here (before
983          *    processing the OACK) and disable it when processing the
984          *    multicast option if we are not the master client.
985 	 *
986 	 * 3. MTFTP; receiving a unicast datagram indicates that we
987 	 *    are the "master client" and should send ACKs.
988 	 */
989 	tftp->flags |= TFTP_FL_SEND_ACK;
990 
991 	return tftp_rx ( tftp, iobuf, meta );
992 }
993 
994 /** TFTP socket operations */
995 static struct interface_operation tftp_socket_operations[] = {
996 	INTF_OP ( xfer_deliver, struct tftp_request *, tftp_socket_deliver ),
997 };
998 
999 /** TFTP socket interface descriptor */
1000 static struct interface_descriptor tftp_socket_desc =
1001 	INTF_DESC ( struct tftp_request, socket, tftp_socket_operations );
1002 
1003 /** TFTP multicast socket operations */
1004 static struct interface_operation tftp_mc_socket_operations[] = {
1005 	INTF_OP ( xfer_deliver, struct tftp_request *, tftp_rx ),
1006 };
1007 
1008 /** TFTP multicast socket interface descriptor */
1009 static struct interface_descriptor tftp_mc_socket_desc =
1010 	INTF_DESC ( struct tftp_request, mc_socket, tftp_mc_socket_operations );
1011 
1012 /**
1013  * Check flow control window
1014  *
1015  * @v tftp		TFTP connection
1016  * @ret len		Length of window
1017  */
tftp_xfer_window(struct tftp_request * tftp)1018 static size_t tftp_xfer_window ( struct tftp_request *tftp ) {
1019 
1020 	/* We abuse this data-xfer method to convey the blocksize to
1021 	 * the caller.  This really should be done using some kind of
1022 	 * stat() method, but we don't yet have the facility to do
1023 	 * that.
1024 	 */
1025 	return tftp->blksize;
1026 }
1027 
1028 /**
1029  * Terminate download
1030  *
1031  * @v tftp		TFTP connection
1032  * @v rc		Reason for close
1033  */
tftp_close(struct tftp_request * tftp,int rc)1034 static void tftp_close ( struct tftp_request *tftp, int rc ) {
1035 
1036 	/* Abort download */
1037 	tftp_send_error ( tftp, 0, "TFTP Aborted" );
1038 
1039 	/* Close TFTP request */
1040 	tftp_done ( tftp, rc );
1041 }
1042 
1043 /** TFTP data transfer interface operations */
1044 static struct interface_operation tftp_xfer_operations[] = {
1045 	INTF_OP ( xfer_window, struct tftp_request *, tftp_xfer_window ),
1046 	INTF_OP ( intf_close, struct tftp_request *, tftp_close ),
1047 };
1048 
1049 /** TFTP data transfer interface descriptor */
1050 static struct interface_descriptor tftp_xfer_desc =
1051 	INTF_DESC ( struct tftp_request, xfer, tftp_xfer_operations );
1052 
1053 /**
1054  * Initiate TFTP/TFTM/MTFTP download
1055  *
1056  * @v xfer		Data transfer interface
1057  * @v uri		Uniform Resource Identifier
1058  * @ret rc		Return status code
1059  */
tftp_core_open(struct interface * xfer,struct uri * uri,unsigned int default_port,struct sockaddr * multicast,unsigned int flags)1060 static int tftp_core_open ( struct interface *xfer, struct uri *uri,
1061 			    unsigned int default_port,
1062 			    struct sockaddr *multicast,
1063 			    unsigned int flags ) {
1064 	struct tftp_request *tftp;
1065 	int rc;
1066 
1067 	/* Sanity checks */
1068 	if ( ! uri->host )
1069 		return -EINVAL;
1070 	if ( ! uri->path )
1071 		return -EINVAL;
1072 	if ( uri->path[0] != '/' )
1073 		return -EINVAL;
1074 
1075 	/* Allocate and populate TFTP structure */
1076 	tftp = zalloc ( sizeof ( *tftp ) );
1077 	if ( ! tftp )
1078 		return -ENOMEM;
1079 	ref_init ( &tftp->refcnt, tftp_free );
1080 	intf_init ( &tftp->xfer, &tftp_xfer_desc, &tftp->refcnt );
1081 	intf_init ( &tftp->socket, &tftp_socket_desc, &tftp->refcnt );
1082 	intf_init ( &tftp->mc_socket, &tftp_mc_socket_desc, &tftp->refcnt );
1083 	timer_init ( &tftp->timer, tftp_timer_expired, &tftp->refcnt );
1084 	tftp->uri = uri_get ( uri );
1085 	tftp->blksize = TFTP_DEFAULT_BLKSIZE;
1086 	tftp->flags = flags;
1087 
1088 	/* Open socket */
1089 	tftp->port = uri_port ( tftp->uri, default_port );
1090 	if ( ( rc = tftp_reopen ( tftp ) ) != 0 )
1091 		goto err;
1092 
1093 	/* Open multicast socket */
1094 	if ( multicast ) {
1095 		if ( ( rc = tftp_reopen_mc ( tftp, multicast ) ) != 0 )
1096 			goto err;
1097 	}
1098 
1099 	/* Start timer to initiate RRQ */
1100 	start_timer_nodelay ( &tftp->timer );
1101 
1102 	/* Attach to parent interface, mortalise self, and return */
1103 	intf_plug_plug ( &tftp->xfer, xfer );
1104 	ref_put ( &tftp->refcnt );
1105 	return 0;
1106 
1107  err:
1108 	DBGC ( tftp, "TFTP %p could not create request: %s\n",
1109 	       tftp, strerror ( rc ) );
1110 	tftp_done ( tftp, rc );
1111 	ref_put ( &tftp->refcnt );
1112 	return rc;
1113 }
1114 
1115 /**
1116  * Initiate TFTP download
1117  *
1118  * @v xfer		Data transfer interface
1119  * @v uri		Uniform Resource Identifier
1120  * @ret rc		Return status code
1121  */
tftp_open(struct interface * xfer,struct uri * uri)1122 static int tftp_open ( struct interface *xfer, struct uri *uri ) {
1123 	return tftp_core_open ( xfer, uri, TFTP_PORT, NULL,
1124 				TFTP_FL_RRQ_SIZES );
1125 
1126 }
1127 
1128 /** TFTP URI opener */
1129 struct uri_opener tftp_uri_opener __uri_opener = {
1130 	.scheme	= "tftp",
1131 	.open	= tftp_open,
1132 };
1133 
1134 /**
1135  * Initiate TFTM download
1136  *
1137  * @v xfer		Data transfer interface
1138  * @v uri		Uniform Resource Identifier
1139  * @ret rc		Return status code
1140  */
tftm_open(struct interface * xfer,struct uri * uri)1141 static int tftm_open ( struct interface *xfer, struct uri *uri ) {
1142 	return tftp_core_open ( xfer, uri, TFTP_PORT, NULL,
1143 				( TFTP_FL_RRQ_SIZES |
1144 				  TFTP_FL_RRQ_MULTICAST ) );
1145 
1146 }
1147 
1148 /** TFTM URI opener */
1149 struct uri_opener tftm_uri_opener __uri_opener = {
1150 	.scheme	= "tftm",
1151 	.open	= tftm_open,
1152 };
1153 
1154 /**
1155  * Initiate MTFTP download
1156  *
1157  * @v xfer		Data transfer interface
1158  * @v uri		Uniform Resource Identifier
1159  * @ret rc		Return status code
1160  */
mtftp_open(struct interface * xfer,struct uri * uri)1161 static int mtftp_open ( struct interface *xfer, struct uri *uri ) {
1162 	return tftp_core_open ( xfer, uri, MTFTP_PORT,
1163 				( struct sockaddr * ) &tftp_mtftp_socket,
1164 				TFTP_FL_MTFTP_RECOVERY );
1165 }
1166 
1167 /** MTFTP URI opener */
1168 struct uri_opener mtftp_uri_opener __uri_opener = {
1169 	.scheme	= "mtftp",
1170 	.open	= mtftp_open,
1171 };
1172 
1173 /******************************************************************************
1174  *
1175  * Settings
1176  *
1177  ******************************************************************************
1178  */
1179 
1180 /**
1181  * Apply TFTP configuration settings
1182  *
1183  * @ret rc		Return status code
1184  */
tftp_apply_settings(void)1185 static int tftp_apply_settings ( void ) {
1186 	static struct in_addr tftp_server = { 0 };
1187 	struct in_addr new_tftp_server;
1188 	char uri_string[32];
1189 	struct uri *uri;
1190 
1191 	/* Retrieve TFTP server setting */
1192 	fetch_ipv4_setting ( NULL, &next_server_setting, &new_tftp_server );
1193 
1194 	/* If TFTP server setting has changed, set the current working
1195 	 * URI to match.  Do it only when the TFTP server has changed
1196 	 * to try to minimise surprises to the user, who probably
1197 	 * won't expect the CWURI to change just because they updated
1198 	 * an unrelated setting and triggered all the settings
1199 	 * applicators.
1200 	 */
1201 	if ( new_tftp_server.s_addr &&
1202 	     ( new_tftp_server.s_addr != tftp_server.s_addr ) ) {
1203 		DBGC ( &tftp_server, "TFTP server changed %s => ",
1204 		       inet_ntoa ( tftp_server ) );
1205 		DBGC ( &tftp_server, "%s\n", inet_ntoa ( new_tftp_server ) );
1206 		snprintf ( uri_string, sizeof ( uri_string ),
1207 			   "tftp://%s/", inet_ntoa ( new_tftp_server ) );
1208 		uri = parse_uri ( uri_string );
1209 		if ( ! uri )
1210 			return -ENOMEM;
1211 		churi ( uri );
1212 		uri_put ( uri );
1213 		tftp_server = new_tftp_server;
1214 	}
1215 
1216 	return 0;
1217 }
1218 
1219 /** TFTP settings applicator */
1220 struct settings_applicator tftp_settings_applicator __settings_applicator = {
1221 	.apply = tftp_apply_settings,
1222 };
1223