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