summaryrefslogtreecommitdiffstats
path: root/qemu/roms/ipxe/src/net/tcp
diff options
context:
space:
mode:
Diffstat (limited to 'qemu/roms/ipxe/src/net/tcp')
-rw-r--r--qemu/roms/ipxe/src/net/tcp/ftp.c546
-rw-r--r--qemu/roms/ipxe/src/net/tcp/http.c51
-rw-r--r--qemu/roms/ipxe/src/net/tcp/httpcore.c1574
-rw-r--r--qemu/roms/ipxe/src/net/tcp/https.c52
-rw-r--r--qemu/roms/ipxe/src/net/tcp/iscsi.c2126
-rw-r--r--qemu/roms/ipxe/src/net/tcp/oncrpc.c250
-rw-r--r--qemu/roms/ipxe/src/net/tcp/syslogs.c269
7 files changed, 4868 insertions, 0 deletions
diff --git a/qemu/roms/ipxe/src/net/tcp/ftp.c b/qemu/roms/ipxe/src/net/tcp/ftp.c
new file mode 100644
index 000000000..be7a7c3b5
--- /dev/null
+++ b/qemu/roms/ipxe/src/net/tcp/ftp.c
@@ -0,0 +1,546 @@
+/*
+ * Copyright (C) 2007 Michael Brown <mbrown@fensystems.co.uk>.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation; either version 2 of the
+ * License, or any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include <stdint.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <assert.h>
+#include <errno.h>
+#include <ctype.h>
+#include <byteswap.h>
+#include <ipxe/socket.h>
+#include <ipxe/tcpip.h>
+#include <ipxe/in.h>
+#include <ipxe/iobuf.h>
+#include <ipxe/xfer.h>
+#include <ipxe/open.h>
+#include <ipxe/uri.h>
+#include <ipxe/features.h>
+#include <ipxe/ftp.h>
+
+/** @file
+ *
+ * File transfer protocol
+ *
+ */
+
+FEATURE ( FEATURE_PROTOCOL, "FTP", DHCP_EB_FEATURE_FTP, 1 );
+
+/**
+ * FTP states
+ *
+ * These @b must be sequential, i.e. a successful FTP session must
+ * pass through each of these states in order.
+ */
+enum ftp_state {
+ FTP_CONNECT = 0,
+ FTP_USER,
+ FTP_PASS,
+ FTP_TYPE,
+ FTP_SIZE,
+ FTP_PASV,
+ FTP_RETR,
+ FTP_WAIT,
+ FTP_QUIT,
+ FTP_DONE,
+};
+
+/**
+ * An FTP request
+ *
+ */
+struct ftp_request {
+ /** Reference counter */
+ struct refcnt refcnt;
+ /** Data transfer interface */
+ struct interface xfer;
+
+ /** URI being fetched */
+ struct uri *uri;
+ /** FTP control channel interface */
+ struct interface control;
+ /** FTP data channel interface */
+ struct interface data;
+
+ /** Current state */
+ enum ftp_state state;
+ /** Buffer to be filled with data received via the control channel */
+ char *recvbuf;
+ /** Remaining size of recvbuf */
+ size_t recvsize;
+ /** FTP status code, as text */
+ char status_text[5];
+ /** Passive-mode parameters, as text */
+ char passive_text[24]; /* "aaa,bbb,ccc,ddd,eee,fff" */
+ /** File size, as text */
+ char filesize[20];
+};
+
+/**
+ * Free FTP request
+ *
+ * @v refcnt Reference counter
+ */
+static void ftp_free ( struct refcnt *refcnt ) {
+ struct ftp_request *ftp =
+ container_of ( refcnt, struct ftp_request, refcnt );
+
+ DBGC ( ftp, "FTP %p freed\n", ftp );
+
+ uri_put ( ftp->uri );
+ free ( ftp );
+}
+
+/**
+ * Mark FTP operation as complete
+ *
+ * @v ftp FTP request
+ * @v rc Return status code
+ */
+static void ftp_done ( struct ftp_request *ftp, int rc ) {
+
+ DBGC ( ftp, "FTP %p completed (%s)\n", ftp, strerror ( rc ) );
+
+ /* Close all data transfer interfaces */
+ intf_shutdown ( &ftp->data, rc );
+ intf_shutdown ( &ftp->control, rc );
+ intf_shutdown ( &ftp->xfer, rc );
+}
+
+/*****************************************************************************
+ *
+ * FTP control channel
+ *
+ */
+
+/** An FTP control channel string */
+struct ftp_control_string {
+ /** Literal portion */
+ const char *literal;
+ /** Variable portion
+ *
+ * @v ftp FTP request
+ * @ret string Variable portion of string
+ */
+ const char * ( *variable ) ( struct ftp_request *ftp );
+};
+
+/**
+ * Retrieve FTP pathname
+ *
+ * @v ftp FTP request
+ * @ret path FTP pathname
+ */
+static const char * ftp_uri_path ( struct ftp_request *ftp ) {
+ return ftp->uri->path;
+}
+
+/**
+ * Retrieve FTP user
+ *
+ * @v ftp FTP request
+ * @ret user FTP user
+ */
+static const char * ftp_user ( struct ftp_request *ftp ) {
+ static char *ftp_default_user = "anonymous";
+ return ftp->uri->user ? ftp->uri->user : ftp_default_user;
+}
+
+/**
+ * Retrieve FTP password
+ *
+ * @v ftp FTP request
+ * @ret password FTP password
+ */
+static const char * ftp_password ( struct ftp_request *ftp ) {
+ static char *ftp_default_password = "ipxe@ipxe.org";
+ return ftp->uri->password ? ftp->uri->password : ftp_default_password;
+}
+
+/** FTP control channel strings */
+static struct ftp_control_string ftp_strings[] = {
+ [FTP_CONNECT] = { NULL, NULL },
+ [FTP_USER] = { "USER ", ftp_user },
+ [FTP_PASS] = { "PASS ", ftp_password },
+ [FTP_TYPE] = { "TYPE I", NULL },
+ [FTP_SIZE] = { "SIZE ", ftp_uri_path },
+ [FTP_PASV] = { "PASV", NULL },
+ [FTP_RETR] = { "RETR ", ftp_uri_path },
+ [FTP_WAIT] = { NULL, NULL },
+ [FTP_QUIT] = { "QUIT", NULL },
+ [FTP_DONE] = { NULL, NULL },
+};
+
+/**
+ * Parse FTP byte sequence value
+ *
+ * @v text Text string
+ * @v value Value buffer
+ * @v len Length of value buffer
+ *
+ * This parses an FTP byte sequence value (e.g. the "aaa,bbb,ccc,ddd"
+ * form for IP addresses in PORT commands) into a byte sequence. @c
+ * *text will be updated to point beyond the end of the parsed byte
+ * sequence.
+ *
+ * This function is safe in the presence of malformed data, though the
+ * output is undefined.
+ */
+static void ftp_parse_value ( char **text, uint8_t *value, size_t len ) {
+ do {
+ *(value++) = strtoul ( *text, text, 10 );
+ if ( **text )
+ (*text)++;
+ } while ( --len );
+}
+
+/**
+ * Move to next state and send the appropriate FTP control string
+ *
+ * @v ftp FTP request
+ *
+ */
+static void ftp_next_state ( struct ftp_request *ftp ) {
+ struct ftp_control_string *ftp_string;
+ const char *literal;
+ const char *variable;
+
+ /* Move to next state */
+ if ( ftp->state < FTP_DONE )
+ ftp->state++;
+
+ /* Send control string if needed */
+ ftp_string = &ftp_strings[ftp->state];
+ literal = ftp_string->literal;
+ variable = ( ftp_string->variable ?
+ ftp_string->variable ( ftp ) : "" );
+ if ( literal ) {
+ DBGC ( ftp, "FTP %p sending %s%s\n", ftp, literal, variable );
+ xfer_printf ( &ftp->control, "%s%s\r\n", literal, variable );
+ }
+}
+
+/**
+ * Handle an FTP control channel response
+ *
+ * @v ftp FTP request
+ *
+ * This is called once we have received a complete response line.
+ */
+static void ftp_reply ( struct ftp_request *ftp ) {
+ char status_major = ftp->status_text[0];
+ char separator = ftp->status_text[3];
+
+ DBGC ( ftp, "FTP %p received status %s\n", ftp, ftp->status_text );
+
+ /* Ignore malformed lines */
+ if ( separator != ' ' )
+ return;
+
+ /* Ignore "intermediate" responses (1xx codes) */
+ if ( status_major == '1' )
+ return;
+
+ /* If the SIZE command is not supported by the server, we go to
+ * the next step.
+ */
+ if ( ( status_major == '5' ) && ( ftp->state == FTP_SIZE ) ) {
+ ftp_next_state ( ftp );
+ return;
+ }
+
+ /* Anything other than success (2xx) or, in the case of a
+ * repsonse to a "USER" command, a password prompt (3xx), is a
+ * fatal error.
+ */
+ if ( ! ( ( status_major == '2' ) ||
+ ( ( status_major == '3' ) && ( ftp->state == FTP_USER ) ) ) ){
+ /* Flag protocol error and close connections */
+ ftp_done ( ftp, -EPROTO );
+ return;
+ }
+
+ /* Parse file size */
+ if ( ftp->state == FTP_SIZE ) {
+ size_t filesize;
+ char *endptr;
+
+ /* Parse size */
+ filesize = strtoul ( ftp->filesize, &endptr, 10 );
+ if ( *endptr != '\0' ) {
+ DBGC ( ftp, "FTP %p invalid SIZE \"%s\"\n",
+ ftp, ftp->filesize );
+ ftp_done ( ftp, -EPROTO );
+ return;
+ }
+
+ /* Use seek() to notify recipient of filesize */
+ DBGC ( ftp, "FTP %p file size is %zd bytes\n", ftp, filesize );
+ xfer_seek ( &ftp->xfer, filesize );
+ xfer_seek ( &ftp->xfer, 0 );
+ }
+
+ /* Open passive connection when we get "PASV" response */
+ if ( ftp->state == FTP_PASV ) {
+ char *ptr = ftp->passive_text;
+ union {
+ struct sockaddr_in sin;
+ struct sockaddr sa;
+ } sa;
+ int rc;
+
+ sa.sin.sin_family = AF_INET;
+ ftp_parse_value ( &ptr, ( uint8_t * ) &sa.sin.sin_addr,
+ sizeof ( sa.sin.sin_addr ) );
+ ftp_parse_value ( &ptr, ( uint8_t * ) &sa.sin.sin_port,
+ sizeof ( sa.sin.sin_port ) );
+ if ( ( rc = xfer_open_socket ( &ftp->data, SOCK_STREAM,
+ &sa.sa, NULL ) ) != 0 ) {
+ DBGC ( ftp, "FTP %p could not open data connection\n",
+ ftp );
+ ftp_done ( ftp, rc );
+ return;
+ }
+ }
+
+ /* Move to next state and send control string */
+ ftp_next_state ( ftp );
+
+}
+
+/**
+ * Handle new data arriving on FTP control channel
+ *
+ * @v ftp FTP request
+ * @v iob I/O buffer
+ * @v meta Data transfer metadata
+ * @ret rc Return status code
+ *
+ * Data is collected until a complete line is received, at which point
+ * its information is passed to ftp_reply().
+ */
+static int ftp_control_deliver ( struct ftp_request *ftp,
+ struct io_buffer *iobuf,
+ struct xfer_metadata *meta __unused ) {
+ char *data = iobuf->data;
+ size_t len = iob_len ( iobuf );
+ char *recvbuf = ftp->recvbuf;
+ size_t recvsize = ftp->recvsize;
+ char c;
+
+ while ( len-- ) {
+ c = *(data++);
+ if ( ( c == '\r' ) || ( c == '\n' ) ) {
+ /* End of line: call ftp_reply() to handle
+ * completed reply. Avoid calling ftp_reply()
+ * twice if we receive both \r and \n.
+ */
+ if ( recvbuf != ftp->status_text )
+ ftp_reply ( ftp );
+ /* Start filling up the status code buffer */
+ recvbuf = ftp->status_text;
+ recvsize = sizeof ( ftp->status_text ) - 1;
+ } else if ( ( ftp->state == FTP_PASV ) && ( c == '(' ) ) {
+ /* Start filling up the passive parameter buffer */
+ recvbuf = ftp->passive_text;
+ recvsize = sizeof ( ftp->passive_text ) - 1;
+ } else if ( ( ftp->state == FTP_PASV ) && ( c == ')' ) ) {
+ /* Stop filling the passive parameter buffer */
+ recvsize = 0;
+ } else if ( ( ftp->state == FTP_SIZE ) && ( c == ' ' ) ) {
+ /* Start filling up the file size buffer */
+ recvbuf = ftp->filesize;
+ recvsize = sizeof ( ftp->filesize ) - 1;
+ } else {
+ /* Fill up buffer if applicable */
+ if ( recvsize > 0 ) {
+ *(recvbuf++) = c;
+ recvsize--;
+ }
+ }
+ }
+
+ /* Store for next invocation */
+ ftp->recvbuf = recvbuf;
+ ftp->recvsize = recvsize;
+
+ /* Free I/O buffer */
+ free_iob ( iobuf );
+
+ return 0;
+}
+
+/** FTP control channel interface operations */
+static struct interface_operation ftp_control_operations[] = {
+ INTF_OP ( xfer_deliver, struct ftp_request *, ftp_control_deliver ),
+ INTF_OP ( intf_close, struct ftp_request *, ftp_done ),
+};
+
+/** FTP control channel interface descriptor */
+static struct interface_descriptor ftp_control_desc =
+ INTF_DESC ( struct ftp_request, control, ftp_control_operations );
+
+/*****************************************************************************
+ *
+ * FTP data channel
+ *
+ */
+
+/**
+ * Handle FTP data channel being closed
+ *
+ * @v ftp FTP request
+ * @v rc Reason for closure
+ *
+ * When the data channel is closed, the control channel should be left
+ * alone; the server will send a completion message via the control
+ * channel which we'll pick up.
+ *
+ * If the data channel is closed due to an error, we abort the request.
+ */
+static void ftp_data_closed ( struct ftp_request *ftp, int rc ) {
+
+ DBGC ( ftp, "FTP %p data connection closed: %s\n",
+ ftp, strerror ( rc ) );
+
+ /* If there was an error, close control channel and record status */
+ if ( rc ) {
+ ftp_done ( ftp, rc );
+ } else {
+ ftp_next_state ( ftp );
+ }
+}
+
+/** FTP data channel interface operations */
+static struct interface_operation ftp_data_operations[] = {
+ INTF_OP ( intf_close, struct ftp_request *, ftp_data_closed ),
+};
+
+/** FTP data channel interface descriptor */
+static struct interface_descriptor ftp_data_desc =
+ INTF_DESC_PASSTHRU ( struct ftp_request, data, ftp_data_operations,
+ xfer );
+
+/*****************************************************************************
+ *
+ * Data transfer interface
+ *
+ */
+
+/** FTP data transfer interface operations */
+static struct interface_operation ftp_xfer_operations[] = {
+ INTF_OP ( intf_close, struct ftp_request *, ftp_done ),
+};
+
+/** FTP data transfer interface descriptor */
+static struct interface_descriptor ftp_xfer_desc =
+ INTF_DESC_PASSTHRU ( struct ftp_request, xfer, ftp_xfer_operations,
+ data );
+
+/*****************************************************************************
+ *
+ * URI opener
+ *
+ */
+
+/**
+ * Check validity of FTP control channel string
+ *
+ * @v string String
+ * @ret rc Return status code
+ */
+static int ftp_check_string ( const char *string ) {
+ char c;
+
+ /* The FTP control channel is line-based. Check for invalid
+ * non-printable characters (e.g. newlines).
+ */
+ while ( ( c = *(string++) ) ) {
+ if ( ! isprint ( c ) )
+ return -EINVAL;
+ }
+ return 0;
+}
+
+/**
+ * Initiate an FTP connection
+ *
+ * @v xfer Data transfer interface
+ * @v uri Uniform Resource Identifier
+ * @ret rc Return status code
+ */
+static int ftp_open ( struct interface *xfer, struct uri *uri ) {
+ struct ftp_request *ftp;
+ struct sockaddr_tcpip server;
+ int rc;
+
+ /* Sanity checks */
+ if ( ! uri->host )
+ return -EINVAL;
+ if ( ! uri->path )
+ return -EINVAL;
+ if ( ( rc = ftp_check_string ( uri->path ) ) != 0 )
+ return rc;
+ if ( uri->user && ( ( rc = ftp_check_string ( uri->user ) ) != 0 ) )
+ return rc;
+ if ( uri->password &&
+ ( ( rc = ftp_check_string ( uri->password ) ) != 0 ) )
+ return rc;
+
+ /* Allocate and populate structure */
+ ftp = zalloc ( sizeof ( *ftp ) );
+ if ( ! ftp )
+ return -ENOMEM;
+ ref_init ( &ftp->refcnt, ftp_free );
+ intf_init ( &ftp->xfer, &ftp_xfer_desc, &ftp->refcnt );
+ intf_init ( &ftp->control, &ftp_control_desc, &ftp->refcnt );
+ intf_init ( &ftp->data, &ftp_data_desc, &ftp->refcnt );
+ ftp->uri = uri_get ( uri );
+ ftp->recvbuf = ftp->status_text;
+ ftp->recvsize = sizeof ( ftp->status_text ) - 1;
+
+ DBGC ( ftp, "FTP %p fetching %s\n", ftp, ftp->uri->path );
+
+ /* Open control connection */
+ memset ( &server, 0, sizeof ( server ) );
+ server.st_port = htons ( uri_port ( uri, FTP_PORT ) );
+ if ( ( rc = xfer_open_named_socket ( &ftp->control, SOCK_STREAM,
+ ( struct sockaddr * ) &server,
+ uri->host, NULL ) ) != 0 )
+ goto err;
+
+ /* Attach to parent interface, mortalise self, and return */
+ intf_plug_plug ( &ftp->xfer, xfer );
+ ref_put ( &ftp->refcnt );
+ return 0;
+
+ err:
+ DBGC ( ftp, "FTP %p could not create request: %s\n",
+ ftp, strerror ( rc ) );
+ ftp_done ( ftp, rc );
+ ref_put ( &ftp->refcnt );
+ return rc;
+}
+
+/** FTP URI opener */
+struct uri_opener ftp_uri_opener __uri_opener = {
+ .scheme = "ftp",
+ .open = ftp_open,
+};
diff --git a/qemu/roms/ipxe/src/net/tcp/http.c b/qemu/roms/ipxe/src/net/tcp/http.c
new file mode 100644
index 000000000..90bae9d7a
--- /dev/null
+++ b/qemu/roms/ipxe/src/net/tcp/http.c
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2007 Michael Brown <mbrown@fensystems.co.uk>.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation; either version 2 of the
+ * License, or any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+FILE_LICENCE ( GPL2_OR_LATER );
+
+/**
+ * @file
+ *
+ * Hyper Text Transfer Protocol (HTTP)
+ *
+ */
+
+#include <stddef.h>
+#include <ipxe/open.h>
+#include <ipxe/http.h>
+#include <ipxe/features.h>
+
+FEATURE ( FEATURE_PROTOCOL, "HTTP", DHCP_EB_FEATURE_HTTP, 1 );
+
+/**
+ * Initiate an HTTP connection
+ *
+ * @v xfer Data transfer interface
+ * @v uri Uniform Resource Identifier
+ * @ret rc Return status code
+ */
+static int http_open ( struct interface *xfer, struct uri *uri ) {
+ return http_open_filter ( xfer, uri, HTTP_PORT, NULL );
+}
+
+/** HTTP URI opener */
+struct uri_opener http_uri_opener __uri_opener = {
+ .scheme = "http",
+ .open = http_open,
+};
diff --git a/qemu/roms/ipxe/src/net/tcp/httpcore.c b/qemu/roms/ipxe/src/net/tcp/httpcore.c
new file mode 100644
index 000000000..1d1953e61
--- /dev/null
+++ b/qemu/roms/ipxe/src/net/tcp/httpcore.c
@@ -0,0 +1,1574 @@
+/*
+ * Copyright (C) 2007 Michael Brown <mbrown@fensystems.co.uk>.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation; either version 2 of the
+ * License, or any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+FILE_LICENCE ( GPL2_OR_LATER );
+
+/**
+ * @file
+ *
+ * Hyper Text Transfer Protocol (HTTP) core functionality
+ *
+ */
+
+#include <stdint.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <strings.h>
+#include <byteswap.h>
+#include <errno.h>
+#include <ctype.h>
+#include <assert.h>
+#include <ipxe/uri.h>
+#include <ipxe/refcnt.h>
+#include <ipxe/iobuf.h>
+#include <ipxe/xfer.h>
+#include <ipxe/open.h>
+#include <ipxe/socket.h>
+#include <ipxe/tcpip.h>
+#include <ipxe/process.h>
+#include <ipxe/retry.h>
+#include <ipxe/timer.h>
+#include <ipxe/linebuf.h>
+#include <ipxe/base64.h>
+#include <ipxe/base16.h>
+#include <ipxe/md5.h>
+#include <ipxe/blockdev.h>
+#include <ipxe/acpi.h>
+#include <ipxe/version.h>
+#include <ipxe/params.h>
+#include <ipxe/profile.h>
+#include <ipxe/http.h>
+
+/* Disambiguate the various error causes */
+#define EACCES_401 __einfo_error ( EINFO_EACCES_401 )
+#define EINFO_EACCES_401 \
+ __einfo_uniqify ( EINFO_EACCES, 0x01, "HTTP 401 Unauthorized" )
+#define EIO_OTHER __einfo_error ( EINFO_EIO_OTHER )
+#define EINFO_EIO_OTHER \
+ __einfo_uniqify ( EINFO_EIO, 0x01, "Unrecognised HTTP response code" )
+#define EIO_CONTENT_LENGTH __einfo_error ( EINFO_EIO_CONTENT_LENGTH )
+#define EINFO_EIO_CONTENT_LENGTH \
+ __einfo_uniqify ( EINFO_EIO, 0x02, "Content length mismatch" )
+#define EINVAL_RESPONSE __einfo_error ( EINFO_EINVAL_RESPONSE )
+#define EINFO_EINVAL_RESPONSE \
+ __einfo_uniqify ( EINFO_EINVAL, 0x01, "Invalid content length" )
+#define EINVAL_HEADER __einfo_error ( EINFO_EINVAL_HEADER )
+#define EINFO_EINVAL_HEADER \
+ __einfo_uniqify ( EINFO_EINVAL, 0x02, "Invalid header" )
+#define EINVAL_CONTENT_LENGTH __einfo_error ( EINFO_EINVAL_CONTENT_LENGTH )
+#define EINFO_EINVAL_CONTENT_LENGTH \
+ __einfo_uniqify ( EINFO_EINVAL, 0x03, "Invalid content length" )
+#define EINVAL_CHUNK_LENGTH __einfo_error ( EINFO_EINVAL_CHUNK_LENGTH )
+#define EINFO_EINVAL_CHUNK_LENGTH \
+ __einfo_uniqify ( EINFO_EINVAL, 0x04, "Invalid chunk length" )
+#define ENOENT_404 __einfo_error ( EINFO_ENOENT_404 )
+#define EINFO_ENOENT_404 \
+ __einfo_uniqify ( EINFO_ENOENT, 0x01, "HTTP 404 Not Found" )
+#define EPERM_403 __einfo_error ( EINFO_EPERM_403 )
+#define EINFO_EPERM_403 \
+ __einfo_uniqify ( EINFO_EPERM, 0x01, "HTTP 403 Forbidden" )
+#define EPROTO_UNSOLICITED __einfo_error ( EINFO_EPROTO_UNSOLICITED )
+#define EINFO_EPROTO_UNSOLICITED \
+ __einfo_uniqify ( EINFO_EPROTO, 0x01, "Unsolicited data" )
+
+/** Block size used for HTTP block device request */
+#define HTTP_BLKSIZE 512
+
+/** Retry delay used when we cannot understand the Retry-After header */
+#define HTTP_RETRY_SECONDS 5
+
+/** Receive profiler */
+static struct profiler http_rx_profiler __profiler = { .name = "http.rx" };
+
+/** Data transfer profiler */
+static struct profiler http_xfer_profiler __profiler = { .name = "http.xfer" };
+
+/** HTTP flags */
+enum http_flags {
+ /** Request is waiting to be transmitted */
+ HTTP_TX_PENDING = 0x0001,
+ /** Fetch header only */
+ HTTP_HEAD_ONLY = 0x0002,
+ /** Client would like to keep connection alive */
+ HTTP_CLIENT_KEEPALIVE = 0x0004,
+ /** Server will keep connection alive */
+ HTTP_SERVER_KEEPALIVE = 0x0008,
+ /** Discard the current request and try again */
+ HTTP_TRY_AGAIN = 0x0010,
+ /** Provide Basic authentication details */
+ HTTP_BASIC_AUTH = 0x0020,
+ /** Provide Digest authentication details */
+ HTTP_DIGEST_AUTH = 0x0040,
+ /** Socket must be reopened */
+ HTTP_REOPEN_SOCKET = 0x0080,
+};
+
+/** HTTP receive state */
+enum http_rx_state {
+ HTTP_RX_RESPONSE = 0,
+ HTTP_RX_HEADER,
+ HTTP_RX_CHUNK_LEN,
+ /* In HTTP_RX_DATA, it is acceptable for the server to close
+ * the connection (unless we are in the middle of a chunked
+ * transfer).
+ */
+ HTTP_RX_DATA,
+ /* In the following states, it is acceptable for the server to
+ * close the connection.
+ */
+ HTTP_RX_TRAILER,
+ HTTP_RX_IDLE,
+ HTTP_RX_DEAD,
+};
+
+/**
+ * An HTTP request
+ *
+ */
+struct http_request {
+ /** Reference count */
+ struct refcnt refcnt;
+ /** Data transfer interface */
+ struct interface xfer;
+ /** Partial transfer interface */
+ struct interface partial;
+
+ /** URI being fetched */
+ struct uri *uri;
+ /** Default port */
+ unsigned int default_port;
+ /** Filter (if any) */
+ int ( * filter ) ( struct interface *xfer,
+ const char *name,
+ struct interface **next );
+ /** Transport layer interface */
+ struct interface socket;
+
+ /** Flags */
+ unsigned int flags;
+ /** Starting offset of partial transfer (if applicable) */
+ size_t partial_start;
+ /** Length of partial transfer (if applicable) */
+ size_t partial_len;
+
+ /** TX process */
+ struct process process;
+
+ /** RX state */
+ enum http_rx_state rx_state;
+ /** Response code */
+ unsigned int code;
+ /** Received length */
+ size_t rx_len;
+ /** Length remaining (or 0 if unknown) */
+ size_t remaining;
+ /** HTTP is using Transfer-Encoding: chunked */
+ int chunked;
+ /** Current chunk length remaining (if applicable) */
+ size_t chunk_remaining;
+ /** Line buffer for received header lines */
+ struct line_buffer linebuf;
+ /** Receive data buffer (if applicable) */
+ userptr_t rx_buffer;
+
+ /** Authentication realm (if any) */
+ char *auth_realm;
+ /** Authentication nonce (if any) */
+ char *auth_nonce;
+ /** Authentication opaque string (if any) */
+ char *auth_opaque;
+
+ /** Request retry timer */
+ struct retry_timer timer;
+ /** Retry delay (in timer ticks) */
+ unsigned long retry_delay;
+};
+
+/**
+ * Free HTTP request
+ *
+ * @v refcnt Reference counter
+ */
+static void http_free ( struct refcnt *refcnt ) {
+ struct http_request *http =
+ container_of ( refcnt, struct http_request, refcnt );
+
+ uri_put ( http->uri );
+ empty_line_buffer ( &http->linebuf );
+ free ( http->auth_realm );
+ free ( http->auth_nonce );
+ free ( http->auth_opaque );
+ free ( http );
+};
+
+/**
+ * Close HTTP request
+ *
+ * @v http HTTP request
+ * @v rc Return status code
+ */
+static void http_close ( struct http_request *http, int rc ) {
+
+ /* Prevent further processing of any current packet */
+ http->rx_state = HTTP_RX_DEAD;
+
+ /* Prevent reconnection */
+ http->flags &= ~HTTP_CLIENT_KEEPALIVE;
+
+ /* Remove process */
+ process_del ( &http->process );
+
+ /* Close all data transfer interfaces */
+ intf_shutdown ( &http->socket, rc );
+ intf_shutdown ( &http->partial, rc );
+ intf_shutdown ( &http->xfer, rc );
+}
+
+/**
+ * Open HTTP socket
+ *
+ * @v http HTTP request
+ * @ret rc Return status code
+ */
+static int http_socket_open ( struct http_request *http ) {
+ struct uri *uri = http->uri;
+ struct sockaddr_tcpip server;
+ struct interface *socket;
+ int rc;
+
+ /* Open socket */
+ memset ( &server, 0, sizeof ( server ) );
+ server.st_port = htons ( uri_port ( uri, http->default_port ) );
+ socket = &http->socket;
+ if ( http->filter ) {
+ if ( ( rc = http->filter ( socket, uri->host, &socket ) ) != 0 )
+ return rc;
+ }
+ if ( ( rc = xfer_open_named_socket ( socket, SOCK_STREAM,
+ ( struct sockaddr * ) &server,
+ uri->host, NULL ) ) != 0 )
+ return rc;
+
+ return 0;
+}
+
+/**
+ * Retry HTTP request
+ *
+ * @v timer Retry timer
+ * @v fail Failure indicator
+ */
+static void http_retry ( struct retry_timer *timer, int fail __unused ) {
+ struct http_request *http =
+ container_of ( timer, struct http_request, timer );
+ int rc;
+
+ /* Reopen socket if required */
+ if ( http->flags & HTTP_REOPEN_SOCKET ) {
+ http->flags &= ~HTTP_REOPEN_SOCKET;
+ DBGC ( http, "HTTP %p reopening connection\n", http );
+ if ( ( rc = http_socket_open ( http ) ) != 0 ) {
+ http_close ( http, rc );
+ return;
+ }
+ }
+
+ /* Retry the request if applicable */
+ if ( http->flags & HTTP_TRY_AGAIN ) {
+ http->flags &= ~HTTP_TRY_AGAIN;
+ DBGC ( http, "HTTP %p retrying request\n", http );
+ http->flags |= HTTP_TX_PENDING;
+ http->rx_state = HTTP_RX_RESPONSE;
+ process_add ( &http->process );
+ }
+}
+
+/**
+ * Mark HTTP request as completed successfully
+ *
+ * @v http HTTP request
+ */
+static void http_done ( struct http_request *http ) {
+
+ /* If we are not at an appropriate stage of the protocol
+ * (including being in the middle of a chunked transfer),
+ * force an error.
+ */
+ if ( ( http->rx_state < HTTP_RX_DATA ) || ( http->chunked != 0 ) ) {
+ DBGC ( http, "HTTP %p connection closed unexpectedly in state "
+ "%d\n", http, http->rx_state );
+ http_close ( http, -ECONNRESET );
+ return;
+ }
+
+ /* If we had a Content-Length, and the received content length
+ * isn't correct, force an error
+ */
+ if ( http->remaining != 0 ) {
+ DBGC ( http, "HTTP %p incorrect length %zd, should be %zd\n",
+ http, http->rx_len, ( http->rx_len + http->remaining ) );
+ http_close ( http, -EIO_CONTENT_LENGTH );
+ return;
+ }
+
+ /* Enter idle state */
+ http->rx_state = HTTP_RX_IDLE;
+ http->rx_len = 0;
+ assert ( http->remaining == 0 );
+ assert ( http->chunked == 0 );
+ assert ( http->chunk_remaining == 0 );
+
+ /* Close partial transfer interface */
+ if ( ! ( http->flags & HTTP_TRY_AGAIN ) )
+ intf_restart ( &http->partial, 0 );
+
+ /* Close everything unless we want to keep the connection alive */
+ if ( ! ( http->flags & ( HTTP_CLIENT_KEEPALIVE | HTTP_TRY_AGAIN ) ) ) {
+ http_close ( http, 0 );
+ return;
+ }
+
+ /* If the server is not intending to keep the connection
+ * alive, then close the socket and mark it as requiring
+ * reopening.
+ */
+ if ( ! ( http->flags & HTTP_SERVER_KEEPALIVE ) ) {
+ intf_restart ( &http->socket, 0 );
+ http->flags &= ~HTTP_SERVER_KEEPALIVE;
+ http->flags |= HTTP_REOPEN_SOCKET;
+ }
+
+ /* Start request retry timer */
+ start_timer_fixed ( &http->timer, http->retry_delay );
+ http->retry_delay = 0;
+}
+
+/**
+ * Convert HTTP response code to return status code
+ *
+ * @v response HTTP response code
+ * @ret rc Return status code
+ */
+static int http_response_to_rc ( unsigned int response ) {
+ switch ( response ) {
+ case 200:
+ case 206:
+ case 301:
+ case 302:
+ case 303:
+ return 0;
+ case 404:
+ return -ENOENT_404;
+ case 403:
+ return -EPERM_403;
+ case 401:
+ return -EACCES_401;
+ default:
+ return -EIO_OTHER;
+ }
+}
+
+/**
+ * Handle HTTP response
+ *
+ * @v http HTTP request
+ * @v response HTTP response
+ * @ret rc Return status code
+ */
+static int http_rx_response ( struct http_request *http, char *response ) {
+ char *spc;
+
+ DBGC ( http, "HTTP %p response \"%s\"\n", http, response );
+
+ /* Check response starts with "HTTP/" */
+ if ( strncmp ( response, "HTTP/", 5 ) != 0 )
+ return -EINVAL_RESPONSE;
+
+ /* Locate and store response code */
+ spc = strchr ( response, ' ' );
+ if ( ! spc )
+ return -EINVAL_RESPONSE;
+ http->code = strtoul ( spc, NULL, 10 );
+
+ /* Move to receive headers */
+ http->rx_state = ( ( http->flags & HTTP_HEAD_ONLY ) ?
+ HTTP_RX_TRAILER : HTTP_RX_HEADER );
+ return 0;
+}
+
+/**
+ * Handle HTTP Location header
+ *
+ * @v http HTTP request
+ * @v value HTTP header value
+ * @ret rc Return status code
+ */
+static int http_rx_location ( struct http_request *http, char *value ) {
+ int rc;
+
+ /* Redirect to new location */
+ DBGC ( http, "HTTP %p redirecting to %s\n", http, value );
+ if ( ( rc = xfer_redirect ( &http->xfer, LOCATION_URI_STRING,
+ value ) ) != 0 ) {
+ DBGC ( http, "HTTP %p could not redirect: %s\n",
+ http, strerror ( rc ) );
+ return rc;
+ }
+
+ return 0;
+}
+
+/**
+ * Handle HTTP Content-Length header
+ *
+ * @v http HTTP request
+ * @v value HTTP header value
+ * @ret rc Return status code
+ */
+static int http_rx_content_length ( struct http_request *http, char *value ) {
+ struct block_device_capacity capacity;
+ size_t content_len;
+ char *endp;
+
+ /* Parse content length */
+ content_len = strtoul ( value, &endp, 10 );
+ if ( ! ( ( *endp == '\0' ) || isspace ( *endp ) ) ) {
+ DBGC ( http, "HTTP %p invalid Content-Length \"%s\"\n",
+ http, value );
+ return -EINVAL_CONTENT_LENGTH;
+ }
+
+ /* If we already have an expected content length, and this
+ * isn't it, then complain
+ */
+ if ( http->remaining && ( http->remaining != content_len ) ) {
+ DBGC ( http, "HTTP %p incorrect Content-Length %zd (expected "
+ "%zd)\n", http, content_len, http->remaining );
+ return -EIO_CONTENT_LENGTH;
+ }
+ if ( ! ( http->flags & HTTP_HEAD_ONLY ) )
+ http->remaining = content_len;
+
+ /* Do nothing more if we are retrying the request */
+ if ( http->flags & HTTP_TRY_AGAIN )
+ return 0;
+
+ /* Use seek() to notify recipient of filesize */
+ xfer_seek ( &http->xfer, http->remaining );
+ xfer_seek ( &http->xfer, 0 );
+
+ /* Report block device capacity if applicable */
+ if ( http->flags & HTTP_HEAD_ONLY ) {
+ capacity.blocks = ( content_len / HTTP_BLKSIZE );
+ capacity.blksize = HTTP_BLKSIZE;
+ capacity.max_count = -1U;
+ block_capacity ( &http->partial, &capacity );
+ }
+ return 0;
+}
+
+/**
+ * Handle HTTP Transfer-Encoding header
+ *
+ * @v http HTTP request
+ * @v value HTTP header value
+ * @ret rc Return status code
+ */
+static int http_rx_transfer_encoding ( struct http_request *http, char *value ){
+
+ if ( strcasecmp ( value, "chunked" ) == 0 ) {
+ /* Mark connection as using chunked transfer encoding */
+ http->chunked = 1;
+ }
+
+ return 0;
+}
+
+/**
+ * Handle HTTP Connection header
+ *
+ * @v http HTTP request
+ * @v value HTTP header value
+ * @ret rc Return status code
+ */
+static int http_rx_connection ( struct http_request *http, char *value ) {
+
+ if ( strcasecmp ( value, "keep-alive" ) == 0 ) {
+ /* Mark connection as being kept alive by the server */
+ http->flags |= HTTP_SERVER_KEEPALIVE;
+ }
+
+ return 0;
+}
+
+/**
+ * Handle WWW-Authenticate Basic header
+ *
+ * @v http HTTP request
+ * @v params Parameters
+ * @ret rc Return status code
+ */
+static int http_rx_basic_auth ( struct http_request *http, char *params ) {
+
+ DBGC ( http, "HTTP %p Basic authentication required (%s)\n",
+ http, params );
+
+ /* If we received a 401 Unauthorized response, then retry
+ * using Basic authentication
+ */
+ if ( ( http->code == 401 ) &&
+ ( ! ( http->flags & HTTP_BASIC_AUTH ) ) &&
+ ( http->uri->user != NULL ) ) {
+ http->flags |= ( HTTP_TRY_AGAIN | HTTP_BASIC_AUTH );
+ }
+
+ return 0;
+}
+
+/**
+ * Parse Digest authentication parameter
+ *
+ * @v params Parameters
+ * @v name Parameter name (including trailing "=\"")
+ * @ret value Parameter value, or NULL
+ */
+static char * http_digest_param ( char *params, const char *name ) {
+ char *key;
+ char *value;
+ char *terminator;
+
+ /* Locate parameter */
+ key = strstr ( params, name );
+ if ( ! key )
+ return NULL;
+
+ /* Extract value */
+ value = ( key + strlen ( name ) );
+ terminator = strchr ( value, '"' );
+ if ( ! terminator )
+ return NULL;
+ return strndup ( value, ( terminator - value ) );
+}
+
+/**
+ * Handle WWW-Authenticate Digest header
+ *
+ * @v http HTTP request
+ * @v params Parameters
+ * @ret rc Return status code
+ */
+static int http_rx_digest_auth ( struct http_request *http, char *params ) {
+
+ DBGC ( http, "HTTP %p Digest authentication required (%s)\n",
+ http, params );
+
+ /* If we received a 401 Unauthorized response, then retry
+ * using Digest authentication
+ */
+ if ( ( http->code == 401 ) &&
+ ( ! ( http->flags & HTTP_DIGEST_AUTH ) ) &&
+ ( http->uri->user != NULL ) ) {
+
+ /* Extract realm */
+ free ( http->auth_realm );
+ http->auth_realm = http_digest_param ( params, "realm=\"" );
+ if ( ! http->auth_realm ) {
+ DBGC ( http, "HTTP %p Digest prompt missing realm\n",
+ http );
+ return -EINVAL_HEADER;
+ }
+
+ /* Extract nonce */
+ free ( http->auth_nonce );
+ http->auth_nonce = http_digest_param ( params, "nonce=\"" );
+ if ( ! http->auth_nonce ) {
+ DBGC ( http, "HTTP %p Digest prompt missing nonce\n",
+ http );
+ return -EINVAL_HEADER;
+ }
+
+ /* Extract opaque */
+ free ( http->auth_opaque );
+ http->auth_opaque = http_digest_param ( params, "opaque=\"" );
+ if ( ! http->auth_opaque ) {
+ /* Not an error; "opaque" is optional */
+ }
+
+ http->flags |= ( HTTP_TRY_AGAIN | HTTP_DIGEST_AUTH );
+ }
+
+ return 0;
+}
+
+/** An HTTP WWW-Authenticate header handler */
+struct http_auth_header_handler {
+ /** Scheme (e.g. "Basic") */
+ const char *scheme;
+ /** Handle received parameters
+ *
+ * @v http HTTP request
+ * @v params Parameters
+ * @ret rc Return status code
+ */
+ int ( * rx ) ( struct http_request *http, char *params );
+};
+
+/** List of HTTP WWW-Authenticate header handlers */
+static struct http_auth_header_handler http_auth_header_handlers[] = {
+ {
+ .scheme = "Basic",
+ .rx = http_rx_basic_auth,
+ },
+ {
+ .scheme = "Digest",
+ .rx = http_rx_digest_auth,
+ },
+ { NULL, NULL },
+};
+
+/**
+ * Handle HTTP WWW-Authenticate header
+ *
+ * @v http HTTP request
+ * @v value HTTP header value
+ * @ret rc Return status code
+ */
+static int http_rx_www_authenticate ( struct http_request *http, char *value ) {
+ struct http_auth_header_handler *handler;
+ char *separator;
+ char *scheme;
+ char *params;
+ int rc;
+
+ /* Extract scheme */
+ separator = strchr ( value, ' ' );
+ if ( ! separator ) {
+ DBGC ( http, "HTTP %p malformed WWW-Authenticate header\n",
+ http );
+ return -EINVAL_HEADER;
+ }
+ *separator = '\0';
+ scheme = value;
+ params = ( separator + 1 );
+
+ /* Hand off to header handler, if one exists */
+ for ( handler = http_auth_header_handlers; handler->scheme; handler++ ){
+ if ( strcasecmp ( scheme, handler->scheme ) == 0 ) {
+ if ( ( rc = handler->rx ( http, params ) ) != 0 )
+ return rc;
+ break;
+ }
+ }
+ return 0;
+}
+
+/**
+ * Handle HTTP Retry-After header
+ *
+ * @v http HTTP request
+ * @v value HTTP header value
+ * @ret rc Return status code
+ */
+static int http_rx_retry_after ( struct http_request *http, char *value ) {
+ unsigned long seconds;
+ char *endp;
+
+ DBGC ( http, "HTTP %p retry requested (%s)\n", http, value );
+
+ /* If we received a 503 Service Unavailable response, then
+ * retry after the specified number of seconds. If the value
+ * is not a simple number of seconds (e.g. a full HTTP date),
+ * then retry after a fixed delay, since we don't have code
+ * able to parse full HTTP dates.
+ */
+ if ( http->code == 503 ) {
+ seconds = strtoul ( value, &endp, 10 );
+ if ( *endp != '\0' ) {
+ seconds = HTTP_RETRY_SECONDS;
+ DBGC ( http, "HTTP %p cannot understand \"%s\"; "
+ "using %ld seconds\n", http, value, seconds );
+ }
+ http->flags |= HTTP_TRY_AGAIN;
+ http->retry_delay = ( seconds * TICKS_PER_SEC );
+ }
+
+ return 0;
+}
+
+/** An HTTP header handler */
+struct http_header_handler {
+ /** Name (e.g. "Content-Length") */
+ const char *header;
+ /** Handle received header
+ *
+ * @v http HTTP request
+ * @v value HTTP header value
+ * @ret rc Return status code
+ *
+ * If an error is returned, the download will be aborted.
+ */
+ int ( * rx ) ( struct http_request *http, char *value );
+};
+
+/** List of HTTP header handlers */
+static struct http_header_handler http_header_handlers[] = {
+ {
+ .header = "Location",
+ .rx = http_rx_location,
+ },
+ {
+ .header = "Content-Length",
+ .rx = http_rx_content_length,
+ },
+ {
+ .header = "Transfer-Encoding",
+ .rx = http_rx_transfer_encoding,
+ },
+ {
+ .header = "Connection",
+ .rx = http_rx_connection,
+ },
+ {
+ .header = "WWW-Authenticate",
+ .rx = http_rx_www_authenticate,
+ },
+ {
+ .header = "Retry-After",
+ .rx = http_rx_retry_after,
+ },
+ { NULL, NULL }
+};
+
+/**
+ * Handle HTTP header
+ *
+ * @v http HTTP request
+ * @v header HTTP header
+ * @ret rc Return status code
+ */
+static int http_rx_header ( struct http_request *http, char *header ) {
+ struct http_header_handler *handler;
+ char *separator;
+ char *value;
+ int rc;
+
+ /* An empty header line marks the end of this phase */
+ if ( ! header[0] ) {
+ empty_line_buffer ( &http->linebuf );
+
+ /* Handle response code */
+ if ( ! ( http->flags & HTTP_TRY_AGAIN ) ) {
+ if ( ( rc = http_response_to_rc ( http->code ) ) != 0 )
+ return rc;
+ }
+
+ /* Move to next state */
+ if ( http->rx_state == HTTP_RX_HEADER ) {
+ DBGC ( http, "HTTP %p start of data\n", http );
+ http->rx_state = ( http->chunked ?
+ HTTP_RX_CHUNK_LEN : HTTP_RX_DATA );
+ if ( ( http->partial_len != 0 ) &&
+ ( ! ( http->flags & HTTP_TRY_AGAIN ) ) ) {
+ http->remaining = http->partial_len;
+ }
+ return 0;
+ } else {
+ DBGC ( http, "HTTP %p end of trailer\n", http );
+ http_done ( http );
+ return 0;
+ }
+ }
+
+ DBGC ( http, "HTTP %p header \"%s\"\n", http, header );
+
+ /* Split header at the ": " */
+ separator = strstr ( header, ": " );
+ if ( ! separator ) {
+ DBGC ( http, "HTTP %p malformed header\n", http );
+ return -EINVAL_HEADER;
+ }
+ *separator = '\0';
+ value = ( separator + 2 );
+
+ /* Hand off to header handler, if one exists */
+ for ( handler = http_header_handlers ; handler->header ; handler++ ) {
+ if ( strcasecmp ( header, handler->header ) == 0 ) {
+ if ( ( rc = handler->rx ( http, value ) ) != 0 )
+ return rc;
+ break;
+ }
+ }
+ return 0;
+}
+
+/**
+ * Handle HTTP chunk length
+ *
+ * @v http HTTP request
+ * @v length HTTP chunk length
+ * @ret rc Return status code
+ */
+static int http_rx_chunk_len ( struct http_request *http, char *length ) {
+ char *endp;
+
+ /* Skip blank lines between chunks */
+ if ( length[0] == '\0' )
+ return 0;
+
+ /* Parse chunk length */
+ http->chunk_remaining = strtoul ( length, &endp, 16 );
+ if ( *endp != '\0' ) {
+ DBGC ( http, "HTTP %p invalid chunk length \"%s\"\n",
+ http, length );
+ return -EINVAL_CHUNK_LENGTH;
+ }
+
+ /* Terminate chunked encoding if applicable */
+ if ( http->chunk_remaining == 0 ) {
+ DBGC ( http, "HTTP %p end of chunks\n", http );
+ http->chunked = 0;
+ http->rx_state = HTTP_RX_TRAILER;
+ return 0;
+ }
+
+ /* Use seek() to notify recipient of new filesize */
+ DBGC ( http, "HTTP %p start of chunk of length %zd\n",
+ http, http->chunk_remaining );
+ if ( ! ( http->flags & HTTP_TRY_AGAIN ) ) {
+ xfer_seek ( &http->xfer,
+ ( http->rx_len + http->chunk_remaining ) );
+ xfer_seek ( &http->xfer, http->rx_len );
+ }
+
+ /* Start receiving data */
+ http->rx_state = HTTP_RX_DATA;
+
+ return 0;
+}
+
+/** An HTTP line-based data handler */
+struct http_line_handler {
+ /** Handle line
+ *
+ * @v http HTTP request
+ * @v line Line to handle
+ * @ret rc Return status code
+ */
+ int ( * rx ) ( struct http_request *http, char *line );
+};
+
+/** List of HTTP line-based data handlers */
+static struct http_line_handler http_line_handlers[] = {
+ [HTTP_RX_RESPONSE] = { .rx = http_rx_response },
+ [HTTP_RX_HEADER] = { .rx = http_rx_header },
+ [HTTP_RX_CHUNK_LEN] = { .rx = http_rx_chunk_len },
+ [HTTP_RX_TRAILER] = { .rx = http_rx_header },
+};
+
+/**
+ * Handle new data arriving via HTTP connection
+ *
+ * @v http HTTP request
+ * @v iobuf I/O buffer
+ * @v meta Data transfer metadata
+ * @ret rc Return status code
+ */
+static int http_socket_deliver ( struct http_request *http,
+ struct io_buffer *iobuf,
+ struct xfer_metadata *meta __unused ) {
+ struct http_line_handler *lh;
+ char *line;
+ size_t data_len;
+ ssize_t line_len;
+ int rc = 0;
+
+ profile_start ( &http_rx_profiler );
+ while ( iobuf && iob_len ( iobuf ) ) {
+
+ switch ( http->rx_state ) {
+ case HTTP_RX_IDLE:
+ /* Receiving any data in this state is an error */
+ DBGC ( http, "HTTP %p received %zd bytes while %s\n",
+ http, iob_len ( iobuf ),
+ ( ( http->rx_state == HTTP_RX_IDLE ) ?
+ "idle" : "dead" ) );
+ rc = -EPROTO_UNSOLICITED;
+ goto done;
+ case HTTP_RX_DEAD:
+ /* Do no further processing */
+ goto done;
+ case HTTP_RX_DATA:
+ /* Pass received data to caller */
+ data_len = iob_len ( iobuf );
+ if ( http->chunk_remaining &&
+ ( http->chunk_remaining < data_len ) ) {
+ data_len = http->chunk_remaining;
+ }
+ if ( http->remaining &&
+ ( http->remaining < data_len ) ) {
+ data_len = http->remaining;
+ }
+ if ( http->flags & HTTP_TRY_AGAIN ) {
+ /* Discard all received data */
+ iob_pull ( iobuf, data_len );
+ } else if ( http->rx_buffer != UNULL ) {
+ /* Copy to partial transfer buffer */
+ copy_to_user ( http->rx_buffer, http->rx_len,
+ iobuf->data, data_len );
+ iob_pull ( iobuf, data_len );
+ } else if ( data_len < iob_len ( iobuf ) ) {
+ /* Deliver partial buffer as raw data */
+ profile_start ( &http_xfer_profiler );
+ rc = xfer_deliver_raw ( &http->xfer,
+ iobuf->data, data_len );
+ iob_pull ( iobuf, data_len );
+ if ( rc != 0 )
+ goto done;
+ profile_stop ( &http_xfer_profiler );
+ } else {
+ /* Deliver whole I/O buffer */
+ profile_start ( &http_xfer_profiler );
+ if ( ( rc = xfer_deliver_iob ( &http->xfer,
+ iob_disown ( iobuf ) ) ) != 0 )
+ goto done;
+ profile_stop ( &http_xfer_profiler );
+ }
+ http->rx_len += data_len;
+ if ( http->chunk_remaining ) {
+ http->chunk_remaining -= data_len;
+ if ( http->chunk_remaining == 0 )
+ http->rx_state = HTTP_RX_CHUNK_LEN;
+ }
+ if ( http->remaining ) {
+ http->remaining -= data_len;
+ if ( ( http->remaining == 0 ) &&
+ ( http->rx_state == HTTP_RX_DATA ) ) {
+ http_done ( http );
+ }
+ }
+ break;
+ case HTTP_RX_RESPONSE:
+ case HTTP_RX_HEADER:
+ case HTTP_RX_CHUNK_LEN:
+ case HTTP_RX_TRAILER:
+ /* In the other phases, buffer and process a
+ * line at a time
+ */
+ line_len = line_buffer ( &http->linebuf, iobuf->data,
+ iob_len ( iobuf ) );
+ if ( line_len < 0 ) {
+ rc = line_len;
+ DBGC ( http, "HTTP %p could not buffer line: "
+ "%s\n", http, strerror ( rc ) );
+ goto done;
+ }
+ iob_pull ( iobuf, line_len );
+ line = buffered_line ( &http->linebuf );
+ if ( line ) {
+ lh = &http_line_handlers[http->rx_state];
+ if ( ( rc = lh->rx ( http, line ) ) != 0 )
+ goto done;
+ }
+ break;
+ default:
+ assert ( 0 );
+ break;
+ }
+ }
+
+ done:
+ if ( rc )
+ http_close ( http, rc );
+ free_iob ( iobuf );
+ profile_stop ( &http_rx_profiler );
+ return rc;
+}
+
+/**
+ * Check HTTP socket flow control window
+ *
+ * @v http HTTP request
+ * @ret len Length of window
+ */
+static size_t http_socket_window ( struct http_request *http __unused ) {
+
+ /* Window is always open. This is to prevent TCP from
+ * stalling if our parent window is not currently open.
+ */
+ return ( ~( ( size_t ) 0 ) );
+}
+
+/**
+ * Close HTTP socket
+ *
+ * @v http HTTP request
+ * @v rc Reason for close
+ */
+static void http_socket_close ( struct http_request *http, int rc ) {
+
+ /* If we have an error, terminate */
+ if ( rc != 0 ) {
+ http_close ( http, rc );
+ return;
+ }
+
+ /* Mark HTTP request as complete */
+ http_done ( http );
+}
+
+/**
+ * Generate HTTP Basic authorisation string
+ *
+ * @v http HTTP request
+ * @ret auth Authorisation string, or NULL on error
+ *
+ * The authorisation string is dynamically allocated, and must be
+ * freed by the caller.
+ */
+static char * http_basic_auth ( struct http_request *http ) {
+ const char *user = http->uri->user;
+ const char *password = ( http->uri->password ?
+ http->uri->password : "" );
+ size_t user_pw_len =
+ ( strlen ( user ) + 1 /* ":" */ + strlen ( password ) );
+ char user_pw[ user_pw_len + 1 /* NUL */ ];
+ size_t user_pw_base64_len = base64_encoded_len ( user_pw_len );
+ char user_pw_base64[ user_pw_base64_len + 1 /* NUL */ ];
+ char *auth;
+ int len;
+
+ /* Sanity check */
+ assert ( user != NULL );
+
+ /* Make "user:password" string from decoded fields */
+ snprintf ( user_pw, sizeof ( user_pw ), "%s:%s", user, password );
+
+ /* Base64-encode the "user:password" string */
+ base64_encode ( ( void * ) user_pw, user_pw_len, user_pw_base64 );
+
+ /* Generate the authorisation string */
+ len = asprintf ( &auth, "Authorization: Basic %s\r\n",
+ user_pw_base64 );
+ if ( len < 0 )
+ return NULL;
+
+ return auth;
+}
+
+/**
+ * Generate HTTP Digest authorisation string
+ *
+ * @v http HTTP request
+ * @v method HTTP method (e.g. "GET")
+ * @v uri HTTP request URI (e.g. "/index.html")
+ * @ret auth Authorisation string, or NULL on error
+ *
+ * The authorisation string is dynamically allocated, and must be
+ * freed by the caller.
+ */
+static char * http_digest_auth ( struct http_request *http,
+ const char *method, const char *uri ) {
+ const char *user = http->uri->user;
+ const char *password = ( http->uri->password ?
+ http->uri->password : "" );
+ const char *realm = http->auth_realm;
+ const char *nonce = http->auth_nonce;
+ const char *opaque = http->auth_opaque;
+ static const char colon = ':';
+ uint8_t ctx[MD5_CTX_SIZE];
+ uint8_t digest[MD5_DIGEST_SIZE];
+ char ha1[ base16_encoded_len ( sizeof ( digest ) ) + 1 /* NUL */ ];
+ char ha2[ base16_encoded_len ( sizeof ( digest ) ) + 1 /* NUL */ ];
+ char response[ base16_encoded_len ( sizeof ( digest ) ) + 1 /* NUL */ ];
+ char *auth;
+ int len;
+
+ /* Sanity checks */
+ assert ( user != NULL );
+ assert ( realm != NULL );
+ assert ( nonce != NULL );
+
+ /* Generate HA1 */
+ digest_init ( &md5_algorithm, ctx );
+ digest_update ( &md5_algorithm, ctx, user, strlen ( user ) );
+ digest_update ( &md5_algorithm, ctx, &colon, sizeof ( colon ) );
+ digest_update ( &md5_algorithm, ctx, realm, strlen ( realm ) );
+ digest_update ( &md5_algorithm, ctx, &colon, sizeof ( colon ) );
+ digest_update ( &md5_algorithm, ctx, password, strlen ( password ) );
+ digest_final ( &md5_algorithm, ctx, digest );
+ base16_encode ( digest, sizeof ( digest ), ha1 );
+
+ /* Generate HA2 */
+ digest_init ( &md5_algorithm, ctx );
+ digest_update ( &md5_algorithm, ctx, method, strlen ( method ) );
+ digest_update ( &md5_algorithm, ctx, &colon, sizeof ( colon ) );
+ digest_update ( &md5_algorithm, ctx, uri, strlen ( uri ) );
+ digest_final ( &md5_algorithm, ctx, digest );
+ base16_encode ( digest, sizeof ( digest ), ha2 );
+
+ /* Generate response */
+ digest_init ( &md5_algorithm, ctx );
+ digest_update ( &md5_algorithm, ctx, ha1, strlen ( ha1 ) );
+ digest_update ( &md5_algorithm, ctx, &colon, sizeof ( colon ) );
+ digest_update ( &md5_algorithm, ctx, nonce, strlen ( nonce ) );
+ digest_update ( &md5_algorithm, ctx, &colon, sizeof ( colon ) );
+ digest_update ( &md5_algorithm, ctx, ha2, strlen ( ha2 ) );
+ digest_final ( &md5_algorithm, ctx, digest );
+ base16_encode ( digest, sizeof ( digest ), response );
+
+ /* Generate the authorisation string */
+ len = asprintf ( &auth, "Authorization: Digest username=\"%s\", "
+ "realm=\"%s\", nonce=\"%s\", uri=\"%s\", "
+ "%s%s%sresponse=\"%s\"\r\n", user, realm, nonce, uri,
+ ( opaque ? "opaque=\"" : "" ),
+ ( opaque ? opaque : "" ),
+ ( opaque ? "\", " : "" ), response );
+ if ( len < 0 )
+ return NULL;
+
+ return auth;
+}
+
+/**
+ * Generate HTTP POST parameter list
+ *
+ * @v http HTTP request
+ * @v buf Buffer to contain HTTP POST parameters
+ * @v len Length of buffer
+ * @ret len Length of parameter list (excluding terminating NUL)
+ */
+static size_t http_post_params ( struct http_request *http,
+ char *buf, size_t len ) {
+ struct parameter *param;
+ ssize_t remaining = len;
+ size_t frag_len;
+
+ /* Add each parameter in the form "key=value", joined with "&" */
+ len = 0;
+ for_each_param ( param, http->uri->params ) {
+
+ /* Add the "&", if applicable */
+ if ( len ) {
+ if ( remaining > 0 )
+ *buf = '&';
+ buf++;
+ len++;
+ remaining--;
+ }
+
+ /* URI-encode the key */
+ frag_len = uri_encode ( param->key, 0, buf, remaining );
+ buf += frag_len;
+ len += frag_len;
+ remaining -= frag_len;
+
+ /* Add the "=" */
+ if ( remaining > 0 )
+ *buf = '=';
+ buf++;
+ len++;
+ remaining--;
+
+ /* URI-encode the value */
+ frag_len = uri_encode ( param->value, 0, buf, remaining );
+ buf += frag_len;
+ len += frag_len;
+ remaining -= frag_len;
+ }
+
+ /* Ensure string is NUL-terminated even if no parameters are present */
+ if ( remaining > 0 )
+ *buf = '\0';
+
+ return len;
+}
+
+/**
+ * Generate HTTP POST body
+ *
+ * @v http HTTP request
+ * @ret post I/O buffer containing POST body, or NULL on error
+ */
+static struct io_buffer * http_post ( struct http_request *http ) {
+ struct io_buffer *post;
+ size_t len;
+ size_t check_len;
+
+ /* Calculate length of parameter list */
+ len = http_post_params ( http, NULL, 0 );
+
+ /* Allocate parameter list */
+ post = alloc_iob ( len + 1 /* NUL */ );
+ if ( ! post )
+ return NULL;
+
+ /* Fill parameter list */
+ check_len = http_post_params ( http, iob_put ( post, len ),
+ ( len + 1 /* NUL */ ) );
+ assert ( len == check_len );
+ DBGC ( http, "HTTP %p POST %s\n", http, ( ( char * ) post->data ) );
+
+ return post;
+}
+
+/**
+ * HTTP process
+ *
+ * @v http HTTP request
+ */
+static void http_step ( struct http_request *http ) {
+ struct io_buffer *post;
+ struct uri host_uri;
+ struct uri path_uri;
+ char *host_uri_string;
+ char *path_uri_string;
+ char *method;
+ char *range;
+ char *auth;
+ char *content;
+ int len;
+ int rc;
+
+ /* Do nothing if we have already transmitted the request */
+ if ( ! ( http->flags & HTTP_TX_PENDING ) )
+ return;
+
+ /* Do nothing until socket is ready */
+ if ( ! xfer_window ( &http->socket ) )
+ return;
+
+ /* Force a HEAD request if we have nowhere to send any received data */
+ if ( ( xfer_window ( &http->xfer ) == 0 ) &&
+ ( http->rx_buffer == UNULL ) ) {
+ http->flags |= ( HTTP_HEAD_ONLY | HTTP_CLIENT_KEEPALIVE );
+ }
+
+ /* Determine method */
+ method = ( ( http->flags & HTTP_HEAD_ONLY ) ? "HEAD" :
+ ( http->uri->params ? "POST" : "GET" ) );
+
+ /* Construct host URI */
+ memset ( &host_uri, 0, sizeof ( host_uri ) );
+ host_uri.host = http->uri->host;
+ host_uri.port = http->uri->port;
+ host_uri_string = format_uri_alloc ( &host_uri );
+ if ( ! host_uri_string ) {
+ rc = -ENOMEM;
+ goto err_host_uri;
+ }
+
+ /* Construct path URI */
+ memset ( &path_uri, 0, sizeof ( path_uri ) );
+ path_uri.path = ( http->uri->path ? http->uri->path : "/" );
+ path_uri.query = http->uri->query;
+ path_uri_string = format_uri_alloc ( &path_uri );
+ if ( ! path_uri_string ) {
+ rc = -ENOMEM;
+ goto err_path_uri;
+ }
+
+ /* Calculate range request parameters if applicable */
+ if ( http->partial_len ) {
+ len = asprintf ( &range, "Range: bytes=%zd-%zd\r\n",
+ http->partial_start,
+ ( http->partial_start + http->partial_len
+ - 1 ) );
+ if ( len < 0 ) {
+ rc = len;
+ goto err_range;
+ }
+ } else {
+ range = NULL;
+ }
+
+ /* Construct authorisation, if applicable */
+ if ( http->flags & HTTP_BASIC_AUTH ) {
+ auth = http_basic_auth ( http );
+ if ( ! auth ) {
+ rc = -ENOMEM;
+ goto err_auth;
+ }
+ } else if ( http->flags & HTTP_DIGEST_AUTH ) {
+ auth = http_digest_auth ( http, method, path_uri_string );
+ if ( ! auth ) {
+ rc = -ENOMEM;
+ goto err_auth;
+ }
+ } else {
+ auth = NULL;
+ }
+
+ /* Construct POST content, if applicable */
+ if ( http->uri->params ) {
+ post = http_post ( http );
+ if ( ! post ) {
+ rc = -ENOMEM;
+ goto err_post;
+ }
+ len = asprintf ( &content, "Content-Type: "
+ "application/x-www-form-urlencoded\r\n"
+ "Content-Length: %zd\r\n", iob_len ( post ) );
+ if ( len < 0 ) {
+ rc = len;
+ goto err_content;
+ }
+ } else {
+ post = NULL;
+ content = NULL;
+ }
+
+ /* Mark request as transmitted */
+ http->flags &= ~HTTP_TX_PENDING;
+
+ /* Send request */
+ if ( ( rc = xfer_printf ( &http->socket,
+ "%s %s HTTP/1.1\r\n"
+ "User-Agent: iPXE/%s\r\n"
+ "Host: %s\r\n"
+ "%s%s%s%s"
+ "\r\n",
+ method, path_uri_string, product_version,
+ host_uri_string,
+ ( ( http->flags & HTTP_CLIENT_KEEPALIVE ) ?
+ "Connection: keep-alive\r\n" : "" ),
+ ( range ? range : "" ),
+ ( auth ? auth : "" ),
+ ( content ? content : "" ) ) ) != 0 ) {
+ goto err_xfer;
+ }
+
+ /* Send POST content, if applicable */
+ if ( post ) {
+ if ( ( rc = xfer_deliver_iob ( &http->socket,
+ iob_disown ( post ) ) ) != 0 )
+ goto err_xfer_post;
+ }
+
+ err_xfer_post:
+ err_xfer:
+ free ( content );
+ err_content:
+ free ( post );
+ err_post:
+ free ( auth );
+ err_auth:
+ free ( range );
+ err_range:
+ free ( path_uri_string );
+ err_path_uri:
+ free ( host_uri_string );
+ err_host_uri:
+ if ( rc != 0 )
+ http_close ( http, rc );
+}
+
+/**
+ * Check HTTP data transfer flow control window
+ *
+ * @v http HTTP request
+ * @ret len Length of window
+ */
+static size_t http_xfer_window ( struct http_request *http ) {
+
+ /* New block commands may be issued only when we are idle */
+ return ( ( http->rx_state == HTTP_RX_IDLE ) ? 1 : 0 );
+}
+
+/**
+ * Initiate HTTP partial read
+ *
+ * @v http HTTP request
+ * @v partial Partial transfer interface
+ * @v offset Starting offset
+ * @v buffer Data buffer
+ * @v len Length
+ * @ret rc Return status code
+ */
+static int http_partial_read ( struct http_request *http,
+ struct interface *partial,
+ size_t offset, userptr_t buffer, size_t len ) {
+
+ /* Sanity check */
+ if ( http_xfer_window ( http ) == 0 )
+ return -EBUSY;
+
+ /* Initialise partial transfer parameters */
+ http->rx_buffer = buffer;
+ http->partial_start = offset;
+ http->partial_len = len;
+
+ /* Schedule request */
+ http->rx_state = HTTP_RX_RESPONSE;
+ http->flags = ( HTTP_TX_PENDING | HTTP_CLIENT_KEEPALIVE );
+ if ( ! len )
+ http->flags |= HTTP_HEAD_ONLY;
+ process_add ( &http->process );
+
+ /* Attach to parent interface and return */
+ intf_plug_plug ( &http->partial, partial );
+
+ return 0;
+}
+
+/**
+ * Issue HTTP block device read
+ *
+ * @v http HTTP request
+ * @v block Block data interface
+ * @v lba Starting logical block address
+ * @v count Number of blocks to transfer
+ * @v buffer Data buffer
+ * @v len Length of data buffer
+ * @ret rc Return status code
+ */
+static int http_block_read ( struct http_request *http,
+ struct interface *block,
+ uint64_t lba, unsigned int count,
+ userptr_t buffer, size_t len __unused ) {
+
+ return http_partial_read ( http, block, ( lba * HTTP_BLKSIZE ),
+ buffer, ( count * HTTP_BLKSIZE ) );
+}
+
+/**
+ * Read HTTP block device capacity
+ *
+ * @v http HTTP request
+ * @v block Block data interface
+ * @ret rc Return status code
+ */
+static int http_block_read_capacity ( struct http_request *http,
+ struct interface *block ) {
+
+ return http_partial_read ( http, block, 0, 0, 0 );
+}
+
+/**
+ * Describe HTTP device in an ACPI table
+ *
+ * @v http HTTP request
+ * @v acpi ACPI table
+ * @v len Length of ACPI table
+ * @ret rc Return status code
+ */
+static int http_acpi_describe ( struct http_request *http,
+ struct acpi_description_header *acpi,
+ size_t len ) {
+
+ DBGC ( http, "HTTP %p cannot yet describe device in an ACPI table\n",
+ http );
+ ( void ) acpi;
+ ( void ) len;
+ return 0;
+}
+
+/** HTTP socket interface operations */
+static struct interface_operation http_socket_operations[] = {
+ INTF_OP ( xfer_window, struct http_request *, http_socket_window ),
+ INTF_OP ( xfer_deliver, struct http_request *, http_socket_deliver ),
+ INTF_OP ( xfer_window_changed, struct http_request *, http_step ),
+ INTF_OP ( intf_close, struct http_request *, http_socket_close ),
+};
+
+/** HTTP socket interface descriptor */
+static struct interface_descriptor http_socket_desc =
+ INTF_DESC_PASSTHRU ( struct http_request, socket,
+ http_socket_operations, xfer );
+
+/** HTTP partial transfer interface operations */
+static struct interface_operation http_partial_operations[] = {
+ INTF_OP ( intf_close, struct http_request *, http_close ),
+};
+
+/** HTTP partial transfer interface descriptor */
+static struct interface_descriptor http_partial_desc =
+ INTF_DESC ( struct http_request, partial, http_partial_operations );
+
+/** HTTP data transfer interface operations */
+static struct interface_operation http_xfer_operations[] = {
+ INTF_OP ( xfer_window, struct http_request *, http_xfer_window ),
+ INTF_OP ( block_read, struct http_request *, http_block_read ),
+ INTF_OP ( block_read_capacity, struct http_request *,
+ http_block_read_capacity ),
+ INTF_OP ( intf_close, struct http_request *, http_close ),
+ INTF_OP ( acpi_describe, struct http_request *, http_acpi_describe ),
+};
+
+/** HTTP data transfer interface descriptor */
+static struct interface_descriptor http_xfer_desc =
+ INTF_DESC_PASSTHRU ( struct http_request, xfer,
+ http_xfer_operations, socket );
+
+/** HTTP process descriptor */
+static struct process_descriptor http_process_desc =
+ PROC_DESC_ONCE ( struct http_request, process, http_step );
+
+/**
+ * Initiate an HTTP connection, with optional filter
+ *
+ * @v xfer Data transfer interface
+ * @v uri Uniform Resource Identifier
+ * @v default_port Default port number
+ * @v filter Filter to apply to socket, or NULL
+ * @ret rc Return status code
+ */
+int http_open_filter ( struct interface *xfer, struct uri *uri,
+ unsigned int default_port,
+ int ( * filter ) ( struct interface *xfer,
+ const char *name,
+ struct interface **next ) ) {
+ struct http_request *http;
+ int rc;
+
+ /* Sanity checks */
+ if ( ! uri->host )
+ return -EINVAL;
+
+ /* Allocate and populate HTTP structure */
+ http = zalloc ( sizeof ( *http ) );
+ if ( ! http )
+ return -ENOMEM;
+ ref_init ( &http->refcnt, http_free );
+ intf_init ( &http->xfer, &http_xfer_desc, &http->refcnt );
+ intf_init ( &http->partial, &http_partial_desc, &http->refcnt );
+ http->uri = uri_get ( uri );
+ http->default_port = default_port;
+ http->filter = filter;
+ intf_init ( &http->socket, &http_socket_desc, &http->refcnt );
+ process_init ( &http->process, &http_process_desc, &http->refcnt );
+ timer_init ( &http->timer, http_retry, &http->refcnt );
+ http->flags = HTTP_TX_PENDING;
+
+ /* Open socket */
+ if ( ( rc = http_socket_open ( http ) ) != 0 )
+ goto err;
+
+ /* Attach to parent interface, mortalise self, and return */
+ intf_plug_plug ( &http->xfer, xfer );
+ ref_put ( &http->refcnt );
+ return 0;
+
+ err:
+ DBGC ( http, "HTTP %p could not create request: %s\n",
+ http, strerror ( rc ) );
+ http_close ( http, rc );
+ ref_put ( &http->refcnt );
+ return rc;
+}
diff --git a/qemu/roms/ipxe/src/net/tcp/https.c b/qemu/roms/ipxe/src/net/tcp/https.c
new file mode 100644
index 000000000..6112acdae
--- /dev/null
+++ b/qemu/roms/ipxe/src/net/tcp/https.c
@@ -0,0 +1,52 @@
+/*
+ * Copyright (C) 2007 Michael Brown <mbrown@fensystems.co.uk>.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation; either version 2 of the
+ * License, or any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+FILE_LICENCE ( GPL2_OR_LATER );
+
+/**
+ * @file
+ *
+ * Secure Hyper Text Transfer Protocol (HTTPS)
+ *
+ */
+
+#include <stddef.h>
+#include <ipxe/open.h>
+#include <ipxe/tls.h>
+#include <ipxe/http.h>
+#include <ipxe/features.h>
+
+FEATURE ( FEATURE_PROTOCOL, "HTTPS", DHCP_EB_FEATURE_HTTPS, 1 );
+
+/**
+ * Initiate an HTTPS connection
+ *
+ * @v xfer Data transfer interface
+ * @v uri Uniform Resource Identifier
+ * @ret rc Return status code
+ */
+static int https_open ( struct interface *xfer, struct uri *uri ) {
+ return http_open_filter ( xfer, uri, HTTPS_PORT, add_tls );
+}
+
+/** HTTPS URI opener */
+struct uri_opener https_uri_opener __uri_opener = {
+ .scheme = "https",
+ .open = https_open,
+};
diff --git a/qemu/roms/ipxe/src/net/tcp/iscsi.c b/qemu/roms/ipxe/src/net/tcp/iscsi.c
new file mode 100644
index 000000000..03c6d0f23
--- /dev/null
+++ b/qemu/roms/ipxe/src/net/tcp/iscsi.c
@@ -0,0 +1,2126 @@
+/*
+ * Copyright (C) 2006 Michael Brown <mbrown@fensystems.co.uk>.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation; either version 2 of the
+ * License, or any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+FILE_LICENCE ( GPL2_OR_LATER );
+
+#include <stddef.h>
+#include <string.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <errno.h>
+#include <assert.h>
+#include <byteswap.h>
+#include <ipxe/vsprintf.h>
+#include <ipxe/socket.h>
+#include <ipxe/iobuf.h>
+#include <ipxe/uri.h>
+#include <ipxe/xfer.h>
+#include <ipxe/open.h>
+#include <ipxe/scsi.h>
+#include <ipxe/process.h>
+#include <ipxe/uaccess.h>
+#include <ipxe/tcpip.h>
+#include <ipxe/settings.h>
+#include <ipxe/features.h>
+#include <ipxe/base16.h>
+#include <ipxe/base64.h>
+#include <ipxe/ibft.h>
+#include <ipxe/iscsi.h>
+
+/** @file
+ *
+ * iSCSI protocol
+ *
+ */
+
+FEATURE ( FEATURE_PROTOCOL, "iSCSI", DHCP_EB_FEATURE_ISCSI, 1 );
+
+/* Disambiguate the various error causes */
+#define EACCES_INCORRECT_TARGET_USERNAME \
+ __einfo_error ( EINFO_EACCES_INCORRECT_TARGET_USERNAME )
+#define EINFO_EACCES_INCORRECT_TARGET_USERNAME \
+ __einfo_uniqify ( EINFO_EACCES, 0x01, "Incorrect target username" )
+#define EACCES_INCORRECT_TARGET_PASSWORD \
+ __einfo_error ( EINFO_EACCES_INCORRECT_TARGET_PASSWORD )
+#define EINFO_EACCES_INCORRECT_TARGET_PASSWORD \
+ __einfo_uniqify ( EINFO_EACCES, 0x02, "Incorrect target password" )
+#define EINVAL_ROOT_PATH_TOO_SHORT \
+ __einfo_error ( EINFO_EINVAL_ROOT_PATH_TOO_SHORT )
+#define EINFO_EINVAL_ROOT_PATH_TOO_SHORT \
+ __einfo_uniqify ( EINFO_EINVAL, 0x01, "Root path too short" )
+#define EINVAL_BAD_CREDENTIAL_MIX \
+ __einfo_error ( EINFO_EINVAL_BAD_CREDENTIAL_MIX )
+#define EINFO_EINVAL_BAD_CREDENTIAL_MIX \
+ __einfo_uniqify ( EINFO_EINVAL, 0x02, "Bad credential mix" )
+#define EINVAL_NO_ROOT_PATH \
+ __einfo_error ( EINFO_EINVAL_NO_ROOT_PATH )
+#define EINFO_EINVAL_NO_ROOT_PATH \
+ __einfo_uniqify ( EINFO_EINVAL, 0x03, "No root path" )
+#define EINVAL_NO_TARGET_IQN \
+ __einfo_error ( EINFO_EINVAL_NO_TARGET_IQN )
+#define EINFO_EINVAL_NO_TARGET_IQN \
+ __einfo_uniqify ( EINFO_EINVAL, 0x04, "No target IQN" )
+#define EINVAL_NO_INITIATOR_IQN \
+ __einfo_error ( EINFO_EINVAL_NO_INITIATOR_IQN )
+#define EINFO_EINVAL_NO_INITIATOR_IQN \
+ __einfo_uniqify ( EINFO_EINVAL, 0x05, "No initiator IQN" )
+#define EIO_TARGET_UNAVAILABLE \
+ __einfo_error ( EINFO_EIO_TARGET_UNAVAILABLE )
+#define EINFO_EIO_TARGET_UNAVAILABLE \
+ __einfo_uniqify ( EINFO_EIO, 0x01, "Target not currently operational" )
+#define EIO_TARGET_NO_RESOURCES \
+ __einfo_error ( EINFO_EIO_TARGET_NO_RESOURCES )
+#define EINFO_EIO_TARGET_NO_RESOURCES \
+ __einfo_uniqify ( EINFO_EIO, 0x02, "Target out of resources" )
+#define ENOTSUP_INITIATOR_STATUS \
+ __einfo_error ( EINFO_ENOTSUP_INITIATOR_STATUS )
+#define EINFO_ENOTSUP_INITIATOR_STATUS \
+ __einfo_uniqify ( EINFO_ENOTSUP, 0x01, "Unsupported initiator status" )
+#define ENOTSUP_OPCODE \
+ __einfo_error ( EINFO_ENOTSUP_OPCODE )
+#define EINFO_ENOTSUP_OPCODE \
+ __einfo_uniqify ( EINFO_ENOTSUP, 0x02, "Unsupported opcode" )
+#define ENOTSUP_DISCOVERY \
+ __einfo_error ( EINFO_ENOTSUP_DISCOVERY )
+#define EINFO_ENOTSUP_DISCOVERY \
+ __einfo_uniqify ( EINFO_ENOTSUP, 0x03, "Discovery not supported" )
+#define ENOTSUP_TARGET_STATUS \
+ __einfo_error ( EINFO_ENOTSUP_TARGET_STATUS )
+#define EINFO_ENOTSUP_TARGET_STATUS \
+ __einfo_uniqify ( EINFO_ENOTSUP, 0x04, "Unsupported target status" )
+#define ENOTSUP_NOP_IN \
+ __einfo_error ( EINFO_ENOTSUP_NOP_IN )
+#define EINFO_ENOTSUP_NOP_IN \
+ __einfo_uniqify ( EINFO_ENOTSUP, 0x05, "Unsupported NOP-In received" )
+#define EPERM_INITIATOR_AUTHENTICATION \
+ __einfo_error ( EINFO_EPERM_INITIATOR_AUTHENTICATION )
+#define EINFO_EPERM_INITIATOR_AUTHENTICATION \
+ __einfo_uniqify ( EINFO_EPERM, 0x01, "Initiator authentication failed" )
+#define EPERM_INITIATOR_AUTHORISATION \
+ __einfo_error ( EINFO_EPERM_INITIATOR_AUTHORISATION )
+#define EINFO_EPERM_INITIATOR_AUTHORISATION \
+ __einfo_uniqify ( EINFO_EPERM, 0x02, "Initiator not authorised" )
+#define EPROTO_INVALID_CHAP_ALGORITHM \
+ __einfo_error ( EINFO_EPROTO_INVALID_CHAP_ALGORITHM )
+#define EINFO_EPROTO_INVALID_CHAP_ALGORITHM \
+ __einfo_uniqify ( EINFO_EPROTO, 0x01, "Invalid CHAP algorithm" )
+#define EPROTO_INVALID_CHAP_IDENTIFIER \
+ __einfo_error ( EINFO_EPROTO_INVALID_CHAP_IDENTIFIER )
+#define EINFO_EPROTO_INVALID_CHAP_IDENTIFIER \
+ __einfo_uniqify ( EINFO_EPROTO, 0x02, "Invalid CHAP identifier" )
+#define EPROTO_INVALID_LARGE_BINARY \
+ __einfo_error ( EINFO_EPROTO_INVALID_LARGE_BINARY )
+#define EINFO_EPROTO_INVALID_LARGE_BINARY \
+ __einfo_uniqify ( EINFO_EPROTO, 0x03, "Invalid large binary" )
+#define EPROTO_INVALID_CHAP_RESPONSE \
+ __einfo_error ( EINFO_EPROTO_INVALID_CHAP_RESPONSE )
+#define EINFO_EPROTO_INVALID_CHAP_RESPONSE \
+ __einfo_uniqify ( EINFO_EPROTO, 0x04, "Invalid CHAP response" )
+#define EPROTO_INVALID_KEY_VALUE_PAIR \
+ __einfo_error ( EINFO_EPROTO_INVALID_KEY_VALUE_PAIR )
+#define EINFO_EPROTO_INVALID_KEY_VALUE_PAIR \
+ __einfo_uniqify ( EINFO_EPROTO, 0x05, "Invalid key/value pair" )
+#define EPROTO_VALUE_REJECTED \
+ __einfo_error ( EINFO_EPROTO_VALUE_REJECTED )
+#define EINFO_EPROTO_VALUE_REJECTED \
+ __einfo_uniqify ( EINFO_EPROTO, 0x06, "Parameter rejected" )
+
+static void iscsi_start_tx ( struct iscsi_session *iscsi );
+static void iscsi_start_login ( struct iscsi_session *iscsi );
+static void iscsi_start_data_out ( struct iscsi_session *iscsi,
+ unsigned int datasn );
+
+/**
+ * Finish receiving PDU data into buffer
+ *
+ * @v iscsi iSCSI session
+ */
+static void iscsi_rx_buffered_data_done ( struct iscsi_session *iscsi ) {
+ free ( iscsi->rx_buffer );
+ iscsi->rx_buffer = NULL;
+}
+
+/**
+ * Receive PDU data into buffer
+ *
+ * @v iscsi iSCSI session
+ * @v data Data to receive
+ * @v len Length of data
+ * @ret rc Return status code
+ *
+ * This can be used when the RX PDU type handler wishes to buffer up
+ * all received data and process the PDU as a single unit. The caller
+ * is repsonsible for calling iscsi_rx_buffered_data_done() after
+ * processing the data.
+ */
+static int iscsi_rx_buffered_data ( struct iscsi_session *iscsi,
+ const void *data, size_t len ) {
+
+ /* Allocate buffer on first call */
+ if ( ! iscsi->rx_buffer ) {
+ iscsi->rx_buffer = malloc ( iscsi->rx_len );
+ if ( ! iscsi->rx_buffer )
+ return -ENOMEM;
+ }
+
+ /* Copy data to buffer */
+ assert ( ( iscsi->rx_offset + len ) <= iscsi->rx_len );
+ memcpy ( ( iscsi->rx_buffer + iscsi->rx_offset ), data, len );
+
+ return 0;
+}
+
+/**
+ * Free iSCSI session
+ *
+ * @v refcnt Reference counter
+ */
+static void iscsi_free ( struct refcnt *refcnt ) {
+ struct iscsi_session *iscsi =
+ container_of ( refcnt, struct iscsi_session, refcnt );
+
+ free ( iscsi->initiator_iqn );
+ free ( iscsi->target_address );
+ free ( iscsi->target_iqn );
+ free ( iscsi->initiator_username );
+ free ( iscsi->initiator_password );
+ free ( iscsi->target_username );
+ free ( iscsi->target_password );
+ chap_finish ( &iscsi->chap );
+ iscsi_rx_buffered_data_done ( iscsi );
+ free ( iscsi->command );
+ free ( iscsi );
+}
+
+/**
+ * Shut down iSCSI interface
+ *
+ * @v iscsi iSCSI session
+ * @v rc Reason for close
+ */
+static void iscsi_close ( struct iscsi_session *iscsi, int rc ) {
+
+ /* A TCP graceful close is still an error from our point of view */
+ if ( rc == 0 )
+ rc = -ECONNRESET;
+
+ DBGC ( iscsi, "iSCSI %p closed: %s\n", iscsi, strerror ( rc ) );
+
+ /* Stop transmission process */
+ process_del ( &iscsi->process );
+
+ /* Shut down interfaces */
+ intf_shutdown ( &iscsi->socket, rc );
+ intf_shutdown ( &iscsi->control, rc );
+ intf_shutdown ( &iscsi->data, rc );
+}
+
+/**
+ * Assign new iSCSI initiator task tag
+ *
+ * @v iscsi iSCSI session
+ */
+static void iscsi_new_itt ( struct iscsi_session *iscsi ) {
+ static uint16_t itt_idx;
+
+ iscsi->itt = ( ISCSI_TAG_MAGIC | (++itt_idx) );
+}
+
+/**
+ * Open iSCSI transport-layer connection
+ *
+ * @v iscsi iSCSI session
+ * @ret rc Return status code
+ */
+static int iscsi_open_connection ( struct iscsi_session *iscsi ) {
+ struct sockaddr_tcpip target;
+ int rc;
+
+ assert ( iscsi->tx_state == ISCSI_TX_IDLE );
+ assert ( iscsi->rx_state == ISCSI_RX_BHS );
+ assert ( iscsi->rx_offset == 0 );
+
+ /* Open socket */
+ memset ( &target, 0, sizeof ( target ) );
+ target.st_port = htons ( iscsi->target_port );
+ if ( ( rc = xfer_open_named_socket ( &iscsi->socket, SOCK_STREAM,
+ ( struct sockaddr * ) &target,
+ iscsi->target_address,
+ NULL ) ) != 0 ) {
+ DBGC ( iscsi, "iSCSI %p could not open socket: %s\n",
+ iscsi, strerror ( rc ) );
+ return rc;
+ }
+
+ /* Enter security negotiation phase */
+ iscsi->status = ( ISCSI_STATUS_SECURITY_NEGOTIATION_PHASE |
+ ISCSI_STATUS_STRINGS_SECURITY );
+ if ( iscsi->target_username )
+ iscsi->status |= ISCSI_STATUS_AUTH_REVERSE_REQUIRED;
+
+ /* Assign new ISID */
+ iscsi->isid_iana_qual = ( random() & 0xffff );
+
+ /* Assign fresh initiator task tag */
+ iscsi_new_itt ( iscsi );
+
+ /* Initiate login */
+ iscsi_start_login ( iscsi );
+
+ return 0;
+}
+
+/**
+ * Close iSCSI transport-layer connection
+ *
+ * @v iscsi iSCSI session
+ * @v rc Reason for close
+ *
+ * Closes the transport-layer connection and resets the session state
+ * ready to attempt a fresh login.
+ */
+static void iscsi_close_connection ( struct iscsi_session *iscsi, int rc ) {
+
+ /* Close all data transfer interfaces */
+ intf_restart ( &iscsi->socket, rc );
+
+ /* Clear connection status */
+ iscsi->status = 0;
+
+ /* Reset TX and RX state machines */
+ iscsi->tx_state = ISCSI_TX_IDLE;
+ iscsi->rx_state = ISCSI_RX_BHS;
+ iscsi->rx_offset = 0;
+
+ /* Free any temporary dynamically allocated memory */
+ chap_finish ( &iscsi->chap );
+ iscsi_rx_buffered_data_done ( iscsi );
+}
+
+/**
+ * Mark iSCSI SCSI operation as complete
+ *
+ * @v iscsi iSCSI session
+ * @v rc Return status code
+ * @v rsp SCSI response, if any
+ *
+ * Note that iscsi_scsi_done() will not close the connection, and must
+ * therefore be called only when the internal state machines are in an
+ * appropriate state, otherwise bad things may happen on the next call
+ * to iscsi_scsi_command(). The general rule is to call
+ * iscsi_scsi_done() only at the end of receiving a PDU; at this point
+ * the TX and RX engines should both be idle.
+ */
+static void iscsi_scsi_done ( struct iscsi_session *iscsi, int rc,
+ struct scsi_rsp *rsp ) {
+ uint32_t itt = iscsi->itt;
+
+ assert ( iscsi->tx_state == ISCSI_TX_IDLE );
+
+ /* Clear command */
+ free ( iscsi->command );
+ iscsi->command = NULL;
+
+ /* Send SCSI response, if any */
+ if ( rsp )
+ scsi_response ( &iscsi->data, rsp );
+
+ /* Close SCSI command, if this is still the same command. (It
+ * is possible that the command interface has already been
+ * closed as a result of the SCSI response we sent.)
+ */
+ if ( iscsi->itt == itt )
+ intf_restart ( &iscsi->data, rc );
+}
+
+/****************************************************************************
+ *
+ * iSCSI SCSI command issuing
+ *
+ */
+
+/**
+ * Build iSCSI SCSI command BHS
+ *
+ * @v iscsi iSCSI session
+ *
+ * We don't currently support bidirectional commands (i.e. with both
+ * Data-In and Data-Out segments); these would require providing code
+ * to generate an AHS, and there doesn't seem to be any need for it at
+ * the moment.
+ */
+static void iscsi_start_command ( struct iscsi_session *iscsi ) {
+ struct iscsi_bhs_scsi_command *command = &iscsi->tx_bhs.scsi_command;
+
+ assert ( ! ( iscsi->command->data_in && iscsi->command->data_out ) );
+
+ /* Construct BHS and initiate transmission */
+ iscsi_start_tx ( iscsi );
+ command->opcode = ISCSI_OPCODE_SCSI_COMMAND;
+ command->flags = ( ISCSI_FLAG_FINAL |
+ ISCSI_COMMAND_ATTR_SIMPLE );
+ if ( iscsi->command->data_in )
+ command->flags |= ISCSI_COMMAND_FLAG_READ;
+ if ( iscsi->command->data_out )
+ command->flags |= ISCSI_COMMAND_FLAG_WRITE;
+ /* lengths left as zero */
+ memcpy ( &command->lun, &iscsi->command->lun,
+ sizeof ( command->lun ) );
+ command->itt = htonl ( iscsi->itt );
+ command->exp_len = htonl ( iscsi->command->data_in_len |
+ iscsi->command->data_out_len );
+ command->cmdsn = htonl ( iscsi->cmdsn );
+ command->expstatsn = htonl ( iscsi->statsn + 1 );
+ memcpy ( &command->cdb, &iscsi->command->cdb, sizeof ( command->cdb ));
+ DBGC2 ( iscsi, "iSCSI %p start " SCSI_CDB_FORMAT " %s %#zx\n",
+ iscsi, SCSI_CDB_DATA ( command->cdb ),
+ ( iscsi->command->data_in ? "in" : "out" ),
+ ( iscsi->command->data_in ?
+ iscsi->command->data_in_len :
+ iscsi->command->data_out_len ) );
+}
+
+/**
+ * Receive data segment of an iSCSI SCSI response PDU
+ *
+ * @v iscsi iSCSI session
+ * @v data Received data
+ * @v len Length of received data
+ * @v remaining Data remaining after this data
+ * @ret rc Return status code
+ */
+static int iscsi_rx_scsi_response ( struct iscsi_session *iscsi,
+ const void *data, size_t len,
+ size_t remaining ) {
+ struct iscsi_bhs_scsi_response *response
+ = &iscsi->rx_bhs.scsi_response;
+ struct scsi_rsp rsp;
+ uint32_t residual_count;
+ size_t data_len;
+ int rc;
+
+ /* Buffer up the PDU data */
+ if ( ( rc = iscsi_rx_buffered_data ( iscsi, data, len ) ) != 0 ) {
+ DBGC ( iscsi, "iSCSI %p could not buffer SCSI response: %s\n",
+ iscsi, strerror ( rc ) );
+ return rc;
+ }
+ if ( remaining )
+ return 0;
+
+ /* Parse SCSI response and discard buffer */
+ memset ( &rsp, 0, sizeof ( rsp ) );
+ rsp.status = response->status;
+ residual_count = ntohl ( response->residual_count );
+ if ( response->flags & ISCSI_DATA_FLAG_OVERFLOW ) {
+ rsp.overrun = residual_count;
+ } else if ( response->flags & ISCSI_DATA_FLAG_UNDERFLOW ) {
+ rsp.overrun = -(residual_count);
+ }
+ data_len = ISCSI_DATA_LEN ( response->lengths );
+ if ( data_len ) {
+ scsi_parse_sense ( ( iscsi->rx_buffer + 2 ), ( data_len - 2 ),
+ &rsp.sense );
+ }
+ iscsi_rx_buffered_data_done ( iscsi );
+
+ /* Check for errors */
+ if ( response->response != ISCSI_RESPONSE_COMMAND_COMPLETE )
+ return -EIO;
+
+ /* Mark as completed */
+ iscsi_scsi_done ( iscsi, 0, &rsp );
+ return 0;
+}
+
+/**
+ * Receive data segment of an iSCSI data-in PDU
+ *
+ * @v iscsi iSCSI session
+ * @v data Received data
+ * @v len Length of received data
+ * @v remaining Data remaining after this data
+ * @ret rc Return status code
+ */
+static int iscsi_rx_data_in ( struct iscsi_session *iscsi,
+ const void *data, size_t len,
+ size_t remaining ) {
+ struct iscsi_bhs_data_in *data_in = &iscsi->rx_bhs.data_in;
+ unsigned long offset;
+
+ /* Copy data to data-in buffer */
+ offset = ntohl ( data_in->offset ) + iscsi->rx_offset;
+ assert ( iscsi->command != NULL );
+ assert ( iscsi->command->data_in );
+ assert ( ( offset + len ) <= iscsi->command->data_in_len );
+ copy_to_user ( iscsi->command->data_in, offset, data, len );
+
+ /* Wait for whole SCSI response to arrive */
+ if ( remaining )
+ return 0;
+
+ /* Mark as completed if status is present */
+ if ( data_in->flags & ISCSI_DATA_FLAG_STATUS ) {
+ assert ( ( offset + len ) == iscsi->command->data_in_len );
+ assert ( data_in->flags & ISCSI_FLAG_FINAL );
+ /* iSCSI cannot return an error status via a data-in */
+ iscsi_scsi_done ( iscsi, 0, NULL );
+ }
+
+ return 0;
+}
+
+/**
+ * Receive data segment of an iSCSI R2T PDU
+ *
+ * @v iscsi iSCSI session
+ * @v data Received data
+ * @v len Length of received data
+ * @v remaining Data remaining after this data
+ * @ret rc Return status code
+ */
+static int iscsi_rx_r2t ( struct iscsi_session *iscsi,
+ const void *data __unused, size_t len __unused,
+ size_t remaining __unused ) {
+ struct iscsi_bhs_r2t *r2t = &iscsi->rx_bhs.r2t;
+
+ /* Record transfer parameters and trigger first data-out */
+ iscsi->ttt = ntohl ( r2t->ttt );
+ iscsi->transfer_offset = ntohl ( r2t->offset );
+ iscsi->transfer_len = ntohl ( r2t->len );
+ iscsi_start_data_out ( iscsi, 0 );
+
+ return 0;
+}
+
+/**
+ * Build iSCSI data-out BHS
+ *
+ * @v iscsi iSCSI session
+ * @v datasn Data sequence number within the transfer
+ *
+ */
+static void iscsi_start_data_out ( struct iscsi_session *iscsi,
+ unsigned int datasn ) {
+ struct iscsi_bhs_data_out *data_out = &iscsi->tx_bhs.data_out;
+ unsigned long offset;
+ unsigned long remaining;
+ unsigned long len;
+
+ /* We always send 512-byte Data-Out PDUs; this removes the
+ * need to worry about the target's MaxRecvDataSegmentLength.
+ */
+ offset = datasn * 512;
+ remaining = iscsi->transfer_len - offset;
+ len = remaining;
+ if ( len > 512 )
+ len = 512;
+
+ /* Construct BHS and initiate transmission */
+ iscsi_start_tx ( iscsi );
+ data_out->opcode = ISCSI_OPCODE_DATA_OUT;
+ if ( len == remaining )
+ data_out->flags = ( ISCSI_FLAG_FINAL );
+ ISCSI_SET_LENGTHS ( data_out->lengths, 0, len );
+ data_out->lun = iscsi->command->lun;
+ data_out->itt = htonl ( iscsi->itt );
+ data_out->ttt = htonl ( iscsi->ttt );
+ data_out->expstatsn = htonl ( iscsi->statsn + 1 );
+ data_out->datasn = htonl ( datasn );
+ data_out->offset = htonl ( iscsi->transfer_offset + offset );
+ DBGC ( iscsi, "iSCSI %p start data out DataSN %#x len %#lx\n",
+ iscsi, datasn, len );
+}
+
+/**
+ * Complete iSCSI data-out PDU transmission
+ *
+ * @v iscsi iSCSI session
+ *
+ */
+static void iscsi_data_out_done ( struct iscsi_session *iscsi ) {
+ struct iscsi_bhs_data_out *data_out = &iscsi->tx_bhs.data_out;
+
+ /* If we haven't reached the end of the sequence, start
+ * sending the next data-out PDU.
+ */
+ if ( ! ( data_out->flags & ISCSI_FLAG_FINAL ) )
+ iscsi_start_data_out ( iscsi, ntohl ( data_out->datasn ) + 1 );
+}
+
+/**
+ * Send iSCSI data-out data segment
+ *
+ * @v iscsi iSCSI session
+ * @ret rc Return status code
+ */
+static int iscsi_tx_data_out ( struct iscsi_session *iscsi ) {
+ struct iscsi_bhs_data_out *data_out = &iscsi->tx_bhs.data_out;
+ struct io_buffer *iobuf;
+ unsigned long offset;
+ size_t len;
+ size_t pad_len;
+
+ offset = ntohl ( data_out->offset );
+ len = ISCSI_DATA_LEN ( data_out->lengths );
+ pad_len = ISCSI_DATA_PAD_LEN ( data_out->lengths );
+
+ assert ( iscsi->command != NULL );
+ assert ( iscsi->command->data_out );
+ assert ( ( offset + len ) <= iscsi->command->data_out_len );
+
+ iobuf = xfer_alloc_iob ( &iscsi->socket, ( len + pad_len ) );
+ if ( ! iobuf )
+ return -ENOMEM;
+
+ copy_from_user ( iob_put ( iobuf, len ),
+ iscsi->command->data_out, offset, len );
+ memset ( iob_put ( iobuf, pad_len ), 0, pad_len );
+
+ return xfer_deliver_iob ( &iscsi->socket, iobuf );
+}
+
+/**
+ * Receive data segment of an iSCSI NOP-In
+ *
+ * @v iscsi iSCSI session
+ * @v data Received data
+ * @v len Length of received data
+ * @v remaining Data remaining after this data
+ * @ret rc Return status code
+ */
+static int iscsi_rx_nop_in ( struct iscsi_session *iscsi,
+ const void *data __unused, size_t len __unused,
+ size_t remaining __unused ) {
+ struct iscsi_nop_in *nop_in = &iscsi->rx_bhs.nop_in;
+
+ DBGC2 ( iscsi, "iSCSI %p received NOP-In\n", iscsi );
+
+ /* We don't currently have the ability to respond to NOP-Ins
+ * sent as ping requests, but we can happily accept NOP-Ins
+ * sent merely to update CmdSN.
+ */
+ if ( nop_in->ttt != htonl ( ISCSI_TAG_RESERVED ) ) {
+ DBGC ( iscsi, "iSCSI %p received unsupported NOP-In with TTT "
+ "%08x\n", iscsi, ntohl ( nop_in->ttt ) );
+ return -ENOTSUP_NOP_IN;
+ }
+
+ return 0;
+}
+
+/****************************************************************************
+ *
+ * iSCSI login
+ *
+ */
+
+/**
+ * Build iSCSI login request strings
+ *
+ * @v iscsi iSCSI session
+ *
+ * These are the initial set of strings sent in the first login
+ * request PDU. We want the following settings:
+ *
+ * HeaderDigest=None
+ * DataDigest=None
+ * MaxConnections is irrelevant; we make only one connection anyway [4]
+ * InitialR2T=Yes [1]
+ * ImmediateData is irrelevant; we never send immediate data [4]
+ * MaxRecvDataSegmentLength=8192 (default; we don't care) [3]
+ * MaxBurstLength=262144 (default; we don't care) [3]
+ * FirstBurstLength=262144 (default; we don't care)
+ * DefaultTime2Wait=0 [2]
+ * DefaultTime2Retain=0 [2]
+ * MaxOutstandingR2T=1
+ * DataPDUInOrder=Yes
+ * DataSequenceInOrder=Yes
+ * ErrorRecoveryLevel=0
+ *
+ * [1] InitialR2T has an OR resolution function, so the target may
+ * force us to use it. We therefore simplify our logic by always
+ * using it.
+ *
+ * [2] These ensure that we can safely start a new task once we have
+ * reconnected after a failure, without having to manually tidy up
+ * after the old one.
+ *
+ * [3] We are quite happy to use the RFC-defined default values for
+ * these parameters, but some targets (notably OpenSolaris)
+ * incorrectly assume a default value of zero, so we explicitly
+ * specify the default values.
+ *
+ * [4] We are quite happy to use the RFC-defined default values for
+ * these parameters, but some targets (notably a QNAP TS-639Pro) fail
+ * unless they are supplied, so we explicitly specify the default
+ * values.
+ */
+static int iscsi_build_login_request_strings ( struct iscsi_session *iscsi,
+ void *data, size_t len ) {
+ unsigned int used = 0;
+ const char *auth_method;
+
+ if ( iscsi->status & ISCSI_STATUS_STRINGS_SECURITY ) {
+ /* Default to allowing no authentication */
+ auth_method = "None";
+ /* If we have a credential to supply, permit CHAP */
+ if ( iscsi->initiator_username )
+ auth_method = "CHAP,None";
+ /* If we have a credential to check, force CHAP */
+ if ( iscsi->target_username )
+ auth_method = "CHAP";
+ used += ssnprintf ( data + used, len - used,
+ "InitiatorName=%s%c"
+ "TargetName=%s%c"
+ "SessionType=Normal%c"
+ "AuthMethod=%s%c",
+ iscsi->initiator_iqn, 0,
+ iscsi->target_iqn, 0, 0,
+ auth_method, 0 );
+ }
+
+ if ( iscsi->status & ISCSI_STATUS_STRINGS_CHAP_ALGORITHM ) {
+ used += ssnprintf ( data + used, len - used, "CHAP_A=5%c", 0 );
+ }
+
+ if ( ( iscsi->status & ISCSI_STATUS_STRINGS_CHAP_RESPONSE ) ) {
+ char buf[ base16_encoded_len ( iscsi->chap.response_len ) + 1 ];
+ assert ( iscsi->initiator_username != NULL );
+ base16_encode ( iscsi->chap.response, iscsi->chap.response_len,
+ buf );
+ used += ssnprintf ( data + used, len - used,
+ "CHAP_N=%s%cCHAP_R=0x%s%c",
+ iscsi->initiator_username, 0, buf, 0 );
+ }
+
+ if ( ( iscsi->status & ISCSI_STATUS_STRINGS_CHAP_CHALLENGE ) ) {
+ size_t challenge_len = ( sizeof ( iscsi->chap_challenge ) - 1 );
+ char buf[ base16_encoded_len ( challenge_len ) + 1 ];
+ base16_encode ( ( iscsi->chap_challenge + 1 ), challenge_len,
+ buf );
+ used += ssnprintf ( data + used, len - used,
+ "CHAP_I=%d%cCHAP_C=0x%s%c",
+ iscsi->chap_challenge[0], 0, buf, 0 );
+ }
+
+ if ( iscsi->status & ISCSI_STATUS_STRINGS_OPERATIONAL ) {
+ used += ssnprintf ( data + used, len - used,
+ "HeaderDigest=None%c"
+ "DataDigest=None%c"
+ "MaxConnections=1%c"
+ "InitialR2T=Yes%c"
+ "ImmediateData=No%c"
+ "MaxRecvDataSegmentLength=8192%c"
+ "MaxBurstLength=262144%c"
+ "DefaultTime2Wait=0%c"
+ "DefaultTime2Retain=0%c"
+ "MaxOutstandingR2T=1%c"
+ "DataPDUInOrder=Yes%c"
+ "DataSequenceInOrder=Yes%c"
+ "ErrorRecoveryLevel=0%c",
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
+ }
+
+ return used;
+}
+
+/**
+ * Build iSCSI login request BHS
+ *
+ * @v iscsi iSCSI session
+ */
+static void iscsi_start_login ( struct iscsi_session *iscsi ) {
+ struct iscsi_bhs_login_request *request = &iscsi->tx_bhs.login_request;
+ int len;
+
+ switch ( iscsi->status & ISCSI_LOGIN_CSG_MASK ) {
+ case ISCSI_LOGIN_CSG_SECURITY_NEGOTIATION:
+ DBGC ( iscsi, "iSCSI %p entering security negotiation\n",
+ iscsi );
+ break;
+ case ISCSI_LOGIN_CSG_OPERATIONAL_NEGOTIATION:
+ DBGC ( iscsi, "iSCSI %p entering operational negotiation\n",
+ iscsi );
+ break;
+ default:
+ assert ( 0 );
+ }
+
+ /* Construct BHS and initiate transmission */
+ iscsi_start_tx ( iscsi );
+ request->opcode = ( ISCSI_OPCODE_LOGIN_REQUEST |
+ ISCSI_FLAG_IMMEDIATE );
+ request->flags = ( ( iscsi->status & ISCSI_STATUS_PHASE_MASK ) |
+ ISCSI_LOGIN_FLAG_TRANSITION );
+ /* version_max and version_min left as zero */
+ len = iscsi_build_login_request_strings ( iscsi, NULL, 0 );
+ ISCSI_SET_LENGTHS ( request->lengths, 0, len );
+ request->isid_iana_en = htonl ( ISCSI_ISID_IANA |
+ IANA_EN_FEN_SYSTEMS );
+ request->isid_iana_qual = htons ( iscsi->isid_iana_qual );
+ /* tsih left as zero */
+ request->itt = htonl ( iscsi->itt );
+ /* cid left as zero */
+ request->cmdsn = htonl ( iscsi->cmdsn );
+ request->expstatsn = htonl ( iscsi->statsn + 1 );
+}
+
+/**
+ * Complete iSCSI login request PDU transmission
+ *
+ * @v iscsi iSCSI session
+ *
+ */
+static void iscsi_login_request_done ( struct iscsi_session *iscsi ) {
+
+ /* Clear any "strings to send" flags */
+ iscsi->status &= ~ISCSI_STATUS_STRINGS_MASK;
+
+ /* Free any dynamically allocated storage used for login */
+ chap_finish ( &iscsi->chap );
+}
+
+/**
+ * Transmit data segment of an iSCSI login request PDU
+ *
+ * @v iscsi iSCSI session
+ * @ret rc Return status code
+ *
+ * For login requests, the data segment consists of the login strings.
+ */
+static int iscsi_tx_login_request ( struct iscsi_session *iscsi ) {
+ struct iscsi_bhs_login_request *request = &iscsi->tx_bhs.login_request;
+ struct io_buffer *iobuf;
+ size_t len;
+ size_t pad_len;
+
+ len = ISCSI_DATA_LEN ( request->lengths );
+ pad_len = ISCSI_DATA_PAD_LEN ( request->lengths );
+ iobuf = xfer_alloc_iob ( &iscsi->socket, ( len + pad_len ) );
+ if ( ! iobuf )
+ return -ENOMEM;
+ iob_put ( iobuf, len );
+ iscsi_build_login_request_strings ( iscsi, iobuf->data, len );
+ memset ( iob_put ( iobuf, pad_len ), 0, pad_len );
+
+ return xfer_deliver_iob ( &iscsi->socket, iobuf );
+}
+
+/**
+ * Calculate maximum length of decoded large binary value
+ *
+ * @v encoded Encoded large binary value
+ * @v max_raw_len Maximum length of raw data
+ */
+static inline size_t
+iscsi_large_binary_decoded_max_len ( const char *encoded ) {
+ return ( strlen ( encoded ) ); /* Decoding never expands data */
+}
+
+/**
+ * Decode large binary value
+ *
+ * @v encoded Encoded large binary value
+ * @v raw Raw data
+ * @ret len Length of raw data, or negative error
+ */
+static int iscsi_large_binary_decode ( const char *encoded, uint8_t *raw ) {
+
+ if ( encoded[0] != '0' )
+ return -EPROTO_INVALID_LARGE_BINARY;
+
+ switch ( encoded[1] ) {
+ case 'x' :
+ case 'X' :
+ return base16_decode ( ( encoded + 2 ), raw );
+ case 'b' :
+ case 'B' :
+ return base64_decode ( ( encoded + 2 ), raw );
+ default:
+ return -EPROTO_INVALID_LARGE_BINARY;
+ }
+}
+
+/**
+ * Handle iSCSI TargetAddress text value
+ *
+ * @v iscsi iSCSI session
+ * @v value TargetAddress value
+ * @ret rc Return status code
+ */
+static int iscsi_handle_targetaddress_value ( struct iscsi_session *iscsi,
+ const char *value ) {
+ char *separator;
+
+ DBGC ( iscsi, "iSCSI %p will redirect to %s\n", iscsi, value );
+
+ /* Replace target address */
+ free ( iscsi->target_address );
+ iscsi->target_address = strdup ( value );
+ if ( ! iscsi->target_address )
+ return -ENOMEM;
+
+ /* Replace target port */
+ iscsi->target_port = htons ( ISCSI_PORT );
+ separator = strchr ( iscsi->target_address, ':' );
+ if ( separator ) {
+ *separator = '\0';
+ iscsi->target_port = strtoul ( ( separator + 1 ), NULL, 0 );
+ }
+
+ return 0;
+}
+
+/**
+ * Handle iSCSI AuthMethod text value
+ *
+ * @v iscsi iSCSI session
+ * @v value AuthMethod value
+ * @ret rc Return status code
+ */
+static int iscsi_handle_authmethod_value ( struct iscsi_session *iscsi,
+ const char *value ) {
+
+ /* If server requests CHAP, send the CHAP_A string */
+ if ( strcmp ( value, "CHAP" ) == 0 ) {
+ DBGC ( iscsi, "iSCSI %p initiating CHAP authentication\n",
+ iscsi );
+ iscsi->status |= ( ISCSI_STATUS_STRINGS_CHAP_ALGORITHM |
+ ISCSI_STATUS_AUTH_FORWARD_REQUIRED );
+ }
+
+ return 0;
+}
+
+/**
+ * Handle iSCSI CHAP_A text value
+ *
+ * @v iscsi iSCSI session
+ * @v value CHAP_A value
+ * @ret rc Return status code
+ */
+static int iscsi_handle_chap_a_value ( struct iscsi_session *iscsi,
+ const char *value ) {
+
+ /* We only ever offer "5" (i.e. MD5) as an algorithm, so if
+ * the server responds with anything else it is a protocol
+ * violation.
+ */
+ if ( strcmp ( value, "5" ) != 0 ) {
+ DBGC ( iscsi, "iSCSI %p got invalid CHAP algorithm \"%s\"\n",
+ iscsi, value );
+ return -EPROTO_INVALID_CHAP_ALGORITHM;
+ }
+
+ return 0;
+}
+
+/**
+ * Handle iSCSI CHAP_I text value
+ *
+ * @v iscsi iSCSI session
+ * @v value CHAP_I value
+ * @ret rc Return status code
+ */
+static int iscsi_handle_chap_i_value ( struct iscsi_session *iscsi,
+ const char *value ) {
+ unsigned int identifier;
+ char *endp;
+ int rc;
+
+ /* The CHAP identifier is an integer value */
+ identifier = strtoul ( value, &endp, 0 );
+ if ( *endp != '\0' ) {
+ DBGC ( iscsi, "iSCSI %p saw invalid CHAP identifier \"%s\"\n",
+ iscsi, value );
+ return -EPROTO_INVALID_CHAP_IDENTIFIER;
+ }
+
+ /* Prepare for CHAP with MD5 */
+ chap_finish ( &iscsi->chap );
+ if ( ( rc = chap_init ( &iscsi->chap, &md5_algorithm ) ) != 0 ) {
+ DBGC ( iscsi, "iSCSI %p could not initialise CHAP: %s\n",
+ iscsi, strerror ( rc ) );
+ return rc;
+ }
+
+ /* Identifier and secret are the first two components of the
+ * challenge.
+ */
+ chap_set_identifier ( &iscsi->chap, identifier );
+ if ( iscsi->initiator_password ) {
+ chap_update ( &iscsi->chap, iscsi->initiator_password,
+ strlen ( iscsi->initiator_password ) );
+ }
+
+ return 0;
+}
+
+/**
+ * Handle iSCSI CHAP_C text value
+ *
+ * @v iscsi iSCSI session
+ * @v value CHAP_C value
+ * @ret rc Return status code
+ */
+static int iscsi_handle_chap_c_value ( struct iscsi_session *iscsi,
+ const char *value ) {
+ uint8_t buf[ iscsi_large_binary_decoded_max_len ( value ) ];
+ unsigned int i;
+ size_t len;
+ int rc;
+
+ /* Process challenge */
+ rc = iscsi_large_binary_decode ( value, buf );
+ if ( rc < 0 ) {
+ DBGC ( iscsi, "iSCSI %p invalid CHAP challenge \"%s\": %s\n",
+ iscsi, value, strerror ( rc ) );
+ return rc;
+ }
+ len = rc;
+ chap_update ( &iscsi->chap, buf, len );
+
+ /* Build CHAP response */
+ DBGC ( iscsi, "iSCSI %p sending CHAP response\n", iscsi );
+ chap_respond ( &iscsi->chap );
+ iscsi->status |= ISCSI_STATUS_STRINGS_CHAP_RESPONSE;
+
+ /* Send CHAP challenge, if applicable */
+ if ( iscsi->target_username ) {
+ iscsi->status |= ISCSI_STATUS_STRINGS_CHAP_CHALLENGE;
+ /* Generate CHAP challenge data */
+ for ( i = 0 ; i < sizeof ( iscsi->chap_challenge ) ; i++ ) {
+ iscsi->chap_challenge[i] = random();
+ }
+ }
+
+ return 0;
+}
+
+/**
+ * Handle iSCSI CHAP_N text value
+ *
+ * @v iscsi iSCSI session
+ * @v value CHAP_N value
+ * @ret rc Return status code
+ */
+static int iscsi_handle_chap_n_value ( struct iscsi_session *iscsi,
+ const char *value ) {
+
+ /* The target username isn't actually involved at any point in
+ * the authentication process; it merely serves to identify
+ * which password the target is using to generate the CHAP
+ * response. We unnecessarily verify that the username is as
+ * expected, in order to provide mildly helpful diagnostics if
+ * the target is supplying the wrong username/password
+ * combination.
+ */
+ if ( iscsi->target_username &&
+ ( strcmp ( iscsi->target_username, value ) != 0 ) ) {
+ DBGC ( iscsi, "iSCSI %p target username \"%s\" incorrect "
+ "(wanted \"%s\")\n",
+ iscsi, value, iscsi->target_username );
+ return -EACCES_INCORRECT_TARGET_USERNAME;
+ }
+
+ return 0;
+}
+
+/**
+ * Handle iSCSI CHAP_R text value
+ *
+ * @v iscsi iSCSI session
+ * @v value CHAP_R value
+ * @ret rc Return status code
+ */
+static int iscsi_handle_chap_r_value ( struct iscsi_session *iscsi,
+ const char *value ) {
+ uint8_t buf[ iscsi_large_binary_decoded_max_len ( value ) ];
+ size_t len;
+ int rc;
+
+ /* Generate CHAP response for verification */
+ chap_finish ( &iscsi->chap );
+ if ( ( rc = chap_init ( &iscsi->chap, &md5_algorithm ) ) != 0 ) {
+ DBGC ( iscsi, "iSCSI %p could not initialise CHAP: %s\n",
+ iscsi, strerror ( rc ) );
+ return rc;
+ }
+ chap_set_identifier ( &iscsi->chap, iscsi->chap_challenge[0] );
+ if ( iscsi->target_password ) {
+ chap_update ( &iscsi->chap, iscsi->target_password,
+ strlen ( iscsi->target_password ) );
+ }
+ chap_update ( &iscsi->chap, &iscsi->chap_challenge[1],
+ ( sizeof ( iscsi->chap_challenge ) - 1 ) );
+ chap_respond ( &iscsi->chap );
+
+ /* Process response */
+ rc = iscsi_large_binary_decode ( value, buf );
+ if ( rc < 0 ) {
+ DBGC ( iscsi, "iSCSI %p invalid CHAP response \"%s\": %s\n",
+ iscsi, value, strerror ( rc ) );
+ return rc;
+ }
+ len = rc;
+
+ /* Check CHAP response */
+ if ( len != iscsi->chap.response_len ) {
+ DBGC ( iscsi, "iSCSI %p invalid CHAP response length\n",
+ iscsi );
+ return -EPROTO_INVALID_CHAP_RESPONSE;
+ }
+ if ( memcmp ( buf, iscsi->chap.response, len ) != 0 ) {
+ DBGC ( iscsi, "iSCSI %p incorrect CHAP response \"%s\"\n",
+ iscsi, value );
+ return -EACCES_INCORRECT_TARGET_PASSWORD;
+ }
+
+ /* Mark session as authenticated */
+ iscsi->status |= ISCSI_STATUS_AUTH_REVERSE_OK;
+
+ return 0;
+}
+
+/** An iSCSI text string that we want to handle */
+struct iscsi_string_type {
+ /** String key
+ *
+ * This is the portion preceding the "=" sign,
+ * e.g. "InitiatorName", "CHAP_A", etc.
+ */
+ const char *key;
+ /** Handle iSCSI string value
+ *
+ * @v iscsi iSCSI session
+ * @v value iSCSI string value
+ * @ret rc Return status code
+ */
+ int ( * handle ) ( struct iscsi_session *iscsi, const char *value );
+};
+
+/** iSCSI text strings that we want to handle */
+static struct iscsi_string_type iscsi_string_types[] = {
+ { "TargetAddress", iscsi_handle_targetaddress_value },
+ { "AuthMethod", iscsi_handle_authmethod_value },
+ { "CHAP_A", iscsi_handle_chap_a_value },
+ { "CHAP_I", iscsi_handle_chap_i_value },
+ { "CHAP_C", iscsi_handle_chap_c_value },
+ { "CHAP_N", iscsi_handle_chap_n_value },
+ { "CHAP_R", iscsi_handle_chap_r_value },
+ { NULL, NULL }
+};
+
+/**
+ * Handle iSCSI string
+ *
+ * @v iscsi iSCSI session
+ * @v string iSCSI string (in "key=value" format)
+ * @ret rc Return status code
+ */
+static int iscsi_handle_string ( struct iscsi_session *iscsi,
+ const char *string ) {
+ struct iscsi_string_type *type;
+ const char *separator;
+ const char *value;
+ size_t key_len;
+ int rc;
+
+ /* Find separator */
+ separator = strchr ( string, '=' );
+ if ( ! separator ) {
+ DBGC ( iscsi, "iSCSI %p malformed string %s\n",
+ iscsi, string );
+ return -EPROTO_INVALID_KEY_VALUE_PAIR;
+ }
+ key_len = ( separator - string );
+ value = ( separator + 1 );
+
+ /* Check for rejections. Since we send only non-rejectable
+ * values, any rejection is a fatal protocol error.
+ */
+ if ( strcmp ( value, "Reject" ) == 0 ) {
+ DBGC ( iscsi, "iSCSI %p rejection: %s\n", iscsi, string );
+ return -EPROTO_VALUE_REJECTED;
+ }
+
+ /* Handle key/value pair */
+ for ( type = iscsi_string_types ; type->key ; type++ ) {
+ if ( strncmp ( string, type->key, key_len ) != 0 )
+ continue;
+ DBGC ( iscsi, "iSCSI %p handling %s\n", iscsi, string );
+ if ( ( rc = type->handle ( iscsi, value ) ) != 0 ) {
+ DBGC ( iscsi, "iSCSI %p could not handle %s: %s\n",
+ iscsi, string, strerror ( rc ) );
+ return rc;
+ }
+ return 0;
+ }
+ DBGC ( iscsi, "iSCSI %p ignoring %s\n", iscsi, string );
+ return 0;
+}
+
+/**
+ * Handle iSCSI strings
+ *
+ * @v iscsi iSCSI session
+ * @v string iSCSI string buffer
+ * @v len Length of string buffer
+ * @ret rc Return status code
+ */
+static int iscsi_handle_strings ( struct iscsi_session *iscsi,
+ const char *strings, size_t len ) {
+ size_t string_len;
+ int rc;
+
+ /* Handle each string in turn, taking care not to overrun the
+ * data buffer in case of badly-terminated data.
+ */
+ while ( 1 ) {
+ string_len = ( strnlen ( strings, len ) + 1 );
+ if ( string_len > len )
+ break;
+ if ( ( rc = iscsi_handle_string ( iscsi, strings ) ) != 0 )
+ return rc;
+ strings += string_len;
+ len -= string_len;
+ }
+ return 0;
+}
+
+/**
+ * Convert iSCSI response status to return status code
+ *
+ * @v status_class iSCSI status class
+ * @v status_detail iSCSI status detail
+ * @ret rc Return status code
+ */
+static int iscsi_status_to_rc ( unsigned int status_class,
+ unsigned int status_detail ) {
+ switch ( status_class ) {
+ case ISCSI_STATUS_INITIATOR_ERROR :
+ switch ( status_detail ) {
+ case ISCSI_STATUS_INITIATOR_ERROR_AUTHENTICATION :
+ return -EPERM_INITIATOR_AUTHENTICATION;
+ case ISCSI_STATUS_INITIATOR_ERROR_AUTHORISATION :
+ return -EPERM_INITIATOR_AUTHORISATION;
+ case ISCSI_STATUS_INITIATOR_ERROR_NOT_FOUND :
+ case ISCSI_STATUS_INITIATOR_ERROR_REMOVED :
+ return -ENODEV;
+ default :
+ return -ENOTSUP_INITIATOR_STATUS;
+ }
+ case ISCSI_STATUS_TARGET_ERROR :
+ switch ( status_detail ) {
+ case ISCSI_STATUS_TARGET_ERROR_UNAVAILABLE:
+ return -EIO_TARGET_UNAVAILABLE;
+ case ISCSI_STATUS_TARGET_ERROR_NO_RESOURCES:
+ return -EIO_TARGET_NO_RESOURCES;
+ default:
+ return -ENOTSUP_TARGET_STATUS;
+ }
+ default :
+ return -EINVAL;
+ }
+}
+
+/**
+ * Receive data segment of an iSCSI login response PDU
+ *
+ * @v iscsi iSCSI session
+ * @v data Received data
+ * @v len Length of received data
+ * @v remaining Data remaining after this data
+ * @ret rc Return status code
+ */
+static int iscsi_rx_login_response ( struct iscsi_session *iscsi,
+ const void *data, size_t len,
+ size_t remaining ) {
+ struct iscsi_bhs_login_response *response
+ = &iscsi->rx_bhs.login_response;
+ int rc;
+
+ /* Buffer up the PDU data */
+ if ( ( rc = iscsi_rx_buffered_data ( iscsi, data, len ) ) != 0 ) {
+ DBGC ( iscsi, "iSCSI %p could not buffer login response: %s\n",
+ iscsi, strerror ( rc ) );
+ return rc;
+ }
+ if ( remaining )
+ return 0;
+
+ /* Process string data and discard string buffer */
+ if ( ( rc = iscsi_handle_strings ( iscsi, iscsi->rx_buffer,
+ iscsi->rx_len ) ) != 0 )
+ return rc;
+ iscsi_rx_buffered_data_done ( iscsi );
+
+ /* Check for login redirection */
+ if ( response->status_class == ISCSI_STATUS_REDIRECT ) {
+ DBGC ( iscsi, "iSCSI %p redirecting to new server\n", iscsi );
+ iscsi_close_connection ( iscsi, 0 );
+ if ( ( rc = iscsi_open_connection ( iscsi ) ) != 0 ) {
+ DBGC ( iscsi, "iSCSI %p could not redirect: %s\n ",
+ iscsi, strerror ( rc ) );
+ return rc;
+ }
+ return 0;
+ }
+
+ /* Check for fatal errors */
+ if ( response->status_class != 0 ) {
+ DBGC ( iscsi, "iSCSI login failure: class %02x detail %02x\n",
+ response->status_class, response->status_detail );
+ rc = iscsi_status_to_rc ( response->status_class,
+ response->status_detail );
+ return rc;
+ }
+
+ /* Handle login transitions */
+ if ( response->flags & ISCSI_LOGIN_FLAG_TRANSITION ) {
+ iscsi->status &= ~( ISCSI_STATUS_PHASE_MASK |
+ ISCSI_STATUS_STRINGS_MASK );
+ switch ( response->flags & ISCSI_LOGIN_NSG_MASK ) {
+ case ISCSI_LOGIN_NSG_OPERATIONAL_NEGOTIATION:
+ iscsi->status |=
+ ( ISCSI_STATUS_OPERATIONAL_NEGOTIATION_PHASE |
+ ISCSI_STATUS_STRINGS_OPERATIONAL );
+ break;
+ case ISCSI_LOGIN_NSG_FULL_FEATURE_PHASE:
+ iscsi->status |= ISCSI_STATUS_FULL_FEATURE_PHASE;
+ break;
+ default:
+ DBGC ( iscsi, "iSCSI %p got invalid response flags "
+ "%02x\n", iscsi, response->flags );
+ return -EIO;
+ }
+ }
+
+ /* Send next login request PDU if we haven't reached the full
+ * feature phase yet.
+ */
+ if ( ( iscsi->status & ISCSI_STATUS_PHASE_MASK ) !=
+ ISCSI_STATUS_FULL_FEATURE_PHASE ) {
+ iscsi_start_login ( iscsi );
+ return 0;
+ }
+
+ /* Check that target authentication was successful (if required) */
+ if ( ( iscsi->status & ISCSI_STATUS_AUTH_REVERSE_REQUIRED ) &&
+ ! ( iscsi->status & ISCSI_STATUS_AUTH_REVERSE_OK ) ) {
+ DBGC ( iscsi, "iSCSI %p nefarious target tried to bypass "
+ "authentication\n", iscsi );
+ return -EPROTO;
+ }
+
+ /* Notify SCSI layer of window change */
+ DBGC ( iscsi, "iSCSI %p entering full feature phase\n", iscsi );
+ xfer_window_changed ( &iscsi->control );
+
+ return 0;
+}
+
+/****************************************************************************
+ *
+ * iSCSI to socket interface
+ *
+ */
+
+/**
+ * Pause TX engine
+ *
+ * @v iscsi iSCSI session
+ */
+static void iscsi_tx_pause ( struct iscsi_session *iscsi ) {
+ process_del ( &iscsi->process );
+}
+
+/**
+ * Resume TX engine
+ *
+ * @v iscsi iSCSI session
+ */
+static void iscsi_tx_resume ( struct iscsi_session *iscsi ) {
+ process_add ( &iscsi->process );
+}
+
+/**
+ * Start up a new TX PDU
+ *
+ * @v iscsi iSCSI session
+ *
+ * This initiates the process of sending a new PDU. Only one PDU may
+ * be in transit at any one time.
+ */
+static void iscsi_start_tx ( struct iscsi_session *iscsi ) {
+
+ assert ( iscsi->tx_state == ISCSI_TX_IDLE );
+
+ /* Initialise TX BHS */
+ memset ( &iscsi->tx_bhs, 0, sizeof ( iscsi->tx_bhs ) );
+
+ /* Flag TX engine to start transmitting */
+ iscsi->tx_state = ISCSI_TX_BHS;
+
+ /* Start transmission process */
+ iscsi_tx_resume ( iscsi );
+}
+
+/**
+ * Transmit nothing
+ *
+ * @v iscsi iSCSI session
+ * @ret rc Return status code
+ */
+static int iscsi_tx_nothing ( struct iscsi_session *iscsi __unused ) {
+ return 0;
+}
+
+/**
+ * Transmit basic header segment of an iSCSI PDU
+ *
+ * @v iscsi iSCSI session
+ * @ret rc Return status code
+ */
+static int iscsi_tx_bhs ( struct iscsi_session *iscsi ) {
+ return xfer_deliver_raw ( &iscsi->socket, &iscsi->tx_bhs,
+ sizeof ( iscsi->tx_bhs ) );
+}
+
+/**
+ * Transmit data segment of an iSCSI PDU
+ *
+ * @v iscsi iSCSI session
+ * @ret rc Return status code
+ *
+ * Handle transmission of part of a PDU data segment. iscsi::tx_bhs
+ * will be valid when this is called.
+ */
+static int iscsi_tx_data ( struct iscsi_session *iscsi ) {
+ struct iscsi_bhs_common *common = &iscsi->tx_bhs.common;
+
+ switch ( common->opcode & ISCSI_OPCODE_MASK ) {
+ case ISCSI_OPCODE_DATA_OUT:
+ return iscsi_tx_data_out ( iscsi );
+ case ISCSI_OPCODE_LOGIN_REQUEST:
+ return iscsi_tx_login_request ( iscsi );
+ default:
+ /* Nothing to send in other states */
+ return 0;
+ }
+}
+
+/**
+ * Complete iSCSI PDU transmission
+ *
+ * @v iscsi iSCSI session
+ *
+ * Called when a PDU has been completely transmitted and the TX state
+ * machine is about to enter the idle state. iscsi::tx_bhs will be
+ * valid for the just-completed PDU when this is called.
+ */
+static void iscsi_tx_done ( struct iscsi_session *iscsi ) {
+ struct iscsi_bhs_common *common = &iscsi->tx_bhs.common;
+
+ /* Stop transmission process */
+ iscsi_tx_pause ( iscsi );
+
+ switch ( common->opcode & ISCSI_OPCODE_MASK ) {
+ case ISCSI_OPCODE_DATA_OUT:
+ iscsi_data_out_done ( iscsi );
+ case ISCSI_OPCODE_LOGIN_REQUEST:
+ iscsi_login_request_done ( iscsi );
+ default:
+ /* No action */
+ break;
+ }
+}
+
+/**
+ * Transmit iSCSI PDU
+ *
+ * @v iscsi iSCSI session
+ * @v buf Temporary data buffer
+ * @v len Length of temporary data buffer
+ *
+ * Constructs data to be sent for the current TX state
+ */
+static void iscsi_tx_step ( struct iscsi_session *iscsi ) {
+ struct iscsi_bhs_common *common = &iscsi->tx_bhs.common;
+ int ( * tx ) ( struct iscsi_session *iscsi );
+ enum iscsi_tx_state next_state;
+ size_t tx_len;
+ int rc;
+
+ /* Select fragment to transmit */
+ while ( 1 ) {
+ switch ( iscsi->tx_state ) {
+ case ISCSI_TX_BHS:
+ tx = iscsi_tx_bhs;
+ tx_len = sizeof ( iscsi->tx_bhs );
+ next_state = ISCSI_TX_AHS;
+ break;
+ case ISCSI_TX_AHS:
+ tx = iscsi_tx_nothing;
+ tx_len = 0;
+ next_state = ISCSI_TX_DATA;
+ break;
+ case ISCSI_TX_DATA:
+ tx = iscsi_tx_data;
+ tx_len = ISCSI_DATA_LEN ( common->lengths );
+ next_state = ISCSI_TX_IDLE;
+ break;
+ case ISCSI_TX_IDLE:
+ /* Nothing to do; pause processing */
+ iscsi_tx_pause ( iscsi );
+ return;
+ default:
+ assert ( 0 );
+ return;
+ }
+
+ /* Check for window availability, if needed */
+ if ( tx_len && ( xfer_window ( &iscsi->socket ) == 0 ) ) {
+ /* Cannot transmit at this point; pause
+ * processing and wait for window to reopen
+ */
+ iscsi_tx_pause ( iscsi );
+ return;
+ }
+
+ /* Transmit data */
+ if ( ( rc = tx ( iscsi ) ) != 0 ) {
+ DBGC ( iscsi, "iSCSI %p could not transmit: %s\n",
+ iscsi, strerror ( rc ) );
+ /* Transmission errors are fatal */
+ iscsi_close ( iscsi, rc );
+ return;
+ }
+
+ /* Move to next state */
+ iscsi->tx_state = next_state;
+
+ /* If we have moved to the idle state, mark
+ * transmission as complete
+ */
+ if ( iscsi->tx_state == ISCSI_TX_IDLE )
+ iscsi_tx_done ( iscsi );
+ }
+}
+
+/** iSCSI TX process descriptor */
+static struct process_descriptor iscsi_process_desc =
+ PROC_DESC ( struct iscsi_session, process, iscsi_tx_step );
+
+/**
+ * Receive basic header segment of an iSCSI PDU
+ *
+ * @v iscsi iSCSI session
+ * @v data Received data
+ * @v len Length of received data
+ * @v remaining Data remaining after this data
+ * @ret rc Return status code
+ *
+ * This fills in iscsi::rx_bhs with the data from the BHS portion of
+ * the received PDU.
+ */
+static int iscsi_rx_bhs ( struct iscsi_session *iscsi, const void *data,
+ size_t len, size_t remaining __unused ) {
+ memcpy ( &iscsi->rx_bhs.bytes[iscsi->rx_offset], data, len );
+ if ( ( iscsi->rx_offset + len ) >= sizeof ( iscsi->rx_bhs ) ) {
+ DBGC2 ( iscsi, "iSCSI %p received PDU opcode %#x len %#x\n",
+ iscsi, iscsi->rx_bhs.common.opcode,
+ ISCSI_DATA_LEN ( iscsi->rx_bhs.common.lengths ) );
+ }
+ return 0;
+}
+
+/**
+ * Discard portion of an iSCSI PDU.
+ *
+ * @v iscsi iSCSI session
+ * @v data Received data
+ * @v len Length of received data
+ * @v remaining Data remaining after this data
+ * @ret rc Return status code
+ *
+ * This discards data from a portion of a received PDU.
+ */
+static int iscsi_rx_discard ( struct iscsi_session *iscsi __unused,
+ const void *data __unused, size_t len __unused,
+ size_t remaining __unused ) {
+ /* Do nothing */
+ return 0;
+}
+
+/**
+ * Receive data segment of an iSCSI PDU
+ *
+ * @v iscsi iSCSI session
+ * @v data Received data
+ * @v len Length of received data
+ * @v remaining Data remaining after this data
+ * @ret rc Return status code
+ *
+ * Handle processing of part of a PDU data segment. iscsi::rx_bhs
+ * will be valid when this is called.
+ */
+static int iscsi_rx_data ( struct iscsi_session *iscsi, const void *data,
+ size_t len, size_t remaining ) {
+ struct iscsi_bhs_common_response *response
+ = &iscsi->rx_bhs.common_response;
+
+ /* Update cmdsn and statsn */
+ iscsi->cmdsn = ntohl ( response->expcmdsn );
+ iscsi->statsn = ntohl ( response->statsn );
+
+ switch ( response->opcode & ISCSI_OPCODE_MASK ) {
+ case ISCSI_OPCODE_LOGIN_RESPONSE:
+ return iscsi_rx_login_response ( iscsi, data, len, remaining );
+ case ISCSI_OPCODE_SCSI_RESPONSE:
+ return iscsi_rx_scsi_response ( iscsi, data, len, remaining );
+ case ISCSI_OPCODE_DATA_IN:
+ return iscsi_rx_data_in ( iscsi, data, len, remaining );
+ case ISCSI_OPCODE_R2T:
+ return iscsi_rx_r2t ( iscsi, data, len, remaining );
+ case ISCSI_OPCODE_NOP_IN:
+ return iscsi_rx_nop_in ( iscsi, data, len, remaining );
+ default:
+ if ( remaining )
+ return 0;
+ DBGC ( iscsi, "iSCSI %p unknown opcode %02x\n", iscsi,
+ response->opcode );
+ return -ENOTSUP_OPCODE;
+ }
+}
+
+/**
+ * Receive new data
+ *
+ * @v iscsi iSCSI session
+ * @v iobuf I/O buffer
+ * @v meta Data transfer metadata
+ * @ret rc Return status code
+ *
+ * This handles received PDUs. The receive strategy is to fill in
+ * iscsi::rx_bhs with the contents of the BHS portion of the PDU,
+ * throw away any AHS portion, and then process each part of the data
+ * portion as it arrives. The data processing routine therefore
+ * always has a full copy of the BHS available, even for portions of
+ * the data in different packets to the BHS.
+ */
+static int iscsi_socket_deliver ( struct iscsi_session *iscsi,
+ struct io_buffer *iobuf,
+ struct xfer_metadata *meta __unused ) {
+ struct iscsi_bhs_common *common = &iscsi->rx_bhs.common;
+ int ( * rx ) ( struct iscsi_session *iscsi, const void *data,
+ size_t len, size_t remaining );
+ enum iscsi_rx_state next_state;
+ size_t frag_len;
+ size_t remaining;
+ int rc;
+
+ while ( 1 ) {
+ switch ( iscsi->rx_state ) {
+ case ISCSI_RX_BHS:
+ rx = iscsi_rx_bhs;
+ iscsi->rx_len = sizeof ( iscsi->rx_bhs );
+ next_state = ISCSI_RX_AHS;
+ break;
+ case ISCSI_RX_AHS:
+ rx = iscsi_rx_discard;
+ iscsi->rx_len = 4 * ISCSI_AHS_LEN ( common->lengths );
+ next_state = ISCSI_RX_DATA;
+ break;
+ case ISCSI_RX_DATA:
+ rx = iscsi_rx_data;
+ iscsi->rx_len = ISCSI_DATA_LEN ( common->lengths );
+ next_state = ISCSI_RX_DATA_PADDING;
+ break;
+ case ISCSI_RX_DATA_PADDING:
+ rx = iscsi_rx_discard;
+ iscsi->rx_len = ISCSI_DATA_PAD_LEN ( common->lengths );
+ next_state = ISCSI_RX_BHS;
+ break;
+ default:
+ assert ( 0 );
+ rc = -EINVAL;
+ goto done;
+ }
+
+ frag_len = iscsi->rx_len - iscsi->rx_offset;
+ if ( frag_len > iob_len ( iobuf ) )
+ frag_len = iob_len ( iobuf );
+ remaining = iscsi->rx_len - iscsi->rx_offset - frag_len;
+ if ( ( rc = rx ( iscsi, iobuf->data, frag_len,
+ remaining ) ) != 0 ) {
+ DBGC ( iscsi, "iSCSI %p could not process received "
+ "data: %s\n", iscsi, strerror ( rc ) );
+ goto done;
+ }
+
+ iscsi->rx_offset += frag_len;
+ iob_pull ( iobuf, frag_len );
+
+ /* If all the data for this state has not yet been
+ * received, stay in this state for now.
+ */
+ if ( iscsi->rx_offset != iscsi->rx_len ) {
+ rc = 0;
+ goto done;
+ }
+
+ iscsi->rx_state = next_state;
+ iscsi->rx_offset = 0;
+ }
+
+ done:
+ /* Free I/O buffer */
+ free_iob ( iobuf );
+
+ /* Destroy session on error */
+ if ( rc != 0 )
+ iscsi_close ( iscsi, rc );
+
+ return rc;
+}
+
+/**
+ * Handle redirection event
+ *
+ * @v iscsi iSCSI session
+ * @v type Location type
+ * @v args Remaining arguments depend upon location type
+ * @ret rc Return status code
+ */
+static int iscsi_vredirect ( struct iscsi_session *iscsi, int type,
+ va_list args ) {
+ va_list tmp;
+ struct sockaddr *peer;
+
+ /* Intercept redirects to a LOCATION_SOCKET and record the IP
+ * address for the iBFT. This is a bit of a hack, but avoids
+ * inventing an ioctl()-style call to retrieve the socket
+ * address from a data-xfer interface.
+ */
+ if ( type == LOCATION_SOCKET ) {
+ va_copy ( tmp, args );
+ ( void ) va_arg ( tmp, int ); /* Discard "semantics" */
+ peer = va_arg ( tmp, struct sockaddr * );
+ memcpy ( &iscsi->target_sockaddr, peer,
+ sizeof ( iscsi->target_sockaddr ) );
+ va_end ( tmp );
+ }
+
+ return xfer_vreopen ( &iscsi->socket, type, args );
+}
+
+/** iSCSI socket interface operations */
+static struct interface_operation iscsi_socket_operations[] = {
+ INTF_OP ( xfer_deliver, struct iscsi_session *, iscsi_socket_deliver ),
+ INTF_OP ( xfer_window_changed, struct iscsi_session *,
+ iscsi_tx_resume ),
+ INTF_OP ( xfer_vredirect, struct iscsi_session *, iscsi_vredirect ),
+ INTF_OP ( intf_close, struct iscsi_session *, iscsi_close ),
+};
+
+/** iSCSI socket interface descriptor */
+static struct interface_descriptor iscsi_socket_desc =
+ INTF_DESC ( struct iscsi_session, socket, iscsi_socket_operations );
+
+/****************************************************************************
+ *
+ * iSCSI command issuing
+ *
+ */
+
+/**
+ * Check iSCSI flow-control window
+ *
+ * @v iscsi iSCSI session
+ * @ret len Length of window
+ */
+static size_t iscsi_scsi_window ( struct iscsi_session *iscsi ) {
+
+ if ( ( ( iscsi->status & ISCSI_STATUS_PHASE_MASK ) ==
+ ISCSI_STATUS_FULL_FEATURE_PHASE ) &&
+ ( iscsi->command == NULL ) ) {
+ /* We cannot handle concurrent commands */
+ return 1;
+ } else {
+ return 0;
+ }
+}
+
+/**
+ * Issue iSCSI SCSI command
+ *
+ * @v iscsi iSCSI session
+ * @v parent Parent interface
+ * @v command SCSI command
+ * @ret tag Command tag, or negative error
+ */
+static int iscsi_scsi_command ( struct iscsi_session *iscsi,
+ struct interface *parent,
+ struct scsi_cmd *command ) {
+
+ /* This iSCSI implementation cannot handle multiple concurrent
+ * commands or commands arriving before login is complete.
+ */
+ if ( iscsi_scsi_window ( iscsi ) == 0 ) {
+ DBGC ( iscsi, "iSCSI %p cannot handle concurrent commands\n",
+ iscsi );
+ return -EOPNOTSUPP;
+ }
+
+ /* Store command */
+ iscsi->command = malloc ( sizeof ( *command ) );
+ if ( ! iscsi->command )
+ return -ENOMEM;
+ memcpy ( iscsi->command, command, sizeof ( *command ) );
+
+ /* Assign new ITT */
+ iscsi_new_itt ( iscsi );
+
+ /* Start sending command */
+ iscsi_start_command ( iscsi );
+
+ /* Attach to parent interface and return */
+ intf_plug_plug ( &iscsi->data, parent );
+ return iscsi->itt;
+}
+
+/** iSCSI SCSI command-issuing interface operations */
+static struct interface_operation iscsi_control_op[] = {
+ INTF_OP ( scsi_command, struct iscsi_session *, iscsi_scsi_command ),
+ INTF_OP ( xfer_window, struct iscsi_session *, iscsi_scsi_window ),
+ INTF_OP ( intf_close, struct iscsi_session *, iscsi_close ),
+ INTF_OP ( acpi_describe, struct iscsi_session *, ibft_describe ),
+};
+
+/** iSCSI SCSI command-issuing interface descriptor */
+static struct interface_descriptor iscsi_control_desc =
+ INTF_DESC ( struct iscsi_session, control, iscsi_control_op );
+
+/**
+ * Close iSCSI command
+ *
+ * @v iscsi iSCSI session
+ * @v rc Reason for close
+ */
+static void iscsi_command_close ( struct iscsi_session *iscsi, int rc ) {
+
+ /* Restart interface */
+ intf_restart ( &iscsi->data, rc );
+
+ /* Treat unsolicited command closures mid-command as fatal,
+ * because we have no code to handle partially-completed PDUs.
+ */
+ if ( iscsi->command != NULL )
+ iscsi_close ( iscsi, ( ( rc == 0 ) ? -ECANCELED : rc ) );
+}
+
+/** iSCSI SCSI command interface operations */
+static struct interface_operation iscsi_data_op[] = {
+ INTF_OP ( intf_close, struct iscsi_session *, iscsi_command_close ),
+};
+
+/** iSCSI SCSI command interface descriptor */
+static struct interface_descriptor iscsi_data_desc =
+ INTF_DESC ( struct iscsi_session, data, iscsi_data_op );
+
+/****************************************************************************
+ *
+ * Instantiator
+ *
+ */
+
+/** iSCSI root path components (as per RFC4173) */
+enum iscsi_root_path_component {
+ RP_SERVERNAME = 0,
+ RP_PROTOCOL,
+ RP_PORT,
+ RP_LUN,
+ RP_TARGETNAME,
+ NUM_RP_COMPONENTS
+};
+
+/** iSCSI initiator IQN setting */
+const struct setting initiator_iqn_setting __setting ( SETTING_SANBOOT_EXTRA,
+ initiator-iqn ) = {
+ .name = "initiator-iqn",
+ .description = "iSCSI initiator name",
+ .tag = DHCP_ISCSI_INITIATOR_IQN,
+ .type = &setting_type_string,
+};
+
+/** iSCSI reverse username setting */
+const struct setting reverse_username_setting __setting ( SETTING_AUTH_EXTRA,
+ reverse-username ) = {
+ .name = "reverse-username",
+ .description = "Reverse user name",
+ .tag = DHCP_EB_REVERSE_USERNAME,
+ .type = &setting_type_string,
+};
+
+/** iSCSI reverse password setting */
+const struct setting reverse_password_setting __setting ( SETTING_AUTH_EXTRA,
+ reverse-password ) = {
+ .name = "reverse-password",
+ .description = "Reverse password",
+ .tag = DHCP_EB_REVERSE_PASSWORD,
+ .type = &setting_type_string,
+};
+
+/**
+ * Parse iSCSI root path
+ *
+ * @v iscsi iSCSI session
+ * @v root_path iSCSI root path (as per RFC4173)
+ * @ret rc Return status code
+ */
+static int iscsi_parse_root_path ( struct iscsi_session *iscsi,
+ const char *root_path ) {
+ char rp_copy[ strlen ( root_path ) + 1 ];
+ char *rp_comp[NUM_RP_COMPONENTS];
+ char *rp = rp_copy;
+ int i = 0;
+ int rc;
+
+ /* Split root path into component parts */
+ strcpy ( rp_copy, root_path );
+ while ( 1 ) {
+ rp_comp[i++] = rp;
+ if ( i == NUM_RP_COMPONENTS )
+ break;
+ for ( ; *rp != ':' ; rp++ ) {
+ if ( ! *rp ) {
+ DBGC ( iscsi, "iSCSI %p root path \"%s\" "
+ "too short\n", iscsi, root_path );
+ return -EINVAL_ROOT_PATH_TOO_SHORT;
+ }
+ }
+ *(rp++) = '\0';
+ }
+
+ /* Use root path components to configure iSCSI session */
+ iscsi->target_address = strdup ( rp_comp[RP_SERVERNAME] );
+ if ( ! iscsi->target_address )
+ return -ENOMEM;
+ iscsi->target_port = strtoul ( rp_comp[RP_PORT], NULL, 10 );
+ if ( ! iscsi->target_port )
+ iscsi->target_port = ISCSI_PORT;
+ if ( ( rc = scsi_parse_lun ( rp_comp[RP_LUN], &iscsi->lun ) ) != 0 ) {
+ DBGC ( iscsi, "iSCSI %p invalid LUN \"%s\"\n",
+ iscsi, rp_comp[RP_LUN] );
+ return rc;
+ }
+ iscsi->target_iqn = strdup ( rp_comp[RP_TARGETNAME] );
+ if ( ! iscsi->target_iqn )
+ return -ENOMEM;
+
+ return 0;
+}
+
+/**
+ * Fetch iSCSI settings
+ *
+ * @v iscsi iSCSI session
+ * @ret rc Return status code
+ */
+static int iscsi_fetch_settings ( struct iscsi_session *iscsi ) {
+ char *hostname;
+ union uuid uuid;
+ int len;
+
+ /* Fetch relevant settings. Don't worry about freeing on
+ * error, since iscsi_free() will take care of that anyway.
+ */
+ fetch_string_setting_copy ( NULL, &username_setting,
+ &iscsi->initiator_username );
+ fetch_string_setting_copy ( NULL, &password_setting,
+ &iscsi->initiator_password );
+ fetch_string_setting_copy ( NULL, &reverse_username_setting,
+ &iscsi->target_username );
+ fetch_string_setting_copy ( NULL, &reverse_password_setting,
+ &iscsi->target_password );
+
+ /* Use explicit initiator IQN if provided */
+ fetch_string_setting_copy ( NULL, &initiator_iqn_setting,
+ &iscsi->initiator_iqn );
+ if ( iscsi->initiator_iqn )
+ return 0;
+
+ /* Otherwise, try to construct an initiator IQN from the hostname */
+ fetch_string_setting_copy ( NULL, &hostname_setting, &hostname );
+ if ( hostname ) {
+ len = asprintf ( &iscsi->initiator_iqn,
+ ISCSI_DEFAULT_IQN_PREFIX ":%s", hostname );
+ free ( hostname );
+ if ( len < 0 ) {
+ DBGC ( iscsi, "iSCSI %p could not allocate initiator "
+ "IQN\n", iscsi );
+ return -ENOMEM;
+ }
+ assert ( iscsi->initiator_iqn );
+ return 0;
+ }
+
+ /* Otherwise, try to construct an initiator IQN from the UUID */
+ if ( ( len = fetch_uuid_setting ( NULL, &uuid_setting, &uuid ) ) < 0 ) {
+ DBGC ( iscsi, "iSCSI %p has no suitable initiator IQN\n",
+ iscsi );
+ return -EINVAL_NO_INITIATOR_IQN;
+ }
+ if ( ( len = asprintf ( &iscsi->initiator_iqn,
+ ISCSI_DEFAULT_IQN_PREFIX ":%s",
+ uuid_ntoa ( &uuid ) ) ) < 0 ) {
+ DBGC ( iscsi, "iSCSI %p could not allocate initiator IQN\n",
+ iscsi );
+ return -ENOMEM;
+ }
+ assert ( iscsi->initiator_iqn );
+
+ return 0;
+}
+
+
+/**
+ * Check iSCSI authentication details
+ *
+ * @v iscsi iSCSI session
+ * @ret rc Return status code
+ */
+static int iscsi_check_auth ( struct iscsi_session *iscsi ) {
+
+ /* Check for invalid authentication combinations */
+ if ( ( /* Initiator username without password (or vice-versa) */
+ ( !! iscsi->initiator_username ) ^
+ ( !! iscsi->initiator_password ) ) ||
+ ( /* Target username without password (or vice-versa) */
+ ( !! iscsi->target_username ) ^
+ ( !! iscsi->target_password ) ) ||
+ ( /* Target (reverse) without initiator (forward) */
+ ( iscsi->target_username &&
+ ( ! iscsi->initiator_username ) ) ) ) {
+ DBGC ( iscsi, "iSCSI %p invalid credentials: initiator "
+ "%sname,%spw, target %sname,%spw\n", iscsi,
+ ( iscsi->initiator_username ? "" : "no " ),
+ ( iscsi->initiator_password ? "" : "no " ),
+ ( iscsi->target_username ? "" : "no " ),
+ ( iscsi->target_password ? "" : "no " ) );
+ return -EINVAL_BAD_CREDENTIAL_MIX;
+ }
+
+ return 0;
+}
+
+/**
+ * Open iSCSI URI
+ *
+ * @v parent Parent interface
+ * @v uri URI
+ * @ret rc Return status code
+ */
+static int iscsi_open ( struct interface *parent, struct uri *uri ) {
+ struct iscsi_session *iscsi;
+ int rc;
+
+ /* Sanity check */
+ if ( ! uri->opaque ) {
+ rc = -EINVAL_NO_ROOT_PATH;
+ goto err_sanity_uri;
+ }
+
+ /* Allocate and initialise structure */
+ iscsi = zalloc ( sizeof ( *iscsi ) );
+ if ( ! iscsi ) {
+ rc = -ENOMEM;
+ goto err_zalloc;
+ }
+ ref_init ( &iscsi->refcnt, iscsi_free );
+ intf_init ( &iscsi->control, &iscsi_control_desc, &iscsi->refcnt );
+ intf_init ( &iscsi->data, &iscsi_data_desc, &iscsi->refcnt );
+ intf_init ( &iscsi->socket, &iscsi_socket_desc, &iscsi->refcnt );
+ process_init_stopped ( &iscsi->process, &iscsi_process_desc,
+ &iscsi->refcnt );
+
+ /* Parse root path */
+ if ( ( rc = iscsi_parse_root_path ( iscsi, uri->opaque ) ) != 0 )
+ goto err_parse_root_path;
+ /* Set fields not specified by root path */
+ if ( ( rc = iscsi_fetch_settings ( iscsi ) ) != 0 )
+ goto err_fetch_settings;
+ /* Validate authentication */
+ if ( ( rc = iscsi_check_auth ( iscsi ) ) != 0 )
+ goto err_check_auth;
+
+ /* Sanity checks */
+ if ( ! iscsi->target_address ) {
+ DBGC ( iscsi, "iSCSI %p does not yet support discovery\n",
+ iscsi );
+ rc = -ENOTSUP_DISCOVERY;
+ goto err_sanity_address;
+ }
+ if ( ! iscsi->target_iqn ) {
+ DBGC ( iscsi, "iSCSI %p no target address supplied in %s\n",
+ iscsi, uri->opaque );
+ rc = -EINVAL_NO_TARGET_IQN;
+ goto err_sanity_iqn;
+ }
+ DBGC ( iscsi, "iSCSI %p initiator %s\n",iscsi, iscsi->initiator_iqn );
+ DBGC ( iscsi, "iSCSI %p target %s %s\n",
+ iscsi, iscsi->target_address, iscsi->target_iqn );
+
+ /* Open socket */
+ if ( ( rc = iscsi_open_connection ( iscsi ) ) != 0 )
+ goto err_open_connection;
+
+ /* Attach SCSI device to parent interface */
+ if ( ( rc = scsi_open ( parent, &iscsi->control,
+ &iscsi->lun ) ) != 0 ) {
+ DBGC ( iscsi, "iSCSI %p could not create SCSI device: %s\n",
+ iscsi, strerror ( rc ) );
+ goto err_scsi_open;
+ }
+
+ /* Mortalise self, and return */
+ ref_put ( &iscsi->refcnt );
+ return 0;
+
+ err_scsi_open:
+ err_open_connection:
+ err_sanity_iqn:
+ err_sanity_address:
+ err_check_auth:
+ err_fetch_settings:
+ err_parse_root_path:
+ iscsi_close ( iscsi, rc );
+ ref_put ( &iscsi->refcnt );
+ err_zalloc:
+ err_sanity_uri:
+ return rc;
+}
+
+/** iSCSI URI opener */
+struct uri_opener iscsi_uri_opener __uri_opener = {
+ .scheme = "iscsi",
+ .open = iscsi_open,
+};
diff --git a/qemu/roms/ipxe/src/net/tcp/oncrpc.c b/qemu/roms/ipxe/src/net/tcp/oncrpc.c
new file mode 100644
index 000000000..6469867e9
--- /dev/null
+++ b/qemu/roms/ipxe/src/net/tcp/oncrpc.c
@@ -0,0 +1,250 @@
+/*
+ * Copyright (C) 2013 Marin Hannache <ipxe@mareo.fr>.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation; either version 2 of the
+ * License, or any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include <stdint.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <assert.h>
+#include <errno.h>
+#include <byteswap.h>
+#include <ipxe/socket.h>
+#include <ipxe/tcpip.h>
+#include <ipxe/in.h>
+#include <ipxe/iobuf.h>
+#include <ipxe/dhcp.h>
+#include <ipxe/xfer.h>
+#include <ipxe/open.h>
+#include <ipxe/uri.h>
+#include <ipxe/features.h>
+#include <ipxe/oncrpc.h>
+#include <ipxe/oncrpc_iob.h>
+#include <ipxe/init.h>
+#include <ipxe/settings.h>
+#include <ipxe/version.h>
+
+/** @file
+ *
+ * SUN ONC RPC protocol
+ *
+ */
+
+/** Set most significant bit to 1. */
+#define SET_LAST_FRAME( x ) ( (x) | 1 << 31 )
+#define GET_FRAME_SIZE( x ) ( (x) & ~( 1 << 31 ) )
+
+#define ONCRPC_CALL 0
+#define ONCRPC_REPLY 1
+
+/** AUTH NONE authentication flavor */
+struct oncrpc_cred oncrpc_auth_none = {
+ .flavor = ONCRPC_AUTH_NONE,
+ .length = 0
+};
+
+const struct setting uid_setting __setting ( SETTING_AUTH, uid ) = {
+ .name = "uid",
+ .description = "User ID",
+ .tag = DHCP_EB_UID,
+ .type = &setting_type_uint32
+};
+
+const struct setting gid_setting __setting ( SETTING_AUTH, gid ) = {
+ .name = "gid",
+ .description = "Group ID",
+ .tag = DHCP_EB_GID,
+ .type = &setting_type_uint32
+};
+
+/**
+ * Initialize an ONC RPC AUTH SYS credential structure
+ *
+ * @v auth_sys The structure to initialize
+ *
+ * The hostname field is filled with the value of the hostname setting, if the
+ * hostname setting is empty, PRODUCT_SHORT_NAME (usually "iPXE") is used
+ * instead.
+ */
+int oncrpc_init_cred_sys ( struct oncrpc_cred_sys *auth_sys ) {
+ if ( ! auth_sys )
+ return -EINVAL;
+
+ fetch_string_setting_copy ( NULL, &hostname_setting,
+ &auth_sys->hostname );
+ if ( ! auth_sys->hostname )
+ if ( ! ( auth_sys->hostname = strdup ( product_short_name ) ) )
+ return -ENOMEM;
+
+ auth_sys->uid = fetch_uintz_setting ( NULL, &uid_setting );
+ auth_sys->gid = fetch_uintz_setting ( NULL, &uid_setting );
+ auth_sys->aux_gid_len = 0;
+ auth_sys->stamp = 0;
+
+ auth_sys->credential.flavor = ONCRPC_AUTH_SYS;
+ auth_sys->credential.length = 16 +
+ oncrpc_strlen ( auth_sys->hostname );
+
+ return 0;
+}
+
+/**
+ * Prepare an ONC RPC session structure to be used by the ONC RPC layer
+ *
+ * @v session ONC RPC session
+ * @v credential Credential structure pointer
+ * @v verifier Verifier structure pointer
+ * @v prog_name ONC RPC program number
+ * @v prog_vers ONC RPC program version number
+ */
+void oncrpc_init_session ( struct oncrpc_session *session,
+ struct oncrpc_cred *credential,
+ struct oncrpc_cred *verifier, uint32_t prog_name,
+ uint32_t prog_vers ) {
+ if ( ! session )
+ return;
+
+ session->rpc_id = rand();
+ session->credential = credential;
+ session->verifier = verifier;
+ session->prog_name = prog_name;
+ session->prog_vers = prog_vers;
+}
+
+int oncrpc_call ( struct interface *intf, struct oncrpc_session *session,
+ uint32_t proc_name, const struct oncrpc_field fields[] ) {
+ int rc;
+ size_t frame_size;
+ struct io_buffer *io_buf;
+
+ if ( ! session )
+ return -EINVAL;
+
+ struct oncrpc_field header[] = {
+ ONCRPC_FIELD ( int32, 0 ),
+ ONCRPC_FIELD ( int32, ++session->rpc_id ),
+ ONCRPC_FIELD ( int32, ONCRPC_CALL ),
+ ONCRPC_FIELD ( int32, ONCRPC_VERS ),
+ ONCRPC_FIELD ( int32, session->prog_name ),
+ ONCRPC_FIELD ( int32, session->prog_vers ),
+ ONCRPC_FIELD ( int32, proc_name ),
+ ONCRPC_FIELD ( cred, session->credential ),
+ ONCRPC_FIELD ( cred, session->verifier ),
+ ONCRPC_FIELD_END,
+ };
+
+ frame_size = oncrpc_compute_size ( header );
+ frame_size += oncrpc_compute_size ( fields );
+
+ io_buf = alloc_iob ( frame_size );
+ if ( ! io_buf )
+ return -ENOBUFS;
+
+ header[0].value.int32 = SET_LAST_FRAME ( frame_size -
+ sizeof ( uint32_t ) );
+
+ oncrpc_iob_add_fields ( io_buf, header );
+ oncrpc_iob_add_fields ( io_buf, fields );
+
+ rc = xfer_deliver_iob ( intf, io_buf );
+ if ( rc != 0 )
+ free_iob ( io_buf );
+
+ return rc;
+}
+
+size_t oncrpc_compute_size ( const struct oncrpc_field fields[] ) {
+
+ size_t i;
+ size_t size = 0;
+
+ for ( i = 0; fields[i].type != oncrpc_none; i++ ) {
+ switch ( fields[i].type ) {
+ case oncrpc_int32:
+ size += sizeof ( uint32_t );
+ break;
+
+ case oncrpc_int64:
+ size += sizeof ( uint64_t );
+ break;
+
+ case oncrpc_str:
+ size += oncrpc_strlen ( fields[i].value.str );
+ break;
+
+ case oncrpc_array:
+ size += oncrpc_align ( fields[i].value.array.length );
+ size += sizeof ( uint32_t );
+ break;
+
+ case oncrpc_intarray:
+ size += sizeof ( uint32_t ) *
+ fields[i].value.intarray.length;
+ size += sizeof ( uint32_t );
+ break;
+
+ case oncrpc_cred:
+ size += fields[i].value.cred->length;
+ size += 2 * sizeof ( uint32_t );
+ break;
+
+ default:
+ return size;
+ }
+ }
+
+ return size;
+}
+
+/**
+ * Parse an I/O buffer to extract a ONC RPC REPLY
+ * @v session ONC RPC session
+ * @v reply Reply structure where data will be saved
+ * @v io_buf I/O buffer
+ */
+int oncrpc_get_reply ( struct oncrpc_session *session __unused,
+ struct oncrpc_reply *reply, struct io_buffer *io_buf ) {
+ if ( ! reply || ! io_buf )
+ return -EINVAL;
+
+ reply->frame_size = GET_FRAME_SIZE ( oncrpc_iob_get_int ( io_buf ) );
+ reply->rpc_id = oncrpc_iob_get_int ( io_buf );
+
+ /* iPXE has no support for handling ONC RPC call */
+ if ( oncrpc_iob_get_int ( io_buf ) != ONCRPC_REPLY )
+ return -ENOSYS;
+
+ reply->reply_state = oncrpc_iob_get_int ( io_buf );
+
+ if ( reply->reply_state == 0 )
+ {
+ /* verifier.flavor */
+ oncrpc_iob_get_int ( io_buf );
+ /* verifier.length */
+ iob_pull ( io_buf, oncrpc_iob_get_int ( io_buf ));
+
+ /* We don't use the verifier in iPXE, let it be an empty
+ verifier. */
+ reply->verifier = &oncrpc_auth_none;
+ }
+
+ reply->accept_state = oncrpc_iob_get_int ( io_buf );
+ reply->data = io_buf;
+
+ return 0;
+}
diff --git a/qemu/roms/ipxe/src/net/tcp/syslogs.c b/qemu/roms/ipxe/src/net/tcp/syslogs.c
new file mode 100644
index 000000000..095afc543
--- /dev/null
+++ b/qemu/roms/ipxe/src/net/tcp/syslogs.c
@@ -0,0 +1,269 @@
+/*
+ * Copyright (C) 2012 Michael Brown <mbrown@fensystems.co.uk>.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation; either version 2 of the
+ * License, or any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+FILE_LICENCE ( GPL2_OR_LATER );
+
+/** @file
+ *
+ * Encrypted syslog protocol
+ *
+ */
+
+#include <stdint.h>
+#include <stdlib.h>
+#include <byteswap.h>
+#include <ipxe/xfer.h>
+#include <ipxe/open.h>
+#include <ipxe/tcpip.h>
+#include <ipxe/dhcp.h>
+#include <ipxe/settings.h>
+#include <ipxe/console.h>
+#include <ipxe/lineconsole.h>
+#include <ipxe/tls.h>
+#include <ipxe/syslog.h>
+#include <config/console.h>
+
+/* Set default console usage if applicable */
+#if ! ( defined ( CONSOLE_SYSLOGS ) && CONSOLE_EXPLICIT ( CONSOLE_SYSLOGS ) )
+#undef CONSOLE_SYSLOGS
+#define CONSOLE_SYSLOGS ( CONSOLE_USAGE_ALL & ~CONSOLE_USAGE_TUI )
+#endif
+
+struct console_driver syslogs_console __console_driver;
+
+/** The encrypted syslog server */
+static struct sockaddr_tcpip logserver = {
+ .st_port = htons ( SYSLOG_PORT ),
+};
+
+/**
+ * Handle encrypted syslog TLS interface close
+ *
+ * @v intf Interface
+ * @v rc Reason for close
+ */
+static void syslogs_close ( struct interface *intf __unused, int rc ) {
+
+ DBG ( "SYSLOGS console disconnected: %s\n", strerror ( rc ) );
+}
+
+/**
+ * Handle encrypted syslog TLS interface window change
+ *
+ * @v intf Interface
+ */
+static void syslogs_window_changed ( struct interface *intf ) {
+
+ /* Mark console as enabled when window first opens, indicating
+ * that TLS negotiation is complete. (Do not disable console
+ * when window closes again, since TCP will close the window
+ * whenever there is unACKed data.)
+ */
+ if ( xfer_window ( intf ) ) {
+ if ( syslogs_console.disabled )
+ DBG ( "SYSLOGS console connected\n" );
+ syslogs_console.disabled = 0;
+ }
+}
+
+/** Encrypted syslog TLS interface operations */
+static struct interface_operation syslogs_operations[] = {
+ INTF_OP ( xfer_window_changed, struct interface *,
+ syslogs_window_changed ),
+ INTF_OP ( intf_close, struct interface *, syslogs_close ),
+};
+
+/** Encrypted syslog TLS interface descriptor */
+static struct interface_descriptor syslogs_desc =
+ INTF_DESC_PURE ( syslogs_operations );
+
+/** The encrypted syslog TLS interface */
+static struct interface syslogs = INTF_INIT ( syslogs_desc );
+
+/******************************************************************************
+ *
+ * Console driver
+ *
+ ******************************************************************************
+ */
+
+/** Encrypted syslog line buffer */
+static char syslogs_buffer[SYSLOG_BUFSIZE];
+
+/** Encrypted syslog severity */
+static unsigned int syslogs_severity = SYSLOG_DEFAULT_SEVERITY;
+
+/**
+ * Handle ANSI set encrypted syslog priority (private sequence)
+ *
+ * @v ctx ANSI escape sequence context
+ * @v count Parameter count
+ * @v params List of graphic rendition aspects
+ */
+static void syslogs_handle_priority ( struct ansiesc_context *ctx __unused,
+ unsigned int count __unused,
+ int params[] ) {
+ if ( params[0] >= 0 ) {
+ syslogs_severity = params[0];
+ } else {
+ syslogs_severity = SYSLOG_DEFAULT_SEVERITY;
+ }
+}
+
+/** Encrypted syslog ANSI escape sequence handlers */
+static struct ansiesc_handler syslogs_handlers[] = {
+ { ANSIESC_LOG_PRIORITY, syslogs_handle_priority },
+ { 0, NULL }
+};
+
+/** Encrypted syslog line console */
+static struct line_console syslogs_line = {
+ .buffer = syslogs_buffer,
+ .len = sizeof ( syslogs_buffer ),
+ .ctx = {
+ .handlers = syslogs_handlers,
+ },
+};
+
+/** Encrypted syslog recursion marker */
+static int syslogs_entered;
+
+/**
+ * Print a character to encrypted syslog console
+ *
+ * @v character Character to be printed
+ */
+static void syslogs_putchar ( int character ) {
+ int rc;
+
+ /* Ignore if we are already mid-logging */
+ if ( syslogs_entered )
+ return;
+
+ /* Fill line buffer */
+ if ( line_putchar ( &syslogs_line, character ) == 0 )
+ return;
+
+ /* Guard against re-entry */
+ syslogs_entered = 1;
+
+ /* Send log message */
+ if ( ( rc = syslog_send ( &syslogs, syslogs_severity,
+ syslogs_buffer, "\n" ) ) != 0 ) {
+ DBG ( "SYSLOGS could not send log message: %s\n",
+ strerror ( rc ) );
+ }
+
+ /* Clear re-entry flag */
+ syslogs_entered = 0;
+}
+
+/** Encrypted syslog console driver */
+struct console_driver syslogs_console __console_driver = {
+ .putchar = syslogs_putchar,
+ .disabled = CONSOLE_DISABLED,
+ .usage = CONSOLE_SYSLOGS,
+};
+
+/******************************************************************************
+ *
+ * Settings
+ *
+ ******************************************************************************
+ */
+
+/** Encrypted syslog server setting */
+const struct setting syslogs_setting __setting ( SETTING_MISC, syslogs ) = {
+ .name = "syslogs",
+ .description = "Encrypted syslog server",
+ .tag = DHCP_EB_SYSLOGS_SERVER,
+ .type = &setting_type_string,
+};
+
+/**
+ * Apply encrypted syslog settings
+ *
+ * @ret rc Return status code
+ */
+static int apply_syslogs_settings ( void ) {
+ static char *old_server;
+ char *server;
+ struct interface *socket;
+ int rc;
+
+ /* Fetch log server */
+ fetch_string_setting_copy ( NULL, &syslogs_setting, &server );
+
+ /* Do nothing unless log server has changed */
+ if ( ( ( server == NULL ) && ( old_server == NULL ) ) ||
+ ( ( server != NULL ) && ( old_server != NULL ) &&
+ ( strcmp ( server, old_server ) == 0 ) ) ) {
+ rc = 0;
+ goto out_no_change;
+ }
+ free ( old_server );
+ old_server = NULL;
+
+ /* Reset encrypted syslog connection */
+ syslogs_console.disabled = CONSOLE_DISABLED;
+ intf_restart ( &syslogs, 0 );
+
+ /* Do nothing unless we have a log server */
+ if ( ! server ) {
+ DBG ( "SYSLOGS has no log server\n" );
+ rc = 0;
+ goto out_no_server;
+ }
+
+ /* Add TLS filter */
+ if ( ( rc = add_tls ( &syslogs, server, &socket ) ) != 0 ) {
+ DBG ( "SYSLOGS cannot create TLS filter: %s\n",
+ strerror ( rc ) );
+ goto err_add_tls;
+ }
+
+ /* Connect to log server */
+ if ( ( rc = xfer_open_named_socket ( socket, SOCK_STREAM,
+ (( struct sockaddr *) &logserver ),
+ server, NULL ) ) != 0 ) {
+ DBG ( "SYSLOGS cannot connect to log server: %s\n",
+ strerror ( rc ) );
+ goto err_open_named_socket;
+ }
+ DBG ( "SYSLOGS using log server %s\n", server );
+
+ /* Record log server */
+ old_server = server;
+ server = NULL;
+
+ /* Success */
+ rc = 0;
+
+ err_open_named_socket:
+ err_add_tls:
+ out_no_server:
+ out_no_change:
+ free ( server );
+ return rc;
+}
+
+/** Encrypted syslog settings applicator */
+struct settings_applicator syslogs_applicator __settings_applicator = {
+ .apply = apply_syslogs_settings,
+};