smb-server 0.9.1

SMB2/3 file-sharing server library with pluggable storage backends.
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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
//! CREATE Request/Response (MS-SMB2 §2.2.13 / §2.2.14).
//!
//! `create_contexts` is a chained sequence of `SMB2_CREATE_CONTEXT` records
//! (MS-SMB2 §2.2.13.2). Each record has `Next` (offset to the next entry,
//! relative to the start of *this* entry; 0 marks the last), a name + data
//! pair, and 8-byte alignment.

use binrw::{BinRead, BinWrite, binrw};
use std::io::Cursor;

use crate::proto::error::{ProtoError, ProtoResult};

/// SMB2 FileId - opaque 16 bytes (volatile + persistent).
///
/// MS-SMB2 2.2.14.1. The server sets both halves to the same value, except
/// for durable opens, whose persistent half is random.
#[binrw]
#[brw(little)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct FileId {
    pub persistent: u64,
    pub volatile: u64,
}

impl FileId {
    pub const fn new(persistent: u64, volatile: u64) -> Self {
        Self {
            persistent,
            volatile,
        }
    }

    /// MS-SMB2: the "any" FileId is `0xFFFF...FFFF`.
    pub const fn any() -> Self {
        Self {
            persistent: u64::MAX,
            volatile: u64::MAX,
        }
    }
}

/// Offset of the first byte after the fixed CREATE request fields, counted
/// from the start of the SMB2 header: 64 + 56.
const CREATE_BUFFER_OFFSET: u64 = 0x78;

/// MS-SMB2 §2.2.13 CREATE Request.
///
/// The file `name` (UTF-16LE) and the `create_contexts` blob sit at
/// `name_offset` and `create_contexts_offset`, counted from the start of the
/// SMB2 header, after the fixed fields. `parse` reads them from those offsets
/// and fails when a non-empty one starts before the end of the fixed fields or
/// ends past the request. `write_to` writes them back to back after the fixed
/// fields, so the offsets must match that layout.
/// [`CreateContext::parse_chain`] decodes the `create_contexts` blob.
#[binrw]
#[brw(little)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CreateRequest {
    pub structure_size: u16,
    pub security_flags: u8,
    pub requested_oplock_level: u8,
    pub impersonation_level: u32,
    pub smb_create_flags: u64,
    pub reserved: u64,
    pub desired_access: u32,
    pub file_attributes: u32,
    pub share_access: u32,
    pub create_disposition: u32,
    pub create_options: u32,
    pub name_offset: u16,
    pub name_length: u16,
    pub create_contexts_offset: u32,
    pub create_contexts_length: u32,
    /// UTF-16LE filename.
    #[br(parse_with = super::read_buf_at, args(
        name_offset.into(),
        name_length.into(),
        CREATE_BUFFER_OFFSET,
    ))]
    pub name: Vec<u8>,
    /// Raw create-contexts chain bytes; parse with
    /// [`CreateContext::parse_chain`].
    #[br(parse_with = super::read_buf_at, args(
        create_contexts_offset.into(),
        create_contexts_length as usize,
        CREATE_BUFFER_OFFSET,
    ))]
    pub create_contexts: Vec<u8>,
}

impl CreateRequest {
    /// Decode the UTF-16LE filename.
    pub fn name_str(&self) -> Option<String> {
        if !self.name.len().is_multiple_of(2) {
            return None;
        }
        let units: Vec<u16> = self
            .name
            .chunks_exact(2)
            .map(|c| u16::from_le_bytes([c[0], c[1]]))
            .collect();
        Some(String::from_utf16_lossy(&units))
    }

    pub fn parse(buf: &[u8]) -> ProtoResult<Self> {
        Ok(Self::read(&mut Cursor::new(buf))?)
    }
    pub fn write_to(&self, out: &mut Vec<u8>) -> ProtoResult<()> {
        let mut c = Cursor::new(Vec::new());
        BinWrite::write(self, &mut c)?;
        out.extend_from_slice(&c.into_inner());
        Ok(())
    }
}

/// MS-SMB2 §2.2.14 CREATE Response.
#[binrw]
#[brw(little)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CreateResponse {
    pub structure_size: u16,
    pub oplock_level: u8,
    pub flags: u8,
    pub create_action: u32,
    pub creation_time: u64,
    pub last_access_time: u64,
    pub last_write_time: u64,
    pub change_time: u64,
    pub allocation_size: u64,
    pub end_of_file: u64,
    pub file_attributes: u32,
    pub reserved2: u32,
    pub file_id: FileId,
    pub create_contexts_offset: u32,
    pub create_contexts_length: u32,
    #[br(parse_with = super::read_buf, args(create_contexts_length as usize))]
    pub create_contexts: Vec<u8>,
}

impl CreateResponse {
    pub fn parse(buf: &[u8]) -> ProtoResult<Self> {
        Ok(Self::read(&mut Cursor::new(buf))?)
    }
    pub fn write_to(&self, out: &mut Vec<u8>) -> ProtoResult<()> {
        let mut c = Cursor::new(Vec::new());
        BinWrite::write(self, &mut c)?;
        out.extend_from_slice(&c.into_inner());
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// Create contexts (MS-SMB2 §2.2.13.2)
// ---------------------------------------------------------------------------

/// Generic SMB2_CREATE_CONTEXT envelope.
///
/// Per MS-SMB2 §2.2.13.2 each entry has:
/// * `Next` - offset (bytes) from the start of *this* entry to the start of
///   the next entry in the chain, or 0 for the last entry.
/// * `NameOffset`/`NameLength` - name (typically a 4-byte ASCII tag) at an
///   offset relative to the entry start.
/// * `Reserved` - 2 bytes.
/// * `DataOffset`/`DataLength` - payload at an offset relative to the entry
///   start.
///
/// Each entry is held as `name` and `data` byte vectors. The chain reader and
/// writer below handle `Next` and 8-byte alignment between entries.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct CreateContext {
    pub name: Vec<u8>,
    pub data: Vec<u8>,
}

impl CreateContext {
    // Well-known names (MS-SMB2 §2.2.13.2 table). 4-byte ASCII tags.
    pub const NAME_EXTA: &'static [u8; 4] = b"ExtA"; // SMB2_CREATE_EA_BUFFER
    pub const NAME_SECD: &'static [u8; 4] = b"SecD"; // SMB2_CREATE_SD_BUFFER
    pub const NAME_DHNQ: &'static [u8; 4] = b"DHnQ"; // DURABLE_HANDLE_REQUEST
    pub const NAME_DHNC: &'static [u8; 4] = b"DHnC"; // DURABLE_HANDLE_RECONNECT
    pub const NAME_ALSI: &'static [u8; 4] = b"AlSi"; // ALLOCATION_SIZE
    pub const NAME_MXAC: &'static [u8; 4] = b"MxAc"; // QUERY_MAXIMAL_ACCESS
    pub const NAME_TWRP: &'static [u8; 4] = b"TWrp"; // TIMEWARP_TOKEN
    pub const NAME_QFID: &'static [u8; 4] = b"QFid"; // QUERY_ON_DISK_ID
    pub const NAME_RQLS: &'static [u8; 4] = b"RqLs"; // REQUEST_LEASE
    pub const NAME_DH2Q: &'static [u8; 4] = b"DH2Q"; // DURABLE_HANDLE_REQUEST_V2
    pub const NAME_DH2C: &'static [u8; 4] = b"DH2C"; // DURABLE_HANDLE_RECONNECT_V2
    pub const NAME_AAPL: &'static [u8; 4] = b"AAPL"; // Apple's SMB2 extensions

    /// Parse a chain of create-contexts from the raw chain bytes.
    ///
    /// The chain is empty if `chain.is_empty()`. Otherwise `Next` offsets are
    /// followed until one is zero. Each context spans from its start to the
    /// next context, or to the end of the chain for the last one. A context
    /// shorter than its 16-byte header, a name shorter than 4 bytes, or a
    /// name or data outside the context is malformed.
    pub fn parse_chain(chain: &[u8]) -> ProtoResult<Vec<CreateContext>> {
        let mut out = Vec::new();
        if chain.is_empty() {
            return Ok(out);
        }
        let mut cursor_off = 0usize;
        loop {
            let rest = chain
                .get(cursor_off..)
                .ok_or(ProtoError::Malformed("create context out of range"))?;
            if rest.len() < 16 {
                return Err(ProtoError::Malformed("create context too short"));
            }
            let next = u32::from_le_bytes([rest[0], rest[1], rest[2], rest[3]]) as usize;
            let entry = match next {
                0 => rest,
                16.. => rest
                    .get(..next)
                    .ok_or(ProtoError::Malformed("create context next out of range"))?,
                _ => return Err(ProtoError::Malformed("create context too short")),
            };
            let name_offset = u16::from_le_bytes([entry[4], entry[5]]) as usize;
            let name_length = u16::from_le_bytes([entry[6], entry[7]]) as usize;
            // entry[8..10] = reserved
            let data_offset = u16::from_le_bytes([entry[10], entry[11]]) as usize;
            let data_length =
                u32::from_le_bytes([entry[12], entry[13], entry[14], entry[15]]) as usize;
            if name_length < 4 {
                return Err(ProtoError::Malformed("create context name too short"));
            }

            let name = entry
                .get(name_offset..name_offset + name_length)
                .ok_or(ProtoError::Malformed("create context name out of range"))?
                .to_vec();
            let data = if data_length == 0 {
                Vec::new()
            } else {
                data_offset
                    .checked_add(data_length)
                    .and_then(|end| entry.get(data_offset..end))
                    .ok_or(ProtoError::Malformed("create context data out of range"))?
                    .to_vec()
            };
            out.push(CreateContext { name, data });

            if next == 0 {
                break;
            }
            cursor_off = cursor_off
                .checked_add(next)
                .ok_or(ProtoError::Malformed("create context next overflow"))?;
        }
        Ok(out)
    }

    /// Encode a chain of create-contexts into `out`. Inserts `Next` offsets
    /// and 8-byte alignment padding between entries.
    pub fn encode_chain(list: &[CreateContext], out: &mut Vec<u8>) -> ProtoResult<()> {
        if list.is_empty() {
            return Ok(());
        }
        // We build the chain in a scratch buffer, then copy. Each entry is:
        //   16-byte header + name + (pad to 8) + data + (pad to 8 if not last)
        // The `Next` of every entry except the last is the size from this
        // entry's start to the next entry's start.
        let mut scratch: Vec<u8> = Vec::new();
        let mut entry_starts: Vec<usize> = Vec::with_capacity(list.len());

        for (i, ctx) in list.iter().enumerate() {
            // Each entry starts 8-byte aligned; the caller places the chain at
            // an 8-aligned offset.
            while !scratch.len().is_multiple_of(8) {
                scratch.push(0);
            }
            entry_starts.push(scratch.len());

            // Reserve 16 bytes for the header; will fill in once we know
            // the actual offsets.
            let header_pos = scratch.len();
            scratch.extend_from_slice(&[0u8; 16]);

            // Name immediately follows the header.
            let name_offset_rel = (scratch.len() - header_pos) as u16;
            scratch.extend_from_slice(&ctx.name);
            // Pad to 8 before data.
            while !(scratch.len() - header_pos).is_multiple_of(8) {
                scratch.push(0);
            }
            let data_offset_rel = (scratch.len() - header_pos) as u16;
            scratch.extend_from_slice(&ctx.data);

            // Now backfill the header bytes (Next is patched after the loop).
            let hdr = &mut scratch[header_pos..header_pos + 16];
            hdr[0..4].copy_from_slice(&0u32.to_le_bytes()); // Next, fixed up below
            hdr[4..6].copy_from_slice(&name_offset_rel.to_le_bytes());
            hdr[6..8].copy_from_slice(&(ctx.name.len() as u16).to_le_bytes());
            hdr[8..10].copy_from_slice(&0u16.to_le_bytes()); // Reserved
            hdr[10..12].copy_from_slice(&data_offset_rel.to_le_bytes());
            hdr[12..16].copy_from_slice(&(ctx.data.len() as u32).to_le_bytes());

            // For non-last, pad the trailing data area to 8 so the next
            // entry starts aligned.
            if i + 1 < list.len() {
                while !scratch.len().is_multiple_of(8) {
                    scratch.push(0);
                }
            }
        }

        // Patch `Next` offsets.
        for i in 0..(entry_starts.len() - 1) {
            let this = entry_starts[i];
            let next = entry_starts[i + 1];
            let delta = (next - this) as u32;
            scratch[this..this + 4].copy_from_slice(&delta.to_le_bytes());
        }
        // Last entry's Next stays 0.

        out.extend_from_slice(&scratch);
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// Helper enums (oplock level, impersonation level)
// ---------------------------------------------------------------------------

/// MS-SMB2 §2.2.13 RequestedOplockLevel / §2.2.14 OplockLevel.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum OplockLevel {
    None = 0x00,
    Ii = 0x01,
    Exclusive = 0x08,
    Batch = 0x09,
    Lease = 0xFF,
}

impl OplockLevel {
    pub fn from_u8(v: u8) -> Option<Self> {
        Some(match v {
            0x00 => Self::None,
            0x01 => Self::Ii,
            0x08 => Self::Exclusive,
            0x09 => Self::Batch,
            0xFF => Self::Lease,
            _ => return None,
        })
    }
}

/// MS-SMB2 §2.2.13 ImpersonationLevel.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u32)]
pub enum ImpersonationLevel {
    Anonymous = 0x0000_0000,
    Identification = 0x0000_0001,
    Impersonation = 0x0000_0002,
    Delegate = 0x0000_0003,
}

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

    fn utf16le(s: &str) -> Vec<u8> {
        s.encode_utf16().flat_map(u16::to_le_bytes).collect()
    }

    #[test]
    fn request_round_trips() {
        let name = utf16le("dir\\file.txt");
        let r = CreateRequest {
            structure_size: 57,
            security_flags: 0,
            requested_oplock_level: 0,
            impersonation_level: ImpersonationLevel::Impersonation as u32,
            smb_create_flags: 0,
            reserved: 0,
            desired_access: 0x0012_0089,
            file_attributes: 0,
            share_access: 0x0000_0007,
            create_disposition: 1,
            create_options: 0x0000_0040,
            name_offset: 0x78,
            name_length: name.len() as u16,
            create_contexts_offset: 0,
            create_contexts_length: 0,
            name,
            create_contexts: vec![],
        };
        let mut buf = Vec::new();
        r.write_to(&mut buf).unwrap();
        let decoded = CreateRequest::parse(&buf).unwrap();
        assert_eq!(decoded, r);
        assert_eq!(decoded.name_str().unwrap(), "dir\\file.txt");
    }

    /// CREATE body with `name` at `name_offset` and `contexts` at
    /// `contexts_offset`, zero-filling any gap after the fixed fields.
    fn body_with_buffers(
        name: &[u8],
        name_offset: u16,
        contexts: &[u8],
        contexts_offset: u32,
    ) -> Vec<u8> {
        let fixed = CreateRequest {
            structure_size: 57,
            security_flags: 0,
            requested_oplock_level: 0,
            impersonation_level: ImpersonationLevel::Impersonation as u32,
            smb_create_flags: 0,
            reserved: 0,
            desired_access: 0x0012_0089,
            file_attributes: 0,
            share_access: 0x0000_0007,
            create_disposition: 1,
            create_options: 0,
            name_offset,
            name_length: name.len() as u16,
            create_contexts_offset: contexts_offset,
            create_contexts_length: contexts.len() as u32,
            name: vec![],
            create_contexts: vec![],
        };
        let mut body = Vec::new();
        fixed.write_to(&mut body).unwrap();
        for (data, offset) in [(name, u32::from(name_offset)), (contexts, contexts_offset)] {
            if data.is_empty() {
                continue;
            }
            let start = offset as usize - 64;
            if body.len() < start + data.len() {
                body.resize(start + data.len(), 0);
            }
            body[start..start + data.len()].copy_from_slice(data);
        }
        body
    }

    #[test]
    fn request_reads_name_and_contexts_at_their_offsets() {
        let name = utf16le("dir\\file.txt");
        let ctxs = vec![CreateContext {
            name: CreateContext::NAME_MXAC.to_vec(),
            data: vec![],
        }];
        let mut chain = Vec::new();
        CreateContext::encode_chain(&ctxs, &mut chain).unwrap();
        // Name 8 bytes past the fixed fields, contexts 8-aligned after it.
        let name_offset = 0x80;
        let contexts_offset = (u32::from(name_offset) + name.len() as u32).next_multiple_of(8);
        let body = body_with_buffers(&name, name_offset, &chain, contexts_offset);

        let req = CreateRequest::parse(&body).unwrap();
        assert_eq!(req.name_str().unwrap(), "dir\\file.txt");
        assert_eq!(
            CreateContext::parse_chain(&req.create_contexts).unwrap(),
            ctxs
        );
    }

    #[test]
    fn request_rejects_buffers_outside_the_request() {
        // Byte position of NameOffset in the request body.
        const NAME_OFFSET_FIELD: usize = 44;
        let name = utf16le("a.txt");
        // Inside the fixed fields, past the end.
        for name_offset in [0x70, 0x200] {
            let mut body = body_with_buffers(&name, 0x78, &[], 0x78);
            body[NAME_OFFSET_FIELD..NAME_OFFSET_FIELD + 2]
                .copy_from_slice(&u16::to_le_bytes(name_offset));
            assert!(
                CreateRequest::parse(&body).is_err(),
                "name offset {name_offset:#x}"
            );
        }
        // Contexts that run past the end of the request.
        let mut body = body_with_buffers(&name, 0x78, &[0; 16], 0x88);
        body.truncate(body.len() - 1);
        assert!(CreateRequest::parse(&body).is_err());
    }

    #[test]
    fn request_accepts_empty_buffers_at_any_offset() {
        let body = body_with_buffers(&[], 0, &[], 0);
        let req = CreateRequest::parse(&body).unwrap();
        assert_eq!(req.name_str().unwrap(), "");
        assert!(req.create_contexts.is_empty());
    }

    #[test]
    fn response_round_trips() {
        let r = CreateResponse {
            structure_size: 89,
            oplock_level: 0,
            flags: 0,
            create_action: 1,
            creation_time: 0x01D9_0000_0000_0000,
            last_access_time: 0x01D9_0000_0000_0000,
            last_write_time: 0x01D9_0000_0000_0000,
            change_time: 0x01D9_0000_0000_0000,
            allocation_size: 0x1000,
            end_of_file: 0x800,
            file_attributes: 0x0020,
            reserved2: 0,
            file_id: FileId::new(0x1234, 0x5678),
            create_contexts_offset: 0,
            create_contexts_length: 0,
            create_contexts: vec![],
        };
        let mut buf = Vec::new();
        r.write_to(&mut buf).unwrap();
        let decoded = CreateResponse::parse(&buf).unwrap();
        assert_eq!(decoded, r);
    }

    #[test]
    fn create_context_chain_round_trips_single() {
        let ctxs = vec![CreateContext {
            name: b"MxAc".to_vec(),
            data: vec![],
        }];
        let mut buf = Vec::new();
        CreateContext::encode_chain(&ctxs, &mut buf).unwrap();
        let decoded = CreateContext::parse_chain(&buf).unwrap();
        assert_eq!(decoded, ctxs);
    }

    #[test]
    fn create_context_chain_round_trips_multi() {
        let ctxs = vec![
            CreateContext {
                name: b"DHnQ".to_vec(),
                data: vec![0u8; 16],
            },
            CreateContext {
                name: b"MxAc".to_vec(),
                data: vec![],
            },
            CreateContext {
                name: b"QFid".to_vec(),
                data: vec![0xAA; 32],
            },
        ];
        let mut buf = Vec::new();
        CreateContext::encode_chain(&ctxs, &mut buf).unwrap();
        let decoded = CreateContext::parse_chain(&buf).unwrap();
        assert_eq!(decoded, ctxs);
    }

    #[test]
    fn create_context_chain_rejects_malformed_entries() {
        let short_name = vec![CreateContext {
            name: b"MxA".to_vec(),
            data: vec![],
        }];
        let mut buf = Vec::new();
        CreateContext::encode_chain(&short_name, &mut buf).unwrap();
        assert!(CreateContext::parse_chain(&buf).is_err());

        let pair = vec![
            CreateContext {
                name: b"QFid".to_vec(),
                data: vec![],
            },
            CreateContext {
                name: b"MxAc".to_vec(),
                data: vec![0; 8],
            },
        ];
        let mut chain = Vec::new();
        CreateContext::encode_chain(&pair, &mut chain).unwrap();
        let next = u32::from_le_bytes(chain[0..4].try_into().unwrap());
        // Data that runs from the first context into the second.
        let mut bad = chain.clone();
        bad[10..12].copy_from_slice(&16u16.to_le_bytes());
        bad[12..16].copy_from_slice(&next.to_le_bytes());
        assert!(CreateContext::parse_chain(&bad).is_err());
        // Next inside the first header, and past the end of the chain.
        for next in [8u32, chain.len() as u32 + 8] {
            let mut bad = chain.clone();
            bad[0..4].copy_from_slice(&next.to_le_bytes());
            assert!(CreateContext::parse_chain(&bad).is_err(), "next {next}");
        }
    }

    #[test]
    fn empty_chain_round_trips() {
        let ctxs: Vec<CreateContext> = vec![];
        let mut buf = Vec::new();
        CreateContext::encode_chain(&ctxs, &mut buf).unwrap();
        assert!(buf.is_empty());
        let decoded = CreateContext::parse_chain(&buf).unwrap();
        assert!(decoded.is_empty());
    }
}