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,char * value)548 static int tftp_process_blksize ( struct tftp_request *tftp, char *value ) {
549 	char *end;
550 
551 	tftp->blksize = strtoul ( value, &end, 10 );
552 	if ( *end ) {
553 		DBGC ( tftp, "TFTP %p got invalid blksize \"%s\"\n",
554 		       tftp, value );
555 		return -EINVAL_BLKSIZE;
556 	}
557 	DBGC ( tftp, "TFTP %p blksize=%d\n", tftp, tftp->blksize );
558 
559 	return 0;
560 }
561 
562 /**
563  * Process TFTP "tsize" option
564  *
565  * @v tftp		TFTP connection
566  * @v value		Option value
567  * @ret rc		Return status code
568  */
tftp_process_tsize(struct tftp_request * tftp,char * value)569 static int tftp_process_tsize ( struct tftp_request *tftp, char *value ) {
570 	char *end;
571 
572 	tftp->tsize = strtoul ( value, &end, 10 );
573 	if ( *end ) {
574 		DBGC ( tftp, "TFTP %p got invalid tsize \"%s\"\n",
575 		       tftp, value );
576 		return -EINVAL_TSIZE;
577 	}
578 	DBGC ( tftp, "TFTP %p tsize=%ld\n", tftp, tftp->tsize );
579 
580 	return 0;
581 }
582 
583 /**
584  * Process TFTP "multicast" option
585  *
586  * @v tftp		TFTP connection
587  * @v value		Option value
588  * @ret rc		Return status code
589  */
tftp_process_multicast(struct tftp_request * tftp,char * value)590 static int tftp_process_multicast ( struct tftp_request *tftp, char *value ) {
591 	union {
592 		struct sockaddr sa;
593 		struct sockaddr_in sin;
594 	} socket;
595 	char *addr;
596 	char *port;
597 	char *port_end;
598 	char *mc;
599 	char *mc_end;
600 	int rc;
601 
602 	/* Split value into "addr,port,mc" fields */
603 	addr = value;
604 	port = strchr ( addr, ',' );
605 	if ( ! port ) {
606 		DBGC ( tftp, "TFTP %p multicast missing port,mc\n", tftp );
607 		return -EINVAL_MC_NO_PORT;
608 	}
609 	*(port++) = '\0';
610 	mc = strchr ( port, ',' );
611 	if ( ! mc ) {
612 		DBGC ( tftp, "TFTP %p multicast missing mc\n", tftp );
613 		return -EINVAL_MC_NO_MC;
614 	}
615 	*(mc++) = '\0';
616 
617 	/* Parse parameters */
618 	if ( strtoul ( mc, &mc_end, 0 ) == 0 )
619 		tftp->flags &= ~TFTP_FL_SEND_ACK;
620 	if ( *mc_end ) {
621 		DBGC ( tftp, "TFTP %p multicast invalid mc %s\n", tftp, mc );
622 		return -EINVAL_MC_INVALID_MC;
623 	}
624 	DBGC ( tftp, "TFTP %p is%s the master client\n",
625 	       tftp, ( ( tftp->flags & TFTP_FL_SEND_ACK ) ? "" : " not" ) );
626 	if ( *addr && *port ) {
627 		socket.sin.sin_family = AF_INET;
628 		if ( inet_aton ( addr, &socket.sin.sin_addr ) == 0 ) {
629 			DBGC ( tftp, "TFTP %p multicast invalid IP address "
630 			       "%s\n", tftp, addr );
631 			return -EINVAL_MC_INVALID_IP;
632 		}
633 		DBGC ( tftp, "TFTP %p multicast IP address %s\n",
634 		       tftp, inet_ntoa ( socket.sin.sin_addr ) );
635 		socket.sin.sin_port = htons ( strtoul ( port, &port_end, 0 ) );
636 		if ( *port_end ) {
637 			DBGC ( tftp, "TFTP %p multicast invalid port %s\n",
638 			       tftp, port );
639 			return -EINVAL_MC_INVALID_PORT;
640 		}
641 		DBGC ( tftp, "TFTP %p multicast port %d\n",
642 		       tftp, ntohs ( socket.sin.sin_port ) );
643 		if ( ( rc = tftp_reopen_mc ( tftp, &socket.sa ) ) != 0 )
644 			return rc;
645 	}
646 
647 	return 0;
648 }
649 
650 /** A TFTP option */
651 struct tftp_option {
652 	/** Option name */
653 	const char *name;
654 	/** Option processor
655 	 *
656 	 * @v tftp	TFTP connection
657 	 * @v value	Option value
658 	 * @ret rc	Return status code
659 	 */
660 	int ( * process ) ( struct tftp_request *tftp, char *value );
661 };
662 
663 /** Recognised TFTP options */
664 static struct tftp_option tftp_options[] = {
665 	{ "blksize", tftp_process_blksize },
666 	{ "tsize", tftp_process_tsize },
667 	{ "multicast", tftp_process_multicast },
668 	{ NULL, NULL }
669 };
670 
671 /**
672  * Process TFTP option
673  *
674  * @v tftp		TFTP connection
675  * @v name		Option name
676  * @v value		Option value
677  * @ret rc		Return status code
678  */
tftp_process_option(struct tftp_request * tftp,const char * name,char * value)679 static int tftp_process_option ( struct tftp_request *tftp,
680 				 const char *name, char *value ) {
681 	struct tftp_option *option;
682 
683 	for ( option = tftp_options ; option->name ; option++ ) {
684 		if ( strcasecmp ( name, option->name ) == 0 )
685 			return option->process ( tftp, value );
686 	}
687 
688 	DBGC ( tftp, "TFTP %p received unknown option \"%s\" = \"%s\"\n",
689 	       tftp, name, value );
690 
691 	/* Unknown options should be silently ignored */
692 	return 0;
693 }
694 
695 /**
696  * Receive OACK
697  *
698  * @v tftp		TFTP connection
699  * @v buf		Temporary data buffer
700  * @v len		Length of temporary data buffer
701  * @ret rc		Return status code
702  */
tftp_rx_oack(struct tftp_request * tftp,void * buf,size_t len)703 static int tftp_rx_oack ( struct tftp_request *tftp, void *buf, size_t len ) {
704 	struct tftp_oack *oack = buf;
705 	char *end = buf + len;
706 	char *name;
707 	char *value;
708 	char *next;
709 	int rc = 0;
710 
711 	/* Sanity check */
712 	if ( len < sizeof ( *oack ) ) {
713 		DBGC ( tftp, "TFTP %p received underlength OACK packet "
714 		       "length %zd\n", tftp, len );
715 		rc = -EINVAL;
716 		goto done;
717 	}
718 
719 	/* Process each option in turn */
720 	for ( name = oack->data ; name < end ; name = next ) {
721 
722 		/* Parse option name and value
723 		 *
724 		 * We treat parsing errors as non-fatal, because there
725 		 * exists at least one TFTP server (IBM Tivoli PXE
726 		 * Server 5.1.0.3) that has been observed to send
727 		 * malformed OACKs containing trailing garbage bytes.
728 		 */
729 		value = ( name + strnlen ( name, ( end - name ) ) + 1 );
730 		if ( value > end ) {
731 			DBGC ( tftp, "TFTP %p received OACK with malformed "
732 			       "option name:\n", tftp );
733 			DBGC_HD ( tftp, oack, len );
734 			break;
735 		}
736 		if ( value == end ) {
737 			DBGC ( tftp, "TFTP %p received OACK missing value "
738 			       "for option \"%s\"\n", tftp, name );
739 			DBGC_HD ( tftp, oack, len );
740 			break;
741 		}
742 		next = ( value + strnlen ( value, ( end - value ) ) + 1 );
743 		if ( next > end ) {
744 			DBGC ( tftp, "TFTP %p received OACK with malformed "
745 			       "value for option \"%s\":\n", tftp, name );
746 			DBGC_HD ( tftp, oack, len );
747 			break;
748 		}
749 
750 		/* Process option */
751 		if ( ( rc = tftp_process_option ( tftp, name, value ) ) != 0 )
752 			goto done;
753 	}
754 
755 	/* Process tsize information, if available */
756 	if ( tftp->tsize ) {
757 		if ( ( rc = tftp_presize ( tftp, tftp->tsize ) ) != 0 )
758 			goto done;
759 	}
760 
761 	/* Request next data block */
762 	tftp_send_packet ( tftp );
763 
764  done:
765 	if ( rc )
766 		tftp_done ( tftp, rc );
767 	return rc;
768 }
769 
770 /**
771  * Receive DATA
772  *
773  * @v tftp		TFTP connection
774  * @v iobuf		I/O buffer
775  * @ret rc		Return status code
776  *
777  * Takes ownership of I/O buffer.
778  */
tftp_rx_data(struct tftp_request * tftp,struct io_buffer * iobuf)779 static int tftp_rx_data ( struct tftp_request *tftp,
780 			  struct io_buffer *iobuf ) {
781 	struct tftp_data *data = iobuf->data;
782 	struct xfer_metadata meta;
783 	unsigned int block;
784 	off_t offset;
785 	size_t data_len;
786 	int rc;
787 
788 	/* Sanity check */
789 	if ( iob_len ( iobuf ) < sizeof ( *data ) ) {
790 		DBGC ( tftp, "TFTP %p received underlength DATA packet "
791 		       "length %zd\n", tftp, iob_len ( iobuf ) );
792 		rc = -EINVAL;
793 		goto done;
794 	}
795 
796 	/* Calculate block number */
797 	block = ( ( bitmap_first_gap ( &tftp->bitmap ) + 1 ) & ~0xffff );
798 	if ( data->block == 0 && block == 0 ) {
799 		DBGC ( tftp, "TFTP %p received data block 0\n", tftp );
800 		rc = -EINVAL;
801 		goto done;
802 	}
803 	block += ( ntohs ( data->block ) - 1 );
804 
805 	/* Extract data */
806 	offset = ( block * tftp->blksize );
807 	iob_pull ( iobuf, sizeof ( *data ) );
808 	data_len = iob_len ( iobuf );
809 	if ( data_len > tftp->blksize ) {
810 		DBGC ( tftp, "TFTP %p received overlength DATA packet "
811 		       "length %zd\n", tftp, data_len );
812 		rc = -EINVAL;
813 		goto done;
814 	}
815 
816 	/* Deliver data */
817 	memset ( &meta, 0, sizeof ( meta ) );
818 	meta.flags = XFER_FL_ABS_OFFSET;
819 	meta.offset = offset;
820 	if ( ( rc = xfer_deliver ( &tftp->xfer, iob_disown ( iobuf ),
821 				   &meta ) ) != 0 ) {
822 		DBGC ( tftp, "TFTP %p could not deliver data: %s\n",
823 		       tftp, strerror ( rc ) );
824 		goto done;
825 	}
826 
827 	/* Ensure block bitmap is ready */
828 	if ( ( rc = tftp_presize ( tftp, ( offset + data_len ) ) ) != 0 )
829 		goto done;
830 
831 	/* Mark block as received */
832 	bitmap_set ( &tftp->bitmap, block );
833 
834 	/* Acknowledge block */
835 	tftp_send_packet ( tftp );
836 
837 	/* If all blocks have been received, finish. */
838 	if ( bitmap_full ( &tftp->bitmap ) )
839 		tftp_done ( tftp, 0 );
840 
841  done:
842 	free_iob ( iobuf );
843 	if ( rc )
844 		tftp_done ( tftp, rc );
845 	return rc;
846 }
847 
848 /**
849  * Convert TFTP error code to return status code
850  *
851  * @v errcode		TFTP error code
852  * @ret rc		Return status code
853  */
tftp_errcode_to_rc(unsigned int errcode)854 static int tftp_errcode_to_rc ( unsigned int errcode ) {
855 	switch ( errcode ) {
856 	case TFTP_ERR_FILE_NOT_FOUND:	return -ENOENT;
857 	case TFTP_ERR_ACCESS_DENIED:	return -EACCES;
858 	case TFTP_ERR_ILLEGAL_OP:	return -ENOTTY;
859 	default:			return -ENOTSUP;
860 	}
861 }
862 
863 /**
864  * Receive ERROR
865  *
866  * @v tftp		TFTP connection
867  * @v buf		Temporary data buffer
868  * @v len		Length of temporary data buffer
869  * @ret rc		Return status code
870  */
tftp_rx_error(struct tftp_request * tftp,void * buf,size_t len)871 static int tftp_rx_error ( struct tftp_request *tftp, void *buf, size_t len ) {
872 	struct tftp_error *error = buf;
873 	int rc;
874 
875 	/* Sanity check */
876 	if ( len < sizeof ( *error ) ) {
877 		DBGC ( tftp, "TFTP %p received underlength ERROR packet "
878 		       "length %zd\n", tftp, len );
879 		return -EINVAL;
880 	}
881 
882 	DBGC ( tftp, "TFTP %p received ERROR packet with code %d, message "
883 	       "\"%s\"\n", tftp, ntohs ( error->errcode ), error->errmsg );
884 
885 	/* Determine final operation result */
886 	rc = tftp_errcode_to_rc ( ntohs ( error->errcode ) );
887 
888 	/* Close TFTP request */
889 	tftp_done ( tftp, rc );
890 
891 	return 0;
892 }
893 
894 /**
895  * Receive new data
896  *
897  * @v tftp		TFTP connection
898  * @v iobuf		I/O buffer
899  * @v meta		Transfer metadata
900  * @ret rc		Return status code
901  */
tftp_rx(struct tftp_request * tftp,struct io_buffer * iobuf,struct xfer_metadata * meta)902 static int tftp_rx ( struct tftp_request *tftp,
903 		     struct io_buffer *iobuf,
904 		     struct xfer_metadata *meta ) {
905 	struct sockaddr_tcpip *st_src;
906 	struct tftp_common *common = iobuf->data;
907 	size_t len = iob_len ( iobuf );
908 	int rc = -EINVAL;
909 
910 	/* Sanity checks */
911 	if ( len < sizeof ( *common ) ) {
912 		DBGC ( tftp, "TFTP %p received underlength packet length "
913 		       "%zd\n", tftp, len );
914 		goto done;
915 	}
916 	if ( ! meta->src ) {
917 		DBGC ( tftp, "TFTP %p received packet without source port\n",
918 		       tftp );
919 		goto done;
920 	}
921 
922 	/* Filter by TID.  Set TID on first response received */
923 	st_src = ( struct sockaddr_tcpip * ) meta->src;
924 	if ( ! tftp->peer.st_family ) {
925 		memcpy ( &tftp->peer, st_src, sizeof ( tftp->peer ) );
926 		DBGC ( tftp, "TFTP %p using remote port %d\n", tftp,
927 		       ntohs ( tftp->peer.st_port ) );
928 	} else if ( memcmp ( &tftp->peer, st_src,
929 			     sizeof ( tftp->peer ) ) != 0 ) {
930 		DBGC ( tftp, "TFTP %p received packet from wrong source (got "
931 		       "%d, wanted %d)\n", tftp, ntohs ( st_src->st_port ),
932 		       ntohs ( tftp->peer.st_port ) );
933 		goto done;
934 	}
935 
936 	switch ( common->opcode ) {
937 	case htons ( TFTP_OACK ):
938 		rc = tftp_rx_oack ( tftp, iobuf->data, len );
939 		break;
940 	case htons ( TFTP_DATA ):
941 		rc = tftp_rx_data ( tftp, iob_disown ( iobuf ) );
942 		break;
943 	case htons ( TFTP_ERROR ):
944 		rc = tftp_rx_error ( tftp, iobuf->data, len );
945 		break;
946 	default:
947 		DBGC ( tftp, "TFTP %p received strange packet type %d\n",
948 		       tftp, ntohs ( common->opcode ) );
949 		break;
950 	};
951 
952  done:
953 	free_iob ( iobuf );
954 	return rc;
955 }
956 
957 /**
958  * Receive new data via socket
959  *
960  * @v tftp		TFTP connection
961  * @v iobuf		I/O buffer
962  * @v meta		Transfer metadata
963  * @ret rc		Return status code
964  */
tftp_socket_deliver(struct tftp_request * tftp,struct io_buffer * iobuf,struct xfer_metadata * meta)965 static int tftp_socket_deliver ( struct tftp_request *tftp,
966 				 struct io_buffer *iobuf,
967 				 struct xfer_metadata *meta ) {
968 
969 	/* Enable sending ACKs when we receive a unicast packet.  This
970 	 * covers three cases:
971 	 *
972 	 * 1. Standard TFTP; we should always send ACKs, and will
973 	 *    always receive a unicast packet before we need to send the
974 	 *    first ACK.
975 	 *
976 	 * 2. RFC2090 multicast TFTP; the only unicast packets we will
977          *    receive are the OACKs; enable sending ACKs here (before
978          *    processing the OACK) and disable it when processing the
979          *    multicast option if we are not the master client.
980 	 *
981 	 * 3. MTFTP; receiving a unicast datagram indicates that we
982 	 *    are the "master client" and should send ACKs.
983 	 */
984 	tftp->flags |= TFTP_FL_SEND_ACK;
985 
986 	return tftp_rx ( tftp, iobuf, meta );
987 }
988 
989 /** TFTP socket operations */
990 static struct interface_operation tftp_socket_operations[] = {
991 	INTF_OP ( xfer_deliver, struct tftp_request *, tftp_socket_deliver ),
992 };
993 
994 /** TFTP socket interface descriptor */
995 static struct interface_descriptor tftp_socket_desc =
996 	INTF_DESC ( struct tftp_request, socket, tftp_socket_operations );
997 
998 /** TFTP multicast socket operations */
999 static struct interface_operation tftp_mc_socket_operations[] = {
1000 	INTF_OP ( xfer_deliver, struct tftp_request *, tftp_rx ),
1001 };
1002 
1003 /** TFTP multicast socket interface descriptor */
1004 static struct interface_descriptor tftp_mc_socket_desc =
1005 	INTF_DESC ( struct tftp_request, mc_socket, tftp_mc_socket_operations );
1006 
1007 /**
1008  * Check flow control window
1009  *
1010  * @v tftp		TFTP connection
1011  * @ret len		Length of window
1012  */
tftp_xfer_window(struct tftp_request * tftp)1013 static size_t tftp_xfer_window ( struct tftp_request *tftp ) {
1014 
1015 	/* We abuse this data-xfer method to convey the blocksize to
1016 	 * the caller.  This really should be done using some kind of
1017 	 * stat() method, but we don't yet have the facility to do
1018 	 * that.
1019 	 */
1020 	return tftp->blksize;
1021 }
1022 
1023 /**
1024  * Terminate download
1025  *
1026  * @v tftp		TFTP connection
1027  * @v rc		Reason for close
1028  */
tftp_close(struct tftp_request * tftp,int rc)1029 static void tftp_close ( struct tftp_request *tftp, int rc ) {
1030 
1031 	/* Abort download */
1032 	tftp_send_error ( tftp, 0, "TFTP Aborted" );
1033 
1034 	/* Close TFTP request */
1035 	tftp_done ( tftp, rc );
1036 }
1037 
1038 /** TFTP data transfer interface operations */
1039 static struct interface_operation tftp_xfer_operations[] = {
1040 	INTF_OP ( xfer_window, struct tftp_request *, tftp_xfer_window ),
1041 	INTF_OP ( intf_close, struct tftp_request *, tftp_close ),
1042 };
1043 
1044 /** TFTP data transfer interface descriptor */
1045 static struct interface_descriptor tftp_xfer_desc =
1046 	INTF_DESC ( struct tftp_request, xfer, tftp_xfer_operations );
1047 
1048 /**
1049  * Initiate TFTP/TFTM/MTFTP download
1050  *
1051  * @v xfer		Data transfer interface
1052  * @v uri		Uniform Resource Identifier
1053  * @ret rc		Return status code
1054  */
tftp_core_open(struct interface * xfer,struct uri * uri,unsigned int default_port,struct sockaddr * multicast,unsigned int flags)1055 static int tftp_core_open ( struct interface *xfer, struct uri *uri,
1056 			    unsigned int default_port,
1057 			    struct sockaddr *multicast,
1058 			    unsigned int flags ) {
1059 	struct tftp_request *tftp;
1060 	int rc;
1061 
1062 	/* Sanity checks */
1063 	if ( ! uri->host )
1064 		return -EINVAL;
1065 	if ( ! uri->path )
1066 		return -EINVAL;
1067 	if ( uri->path[0] != '/' )
1068 		return -EINVAL;
1069 
1070 	/* Allocate and populate TFTP structure */
1071 	tftp = zalloc ( sizeof ( *tftp ) );
1072 	if ( ! tftp )
1073 		return -ENOMEM;
1074 	ref_init ( &tftp->refcnt, tftp_free );
1075 	intf_init ( &tftp->xfer, &tftp_xfer_desc, &tftp->refcnt );
1076 	intf_init ( &tftp->socket, &tftp_socket_desc, &tftp->refcnt );
1077 	intf_init ( &tftp->mc_socket, &tftp_mc_socket_desc, &tftp->refcnt );
1078 	timer_init ( &tftp->timer, tftp_timer_expired, &tftp->refcnt );
1079 	tftp->uri = uri_get ( uri );
1080 	tftp->blksize = TFTP_DEFAULT_BLKSIZE;
1081 	tftp->flags = flags;
1082 
1083 	/* Open socket */
1084 	tftp->port = uri_port ( tftp->uri, default_port );
1085 	if ( ( rc = tftp_reopen ( tftp ) ) != 0 )
1086 		goto err;
1087 
1088 	/* Open multicast socket */
1089 	if ( multicast ) {
1090 		if ( ( rc = tftp_reopen_mc ( tftp, multicast ) ) != 0 )
1091 			goto err;
1092 	}
1093 
1094 	/* Start timer to initiate RRQ */
1095 	start_timer_nodelay ( &tftp->timer );
1096 
1097 	/* Attach to parent interface, mortalise self, and return */
1098 	intf_plug_plug ( &tftp->xfer, xfer );
1099 	ref_put ( &tftp->refcnt );
1100 	return 0;
1101 
1102  err:
1103 	DBGC ( tftp, "TFTP %p could not create request: %s\n",
1104 	       tftp, strerror ( rc ) );
1105 	tftp_done ( tftp, rc );
1106 	ref_put ( &tftp->refcnt );
1107 	return rc;
1108 }
1109 
1110 /**
1111  * Initiate TFTP download
1112  *
1113  * @v xfer		Data transfer interface
1114  * @v uri		Uniform Resource Identifier
1115  * @ret rc		Return status code
1116  */
tftp_open(struct interface * xfer,struct uri * uri)1117 static int tftp_open ( struct interface *xfer, struct uri *uri ) {
1118 	return tftp_core_open ( xfer, uri, TFTP_PORT, NULL,
1119 				TFTP_FL_RRQ_SIZES );
1120 
1121 }
1122 
1123 /** TFTP URI opener */
1124 struct uri_opener tftp_uri_opener __uri_opener = {
1125 	.scheme	= "tftp",
1126 	.open	= tftp_open,
1127 };
1128 
1129 /**
1130  * Initiate TFTM download
1131  *
1132  * @v xfer		Data transfer interface
1133  * @v uri		Uniform Resource Identifier
1134  * @ret rc		Return status code
1135  */
tftm_open(struct interface * xfer,struct uri * uri)1136 static int tftm_open ( struct interface *xfer, struct uri *uri ) {
1137 	return tftp_core_open ( xfer, uri, TFTP_PORT, NULL,
1138 				( TFTP_FL_RRQ_SIZES |
1139 				  TFTP_FL_RRQ_MULTICAST ) );
1140 
1141 }
1142 
1143 /** TFTM URI opener */
1144 struct uri_opener tftm_uri_opener __uri_opener = {
1145 	.scheme	= "tftm",
1146 	.open	= tftm_open,
1147 };
1148 
1149 /**
1150  * Initiate MTFTP download
1151  *
1152  * @v xfer		Data transfer interface
1153  * @v uri		Uniform Resource Identifier
1154  * @ret rc		Return status code
1155  */
mtftp_open(struct interface * xfer,struct uri * uri)1156 static int mtftp_open ( struct interface *xfer, struct uri *uri ) {
1157 	return tftp_core_open ( xfer, uri, MTFTP_PORT,
1158 				( struct sockaddr * ) &tftp_mtftp_socket,
1159 				TFTP_FL_MTFTP_RECOVERY );
1160 }
1161 
1162 /** MTFTP URI opener */
1163 struct uri_opener mtftp_uri_opener __uri_opener = {
1164 	.scheme	= "mtftp",
1165 	.open	= mtftp_open,
1166 };
1167 
1168 /******************************************************************************
1169  *
1170  * Settings
1171  *
1172  ******************************************************************************
1173  */
1174 
1175 /**
1176  * Apply TFTP configuration settings
1177  *
1178  * @ret rc		Return status code
1179  */
tftp_apply_settings(void)1180 static int tftp_apply_settings ( void ) {
1181 	static struct in_addr tftp_server = { 0 };
1182 	struct in_addr new_tftp_server;
1183 	char uri_string[32];
1184 	struct uri *uri;
1185 
1186 	/* Retrieve TFTP server setting */
1187 	fetch_ipv4_setting ( NULL, &next_server_setting, &new_tftp_server );
1188 
1189 	/* If TFTP server setting has changed, set the current working
1190 	 * URI to match.  Do it only when the TFTP server has changed
1191 	 * to try to minimise surprises to the user, who probably
1192 	 * won't expect the CWURI to change just because they updated
1193 	 * an unrelated setting and triggered all the settings
1194 	 * applicators.
1195 	 */
1196 	if ( new_tftp_server.s_addr &&
1197 	     ( new_tftp_server.s_addr != tftp_server.s_addr ) ) {
1198 		DBGC ( &tftp_server, "TFTP server changed %s => ",
1199 		       inet_ntoa ( tftp_server ) );
1200 		DBGC ( &tftp_server, "%s\n", inet_ntoa ( new_tftp_server ) );
1201 		snprintf ( uri_string, sizeof ( uri_string ),
1202 			   "tftp://%s/", inet_ntoa ( new_tftp_server ) );
1203 		uri = parse_uri ( uri_string );
1204 		if ( ! uri )
1205 			return -ENOMEM;
1206 		churi ( uri );
1207 		uri_put ( uri );
1208 		tftp_server = new_tftp_server;
1209 	}
1210 
1211 	return 0;
1212 }
1213 
1214 /** TFTP settings applicator */
1215 struct settings_applicator tftp_settings_applicator __settings_applicator = {
1216 	.apply = tftp_apply_settings,
1217 };
1218