aloha 0.1.0

Low-level Rust implementation of Oblivious HTTP
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
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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
// Copyright (c) 2022-2023 Cloudflare, Inc.
// Licensed under the Apache-2.0 license found in the LICENSE file or
// at http://www.apache.org/licenses/LICENSE-2.0

use bytes::BufMut;

use super::*;

/// Entrypoint to build a bHTTP message.
pub struct Builder<B> {
    buf: B,
    framing: Framing,
}

impl<B: BufMut> Builder<B> {
    /// Create a new builder.
    pub fn new(buf: B, framing: Framing) -> Self {
        Self { buf, framing }
    }

    /// Push request control data.
    pub fn push_ctrl(
        mut self,
        mut method: &[u8],
        mut scheme: &[u8],
        mut authority: &[u8],
        mut path: &[u8],
    ) -> Result<HeaderBuilder<B>> {
        if !self.framing.is_request() {
            return Err(Error::UnexpectedFraming);
        }

        if !self.buf.has_remaining_mut() {
            return Err(Error::ShortBuf);
        }
        self.buf.put_u8(self.framing as u8);

        compose_len_bytes(&mut self.buf, &mut method)?;
        compose_len_bytes(&mut self.buf, &mut scheme)?;
        compose_len_bytes(&mut self.buf, &mut authority)?;
        compose_len_bytes(&mut self.buf, &mut path)?;

        Ok(HeaderBuilder {
            buf: self.buf,
            framing: self.framing,
            appending: false,
        })
    }

    /// Push informational/final response contral data.
    pub fn push_status(mut self, status: usize) -> Result<InfoBuilder<B>> {
        if self.framing.is_request() {
            return Err(Error::UnexpectedFraming);
        }

        if !self.buf.has_remaining_mut() {
            return Err(Error::ShortBuf);
        }
        self.buf.put_u8(self.framing as u8);

        VarInt::try_from(status)?.compose(&mut self.buf)?;

        Ok(InfoBuilder {
            buf: self.buf,
            framing: self.framing,
            is_final: is_final_ctrl(status),
            appending: false,
        })
    }
}

/// Build response informational/final control data.
pub struct RCtrlBuilder<B> {
    buf: B,
    framing: Framing,
}

impl<B: BufMut> RCtrlBuilder<B> {
    /// Push informational/final response contral data.
    pub fn push_status(mut self, status: usize) -> Result<InfoBuilder<B>> {
        VarInt::try_from(status)?.compose(&mut self.buf)?;
        Ok(InfoBuilder {
            buf: self.buf,
            framing: self.framing,
            is_final: is_final_ctrl(status),
            appending: false,
        })
    }
}

/// Build informational response fields.
pub struct InfoBuilder<B> {
    buf: B,
    framing: Framing,
    is_final: bool,
    appending: bool,
}

impl<B: BufMut> InfoBuilder<B> {
    /// Push all the informational fields.
    pub fn push_fields(mut self, fields: &[(&[u8], &[u8])]) -> Result<RCtrlBuilder<B>> {
        if self.is_final {
            return Err(Error::UnexpectedBuildState);
        }

        push_fields(&mut self.buf, self.framing, fields)?;
        Ok(RCtrlBuilder {
            buf: self.buf,
            framing: self.framing,
        })
    }

    /// Append a single field line in indeterminate length mode.
    pub fn append_field(mut self, field: (&[u8], &[u8])) -> Result<Self> {
        if self.framing.known_len() {
            return Err(Error::UnexpectedFraming);
        }

        if self.is_final {
            return Err(Error::UnexpectedBuildState);
        }

        let (mut name, mut value) = field;
        if name.is_empty() {
            return Err(Error::InvalidInput);
        }
        compose_len_bytes(&mut self.buf, &mut name)?;
        compose_len_bytes(&mut self.buf, &mut value)?;
        self.appending = true;
        Ok(self)
    }

    /// Finish appending field line.
    pub fn done(mut self) -> Result<RCtrlBuilder<B>> {
        if self.framing.known_len() {
            return Err(Error::UnexpectedFraming);
        }

        if self.is_final || !self.appending {
            return Err(Error::UnexpectedBuildState);
        }

        if !self.buf.has_remaining_mut() {
            return Err(Error::ShortBuf);
        }
        self.buf.put_u8(CONTENT_TERMINATOR);

        Ok(RCtrlBuilder {
            buf: self.buf,
            framing: self.framing,
        })
    }

    /// Move to next builder in chain.
    pub fn next(self) -> Result<HeaderBuilder<B>> {
        if !self.is_final {
            return Err(Error::UnexpectedBuildState);
        }

        Ok(HeaderBuilder {
            buf: self.buf,
            framing: self.framing,
            appending: false,
        })
    }
}

/// Build headers.
pub struct HeaderBuilder<B> {
    buf: B,
    framing: Framing,
    appending: bool,
}

impl<B: BufMut> HeaderBuilder<B> {
    /// Push all the headers.
    pub fn push_headers(mut self, fields: &[(&[u8], &[u8])]) -> Result<ContentBuilder<B>> {
        push_fields(&mut self.buf, self.framing, fields)?;
        Ok(ContentBuilder {
            buf: self.buf,
            framing: self.framing,
            appending: false,
        })
    }

    /// Append a single header in indeterminate length mode.
    pub fn append_header(mut self, field: (&[u8], &[u8])) -> Result<Self> {
        if self.framing.known_len() {
            return Err(Error::UnexpectedFraming);
        }

        let (mut name, mut value) = field;
        if name.is_empty() {
            return Err(Error::InvalidInput);
        }
        compose_len_bytes(&mut self.buf, &mut name)?;
        compose_len_bytes(&mut self.buf, &mut value)?;
        self.appending = true;
        Ok(self)
    }

    /// Move to next builder in chain.
    pub fn next(mut self) -> Result<ContentBuilder<B>> {
        if !self.appending {
            return Err(Error::UnexpectedBuildState);
        }

        if !self.buf.has_remaining_mut() {
            return Err(Error::ShortBuf);
        }
        self.buf.put_u8(CONTENT_TERMINATOR);
        Ok(ContentBuilder {
            buf: self.buf,
            framing: self.framing,
            appending: false,
        })
    }
}

/// Build content.
pub struct ContentBuilder<B> {
    buf: B,
    framing: Framing,
    appending: bool,
}

impl<B: BufMut> ContentBuilder<B> {
    /// Push content at once.
    pub fn push_content(mut self, mut content: &[u8]) -> Result<TailerBuilder<B>> {
        let empty = content.is_empty();
        compose_len_bytes(&mut self.buf, &mut content)?;

        // Content has already been terminated if empty.
        if !self.framing.known_len() && !empty {
            if !self.buf.has_remaining_mut() {
                return Err(Error::ShortBuf);
            }
            self.buf.put_u8(CONTENT_TERMINATOR);
        }

        Ok(TailerBuilder {
            buf: self.buf,
            framing: self.framing,
            appending: false,
        })
    }

    /// Append a content chunk in indeterminate length mode.
    pub fn append_chunk(mut self, mut chunk: &[u8]) -> Result<Self> {
        if chunk.is_empty() {
            return Err(Error::InvalidInput);
        }

        compose_len_bytes(&mut self.buf, &mut chunk)?;
        self.appending = true;
        Ok(self)
    }

    /// Move to next builder in chain.
    pub fn next(mut self) -> Result<TailerBuilder<B>> {
        if !self.buf.has_remaining_mut() {
            return Err(Error::ShortBuf);
        }
        self.buf.put_u8(CONTENT_TERMINATOR);

        Ok(TailerBuilder {
            buf: self.buf,
            framing: self.framing,
            appending: false,
        })
    }
}

/// Build tailers.
pub struct TailerBuilder<B> {
    buf: B,
    framing: Framing,
    appending: bool,
}

impl<B: BufMut> TailerBuilder<B> {
    /// Push all tailers at once.
    pub fn push_tailers(mut self, fields: &[(&[u8], &[u8])]) -> Result<PaddingBuilder<B>> {
        push_fields(&mut self.buf, self.framing, fields)?;
        Ok(PaddingBuilder { buf: self.buf })
    }

    /// Append a single tailer in indeterminate length mode.
    pub fn append_tailer(mut self, field: (&[u8], &[u8])) -> Result<Self> {
        if self.framing.known_len() {
            return Err(Error::UnexpectedFraming);
        }

        let (mut name, mut value) = field;
        if name.is_empty() {
            return Err(Error::InvalidInput);
        }
        compose_len_bytes(&mut self.buf, &mut name)?;
        compose_len_bytes(&mut self.buf, &mut value)?;
        self.appending = true;
        Ok(self)
    }

    /// Move to next builder in chain.
    pub fn next(mut self) -> Result<PaddingBuilder<B>> {
        if !self.appending {
            return Err(Error::UnexpectedBuildState);
        }

        if !self.buf.has_remaining_mut() {
            return Err(Error::ShortBuf);
        }
        self.buf.put_u8(CONTENT_TERMINATOR);
        Ok(PaddingBuilder { buf: self.buf })
    }
}

/// Build padding.
pub struct PaddingBuilder<B> {
    buf: B,
}

impl<B: BufMut> PaddingBuilder<B> {
    /// Push n bytes of padding.
    pub fn push_padding(mut self, n: usize) -> Result<()> {
        if self.buf.remaining_mut() < n {
            return Err(Error::ShortBuf);
        }
        self.buf.put_bytes(CONTENT_TERMINATOR, n);
        Ok(())
    }
}

fn push_fields<B: BufMut>(buf: &mut B, framing: Framing, fields: &[(&[u8], &[u8])]) -> Result<()> {
    if framing.known_len() {
        push_fields_with_len(buf, fields)
    } else {
        push_fields_no_len(buf, fields)
    }
}

fn push_fields_with_len<B: BufMut>(buf: &mut B, fields: &[(&[u8], &[u8])]) -> Result<()> {
    let mut len = 0;
    for (name, value) in fields.iter() {
        len += VarInt::try_from(name.len())?.size();
        len += name.len();
        len += VarInt::try_from(value.len())?.size();
        len += value.len();
    }

    let n = VarInt::try_from(len)?;
    if buf.remaining_mut() < n.size() + len {
        return Err(Error::ShortBuf);
    }

    n.compose(buf)?;

    for (mut name, mut value) in fields.iter() {
        compose_len_bytes(buf, &mut name)?;
        compose_len_bytes(buf, &mut value)?;
    }

    Ok(())
}

fn push_fields_no_len<B: BufMut>(buf: &mut B, fields: &[(&[u8], &[u8])]) -> Result<()> {
    for (mut name, mut value) in fields.iter() {
        if name.is_empty() {
            return Err(Error::InvalidInput);
        }
        compose_len_bytes(buf, &mut name)?;
        compose_len_bytes(buf, &mut value)?;
    }

    if !buf.has_remaining_mut() {
        return Err(Error::ShortBuf);
    }
    buf.put_u8(CONTENT_TERMINATOR);

    Ok(())
}

// If data is empty, 1 byte of 0 will be pushed.
fn compose_len_bytes<B: BufMut, T: Buf>(buf: &mut B, data: &mut T) -> Result<()> {
    let len = data.remaining();
    let n = VarInt::try_from(len)?;

    if buf.remaining_mut() < n.size() + len {
        return Err(Error::ShortBuf);
    }

    n.compose(buf)?;
    buf.put(data);
    Ok(())
}

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

    #[test]
    fn build_known_len_req() {
        let mut buf = Vec::new();
        Builder::new(&mut buf, Framing::KnownLenReq)
            .push_ctrl(b"GET", b"https", b"", b"/hello.txt")
            .unwrap()
            .push_headers(&[
                (
                    &b"user-agent"[..],
                    &b"curl/7.16.3 libcurl/7.16.3 OpenSSL/0.9.7l zlib/1.2.3"[..],
                ),
                (&b"host"[..], &b"www.example.com"[..]),
                (&b"accept-language"[..], &b"en, mi"[..]),
            ])
            .unwrap()
            .push_content(&[])
            .unwrap()
            .push_tailers(&[])
            .unwrap();
        assert_eq!(EXAMPLE_KNOWN_LEN_REQ2, buf);
    }

    #[test]
    fn build_ind_len_req() {
        let mut buf = Vec::new();
        Builder::new(&mut buf, Framing::IndLenReq)
            .push_ctrl(b"GET", b"https", b"", b"/hello.txt")
            .unwrap()
            .push_headers(&[
                (
                    &b"user-agent"[..],
                    &b"curl/7.16.3 libcurl/7.16.3 OpenSSL/0.9.7l zlib/1.2.3"[..],
                ),
                (&b"host"[..], &b"www.example.com"[..]),
                (&b"accept-language"[..], &b"en, mi"[..]),
            ])
            .unwrap()
            .push_content(&[])
            .unwrap()
            .push_tailers(&[])
            .unwrap()
            .push_padding(10)
            .unwrap();
        assert_eq!(EXAMPLE_IND_LEN_REQ1, buf);
    }

    #[test]
    fn build_known_len_res() {
        let mut buf = Vec::new();
        Builder::new(&mut buf, Framing::KnownLenRes)
            .push_status(200)
            .unwrap()
            .next()
            .unwrap()
            .push_headers(&[])
            .unwrap()
            .push_content("This content contains CRLF.\r\n".as_bytes())
            .unwrap()
            .push_tailers(&[("trailer".as_bytes(), "text".as_bytes())])
            .unwrap();
        assert_eq!(EXAMPLE_KNOWN_LEN_RES1, buf);
    }

    #[test]
    fn build_ind_len_res() {
        let mut buf = Vec::new();
        Builder::new(&mut buf, Framing::IndLenRes)
            .push_status(102)
            .unwrap()
            .push_fields(&[("running".as_bytes(), r#""sleep 15""#.as_bytes())])
            .unwrap()
            .push_status(103)
            .unwrap()
            .push_fields(&[
                (
                    "link".as_bytes(),
                    r#"</style.css>; rel=preload; as=style"#.as_bytes(),
                ),
                (
                    "link".as_bytes(),
                    r#"</script.js>; rel=preload; as=script"#.as_bytes(),
                ),
            ])
            .unwrap()
            .push_status(200)
            .unwrap()
            .next()
            .unwrap()
            .push_headers(&[
                (
                    "date".as_bytes(),
                    r#"Mon, 27 Jul 2009 12:28:53 GMT"#.as_bytes(),
                ),
                ("server".as_bytes(), "Apache".as_bytes()),
                (
                    "last-modified".as_bytes(),
                    "Wed, 22 Jul 2009 19:15:56 GMT".as_bytes(),
                ),
                ("etag".as_bytes(), r#""34aa387-d-1568eb00""#.as_bytes()),
                ("accept-ranges".as_bytes(), "bytes".as_bytes()),
                ("content-length".as_bytes(), "51".as_bytes()),
                ("vary".as_bytes(), "Accept-Encoding".as_bytes()),
                ("content-type".as_bytes(), "text/plain".as_bytes()),
            ])
            .unwrap()
            .push_content("Hello World! My content includes a trailing CRLF.\r\n".as_bytes())
            .unwrap()
            .push_tailers(&[])
            .unwrap();

        assert_eq!(EXAMPLE_IND_LEN_RES1, &buf);
    }
}