aienux
Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.
Brought by drakestapleton
aienux / vendor / uefi / src / proto / network / http.rs
| 1 | // SPDX-License-Identifier: MIT OR Apache-2.0 |
| 2 | |
| 3 | #![cfg(feature = "alloc")] |
| 4 | |
| 5 | //! HTTP Protocol. |
| 6 | //! |
| 7 | //! See [`Http`]. |
| 8 | |
| 9 | use alloc::string::String; |
| 10 | use alloc::vec; |
| 11 | use alloc::vec::Vec; |
| 12 | use core::ffi::{CStr, c_char, c_void}; |
| 13 | use core::ptr::{self, NonNull}; |
| 14 | use log::debug; |
| 15 | |
| 16 | use uefi::boot::{self, ScopedProtocol}; |
| 17 | use uefi::prelude::*; |
| 18 | use uefi::proto::unsafe_protocol; |
| 19 | use uefi_raw::protocol::driver::ServiceBindingProtocol; |
| 20 | use uefi_raw::protocol::network::http::{ |
| 21 | HttpAccessPoint, HttpConfigData, HttpHeader, HttpMessage, HttpMethod, HttpProtocol, |
| 22 | HttpRequestData, HttpResponseData, HttpStatusCode, HttpToken, HttpV4AccessPoint, HttpVersion, |
| 23 | }; |
| 24 | |
| 25 | /// HTTP [`Protocol`]. Send HTTP Requests. |
| 26 | /// |
| 27 | /// [`Protocol`]: uefi::proto::Protocol |
| 28 | #[derive(Debug)] |
| 29 | #[unsafe_protocol(HttpProtocol::GUID)] |
| 30 | #[repr(transparent)] |
| 31 | pub struct Http(HttpProtocol); |
| 32 | |
| 33 | impl Http { |
| 34 | /// Receive HTTP Protocol configuration. |
| 35 | pub fn get_mode_data(&mut self) -> uefi::Result<HttpConfigData> { |
| 36 | let mut config_data = HttpConfigData::default(); |
| 37 | // SAFETY: The memory is valid. |
| 38 | let status = unsafe { (self.0.get_mode_data)(&mut self.0, &mut config_data) }; |
| 39 | match status { |
| 40 | Status::SUCCESS => Ok(config_data), |
| 41 | _ => Err(status.into()), |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | /// Configure HTTP Protocol. Must be called before sending HTTP requests. |
| 46 | pub fn configure(&mut self, config_data: &HttpConfigData) -> uefi::Result<()> { |
| 47 | // SAFETY: The memory is valid. |
| 48 | let status = unsafe { (self.0.configure)(&mut self.0, config_data) }; |
| 49 | debug!("http raw: configure({config_data:?}) -> {status}"); |
| 50 | match status { |
| 51 | Status::SUCCESS => Ok(()), |
| 52 | _ => Err(status.into()), |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | /// Send HTTP request. |
| 57 | pub fn request(&mut self, token: &mut HttpToken) -> uefi::Result<()> { |
| 58 | // SAFETY: The memory is valid. |
| 59 | let status = unsafe { (self.0.request)(&mut self.0, token) }; |
| 60 | debug!( |
| 61 | "http raw: request(headers={}, body_len={}) -> {status}, token.status={}", |
| 62 | // SAFETY: The memory is valid. |
| 63 | unsafe { (*token.message).header_count }, |
| 64 | // SAFETY: The memory is valid. |
| 65 | unsafe { (*token.message).body_length }, |
| 66 | token.status, |
| 67 | ); |
| 68 | match status { |
| 69 | Status::SUCCESS => Ok(()), |
| 70 | _ => Err(status.into()), |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | /// Cancel HTTP request. |
| 75 | pub fn cancel(&mut self, token: &mut HttpToken) -> uefi::Result<()> { |
| 76 | // SAFETY: The memory is valid. |
| 77 | let status = unsafe { (self.0.cancel)(&mut self.0, token) }; |
| 78 | match status { |
| 79 | Status::SUCCESS => Ok(()), |
| 80 | _ => Err(status.into()), |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | /// Receive HTTP response. |
| 85 | pub fn response(&mut self, token: &mut HttpToken) -> uefi::Result<()> { |
| 86 | // SAFETY: The memory is valid. |
| 87 | let status = unsafe { (self.0.response)(&mut self.0, token) }; |
| 88 | debug!( |
| 89 | "http raw: response(body_len={}) -> {status}, token.status={}", |
| 90 | // SAFETY: The memory is valid. |
| 91 | unsafe { (*token.message).body_length }, |
| 92 | token.status, |
| 93 | ); |
| 94 | match status { |
| 95 | Status::SUCCESS => Ok(()), |
| 96 | _ => Err(status.into()), |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | /// Poll network stack for updates. |
| 101 | pub fn poll(&mut self) -> uefi::Result<()> { |
| 102 | // SAFETY: The memory is valid. |
| 103 | let status = unsafe { (self.0.poll)(&mut self.0) }; |
| 104 | match status { |
| 105 | Status::SUCCESS => Ok(()), |
| 106 | _ => Err(status.into()), |
| 107 | } |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | /// A token that was handed to the firmware by [`Http::request`] or |
| 112 | /// [`Http::response`] and has not completed yet. |
| 113 | struct PendingToken<'a> { |
| 114 | http: &'a mut Http, |
| 115 | token: &'a mut HttpToken, |
| 116 | } |
| 117 | |
| 118 | impl<'a> PendingToken<'a> { |
| 119 | /// Sends the request described by `token`. |
| 120 | fn request(http: &'a mut Http, token: &'a mut HttpToken) -> uefi::Result<Self> { |
| 121 | http.request(token)?; |
| 122 | Ok(Self { http, token }) |
| 123 | } |
| 124 | |
| 125 | /// Starts receiving the response described by `token`. |
| 126 | fn response(http: &'a mut Http, token: &'a mut HttpToken) -> uefi::Result<Self> { |
| 127 | http.response(token)?; |
| 128 | Ok(Self { http, token }) |
| 129 | } |
| 130 | |
| 131 | /// Polls the network stack until the token completes and returns its |
| 132 | /// final status. |
| 133 | fn wait(self) -> uefi::Result<Status> { |
| 134 | let mut polls = 0; |
| 135 | while self.token.status == Status::NOT_READY { |
| 136 | self.http.poll()?; |
| 137 | polls += 1; |
| 138 | } |
| 139 | debug!( |
| 140 | "http: token completed after {polls} polls with {}", |
| 141 | self.token.status |
| 142 | ); |
| 143 | Ok(self.token.status) |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | impl Drop for PendingToken<'_> { |
| 148 | fn drop(&mut self) { |
| 149 | if self.token.status == Status::NOT_READY { |
| 150 | // Nothing sensible can be done if cancelling fails. |
| 151 | let _ = self.http.cancel(self.token); |
| 152 | } |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | /// HTTP Service Binding Protocol. |
| 157 | #[derive(Debug)] |
| 158 | #[unsafe_protocol(HttpProtocol::SERVICE_BINDING_GUID)] |
| 159 | #[repr(transparent)] |
| 160 | pub struct HttpBinding(ServiceBindingProtocol); |
| 161 | |
| 162 | impl HttpBinding { |
| 163 | /// Create HTTP Protocol Handle. |
| 164 | pub fn create_child(&mut self) -> uefi::Result<Handle> { |
| 165 | let mut c_handle = ptr::null_mut(); |
| 166 | let status; |
| 167 | let handle; |
| 168 | // SAFETY: The memory is valid. |
| 169 | unsafe { |
| 170 | status = (self.0.create_child)(&mut self.0, &mut c_handle); |
| 171 | handle = Handle::from_ptr(c_handle); |
| 172 | }; |
| 173 | match status { |
| 174 | Status::SUCCESS => Ok(handle.unwrap()), |
| 175 | _ => Err(status.into()), |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | /// Destroy HTTP Protocol Handle. |
| 180 | pub fn destroy_child(&mut self, handle: Handle) -> uefi::Result<()> { |
| 181 | // SAFETY: The memory is valid. |
| 182 | let status = unsafe { (self.0.destroy_child)(&mut self.0, handle.as_ptr()) }; |
| 183 | match status { |
| 184 | Status::SUCCESS => Ok(()), |
| 185 | _ => Err(status.into()), |
| 186 | } |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | /// Representation of the underlying UEFI HTTP response. |
| 191 | /// |
| 192 | /// Helper type for [`HttpHelper`]. |
| 193 | #[derive(Debug)] |
| 194 | pub struct HttpHelperResponse { |
| 195 | /// HTTP Status |
| 196 | pub status: HttpStatusCode, |
| 197 | /// HTTP Response Headers |
| 198 | pub headers: Vec<(String, String)>, |
| 199 | /// Partial or entire HTTP body, depending on context. |
| 200 | pub body: Vec<u8>, |
| 201 | } |
| 202 | |
| 203 | /// HTTP Helper, makes using the [HTTP] [`Protocol`] more convenient. |
| 204 | /// |
| 205 | /// [HTTP]: Http |
| 206 | /// [`Protocol`]: uefi::proto::Protocol |
| 207 | #[derive(Debug)] |
| 208 | pub struct HttpHelper { |
| 209 | child_handle: Handle, |
| 210 | binding: ScopedProtocol<HttpBinding>, |
| 211 | protocol: Option<ScopedProtocol<Http>>, |
| 212 | } |
| 213 | |
| 214 | /// Frees the headers of a response message. |
| 215 | /// |
| 216 | /// The driver allocates the header array as well as each field name and |
| 217 | /// value from the pool, and the caller has to free all of them. |
| 218 | /// |
| 219 | /// # Safety |
| 220 | /// |
| 221 | /// `msg` must be a response message filled by the driver. |
| 222 | unsafe fn free_response_headers(msg: &HttpMessage) { |
| 223 | let Some(headers) = NonNull::new(msg.header) else { |
| 224 | return; |
| 225 | }; |
| 226 | for i in 0..msg.header_count { |
| 227 | // SAFETY: The driver wrote `header_count` entries. |
| 228 | let header = unsafe { &*headers.as_ptr().add(i) }; |
| 229 | for field in [header.field_name, header.field_value] { |
| 230 | if let Some(field) = NonNull::new(field.cast_mut()) { |
| 231 | // SAFETY: The string was allocated by the matching UEFI |
| 232 | // allocator. |
| 233 | let _ = unsafe { boot::free_pool(field.cast()) }; |
| 234 | } |
| 235 | } |
| 236 | } |
| 237 | // SAFETY: The array was allocated by the matching UEFI allocator. |
| 238 | let _ = unsafe { boot::free_pool(headers.cast()) }; |
| 239 | } |
| 240 | |
| 241 | impl HttpHelper { |
| 242 | /// Create new HTTP helper instance for the given NIC handle. |
| 243 | pub fn new(nic_handle: Handle) -> uefi::Result<Self> { |
| 244 | // SAFETY: The memory is valid. |
| 245 | let mut binding = unsafe { |
| 246 | boot::open_protocol::<HttpBinding>( |
| 247 | boot::OpenProtocolParams { |
| 248 | handle: nic_handle, |
| 249 | agent: boot::image_handle(), |
| 250 | controller: None, |
| 251 | }, |
| 252 | boot::OpenProtocolAttributes::GetProtocol, |
| 253 | )? |
| 254 | }; |
| 255 | debug!("http: binding proto ok"); |
| 256 | |
| 257 | let child_handle = binding.create_child()?; |
| 258 | debug!("http: child handle ok"); |
| 259 | |
| 260 | // SAFETY: The memory is valid. |
| 261 | let protocol_res = unsafe { |
| 262 | boot::open_protocol::<Http>( |
| 263 | boot::OpenProtocolParams { |
| 264 | handle: child_handle, |
| 265 | agent: boot::image_handle(), |
| 266 | controller: None, |
| 267 | }, |
| 268 | boot::OpenProtocolAttributes::GetProtocol, |
| 269 | ) |
| 270 | }; |
| 271 | if let Err(e) = protocol_res { |
| 272 | let _ = binding.destroy_child(child_handle); |
| 273 | return Err(e); |
| 274 | } |
| 275 | debug!("http: protocol ok"); |
| 276 | |
| 277 | Ok(Self { |
| 278 | child_handle, |
| 279 | binding, |
| 280 | protocol: Some(protocol_res.unwrap()), |
| 281 | }) |
| 282 | } |
| 283 | |
| 284 | /// Configure the HTTP Protocol with some sane defaults. |
| 285 | pub fn configure(&mut self) -> uefi::Result<()> { |
| 286 | let mut ip4 = HttpV4AccessPoint { |
| 287 | use_default_addr: true.into(), |
| 288 | ..Default::default() |
| 289 | }; |
| 290 | |
| 291 | let config = HttpConfigData { |
| 292 | http_version: HttpVersion::HTTP_VERSION_10, |
| 293 | time_out_millisec: 10_000, |
| 294 | local_addr_is_ipv6: false.into(), |
| 295 | access_point: HttpAccessPoint { |
| 296 | ipv4_node: &mut ip4, |
| 297 | }, |
| 298 | }; |
| 299 | |
| 300 | self.protocol.as_mut().unwrap().configure(&config)?; |
| 301 | debug!("http: configure ok"); |
| 302 | |
| 303 | Ok(()) |
| 304 | } |
| 305 | |
| 306 | /// Send HTTP request |
| 307 | pub fn request( |
| 308 | &mut self, |
| 309 | method: HttpMethod, |
| 310 | url: &str, |
| 311 | body: Option<&mut [u8]>, |
| 312 | ) -> uefi::Result<()> { |
| 313 | let url16 = uefi::CString16::try_from(url).unwrap(); |
| 314 | |
| 315 | let scheme = url.split(':').next().unwrap_or("<missing>"); |
| 316 | let Some(hostname) = url.split('/').nth(2) else { |
| 317 | return Err(Status::INVALID_PARAMETER.into()); |
| 318 | }; |
| 319 | let mut c_hostname = String::from(hostname); |
| 320 | c_hostname.push('\0'); |
| 321 | debug!( |
| 322 | "http: request setup: method={method:?}, scheme={scheme}, host={hostname}, body_len={}", |
| 323 | body.as_ref().map_or(0, |body| body.len()) |
| 324 | ); |
| 325 | |
| 326 | let mut tx_req = HttpRequestData { |
| 327 | method, |
| 328 | url: url16.as_ptr().cast::<u16>(), |
| 329 | }; |
| 330 | |
| 331 | let mut tx_hdr = Vec::new(); |
| 332 | tx_hdr.push(HttpHeader { |
| 333 | field_name: c"Host".as_ptr().cast::<u8>(), |
| 334 | field_value: c_hostname.as_ptr(), |
| 335 | }); |
| 336 | |
| 337 | let mut tx_msg = HttpMessage::default(); |
| 338 | tx_msg.data.request = &mut tx_req; |
| 339 | tx_msg.header_count = tx_hdr.len(); |
| 340 | tx_msg.header = tx_hdr.as_mut_ptr(); |
| 341 | if let Some(body) = body { |
| 342 | tx_msg.body_length = body.len(); |
| 343 | tx_msg.body = body.as_mut_ptr().cast::<c_void>(); |
| 344 | } |
| 345 | |
| 346 | let mut tx_token = HttpToken { |
| 347 | status: Status::NOT_READY, |
| 348 | message: &mut tx_msg, |
| 349 | ..Default::default() |
| 350 | }; |
| 351 | |
| 352 | let p = self.protocol.as_mut().unwrap(); |
| 353 | let pending = PendingToken::request(p, &mut tx_token)?; |
| 354 | debug!("http: request sent ok"); |
| 355 | |
| 356 | let status = pending.wait()?; |
| 357 | if status != Status::SUCCESS { |
| 358 | return Err(status.into()); |
| 359 | }; |
| 360 | |
| 361 | debug!("http: request status ok"); |
| 362 | |
| 363 | Ok(()) |
| 364 | } |
| 365 | |
| 366 | /// Send HTTP GET request |
| 367 | pub fn request_get(&mut self, url: &str) -> uefi::Result<()> { |
| 368 | self.request(HttpMethod::GET, url, None)?; |
| 369 | Ok(()) |
| 370 | } |
| 371 | |
| 372 | /// Send HTTP HEAD request |
| 373 | pub fn request_head(&mut self, url: &str) -> uefi::Result<()> { |
| 374 | self.request(HttpMethod::HEAD, url, None)?; |
| 375 | Ok(()) |
| 376 | } |
| 377 | |
| 378 | /// Receive the start of the http response, the headers and (parts of) the |
| 379 | /// body. |
| 380 | /// |
| 381 | /// Depending on the HTTP response, its length, its encoding, and its |
| 382 | /// transmission method (chunked or not), users may have to call |
| 383 | /// [`Self::response_more`] afterward. |
| 384 | pub fn response_first(&mut self, expect_body: bool) -> uefi::Result<HttpHelperResponse> { |
| 385 | let mut rx_rsp = HttpResponseData { |
| 386 | status_code: HttpStatusCode::STATUS_UNSUPPORTED, |
| 387 | }; |
| 388 | |
| 389 | let mut body = vec![0; if expect_body { 16 * 1024 } else { 0 }]; |
| 390 | let mut rx_msg = HttpMessage::default(); |
| 391 | rx_msg.data.response = &mut rx_rsp; |
| 392 | rx_msg.body_length = body.len(); |
| 393 | rx_msg.body = if !body.is_empty() { |
| 394 | body.as_mut_ptr() |
| 395 | } else { |
| 396 | ptr::null() |
| 397 | } as *mut c_void; |
| 398 | |
| 399 | let mut rx_token = HttpToken { |
| 400 | status: Status::NOT_READY, |
| 401 | message: &mut rx_msg, |
| 402 | ..Default::default() |
| 403 | }; |
| 404 | |
| 405 | let p = self.protocol.as_mut().unwrap(); |
| 406 | let status = PendingToken::response(p, &mut rx_token)?.wait()?; |
| 407 | |
| 408 | debug!("http: response: {status} / {:?}", rx_rsp.status_code); |
| 409 | |
| 410 | if status != Status::SUCCESS && status != Status::HTTP_ERROR { |
| 411 | // SAFETY: `rx_msg` was filled by the driver. |
| 412 | unsafe { free_response_headers(&rx_msg) }; |
| 413 | return Err(status.into()); |
| 414 | }; |
| 415 | |
| 416 | debug!("http: headers: {}", rx_msg.header_count); |
| 417 | let mut headers: Vec<(String, String)> = Vec::new(); |
| 418 | for i in 0..rx_msg.header_count { |
| 419 | let n; |
| 420 | let v; |
| 421 | // SAFETY: The memory is valid. |
| 422 | unsafe { |
| 423 | n = CStr::from_ptr((*rx_msg.header.add(i)).field_name.cast::<c_char>()); |
| 424 | v = CStr::from_ptr((*rx_msg.header.add(i)).field_value.cast::<c_char>()); |
| 425 | } |
| 426 | // The strings come from the server and are not guaranteed to be |
| 427 | // UTF-8. |
| 428 | headers.push(( |
| 429 | String::from_utf8_lossy(n.to_bytes()).to_lowercase(), |
| 430 | String::from_utf8_lossy(v.to_bytes()).into_owned(), |
| 431 | )); |
| 432 | } |
| 433 | // SAFETY: `rx_msg` was filled by the driver. |
| 434 | unsafe { free_response_headers(&rx_msg) }; |
| 435 | |
| 436 | debug!("http: body: {}/{}", rx_msg.body_length, body.len()); |
| 437 | |
| 438 | let rsp = HttpHelperResponse { |
| 439 | status: rx_rsp.status_code, |
| 440 | headers, |
| 441 | body: body[0..rx_msg.body_length].to_vec(), |
| 442 | }; |
| 443 | Ok(rsp) |
| 444 | } |
| 445 | |
| 446 | /// Try to receive more of the HTTP response and append any new data to the |
| 447 | /// provided `body` vector. |
| 448 | pub fn response_more<'a>(&mut self, body: &'a mut Vec<u8>) -> uefi::Result<&'a [u8]> { |
| 449 | let mut body_recv_buffer = vec![0; 16 * 1024]; |
| 450 | let mut rx_msg = HttpMessage { |
| 451 | body_length: body_recv_buffer.len(), |
| 452 | body: body_recv_buffer.as_mut_ptr().cast::<c_void>(), |
| 453 | ..Default::default() |
| 454 | }; |
| 455 | |
| 456 | let mut rx_token = HttpToken { |
| 457 | status: Status::NOT_READY, |
| 458 | message: &mut rx_msg, |
| 459 | ..Default::default() |
| 460 | }; |
| 461 | |
| 462 | let p = self.protocol.as_mut().unwrap(); |
| 463 | let status = PendingToken::response(p, &mut rx_token)?.wait()?; |
| 464 | |
| 465 | debug!("http: response: {status}"); |
| 466 | |
| 467 | if status != Status::SUCCESS { |
| 468 | return Err(status.into()); |
| 469 | }; |
| 470 | |
| 471 | debug!( |
| 472 | "http: body: {}/{}", |
| 473 | rx_msg.body_length, |
| 474 | body_recv_buffer.len() |
| 475 | ); |
| 476 | |
| 477 | let new_data = &body_recv_buffer[0..rx_msg.body_length]; |
| 478 | body.extend(new_data); |
| 479 | let new_data_slice = &body[body.len() - new_data.len()..]; |
| 480 | Ok(new_data_slice) |
| 481 | } |
| 482 | } |
| 483 | |
| 484 | impl Drop for HttpHelper { |
| 485 | fn drop(&mut self) { |
| 486 | // protocol must go out of scope before calling destroy_child |
| 487 | self.protocol = None; |
| 488 | let _ = self.binding.destroy_child(self.child_handle); |
| 489 | } |
| 490 | } |