These changes are the raw update to qemu-2.6.
[kvmfornfv.git] / qemu / roms / ipxe / src / net / udp / tftp.c
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  */
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  */
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  */
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  */
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  */
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         num_blocks = ( ( filesize / tftp->blksize ) + 1 );
283         if ( ( rc = bitmap_resize ( &tftp->bitmap, num_blocks ) ) != 0 ) {
284                 DBGC ( tftp, "TFTP %p could not resize bitmap to %d blocks: "
285                        "%s\n", tftp, num_blocks, strerror ( rc ) );
286                 return rc;
287         }
288
289         return 0;
290 }
291
292 /**
293  * MTFTP multicast receive address
294  *
295  * This is treated as a global configuration parameter.
296  */
297 static struct sockaddr_in tftp_mtftp_socket = {
298         .sin_family = AF_INET,
299         .sin_addr.s_addr = htonl ( 0xefff0101 ),
300         .sin_port = htons ( 3001 ),
301 };
302
303 /**
304  * Set MTFTP multicast address
305  *
306  * @v address           Multicast IPv4 address
307  */
308 void tftp_set_mtftp_address ( struct in_addr address ) {
309         tftp_mtftp_socket.sin_addr = address;
310 }
311
312 /**
313  * Set MTFTP multicast port
314  *
315  * @v port              Multicast port
316  */
317 void tftp_set_mtftp_port ( unsigned int port ) {
318         tftp_mtftp_socket.sin_port = htons ( port );
319 }
320
321 /**
322  * Transmit RRQ
323  *
324  * @v tftp              TFTP connection
325  * @ret rc              Return status code
326  */
327 static int tftp_send_rrq ( struct tftp_request *tftp ) {
328         const char *path = tftp->uri->path;
329         struct tftp_rrq *rrq;
330         size_t len;
331         struct io_buffer *iobuf;
332         size_t blksize;
333
334         DBGC ( tftp, "TFTP %p requesting \"%s\"\n", tftp, path );
335
336         /* Allocate buffer */
337         len = ( sizeof ( *rrq ) + strlen ( path ) + 1 /* NUL */
338                 + 5 + 1 /* "octet" + NUL */
339                 + 7 + 1 + 5 + 1 /* "blksize" + NUL + ddddd + NUL */
340                 + 5 + 1 + 1 + 1 /* "tsize" + NUL + "0" + NUL */ 
341                 + 9 + 1 + 1 /* "multicast" + NUL + NUL */ );
342         iobuf = xfer_alloc_iob ( &tftp->socket, len );
343         if ( ! iobuf )
344                 return -ENOMEM;
345
346         /* Determine block size */
347         blksize = xfer_window ( &tftp->xfer );
348         if ( blksize > TFTP_MAX_BLKSIZE )
349                 blksize = TFTP_MAX_BLKSIZE;
350
351         /* Build request */
352         rrq = iob_put ( iobuf, sizeof ( *rrq ) );
353         rrq->opcode = htons ( TFTP_RRQ );
354         iob_put ( iobuf, snprintf ( iobuf->tail, iob_tailroom ( iobuf ),
355                                     "%s%coctet", path, 0 ) + 1 );
356         if ( tftp->flags & TFTP_FL_RRQ_SIZES ) {
357                 iob_put ( iobuf, snprintf ( iobuf->tail,
358                                             iob_tailroom ( iobuf ),
359                                             "blksize%c%zd%ctsize%c0",
360                                             0, blksize, 0, 0 ) + 1 );
361         }
362         if ( tftp->flags & TFTP_FL_RRQ_MULTICAST ) {
363                 iob_put ( iobuf, snprintf ( iobuf->tail,
364                                             iob_tailroom ( iobuf ),
365                                             "multicast%c", 0 ) + 1 );
366         }
367
368         /* RRQ always goes to the address specified in the initial
369          * xfer_open() call
370          */
371         return xfer_deliver_iob ( &tftp->socket, iobuf );
372 }
373
374 /**
375  * Transmit ACK
376  *
377  * @v tftp              TFTP connection
378  * @ret rc              Return status code
379  */
380 static int tftp_send_ack ( struct tftp_request *tftp ) {
381         struct tftp_ack *ack;
382         struct io_buffer *iobuf;
383         struct xfer_metadata meta = {
384                 .dest = ( struct sockaddr * ) &tftp->peer,
385         };
386         unsigned int block;
387
388         /* Determine next required block number */
389         block = bitmap_first_gap ( &tftp->bitmap );
390         DBGC2 ( tftp, "TFTP %p sending ACK for block %d\n", tftp, block );
391
392         /* Allocate buffer */
393         iobuf = xfer_alloc_iob ( &tftp->socket, sizeof ( *ack ) );
394         if ( ! iobuf )
395                 return -ENOMEM;
396
397         /* Build ACK */
398         ack = iob_put ( iobuf, sizeof ( *ack ) );
399         ack->opcode = htons ( TFTP_ACK );
400         ack->block = htons ( block );
401
402         /* ACK always goes to the peer recorded from the RRQ response */
403         return xfer_deliver ( &tftp->socket, iobuf, &meta );
404 }
405
406 /**
407  * Transmit ERROR (Abort)
408  *
409  * @v tftp              TFTP connection
410  * @v errcode           TFTP error code
411  * @v errmsg            Error message string
412  * @ret rc              Return status code
413  */
414 static int tftp_send_error ( struct tftp_request *tftp, int errcode,
415                              const char *errmsg ) {
416         struct tftp_error *err;
417         struct io_buffer *iobuf;
418         struct xfer_metadata meta = {
419                 .dest = ( struct sockaddr * ) &tftp->peer,
420         };
421         size_t msglen;
422
423         DBGC2 ( tftp, "TFTP %p sending ERROR %d: %s\n", tftp, errcode,
424                 errmsg );
425
426         /* Allocate buffer */
427         msglen = sizeof ( *err ) + strlen ( errmsg ) + 1 /* NUL */;
428         iobuf = xfer_alloc_iob ( &tftp->socket, msglen );
429         if ( ! iobuf )
430                 return -ENOMEM;
431
432         /* Build ERROR */
433         err = iob_put ( iobuf, msglen );
434         err->opcode = htons ( TFTP_ERROR );
435         err->errcode = htons ( errcode );
436         strcpy ( err->errmsg, errmsg );
437
438         /* ERR always goes to the peer recorded from the RRQ response */
439         return xfer_deliver ( &tftp->socket, iobuf, &meta );
440 }
441
442 /**
443  * Transmit next relevant packet
444  *
445  * @v tftp              TFTP connection
446  * @ret rc              Return status code
447  */
448 static int tftp_send_packet ( struct tftp_request *tftp ) {
449
450         /* Update retransmission timer.  While name resolution takes place the
451          * window is zero.  Avoid unnecessary delay after name resolution
452          * completes by retrying immediately.
453          */
454         stop_timer ( &tftp->timer );
455         if ( xfer_window ( &tftp->socket ) ) {
456                 start_timer ( &tftp->timer );
457         } else {
458                 start_timer_nodelay ( &tftp->timer );
459         }
460
461         /* Send RRQ or ACK as appropriate */
462         if ( ! tftp->peer.st_family ) {
463                 return tftp_send_rrq ( tftp );
464         } else {
465                 if ( tftp->flags & TFTP_FL_SEND_ACK ) {
466                         return tftp_send_ack ( tftp );
467                 } else {
468                         return 0;
469                 }
470         }
471 }
472
473 /**
474  * Handle TFTP retransmission timer expiry
475  *
476  * @v timer             Retry timer
477  * @v fail              Failure indicator
478  */
479 static void tftp_timer_expired ( struct retry_timer *timer, int fail ) {
480         struct tftp_request *tftp =
481                 container_of ( timer, struct tftp_request, timer );
482         int rc;
483
484         /* If we are doing MTFTP, attempt the various recovery strategies */
485         if ( tftp->flags & TFTP_FL_MTFTP_RECOVERY ) {
486                 if ( tftp->peer.st_family ) {
487                         /* If we have received any response from the server,
488                          * try resending the RRQ to restart the download.
489                          */
490                         DBGC ( tftp, "TFTP %p attempting reopen\n", tftp );
491                         if ( ( rc = tftp_reopen ( tftp ) ) != 0 )
492                                 goto err;
493                 } else {
494                         /* Fall back to plain TFTP after several attempts */
495                         tftp->mtftp_timeouts++;
496                         DBGC ( tftp, "TFTP %p timeout %d waiting for MTFTP "
497                                "open\n", tftp, tftp->mtftp_timeouts );
498
499                         if ( tftp->mtftp_timeouts > MTFTP_MAX_TIMEOUTS ) {
500                                 DBGC ( tftp, "TFTP %p falling back to plain "
501                                        "TFTP\n", tftp );
502                                 tftp->flags = TFTP_FL_RRQ_SIZES;
503
504                                 /* Close multicast socket */
505                                 intf_restart ( &tftp->mc_socket, 0 );
506
507                                 /* Reset retry timer */
508                                 start_timer_nodelay ( &tftp->timer );
509
510                                 /* The blocksize may change: discard
511                                  * the block bitmap
512                                  */
513                                 bitmap_free ( &tftp->bitmap );
514                                 memset ( &tftp->bitmap, 0,
515                                          sizeof ( tftp->bitmap ) );
516
517                                 /* Reopen on standard TFTP port */
518                                 tftp->port = TFTP_PORT;
519                                 if ( ( rc = tftp_reopen ( tftp ) ) != 0 )
520                                         goto err;
521                         }
522                 }
523         } else {
524                 /* Not doing MTFTP (or have fallen back to plain
525                  * TFTP); fail as per normal.
526                  */
527                 if ( fail ) {
528                         rc = -ETIMEDOUT;
529                         goto err;
530                 }
531         }
532         tftp_send_packet ( tftp );
533         return;
534
535  err:
536         tftp_done ( tftp, rc );
537 }
538
539 /**
540  * Process TFTP "blksize" option
541  *
542  * @v tftp              TFTP connection
543  * @v value             Option value
544  * @ret rc              Return status code
545  */
546 static int tftp_process_blksize ( struct tftp_request *tftp,
547                                   const char *value ) {
548         char *end;
549
550         tftp->blksize = strtoul ( value, &end, 10 );
551         if ( *end ) {
552                 DBGC ( tftp, "TFTP %p got invalid blksize \"%s\"\n",
553                        tftp, value );
554                 return -EINVAL_BLKSIZE;
555         }
556         DBGC ( tftp, "TFTP %p blksize=%d\n", tftp, tftp->blksize );
557
558         return 0;
559 }
560
561 /**
562  * Process TFTP "tsize" option
563  *
564  * @v tftp              TFTP connection
565  * @v value             Option value
566  * @ret rc              Return status code
567  */
568 static int tftp_process_tsize ( struct tftp_request *tftp,
569                                 const 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  */
590 static int tftp_process_multicast ( struct tftp_request *tftp,
591                                     const char *value ) {
592         union {
593                 struct sockaddr sa;
594                 struct sockaddr_in sin;
595         } socket;
596         char buf[ strlen ( value ) + 1 ];
597         char *addr;
598         char *port;
599         char *port_end;
600         char *mc;
601         char *mc_end;
602         int rc;
603
604         /* Split value into "addr,port,mc" fields */
605         memcpy ( buf, value, sizeof ( buf ) );
606         addr = buf;
607         port = strchr ( addr, ',' );
608         if ( ! port ) {
609                 DBGC ( tftp, "TFTP %p multicast missing port,mc\n", tftp );
610                 return -EINVAL_MC_NO_PORT;
611         }
612         *(port++) = '\0';
613         mc = strchr ( port, ',' );
614         if ( ! mc ) {
615                 DBGC ( tftp, "TFTP %p multicast missing mc\n", tftp );
616                 return -EINVAL_MC_NO_MC;
617         }
618         *(mc++) = '\0';
619
620         /* Parse parameters */
621         if ( strtoul ( mc, &mc_end, 0 ) == 0 )
622                 tftp->flags &= ~TFTP_FL_SEND_ACK;
623         if ( *mc_end ) {
624                 DBGC ( tftp, "TFTP %p multicast invalid mc %s\n", tftp, mc );
625                 return -EINVAL_MC_INVALID_MC;
626         }
627         DBGC ( tftp, "TFTP %p is%s the master client\n",
628                tftp, ( ( tftp->flags & TFTP_FL_SEND_ACK ) ? "" : " not" ) );
629         if ( *addr && *port ) {
630                 socket.sin.sin_family = AF_INET;
631                 if ( inet_aton ( addr, &socket.sin.sin_addr ) == 0 ) {
632                         DBGC ( tftp, "TFTP %p multicast invalid IP address "
633                                "%s\n", tftp, addr );
634                         return -EINVAL_MC_INVALID_IP;
635                 }
636                 DBGC ( tftp, "TFTP %p multicast IP address %s\n",
637                        tftp, inet_ntoa ( socket.sin.sin_addr ) );
638                 socket.sin.sin_port = htons ( strtoul ( port, &port_end, 0 ) );
639                 if ( *port_end ) {
640                         DBGC ( tftp, "TFTP %p multicast invalid port %s\n",
641                                tftp, port );
642                         return -EINVAL_MC_INVALID_PORT;
643                 }
644                 DBGC ( tftp, "TFTP %p multicast port %d\n",
645                        tftp, ntohs ( socket.sin.sin_port ) );
646                 if ( ( rc = tftp_reopen_mc ( tftp, &socket.sa ) ) != 0 )
647                         return rc;
648         }
649
650         return 0;
651 }
652
653 /** A TFTP option */
654 struct tftp_option {
655         /** Option name */
656         const char *name;
657         /** Option processor
658          *
659          * @v tftp      TFTP connection
660          * @v value     Option value
661          * @ret rc      Return status code
662          */
663         int ( * process ) ( struct tftp_request *tftp, const char *value );
664 };
665
666 /** Recognised TFTP options */
667 static struct tftp_option tftp_options[] = {
668         { "blksize", tftp_process_blksize },
669         { "tsize", tftp_process_tsize },
670         { "multicast", tftp_process_multicast },
671         { NULL, NULL }
672 };
673
674 /**
675  * Process TFTP option
676  *
677  * @v tftp              TFTP connection
678  * @v name              Option name
679  * @v value             Option value
680  * @ret rc              Return status code
681  */
682 static int tftp_process_option ( struct tftp_request *tftp,
683                                  const char *name, const char *value ) {
684         struct tftp_option *option;
685
686         for ( option = tftp_options ; option->name ; option++ ) {
687                 if ( strcasecmp ( name, option->name ) == 0 )
688                         return option->process ( tftp, value );
689         }
690
691         DBGC ( tftp, "TFTP %p received unknown option \"%s\" = \"%s\"\n",
692                tftp, name, value );
693
694         /* Unknown options should be silently ignored */
695         return 0;
696 }
697
698 /**
699  * Receive OACK
700  *
701  * @v tftp              TFTP connection
702  * @v buf               Temporary data buffer
703  * @v len               Length of temporary data buffer
704  * @ret rc              Return status code
705  */
706 static int tftp_rx_oack ( struct tftp_request *tftp, void *buf, size_t len ) {
707         struct tftp_oack *oack = buf;
708         char *end = buf + len;
709         char *name;
710         char *value;
711         char *next;
712         int rc = 0;
713
714         /* Sanity check */
715         if ( len < sizeof ( *oack ) ) {
716                 DBGC ( tftp, "TFTP %p received underlength OACK packet "
717                        "length %zd\n", tftp, len );
718                 rc = -EINVAL;
719                 goto done;
720         }
721
722         /* Process each option in turn */
723         for ( name = oack->data ; name < end ; name = next ) {
724
725                 /* Parse option name and value
726                  *
727                  * We treat parsing errors as non-fatal, because there
728                  * exists at least one TFTP server (IBM Tivoli PXE
729                  * Server 5.1.0.3) that has been observed to send
730                  * malformed OACKs containing trailing garbage bytes.
731                  */
732                 value = ( name + strnlen ( name, ( end - name ) ) + 1 );
733                 if ( value > end ) {
734                         DBGC ( tftp, "TFTP %p received OACK with malformed "
735                                "option name:\n", tftp );
736                         DBGC_HD ( tftp, oack, len );
737                         break;
738                 }
739                 if ( value == end ) {
740                         DBGC ( tftp, "TFTP %p received OACK missing value "
741                                "for option \"%s\"\n", tftp, name );
742                         DBGC_HD ( tftp, oack, len );
743                         break;
744                 }
745                 next = ( value + strnlen ( value, ( end - value ) ) + 1 );
746                 if ( next > end ) {
747                         DBGC ( tftp, "TFTP %p received OACK with malformed "
748                                "value for option \"%s\":\n", tftp, name );
749                         DBGC_HD ( tftp, oack, len );
750                         break;
751                 }
752
753                 /* Process option */
754                 if ( ( rc = tftp_process_option ( tftp, name, value ) ) != 0 )
755                         goto done;
756         }
757
758         /* Process tsize information, if available */
759         if ( tftp->tsize ) {
760                 if ( ( rc = tftp_presize ( tftp, tftp->tsize ) ) != 0 )
761                         goto done;
762         }
763
764         /* Request next data block */
765         tftp_send_packet ( tftp );
766
767  done:
768         if ( rc )
769                 tftp_done ( tftp, rc );
770         return rc;
771 }
772
773 /**
774  * Receive DATA
775  *
776  * @v tftp              TFTP connection
777  * @v iobuf             I/O buffer
778  * @ret rc              Return status code
779  *
780  * Takes ownership of I/O buffer.
781  */
782 static int tftp_rx_data ( struct tftp_request *tftp,
783                           struct io_buffer *iobuf ) {
784         struct tftp_data *data = iobuf->data;
785         struct xfer_metadata meta;
786         unsigned int block;
787         off_t offset;
788         size_t data_len;
789         int rc;
790
791         /* Sanity check */
792         if ( iob_len ( iobuf ) < sizeof ( *data ) ) {
793                 DBGC ( tftp, "TFTP %p received underlength DATA packet "
794                        "length %zd\n", tftp, iob_len ( iobuf ) );
795                 rc = -EINVAL;
796                 goto done;
797         }
798
799         /* Calculate block number */
800         block = ( ( bitmap_first_gap ( &tftp->bitmap ) + 1 ) & ~0xffff );
801         if ( data->block == 0 && block == 0 ) {
802                 DBGC ( tftp, "TFTP %p received data block 0\n", tftp );
803                 rc = -EINVAL;
804                 goto done;
805         }
806         block += ( ntohs ( data->block ) - 1 );
807
808         /* Extract data */
809         offset = ( block * tftp->blksize );
810         iob_pull ( iobuf, sizeof ( *data ) );
811         data_len = iob_len ( iobuf );
812         if ( data_len > tftp->blksize ) {
813                 DBGC ( tftp, "TFTP %p received overlength DATA packet "
814                        "length %zd\n", tftp, data_len );
815                 rc = -EINVAL;
816                 goto done;
817         }
818
819         /* Deliver data */
820         memset ( &meta, 0, sizeof ( meta ) );
821         meta.flags = XFER_FL_ABS_OFFSET;
822         meta.offset = offset;
823         if ( ( rc = xfer_deliver ( &tftp->xfer, iob_disown ( iobuf ),
824                                    &meta ) ) != 0 ) {
825                 DBGC ( tftp, "TFTP %p could not deliver data: %s\n",
826                        tftp, strerror ( rc ) );
827                 goto done;
828         }
829
830         /* Ensure block bitmap is ready */
831         if ( ( rc = tftp_presize ( tftp, ( offset + data_len ) ) ) != 0 )
832                 goto done;
833
834         /* Mark block as received */
835         bitmap_set ( &tftp->bitmap, block );
836
837         /* Acknowledge block */
838         tftp_send_packet ( tftp );
839
840         /* If all blocks have been received, finish. */
841         if ( bitmap_full ( &tftp->bitmap ) )
842                 tftp_done ( tftp, 0 );
843
844  done:
845         free_iob ( iobuf );
846         if ( rc )
847                 tftp_done ( tftp, rc );
848         return rc;
849 }
850
851 /**
852  * Convert TFTP error code to return status code
853  *
854  * @v errcode           TFTP error code
855  * @ret rc              Return status code
856  */
857 static int tftp_errcode_to_rc ( unsigned int errcode ) {
858         switch ( errcode ) {
859         case TFTP_ERR_FILE_NOT_FOUND:   return -ENOENT;
860         case TFTP_ERR_ACCESS_DENIED:    return -EACCES;
861         case TFTP_ERR_ILLEGAL_OP:       return -ENOTTY;
862         default:                        return -ENOTSUP;
863         }
864 }
865
866 /**
867  * Receive ERROR
868  *
869  * @v tftp              TFTP connection
870  * @v buf               Temporary data buffer
871  * @v len               Length of temporary data buffer
872  * @ret rc              Return status code
873  */
874 static int tftp_rx_error ( struct tftp_request *tftp, void *buf, size_t len ) {
875         struct tftp_error *error = buf;
876         int rc;
877
878         /* Sanity check */
879         if ( len < sizeof ( *error ) ) {
880                 DBGC ( tftp, "TFTP %p received underlength ERROR packet "
881                        "length %zd\n", tftp, len );
882                 return -EINVAL;
883         }
884
885         DBGC ( tftp, "TFTP %p received ERROR packet with code %d, message "
886                "\"%s\"\n", tftp, ntohs ( error->errcode ), error->errmsg );
887         
888         /* Determine final operation result */
889         rc = tftp_errcode_to_rc ( ntohs ( error->errcode ) );
890
891         /* Close TFTP request */
892         tftp_done ( tftp, rc );
893
894         return 0;
895 }
896
897 /**
898  * Receive new data
899  *
900  * @v tftp              TFTP connection
901  * @v iobuf             I/O buffer
902  * @v meta              Transfer metadata
903  * @ret rc              Return status code
904  */
905 static int tftp_rx ( struct tftp_request *tftp,
906                      struct io_buffer *iobuf,
907                      struct xfer_metadata *meta ) {
908         struct sockaddr_tcpip *st_src;
909         struct tftp_common *common = iobuf->data;
910         size_t len = iob_len ( iobuf );
911         int rc = -EINVAL;
912         
913         /* Sanity checks */
914         if ( len < sizeof ( *common ) ) {
915                 DBGC ( tftp, "TFTP %p received underlength packet length "
916                        "%zd\n", tftp, len );
917                 goto done;
918         }
919         if ( ! meta->src ) {
920                 DBGC ( tftp, "TFTP %p received packet without source port\n",
921                        tftp );
922                 goto done;
923         }
924
925         /* Filter by TID.  Set TID on first response received */
926         st_src = ( struct sockaddr_tcpip * ) meta->src;
927         if ( ! tftp->peer.st_family ) {
928                 memcpy ( &tftp->peer, st_src, sizeof ( tftp->peer ) );
929                 DBGC ( tftp, "TFTP %p using remote port %d\n", tftp,
930                        ntohs ( tftp->peer.st_port ) );
931         } else if ( memcmp ( &tftp->peer, st_src,
932                              sizeof ( tftp->peer ) ) != 0 ) {
933                 DBGC ( tftp, "TFTP %p received packet from wrong source (got "
934                        "%d, wanted %d)\n", tftp, ntohs ( st_src->st_port ),
935                        ntohs ( tftp->peer.st_port ) );
936                 goto done;
937         }
938
939         switch ( common->opcode ) {
940         case htons ( TFTP_OACK ):
941                 rc = tftp_rx_oack ( tftp, iobuf->data, len );
942                 break;
943         case htons ( TFTP_DATA ):
944                 rc = tftp_rx_data ( tftp, iob_disown ( iobuf ) );
945                 break;
946         case htons ( TFTP_ERROR ):
947                 rc = tftp_rx_error ( tftp, iobuf->data, len );
948                 break;
949         default:
950                 DBGC ( tftp, "TFTP %p received strange packet type %d\n",
951                        tftp, ntohs ( common->opcode ) );
952                 break;
953         };
954
955  done:
956         free_iob ( iobuf );
957         return rc;
958 }
959
960 /**
961  * Receive new data via socket
962  *
963  * @v tftp              TFTP connection
964  * @v iobuf             I/O buffer
965  * @v meta              Transfer metadata
966  * @ret rc              Return status code
967  */
968 static int tftp_socket_deliver ( struct tftp_request *tftp,
969                                  struct io_buffer *iobuf,
970                                  struct xfer_metadata *meta ) {
971
972         /* Enable sending ACKs when we receive a unicast packet.  This
973          * covers three cases:
974          *
975          * 1. Standard TFTP; we should always send ACKs, and will
976          *    always receive a unicast packet before we need to send the
977          *    first ACK.
978          *
979          * 2. RFC2090 multicast TFTP; the only unicast packets we will
980          *    receive are the OACKs; enable sending ACKs here (before
981          *    processing the OACK) and disable it when processing the
982          *    multicast option if we are not the master client.
983          *
984          * 3. MTFTP; receiving a unicast datagram indicates that we
985          *    are the "master client" and should send ACKs.
986          */
987         tftp->flags |= TFTP_FL_SEND_ACK;
988
989         return tftp_rx ( tftp, iobuf, meta );
990 }
991
992 /** TFTP socket operations */
993 static struct interface_operation tftp_socket_operations[] = {
994         INTF_OP ( xfer_deliver, struct tftp_request *, tftp_socket_deliver ),
995 };
996
997 /** TFTP socket interface descriptor */
998 static struct interface_descriptor tftp_socket_desc =
999         INTF_DESC ( struct tftp_request, socket, tftp_socket_operations );
1000
1001 /** TFTP multicast socket operations */
1002 static struct interface_operation tftp_mc_socket_operations[] = {
1003         INTF_OP ( xfer_deliver, struct tftp_request *, tftp_rx ),
1004 };
1005
1006 /** TFTP multicast socket interface descriptor */
1007 static struct interface_descriptor tftp_mc_socket_desc =
1008         INTF_DESC ( struct tftp_request, mc_socket, tftp_mc_socket_operations );
1009
1010 /**
1011  * Check flow control window
1012  *
1013  * @v tftp              TFTP connection
1014  * @ret len             Length of window
1015  */
1016 static size_t tftp_xfer_window ( struct tftp_request *tftp ) {
1017
1018         /* We abuse this data-xfer method to convey the blocksize to
1019          * the caller.  This really should be done using some kind of
1020          * stat() method, but we don't yet have the facility to do
1021          * that.
1022          */
1023         return tftp->blksize;
1024 }
1025
1026 /**
1027  * Terminate download
1028  *
1029  * @v tftp              TFTP connection
1030  * @v rc                Reason for close
1031  */
1032 static void tftp_close ( struct tftp_request *tftp, int rc ) {
1033
1034         /* Abort download */
1035         tftp_send_error ( tftp, 0, "TFTP Aborted" );
1036
1037         /* Close TFTP request */
1038         tftp_done ( tftp, rc );
1039 }
1040
1041 /** TFTP data transfer interface operations */
1042 static struct interface_operation tftp_xfer_operations[] = {
1043         INTF_OP ( xfer_window, struct tftp_request *, tftp_xfer_window ),
1044         INTF_OP ( intf_close, struct tftp_request *, tftp_close ),
1045 };
1046
1047 /** TFTP data transfer interface descriptor */
1048 static struct interface_descriptor tftp_xfer_desc =
1049         INTF_DESC ( struct tftp_request, xfer, tftp_xfer_operations );
1050
1051 /**
1052  * Initiate TFTP/TFTM/MTFTP download
1053  *
1054  * @v xfer              Data transfer interface
1055  * @v uri               Uniform Resource Identifier
1056  * @ret rc              Return status code
1057  */
1058 static int tftp_core_open ( struct interface *xfer, struct uri *uri,
1059                             unsigned int default_port,
1060                             struct sockaddr *multicast,
1061                             unsigned int flags ) {
1062         struct tftp_request *tftp;
1063         int rc;
1064
1065         /* Sanity checks */
1066         if ( ! uri->host )
1067                 return -EINVAL;
1068         if ( ! uri->path )
1069                 return -EINVAL;
1070
1071         /* Allocate and populate TFTP structure */
1072         tftp = zalloc ( sizeof ( *tftp ) );
1073         if ( ! tftp )
1074                 return -ENOMEM;
1075         ref_init ( &tftp->refcnt, tftp_free );
1076         intf_init ( &tftp->xfer, &tftp_xfer_desc, &tftp->refcnt );
1077         intf_init ( &tftp->socket, &tftp_socket_desc, &tftp->refcnt );
1078         intf_init ( &tftp->mc_socket, &tftp_mc_socket_desc, &tftp->refcnt );
1079         timer_init ( &tftp->timer, tftp_timer_expired, &tftp->refcnt );
1080         tftp->uri = uri_get ( uri );
1081         tftp->blksize = TFTP_DEFAULT_BLKSIZE;
1082         tftp->flags = flags;
1083
1084         /* Open socket */
1085         tftp->port = uri_port ( tftp->uri, default_port );
1086         if ( ( rc = tftp_reopen ( tftp ) ) != 0 )
1087                 goto err;
1088
1089         /* Open multicast socket */
1090         if ( multicast ) {
1091                 if ( ( rc = tftp_reopen_mc ( tftp, multicast ) ) != 0 )
1092                         goto err;
1093         }
1094
1095         /* Start timer to initiate RRQ */
1096         start_timer_nodelay ( &tftp->timer );
1097
1098         /* Attach to parent interface, mortalise self, and return */
1099         intf_plug_plug ( &tftp->xfer, xfer );
1100         ref_put ( &tftp->refcnt );
1101         return 0;
1102
1103  err:
1104         DBGC ( tftp, "TFTP %p could not create request: %s\n",
1105                tftp, strerror ( rc ) );
1106         tftp_done ( tftp, rc );
1107         ref_put ( &tftp->refcnt );
1108         return rc;
1109 }
1110
1111 /**
1112  * Initiate TFTP download
1113  *
1114  * @v xfer              Data transfer interface
1115  * @v uri               Uniform Resource Identifier
1116  * @ret rc              Return status code
1117  */
1118 static int tftp_open ( struct interface *xfer, struct uri *uri ) {
1119         return tftp_core_open ( xfer, uri, TFTP_PORT, NULL,
1120                                 TFTP_FL_RRQ_SIZES );
1121
1122 }
1123
1124 /** TFTP URI opener */
1125 struct uri_opener tftp_uri_opener __uri_opener = {
1126         .scheme = "tftp",
1127         .open   = tftp_open,
1128 };
1129
1130 /**
1131  * Initiate TFTM download
1132  *
1133  * @v xfer              Data transfer interface
1134  * @v uri               Uniform Resource Identifier
1135  * @ret rc              Return status code
1136  */
1137 static int tftm_open ( struct interface *xfer, struct uri *uri ) {
1138         return tftp_core_open ( xfer, uri, TFTP_PORT, NULL,
1139                                 ( TFTP_FL_RRQ_SIZES |
1140                                   TFTP_FL_RRQ_MULTICAST ) );
1141
1142 }
1143
1144 /** TFTM URI opener */
1145 struct uri_opener tftm_uri_opener __uri_opener = {
1146         .scheme = "tftm",
1147         .open   = tftm_open,
1148 };
1149
1150 /**
1151  * Initiate MTFTP download
1152  *
1153  * @v xfer              Data transfer interface
1154  * @v uri               Uniform Resource Identifier
1155  * @ret rc              Return status code
1156  */
1157 static int mtftp_open ( struct interface *xfer, struct uri *uri ) {
1158         return tftp_core_open ( xfer, uri, MTFTP_PORT,
1159                                 ( struct sockaddr * ) &tftp_mtftp_socket,
1160                                 TFTP_FL_MTFTP_RECOVERY );
1161 }
1162
1163 /** MTFTP URI opener */
1164 struct uri_opener mtftp_uri_opener __uri_opener = {
1165         .scheme = "mtftp",
1166         .open   = mtftp_open,
1167 };
1168
1169 /******************************************************************************
1170  *
1171  * Settings
1172  *
1173  ******************************************************************************
1174  */
1175
1176 /**
1177  * Apply TFTP configuration settings
1178  *
1179  * @ret rc              Return status code
1180  */
1181 static int tftp_apply_settings ( void ) {
1182         static struct in_addr tftp_server = { 0 };
1183         struct in_addr last_tftp_server;
1184         char uri_string[32];
1185         struct uri *uri;
1186
1187         /* Retrieve TFTP server setting */
1188         last_tftp_server = tftp_server;
1189         fetch_ipv4_setting ( NULL, &next_server_setting, &tftp_server );
1190
1191         /* If TFTP server setting has changed, set the current working
1192          * URI to match.  Do it only when the TFTP server has changed
1193          * to try to minimise surprises to the user, who probably
1194          * won't expect the CWURI to change just because they updated
1195          * an unrelated setting and triggered all the settings
1196          * applicators.
1197          */
1198         if ( tftp_server.s_addr != last_tftp_server.s_addr ) {
1199                 if ( tftp_server.s_addr ) {
1200                         snprintf ( uri_string, sizeof ( uri_string ),
1201                                    "tftp://%s/", inet_ntoa ( tftp_server ) );
1202                         uri = parse_uri ( uri_string );
1203                         if ( ! uri )
1204                                 return -ENOMEM;
1205                 } else {
1206                         uri = NULL;
1207                 }
1208                 churi ( uri );
1209                 uri_put ( uri );
1210         }
1211
1212         return 0;
1213 }
1214
1215 /** TFTP settings applicator */
1216 struct settings_applicator tftp_settings_applicator __settings_applicator = {
1217         .apply = tftp_apply_settings,
1218 };