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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
use crate::headers::ContentType;
/// Low level API for encoding requests and decoding responses.
use crate::Error;
use core::fmt::Write as _;
use core::mem::size_of;
use embedded_io::{Error as _, ErrorType};
use embedded_io_async::Write;
use heapless::String;

/// A read only HTTP request type
pub struct Request<'a, B>
where
    B: RequestBody,
{
    pub(crate) method: Method,
    pub(crate) base_path: Option<&'a str>,
    pub(crate) path: &'a str,
    pub(crate) auth: Option<Auth<'a>>,
    pub(crate) host: Option<&'a str>,
    pub(crate) body: Option<B>,
    pub(crate) content_type: Option<ContentType>,
    pub(crate) extra_headers: Option<&'a [(&'a str, &'a str)]>,
}

impl Default for Request<'_, ()> {
    fn default() -> Self {
        Self {
            method: Method::GET,
            base_path: None,
            path: "/",
            auth: None,
            host: None,
            body: None,
            content_type: None,
            extra_headers: None,
        }
    }
}

/// A HTTP request builder.
pub trait RequestBuilder<'a, B>
where
    B: RequestBody,
{
    type WithBody<T: RequestBody>: RequestBuilder<'a, T>;

    /// Set optional headers on the request.
    fn headers(self, headers: &'a [(&'a str, &'a str)]) -> Self;
    /// Set the path of the HTTP request.
    fn path(self, path: &'a str) -> Self;
    /// Set the data to send in the HTTP request body.
    fn body<T: RequestBody>(self, body: T) -> Self::WithBody<T>;
    /// Set the host header.
    fn host(self, host: &'a str) -> Self;
    /// Set the content type header for the request.
    fn content_type(self, content_type: ContentType) -> Self;
    /// Set the basic authentication header for the request.
    fn basic_auth(self, username: &'a str, password: &'a str) -> Self;
    /// Return an immutable request.
    fn build(self) -> Request<'a, B>;
}

/// Request authentication scheme.
pub enum Auth<'a> {
    Basic { username: &'a str, password: &'a str },
}

impl<'a> Request<'a, ()> {
    /// Create a new http request.
    #[allow(clippy::new_ret_no_self)]
    pub fn new(method: Method, path: &'a str) -> DefaultRequestBuilder<'a, ()> {
        DefaultRequestBuilder(Request {
            method,
            path,
            ..Default::default()
        })
    }

    /// Create a new GET http request.
    pub fn get(path: &'a str) -> DefaultRequestBuilder<'a, ()> {
        Self::new(Method::GET, path)
    }

    /// Create a new POST http request.
    pub fn post(path: &'a str) -> DefaultRequestBuilder<'a, ()> {
        Self::new(Method::POST, path)
    }

    /// Create a new PUT http request.
    pub fn put(path: &'a str) -> DefaultRequestBuilder<'a, ()> {
        Self::new(Method::PUT, path)
    }

    /// Create a new DELETE http request.
    pub fn delete(path: &'a str) -> DefaultRequestBuilder<'a, ()> {
        Self::new(Method::DELETE, path)
    }

    /// Create a new HEAD http request.
    pub fn head(path: &'a str) -> DefaultRequestBuilder<'a, ()> {
        Self::new(Method::HEAD, path)
    }
}

impl<'a, B> Request<'a, B>
where
    B: RequestBody,
{
    /// Write request to the I/O stream
    pub async fn write<C>(&self, c: &mut C) -> Result<(), Error>
    where
        C: Write,
    {
        write_str(c, self.method.as_str()).await?;
        write_str(c, " ").await?;
        if let Some(base_path) = self.base_path {
            write_str(c, base_path.trim_end_matches('/')).await?;
            if !self.path.starts_with('/') {
                write_str(c, "/").await?;
            }
        }
        write_str(c, self.path).await?;
        write_str(c, " HTTP/1.1\r\n").await?;

        if let Some(auth) = &self.auth {
            match auth {
                Auth::Basic { username, password } => {
                    use base64::engine::{general_purpose, Engine as _};

                    let mut combined: String<128> = String::new();
                    write!(combined, "{}:{}", username, password).map_err(|_| Error::Codec)?;
                    let mut authz = [0; 256];
                    let authz_len = general_purpose::STANDARD
                        .encode_slice(combined.as_bytes(), &mut authz)
                        .map_err(|_| Error::Codec)?;
                    write_str(c, "Authorization: Basic ").await?;
                    write_str(c, unsafe { core::str::from_utf8_unchecked(&authz[..authz_len]) }).await?;
                    write_str(c, "\r\n").await?;
                }
            }
        }
        if let Some(host) = &self.host {
            write_header(c, "Host", host).await?;
        }
        if let Some(content_type) = &self.content_type {
            write_header(c, "Content-Type", content_type.as_str()).await?;
        }
        if let Some(body) = self.body.as_ref() {
            if let Some(len) = body.len() {
                let mut s: String<32> = String::new();
                write!(s, "{}", len).map_err(|_| Error::Codec)?;
                write_header(c, "Content-Length", s.as_str()).await?;
            } else {
                write_header(c, "Transfer-Encoding", "chunked").await?;
            }
        }
        if let Some(extra_headers) = self.extra_headers {
            for (header, value) in extra_headers.iter() {
                write_header(c, header, value).await?;
            }
        }
        write_str(c, "\r\n").await?;
        trace!("Header written");
        if let Some(body) = self.body.as_ref() {
            match body.len() {
                Some(0) => {
                    // Empty body
                }
                Some(len) => {
                    trace!("Writing not-chunked body");
                    let mut writer = FixedBodyWriter(c, 0);
                    body.write(&mut writer).await.map_err(to_errorkind)?;

                    if writer.1 != len {
                        return Err(Error::IncorrectBodyWritten);
                    }
                }
                None => {
                    trace!("Writing chunked body");
                    let mut writer = ChunkedBodyWriter(c, 0);
                    body.write(&mut writer).await?;

                    write_str(c, "0\r\n\r\n").await?;
                }
            }
        }

        c.flush().await.map_err(|e| e.kind())?;
        Ok(())
    }
}

pub struct DefaultRequestBuilder<'a, B>(Request<'a, B>)
where
    B: RequestBody;

impl<'a, B> RequestBuilder<'a, B> for DefaultRequestBuilder<'a, B>
where
    B: RequestBody,
{
    type WithBody<T: RequestBody> = DefaultRequestBuilder<'a, T>;

    fn headers(mut self, headers: &'a [(&'a str, &'a str)]) -> Self {
        self.0.extra_headers.replace(headers);
        self
    }

    fn path(mut self, path: &'a str) -> Self {
        self.0.path = path;
        self
    }

    fn body<T: RequestBody>(self, body: T) -> Self::WithBody<T> {
        DefaultRequestBuilder(Request {
            method: self.0.method,
            base_path: self.0.base_path,
            path: self.0.path,
            auth: self.0.auth,
            host: self.0.host,
            body: Some(body),
            content_type: self.0.content_type,
            extra_headers: self.0.extra_headers,
        })
    }

    fn host(mut self, host: &'a str) -> Self {
        self.0.host.replace(host);
        self
    }

    fn content_type(mut self, content_type: ContentType) -> Self {
        self.0.content_type.replace(content_type);
        self
    }

    fn basic_auth(mut self, username: &'a str, password: &'a str) -> Self {
        self.0.auth.replace(Auth::Basic { username, password });
        self
    }

    fn build(self) -> Request<'a, B> {
        self.0
    }
}

#[derive(Debug, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
/// HTTP request methods
pub enum Method {
    /// GET
    GET,
    /// PUT
    PUT,
    /// POST
    POST,
    /// DELETE
    DELETE,
    /// HEAD
    HEAD,
}

impl Method {
    /// str representation of method
    pub fn as_str(&self) -> &str {
        match self {
            Method::POST => "POST",
            Method::PUT => "PUT",
            Method::GET => "GET",
            Method::DELETE => "DELETE",
            Method::HEAD => "HEAD",
        }
    }
}

async fn write_str<C: Write>(c: &mut C, data: &str) -> Result<(), Error> {
    c.write_all(data.as_bytes()).await.map_err(to_errorkind)?;
    Ok(())
}

async fn write_header<C: Write>(c: &mut C, key: &str, value: &str) -> Result<(), Error> {
    write_str(c, key).await?;
    write_str(c, ": ").await?;
    write_str(c, value).await?;
    write_str(c, "\r\n").await?;
    Ok(())
}

/// The request body
#[allow(clippy::len_without_is_empty)]
pub trait RequestBody {
    /// Get the length of the body if known
    ///
    /// If the length is known, then it will be written in the `Content-Length` header,
    /// chunked encoding will be used otherwise.
    fn len(&self) -> Option<usize> {
        None
    }

    /// Write the body to the provided writer
    async fn write<W: Write>(&self, writer: &mut W) -> Result<(), W::Error>;
}

impl RequestBody for () {
    fn len(&self) -> Option<usize> {
        None
    }

    async fn write<W: Write>(&self, _writer: &mut W) -> Result<(), W::Error> {
        Ok(())
    }
}

impl RequestBody for &[u8] {
    fn len(&self) -> Option<usize> {
        Some(<[u8]>::len(self))
    }

    async fn write<W: Write>(&self, writer: &mut W) -> Result<(), W::Error> {
        writer.write_all(self).await
    }
}

impl<T> RequestBody for Option<T>
where
    T: RequestBody,
{
    fn len(&self) -> Option<usize> {
        self.as_ref().map(|inner| inner.len()).unwrap_or_default()
    }

    async fn write<W: Write>(&self, writer: &mut W) -> Result<(), W::Error> {
        if let Some(inner) = self.as_ref() {
            inner.write(writer).await
        } else {
            Ok(())
        }
    }
}

pub struct FixedBodyWriter<'a, C: Write>(&'a mut C, usize);

impl<C> ErrorType for FixedBodyWriter<'_, C>
where
    C: Write,
{
    type Error = C::Error;
}

impl<C> Write for FixedBodyWriter<'_, C>
where
    C: Write,
{
    async fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
        let written = self.0.write(buf).await?;
        self.1 += written;
        Ok(written)
    }

    async fn write_all(&mut self, buf: &[u8]) -> Result<(), Self::Error> {
        self.0.write_all(buf).await?;
        self.1 += buf.len();
        Ok(())
    }

    async fn flush(&mut self) -> Result<(), Self::Error> {
        self.0.flush().await
    }
}

pub struct ChunkedBodyWriter<'a, C: Write>(&'a mut C, usize);

impl<C> ErrorType for ChunkedBodyWriter<'_, C>
where
    C: Write,
{
    type Error = embedded_io::ErrorKind;
}

fn to_errorkind<E: embedded_io::Error>(e: E) -> embedded_io::ErrorKind {
    e.kind()
}

impl<C> Write for ChunkedBodyWriter<'_, C>
where
    C: Write,
{
    async fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
        self.write_all(buf).await.map_err(to_errorkind)?;
        Ok(buf.len())
    }

    async fn write_all(&mut self, buf: &[u8]) -> Result<(), Self::Error> {
        // Write chunk header
        let len = buf.len();
        let mut hex = [0; 2 * size_of::<usize>()];
        hex::encode_to_slice(len.to_be_bytes(), &mut hex).unwrap();
        let leading_zeros = hex.iter().position(|x| *x != b'0').unwrap_or_default();
        let (_, hex) = hex.split_at(leading_zeros);
        self.0.write_all(hex).await.map_err(to_errorkind)?;
        self.0.write_all(b"\r\n").await.map_err(to_errorkind)?;

        // Write chunk
        self.0.write_all(buf).await.map_err(to_errorkind)?;
        self.1 += len;

        // Write newline
        self.0.write_all(b"\r\n").await.map_err(to_errorkind)?;
        Ok(())
    }

    async fn flush(&mut self) -> Result<(), Self::Error> {
        self.0.flush().await.map_err(|e| e.kind())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn basic_auth() {
        let mut buffer: Vec<u8> = Vec::new();
        Request::new(Method::GET, "/")
            .basic_auth("username", "password")
            .build()
            .write(&mut buffer)
            .await
            .unwrap();

        assert_eq!(
            b"GET / HTTP/1.1\r\nAuthorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=\r\n\r\n",
            buffer.as_slice()
        );
    }

    #[tokio::test]
    async fn with_empty_body() {
        let mut buffer = Vec::new();
        Request::new(Method::POST, "/")
            .body([].as_slice())
            .build()
            .write(&mut buffer)
            .await
            .unwrap();

        assert_eq!(b"POST / HTTP/1.1\r\nContent-Length: 0\r\n\r\n", buffer.as_slice());
    }

    #[tokio::test]
    async fn with_known_body() {
        let mut buffer = Vec::new();
        Request::new(Method::POST, "/")
            .body(b"BODY".as_slice())
            .build()
            .write(&mut buffer)
            .await
            .unwrap();

        assert_eq!(b"POST / HTTP/1.1\r\nContent-Length: 4\r\n\r\nBODY", buffer.as_slice());
    }

    struct ChunkedBody<'a>(&'a [u8]);

    impl RequestBody for ChunkedBody<'_> {
        fn len(&self) -> Option<usize> {
            None // Unknown length: triggers chunked body
        }

        async fn write<W: Write>(&self, writer: &mut W) -> Result<(), W::Error> {
            writer.write_all(self.0).await
        }
    }

    #[tokio::test]
    async fn with_unknown_body() {
        let mut buffer = Vec::new();

        Request::new(Method::POST, "/")
            .body(ChunkedBody(b"BODY".as_slice()))
            .build()
            .write(&mut buffer)
            .await
            .unwrap();

        assert_eq!(
            b"POST / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n4\r\nBODY\r\n0\r\n\r\n",
            buffer.as_slice()
        );
    }
}