diff options
Diffstat (limited to 'roms/ipxe/src/net/tcp')
-rw-r--r-- | roms/ipxe/src/net/tcp/ftp.c | 546 | ||||
-rw-r--r-- | roms/ipxe/src/net/tcp/http.c | 49 | ||||
-rw-r--r-- | roms/ipxe/src/net/tcp/httpauth.c | 145 | ||||
-rw-r--r-- | roms/ipxe/src/net/tcp/httpbasic.c | 122 | ||||
-rw-r--r-- | roms/ipxe/src/net/tcp/httpblock.c | 116 | ||||
-rw-r--r-- | roms/ipxe/src/net/tcp/httpconn.c | 324 | ||||
-rw-r--r-- | roms/ipxe/src/net/tcp/httpcore.c | 1966 | ||||
-rw-r--r-- | roms/ipxe/src/net/tcp/httpdigest.c | 309 | ||||
-rw-r--r-- | roms/ipxe/src/net/tcp/httpgce.c | 72 | ||||
-rw-r--r-- | roms/ipxe/src/net/tcp/httpntlm.c | 220 | ||||
-rw-r--r-- | roms/ipxe/src/net/tcp/https.c | 51 | ||||
-rw-r--r-- | roms/ipxe/src/net/tcp/iscsi.c | 2200 | ||||
-rw-r--r-- | roms/ipxe/src/net/tcp/oncrpc.c | 245 | ||||
-rw-r--r-- | roms/ipxe/src/net/tcp/syslogs.c | 273 |
14 files changed, 6638 insertions, 0 deletions
diff --git a/roms/ipxe/src/net/tcp/ftp.c b/roms/ipxe/src/net/tcp/ftp.c new file mode 100644 index 000000000..be7a7c3b5 --- /dev/null +++ b/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/roms/ipxe/src/net/tcp/http.c b/roms/ipxe/src/net/tcp/http.c new file mode 100644 index 000000000..b000ed80f --- /dev/null +++ b/roms/ipxe/src/net/tcp/http.c @@ -0,0 +1,49 @@ +/* + * 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. + * + * You can also choose to distribute this program under the terms of + * the Unmodified Binary Distribution Licence (as given in the file + * COPYING.UBDL), provided that you have satisfied its requirements. + */ + +FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL ); + +/** + * @file + * + * Hyper Text Transfer Protocol (HTTP) + * + */ + +#include <ipxe/open.h> +#include <ipxe/http.h> +#include <ipxe/features.h> + +FEATURE ( FEATURE_PROTOCOL, "HTTP", DHCP_EB_FEATURE_HTTP, 1 ); + +/** HTTP URI opener */ +struct uri_opener http_uri_opener __uri_opener = { + .scheme = "http", + .open = http_open_uri, +}; + +/** HTTP URI scheme */ +struct http_scheme http_scheme __http_scheme = { + .name = "http", + .port = HTTP_PORT, +}; diff --git a/roms/ipxe/src/net/tcp/httpauth.c b/roms/ipxe/src/net/tcp/httpauth.c new file mode 100644 index 000000000..2c57e3d48 --- /dev/null +++ b/roms/ipxe/src/net/tcp/httpauth.c @@ -0,0 +1,145 @@ +/* + * Copyright (C) 2015 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. + * + * You can also choose to distribute this program under the terms of + * the Unmodified Binary Distribution Licence (as given in the file + * COPYING.UBDL), provided that you have satisfied its requirements. + */ + +FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL ); + +/** + * @file + * + * Hyper Text Transfer Protocol (HTTP) authentication + * + */ + +#include <stdio.h> +#include <strings.h> +#include <errno.h> +#include <ipxe/http.h> + +/** + * Identify authentication scheme + * + * @v http HTTP transaction + * @v name Scheme name + * @ret auth Authentication scheme, or NULL + */ +static struct http_authentication * http_authentication ( const char *name ) { + struct http_authentication *auth; + + /* Identify authentication scheme */ + for_each_table_entry ( auth, HTTP_AUTHENTICATIONS ) { + if ( strcasecmp ( name, auth->name ) == 0 ) + return auth; + } + + return NULL; +} + +/** + * Parse HTTP "WWW-Authenticate" header + * + * @v http HTTP transaction + * @v line Remaining header line + * @ret rc Return status code + */ +static int http_parse_www_authenticate ( struct http_transaction *http, + char *line ) { + struct http_authentication *auth; + char *name; + int rc; + + /* Get scheme name */ + name = http_token ( &line, NULL ); + if ( ! name ) { + DBGC ( http, "HTTP %p malformed WWW-Authenticate \"%s\"\n", + http, line ); + return -EPROTO; + } + + /* Identify scheme */ + auth = http_authentication ( name ); + if ( ! auth ) { + DBGC ( http, "HTTP %p unrecognised authentication scheme " + "\"%s\"\n", http, name ); + /* Ignore; the server may offer other schemes */ + return 0; + } + + /* Use first supported scheme */ + if ( http->response.auth.auth ) + return 0; + http->response.auth.auth = auth; + + /* Parse remaining header line */ + if ( ( rc = auth->parse ( http, line ) ) != 0 ) { + DBGC ( http, "HTTP %p could not parse %s WWW-Authenticate " + "\"%s\": %s\n", http, name, line, strerror ( rc ) ); + return rc; + } + + return 0; +} + +/** HTTP "WWW-Authenticate" header */ +struct http_response_header +http_response_www_authenticate __http_response_header = { + .name = "WWW-Authenticate", + .parse = http_parse_www_authenticate, +}; + +/** + * Construct HTTP "Authorization" header + * + * @v http HTTP transaction + * @v buf Buffer + * @v len Length of buffer + * @ret len Length of header value, or negative error + */ +static int http_format_authorization ( struct http_transaction *http, + char *buf, size_t len ) { + struct http_authentication *auth = http->request.auth.auth; + size_t used; + int auth_len; + int rc; + + /* Do nothing unless we have an authentication scheme */ + if ( ! auth ) + return 0; + + /* Construct header */ + used = snprintf ( buf, len, "%s ", auth->name ); + auth_len = auth->format ( http, ( buf + used ), + ( ( used < len ) ? ( len - used ) : 0 ) ); + if ( auth_len < 0 ) { + rc = auth_len; + return rc; + } + used += auth_len; + + return used; +} + +/** HTTP "Authorization" header */ +struct http_request_header http_request_authorization __http_request_header = { + .name = "Authorization", + .format = http_format_authorization, +}; diff --git a/roms/ipxe/src/net/tcp/httpbasic.c b/roms/ipxe/src/net/tcp/httpbasic.c new file mode 100644 index 000000000..52a67063d --- /dev/null +++ b/roms/ipxe/src/net/tcp/httpbasic.c @@ -0,0 +1,122 @@ +/* + * Copyright (C) 2015 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. + * + * You can also choose to distribute this program under the terms of + * the Unmodified Binary Distribution Licence (as given in the file + * COPYING.UBDL), provided that you have satisfied its requirements. + */ + +FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL ); + +/** + * @file + * + * Hyper Text Transfer Protocol (HTTP) Basic authentication + * + */ + +#include <stdio.h> +#include <errno.h> +#include <ipxe/uri.h> +#include <ipxe/base64.h> +#include <ipxe/http.h> + +/* Disambiguate the various error causes */ +#define EACCES_USERNAME __einfo_error ( EINFO_EACCES_USERNAME ) +#define EINFO_EACCES_USERNAME \ + __einfo_uniqify ( EINFO_EACCES, 0x01, \ + "No username available for Basic authentication" ) + +/** + * Parse HTTP "WWW-Authenticate" header for Basic authentication + * + * @v http HTTP transaction + * @v line Remaining header line + * @ret rc Return status code + */ +static int http_parse_basic_auth ( struct http_transaction *http, + char *line __unused ) { + + /* Allow HTTP request to be retried if the request had not + * already tried authentication. + */ + if ( ! http->request.auth.auth ) + http->response.flags |= HTTP_RESPONSE_RETRY; + + return 0; +} + +/** + * Perform HTTP Basic authentication + * + * @v http HTTP transaction + * @ret rc Return status code + */ +static int http_basic_authenticate ( struct http_transaction *http ) { + struct http_request_auth_basic *req = &http->request.auth.basic; + + /* Record username and password */ + if ( ! http->uri->user ) { + DBGC ( http, "HTTP %p has no username for Basic " + "authentication\n", http ); + return -EACCES_USERNAME; + } + req->username = http->uri->user; + req->password = ( http->uri->password ? http->uri->password : "" ); + + return 0; +} + +/** + * Construct HTTP "Authorization" header for Basic authentication + * + * @v http HTTP transaction + * @v buf Buffer + * @v len Length of buffer + * @ret len Length of header value, or negative error + */ +static int http_format_basic_auth ( struct http_transaction *http, + char *buf, size_t len ) { + struct http_request_auth_basic *req = &http->request.auth.basic; + size_t user_pw_len = ( strlen ( req->username ) + 1 /* ":" */ + + strlen ( req->password ) ); + char user_pw[ user_pw_len + 1 /* NUL */ ]; + + /* Sanity checks */ + assert ( req->username != NULL ); + assert ( req->password != NULL ); + + /* Construct "user:password" string */ + snprintf ( user_pw, sizeof ( user_pw ), "%s:%s", + req->username, req->password ); + + /* Construct response */ + return base64_encode ( user_pw, user_pw_len, buf, len ); +} + +/** HTTP Basic authentication scheme */ +struct http_authentication http_basic_auth __http_authentication = { + .name = "Basic", + .parse = http_parse_basic_auth, + .authenticate = http_basic_authenticate, + .format = http_format_basic_auth, +}; + +/* Drag in HTTP authentication support */ +REQUIRING_SYMBOL ( http_basic_auth ); +REQUIRE_OBJECT ( httpauth ); diff --git a/roms/ipxe/src/net/tcp/httpblock.c b/roms/ipxe/src/net/tcp/httpblock.c new file mode 100644 index 000000000..1abd6b34d --- /dev/null +++ b/roms/ipxe/src/net/tcp/httpblock.c @@ -0,0 +1,116 @@ +/* + * Copyright (C) 2015 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. + * + * You can also choose to distribute this program under the terms of + * the Unmodified Binary Distribution Licence (as given in the file + * COPYING.UBDL), provided that you have satisfied its requirements. + */ + +FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL ); + +/** + * @file + * + * Hyper Text Transfer Protocol (HTTP) block device + * + */ + +#include <stdint.h> +#include <ipxe/uaccess.h> +#include <ipxe/blocktrans.h> +#include <ipxe/blockdev.h> +#include <ipxe/acpi.h> +#include <ipxe/http.h> + +/** Block size used for HTTP block device requests */ +#define HTTP_BLKSIZE 512 + +/** + * Read from block device + * + * @v http HTTP transaction + * @v data Data interface + * @v lba Starting logical block address + * @v count Number of logical blocks + * @v buffer Data buffer + * @v len Length of data buffer + * @ret rc Return status code + */ +int http_block_read ( struct http_transaction *http, struct interface *data, + uint64_t lba, unsigned int count, userptr_t buffer, + size_t len ) { + struct http_request_range range; + int rc; + + /* Sanity check */ + assert ( len == ( count * HTTP_BLKSIZE ) ); + + /* Construct request range descriptor */ + range.start = ( lba * HTTP_BLKSIZE ); + range.len = len; + + /* Start a range request to retrieve the block(s) */ + if ( ( rc = http_open ( data, &http_get, http->uri, &range, + NULL ) ) != 0 ) + goto err_open; + + /* Insert block device translator */ + if ( ( rc = block_translate ( data, buffer, len ) ) != 0 ) { + DBGC ( http, "HTTP %p could not insert block translator: %s\n", + http, strerror ( rc ) ); + goto err_translate; + } + + return 0; + + err_translate: + intf_restart ( data, rc ); + err_open: + return rc; +} + +/** + * Read block device capacity + * + * @v control Control interface + * @v data Data interface + * @ret rc Return status code + */ +int http_block_read_capacity ( struct http_transaction *http, + struct interface *data ) { + int rc; + + /* Start a HEAD request to retrieve the capacity */ + if ( ( rc = http_open ( data, &http_head, http->uri, NULL, + NULL ) ) != 0 ) + goto err_open; + + /* Insert block device translator */ + if ( ( rc = block_translate ( data, UNULL, HTTP_BLKSIZE ) ) != 0 ) { + DBGC ( http, "HTTP %p could not insert block translator: %s\n", + http, strerror ( rc ) ); + goto err_translate; + } + + return 0; + + err_translate: + intf_restart ( data, rc ); + err_open: + return rc; +} diff --git a/roms/ipxe/src/net/tcp/httpconn.c b/roms/ipxe/src/net/tcp/httpconn.c new file mode 100644 index 000000000..5121ff6c2 --- /dev/null +++ b/roms/ipxe/src/net/tcp/httpconn.c @@ -0,0 +1,324 @@ +/* + * Copyright (C) 2015 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. + * + * You can also choose to distribute this program under the terms of + * the Unmodified Binary Distribution Licence (as given in the file + * COPYING.UBDL), provided that you have satisfied its requirements. + */ + +FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL ); + +/** + * @file + * + * Hyper Text Transfer Protocol (HTTP) connection management + * + */ + +#include <stdlib.h> +#include <string.h> +#include <errno.h> +#include <byteswap.h> +#include <ipxe/tcpip.h> +#include <ipxe/uri.h> +#include <ipxe/timer.h> +#include <ipxe/xfer.h> +#include <ipxe/open.h> +#include <ipxe/pool.h> +#include <ipxe/http.h> + +/** HTTP pooled connection expiry time */ +#define HTTP_CONN_EXPIRY ( 10 * TICKS_PER_SEC ) + +/** HTTP connection pool */ +static LIST_HEAD ( http_connection_pool ); + +/** + * Identify HTTP scheme + * + * @v uri URI + * @ret scheme HTTP scheme, or NULL + */ +static struct http_scheme * http_scheme ( struct uri *uri ) { + struct http_scheme *scheme; + + /* Sanity check */ + if ( ! uri->scheme ) + return NULL; + + /* Identify scheme */ + for_each_table_entry ( scheme, HTTP_SCHEMES ) { + if ( strcmp ( uri->scheme, scheme->name ) == 0 ) + return scheme; + } + + return NULL; +} + +/** + * Free HTTP connection + * + * @v refcnt Reference count + */ +static void http_conn_free ( struct refcnt *refcnt ) { + struct http_connection *conn = + container_of ( refcnt, struct http_connection, refcnt ); + + /* Free connection */ + uri_put ( conn->uri ); + free ( conn ); +} + +/** + * Close HTTP connection + * + * @v conn HTTP connection + * @v rc Reason for close + */ +static void http_conn_close ( struct http_connection *conn, int rc ) { + + /* Remove from connection pool, if applicable */ + pool_del ( &conn->pool ); + + /* Shut down interfaces */ + intf_shutdown ( &conn->socket, rc ); + intf_shutdown ( &conn->xfer, rc ); + if ( rc == 0 ) { + DBGC2 ( conn, "HTTPCONN %p closed %s://%s\n", + conn, conn->scheme->name, conn->uri->host ); + } else { + DBGC ( conn, "HTTPCONN %p closed %s://%s: %s\n", + conn, conn->scheme->name, conn->uri->host, + strerror ( rc ) ); + } +} + +/** + * Disconnect idle HTTP connection + * + * @v pool Pooled connection + */ +static void http_conn_expired ( struct pooled_connection *pool ) { + struct http_connection *conn = + container_of ( pool, struct http_connection, pool ); + + /* Close connection */ + http_conn_close ( conn, 0 /* Not an error to close idle connection */ ); +} + +/** + * Receive data from transport layer interface + * + * @v http HTTP connection + * @v iobuf I/O buffer + * @v meta Transfer metadata + * @ret rc Return status code + */ +static int http_conn_socket_deliver ( struct http_connection *conn, + struct io_buffer *iobuf, + struct xfer_metadata *meta ) { + + /* Mark connection as alive */ + pool_alive ( &conn->pool ); + + /* Pass on to data transfer interface */ + return xfer_deliver ( &conn->xfer, iobuf, meta ); +} + +/** + * Close HTTP connection transport layer interface + * + * @v http HTTP connection + * @v rc Reason for close + */ +static void http_conn_socket_close ( struct http_connection *conn, int rc ) { + + /* If we are reopenable (i.e. we are a recycled connection + * from the connection pool, and we have received no data from + * the underlying socket since we were pooled), then suggest + * that the client should reopen the connection. + */ + if ( pool_is_reopenable ( &conn->pool ) ) + pool_reopen ( &conn->xfer ); + + /* Close the connection */ + http_conn_close ( conn, rc ); +} + +/** + * Recycle this connection after closing + * + * @v http HTTP connection + */ +static void http_conn_xfer_recycle ( struct http_connection *conn ) { + + /* Mark connection as recyclable */ + pool_recyclable ( &conn->pool ); + DBGC2 ( conn, "HTTPCONN %p keepalive enabled\n", conn ); +} + +/** + * Close HTTP connection data transfer interface + * + * @v conn HTTP connection + * @v rc Reason for close + */ +static void http_conn_xfer_close ( struct http_connection *conn, int rc ) { + + /* Add to the connection pool if keepalive is enabled and no + * error occurred. + */ + if ( ( rc == 0 ) && pool_is_recyclable ( &conn->pool ) ) { + intf_restart ( &conn->xfer, rc ); + pool_add ( &conn->pool, &http_connection_pool, + HTTP_CONN_EXPIRY ); + DBGC2 ( conn, "HTTPCONN %p pooled %s://%s\n", + conn, conn->scheme->name, conn->uri->host ); + return; + } + + /* Otherwise, close the connection */ + http_conn_close ( conn, rc ); +} + +/** HTTP connection socket interface operations */ +static struct interface_operation http_conn_socket_operations[] = { + INTF_OP ( xfer_deliver, struct http_connection *, + http_conn_socket_deliver ), + INTF_OP ( intf_close, struct http_connection *, + http_conn_socket_close ), +}; + +/** HTTP connection socket interface descriptor */ +static struct interface_descriptor http_conn_socket_desc = + INTF_DESC_PASSTHRU ( struct http_connection, socket, + http_conn_socket_operations, xfer ); + +/** HTTP connection data transfer interface operations */ +static struct interface_operation http_conn_xfer_operations[] = { + INTF_OP ( pool_recycle, struct http_connection *, + http_conn_xfer_recycle ), + INTF_OP ( intf_close, struct http_connection *, + http_conn_xfer_close ), +}; + +/** HTTP connection data transfer interface descriptor */ +static struct interface_descriptor http_conn_xfer_desc = + INTF_DESC_PASSTHRU ( struct http_connection, xfer, + http_conn_xfer_operations, socket ); + +/** + * Connect to an HTTP server + * + * @v xfer Data transfer interface + * @v uri Connection URI + * @ret rc Return status code + * + * HTTP connections are pooled. The caller should be prepared to + * receive a pool_reopen() message. + */ +int http_connect ( struct interface *xfer, struct uri *uri ) { + struct http_connection *conn; + struct http_scheme *scheme; + struct sockaddr_tcpip server; + struct interface *socket; + unsigned int port; + int rc; + + /* Identify scheme */ + scheme = http_scheme ( uri ); + if ( ! scheme ) + return -ENOTSUP; + + /* Sanity check */ + if ( ! uri->host ) + return -EINVAL; + + /* Identify port */ + port = uri_port ( uri, scheme->port ); + + /* Look for a reusable connection in the pool. Reuse the most + * recent connection in order to accommodate authentication + * schemes that break the stateless nature of HTTP and rely on + * the same connection being reused for authentication + * responses. + */ + list_for_each_entry_reverse ( conn, &http_connection_pool, pool.list ) { + + /* Sanity checks */ + assert ( conn->uri != NULL ); + assert ( conn->uri->host != NULL ); + + /* Reuse connection, if possible */ + if ( ( scheme == conn->scheme ) && + ( strcmp ( uri->host, conn->uri->host ) == 0 ) && + ( port == uri_port ( conn->uri, scheme->port ) ) ) { + + /* Remove from connection pool, stop timer, + * attach to parent interface, and return. + */ + pool_del ( &conn->pool ); + intf_plug_plug ( &conn->xfer, xfer ); + DBGC2 ( conn, "HTTPCONN %p reused %s://%s:%d\n", conn, + conn->scheme->name, conn->uri->host, port ); + return 0; + } + } + + /* Allocate and initialise structure */ + conn = zalloc ( sizeof ( *conn ) ); + if ( ! conn ) { + rc = -ENOMEM; + goto err_alloc; + } + ref_init ( &conn->refcnt, http_conn_free ); + conn->uri = uri_get ( uri ); + conn->scheme = scheme; + intf_init ( &conn->socket, &http_conn_socket_desc, &conn->refcnt ); + intf_init ( &conn->xfer, &http_conn_xfer_desc, &conn->refcnt ); + pool_init ( &conn->pool, http_conn_expired, &conn->refcnt ); + + /* Open socket */ + memset ( &server, 0, sizeof ( server ) ); + server.st_port = htons ( port ); + socket = &conn->socket; + if ( scheme->filter && + ( ( rc = scheme->filter ( socket, uri->host, &socket ) ) != 0 ) ) + goto err_filter; + if ( ( rc = xfer_open_named_socket ( socket, SOCK_STREAM, + ( struct sockaddr * ) &server, + uri->host, NULL ) ) != 0 ) + goto err_open; + + /* Attach to parent interface, mortalise self, and return */ + intf_plug_plug ( &conn->xfer, xfer ); + ref_put ( &conn->refcnt ); + + DBGC2 ( conn, "HTTPCONN %p created %s://%s:%d\n", conn, + conn->scheme->name, conn->uri->host, port ); + return 0; + + err_open: + err_filter: + DBGC2 ( conn, "HTTPCONN %p could not create %s://%s:%d: %s\n", conn, + conn->scheme->name, conn->uri->host, port, strerror ( rc ) ); + http_conn_close ( conn, rc ); + ref_put ( &conn->refcnt ); + err_alloc: + return rc; +} diff --git a/roms/ipxe/src/net/tcp/httpcore.c b/roms/ipxe/src/net/tcp/httpcore.c new file mode 100644 index 000000000..f755fb72d --- /dev/null +++ b/roms/ipxe/src/net/tcp/httpcore.c @@ -0,0 +1,1966 @@ +/* + * Copyright (C) 2015 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. + * + * You can also choose to distribute this program under the terms of + * the Unmodified Binary Distribution Licence (as given in the file + * COPYING.UBDL), provided that you have satisfied its requirements. + */ + +FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL ); + +/** + * @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/process.h> +#include <ipxe/retry.h> +#include <ipxe/timer.h> +#include <ipxe/linebuf.h> +#include <ipxe/xferbuf.h> +#include <ipxe/blockdev.h> +#include <ipxe/acpi.h> +#include <ipxe/version.h> +#include <ipxe/params.h> +#include <ipxe/profile.h> +#include <ipxe/vsprintf.h> +#include <ipxe/errortab.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 EINVAL_STATUS __einfo_error ( EINFO_EINVAL_STATUS ) +#define EINFO_EINVAL_STATUS \ + __einfo_uniqify ( EINFO_EINVAL, 0x01, "Invalid status line" ) +#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 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 EIO_4XX __einfo_error ( EINFO_EIO_4XX ) +#define EINFO_EIO_4XX \ + __einfo_uniqify ( EINFO_EIO, 0x04, "HTTP 4xx Client Error" ) +#define EIO_5XX __einfo_error ( EINFO_EIO_5XX ) +#define EINFO_EIO_5XX \ + __einfo_uniqify ( EINFO_EIO, 0x05, "HTTP 5xx Server Error" ) +#define ENOENT_404 __einfo_error ( EINFO_ENOENT_404 ) +#define EINFO_ENOENT_404 \ + __einfo_uniqify ( EINFO_ENOENT, 0x01, "HTTP 404 Not Found" ) +#define ENOTSUP_CONNECTION __einfo_error ( EINFO_ENOTSUP_CONNECTION ) +#define EINFO_ENOTSUP_CONNECTION \ + __einfo_uniqify ( EINFO_ENOTSUP, 0x01, "Unsupported connection header" ) +#define ENOTSUP_TRANSFER __einfo_error ( EINFO_ENOTSUP_TRANSFER ) +#define EINFO_ENOTSUP_TRANSFER \ + __einfo_uniqify ( EINFO_ENOTSUP, 0x02, "Unsupported transfer encoding" ) +#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" ) + +/** 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" }; + +/** Human-readable error messages */ +struct errortab http_errors[] __errortab = { + __einfo_errortab ( EINFO_EIO_4XX ), + __einfo_errortab ( EINFO_EIO_5XX ), +}; + +static struct http_state http_request; +static struct http_state http_headers; +static struct http_state http_trailers; +static struct http_transfer_encoding http_transfer_identity; + +/****************************************************************************** + * + * Methods + * + ****************************************************************************** + */ + +/** HTTP HEAD method */ +struct http_method http_head = { + .name = "HEAD", +}; + +/** HTTP GET method */ +struct http_method http_get = { + .name = "GET", +}; + +/** HTTP POST method */ +struct http_method http_post = { + .name = "POST", +}; + +/****************************************************************************** + * + * Utility functions + * + ****************************************************************************** + */ + +/** + * Handle received HTTP line-buffered data + * + * @v http HTTP transaction + * @v iobuf I/O buffer + * @v linebuf Line buffer + * @ret rc Return status code + */ +static int http_rx_linebuf ( struct http_transaction *http, + struct io_buffer *iobuf, + struct line_buffer *linebuf ) { + int consumed; + int rc; + + /* Buffer received line */ + consumed = line_buffer ( linebuf, iobuf->data, iob_len ( iobuf ) ); + if ( consumed < 0 ) { + rc = consumed; + DBGC ( http, "HTTP %p could not buffer line: %s\n", + http, strerror ( rc ) ); + return rc; + } + + /* Consume line */ + iob_pull ( iobuf, consumed ); + + return 0; +} + +/** + * Get HTTP response token + * + * @v line Line position + * @v value Token value to fill in (if any) + * @ret token Token, or NULL + */ +char * http_token ( char **line, char **value ) { + char *token; + char quote = '\0'; + char c; + + /* Avoid returning uninitialised data */ + if ( value ) + *value = NULL; + + /* Skip any initial whitespace or commas */ + while ( ( isspace ( **line ) ) || ( **line == ',' ) ) + (*line)++; + + /* Check for end of line and record token position */ + if ( ! **line ) + return NULL; + token = *line; + + /* Scan for end of token */ + while ( ( c = **line ) ) { + + /* Terminate if we hit an unquoted whitespace or comma */ + if ( ( isspace ( c ) || ( c == ',' ) ) && ! quote ) + break; + + /* Terminate if we hit a closing quote */ + if ( c == quote ) + break; + + /* Check for value separator */ + if ( value && ( ! *value ) && ( c == '=' ) ) { + + /* Terminate key portion of token */ + *((*line)++) = '\0'; + + /* Check for quote character */ + c = **line; + if ( ( c == '"' ) || ( c == '\'' ) ) { + quote = c; + (*line)++; + } + + /* Record value portion of token */ + *value = *line; + + } else { + + /* Move to next character */ + (*line)++; + } + } + + /* Terminate token, if applicable */ + if ( c ) + *((*line)++) = '\0'; + + return token; +} + +/****************************************************************************** + * + * Transactions + * + ****************************************************************************** + */ + +/** + * Free HTTP transaction + * + * @v refcnt Reference count + */ +static void http_free ( struct refcnt *refcnt ) { + struct http_transaction *http = + container_of ( refcnt, struct http_transaction, refcnt ); + + empty_line_buffer ( &http->response.headers ); + empty_line_buffer ( &http->linebuf ); + uri_put ( http->uri ); + free ( http ); +} + +/** + * Close HTTP transaction + * + * @v http HTTP transaction + * @v rc Reason for close + */ +static void http_close ( struct http_transaction *http, int rc ) { + + /* Stop process */ + process_del ( &http->process ); + + /* Stop timer */ + stop_timer ( &http->timer ); + + /* Close all interfaces */ + intfs_shutdown ( rc, &http->conn, &http->transfer, &http->content, + &http->xfer, NULL ); +} + +/** + * Close HTTP transaction with error (even if none specified) + * + * @v http HTTP transaction + * @v rc Reason for close + */ +static void http_close_error ( struct http_transaction *http, int rc ) { + + /* Treat any close as an error */ + http_close ( http, ( rc ? rc : -EPIPE ) ); +} + +/** + * Reopen stale HTTP connection + * + * @v http HTTP transaction + */ +static void http_reopen ( struct http_transaction *http ) { + int rc; + + /* Close existing connection */ + intf_restart ( &http->conn, -ECANCELED ); + + /* Reopen connection */ + if ( ( rc = http_connect ( &http->conn, http->uri ) ) != 0 ) { + DBGC ( http, "HTTP %p could not reconnect: %s\n", + http, strerror ( rc ) ); + goto err_connect; + } + + /* Reset state */ + http->state = &http_request; + + /* Reschedule transmission process */ + process_add ( &http->process ); + + return; + + err_connect: + http_close ( http, rc ); +} + +/** + * Handle retry timer expiry + * + * @v timer Retry timer + * @v over Failure indicator + */ +static void http_expired ( struct retry_timer *timer, int over __unused ) { + struct http_transaction *http = + container_of ( timer, struct http_transaction, timer ); + + /* Reopen connection */ + http_reopen ( http ); +} + +/** + * HTTP transmit process + * + * @v http HTTP transaction + */ +static void http_step ( struct http_transaction *http ) { + int rc; + + /* Do nothing if we have nothing to transmit */ + if ( ! http->state->tx ) + return; + + /* Do nothing until connection is ready */ + if ( ! xfer_window ( &http->conn ) ) + return; + + /* Notify data transfer interface that window may have changed */ + xfer_window_changed ( &http->xfer ); + + /* Do nothing until data transfer interface is ready */ + if ( ! xfer_window ( &http->xfer ) ) + return; + + /* Transmit data */ + if ( ( rc = http->state->tx ( http ) ) != 0 ) + goto err; + + return; + + err: + http_close ( http, rc ); +} + +/** + * Handle received HTTP data + * + * @v http HTTP transaction + * @v iobuf I/O buffer + * @v meta Transfer metadata + * @ret rc Return status code + * + * This function takes ownership of the I/O buffer. + */ +static int http_conn_deliver ( struct http_transaction *http, + struct io_buffer *iobuf, + struct xfer_metadata *meta __unused ) { + int rc; + + /* Handle received data */ + profile_start ( &http_rx_profiler ); + while ( iobuf && iob_len ( iobuf ) ) { + + /* Sanity check */ + if ( ( ! http->state ) || ( ! http->state->rx ) ) { + DBGC ( http, "HTTP %p unexpected data\n", http ); + rc = -EPROTO_UNSOLICITED; + goto err; + } + + /* Receive (some) data */ + if ( ( rc = http->state->rx ( http, &iobuf ) ) != 0 ) + goto err; + } + + /* Free I/O buffer, if applicable */ + free_iob ( iobuf ); + + profile_stop ( &http_rx_profiler ); + return 0; + + err: + free_iob ( iobuf ); + http_close ( http, rc ); + return rc; +} + +/** + * Handle server connection close + * + * @v http HTTP transaction + * @v rc Reason for close + */ +static void http_conn_close ( struct http_transaction *http, int rc ) { + + /* Sanity checks */ + assert ( http->state != NULL ); + assert ( http->state->close != NULL ); + + /* Restart server connection interface */ + intf_restart ( &http->conn, rc ); + + /* Hand off to state-specific method */ + http->state->close ( http, rc ); +} + +/** + * Handle received content-decoded data + * + * @v http HTTP transaction + * @v iobuf I/O buffer + * @v meta Data transfer metadata + */ +static int http_content_deliver ( struct http_transaction *http, + struct io_buffer *iobuf, + struct xfer_metadata *meta ) { + int rc; + + /* Ignore content if this is anything other than a successful + * transfer. + */ + if ( http->response.rc != 0 ) { + free_iob ( iobuf ); + return 0; + } + + /* Deliver to data transfer interface */ + profile_start ( &http_xfer_profiler ); + if ( ( rc = xfer_deliver ( &http->xfer, iob_disown ( iobuf ), + meta ) ) != 0 ) + return rc; + profile_stop ( &http_xfer_profiler ); + + return 0; +} + +/** + * Get underlying data transfer buffer + * + * @v http HTTP transaction + * @ret xferbuf Data transfer buffer, or NULL on error + */ +static struct xfer_buffer * +http_content_buffer ( struct http_transaction *http ) { + + /* Deny access to the data transfer buffer if this is anything + * other than a successful transfer. + */ + if ( http->response.rc != 0 ) + return NULL; + + /* Hand off to data transfer interface */ + return xfer_buffer ( &http->xfer ); +} + +/** + * Read from block device (when HTTP block device support is not present) + * + * @v http HTTP transaction + * @v data Data interface + * @v lba Starting logical block address + * @v count Number of logical blocks + * @v buffer Data buffer + * @v len Length of data buffer + * @ret rc Return status code + */ +__weak int http_block_read ( struct http_transaction *http __unused, + struct interface *data __unused, + uint64_t lba __unused, unsigned int count __unused, + userptr_t buffer __unused, size_t len __unused ) { + + return -ENOTSUP; +} + +/** + * Read block device capacity (when HTTP block device support is not present) + * + * @v control Control interface + * @v data Data interface + * @ret rc Return status code + */ +__weak int http_block_read_capacity ( struct http_transaction *http __unused, + struct interface *data __unused ) { + + return -ENOTSUP; +} + +/** HTTP data transfer interface operations */ +static struct interface_operation http_xfer_operations[] = { + INTF_OP ( block_read, struct http_transaction *, http_block_read ), + INTF_OP ( block_read_capacity, struct http_transaction *, + http_block_read_capacity ), + INTF_OP ( xfer_window_changed, struct http_transaction *, http_step ), + INTF_OP ( intf_close, struct http_transaction *, http_close ), +}; + +/** HTTP data transfer interface descriptor */ +static struct interface_descriptor http_xfer_desc = + INTF_DESC_PASSTHRU ( struct http_transaction, xfer, + http_xfer_operations, content ); + +/** HTTP content-decoded interface operations */ +static struct interface_operation http_content_operations[] = { + INTF_OP ( xfer_deliver, struct http_transaction *, + http_content_deliver ), + INTF_OP ( xfer_buffer, struct http_transaction *, http_content_buffer ), + INTF_OP ( intf_close, struct http_transaction *, http_close ), +}; + +/** HTTP content-decoded interface descriptor */ +static struct interface_descriptor http_content_desc = + INTF_DESC_PASSTHRU ( struct http_transaction, content, + http_content_operations, xfer ); + +/** HTTP transfer-decoded interface operations */ +static struct interface_operation http_transfer_operations[] = { + INTF_OP ( intf_close, struct http_transaction *, http_close ), +}; + +/** HTTP transfer-decoded interface descriptor */ +static struct interface_descriptor http_transfer_desc = + INTF_DESC_PASSTHRU ( struct http_transaction, transfer, + http_transfer_operations, conn ); + +/** HTTP server connection interface operations */ +static struct interface_operation http_conn_operations[] = { + INTF_OP ( xfer_deliver, struct http_transaction *, http_conn_deliver ), + INTF_OP ( xfer_window_changed, struct http_transaction *, http_step ), + INTF_OP ( pool_reopen, struct http_transaction *, http_reopen ), + INTF_OP ( intf_close, struct http_transaction *, http_conn_close ), +}; + +/** HTTP server connection interface descriptor */ +static struct interface_descriptor http_conn_desc = + INTF_DESC_PASSTHRU ( struct http_transaction, conn, + http_conn_operations, transfer ); + +/** HTTP process descriptor */ +static struct process_descriptor http_process_desc = + PROC_DESC_ONCE ( struct http_transaction, process, http_step ); + +/** + * Open HTTP transaction + * + * @v xfer Data transfer interface + * @v method Request method + * @v uri Request URI + * @v range Content range (if any) + * @v content Request content (if any) + * @ret rc Return status code + */ +int http_open ( struct interface *xfer, struct http_method *method, + struct uri *uri, struct http_request_range *range, + struct http_request_content *content ) { + struct http_transaction *http; + struct uri request_uri; + struct uri request_host; + size_t request_uri_len; + size_t request_host_len; + size_t content_len; + char *request_uri_string; + char *request_host_string; + void *content_data; + int rc; + + /* Calculate request URI length */ + memset ( &request_uri, 0, sizeof ( request_uri ) ); + request_uri.path = ( uri->path ? uri->path : "/" ); + request_uri.query = uri->query; + request_uri_len = + ( format_uri ( &request_uri, NULL, 0 ) + 1 /* NUL */); + + /* Calculate host name length */ + memset ( &request_host, 0, sizeof ( request_host ) ); + request_host.host = uri->host; + request_host.port = uri->port; + request_host_len = + ( format_uri ( &request_host, NULL, 0 ) + 1 /* NUL */ ); + + /* Calculate request content length */ + content_len = ( content ? content->len : 0 ); + + /* Allocate and initialise structure */ + http = zalloc ( sizeof ( *http ) + request_uri_len + request_host_len + + content_len ); + if ( ! http ) { + rc = -ENOMEM; + goto err_alloc; + } + request_uri_string = ( ( ( void * ) http ) + sizeof ( *http ) ); + request_host_string = ( request_uri_string + request_uri_len ); + content_data = ( request_host_string + request_host_len ); + format_uri ( &request_uri, request_uri_string, request_uri_len ); + format_uri ( &request_host, request_host_string, request_host_len ); + ref_init ( &http->refcnt, http_free ); + intf_init ( &http->xfer, &http_xfer_desc, &http->refcnt ); + intf_init ( &http->content, &http_content_desc, &http->refcnt ); + intf_init ( &http->transfer, &http_transfer_desc, &http->refcnt ); + intf_init ( &http->conn, &http_conn_desc, &http->refcnt ); + intf_plug_plug ( &http->transfer, &http->content ); + process_init ( &http->process, &http_process_desc, &http->refcnt ); + timer_init ( &http->timer, http_expired, &http->refcnt ); + http->uri = uri_get ( uri ); + http->request.method = method; + http->request.uri = request_uri_string; + http->request.host = request_host_string; + if ( range ) { + memcpy ( &http->request.range, range, + sizeof ( http->request.range ) ); + } + if ( content ) { + http->request.content.type = content->type; + http->request.content.data = content_data; + http->request.content.len = content_len; + memcpy ( content_data, content->data, content_len ); + } + http->state = &http_request; + DBGC2 ( http, "HTTP %p %s://%s%s\n", http, http->uri->scheme, + http->request.host, http->request.uri ); + + /* Open connection */ + if ( ( rc = http_connect ( &http->conn, uri ) ) != 0 ) { + DBGC ( http, "HTTP %p could not connect: %s\n", + http, strerror ( rc ) ); + goto err_connect; + } + + /* Attach to parent interface, mortalise self, and return */ + intf_plug_plug ( &http->xfer, xfer ); + ref_put ( &http->refcnt ); + return 0; + + err_connect: + http_close ( http, rc ); + ref_put ( &http->refcnt ); + err_alloc: + return rc; +} + +/** + * Redirect HTTP transaction + * + * @v http HTTP transaction + * @v location New location + * @ret rc Return status code + */ +static int http_redirect ( struct http_transaction *http, + const char *location ) { + struct uri *location_uri; + struct uri *resolved_uri; + int rc; + + DBGC2 ( http, "HTTP %p redirecting to \"%s\"\n", http, location ); + + /* Parse location URI */ + location_uri = parse_uri ( location ); + if ( ! location_uri ) { + rc = -ENOMEM; + goto err_parse_uri; + } + + /* Resolve as relative to original URI */ + resolved_uri = resolve_uri ( http->uri, location_uri ); + if ( ! resolved_uri ) { + rc = -ENOMEM; + goto err_resolve_uri; + } + + /* Redirect to new URI */ + if ( ( rc = xfer_redirect ( &http->xfer, LOCATION_URI, + resolved_uri ) ) != 0 ) { + DBGC ( http, "HTTP %p could not redirect: %s\n", + http, strerror ( rc ) ); + goto err_redirect; + } + + err_redirect: + uri_put ( resolved_uri ); + err_resolve_uri: + uri_put ( location_uri ); + err_parse_uri: + return rc; +} + +/** + * Handle successful transfer completion + * + * @v http HTTP transaction + * @ret rc Return status code + */ +static int http_transfer_complete ( struct http_transaction *http ) { + struct http_authentication *auth; + const char *location; + int rc; + + /* Keep connection alive if applicable */ + if ( http->response.flags & HTTP_RESPONSE_KEEPALIVE ) + pool_recycle ( &http->conn ); + + /* Restart server connection interface */ + intf_restart ( &http->conn, 0 ); + + /* No more data is expected */ + http->state = NULL; + + /* If transaction is successful, then close the + * transfer-decoded interface. The content encoding may + * choose whether or not to immediately terminate the + * transaction. + */ + if ( http->response.rc == 0 ) { + intf_shutdown ( &http->transfer, 0 ); + return 0; + } + + /* Perform redirection, if applicable */ + if ( ( location = http->response.location ) ) { + if ( ( rc = http_redirect ( http, location ) ) != 0 ) + return rc; + http_close ( http, 0 ); + return 0; + } + + /* Fail unless a retry is permitted */ + if ( ! ( http->response.flags & HTTP_RESPONSE_RETRY ) ) + return http->response.rc; + + /* Perform authentication, if applicable */ + if ( ( auth = http->response.auth.auth ) ) { + http->request.auth.auth = auth; + DBGC2 ( http, "HTTP %p performing %s authentication\n", + http, auth->name ); + if ( ( rc = auth->authenticate ( http ) ) != 0 ) { + DBGC ( http, "HTTP %p could not authenticate: %s\n", + http, strerror ( rc ) ); + return rc; + } + } + + /* Restart content decoding interfaces */ + intfs_restart ( http->response.rc, &http->content, &http->transfer, + NULL ); + intf_plug_plug ( &http->transfer, &http->content ); + http->len = 0; + assert ( http->remaining == 0 ); + + /* Retry immediately if applicable. We cannot rely on an + * immediate timer expiry, since certain Microsoft-designed + * HTTP extensions such as NTLM break the fundamentally + * stateless nature of HTTP and rely on the same connection + * being reused for authentication. See RFC7230 section 2.3 + * for further details. + */ + if ( ! http->response.retry_after ) { + http_reopen ( http ); + return 0; + } + + /* Start timer to initiate retry */ + DBGC2 ( http, "HTTP %p retrying after %d seconds\n", + http, http->response.retry_after ); + start_timer_fixed ( &http->timer, + ( http->response.retry_after * TICKS_PER_SEC ) ); + return 0; +} + +/****************************************************************************** + * + * Requests + * + ****************************************************************************** + */ + +/** + * Construct HTTP request headers + * + * @v http HTTP transaction + * @v buf Buffer + * @v len Length of buffer + * @ret len Length, or negative error + */ +static int http_format_headers ( struct http_transaction *http, char *buf, + size_t len ) { + struct http_request_header *header; + size_t used; + size_t remaining; + char *line; + int value_len; + int rc; + + /* Construct request line */ + used = ssnprintf ( buf, len, "%s %s HTTP/1.1", + http->request.method->name, http->request.uri ); + if ( used < len ) + DBGC2 ( http, "HTTP %p TX %s\n", http, buf ); + used += ssnprintf ( ( buf + used ), ( len - used ), "\r\n" ); + + /* Construct all headers */ + for_each_table_entry ( header, HTTP_REQUEST_HEADERS ) { + + /* Determine header value length */ + value_len = header->format ( http, NULL, 0 ); + if ( value_len < 0 ) { + rc = value_len; + return rc; + } + + /* Skip zero-length headers */ + if ( ! value_len ) + continue; + + /* Construct header */ + line = ( buf + used ); + used += ssnprintf ( ( buf + used ), ( len - used ), "%s: ", + header->name ); + remaining = ( ( used < len ) ? ( len - used ) : 0 ); + used += header->format ( http, ( buf + used ), remaining ); + if ( used < len ) + DBGC2 ( http, "HTTP %p TX %s\n", http, line ); + used += ssnprintf ( ( buf + used ), ( len - used ), "\r\n" ); + } + + /* Construct terminating newline */ + used += ssnprintf ( ( buf + used ), ( len - used ), "\r\n" ); + + return used; +} + +/** + * Construct HTTP "Host" header + * + * @v http HTTP transaction + * @v buf Buffer + * @v len Length of buffer + * @ret len Length of header value, or negative error + */ +static int http_format_host ( struct http_transaction *http, char *buf, + size_t len ) { + + /* Construct host URI */ + return snprintf ( buf, len, "%s", http->request.host ); +} + +/** HTTP "Host" header "*/ +struct http_request_header http_request_host __http_request_header = { + .name = "Host", + .format = http_format_host, +}; + +/** + * Construct HTTP "User-Agent" header + * + * @v http HTTP transaction + * @v buf Buffer + * @v len Length of buffer + * @ret len Length of header value, or negative error + */ +static int http_format_user_agent ( struct http_transaction *http __unused, + char *buf, size_t len ) { + + /* Construct user agent */ + return snprintf ( buf, len, "iPXE/%s", product_version ); +} + +/** HTTP "User-Agent" header */ +struct http_request_header http_request_user_agent __http_request_header = { + .name = "User-Agent", + .format = http_format_user_agent, +}; + +/** + * Construct HTTP "Connection" header + * + * @v http HTTP transaction + * @v buf Buffer + * @v len Length of buffer + * @ret len Length of header value, or negative error + */ +static int http_format_connection ( struct http_transaction *http __unused, + char *buf, size_t len ) { + + /* Always request keep-alive */ + return snprintf ( buf, len, "keep-alive" ); +} + +/** HTTP "Connection" header */ +struct http_request_header http_request_connection __http_request_header = { + .name = "Connection", + .format = http_format_connection, +}; + +/** + * Construct HTTP "Range" header + * + * @v http HTTP transaction + * @v buf Buffer + * @v len Length of buffer + * @ret len Length of header value, or negative error + */ +static int http_format_range ( struct http_transaction *http, + char *buf, size_t len ) { + + /* Construct range, if applicable */ + if ( http->request.range.len ) { + return snprintf ( buf, len, "bytes=%zd-%zd", + http->request.range.start, + ( http->request.range.start + + http->request.range.len - 1 ) ); + } else { + return 0; + } +} + +/** HTTP "Range" header */ +struct http_request_header http_request_range __http_request_header = { + .name = "Range", + .format = http_format_range, +}; + +/** + * Construct HTTP "Content-Type" header + * + * @v http HTTP transaction + * @v buf Buffer + * @v len Length of buffer + * @ret len Length of header value, or negative error + */ +static int http_format_content_type ( struct http_transaction *http, + char *buf, size_t len ) { + + /* Construct content type, if applicable */ + if ( http->request.content.type ) { + return snprintf ( buf, len, "%s", http->request.content.type ); + } else { + return 0; + } +} + +/** HTTP "Content-Type" header */ +struct http_request_header http_request_content_type __http_request_header = { + .name = "Content-Type", + .format = http_format_content_type, +}; + +/** + * Construct HTTP "Content-Length" header + * + * @v http HTTP transaction + * @v buf Buffer + * @v len Length of buffer + * @ret len Length of header value, or negative error + */ +static int http_format_content_length ( struct http_transaction *http, + char *buf, size_t len ) { + + /* Construct content length, if applicable */ + if ( http->request.content.len ) { + return snprintf ( buf, len, "%zd", http->request.content.len ); + } else { + return 0; + } +} + +/** HTTP "Content-Length" header */ +struct http_request_header http_request_content_length __http_request_header = { + .name = "Content-Length", + .format = http_format_content_length, +}; + +/** + * Construct HTTP "Accept-Encoding" header + * + * @v http HTTP transaction + * @v buf Buffer + * @v len Length of buffer + * @ret len Length of header value, or negative error + */ +static int http_format_accept_encoding ( struct http_transaction *http, + char *buf, size_t len ) { + struct http_content_encoding *encoding; + const char *sep = ""; + size_t used = 0; + + /* Construct list of content encodings */ + for_each_table_entry ( encoding, HTTP_CONTENT_ENCODINGS ) { + if ( encoding->supported && ( ! encoding->supported ( http ) ) ) + continue; + used += ssnprintf ( ( buf + used ), ( len - used ), + "%s%s", sep, encoding->name ); + sep = ", "; + } + + return used; +} + +/** HTTP "Accept-Encoding" header */ +struct http_request_header http_request_accept_encoding __http_request_header ={ + .name = "Accept-Encoding", + .format = http_format_accept_encoding, +}; + +/** + * Transmit request + * + * @v http HTTP transaction + * @ret rc Return status code + */ +static int http_tx_request ( struct http_transaction *http ) { + struct io_buffer *iobuf; + int len; + int check_len; + int rc; + + /* Calculate request length */ + len = http_format_headers ( http, NULL, 0 ); + if ( len < 0 ) { + rc = len; + DBGC ( http, "HTTP %p could not construct request: %s\n", + http, strerror ( rc ) ); + goto err_len; + } + + /* Allocate I/O buffer */ + iobuf = alloc_iob ( len + 1 /* NUL */ + http->request.content.len ); + if ( ! iobuf ) { + rc = -ENOMEM; + goto err_alloc; + } + + /* Construct request */ + check_len = http_format_headers ( http, iob_put ( iobuf, len ), + ( len + 1 /* NUL */ ) ); + assert ( check_len == len ); + memcpy ( iob_put ( iobuf, http->request.content.len ), + http->request.content.data, http->request.content.len ); + + /* Deliver request */ + if ( ( rc = xfer_deliver_iob ( &http->conn, + iob_disown ( iobuf ) ) ) != 0 ) { + DBGC ( http, "HTTP %p could not deliver request: %s\n", + http, strerror ( rc ) ); + goto err_deliver; + } + + /* Clear any previous response */ + empty_line_buffer ( &http->response.headers ); + memset ( &http->response, 0, sizeof ( http->response ) ); + + /* Move to response headers state */ + http->state = &http_headers; + + return 0; + + err_deliver: + free_iob ( iobuf ); + err_alloc: + err_len: + return rc; +} + +/** HTTP request state */ +static struct http_state http_request = { + .tx = http_tx_request, + .close = http_close_error, +}; + +/****************************************************************************** + * + * Response headers + * + ****************************************************************************** + */ + +/** + * Parse HTTP status line + * + * @v http HTTP transaction + * @v line Status line + * @ret rc Return status code + */ +static int http_parse_status ( struct http_transaction *http, char *line ) { + char *endp; + char *version; + char *vernum; + char *status; + int response_rc; + + DBGC2 ( http, "HTTP %p RX %s\n", http, line ); + + /* Parse HTTP version */ + version = http_token ( &line, NULL ); + if ( ( ! version ) || ( strncmp ( version, "HTTP/", 5 ) != 0 ) ) { + DBGC ( http, "HTTP %p malformed version \"%s\"\n", http, line ); + return -EINVAL_STATUS; + } + + /* Keepalive is enabled by default for anything newer than HTTP/1.0 */ + vernum = ( version + 5 /* "HTTP/" (presence already checked) */ ); + if ( vernum[0] == '0' ) { + /* HTTP/0.x : keepalive not enabled by default */ + } else if ( strncmp ( vernum, "1.0", 3 ) == 0 ) { + /* HTTP/1.0 : keepalive not enabled by default */ + } else { + /* HTTP/1.1 or newer: keepalive enabled by default */ + http->response.flags |= HTTP_RESPONSE_KEEPALIVE; + } + + /* Parse status code */ + status = line; + http->response.status = strtoul ( status, &endp, 10 ); + if ( *endp != ' ' ) { + DBGC ( http, "HTTP %p malformed status code \"%s\"\n", + http, status ); + return -EINVAL_STATUS; + } + + /* Convert HTTP status code to iPXE return status code */ + if ( status[0] == '2' ) { + /* 2xx Success */ + response_rc = 0; + } else if ( status[0] == '3' ) { + /* 3xx Redirection */ + response_rc = -EXDEV; + } else if ( http->response.status == 401 ) { + /* 401 Unauthorized */ + response_rc = -EACCES_401; + } else if ( http->response.status == 403 ) { + /* 403 Forbidden */ + response_rc = -EPERM_403; + } else if ( http->response.status == 404 ) { + /* 404 Not Found */ + response_rc = -ENOENT_404; + } else if ( status[0] == '4' ) { + /* 4xx Client Error (not already specified) */ + response_rc = -EIO_4XX; + } else if ( status[0] == '5' ) { + /* 5xx Server Error */ + response_rc = -EIO_5XX; + } else { + /* Unrecognised */ + response_rc = -EIO_OTHER; + } + http->response.rc = response_rc; + if ( response_rc ) + DBGC ( http, "HTTP %p status %s\n", http, status ); + + return 0; +} + +/** + * Parse HTTP header + * + * @v http HTTP transaction + * @v line Header line + * @ret rc Return status code + */ +static int http_parse_header ( struct http_transaction *http, char *line ) { + struct http_response_header *header; + char *name = line; + char *sep; + + DBGC2 ( http, "HTTP %p RX %s\n", http, line ); + + /* Extract header name */ + sep = strchr ( line, ':' ); + if ( ! sep ) { + DBGC ( http, "HTTP %p malformed header \"%s\"\n", http, line ); + return -EINVAL_HEADER; + } + *sep = '\0'; + + /* Extract remainder of line */ + line = ( sep + 1 ); + while ( isspace ( *line ) ) + line++; + + /* Process header, if recognised */ + for_each_table_entry ( header, HTTP_RESPONSE_HEADERS ) { + if ( strcasecmp ( name, header->name ) == 0 ) + return header->parse ( http, line ); + } + + /* Unrecognised headers should be ignored */ + return 0; +} + +/** + * Parse HTTP response headers + * + * @v http HTTP transaction + * @ret rc Return status code + */ +static int http_parse_headers ( struct http_transaction *http ) { + char *line; + char *next; + int rc; + + /* Get status line */ + line = http->response.headers.data; + assert ( line != NULL ); + next = ( line + strlen ( line ) + 1 /* NUL */ ); + + /* Parse status line */ + if ( ( rc = http_parse_status ( http, line ) ) != 0 ) + return rc; + + /* Process header lines */ + while ( 1 ) { + + /* Move to next line */ + line = next; + next = ( line + strlen ( line ) + 1 /* NUL */ ); + + /* Stop on terminating blank line */ + if ( ! line[0] ) + return 0; + + /* Process header line */ + if ( ( rc = http_parse_header ( http, line ) ) != 0 ) + return rc; + } +} + +/** + * Parse HTTP "Location" header + * + * @v http HTTP transaction + * @v line Remaining header line + * @ret rc Return status code + */ +static int http_parse_location ( struct http_transaction *http, char *line ) { + + /* Store location */ + http->response.location = line; + return 0; +} + +/** HTTP "Location" header */ +struct http_response_header http_response_location __http_response_header = { + .name = "Location", + .parse = http_parse_location, +}; + +/** + * Parse HTTP "Transfer-Encoding" header + * + * @v http HTTP transaction + * @v line Remaining header line + * @ret rc Return status code + */ +static int http_parse_transfer_encoding ( struct http_transaction *http, + char *line ) { + struct http_transfer_encoding *encoding; + + /* Check for known transfer encodings */ + for_each_table_entry ( encoding, HTTP_TRANSFER_ENCODINGS ) { + if ( strcasecmp ( line, encoding->name ) == 0 ) { + http->response.transfer.encoding = encoding; + return 0; + } + } + + DBGC ( http, "HTTP %p unrecognised Transfer-Encoding \"%s\"\n", + http, line ); + return -ENOTSUP_TRANSFER; +} + +/** HTTP "Transfer-Encoding" header */ +struct http_response_header +http_response_transfer_encoding __http_response_header = { + .name = "Transfer-Encoding", + .parse = http_parse_transfer_encoding, +}; + +/** + * Parse HTTP "Connection" header + * + * @v http HTTP transaction + * @v line Remaining header line + * @ret rc Return status code + */ +static int http_parse_connection ( struct http_transaction *http, char *line ) { + char *token; + + /* Check for known connection intentions */ + while ( ( token = http_token ( &line, NULL ) ) ) { + if ( strcasecmp ( token, "keep-alive" ) == 0 ) + http->response.flags |= HTTP_RESPONSE_KEEPALIVE; + if ( strcasecmp ( token, "close" ) == 0 ) + http->response.flags &= ~HTTP_RESPONSE_KEEPALIVE; + } + + return 0; +} + +/** HTTP "Connection" header */ +struct http_response_header http_response_connection __http_response_header = { + .name = "Connection", + .parse = http_parse_connection, +}; + +/** + * Parse HTTP "Content-Length" header + * + * @v http HTTP transaction + * @v line Remaining header line + * @ret rc Return status code + */ +static int http_parse_content_length ( struct http_transaction *http, + char *line ) { + char *endp; + + /* Parse length */ + http->response.content.len = strtoul ( line, &endp, 10 ); + if ( *endp != '\0' ) { + DBGC ( http, "HTTP %p invalid Content-Length \"%s\"\n", + http, line ); + return -EINVAL_CONTENT_LENGTH; + } + + /* Record that we have a content length (since it may be zero) */ + http->response.flags |= HTTP_RESPONSE_CONTENT_LEN; + + return 0; +} + +/** HTTP "Content-Length" header */ +struct http_response_header +http_response_content_length __http_response_header = { + .name = "Content-Length", + .parse = http_parse_content_length, +}; + +/** + * Parse HTTP "Content-Encoding" header + * + * @v http HTTP transaction + * @v line Remaining header line + * @ret rc Return status code + */ +static int http_parse_content_encoding ( struct http_transaction *http, + char *line ) { + struct http_content_encoding *encoding; + + /* Check for known content encodings */ + for_each_table_entry ( encoding, HTTP_CONTENT_ENCODINGS ) { + if ( encoding->supported && ( ! encoding->supported ( http ) ) ) + continue; + if ( strcasecmp ( line, encoding->name ) == 0 ) { + http->response.content.encoding = encoding; + return 0; + } + } + + /* Some servers (e.g. Apache) have a habit of specifying + * unwarranted content encodings. For example, if Apache + * detects (via /etc/httpd/conf/magic) that a file's contents + * are gzip-compressed, it will set "Content-Encoding: x-gzip" + * regardless of the client's Accept-Encoding header. The + * only viable way to handle such servers is to treat unknown + * content encodings as equivalent to "identity". + */ + DBGC ( http, "HTTP %p unrecognised Content-Encoding \"%s\"\n", + http, line ); + return 0; +} + +/** HTTP "Content-Encoding" header */ +struct http_response_header +http_response_content_encoding __http_response_header = { + .name = "Content-Encoding", + .parse = http_parse_content_encoding, +}; + +/** + * Parse HTTP "Retry-After" header + * + * @v http HTTP transaction + * @v line Remaining header line + * @ret rc Return status code + */ +static int http_parse_retry_after ( struct http_transaction *http, + char *line ) { + char *endp; + + /* Try to parse value as a simple number of seconds */ + http->response.retry_after = strtoul ( line, &endp, 10 ); + if ( *endp != '\0' ) { + /* For any value which is not a simple number of + * seconds (e.g. a full HTTP date), just retry after a + * fixed delay, since we don't have code able to parse + * full HTTP dates. + */ + http->response.retry_after = HTTP_RETRY_SECONDS; + DBGC ( http, "HTTP %p cannot understand Retry-After \"%s\"; " + "using %d seconds\n", http, line, HTTP_RETRY_SECONDS ); + } + + /* Allow HTTP request to be retried after specified delay */ + http->response.flags |= HTTP_RESPONSE_RETRY; + + return 0; +} + +/** HTTP "Retry-After" header */ +struct http_response_header http_response_retry_after __http_response_header = { + .name = "Retry-After", + .parse = http_parse_retry_after, +}; + +/** + * Handle received HTTP headers + * + * @v http HTTP transaction + * @v iobuf I/O buffer (may be claimed) + * @ret rc Return status code + */ +static int http_rx_headers ( struct http_transaction *http, + struct io_buffer **iobuf ) { + struct http_transfer_encoding *transfer; + struct http_content_encoding *content; + char *line; + int rc; + + /* Buffer header line */ + if ( ( rc = http_rx_linebuf ( http, *iobuf, + &http->response.headers ) ) != 0 ) + return rc; + + /* Wait until we see the empty line marking end of headers */ + line = buffered_line ( &http->response.headers ); + if ( ( line == NULL ) || ( line[0] != '\0' ) ) + return 0; + + /* Process headers */ + if ( ( rc = http_parse_headers ( http ) ) != 0 ) + return rc; + + /* Initialise content encoding, if applicable */ + if ( ( content = http->response.content.encoding ) && + ( ( rc = content->init ( http ) ) != 0 ) ) { + DBGC ( http, "HTTP %p could not initialise %s content " + "encoding: %s\n", http, content->name, strerror ( rc ) ); + return rc; + } + + /* Presize receive buffer, if we have a content length */ + if ( http->response.content.len ) { + xfer_seek ( &http->transfer, http->response.content.len ); + xfer_seek ( &http->transfer, 0 ); + } + + /* Complete transfer if this is a HEAD request */ + if ( http->request.method == &http_head ) { + if ( ( rc = http_transfer_complete ( http ) ) != 0 ) + return rc; + return 0; + } + + /* Default to identity transfer encoding, if none specified */ + if ( ! http->response.transfer.encoding ) + http->response.transfer.encoding = &http_transfer_identity; + + /* Move to transfer encoding-specific data state */ + transfer = http->response.transfer.encoding; + http->state = &transfer->state; + + /* Initialise transfer encoding */ + if ( ( rc = transfer->init ( http ) ) != 0 ) { + DBGC ( http, "HTTP %p could not initialise %s transfer " + "encoding: %s\n", http, transfer->name, strerror ( rc )); + return rc; + } + + return 0; +} + +/** HTTP response headers state */ +static struct http_state http_headers = { + .rx = http_rx_headers, + .close = http_close_error, +}; + +/****************************************************************************** + * + * Identity transfer encoding + * + ****************************************************************************** + */ + +/** + * Initialise transfer encoding + * + * @v http HTTP transaction + * @ret rc Return status code + */ +static int http_init_transfer_identity ( struct http_transaction *http ) { + int rc; + + /* Complete transfer immediately if we have a zero content length */ + if ( ( http->response.flags & HTTP_RESPONSE_CONTENT_LEN ) && + ( http->response.content.len == 0 ) && + ( ( rc = http_transfer_complete ( http ) ) != 0 ) ) + return rc; + + return 0; +} + +/** + * Handle received data + * + * @v http HTTP transaction + * @v iobuf I/O buffer (may be claimed) + * @ret rc Return status code + */ +static int http_rx_transfer_identity ( struct http_transaction *http, + struct io_buffer **iobuf ) { + size_t len = iob_len ( *iobuf ); + int rc; + + /* Update lengths */ + http->len += len; + + /* Fail if this transfer would overrun the expected content + * length (if any). + */ + if ( ( http->response.flags & HTTP_RESPONSE_CONTENT_LEN ) && + ( http->len > http->response.content.len ) ) { + DBGC ( http, "HTTP %p content length overrun\n", http ); + return -EIO_CONTENT_LENGTH; + } + + /* Hand off to content encoding */ + if ( ( rc = xfer_deliver_iob ( &http->transfer, + iob_disown ( *iobuf ) ) ) != 0 ) + return rc; + + /* Complete transfer if we have received the expected content + * length (if any). + */ + if ( ( http->response.flags & HTTP_RESPONSE_CONTENT_LEN ) && + ( http->len == http->response.content.len ) && + ( ( rc = http_transfer_complete ( http ) ) != 0 ) ) + return rc; + + return 0; +} + +/** + * Handle server connection close + * + * @v http HTTP transaction + * @v rc Reason for close + */ +static void http_close_transfer_identity ( struct http_transaction *http, + int rc ) { + + /* Fail if any error occurred */ + if ( rc != 0 ) + goto err; + + /* Fail if we have a content length (since we would have + * already closed the connection if we had received the + * correct content length). + */ + if ( http->response.flags & HTTP_RESPONSE_CONTENT_LEN ) { + DBGC ( http, "HTTP %p content length underrun\n", http ); + rc = EIO_CONTENT_LENGTH; + goto err; + } + + /* Indicate that transfer is complete */ + if ( ( rc = http_transfer_complete ( http ) ) != 0 ) + goto err; + + return; + + err: + http_close ( http, rc ); +} + +/** Identity transfer encoding */ +static struct http_transfer_encoding http_transfer_identity = { + .name = "identity", + .init = http_init_transfer_identity, + .state = { + .rx = http_rx_transfer_identity, + .close = http_close_transfer_identity, + }, +}; + +/****************************************************************************** + * + * Chunked transfer encoding + * + ****************************************************************************** + */ + +/** + * Initialise transfer encoding + * + * @v http HTTP transaction + * @ret rc Return status code + */ +static int http_init_transfer_chunked ( struct http_transaction *http ) { + + /* Sanity checks */ + assert ( http->remaining == 0 ); + assert ( http->linebuf.len == 0 ); + + return 0; +} + +/** + * Handle received chunk length + * + * @v http HTTP transaction + * @v iobuf I/O buffer (may be claimed) + * @ret rc Return status code + */ +static int http_rx_chunk_len ( struct http_transaction *http, + struct io_buffer **iobuf ) { + char *line; + char *endp; + size_t len; + int rc; + + /* Receive into temporary line buffer */ + if ( ( rc = http_rx_linebuf ( http, *iobuf, &http->linebuf ) ) != 0 ) + return rc; + + /* Wait until we receive a non-empty line */ + line = buffered_line ( &http->linebuf ); + if ( ( line == NULL ) || ( line[0] == '\0' ) ) + return 0; + + /* Parse chunk length */ + http->remaining = strtoul ( line, &endp, 16 ); + if ( *endp != '\0' ) { + DBGC ( http, "HTTP %p invalid chunk length \"%s\"\n", + http, line ); + return -EINVAL_CHUNK_LENGTH; + } + + /* Empty line buffer */ + empty_line_buffer ( &http->linebuf ); + + /* Update expected length */ + len = ( http->len + http->remaining ); + xfer_seek ( &http->transfer, len ); + xfer_seek ( &http->transfer, http->len ); + + /* If chunk length is zero, then move to response trailers state */ + if ( ! http->remaining ) + http->state = &http_trailers; + + return 0; +} + +/** + * Handle received chunk data + * + * @v http HTTP transaction + * @v iobuf I/O buffer (may be claimed) + * @ret rc Return status code + */ +static int http_rx_chunk_data ( struct http_transaction *http, + struct io_buffer **iobuf ) { + struct io_buffer *payload; + uint8_t *crlf; + size_t len; + int rc; + + /* In the common case of a final chunk in a packet which also + * includes the terminating CRLF, strip the terminating CRLF + * (which we would ignore anyway) and hence avoid + * unnecessarily copying the data. + */ + if ( iob_len ( *iobuf ) == ( http->remaining + 2 /* CRLF */ ) ) { + crlf = ( (*iobuf)->data + http->remaining ); + if ( ( crlf[0] == '\r' ) && ( crlf[1] == '\n' ) ) + iob_unput ( (*iobuf), 2 /* CRLF */ ); + } + len = iob_len ( *iobuf ); + + /* Use whole/partial buffer as applicable */ + if ( len <= http->remaining ) { + + /* Whole buffer is to be consumed: decrease remaining + * length and use original I/O buffer as payload. + */ + payload = iob_disown ( *iobuf ); + http->len += len; + http->remaining -= len; + + } else { + + /* Partial buffer is to be consumed: copy data to a + * temporary I/O buffer. + */ + payload = alloc_iob ( http->remaining ); + if ( ! payload ) { + rc = -ENOMEM; + goto err; + } + memcpy ( iob_put ( payload, http->remaining ), (*iobuf)->data, + http->remaining ); + iob_pull ( *iobuf, http->remaining ); + http->len += http->remaining; + http->remaining = 0; + } + + /* Hand off to content encoding */ + if ( ( rc = xfer_deliver_iob ( &http->transfer, + iob_disown ( payload ) ) ) != 0 ) + goto err; + + return 0; + + err: + assert ( payload == NULL ); + return rc; +} + +/** + * Handle received chunked data + * + * @v http HTTP transaction + * @v iobuf I/O buffer (may be claimed) + * @ret rc Return status code + */ +static int http_rx_transfer_chunked ( struct http_transaction *http, + struct io_buffer **iobuf ) { + + /* Handle as chunk length or chunk data as appropriate */ + if ( http->remaining ) { + return http_rx_chunk_data ( http, iobuf ); + } else { + return http_rx_chunk_len ( http, iobuf ); + } +} + +/** Chunked transfer encoding */ +struct http_transfer_encoding http_transfer_chunked __http_transfer_encoding = { + .name = "chunked", + .init = http_init_transfer_chunked, + .state = { + .rx = http_rx_transfer_chunked, + .close = http_close_error, + }, +}; + +/****************************************************************************** + * + * Response trailers + * + ****************************************************************************** + */ + +/** + * Handle received HTTP trailer + * + * @v http HTTP transaction + * @v iobuf I/O buffer (may be claimed) + * @ret rc Return status code + */ +static int http_rx_trailers ( struct http_transaction *http, + struct io_buffer **iobuf ) { + char *line; + int rc; + + /* Buffer trailer line */ + if ( ( rc = http_rx_linebuf ( http, *iobuf, &http->linebuf ) ) != 0 ) + return rc; + + /* Wait until we see the empty line marking end of trailers */ + line = buffered_line ( &http->linebuf ); + if ( ( line == NULL ) || ( line[0] != '\0' ) ) + return 0; + + /* Empty line buffer */ + empty_line_buffer ( &http->linebuf ); + + /* Transfer is complete */ + if ( ( rc = http_transfer_complete ( http ) ) != 0 ) + return rc; + + return 0; +} + +/** HTTP response trailers state */ +static struct http_state http_trailers = { + .rx = http_rx_trailers, + .close = http_close_error, +}; + +/****************************************************************************** + * + * Simple URI openers + * + ****************************************************************************** + */ + +/** + * Construct HTTP parameter list + * + * @v params Parameter list + * @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_params ( struct parameters *params, 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, params ) { + + /* Add the "&", if applicable */ + if ( len ) { + if ( remaining > 0 ) + *buf = '&'; + buf++; + len++; + remaining--; + } + + /* URI-encode the key */ + frag_len = uri_encode_string ( 0, param->key, 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_string ( 0, param->value, 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; +} + +/** + * Open HTTP transaction for simple GET URI + * + * @v xfer Data transfer interface + * @v uri Request URI + * @ret rc Return status code + */ +static int http_open_get_uri ( struct interface *xfer, struct uri *uri ) { + + return http_open ( xfer, &http_get, uri, NULL, NULL ); +} + +/** + * Open HTTP transaction for simple POST URI + * + * @v xfer Data transfer interface + * @v uri Request URI + * @ret rc Return status code + */ +static int http_open_post_uri ( struct interface *xfer, struct uri *uri ) { + struct parameters *params = uri->params; + struct http_request_content content; + void *data; + size_t len; + size_t check_len; + int rc; + + /* Calculate length of parameter list */ + len = http_params ( params, NULL, 0 ); + + /* Allocate temporary parameter list */ + data = zalloc ( len + 1 /* NUL */ ); + if ( ! data ) { + rc = -ENOMEM; + goto err_alloc; + } + + /* Construct temporary parameter list */ + check_len = http_params ( params, data, ( len + 1 /* NUL */ ) ); + assert ( check_len == len ); + + /* Construct request content */ + content.type = "application/x-www-form-urlencoded"; + content.data = data; + content.len = len; + + /* Open HTTP transaction */ + if ( ( rc = http_open ( xfer, &http_post, uri, NULL, &content ) ) != 0 ) + goto err_open; + + err_open: + free ( data ); + err_alloc: + return rc; +} + +/** + * Open HTTP transaction for simple URI + * + * @v xfer Data transfer interface + * @v uri Request URI + * @ret rc Return status code + */ +int http_open_uri ( struct interface *xfer, struct uri *uri ) { + + /* Open GET/POST URI as applicable */ + if ( uri->params ) { + return http_open_post_uri ( xfer, uri ); + } else { + return http_open_get_uri ( xfer, uri ); + } +} + +/* Drag in HTTP extensions */ +REQUIRING_SYMBOL ( http_open ); +REQUIRE_OBJECT ( config_http ); diff --git a/roms/ipxe/src/net/tcp/httpdigest.c b/roms/ipxe/src/net/tcp/httpdigest.c new file mode 100644 index 000000000..4074078c7 --- /dev/null +++ b/roms/ipxe/src/net/tcp/httpdigest.c @@ -0,0 +1,309 @@ +/* + * Copyright (C) 2015 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. + * + * You can also choose to distribute this program under the terms of + * the Unmodified Binary Distribution Licence (as given in the file + * COPYING.UBDL), provided that you have satisfied its requirements. + */ + +FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL ); + +/** + * @file + * + * Hyper Text Transfer Protocol (HTTP) Digest authentication + * + */ + +#include <stdio.h> +#include <errno.h> +#include <strings.h> +#include <ipxe/uri.h> +#include <ipxe/md5.h> +#include <ipxe/base16.h> +#include <ipxe/vsprintf.h> +#include <ipxe/http.h> + +/* Disambiguate the various error causes */ +#define EACCES_USERNAME __einfo_error ( EINFO_EACCES_USERNAME ) +#define EINFO_EACCES_USERNAME \ + __einfo_uniqify ( EINFO_EACCES, 0x01, \ + "No username available for Digest authentication" ) + +/** An HTTP Digest "WWW-Authenticate" response field */ +struct http_digest_field { + /** Name */ + const char *name; + /** Offset */ + size_t offset; +}; + +/** Define an HTTP Digest "WWW-Authenticate" response field */ +#define HTTP_DIGEST_FIELD( _name ) { \ + .name = #_name, \ + .offset = offsetof ( struct http_transaction, \ + response.auth.digest._name ), \ + } + +/** + * Set HTTP Digest "WWW-Authenticate" response field value + * + * @v http HTTP transaction + * @v field Response field + * @v value Field value + */ +static inline void +http_digest_field ( struct http_transaction *http, + struct http_digest_field *field, char *value ) { + char **ptr; + + ptr = ( ( ( void * ) http ) + field->offset ); + *ptr = value; +} + +/** HTTP Digest "WWW-Authenticate" fields */ +static struct http_digest_field http_digest_fields[] = { + HTTP_DIGEST_FIELD ( realm ), + HTTP_DIGEST_FIELD ( qop ), + HTTP_DIGEST_FIELD ( algorithm ), + HTTP_DIGEST_FIELD ( nonce ), + HTTP_DIGEST_FIELD ( opaque ), +}; + +/** + * Parse HTTP "WWW-Authenticate" header for Digest authentication + * + * @v http HTTP transaction + * @v line Remaining header line + * @ret rc Return status code + */ +static int http_parse_digest_auth ( struct http_transaction *http, + char *line ) { + struct http_digest_field *field; + char *key; + char *value; + unsigned int i; + + /* Process fields */ + while ( ( key = http_token ( &line, &value ) ) ) { + for ( i = 0 ; i < ( sizeof ( http_digest_fields ) / + sizeof ( http_digest_fields[0] ) ) ; i++){ + field = &http_digest_fields[i]; + if ( strcasecmp ( key, field->name ) == 0 ) + http_digest_field ( http, field, value ); + } + } + + /* Allow HTTP request to be retried if the request had not + * already tried authentication. + */ + if ( ! http->request.auth.auth ) + http->response.flags |= HTTP_RESPONSE_RETRY; + + return 0; +} + +/** + * Initialise HTTP Digest + * + * @v ctx Digest context + * @v string Initial string + */ +static void http_digest_init ( struct md5_context *ctx ) { + + /* Initialise MD5 digest */ + digest_init ( &md5_algorithm, ctx ); +} + +/** + * Update HTTP Digest with new data + * + * @v ctx Digest context + * @v string String to append + */ +static void http_digest_update ( struct md5_context *ctx, const char *string ) { + static const char colon = ':'; + + /* Add (possibly colon-separated) field to MD5 digest */ + if ( ctx->len ) + digest_update ( &md5_algorithm, ctx, &colon, sizeof ( colon ) ); + digest_update ( &md5_algorithm, ctx, string, strlen ( string ) ); +} + +/** + * Finalise HTTP Digest + * + * @v ctx Digest context + * @v out Buffer for digest output + * @v len Buffer length + */ +static void http_digest_final ( struct md5_context *ctx, char *out, + size_t len ) { + uint8_t digest[MD5_DIGEST_SIZE]; + + /* Finalise and base16-encode MD5 digest */ + digest_final ( &md5_algorithm, ctx, digest ); + base16_encode ( digest, sizeof ( digest ), out, len ); +} + +/** + * Perform HTTP Digest authentication + * + * @v http HTTP transaction + * @ret rc Return status code + */ +static int http_digest_authenticate ( struct http_transaction *http ) { + struct http_request_auth_digest *req = &http->request.auth.digest; + struct http_response_auth_digest *rsp = &http->response.auth.digest; + char ha1[ base16_encoded_len ( MD5_DIGEST_SIZE ) + 1 /* NUL */ ]; + char ha2[ base16_encoded_len ( MD5_DIGEST_SIZE ) + 1 /* NUL */ ]; + static const char md5sess[] = "MD5-sess"; + static const char md5[] = "MD5"; + struct md5_context ctx; + const char *password; + + /* Check for required response parameters */ + if ( ! rsp->realm ) { + DBGC ( http, "HTTP %p has no realm for Digest authentication\n", + http ); + return -EINVAL; + } + if ( ! rsp->nonce ) { + DBGC ( http, "HTTP %p has no nonce for Digest authentication\n", + http ); + return -EINVAL; + } + + /* Record username and password */ + if ( ! http->uri->user ) { + DBGC ( http, "HTTP %p has no username for Digest " + "authentication\n", http ); + return -EACCES_USERNAME; + } + req->username = http->uri->user; + password = ( http->uri->password ? http->uri->password : "" ); + + /* Handle quality of protection */ + if ( rsp->qop ) { + + /* Use "auth" in subsequent request */ + req->qop = "auth"; + + /* Generate a client nonce */ + snprintf ( req->cnonce, sizeof ( req->cnonce ), + "%08lx", random() ); + + /* Determine algorithm */ + req->algorithm = md5; + if ( rsp->algorithm && + ( strcasecmp ( rsp->algorithm, md5sess ) == 0 ) ) { + req->algorithm = md5sess; + } + } + + /* Generate HA1 */ + http_digest_init ( &ctx ); + http_digest_update ( &ctx, req->username ); + http_digest_update ( &ctx, rsp->realm ); + http_digest_update ( &ctx, password ); + http_digest_final ( &ctx, ha1, sizeof ( ha1 ) ); + if ( req->algorithm == md5sess ) { + http_digest_init ( &ctx ); + http_digest_update ( &ctx, ha1 ); + http_digest_update ( &ctx, rsp->nonce ); + http_digest_update ( &ctx, req->cnonce ); + http_digest_final ( &ctx, ha1, sizeof ( ha1 ) ); + } + + /* Generate HA2 */ + http_digest_init ( &ctx ); + http_digest_update ( &ctx, http->request.method->name ); + http_digest_update ( &ctx, http->request.uri ); + http_digest_final ( &ctx, ha2, sizeof ( ha2 ) ); + + /* Generate response */ + http_digest_init ( &ctx ); + http_digest_update ( &ctx, ha1 ); + http_digest_update ( &ctx, rsp->nonce ); + if ( req->qop ) { + http_digest_update ( &ctx, HTTP_DIGEST_NC ); + http_digest_update ( &ctx, req->cnonce ); + http_digest_update ( &ctx, req->qop ); + } + http_digest_update ( &ctx, ha2 ); + http_digest_final ( &ctx, req->response, sizeof ( req->response ) ); + + return 0; +} + +/** + * Construct HTTP "Authorization" header for Digest authentication + * + * @v http HTTP transaction + * @v buf Buffer + * @v len Length of buffer + * @ret len Length of header value, or negative error + */ +static int http_format_digest_auth ( struct http_transaction *http, + char *buf, size_t len ) { + struct http_request_auth_digest *req = &http->request.auth.digest; + struct http_response_auth_digest *rsp = &http->response.auth.digest; + size_t used = 0; + + /* Sanity checks */ + assert ( rsp->realm != NULL ); + assert ( rsp->nonce != NULL ); + assert ( req->username != NULL ); + if ( req->qop ) { + assert ( req->algorithm != NULL ); + assert ( req->cnonce[0] != '\0' ); + } + assert ( req->response[0] != '\0' ); + + /* Construct response */ + used += ssnprintf ( ( buf + used ), ( len - used ), + "realm=\"%s\", nonce=\"%s\", uri=\"%s\", " + "username=\"%s\"", rsp->realm, rsp->nonce, + http->request.uri, req->username ); + if ( rsp->opaque ) { + used += ssnprintf ( ( buf + used ), ( len - used ), + ", opaque=\"%s\"", rsp->opaque ); + } + if ( req->qop ) { + used += ssnprintf ( ( buf + used ), ( len - used ), + ", qop=%s, algorithm=%s, cnonce=\"%s\", " + "nc=" HTTP_DIGEST_NC, req->qop, + req->algorithm, req->cnonce ); + } + used += ssnprintf ( ( buf + used ), ( len - used ), + ", response=\"%s\"", req->response ); + + return used; +} + +/** HTTP Digest authentication scheme */ +struct http_authentication http_digest_auth __http_authentication = { + .name = "Digest", + .parse = http_parse_digest_auth, + .authenticate = http_digest_authenticate, + .format = http_format_digest_auth, +}; + +/* Drag in HTTP authentication support */ +REQUIRING_SYMBOL ( http_digest_auth ); +REQUIRE_OBJECT ( httpauth ); diff --git a/roms/ipxe/src/net/tcp/httpgce.c b/roms/ipxe/src/net/tcp/httpgce.c new file mode 100644 index 000000000..c5d879028 --- /dev/null +++ b/roms/ipxe/src/net/tcp/httpgce.c @@ -0,0 +1,72 @@ +/* + * Copyright (C) 2017 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. + * + * You can also choose to distribute this program under the terms of + * the Unmodified Binary Distribution Licence (as given in the file + * COPYING.UBDL), provided that you have satisfied its requirements. + */ + +FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL ); + +/** + * @file + * + * Google Compute Engine (GCE) metadata retrieval + * + * For some unspecified "security" reason, the Google Compute Engine + * metadata server will refuse any requests that do not include the + * non-standard HTTP header "Metadata-Flavor: Google". + */ + +#include <strings.h> +#include <stdio.h> +#include <ipxe/http.h> + +/** Metadata host name + * + * This is used to identify metadata requests, in the absence of any + * more robust mechanism. + */ +#define GCE_METADATA_HOST_NAME "metadata.google.internal" + +/** + * Construct HTTP "Metadata-Flavor" header + * + * @v http HTTP transaction + * @v buf Buffer + * @v len Length of buffer + * @ret len Length of header value, or negative error + */ +static int http_format_metadata_flavor ( struct http_transaction *http, + char *buf, size_t len ) { + + /* Do nothing unless this appears to be a Google Compute + * Engine metadata request. + */ + if ( strcasecmp ( http->request.host, GCE_METADATA_HOST_NAME ) != 0 ) + return 0; + + /* Construct host URI */ + return snprintf ( buf, len, "Google" ); +} + +/** HTTP "Metadata-Flavor" header */ +struct http_request_header http_request_metadata_flavor __http_request_header ={ + .name = "Metadata-Flavor", + .format = http_format_metadata_flavor, +}; diff --git a/roms/ipxe/src/net/tcp/httpntlm.c b/roms/ipxe/src/net/tcp/httpntlm.c new file mode 100644 index 000000000..25187bd19 --- /dev/null +++ b/roms/ipxe/src/net/tcp/httpntlm.c @@ -0,0 +1,220 @@ +/* + * Copyright (C) 2017 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. + * + * You can also choose to distribute this program under the terms of + * the Unmodified Binary Distribution Licence (as given in the file + * COPYING.UBDL), provided that you have satisfied its requirements. + */ + +FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL ); + +/** + * @file + * + * Hyper Text Transfer Protocol (HTTP) NTLM authentication + * + */ + +#include <string.h> +#include <errno.h> +#include <ipxe/uri.h> +#include <ipxe/base64.h> +#include <ipxe/ntlm.h> +#include <ipxe/netbios.h> +#include <ipxe/http.h> + +struct http_authentication http_ntlm_auth __http_authentication; + +/** Workstation name used for NTLM authentication */ +static const char http_ntlm_workstation[] = "iPXE"; + +/** + * Parse HTTP "WWW-Authenticate" header for NTLM authentication + * + * @v http HTTP transaction + * @v line Remaining header line + * @ret rc Return status code + */ +static int http_parse_ntlm_auth ( struct http_transaction *http, char *line ) { + struct http_response_auth_ntlm *rsp = &http->response.auth.ntlm; + char *copy; + int len; + int rc; + + /* Create temporary copy of Base64-encoded challenge message */ + copy = strdup ( line ); + if ( ! copy ) { + rc = -ENOMEM; + goto err_alloc; + } + + /* Decode challenge message, overwriting the original */ + len = base64_decode ( copy, line, strlen ( line ) ); + if ( len < 0 ) { + rc = len; + DBGC ( http, "HTTP %p could not decode NTLM challenge " + "\"%s\": %s\n", http, copy, strerror ( rc ) ); + goto err_decode; + } + + /* Parse challenge, if present */ + if ( len ) { + rsp->challenge = ( ( void * ) line ); + if ( ( rc = ntlm_challenge ( rsp->challenge, len, + &rsp->info ) ) != 0 ) { + DBGC ( http, "HTTP %p could not parse NTLM challenge: " + "%s\n", http, strerror ( rc ) ); + goto err_challenge; + } + } + + /* Allow HTTP request to be retried if the request had not + * already tried authentication. Note that NTLM requires an + * additional round trip to obtain the challenge message, + * which is not present in the initial WWW-Authenticate. + */ + if ( ( http->request.auth.auth == NULL ) || + ( ( http->request.auth.auth == &http_ntlm_auth ) && + ( http->request.auth.ntlm.len == 0 ) && len ) ) { + http->response.flags |= HTTP_RESPONSE_RETRY; + } + + /* Success */ + rc = 0; + + err_challenge: + err_decode: + free ( copy ); + err_alloc: + return rc; +} + +/** + * Perform HTTP NTLM authentication + * + * @v http HTTP transaction + * @ret rc Return status code + */ +static int http_ntlm_authenticate ( struct http_transaction *http ) { + struct http_request_auth_ntlm *req = &http->request.auth.ntlm; + struct http_response_auth_ntlm *rsp = &http->response.auth.ntlm; + struct ntlm_key key; + const char *domain; + char *username; + const char *password; + + /* If we have no challenge yet, then just send a Negotiate message */ + if ( ! rsp->challenge ) { + DBGC ( http, "HTTP %p sending NTLM Negotiate\n", http ); + return 0; + } + + /* Record username */ + if ( ! http->uri->user ) { + DBGC ( http, "HTTP %p has no username for NTLM " + "authentication\n", http ); + return -EACCES; + } + req->username = http->uri->user; + password = ( http->uri->password ? http->uri->password : "" ); + + /* Split NetBIOS [domain\]username */ + username = ( ( char * ) req->username ); + domain = netbios_domain ( &username ); + + /* Generate key */ + ntlm_key ( domain, username, password, &key ); + + /* Generate responses */ + ntlm_response ( &rsp->info, &key, NULL, &req->lm, &req->nt ); + + /* Calculate Authenticate message length */ + req->len = ntlm_authenticate_len ( &rsp->info, domain, username, + http_ntlm_workstation ); + + /* Restore NetBIOS [domain\]username */ + netbios_domain_undo ( domain, username ); + + return 0; +} + +/** + * Construct HTTP "Authorization" header for NTLM authentication + * + * @v http HTTP transaction + * @v buf Buffer + * @v len Length of buffer + * @ret len Length of header value, or negative error + */ +static int http_format_ntlm_auth ( struct http_transaction *http, + char *buf, size_t len ) { + struct http_request_auth_ntlm *req = &http->request.auth.ntlm; + struct http_response_auth_ntlm *rsp = &http->response.auth.ntlm; + struct ntlm_authenticate *auth; + const char *domain; + char *username; + size_t check; + + /* If we have no challenge yet, then just send a Negotiate message */ + if ( ! rsp->challenge ) { + return base64_encode ( &ntlm_negotiate, + sizeof ( ntlm_negotiate ), buf, len ); + } + + /* Skip allocation if just calculating length */ + if ( ! len ) + return base64_encoded_len ( req->len ); + + /* Allocate temporary buffer for Authenticate message */ + auth = malloc ( req->len ); + if ( ! auth ) + return -ENOMEM; + + /* Split NetBIOS [domain\]username */ + username = ( ( char * ) req->username ); + domain = netbios_domain ( &username ); + + /* Construct raw Authenticate message */ + check = ntlm_authenticate ( &rsp->info, domain, username, + http_ntlm_workstation, &req->lm, + &req->nt, auth ); + assert ( check == req->len ); + + /* Restore NetBIOS [domain\]username */ + netbios_domain_undo ( domain, username ); + + /* Base64-encode Authenticate message */ + len = base64_encode ( auth, req->len, buf, len ); + + /* Free raw Authenticate message */ + free ( auth ); + + return len; +} + +/** HTTP NTLM authentication scheme */ +struct http_authentication http_ntlm_auth __http_authentication = { + .name = "NTLM", + .parse = http_parse_ntlm_auth, + .authenticate = http_ntlm_authenticate, + .format = http_format_ntlm_auth, +}; + +/* Drag in HTTP authentication support */ +REQUIRING_SYMBOL ( http_ntlm_auth ); +REQUIRE_OBJECT ( httpauth ); diff --git a/roms/ipxe/src/net/tcp/https.c b/roms/ipxe/src/net/tcp/https.c new file mode 100644 index 000000000..e91000322 --- /dev/null +++ b/roms/ipxe/src/net/tcp/https.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. + * + * You can also choose to distribute this program under the terms of + * the Unmodified Binary Distribution Licence (as given in the file + * COPYING.UBDL), provided that you have satisfied its requirements. + */ + +FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL ); + +/** + * @file + * + * Secure Hyper Text Transfer Protocol (HTTPS) + * + */ + +#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 ); + +/** HTTPS URI opener */ +struct uri_opener https_uri_opener __uri_opener = { + .scheme = "https", + .open = http_open_uri, +}; + +/** HTTP URI scheme */ +struct http_scheme https_scheme __http_scheme = { + .name = "https", + .port = HTTPS_PORT, + .filter = add_tls, +}; diff --git a/roms/ipxe/src/net/tcp/iscsi.c b/roms/ipxe/src/net/tcp/iscsi.c new file mode 100644 index 000000000..3a44b90f0 --- /dev/null +++ b/roms/ipxe/src/net/tcp/iscsi.c @@ -0,0 +1,2200 @@ +/* + * 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. + * + * You can also choose to distribute this program under the terms of + * the Unmodified Binary Distribution Licence (as given in the file + * COPYING.UBDL), provided that you have satisfied its requirements. + */ + +FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL ); + +#include <stddef.h> +#include <string.h> +#include <stdlib.h> +#include <stdio.h> +#include <ctype.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 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 value" ) +#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 */ + intfs_shutdown ( rc, &iscsi->socket, &iscsi->control, &iscsi->data, + NULL ); +} + +/** + * 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 ) ) + return 0; + + /* Ignore any other NOP-Ins. The target may eventually + * disconnect us for failing to respond, but this minimises + * unnecessary connection closures. + */ + DBGC ( iscsi, "iSCSI %p received unsupported NOP-In with TTT %08x\n", + iscsi, ntohl ( nop_in->ttt ) ); + 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=1 (irrelevant; we make only one connection anyway) [4] + * InitialR2T=Yes [1] + * ImmediateData=No (irrelevant; we never send immediate data) [4] + * MaxRecvDataSegmentLength=8192 (default; we don't care) [3] + * MaxBurstLength=262144 (default; we don't care) [3] + * FirstBurstLength=65536 (irrelevant due to other settings) [5] + * 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. + * + * [5] FirstBurstLength is defined to be irrelevant since we already + * force InitialR2T=Yes and ImmediateData=No, but some targets + * (notably LIO as of kernel 4.11) fail unless it is specified, so we + * explicitly specify the default value. + */ +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, sizeof ( 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, sizeof ( 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" + "FirstBurstLength=65536%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, 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 ); +} + +/** + * Decode large binary value + * + * @v encoded Encoded large binary value + * @v raw Raw data + * @v len Length of data buffer + * @ret len Length of raw data, or negative error + */ +static int iscsi_large_binary_decode ( const char *encoded, uint8_t *raw, + size_t len ) { + + /* Check for initial '0x' or '0b' and decode as appropriate */ + if ( *(encoded++) == '0' ) { + switch ( tolower ( *(encoded++) ) ) { + case 'x' : + return base16_decode ( encoded, raw, len ); + case 'b' : + return base64_decode ( encoded, raw, len ); + } + } + + 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; + unsigned int i; + int len; + int rc; + + /* Allocate decoding buffer */ + len = strlen ( value ); /* Decoding never expands data */ + buf = malloc ( len ); + if ( ! buf ) { + rc = -ENOMEM; + goto err_alloc; + } + + /* Process challenge */ + len = iscsi_large_binary_decode ( value, buf, len ); + if ( len < 0 ) { + rc = len; + DBGC ( iscsi, "iSCSI %p invalid CHAP challenge \"%s\": %s\n", + iscsi, value, strerror ( rc ) ); + goto err_decode; + } + 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(); + } + } + + /* Success */ + rc = 0; + + err_decode: + free ( buf ); + err_alloc: + return rc; +} + +/** + * 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; + int 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 ) ); + goto err_chap_init; + } + 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 ); + + /* Allocate decoding buffer */ + len = strlen ( value ); /* Decoding never expands data */ + buf = malloc ( len ); + if ( ! buf ) { + rc = -ENOMEM; + goto err_alloc; + } + + /* Process response */ + len = iscsi_large_binary_decode ( value, buf, len ); + if ( len < 0 ) { + rc = len; + DBGC ( iscsi, "iSCSI %p invalid CHAP response \"%s\": %s\n", + iscsi, value, strerror ( rc ) ); + goto err_decode; + } + + /* Check CHAP response */ + if ( len != ( int ) iscsi->chap.response_len ) { + DBGC ( iscsi, "iSCSI %p invalid CHAP response length\n", + iscsi ); + rc = -EPROTO_INVALID_CHAP_RESPONSE; + goto err_response_len; + } + if ( memcmp ( buf, iscsi->chap.response, len ) != 0 ) { + DBGC ( iscsi, "iSCSI %p incorrect CHAP response \"%s\"\n", + iscsi, value ); + rc = -EACCES_INCORRECT_TARGET_PASSWORD; + goto err_response; + } + + /* Mark session as authenticated */ + iscsi->status |= ISCSI_STATUS_AUTH_REVERSE_OK; + + err_response: + err_response_len: + err_decode: + free ( buf ); + err_alloc: + err_chap_init: + return rc; +} + +/** 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 ); + break; + case ISCSI_OPCODE_LOGIN_REQUEST: + iscsi_login_request_done ( iscsi ); + break; + 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; + int rc; + + /* 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 ); + } + + /* Redirect to new location */ + if ( ( rc = xfer_vreopen ( &iscsi->socket, type, args ) ) != 0 ) + goto err; + + return 0; + + err: + iscsi_close ( iscsi, rc ); + return rc; +} + +/** 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; +} + +/** + * Get iSCSI ACPI descriptor + * + * @v iscsi iSCSI session + * @ret desc ACPI descriptor + */ +static struct acpi_descriptor * iscsi_describe ( struct iscsi_session *iscsi ) { + + return &iscsi->desc; +} + +/** 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 *, iscsi_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; + char *rp_comp[NUM_RP_COMPONENTS]; + char *rp; + int skip = 0; + int i = 0; + int rc; + + /* Create modifiable copy of root path */ + rp_copy = strdup ( root_path ); + if ( ! rp_copy ) { + rc = -ENOMEM; + goto err_strdup; + } + rp = rp_copy; + + /* Split root path into component parts */ + while ( 1 ) { + rp_comp[i++] = rp; + if ( i == NUM_RP_COMPONENTS ) + break; + for ( ; ( ( *rp != ':' ) || skip ) ; rp++ ) { + if ( ! *rp ) { + DBGC ( iscsi, "iSCSI %p root path \"%s\" " + "too short\n", iscsi, root_path ); + rc = -EINVAL_ROOT_PATH_TOO_SHORT; + goto err_split; + } else if ( *rp == '[' ) { + skip = 1; + } else if ( *rp == ']' ) { + skip = 0; + } + } + *(rp++) = '\0'; + } + + /* Use root path components to configure iSCSI session */ + iscsi->target_address = strdup ( rp_comp[RP_SERVERNAME] ); + if ( ! iscsi->target_address ) { + rc = -ENOMEM; + goto err_servername; + } + 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] ); + goto err_lun; + } + iscsi->target_iqn = strdup ( rp_comp[RP_TARGETNAME] ); + if ( ! iscsi->target_iqn ) { + rc = -ENOMEM; + goto err_targetname; + } + + err_targetname: + err_lun: + err_servername: + err_split: + free ( rp_copy ); + err_strdup: + return rc; +} + +/** + * 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 ); + acpi_init ( &iscsi->desc, &ibft_model, &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/roms/ipxe/src/net/tcp/oncrpc.c b/roms/ipxe/src/net/tcp/oncrpc.c new file mode 100644 index 000000000..cb66aeb85 --- /dev/null +++ b/roms/ipxe/src/net/tcp/oncrpc.c @@ -0,0 +1,245 @@ +/* + * 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[] ) { + 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 ); + + return xfer_deliver_iob ( intf, iob_disown ( io_buf ) ); +} + +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/roms/ipxe/src/net/tcp/syslogs.c b/roms/ipxe/src/net/tcp/syslogs.c new file mode 100644 index 000000000..0c07f86d5 --- /dev/null +++ b/roms/ipxe/src/net/tcp/syslogs.c @@ -0,0 +1,273 @@ +/* + * 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. + * + * You can also choose to distribute this program under the terms of + * the Unmodified Binary Distribution Licence (as given in the file + * COPYING.UBDL), provided that you have satisfied its requirements. + */ + +FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL ); + +/** @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, +}; |