These changes are the raw update to qemu-2.6.
[kvmfornfv.git] / qemu / roms / ipxe / src / net / tcp / httpcore.c
1 /*
2  * Copyright (C) 2015 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 /**
27  * @file
28  *
29  * Hyper Text Transfer Protocol (HTTP) core functionality
30  *
31  */
32
33 #include <stdint.h>
34 #include <stdlib.h>
35 #include <stdio.h>
36 #include <string.h>
37 #include <strings.h>
38 #include <byteswap.h>
39 #include <errno.h>
40 #include <ctype.h>
41 #include <assert.h>
42 #include <ipxe/uri.h>
43 #include <ipxe/refcnt.h>
44 #include <ipxe/iobuf.h>
45 #include <ipxe/xfer.h>
46 #include <ipxe/open.h>
47 #include <ipxe/process.h>
48 #include <ipxe/retry.h>
49 #include <ipxe/timer.h>
50 #include <ipxe/linebuf.h>
51 #include <ipxe/xferbuf.h>
52 #include <ipxe/blockdev.h>
53 #include <ipxe/acpi.h>
54 #include <ipxe/version.h>
55 #include <ipxe/params.h>
56 #include <ipxe/profile.h>
57 #include <ipxe/vsprintf.h>
58 #include <ipxe/http.h>
59
60 /* Disambiguate the various error causes */
61 #define EACCES_401 __einfo_error ( EINFO_EACCES_401 )
62 #define EINFO_EACCES_401 \
63         __einfo_uniqify ( EINFO_EACCES, 0x01, "HTTP 401 Unauthorized" )
64 #define EINVAL_STATUS __einfo_error ( EINFO_EINVAL_STATUS )
65 #define EINFO_EINVAL_STATUS \
66         __einfo_uniqify ( EINFO_EINVAL, 0x01, "Invalid status line" )
67 #define EINVAL_HEADER __einfo_error ( EINFO_EINVAL_HEADER )
68 #define EINFO_EINVAL_HEADER \
69         __einfo_uniqify ( EINFO_EINVAL, 0x02, "Invalid header" )
70 #define EINVAL_CONTENT_LENGTH __einfo_error ( EINFO_EINVAL_CONTENT_LENGTH )
71 #define EINFO_EINVAL_CONTENT_LENGTH \
72         __einfo_uniqify ( EINFO_EINVAL, 0x03, "Invalid content length" )
73 #define EINVAL_CHUNK_LENGTH __einfo_error ( EINFO_EINVAL_CHUNK_LENGTH )
74 #define EINFO_EINVAL_CHUNK_LENGTH \
75         __einfo_uniqify ( EINFO_EINVAL, 0x04, "Invalid chunk length" )
76 #define EIO_OTHER __einfo_error ( EINFO_EIO_OTHER )
77 #define EINFO_EIO_OTHER \
78         __einfo_uniqify ( EINFO_EIO, 0x01, "Unrecognised HTTP response code" )
79 #define EIO_CONTENT_LENGTH __einfo_error ( EINFO_EIO_CONTENT_LENGTH )
80 #define EINFO_EIO_CONTENT_LENGTH \
81         __einfo_uniqify ( EINFO_EIO, 0x02, "Content length mismatch" )
82 #define EIO_4XX __einfo_error ( EINFO_EIO_4XX )
83 #define EINFO_EIO_4XX \
84         __einfo_uniqify ( EINFO_EIO, 0x04, "HTTP 4xx Client Error" )
85 #define EIO_5XX __einfo_error ( EINFO_EIO_5XX )
86 #define EINFO_EIO_5XX \
87         __einfo_uniqify ( EINFO_EIO, 0x05, "HTTP 5xx Server Error" )
88 #define ENOENT_404 __einfo_error ( EINFO_ENOENT_404 )
89 #define EINFO_ENOENT_404 \
90         __einfo_uniqify ( EINFO_ENOENT, 0x01, "HTTP 404 Not Found" )
91 #define ENOTSUP_CONNECTION __einfo_error ( EINFO_ENOTSUP_CONNECTION )
92 #define EINFO_ENOTSUP_CONNECTION \
93         __einfo_uniqify ( EINFO_ENOTSUP, 0x01, "Unsupported connection header" )
94 #define ENOTSUP_TRANSFER __einfo_error ( EINFO_ENOTSUP_TRANSFER )
95 #define EINFO_ENOTSUP_TRANSFER \
96         __einfo_uniqify ( EINFO_ENOTSUP, 0x02, "Unsupported transfer encoding" )
97 #define EPERM_403 __einfo_error ( EINFO_EPERM_403 )
98 #define EINFO_EPERM_403 \
99         __einfo_uniqify ( EINFO_EPERM, 0x01, "HTTP 403 Forbidden" )
100 #define EPROTO_UNSOLICITED __einfo_error ( EINFO_EPROTO_UNSOLICITED )
101 #define EINFO_EPROTO_UNSOLICITED \
102         __einfo_uniqify ( EINFO_EPROTO, 0x01, "Unsolicited data" )
103
104 /** Retry delay used when we cannot understand the Retry-After header */
105 #define HTTP_RETRY_SECONDS 5
106
107 /** Receive profiler */
108 static struct profiler http_rx_profiler __profiler = { .name = "http.rx" };
109
110 /** Data transfer profiler */
111 static struct profiler http_xfer_profiler __profiler = { .name = "http.xfer" };
112
113 static struct http_state http_request;
114 static struct http_state http_headers;
115 static struct http_state http_trailers;
116 static struct http_transfer_encoding http_transfer_identity;
117
118 /******************************************************************************
119  *
120  * Methods
121  *
122  ******************************************************************************
123  */
124
125 /** HTTP HEAD method */
126 struct http_method http_head = {
127         .name = "HEAD",
128 };
129
130 /** HTTP GET method */
131 struct http_method http_get = {
132         .name = "GET",
133 };
134
135 /** HTTP POST method */
136 struct http_method http_post = {
137         .name = "POST",
138 };
139
140 /******************************************************************************
141  *
142  * Utility functions
143  *
144  ******************************************************************************
145  */
146
147 /**
148  * Handle received HTTP line-buffered data
149  *
150  * @v http              HTTP transaction
151  * @v iobuf             I/O buffer
152  * @v linebuf           Line buffer
153  * @ret rc              Return status code
154  */
155 static int http_rx_linebuf ( struct http_transaction *http,
156                              struct io_buffer *iobuf,
157                              struct line_buffer *linebuf ) {
158         int consumed;
159         int rc;
160
161         /* Buffer received line */
162         consumed = line_buffer ( linebuf, iobuf->data, iob_len ( iobuf ) );
163         if ( consumed < 0 ) {
164                 rc = consumed;
165                 DBGC ( http, "HTTP %p could not buffer line: %s\n",
166                        http, strerror ( rc ) );
167                 return rc;
168         }
169
170         /* Consume line */
171         iob_pull ( iobuf, consumed );
172
173         return 0;
174 }
175
176 /**
177  * Get HTTP response token
178  *
179  * @v line              Line position
180  * @v value             Token value to fill in (if any)
181  * @ret token           Token, or NULL
182  */
183 char * http_token ( char **line, char **value ) {
184         char *token;
185         char quote = '\0';
186         char c;
187
188         /* Avoid returning uninitialised data */
189         if ( value )
190                 *value = NULL;
191
192         /* Skip any initial whitespace */
193         while ( isspace ( **line ) )
194                 (*line)++;
195
196         /* Check for end of line and record token position */
197         if ( ! **line )
198                 return NULL;
199         token = *line;
200
201         /* Scan for end of token */
202         while ( ( c = **line ) ) {
203
204                 /* Terminate if we hit an unquoted whitespace */
205                 if ( isspace ( c ) && ! quote )
206                         break;
207
208                 /* Terminate if we hit a closing quote */
209                 if ( c == quote )
210                         break;
211
212                 /* Check for value separator */
213                 if ( value && ( ! *value ) && ( c == '=' ) ) {
214
215                         /* Terminate key portion of token */
216                         *((*line)++) = '\0';
217
218                         /* Check for quote character */
219                         c = **line;
220                         if ( ( c == '"' ) || ( c == '\'' ) ) {
221                                 quote = c;
222                                 (*line)++;
223                         }
224
225                         /* Record value portion of token */
226                         *value = *line;
227
228                 } else {
229
230                         /* Move to next character */
231                         (*line)++;
232                 }
233         }
234
235         /* Terminate token, if applicable */
236         if ( c )
237                 *((*line)++) = '\0';
238
239         return token;
240 }
241
242 /******************************************************************************
243  *
244  * Transactions
245  *
246  ******************************************************************************
247  */
248
249 /**
250  * Free HTTP transaction
251  *
252  * @v refcnt            Reference count
253  */
254 static void http_free ( struct refcnt *refcnt ) {
255         struct http_transaction *http =
256                 container_of ( refcnt, struct http_transaction, refcnt );
257
258         empty_line_buffer ( &http->response.headers );
259         empty_line_buffer ( &http->linebuf );
260         uri_put ( http->uri );
261         free ( http );
262 }
263
264 /**
265  * Close HTTP transaction
266  *
267  * @v http              HTTP transaction
268  * @v rc                Reason for close
269  */
270 static void http_close ( struct http_transaction *http, int rc ) {
271
272         /* Stop process */
273         process_del ( &http->process );
274
275         /* Stop timer */
276         stop_timer ( &http->timer );
277
278         /* Close all interfaces, allowing for the fact that the
279          * content-decoded and transfer-decoded interfaces may be
280          * connected to the same object.
281          */
282         intf_shutdown ( &http->conn, rc );
283         intf_nullify ( &http->transfer );
284         intf_shutdown ( &http->content, rc );
285         intf_shutdown ( &http->transfer, rc );
286         intf_shutdown ( &http->xfer, rc );
287 }
288
289 /**
290  * Close HTTP transaction with error (even if none specified)
291  *
292  * @v http              HTTP transaction
293  * @v rc                Reason for close
294  */
295 static void http_close_error ( struct http_transaction *http, int rc ) {
296
297         /* Treat any close as an error */
298         http_close ( http, ( rc ? rc : -EPIPE ) );
299 }
300
301 /**
302  * Reopen stale HTTP connection
303  *
304  * @v http              HTTP transaction
305  */
306 static void http_reopen ( struct http_transaction *http ) {
307         int rc;
308
309         /* Close existing connection */
310         intf_restart ( &http->conn, -ECANCELED );
311
312         /* Reopen connection */
313         if ( ( rc = http_connect ( &http->conn, http->uri ) ) != 0 ) {
314                 DBGC ( http, "HTTP %p could not reconnect: %s\n",
315                        http, strerror ( rc ) );
316                 goto err_connect;
317         }
318
319         /* Reset state */
320         http->state = &http_request;
321
322         /* Reschedule transmission process */
323         process_add ( &http->process );
324
325         return;
326
327  err_connect:
328         http_close ( http, rc );
329 }
330
331 /**
332  * Handle retry timer expiry
333  *
334  * @v timer             Retry timer
335  * @v over              Failure indicator
336  */
337 static void http_expired ( struct retry_timer *timer, int over __unused ) {
338         struct http_transaction *http =
339                 container_of ( timer, struct http_transaction, timer );
340
341         /* Reopen connection */
342         http_reopen ( http );
343 }
344
345 /**
346  * HTTP transmit process
347  *
348  * @v http              HTTP transaction
349  */
350 static void http_step ( struct http_transaction *http ) {
351         int rc;
352
353         /* Do nothing if we have nothing to transmit */
354         if ( ! http->state->tx )
355                 return;
356
357         /* Do nothing until connection is ready */
358         if ( ! xfer_window ( &http->conn ) )
359                 return;
360
361         /* Do nothing until data transfer interface is ready */
362         if ( ! xfer_window ( &http->xfer ) )
363                 return;
364
365         /* Transmit data */
366         if ( ( rc = http->state->tx ( http ) ) != 0 )
367                 goto err;
368
369         return;
370
371  err:
372         http_close ( http, rc );
373 }
374
375 /**
376  * Handle received HTTP data
377  *
378  * @v http              HTTP transaction
379  * @v iobuf             I/O buffer
380  * @v meta              Transfer metadata
381  * @ret rc              Return status code
382  *
383  * This function takes ownership of the I/O buffer.
384  */
385 static int http_conn_deliver ( struct http_transaction *http,
386                                struct io_buffer *iobuf,
387                                struct xfer_metadata *meta __unused ) {
388         int rc;
389
390         /* Handle received data */
391         profile_start ( &http_rx_profiler );
392         while ( iobuf && iob_len ( iobuf ) ) {
393
394                 /* Sanity check */
395                 if ( ( ! http->state ) || ( ! http->state->rx ) ) {
396                         DBGC ( http, "HTTP %p unexpected data\n", http );
397                         rc = -EPROTO_UNSOLICITED;
398                         goto err;
399                 }
400
401                 /* Receive (some) data */
402                 if ( ( rc = http->state->rx ( http, &iobuf ) ) != 0 )
403                         goto err;
404         }
405
406         /* Free I/O buffer, if applicable */
407         free_iob ( iobuf );
408
409         profile_stop ( &http_rx_profiler );
410         return 0;
411
412  err:
413         free_iob ( iobuf );
414         http_close ( http, rc );
415         return rc;
416 }
417
418 /**
419  * Handle server connection close
420  *
421  * @v http              HTTP transaction
422  * @v rc                Reason for close
423  */
424 static void http_conn_close ( struct http_transaction *http, int rc ) {
425
426         /* Sanity checks */
427         assert ( http->state != NULL );
428         assert ( http->state->close != NULL );
429
430         /* Restart server connection interface */
431         intf_restart ( &http->conn, rc );
432
433         /* Hand off to state-specific method */
434         http->state->close ( http, rc );
435 }
436
437 /**
438  * Handle received content-decoded data
439  *
440  * @v http              HTTP transaction
441  * @v iobuf             I/O buffer
442  * @v meta              Data transfer metadata
443  */
444 static int http_content_deliver ( struct http_transaction *http,
445                                   struct io_buffer *iobuf,
446                                   struct xfer_metadata *meta ) {
447         int rc;
448
449         /* Ignore content if this is anything other than a successful
450          * transfer.
451          */
452         if ( http->response.rc != 0 ) {
453                 free_iob ( iobuf );
454                 return 0;
455         }
456
457         /* Deliver to data transfer interface */
458         profile_start ( &http_xfer_profiler );
459         if ( ( rc = xfer_deliver ( &http->xfer, iob_disown ( iobuf ),
460                                    meta ) ) != 0 )
461                 return rc;
462         profile_stop ( &http_xfer_profiler );
463
464         return 0;
465 }
466
467 /**
468  * Get underlying data transfer buffer
469  *
470  * @v http              HTTP transaction
471  * @ret xferbuf         Data transfer buffer, or NULL on error
472  */
473 static struct xfer_buffer *
474 http_content_buffer ( struct http_transaction *http ) {
475
476         /* Deny access to the data transfer buffer if this is anything
477          * other than a successful transfer.
478          */
479         if ( http->response.rc != 0 )
480                 return NULL;
481
482         /* Hand off to data transfer interface */
483         return xfer_buffer ( &http->xfer );
484 }
485
486 /**
487  * Read from block device (when HTTP block device support is not present)
488  *
489  * @v http              HTTP transaction
490  * @v data              Data interface
491  * @v lba               Starting logical block address
492  * @v count             Number of logical blocks
493  * @v buffer            Data buffer
494  * @v len               Length of data buffer
495  * @ret rc              Return status code
496  */
497 __weak int http_block_read ( struct http_transaction *http __unused,
498                              struct interface *data __unused,
499                              uint64_t lba __unused, unsigned int count __unused,
500                              userptr_t buffer __unused, size_t len __unused ) {
501
502         return -ENOTSUP;
503 }
504
505 /**
506  * Read block device capacity (when HTTP block device support is not present)
507  *
508  * @v control           Control interface
509  * @v data              Data interface
510  * @ret rc              Return status code
511  */
512 __weak int http_block_read_capacity ( struct http_transaction *http __unused,
513                                       struct interface *data __unused ) {
514
515         return -ENOTSUP;
516 }
517
518 /**
519  * Describe device in ACPI table (when HTTP block device support is not present)
520  *
521  * @v http              HTTP transaction
522  * @v acpi              ACPI table
523  * @v len               Length of ACPI table
524  * @ret rc              Return status code
525  */
526 __weak int http_acpi_describe ( struct http_transaction *http __unused,
527                                 struct acpi_description_header *acpi __unused,
528                                 size_t len __unused ) {
529
530         return -ENOTSUP;
531 }
532
533 /** HTTP data transfer interface operations */
534 static struct interface_operation http_xfer_operations[] = {
535         INTF_OP ( block_read, struct http_transaction *, http_block_read ),
536         INTF_OP ( block_read_capacity, struct http_transaction *,
537                   http_block_read_capacity ),
538         INTF_OP ( acpi_describe, struct http_transaction *,
539                   http_acpi_describe ),
540         INTF_OP ( xfer_window_changed, struct http_transaction *, http_step ),
541         INTF_OP ( intf_close, struct http_transaction *, http_close ),
542 };
543
544 /** HTTP data transfer interface descriptor */
545 static struct interface_descriptor http_xfer_desc =
546         INTF_DESC_PASSTHRU ( struct http_transaction, xfer,
547                              http_xfer_operations, content );
548
549 /** HTTP content-decoded interface operations */
550 static struct interface_operation http_content_operations[] = {
551         INTF_OP ( xfer_deliver, struct http_transaction *,
552                   http_content_deliver ),
553         INTF_OP ( xfer_buffer, struct http_transaction *, http_content_buffer ),
554         INTF_OP ( intf_close, struct http_transaction *, http_close ),
555 };
556
557 /** HTTP content-decoded interface descriptor */
558 static struct interface_descriptor http_content_desc =
559         INTF_DESC_PASSTHRU ( struct http_transaction, content,
560                              http_content_operations, xfer );
561
562 /** HTTP transfer-decoded interface operations */
563 static struct interface_operation http_transfer_operations[] = {
564         INTF_OP ( intf_close, struct http_transaction *, http_close ),
565 };
566
567 /** HTTP transfer-decoded interface descriptor */
568 static struct interface_descriptor http_transfer_desc =
569         INTF_DESC_PASSTHRU ( struct http_transaction, transfer,
570                              http_transfer_operations, conn );
571
572 /** HTTP server connection interface operations */
573 static struct interface_operation http_conn_operations[] = {
574         INTF_OP ( xfer_deliver, struct http_transaction *, http_conn_deliver ),
575         INTF_OP ( xfer_window_changed, struct http_transaction *, http_step ),
576         INTF_OP ( pool_reopen, struct http_transaction *, http_reopen ),
577         INTF_OP ( intf_close, struct http_transaction *, http_conn_close ),
578 };
579
580 /** HTTP server connection interface descriptor */
581 static struct interface_descriptor http_conn_desc =
582         INTF_DESC_PASSTHRU ( struct http_transaction, conn,
583                              http_conn_operations, transfer );
584
585 /** HTTP process descriptor */
586 static struct process_descriptor http_process_desc =
587         PROC_DESC_ONCE ( struct http_transaction, process, http_step );
588
589 /**
590  * Open HTTP transaction
591  *
592  * @v xfer              Data transfer interface
593  * @v method            Request method
594  * @v uri               Request URI
595  * @v range             Content range (if any)
596  * @v content           Request content (if any)
597  * @ret rc              Return status code
598  */
599 int http_open ( struct interface *xfer, struct http_method *method,
600                 struct uri *uri, struct http_request_range *range,
601                 struct http_request_content *content ) {
602         struct http_transaction *http;
603         struct uri request_uri;
604         struct uri request_host;
605         size_t request_uri_len;
606         size_t request_host_len;
607         size_t content_len;
608         char *request_uri_string;
609         char *request_host_string;
610         void *content_data;
611         int rc;
612
613         /* Calculate request URI length */
614         memset ( &request_uri, 0, sizeof ( request_uri ) );
615         request_uri.path = ( uri->path ? uri->path : "/" );
616         request_uri.query = uri->query;
617         request_uri_len =
618                 ( format_uri ( &request_uri, NULL, 0 ) + 1 /* NUL */);
619
620         /* Calculate host name length */
621         memset ( &request_host, 0, sizeof ( request_host ) );
622         request_host.host = uri->host;
623         request_host.port = uri->port;
624         request_host_len =
625                 ( format_uri ( &request_host, NULL, 0 ) + 1 /* NUL */ );
626
627         /* Calculate request content length */
628         content_len = ( content ? content->len : 0 );
629
630         /* Allocate and initialise structure */
631         http = zalloc ( sizeof ( *http ) + request_uri_len + request_host_len +
632                         content_len );
633         if ( ! http ) {
634                 rc = -ENOMEM;
635                 goto err_alloc;
636         }
637         request_uri_string = ( ( ( void * ) http ) + sizeof ( *http ) );
638         request_host_string = ( request_uri_string + request_uri_len );
639         content_data = ( request_host_string + request_host_len );
640         format_uri ( &request_uri, request_uri_string, request_uri_len );
641         format_uri ( &request_host, request_host_string, request_host_len );
642         ref_init ( &http->refcnt, http_free );
643         intf_init ( &http->xfer, &http_xfer_desc, &http->refcnt );
644         intf_init ( &http->content, &http_content_desc, &http->refcnt );
645         intf_init ( &http->transfer, &http_transfer_desc, &http->refcnt );
646         intf_init ( &http->conn, &http_conn_desc, &http->refcnt );
647         intf_plug_plug ( &http->transfer, &http->content );
648         process_init ( &http->process, &http_process_desc, &http->refcnt );
649         timer_init ( &http->timer, http_expired, &http->refcnt );
650         http->uri = uri_get ( uri );
651         http->request.method = method;
652         http->request.uri = request_uri_string;
653         http->request.host = request_host_string;
654         if ( range ) {
655                 memcpy ( &http->request.range, range,
656                          sizeof ( http->request.range ) );
657         }
658         if ( content ) {
659                 http->request.content.type = content->type;
660                 http->request.content.data = content_data;
661                 http->request.content.len = content_len;
662                 memcpy ( content_data, content->data, content_len );
663         }
664         http->state = &http_request;
665         DBGC2 ( http, "HTTP %p %s://%s%s\n", http, http->uri->scheme,
666                 http->request.host, http->request.uri );
667
668         /* Open connection */
669         if ( ( rc = http_connect ( &http->conn, uri ) ) != 0 ) {
670                 DBGC ( http, "HTTP %p could not connect: %s\n",
671                        http, strerror ( rc ) );
672                 goto err_connect;
673         }
674
675         /* Attach to parent interface, mortalise self, and return */
676         intf_plug_plug ( &http->xfer, xfer );
677         ref_put ( &http->refcnt );
678         return 0;
679
680  err_connect:
681         http_close ( http, rc );
682         ref_put ( &http->refcnt );
683  err_alloc:
684         return rc;
685 }
686
687 /**
688  * Handle successful transfer completion
689  *
690  * @v http              HTTP transaction
691  * @ret rc              Return status code
692  */
693 static int http_transfer_complete ( struct http_transaction *http ) {
694         struct http_authentication *auth;
695         const char *location;
696         int rc;
697
698         /* Keep connection alive if applicable */
699         if ( http->response.flags & HTTP_RESPONSE_KEEPALIVE )
700                 pool_recycle ( &http->conn );
701
702         /* Restart server connection interface */
703         intf_restart ( &http->conn, 0 );
704
705         /* No more data is expected */
706         http->state = NULL;
707
708         /* If transaction is successful, then close the
709          * transfer-decoded interface.  The content encoding may
710          * choose whether or not to immediately terminate the
711          * transaction.
712          */
713         if ( http->response.rc == 0 ) {
714                 intf_shutdown ( &http->transfer, 0 );
715                 return 0;
716         }
717
718         /* Perform redirection, if applicable */
719         if ( ( location = http->response.location ) ) {
720                 DBGC2 ( http, "HTTP %p redirecting to \"%s\"\n",
721                         http, location );
722                 if ( ( rc = xfer_redirect ( &http->xfer, LOCATION_URI_STRING,
723                                             location ) ) != 0 ) {
724                         DBGC ( http, "HTTP %p could not redirect: %s\n",
725                                http, strerror ( rc ) );
726                         return rc;
727                 }
728                 http_close ( http, 0 );
729                 return 0;
730         }
731
732         /* Fail unless a retry is permitted */
733         if ( ! ( http->response.flags & HTTP_RESPONSE_RETRY ) )
734                 return http->response.rc;
735
736         /* Perform authentication, if applicable */
737         if ( ( auth = http->response.auth.auth ) ) {
738                 http->request.auth.auth = auth;
739                 DBGC2 ( http, "HTTP %p performing %s authentication\n",
740                         http, auth->name );
741                 if ( ( rc = auth->authenticate ( http ) ) != 0 ) {
742                         DBGC ( http, "HTTP %p could not authenticate: %s\n",
743                                http, strerror ( rc ) );
744                         return rc;
745                 }
746         }
747
748         /* Restart content decoding interfaces (which may be attached
749          * to the same object).
750          */
751         intf_nullify ( &http->content );
752         intf_nullify ( &http->transfer );
753         intf_restart ( &http->content, http->response.rc );
754         intf_restart ( &http->transfer, http->response.rc );
755         http->content.desc = &http_content_desc;
756         http->transfer.desc = &http_transfer_desc;
757         intf_plug_plug ( &http->transfer, &http->content );
758         http->len = 0;
759         assert ( http->remaining == 0 );
760
761         /* Start timer to initiate retry */
762         DBGC2 ( http, "HTTP %p retrying after %d seconds\n",
763                 http, http->response.retry_after );
764         start_timer_fixed ( &http->timer,
765                             ( http->response.retry_after * TICKS_PER_SEC ) );
766         return 0;
767 }
768
769 /******************************************************************************
770  *
771  * Requests
772  *
773  ******************************************************************************
774  */
775
776 /**
777  * Construct HTTP request headers
778  *
779  * @v http              HTTP transaction
780  * @v buf               Buffer
781  * @v len               Length of buffer
782  * @ret len             Length, or negative error
783  */
784 static int http_format_headers ( struct http_transaction *http, char *buf,
785                                  size_t len ) {
786         struct http_request_header *header;
787         size_t used;
788         size_t remaining;
789         char *line;
790         int value_len;
791         int rc;
792
793         /* Construct request line */
794         used = ssnprintf ( buf, len, "%s %s HTTP/1.1",
795                            http->request.method->name, http->request.uri );
796         if ( used < len )
797                 DBGC2 ( http, "HTTP %p TX %s\n", http, buf );
798         used += ssnprintf ( ( buf + used ), ( len - used ), "\r\n" );
799
800         /* Construct all headers */
801         for_each_table_entry ( header, HTTP_REQUEST_HEADERS ) {
802
803                 /* Determine header value length */
804                 value_len = header->format ( http, NULL, 0 );
805                 if ( value_len < 0 ) {
806                         rc = value_len;
807                         return rc;
808                 }
809
810                 /* Skip zero-length headers */
811                 if ( ! value_len )
812                         continue;
813
814                 /* Construct header */
815                 line = ( buf + used );
816                 used += ssnprintf ( ( buf + used ), ( len - used ), "%s: ",
817                                     header->name );
818                 remaining = ( ( used < len ) ? ( len - used ) : 0 );
819                 used += header->format ( http, ( buf + used ), remaining );
820                 if ( used < len )
821                         DBGC2 ( http, "HTTP %p TX %s\n", http, line );
822                 used += ssnprintf ( ( buf + used ), ( len - used ), "\r\n" );
823         }
824
825         /* Construct terminating newline */
826         used += ssnprintf ( ( buf + used ), ( len - used ), "\r\n" );
827
828         return used;
829 }
830
831 /**
832  * Construct HTTP "Host" header
833  *
834  * @v http              HTTP transaction
835  * @v buf               Buffer
836  * @v len               Length of buffer
837  * @ret len             Length of header value, or negative error
838  */
839 static int http_format_host ( struct http_transaction *http, char *buf,
840                               size_t len ) {
841
842         /* Construct host URI */
843         return snprintf ( buf, len, "%s", http->request.host );
844 }
845
846 /** HTTP "Host" header "*/
847 struct http_request_header http_request_host __http_request_header = {
848         .name = "Host",
849         .format = http_format_host,
850 };
851
852 /**
853  * Construct HTTP "User-Agent" header
854  *
855  * @v http              HTTP transaction
856  * @v buf               Buffer
857  * @v len               Length of buffer
858  * @ret len             Length of header value, or negative error
859  */
860 static int http_format_user_agent ( struct http_transaction *http __unused,
861                                     char *buf, size_t len ) {
862
863         /* Construct user agent */
864         return snprintf ( buf, len, "iPXE/%s", product_version );
865 }
866
867 /** HTTP "User-Agent" header */
868 struct http_request_header http_request_user_agent __http_request_header = {
869         .name = "User-Agent",
870         .format = http_format_user_agent,
871 };
872
873 /**
874  * Construct HTTP "Connection" header
875  *
876  * @v http              HTTP transaction
877  * @v buf               Buffer
878  * @v len               Length of buffer
879  * @ret len             Length of header value, or negative error
880  */
881 static int http_format_connection ( struct http_transaction *http __unused,
882                                     char *buf, size_t len ) {
883
884         /* Always request keep-alive */
885         return snprintf ( buf, len, "keep-alive" );
886 }
887
888 /** HTTP "Connection" header */
889 struct http_request_header http_request_connection __http_request_header = {
890         .name = "Connection",
891         .format = http_format_connection,
892 };
893
894 /**
895  * Construct HTTP "Range" header
896  *
897  * @v http              HTTP transaction
898  * @v buf               Buffer
899  * @v len               Length of buffer
900  * @ret len             Length of header value, or negative error
901  */
902 static int http_format_range ( struct http_transaction *http,
903                                char *buf, size_t len ) {
904
905         /* Construct range, if applicable */
906         if ( http->request.range.len ) {
907                 return snprintf ( buf, len, "bytes=%zd-%zd",
908                                   http->request.range.start,
909                                   ( http->request.range.start +
910                                     http->request.range.len - 1 ) );
911         } else {
912                 return 0;
913         }
914 }
915
916 /** HTTP "Range" header */
917 struct http_request_header http_request_range __http_request_header = {
918         .name = "Range",
919         .format = http_format_range,
920 };
921
922 /**
923  * Construct HTTP "Content-Type" header
924  *
925  * @v http              HTTP transaction
926  * @v buf               Buffer
927  * @v len               Length of buffer
928  * @ret len             Length of header value, or negative error
929  */
930 static int http_format_content_type ( struct http_transaction *http,
931                                       char *buf, size_t len ) {
932
933         /* Construct content type, if applicable */
934         if ( http->request.content.type ) {
935                 return snprintf ( buf, len, "%s", http->request.content.type );
936         } else {
937                 return 0;
938         }
939 }
940
941 /** HTTP "Content-Type" header */
942 struct http_request_header http_request_content_type __http_request_header = {
943         .name = "Content-Type",
944         .format = http_format_content_type,
945 };
946
947 /**
948  * Construct HTTP "Content-Length" header
949  *
950  * @v http              HTTP transaction
951  * @v buf               Buffer
952  * @v len               Length of buffer
953  * @ret len             Length of header value, or negative error
954  */
955 static int http_format_content_length ( struct http_transaction *http,
956                                         char *buf, size_t len ) {
957
958         /* Construct content length, if applicable */
959         if ( http->request.content.len ) {
960                 return snprintf ( buf, len, "%zd", http->request.content.len );
961         } else {
962                 return 0;
963         }
964 }
965
966 /** HTTP "Content-Length" header */
967 struct http_request_header http_request_content_length __http_request_header = {
968         .name = "Content-Length",
969         .format = http_format_content_length,
970 };
971
972 /**
973  * Construct HTTP "Accept-Encoding" header
974  *
975  * @v http              HTTP transaction
976  * @v buf               Buffer
977  * @v len               Length of buffer
978  * @ret len             Length of header value, or negative error
979  */
980 static int http_format_accept_encoding ( struct http_transaction *http,
981                                          char *buf, size_t len ) {
982         struct http_content_encoding *encoding;
983         const char *sep = "";
984         size_t used = 0;
985
986         /* Construct list of content encodings */
987         for_each_table_entry ( encoding, HTTP_CONTENT_ENCODINGS ) {
988                 if ( encoding->supported && ( ! encoding->supported ( http ) ) )
989                         continue;
990                 used += ssnprintf ( ( buf + used ), ( len - used ),
991                                     "%s%s", sep, encoding->name );
992                 sep = ", ";
993         }
994
995         return used;
996 }
997
998 /** HTTP "Accept-Encoding" header */
999 struct http_request_header http_request_accept_encoding __http_request_header ={
1000         .name = "Accept-Encoding",
1001         .format = http_format_accept_encoding,
1002 };
1003
1004 /**
1005  * Transmit request
1006  *
1007  * @v http              HTTP transaction
1008  * @ret rc              Return status code
1009  */
1010 static int http_tx_request ( struct http_transaction *http ) {
1011         struct io_buffer *iobuf;
1012         int len;
1013         int check_len;
1014         int rc;
1015
1016         /* Calculate request length */
1017         len = http_format_headers ( http, NULL, 0 );
1018         if ( len < 0 ) {
1019                 rc = len;
1020                 DBGC ( http, "HTTP %p could not construct request: %s\n",
1021                        http, strerror ( rc ) );
1022                 goto err_len;
1023         }
1024
1025         /* Allocate I/O buffer */
1026         iobuf = alloc_iob ( len + 1 /* NUL */ + http->request.content.len );
1027         if ( ! iobuf ) {
1028                 rc = -ENOMEM;
1029                 goto err_alloc;
1030         }
1031
1032         /* Construct request */
1033         check_len = http_format_headers ( http, iob_put ( iobuf, len ),
1034                                           ( len + 1 /* NUL */ ) );
1035         assert ( check_len == len );
1036         memcpy ( iob_put ( iobuf, http->request.content.len ),
1037                  http->request.content.data, http->request.content.len );
1038
1039         /* Deliver request */
1040         if ( ( rc = xfer_deliver_iob ( &http->conn,
1041                                        iob_disown ( iobuf ) ) ) != 0 ) {
1042                 DBGC ( http, "HTTP %p could not deliver request: %s\n",
1043                        http, strerror ( rc ) );
1044                 goto err_deliver;
1045         }
1046
1047         /* Clear any previous response */
1048         empty_line_buffer ( &http->response.headers );
1049         memset ( &http->response, 0, sizeof ( http->response ) );
1050
1051         /* Move to response headers state */
1052         http->state = &http_headers;
1053
1054         return 0;
1055
1056  err_deliver:
1057         free_iob ( iobuf );
1058  err_alloc:
1059  err_len:
1060         return rc;
1061 }
1062
1063 /** HTTP request state */
1064 static struct http_state http_request = {
1065         .tx = http_tx_request,
1066         .close = http_close_error,
1067 };
1068
1069 /******************************************************************************
1070  *
1071  * Response headers
1072  *
1073  ******************************************************************************
1074  */
1075
1076 /**
1077  * Parse HTTP status line
1078  *
1079  * @v http              HTTP transaction
1080  * @v line              Status line
1081  * @ret rc              Return status code
1082  */
1083 static int http_parse_status ( struct http_transaction *http, char *line ) {
1084         char *endp;
1085         char *version;
1086         char *vernum;
1087         char *status;
1088         int response_rc;
1089
1090         DBGC2 ( http, "HTTP %p RX %s\n", http, line );
1091
1092         /* Parse HTTP version */
1093         version = http_token ( &line, NULL );
1094         if ( ( ! version ) || ( strncmp ( version, "HTTP/", 5 ) != 0 ) ) {
1095                 DBGC ( http, "HTTP %p malformed version \"%s\"\n", http, line );
1096                 return -EINVAL_STATUS;
1097         }
1098
1099         /* Keepalive is enabled by default for anything newer than HTTP/1.0 */
1100         vernum = ( version + 5 /* "HTTP/" (presence already checked) */ );
1101         if ( vernum[0] == '0' ) {
1102                 /* HTTP/0.x : keepalive not enabled by default */
1103         } else if ( strncmp ( vernum, "1.0", 3 ) == 0 ) {
1104                 /* HTTP/1.0 : keepalive not enabled by default */
1105         } else {
1106                 /* HTTP/1.1 or newer: keepalive enabled by default */
1107                 http->response.flags |= HTTP_RESPONSE_KEEPALIVE;
1108         }
1109
1110         /* Parse status code */
1111         status = line;
1112         http->response.status = strtoul ( status, &endp, 10 );
1113         if ( *endp != ' ' ) {
1114                 DBGC ( http, "HTTP %p malformed status code \"%s\"\n",
1115                        http, status );
1116                 return -EINVAL_STATUS;
1117         }
1118
1119         /* Convert HTTP status code to iPXE return status code */
1120         if ( status[0] == '2' ) {
1121                 /* 2xx Success */
1122                 response_rc = 0;
1123         } else if ( status[0] == '3' ) {
1124                 /* 3xx Redirection */
1125                 response_rc = -EXDEV;
1126         } else if ( http->response.status == 401 ) {
1127                 /* 401 Unauthorized */
1128                 response_rc = -EACCES_401;
1129         } else if ( http->response.status == 403 ) {
1130                 /* 403 Forbidden */
1131                 response_rc = -EPERM_403;
1132         } else if ( http->response.status == 404 ) {
1133                 /* 404 Not Found */
1134                 response_rc = -ENOENT_404;
1135         } else if ( status[0] == '4' ) {
1136                 /* 4xx Client Error (not already specified) */
1137                 response_rc = -EIO_4XX;
1138         } else if ( status[0] == '5' ) {
1139                 /* 5xx Server Error */
1140                 response_rc = -EIO_5XX;
1141         } else {
1142                 /* Unrecognised */
1143                 response_rc = -EIO_OTHER;
1144         }
1145         http->response.rc = response_rc;
1146
1147         return 0;
1148 }
1149
1150 /**
1151  * Parse HTTP header
1152  *
1153  * @v http              HTTP transaction
1154  * @v line              Header line
1155  * @ret rc              Return status code
1156  */
1157 static int http_parse_header ( struct http_transaction *http, char *line ) {
1158         struct http_response_header *header;
1159         char *name = line;
1160         char *sep;
1161
1162         DBGC2 ( http, "HTTP %p RX %s\n", http, line );
1163
1164         /* Extract header name */
1165         sep = strstr ( line, ": " );
1166         if ( ! sep ) {
1167                 DBGC ( http, "HTTP %p malformed header \"%s\"\n", http, line );
1168                 return -EINVAL_HEADER;
1169         }
1170         *sep = '\0';
1171         line = ( sep + 2 /* ": " */ );
1172
1173         /* Process header, if recognised */
1174         for_each_table_entry ( header, HTTP_RESPONSE_HEADERS ) {
1175                 if ( strcasecmp ( name, header->name ) == 0 )
1176                         return header->parse ( http, line );
1177         }
1178
1179         /* Unrecognised headers should be ignored */
1180         return 0;
1181 }
1182
1183 /**
1184  * Parse HTTP response headers
1185  *
1186  * @v http              HTTP transaction
1187  * @ret rc              Return status code
1188  */
1189 static int http_parse_headers ( struct http_transaction *http ) {
1190         char *line;
1191         char *next;
1192         int rc;
1193
1194         /* Get status line */
1195         line = http->response.headers.data;
1196         assert ( line != NULL );
1197         next = ( line + strlen ( line ) + 1 /* NUL */ );
1198
1199         /* Parse status line */
1200         if ( ( rc = http_parse_status ( http, line ) ) != 0 )
1201                 return rc;
1202
1203         /* Process header lines */
1204         while ( 1 ) {
1205
1206                 /* Move to next line */
1207                 line = next;
1208                 next = ( line + strlen ( line ) + 1 /* NUL */ );
1209
1210                 /* Stop on terminating blank line */
1211                 if ( ! line[0] )
1212                         return 0;
1213
1214                 /* Process header line */
1215                 if ( ( rc = http_parse_header ( http, line ) ) != 0 )
1216                         return rc;
1217         }
1218 }
1219
1220 /**
1221  * Parse HTTP "Location" header
1222  *
1223  * @v http              HTTP transaction
1224  * @v line              Remaining header line
1225  * @ret rc              Return status code
1226  */
1227 static int http_parse_location ( struct http_transaction *http, char *line ) {
1228
1229         /* Store location */
1230         http->response.location = line;
1231         return 0;
1232 }
1233
1234 /** HTTP "Location" header */
1235 struct http_response_header http_response_location __http_response_header = {
1236         .name = "Location",
1237         .parse = http_parse_location,
1238 };
1239
1240 /**
1241  * Parse HTTP "Transfer-Encoding" header
1242  *
1243  * @v http              HTTP transaction
1244  * @v line              Remaining header line
1245  * @ret rc              Return status code
1246  */
1247 static int http_parse_transfer_encoding ( struct http_transaction *http,
1248                                           char *line ) {
1249         struct http_transfer_encoding *encoding;
1250
1251         /* Check for known transfer encodings */
1252         for_each_table_entry ( encoding, HTTP_TRANSFER_ENCODINGS ) {
1253                 if ( strcasecmp ( line, encoding->name ) == 0 ) {
1254                         http->response.transfer.encoding = encoding;
1255                         return 0;
1256                 }
1257         }
1258
1259         DBGC ( http, "HTTP %p unrecognised Transfer-Encoding \"%s\"\n",
1260                http, line );
1261         return -ENOTSUP_TRANSFER;
1262 }
1263
1264 /** HTTP "Transfer-Encoding" header */
1265 struct http_response_header
1266 http_response_transfer_encoding __http_response_header = {
1267         .name = "Transfer-Encoding",
1268         .parse = http_parse_transfer_encoding,
1269 };
1270
1271 /**
1272  * Parse HTTP "Connection" header
1273  *
1274  * @v http              HTTP transaction
1275  * @v line              Remaining header line
1276  * @ret rc              Return status code
1277  */
1278 static int http_parse_connection ( struct http_transaction *http, char *line ) {
1279
1280         /* Check for known connection intentions */
1281         if ( strcasecmp ( line, "keep-alive" ) == 0 ) {
1282                 http->response.flags |= HTTP_RESPONSE_KEEPALIVE;
1283                 return 0;
1284         }
1285         if ( strcasecmp ( line, "close" ) == 0 ) {
1286                 http->response.flags &= ~HTTP_RESPONSE_KEEPALIVE;
1287                 return 0;
1288         }
1289
1290         DBGC ( http, "HTTP %p unrecognised Connection \"%s\"\n", http, line );
1291         return -ENOTSUP_CONNECTION;
1292 }
1293
1294 /** HTTP "Connection" header */
1295 struct http_response_header http_response_connection __http_response_header = {
1296         .name = "Connection",
1297         .parse = http_parse_connection,
1298 };
1299
1300 /**
1301  * Parse HTTP "Content-Length" header
1302  *
1303  * @v http              HTTP transaction
1304  * @v line              Remaining header line
1305  * @ret rc              Return status code
1306  */
1307 static int http_parse_content_length ( struct http_transaction *http,
1308                                        char *line ) {
1309         char *endp;
1310
1311         /* Parse length */
1312         http->response.content.len = strtoul ( line, &endp, 10 );
1313         if ( *endp != '\0' ) {
1314                 DBGC ( http, "HTTP %p invalid Content-Length \"%s\"\n",
1315                        http, line );
1316                 return -EINVAL_CONTENT_LENGTH;
1317         }
1318
1319         /* Record that we have a content length (since it may be zero) */
1320         http->response.flags |= HTTP_RESPONSE_CONTENT_LEN;
1321
1322         return 0;
1323 }
1324
1325 /** HTTP "Content-Length" header */
1326 struct http_response_header
1327 http_response_content_length __http_response_header = {
1328         .name = "Content-Length",
1329         .parse = http_parse_content_length,
1330 };
1331
1332 /**
1333  * Parse HTTP "Content-Encoding" header
1334  *
1335  * @v http              HTTP transaction
1336  * @v line              Remaining header line
1337  * @ret rc              Return status code
1338  */
1339 static int http_parse_content_encoding ( struct http_transaction *http,
1340                                          char *line ) {
1341         struct http_content_encoding *encoding;
1342
1343         /* Check for known content encodings */
1344         for_each_table_entry ( encoding, HTTP_CONTENT_ENCODINGS ) {
1345                 if ( encoding->supported && ( ! encoding->supported ( http ) ) )
1346                         continue;
1347                 if ( strcasecmp ( line, encoding->name ) == 0 ) {
1348                         http->response.content.encoding = encoding;
1349                         return 0;
1350                 }
1351         }
1352
1353         /* Some servers (e.g. Apache) have a habit of specifying
1354          * unwarranted content encodings.  For example, if Apache
1355          * detects (via /etc/httpd/conf/magic) that a file's contents
1356          * are gzip-compressed, it will set "Content-Encoding: x-gzip"
1357          * regardless of the client's Accept-Encoding header.  The
1358          * only viable way to handle such servers is to treat unknown
1359          * content encodings as equivalent to "identity".
1360          */
1361         DBGC ( http, "HTTP %p unrecognised Content-Encoding \"%s\"\n",
1362                http, line );
1363         return 0;
1364 }
1365
1366 /** HTTP "Content-Encoding" header */
1367 struct http_response_header
1368 http_response_content_encoding __http_response_header = {
1369         .name = "Content-Encoding",
1370         .parse = http_parse_content_encoding,
1371 };
1372
1373 /**
1374  * Parse HTTP "Retry-After" header
1375  *
1376  * @v http              HTTP transaction
1377  * @v line              Remaining header line
1378  * @ret rc              Return status code
1379  */
1380 static int http_parse_retry_after ( struct http_transaction *http,
1381                                     char *line ) {
1382         char *endp;
1383
1384         /* Try to parse value as a simple number of seconds */
1385         http->response.retry_after = strtoul ( line, &endp, 10 );
1386         if ( *endp != '\0' ) {
1387                 /* For any value which is not a simple number of
1388                  * seconds (e.g. a full HTTP date), just retry after a
1389                  * fixed delay, since we don't have code able to parse
1390                  * full HTTP dates.
1391                  */
1392                 http->response.retry_after = HTTP_RETRY_SECONDS;
1393                 DBGC ( http, "HTTP %p cannot understand Retry-After \"%s\"; "
1394                        "using %d seconds\n", http, line, HTTP_RETRY_SECONDS );
1395         }
1396
1397         /* Allow HTTP request to be retried after specified delay */
1398         http->response.flags |= HTTP_RESPONSE_RETRY;
1399
1400         return 0;
1401 }
1402
1403 /** HTTP "Retry-After" header */
1404 struct http_response_header http_response_retry_after __http_response_header = {
1405         .name = "Retry-After",
1406         .parse = http_parse_retry_after,
1407 };
1408
1409 /**
1410  * Handle received HTTP headers
1411  *
1412  * @v http              HTTP transaction
1413  * @v iobuf             I/O buffer (may be claimed)
1414  * @ret rc              Return status code
1415  */
1416 static int http_rx_headers ( struct http_transaction *http,
1417                              struct io_buffer **iobuf ) {
1418         struct http_transfer_encoding *transfer;
1419         struct http_content_encoding *content;
1420         char *line;
1421         int rc;
1422
1423         /* Buffer header line */
1424         if ( ( rc = http_rx_linebuf ( http, *iobuf,
1425                                       &http->response.headers ) ) != 0 )
1426                 return rc;
1427
1428         /* Wait until we see the empty line marking end of headers */
1429         line = buffered_line ( &http->response.headers );
1430         if ( ( line == NULL ) || ( line[0] != '\0' ) )
1431                 return 0;
1432
1433         /* Process headers */
1434         if ( ( rc = http_parse_headers ( http ) ) != 0 )
1435                 return rc;
1436
1437         /* Initialise content encoding, if applicable */
1438         if ( ( content = http->response.content.encoding ) &&
1439              ( ( rc = content->init ( http ) ) != 0 ) ) {
1440                 DBGC ( http, "HTTP %p could not initialise %s content "
1441                        "encoding: %s\n", http, content->name, strerror ( rc ) );
1442                 return rc;
1443         }
1444
1445         /* Presize receive buffer, if we have a content length */
1446         if ( http->response.content.len ) {
1447                 xfer_seek ( &http->transfer, http->response.content.len );
1448                 xfer_seek ( &http->transfer, 0 );
1449         }
1450
1451         /* Complete transfer if this is a HEAD request */
1452         if ( http->request.method == &http_head ) {
1453                 if ( ( rc = http_transfer_complete ( http ) ) != 0 )
1454                         return rc;
1455                 return 0;
1456         }
1457
1458         /* Default to identity transfer encoding, if none specified */
1459         if ( ! http->response.transfer.encoding )
1460                 http->response.transfer.encoding = &http_transfer_identity;
1461
1462         /* Move to transfer encoding-specific data state */
1463         transfer = http->response.transfer.encoding;
1464         http->state = &transfer->state;
1465
1466         /* Initialise transfer encoding */
1467         if ( ( rc = transfer->init ( http ) ) != 0 ) {
1468                 DBGC ( http, "HTTP %p could not initialise %s transfer "
1469                        "encoding: %s\n", http, transfer->name, strerror ( rc ));
1470                 return rc;
1471         }
1472
1473         return 0;
1474 }
1475
1476 /** HTTP response headers state */
1477 static struct http_state http_headers = {
1478         .rx = http_rx_headers,
1479         .close = http_close_error,
1480 };
1481
1482 /******************************************************************************
1483  *
1484  * Identity transfer encoding
1485  *
1486  ******************************************************************************
1487  */
1488
1489 /**
1490  * Initialise transfer encoding
1491  *
1492  * @v http              HTTP transaction
1493  * @ret rc              Return status code
1494  */
1495 static int http_init_transfer_identity ( struct http_transaction *http ) {
1496         int rc;
1497
1498         /* Complete transfer immediately if we have a zero content length */
1499         if ( ( http->response.flags & HTTP_RESPONSE_CONTENT_LEN ) &&
1500              ( http->response.content.len == 0 ) &&
1501              ( ( rc = http_transfer_complete ( http ) ) != 0 ) )
1502                 return rc;
1503
1504         return 0;
1505 }
1506
1507 /**
1508  * Handle received data
1509  *
1510  * @v http              HTTP transaction
1511  * @v iobuf             I/O buffer (may be claimed)
1512  * @ret rc              Return status code
1513  */
1514 static int http_rx_transfer_identity ( struct http_transaction *http,
1515                                        struct io_buffer **iobuf ) {
1516         size_t len = iob_len ( *iobuf );
1517         int rc;
1518
1519         /* Update lengths */
1520         http->len += len;
1521
1522         /* Fail if this transfer would overrun the expected content
1523          * length (if any).
1524          */
1525         if ( ( http->response.flags & HTTP_RESPONSE_CONTENT_LEN ) &&
1526              ( http->len > http->response.content.len ) ) {
1527                 DBGC ( http, "HTTP %p content length overrun\n", http );
1528                 return -EIO_CONTENT_LENGTH;
1529         }
1530
1531         /* Hand off to content encoding */
1532         if ( ( rc = xfer_deliver_iob ( &http->transfer,
1533                                        iob_disown ( *iobuf ) ) ) != 0 )
1534                 return rc;
1535
1536         /* Complete transfer if we have received the expected content
1537          * length (if any).
1538          */
1539         if ( ( http->response.flags & HTTP_RESPONSE_CONTENT_LEN ) &&
1540              ( http->len == http->response.content.len ) &&
1541              ( ( rc = http_transfer_complete ( http ) ) != 0 ) )
1542                 return rc;
1543
1544         return 0;
1545 }
1546
1547 /**
1548  * Handle server connection close
1549  *
1550  * @v http              HTTP transaction
1551  * @v rc                Reason for close
1552  */
1553 static void http_close_transfer_identity ( struct http_transaction *http,
1554                                            int rc ) {
1555
1556         /* Fail if any error occurred */
1557         if ( rc != 0 )
1558                 goto err;
1559
1560         /* Fail if we have a content length (since we would have
1561          * already closed the connection if we had received the
1562          * correct content length).
1563          */
1564         if ( http->response.flags & HTTP_RESPONSE_CONTENT_LEN ) {
1565                 DBGC ( http, "HTTP %p content length underrun\n", http );
1566                 rc = EIO_CONTENT_LENGTH;
1567                 goto err;
1568         }
1569
1570         /* Indicate that transfer is complete */
1571         if ( ( rc = http_transfer_complete ( http ) ) != 0 )
1572                 goto err;
1573
1574         return;
1575
1576  err:
1577         http_close ( http, rc );
1578 }
1579
1580 /** Identity transfer encoding */
1581 static struct http_transfer_encoding http_transfer_identity = {
1582         .name = "identity",
1583         .init = http_init_transfer_identity,
1584         .state = {
1585                 .rx = http_rx_transfer_identity,
1586                 .close = http_close_transfer_identity,
1587         },
1588 };
1589
1590 /******************************************************************************
1591  *
1592  * Chunked transfer encoding
1593  *
1594  ******************************************************************************
1595  */
1596
1597 /**
1598  * Initialise transfer encoding
1599  *
1600  * @v http              HTTP transaction
1601  * @ret rc              Return status code
1602  */
1603 static int http_init_transfer_chunked ( struct http_transaction *http ) {
1604
1605         /* Sanity checks */
1606         assert ( http->remaining == 0 );
1607         assert ( http->linebuf.len == 0 );
1608
1609         return 0;
1610 }
1611
1612 /**
1613  * Handle received chunk length
1614  *
1615  * @v http              HTTP transaction
1616  * @v iobuf             I/O buffer (may be claimed)
1617  * @ret rc              Return status code
1618  */
1619 static int http_rx_chunk_len ( struct http_transaction *http,
1620                                struct io_buffer **iobuf ) {
1621         char *line;
1622         char *endp;
1623         size_t len;
1624         int rc;
1625
1626         /* Receive into temporary line buffer */
1627         if ( ( rc = http_rx_linebuf ( http, *iobuf, &http->linebuf ) ) != 0 )
1628                 return rc;
1629
1630         /* Wait until we receive a non-empty line */
1631         line = buffered_line ( &http->linebuf );
1632         if ( ( line == NULL ) || ( line[0] == '\0' ) )
1633                 return 0;
1634
1635         /* Parse chunk length */
1636         http->remaining = strtoul ( line, &endp, 16 );
1637         if ( *endp != '\0' ) {
1638                 DBGC ( http, "HTTP %p invalid chunk length \"%s\"\n",
1639                        http, line );
1640                 return -EINVAL_CHUNK_LENGTH;
1641         }
1642
1643         /* Empty line buffer */
1644         empty_line_buffer ( &http->linebuf );
1645
1646         /* Update expected length */
1647         len = ( http->len + http->remaining );
1648         xfer_seek ( &http->transfer, len );
1649         xfer_seek ( &http->transfer, http->len );
1650
1651         /* If chunk length is zero, then move to response trailers state */
1652         if ( ! http->remaining )
1653                 http->state = &http_trailers;
1654
1655         return 0;
1656 }
1657
1658 /**
1659  * Handle received chunk data
1660  *
1661  * @v http              HTTP transaction
1662  * @v iobuf             I/O buffer (may be claimed)
1663  * @ret rc              Return status code
1664  */
1665 static int http_rx_chunk_data ( struct http_transaction *http,
1666                                 struct io_buffer **iobuf ) {
1667         struct io_buffer *payload;
1668         uint8_t *crlf;
1669         size_t len;
1670         int rc;
1671
1672         /* In the common case of a final chunk in a packet which also
1673          * includes the terminating CRLF, strip the terminating CRLF
1674          * (which we would ignore anyway) and hence avoid
1675          * unnecessarily copying the data.
1676          */
1677         if ( iob_len ( *iobuf ) == ( http->remaining + 2 /* CRLF */ ) ) {
1678                 crlf = ( (*iobuf)->data + http->remaining );
1679                 if ( ( crlf[0] == '\r' ) && ( crlf[1] == '\n' ) )
1680                         iob_unput ( (*iobuf), 2 /* CRLF */ );
1681         }
1682         len = iob_len ( *iobuf );
1683
1684         /* Use whole/partial buffer as applicable */
1685         if ( len <= http->remaining ) {
1686
1687                 /* Whole buffer is to be consumed: decrease remaining
1688                  * length and use original I/O buffer as payload.
1689                  */
1690                 payload = iob_disown ( *iobuf );
1691                 http->len += len;
1692                 http->remaining -= len;
1693
1694         } else {
1695
1696                 /* Partial buffer is to be consumed: copy data to a
1697                  * temporary I/O buffer.
1698                  */
1699                 payload = alloc_iob ( http->remaining );
1700                 if ( ! payload ) {
1701                         rc = -ENOMEM;
1702                         goto err;
1703                 }
1704                 memcpy ( iob_put ( payload, http->remaining ), (*iobuf)->data,
1705                          http->remaining );
1706                 iob_pull ( *iobuf, http->remaining );
1707                 http->len += http->remaining;
1708                 http->remaining = 0;
1709         }
1710
1711         /* Hand off to content encoding */
1712         if ( ( rc = xfer_deliver_iob ( &http->transfer,
1713                                        iob_disown ( payload ) ) ) != 0 )
1714                 goto err;
1715
1716         return 0;
1717
1718  err:
1719         assert ( payload == NULL );
1720         return rc;
1721 }
1722
1723 /**
1724  * Handle received chunked data
1725  *
1726  * @v http              HTTP transaction
1727  * @v iobuf             I/O buffer (may be claimed)
1728  * @ret rc              Return status code
1729  */
1730 static int http_rx_transfer_chunked ( struct http_transaction *http,
1731                                       struct io_buffer **iobuf ) {
1732
1733         /* Handle as chunk length or chunk data as appropriate */
1734         if ( http->remaining ) {
1735                 return http_rx_chunk_data ( http, iobuf );
1736         } else {
1737                 return http_rx_chunk_len ( http, iobuf );
1738         }
1739 }
1740
1741 /** Chunked transfer encoding */
1742 struct http_transfer_encoding http_transfer_chunked __http_transfer_encoding = {
1743         .name = "chunked",
1744         .init = http_init_transfer_chunked,
1745         .state = {
1746                 .rx = http_rx_transfer_chunked,
1747                 .close = http_close_error,
1748         },
1749 };
1750
1751 /******************************************************************************
1752  *
1753  * Response trailers
1754  *
1755  ******************************************************************************
1756  */
1757
1758 /**
1759  * Handle received HTTP trailer
1760  *
1761  * @v http              HTTP transaction
1762  * @v iobuf             I/O buffer (may be claimed)
1763  * @ret rc              Return status code
1764  */
1765 static int http_rx_trailers ( struct http_transaction *http,
1766                               struct io_buffer **iobuf ) {
1767         char *line;
1768         int rc;
1769
1770         /* Buffer trailer line */
1771         if ( ( rc = http_rx_linebuf ( http, *iobuf, &http->linebuf ) ) != 0 )
1772                 return rc;
1773
1774         /* Wait until we see the empty line marking end of trailers */
1775         line = buffered_line ( &http->linebuf );
1776         if ( ( line == NULL ) || ( line[0] != '\0' ) )
1777                 return 0;
1778
1779         /* Empty line buffer */
1780         empty_line_buffer ( &http->linebuf );
1781
1782         /* Transfer is complete */
1783         if ( ( rc = http_transfer_complete ( http ) ) != 0 )
1784                 return rc;
1785
1786         return 0;
1787 }
1788
1789 /** HTTP response trailers state */
1790 static struct http_state http_trailers = {
1791         .rx = http_rx_trailers,
1792         .close = http_close_error,
1793 };
1794
1795 /******************************************************************************
1796  *
1797  * Simple URI openers
1798  *
1799  ******************************************************************************
1800  */
1801
1802 /**
1803  * Construct HTTP parameter list
1804  *
1805  * @v params            Parameter list
1806  * @v buf               Buffer to contain HTTP POST parameters
1807  * @v len               Length of buffer
1808  * @ret len             Length of parameter list (excluding terminating NUL)
1809  */
1810 static size_t http_params ( struct parameters *params, char *buf, size_t len ) {
1811         struct parameter *param;
1812         ssize_t remaining = len;
1813         size_t frag_len;
1814
1815         /* Add each parameter in the form "key=value", joined with "&" */
1816         len = 0;
1817         for_each_param ( param, params ) {
1818
1819                 /* Add the "&", if applicable */
1820                 if ( len ) {
1821                         if ( remaining > 0 )
1822                                 *buf = '&';
1823                         buf++;
1824                         len++;
1825                         remaining--;
1826                 }
1827
1828                 /* URI-encode the key */
1829                 frag_len = uri_encode ( param->key, 0, buf, remaining );
1830                 buf += frag_len;
1831                 len += frag_len;
1832                 remaining -= frag_len;
1833
1834                 /* Add the "=" */
1835                 if ( remaining > 0 )
1836                         *buf = '=';
1837                 buf++;
1838                 len++;
1839                 remaining--;
1840
1841                 /* URI-encode the value */
1842                 frag_len = uri_encode ( param->value, 0, buf, remaining );
1843                 buf += frag_len;
1844                 len += frag_len;
1845                 remaining -= frag_len;
1846         }
1847
1848         /* Ensure string is NUL-terminated even if no parameters are present */
1849         if ( remaining > 0 )
1850                 *buf = '\0';
1851
1852         return len;
1853 }
1854
1855 /**
1856  * Open HTTP transaction for simple GET URI
1857  *
1858  * @v xfer              Data transfer interface
1859  * @v uri               Request URI
1860  * @ret rc              Return status code
1861  */
1862 static int http_open_get_uri ( struct interface *xfer, struct uri *uri ) {
1863
1864         return http_open ( xfer, &http_get, uri, NULL, NULL );
1865 }
1866
1867 /**
1868  * Open HTTP transaction for simple POST URI
1869  *
1870  * @v xfer              Data transfer interface
1871  * @v uri               Request URI
1872  * @ret rc              Return status code
1873  */
1874 static int http_open_post_uri ( struct interface *xfer, struct uri *uri ) {
1875         struct parameters *params = uri->params;
1876         struct http_request_content content;
1877         void *data;
1878         size_t len;
1879         size_t check_len;
1880         int rc;
1881
1882         /* Calculate length of parameter list */
1883         len = http_params ( params, NULL, 0 );
1884
1885         /* Allocate temporary parameter list */
1886         data = zalloc ( len + 1 /* NUL */ );
1887         if ( ! data ) {
1888                 rc = -ENOMEM;
1889                 goto err_alloc;
1890         }
1891
1892         /* Construct temporary parameter list */
1893         check_len = http_params ( params, data, ( len + 1 /* NUL */ ) );
1894         assert ( check_len == len );
1895
1896         /* Construct request content */
1897         content.type = "application/x-www-form-urlencoded";
1898         content.data = data;
1899         content.len = len;
1900
1901         /* Open HTTP transaction */
1902         if ( ( rc = http_open ( xfer, &http_post, uri, NULL, &content ) ) != 0 )
1903                 goto err_open;
1904
1905  err_open:
1906         free ( data );
1907  err_alloc:
1908         return rc;
1909 }
1910
1911 /**
1912  * Open HTTP transaction for simple URI
1913  *
1914  * @v xfer              Data transfer interface
1915  * @v uri               Request URI
1916  * @ret rc              Return status code
1917  */
1918 int http_open_uri ( struct interface *xfer, struct uri *uri ) {
1919
1920         /* Open GET/POST URI as applicable */
1921         if ( uri->params ) {
1922                 return http_open_post_uri ( xfer, uri );
1923         } else {
1924                 return http_open_get_uri ( xfer, uri );
1925         }
1926 }
1927
1928 /* Drag in HTTP extensions */
1929 REQUIRING_SYMBOL ( http_open );
1930 REQUIRE_OBJECT ( config_http );