uefi 0.38.0

This crate makes it easy to develop Rust software that leverages safe, convenient, and performant abstractions for UEFI functionality.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
// SPDX-License-Identifier: MIT OR Apache-2.0

#![cfg(feature = "alloc")]

//! HTTP Protocol.
//!
//! See [`Http`].

use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;
use core::ffi::{CStr, c_char, c_void};
use core::ptr;
use log::debug;

use uefi::boot::ScopedProtocol;
use uefi::prelude::*;
use uefi::proto::unsafe_protocol;
use uefi_raw::protocol::driver::ServiceBindingProtocol;
use uefi_raw::protocol::network::http::{
    HttpAccessPoint, HttpConfigData, HttpHeader, HttpMessage, HttpMethod, HttpProtocol,
    HttpRequestData, HttpResponseData, HttpStatusCode, HttpToken, HttpV4AccessPoint, HttpVersion,
};

/// HTTP [`Protocol`]. Send HTTP Requests.
///
/// [`Protocol`]: uefi::proto::Protocol
#[derive(Debug)]
#[unsafe_protocol(HttpProtocol::GUID)]
pub struct Http(HttpProtocol);

impl Http {
    /// Receive HTTP Protocol configuration.
    pub fn get_mode_data(&mut self) -> uefi::Result<HttpConfigData> {
        let mut config_data = HttpConfigData::default();
        let status = unsafe { (self.0.get_mode_data)(&mut self.0, &mut config_data) };
        match status {
            Status::SUCCESS => Ok(config_data),
            _ => Err(status.into()),
        }
    }

    /// Configure HTTP Protocol.  Must be called before sending HTTP requests.
    pub fn configure(&mut self, config_data: &HttpConfigData) -> uefi::Result<()> {
        let status = unsafe { (self.0.configure)(&mut self.0, config_data) };
        debug!("http raw: configure({config_data:?}) -> {status}");
        match status {
            Status::SUCCESS => Ok(()),
            _ => Err(status.into()),
        }
    }

    /// Send HTTP request.
    pub fn request(&mut self, token: &mut HttpToken) -> uefi::Result<()> {
        let status = unsafe { (self.0.request)(&mut self.0, token) };
        debug!(
            "http raw: request(headers={}, body_len={}) -> {status}, token.status={}",
            unsafe { (*token.message).header_count },
            unsafe { (*token.message).body_length },
            token.status,
        );
        match status {
            Status::SUCCESS => Ok(()),
            _ => Err(status.into()),
        }
    }

    /// Cancel HTTP request.
    pub fn cancel(&mut self, token: &mut HttpToken) -> uefi::Result<()> {
        let status = unsafe { (self.0.cancel)(&mut self.0, token) };
        match status {
            Status::SUCCESS => Ok(()),
            _ => Err(status.into()),
        }
    }

    /// Receive HTTP response.
    pub fn response(&mut self, token: &mut HttpToken) -> uefi::Result<()> {
        let status = unsafe { (self.0.response)(&mut self.0, token) };
        debug!(
            "http raw: response(body_len={}) -> {status}, token.status={}",
            unsafe { (*token.message).body_length },
            token.status,
        );
        match status {
            Status::SUCCESS => Ok(()),
            _ => Err(status.into()),
        }
    }

    /// Poll network stack for updates.
    pub fn poll(&mut self) -> uefi::Result<()> {
        let status = unsafe { (self.0.poll)(&mut self.0) };
        match status {
            Status::SUCCESS => Ok(()),
            _ => Err(status.into()),
        }
    }
}

/// HTTP Service Binding Protocol.
#[derive(Debug)]
#[unsafe_protocol(HttpProtocol::SERVICE_BINDING_GUID)]
pub struct HttpBinding(ServiceBindingProtocol);

impl HttpBinding {
    /// Create HTTP Protocol Handle.
    pub fn create_child(&mut self) -> uefi::Result<Handle> {
        let mut c_handle = ptr::null_mut();
        let status;
        let handle;
        unsafe {
            status = (self.0.create_child)(&mut self.0, &mut c_handle);
            handle = Handle::from_ptr(c_handle);
        };
        match status {
            Status::SUCCESS => Ok(handle.unwrap()),
            _ => Err(status.into()),
        }
    }

    /// Destroy HTTP Protocol Handle.
    pub fn destroy_child(&mut self, handle: Handle) -> uefi::Result<()> {
        let status = unsafe { (self.0.destroy_child)(&mut self.0, handle.as_ptr()) };
        match status {
            Status::SUCCESS => Ok(()),
            _ => Err(status.into()),
        }
    }
}

/// Representation of the underlying UEFI HTTP response.
///
/// Helper type for [`HttpHelper`].
#[derive(Debug)]
pub struct HttpHelperResponse {
    /// HTTP Status
    pub status: HttpStatusCode,
    /// HTTP Response Headers
    pub headers: Vec<(String, String)>,
    /// Partial or entire HTTP body, depending on context.
    pub body: Vec<u8>,
}

/// HTTP Helper, makes using the [HTTP] [`Protocol`] more convenient.
///
/// [HTTP]: Http
/// [`Protocol`]: uefi::proto::Protocol
#[derive(Debug)]
pub struct HttpHelper {
    child_handle: Handle,
    binding: ScopedProtocol<HttpBinding>,
    protocol: Option<ScopedProtocol<Http>>,
}

impl HttpHelper {
    /// Create new HTTP helper instance for the given NIC handle.
    pub fn new(nic_handle: Handle) -> uefi::Result<Self> {
        let mut binding = unsafe {
            boot::open_protocol::<HttpBinding>(
                boot::OpenProtocolParams {
                    handle: nic_handle,
                    agent: boot::image_handle(),
                    controller: None,
                },
                boot::OpenProtocolAttributes::GetProtocol,
            )?
        };
        debug!("http: binding proto ok");

        let child_handle = binding.create_child()?;
        debug!("http: child handle ok");

        let protocol_res = unsafe {
            boot::open_protocol::<Http>(
                boot::OpenProtocolParams {
                    handle: child_handle,
                    agent: boot::image_handle(),
                    controller: None,
                },
                boot::OpenProtocolAttributes::GetProtocol,
            )
        };
        if let Err(e) = protocol_res {
            let _ = binding.destroy_child(child_handle);
            return Err(e);
        }
        debug!("http: protocol ok");

        Ok(Self {
            child_handle,
            binding,
            protocol: Some(protocol_res.unwrap()),
        })
    }

    /// Configure the HTTP Protocol with some sane defaults.
    pub fn configure(&mut self) -> uefi::Result<()> {
        let ip4 = HttpV4AccessPoint {
            use_default_addr: true.into(),
            ..Default::default()
        };

        let config = HttpConfigData {
            http_version: HttpVersion::HTTP_VERSION_10,
            time_out_millisec: 10_000,
            local_addr_is_ipv6: false.into(),
            access_point: HttpAccessPoint { ipv4_node: &ip4 },
        };

        self.protocol.as_mut().unwrap().configure(&config)?;
        debug!("http: configure ok");

        Ok(())
    }

    /// Send HTTP request
    pub fn request(
        &mut self,
        method: HttpMethod,
        url: &str,
        body: Option<&mut [u8]>,
    ) -> uefi::Result<()> {
        let url16 = uefi::CString16::try_from(url).unwrap();

        let scheme = url.split(':').next().unwrap_or("<missing>");
        let Some(hostname) = url.split('/').nth(2) else {
            return Err(Status::INVALID_PARAMETER.into());
        };
        let mut c_hostname = String::from(hostname);
        c_hostname.push('\0');
        debug!(
            "http: request setup: method={method:?}, scheme={scheme}, host={hostname}, body_len={}",
            body.as_ref().map_or(0, |body| body.len())
        );

        let mut tx_req = HttpRequestData {
            method,
            url: url16.as_ptr().cast::<u16>(),
        };

        let mut tx_hdr = Vec::new();
        tx_hdr.push(HttpHeader {
            field_name: c"Host".as_ptr().cast::<u8>(),
            field_value: c_hostname.as_ptr(),
        });

        let mut tx_msg = HttpMessage::default();
        tx_msg.data.request = &mut tx_req;
        tx_msg.header_count = tx_hdr.len();
        tx_msg.header = tx_hdr.as_mut_ptr();
        if let Some(body) = body {
            tx_msg.body_length = body.len();
            tx_msg.body = body.as_mut_ptr().cast::<c_void>();
        }

        let mut tx_token = HttpToken {
            status: Status::NOT_READY,
            message: &mut tx_msg,
            ..Default::default()
        };

        let p = self.protocol.as_mut().unwrap();
        p.request(&mut tx_token)?;
        debug!("http: request sent ok");

        let mut polls = 0;
        loop {
            if tx_token.status != Status::NOT_READY {
                break;
            }
            polls += 1;
            p.poll()?;
        }
        debug!(
            "http: request token completed after {polls} polls with {}",
            tx_token.status
        );

        if tx_token.status != Status::SUCCESS {
            return Err(tx_token.status.into());
        };

        debug!("http: request status ok");

        Ok(())
    }

    /// Send HTTP GET request
    pub fn request_get(&mut self, url: &str) -> uefi::Result<()> {
        self.request(HttpMethod::GET, url, None)?;
        Ok(())
    }

    /// Send HTTP HEAD request
    pub fn request_head(&mut self, url: &str) -> uefi::Result<()> {
        self.request(HttpMethod::HEAD, url, None)?;
        Ok(())
    }

    /// Receive the start of the http response, the headers and (parts of) the
    /// body.
    ///
    /// Depending on the HTTP response, its length, its encoding, and its
    /// transmission method (chunked or not), users may have to call
    /// [`Self::response_more`] afterward.
    pub fn response_first(&mut self, expect_body: bool) -> uefi::Result<HttpHelperResponse> {
        let mut rx_rsp = HttpResponseData {
            status_code: HttpStatusCode::STATUS_UNSUPPORTED,
        };

        let mut body = vec![0; if expect_body { 16 * 1024 } else { 0 }];
        let mut rx_msg = HttpMessage::default();
        rx_msg.data.response = &mut rx_rsp;
        rx_msg.body_length = body.len();
        rx_msg.body = if !body.is_empty() {
            body.as_mut_ptr()
        } else {
            ptr::null()
        } as *mut c_void;

        let mut rx_token = HttpToken {
            status: Status::NOT_READY,
            message: &mut rx_msg,
            ..Default::default()
        };

        let p = self.protocol.as_mut().unwrap();
        p.response(&mut rx_token)?;

        loop {
            if rx_token.status != Status::NOT_READY {
                break;
            }
            p.poll()?;
        }

        debug!(
            "http: response: {} / {:?}",
            rx_token.status, rx_rsp.status_code
        );

        if rx_token.status != Status::SUCCESS && rx_token.status != Status::HTTP_ERROR {
            return Err(rx_token.status.into());
        };

        debug!("http: headers: {}", rx_msg.header_count);
        let mut headers: Vec<(String, String)> = Vec::new();
        for i in 0..rx_msg.header_count {
            let n;
            let v;
            unsafe {
                n = CStr::from_ptr((*rx_msg.header.add(i)).field_name.cast::<c_char>());
                v = CStr::from_ptr((*rx_msg.header.add(i)).field_value.cast::<c_char>());
            }
            headers.push((
                n.to_str().unwrap().to_lowercase(),
                String::from(v.to_str().unwrap()),
            ));
        }

        debug!("http: body: {}/{}", rx_msg.body_length, body.len());

        let rsp = HttpHelperResponse {
            status: rx_rsp.status_code,
            headers,
            body: body[0..rx_msg.body_length].to_vec(),
        };
        Ok(rsp)
    }

    /// Try to receive more of the HTTP response and append any new data to the
    /// provided  `body` vector.
    pub fn response_more<'a>(&mut self, body: &'a mut Vec<u8>) -> uefi::Result<&'a [u8]> {
        let mut body_recv_buffer = vec![0; 16 * 1024];
        let mut rx_msg = HttpMessage {
            body_length: body_recv_buffer.len(),
            body: body_recv_buffer.as_mut_ptr().cast::<c_void>(),
            ..Default::default()
        };

        let mut rx_token = HttpToken {
            status: Status::NOT_READY,
            message: &mut rx_msg,
            ..Default::default()
        };

        let p = self.protocol.as_mut().unwrap();
        p.response(&mut rx_token)?;

        loop {
            if rx_token.status != Status::NOT_READY {
                break;
            }
            p.poll()?;
        }

        debug!("http: response: {}", rx_token.status);

        if rx_token.status != Status::SUCCESS {
            return Err(rx_token.status.into());
        };

        debug!(
            "http: body: {}/{}",
            rx_msg.body_length,
            body_recv_buffer.len()
        );

        let new_data = &body_recv_buffer[0..rx_msg.body_length];
        body.extend(new_data);
        let new_data_slice = &body[body.len() - new_data.len()..];
        Ok(new_data_slice)
    }
}

impl Drop for HttpHelper {
    fn drop(&mut self) {
        // protocol must go out of scope before calling destroy_child
        self.protocol = None;
        let _ = self.binding.destroy_child(self.child_handle);
    }
}