unkernel-rs 0.6.0

Native Rust + Wasmtime host library and CLI for unkernel (Linux 7.x on WebAssembly) — zero Node, zero JSPI, zero KVM
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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
//! Host virtio-vsock transport (`wasm_driver_vsock_*`) and blocking stream API for `kwtty`
//! (`exec`/PTY) and `9P2000.L` mounts.

use std::collections::{HashMap, VecDeque};
use std::io;
use std::sync::{Arc, Condvar, Mutex};
use std::time::{Duration, Instant};

pub const VSOCK_HOST_CID: u64 = 2;
pub const VSOCK_GUEST_CID: u64 = 3;
pub const VSOCK_HEADER_SIZE: usize = 44;

const FIRST_HOST_PORT: u32 = 49152;
const DEFAULT_BUF_ALLOC: u32 = 262_144;

const TYPE_STREAM: u16 = 1;

const OP_REQUEST: u16 = 1;
const OP_RESPONSE: u16 = 2;
const OP_RST: u16 = 3;
const OP_SHUTDOWN: u16 = 4;
const OP_RW: u16 = 5;
const OP_CREDIT_UPDATE: u16 = 6;
const OP_CREDIT_REQUEST: u16 = 7;

const SHUTDOWN_RCV: u32 = 1;
const SHUTDOWN_SEND: u32 = 2;

#[derive(Debug, Clone, Copy)]
pub struct VsockHeader {
    pub src_cid: u64,
    pub dst_cid: u64,
    pub src_port: u32,
    pub dst_port: u32,
    pub len: u32,
    pub pkt_type: u16,
    pub op: u16,
    pub flags: u32,
    pub buf_alloc: u32,
    pub fwd_cnt: u32,
}

impl VsockHeader {
    pub fn decode(pkt: &[u8]) -> Option<Self> {
        if pkt.len() < VSOCK_HEADER_SIZE {
            return None;
        }
        Some(Self {
            src_cid: u64::from_le_bytes(pkt[0..8].try_into().ok()?),
            dst_cid: u64::from_le_bytes(pkt[8..16].try_into().ok()?),
            src_port: u32::from_le_bytes(pkt[16..20].try_into().ok()?),
            dst_port: u32::from_le_bytes(pkt[20..24].try_into().ok()?),
            len: u32::from_le_bytes(pkt[24..28].try_into().ok()?),
            pkt_type: u16::from_le_bytes(pkt[28..30].try_into().ok()?),
            op: u16::from_le_bytes(pkt[30..32].try_into().ok()?),
            flags: u32::from_le_bytes(pkt[32..36].try_into().ok()?),
            buf_alloc: u32::from_le_bytes(pkt[36..40].try_into().ok()?),
            fwd_cnt: u32::from_le_bytes(pkt[40..44].try_into().ok()?),
        })
    }

    pub fn encode(&self, payload: &[u8]) -> Vec<u8> {
        let mut pkt = Vec::with_capacity(VSOCK_HEADER_SIZE + payload.len());
        pkt.extend_from_slice(&self.src_cid.to_le_bytes());
        pkt.extend_from_slice(&self.dst_cid.to_le_bytes());
        pkt.extend_from_slice(&self.src_port.to_le_bytes());
        pkt.extend_from_slice(&self.dst_port.to_le_bytes());
        pkt.extend_from_slice(&(payload.len() as u32).to_le_bytes());
        pkt.extend_from_slice(&self.pkt_type.to_le_bytes());
        pkt.extend_from_slice(&self.op.to_le_bytes());
        pkt.extend_from_slice(&self.flags.to_le_bytes());
        pkt.extend_from_slice(&self.buf_alloc.to_le_bytes());
        pkt.extend_from_slice(&self.fwd_cnt.to_le_bytes());
        pkt.extend_from_slice(payload);
        pkt
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ConnState {
    Connecting,
    Established,
    Closed,
}

struct ConnInner {
    state: ConnState,
    rx_buf: VecDeque<u8>,
    rx_cnt: u32,
    fwd_cnt: u32,
    sent_fwd: u32,
    peer_buf_alloc: u32,
    peer_fwd_cnt: u32,
    tx_cnt: u32,
    peer_shut_send: bool,
    peer_shut_rcv: bool,
    shut_sent: u32,
    error: Option<io::ErrorKind>,
}

struct ConnHandle {
    local_port: u32,
    remote_port: u32,
    inner: Mutex<ConnInner>,
    cv: Condvar,
}

impl ConnHandle {
    fn new(local_port: u32, remote_port: u32, state: ConnState) -> Self {
        Self {
            local_port,
            remote_port,
            inner: Mutex::new(ConnInner {
                state,
                rx_buf: VecDeque::new(),
                rx_cnt: 0,
                fwd_cnt: 0,
                sent_fwd: 0,
                peer_buf_alloc: 0,
                peer_fwd_cnt: 0,
                tx_cnt: 0,
                peer_shut_send: false,
                peer_shut_rcv: false,
                shut_sent: 0,
                error: None,
            }),
            cv: Condvar::new(),
        }
    }

    fn peer_credit(c: &ConnInner) -> u32 {
        c.peer_buf_alloc
            .saturating_sub(c.tx_cnt.wrapping_sub(c.peer_fwd_cnt))
    }
}

/// Callback invoked by `VsockHost` whenever a packet is queued for the guest (raises IRQ_VSOCK).
type RaiseIrqFn = Arc<dyn Fn() + Send + Sync>;
type ListenerHandler = Arc<dyn Fn(VsockStream) + Send + Sync>;

struct HostState {
    guest_cid: u64,
    max_payload: usize,
    probed: bool,
    closed: bool,
    next_port: u32,
    to_guest: VecDeque<Vec<u8>>,
    conns: HashMap<(u32, u32), Arc<ConnHandle>>,
    listeners: HashMap<u32, ListenerHandler>,
}

/// Host-side virtio-vsock multiplexer bridged to `wasm_driver_vsock_*`.
pub struct VsockHost {
    state: Mutex<HostState>,
    raise_irq: RaiseIrqFn,
}

impl VsockHost {
    pub fn new(raise_irq: RaiseIrqFn) -> Arc<Self> {
        Arc::new(Self {
            state: Mutex::new(HostState {
                guest_cid: VSOCK_GUEST_CID,
                max_payload: 16384,
                probed: false,
                closed: false,
                next_port: FIRST_HOST_PORT,
                to_guest: VecDeque::new(),
                conns: HashMap::new(),
                listeners: HashMap::new(),
            }),
            raise_irq,
        })
    }

    /// Called from `wasm_driver_vsock_init(guest_cid, rx_max)`.
    pub fn driver_init(&self, guest_cid: u32, rx_max: u32) -> i32 {
        let mut st = self.state.lock().unwrap();
        st.probed = true;
        st.guest_cid = guest_cid as u64;
        if (rx_max as usize) > VSOCK_HEADER_SIZE {
            st.max_payload = ((rx_max as usize) - VSOCK_HEADER_SIZE).min(65536);
        }
        0
    }

    /// Called from `wasm_driver_vsock_rx_len()`.
    pub fn driver_rx_len(&self) -> i32 {
        let st = self.state.lock().unwrap();
        st.to_guest.front().map(|p| p.len() as i32).unwrap_or(0)
    }

    /// Called from `wasm_driver_vsock_recv()`.
    pub fn driver_recv(&self) -> Option<Vec<u8>> {
        let mut st = self.state.lock().unwrap();
        st.to_guest.pop_front()
    }

    /// Called from `wasm_driver_vsock_send(pkt)` when the guest transmits a packet to the host.
    pub fn driver_send(self: &Arc<Self>, pkt: &[u8]) -> i32 {
        let Some(h) = VsockHeader::decode(pkt) else {
            return 0;
        };
        if h.dst_cid != VSOCK_HOST_CID || (h.len as usize) != pkt.len() - VSOCK_HEADER_SIZE {
            return 0;
        }
        if h.pkt_type != TYPE_STREAM {
            self.send_rst(h.src_cid, h.dst_port, h.src_port, h.pkt_type);
            return 0;
        }

        let key = (h.dst_port, h.src_port);
        let existing = { self.state.lock().unwrap().conns.get(&key).cloned() };

        if let Some(conn) = existing {
            if h.op == OP_REQUEST {
                self.reset_conn(&conn);
            } else {
                self.handle_conn_packet(&conn, h, &pkt[VSOCK_HEADER_SIZE..]);
            }
            return 0;
        }

        if h.op != OP_REQUEST {
            if h.op != OP_RST {
                self.send_rst(h.src_cid, h.dst_port, h.src_port, h.pkt_type);
            }
            return 0;
        }

        // Incoming guest connection to a host listener (e.g. port 564 for 9p)
        let listener = {
            self.state
                .lock()
                .unwrap()
                .listeners
                .get(&h.dst_port)
                .cloned()
        };
        let Some(handler) = listener else {
            self.send_rst(h.src_cid, h.dst_port, h.src_port, h.pkt_type);
            return 0;
        };

        let conn = Arc::new(ConnHandle::new(
            h.dst_port,
            h.src_port,
            ConnState::Established,
        ));
        {
            let mut c = conn.inner.lock().unwrap();
            c.peer_buf_alloc = h.buf_alloc;
            c.peer_fwd_cnt = h.fwd_cnt;
        }
        {
            let mut st = self.state.lock().unwrap();
            if st.closed {
                return 0;
            }
            st.conns.insert(key, conn.clone());
        }
        self.send_conn_packet(&conn, OP_RESPONSE, 0, &[]);

        let stream = VsockStream {
            host: self.clone(),
            conn,
        };
        std::thread::Builder::new()
            .name(format!("vsock-accept-{}", h.dst_port))
            .spawn(move || handler(stream))
            .ok();
        0
    }

    /// Register a host listener on `port` (e.g. `564` for 9P2000.L).
    pub fn listen<F>(&self, port: u32, handler: F)
    where
        F: Fn(VsockStream) + Send + Sync + 'static,
    {
        self.state
            .lock()
            .unwrap()
            .listeners
            .insert(port, Arc::new(handler));
    }

    /// Open a host-initiated stream connection to guest `remote_port` (e.g. `1022` for `kwtty`).
    pub fn connect(
        self: &Arc<Self>,
        remote_port: u32,
        timeout: Duration,
    ) -> io::Result<VsockStream> {
        let conn = {
            let mut st = self.state.lock().unwrap();
            if st.closed {
                return Err(io::Error::new(
                    io::ErrorKind::ConnectionAborted,
                    "vsock closed",
                ));
            }
            let mut local = st.next_port;
            while st.listeners.contains_key(&local) || st.conns.contains_key(&(local, remote_port))
            {
                local = if local >= u32::MAX - 1 {
                    FIRST_HOST_PORT
                } else {
                    local + 1
                };
            }
            st.next_port = if local >= u32::MAX - 1 {
                FIRST_HOST_PORT
            } else {
                local + 1
            };
            let c = Arc::new(ConnHandle::new(local, remote_port, ConnState::Connecting));
            st.conns.insert((local, remote_port), c.clone());
            c
        };

        self.send_conn_packet(&conn, OP_REQUEST, 0, &[]);

        let deadline = Instant::now() + timeout;
        let mut c = conn.inner.lock().unwrap();
        while c.state == ConnState::Connecting {
            let now = Instant::now();
            if now >= deadline {
                drop(c);
                self.reset_conn(&conn);
                return Err(io::Error::new(
                    io::ErrorKind::TimedOut,
                    format!("vsock connect to port {remote_port} timed out"),
                ));
            }
            let (guard, _) = conn.cv.wait_timeout(c, deadline - now).unwrap();
            c = guard;
        }
        if c.state == ConnState::Established {
            drop(c);
            Ok(VsockStream {
                host: self.clone(),
                conn,
            })
        } else {
            let kind = c.error.unwrap_or(io::ErrorKind::ConnectionRefused);
            Err(io::Error::new(
                kind,
                format!("vsock connect to port {remote_port} refused"),
            ))
        }
    }

    /// Shut down all active vsock connections and wake any blocked readers/writers.
    pub fn shutdown(&self) {
        let conns: Vec<Arc<ConnHandle>> = {
            let mut st = self.state.lock().unwrap();
            st.closed = true;
            st.to_guest.clear();
            st.listeners.clear();
            st.conns.drain().map(|(_, c)| c).collect()
        };
        for conn in conns {
            let mut c = conn.inner.lock().unwrap();
            c.state = ConnState::Closed;
            c.error.get_or_insert(io::ErrorKind::ConnectionAborted);
            conn.cv.notify_all();
        }
    }

    fn queue_to_guest(&self, pkt: Vec<u8>) {
        {
            let mut st = self.state.lock().unwrap();
            if st.closed {
                return;
            }
            st.to_guest.push_back(pkt);
        }
        (self.raise_irq)();
    }

    fn send_rst(&self, dst_cid: u64, src_port: u32, dst_port: u32, pkt_type: u16) {
        let hdr = VsockHeader {
            src_cid: VSOCK_HOST_CID,
            dst_cid,
            src_port,
            dst_port,
            len: 0,
            pkt_type,
            op: OP_RST,
            flags: 0,
            buf_alloc: 0,
            fwd_cnt: 0,
        };
        self.queue_to_guest(hdr.encode(&[]));
    }

    fn send_conn_packet(&self, conn: &ConnHandle, op: u16, flags: u32, payload: &[u8]) {
        let fwd_cnt = {
            let mut c = conn.inner.lock().unwrap();
            c.sent_fwd = c.fwd_cnt;
            c.fwd_cnt
        };
        let guest_cid = self.state.lock().unwrap().guest_cid;
        let hdr = VsockHeader {
            src_cid: VSOCK_HOST_CID,
            dst_cid: guest_cid,
            src_port: conn.local_port,
            dst_port: conn.remote_port,
            len: payload.len() as u32,
            pkt_type: TYPE_STREAM,
            op,
            flags,
            buf_alloc: DEFAULT_BUF_ALLOC,
            fwd_cnt,
        };
        self.queue_to_guest(hdr.encode(payload));
    }

    fn forget(&self, conn: &ConnHandle) {
        let mut st = self.state.lock().unwrap();
        let key = (conn.local_port, conn.remote_port);
        if let Some(cur) = st.conns.get(&key)
            && std::ptr::eq(Arc::as_ptr(cur), conn as *const ConnHandle)
        {
            st.conns.remove(&key);
        }
    }

    fn reset_conn(&self, conn: &ConnHandle) {
        let was_open = {
            let mut c = conn.inner.lock().unwrap();
            if c.state == ConnState::Closed {
                false
            } else {
                c.state = ConnState::Closed;
                c.error.get_or_insert(io::ErrorKind::ConnectionReset);
                conn.cv.notify_all();
                true
            }
        };
        if was_open {
            self.forget(conn);
            self.send_conn_packet(conn, OP_RST, 0, &[]);
        }
    }

    fn handle_conn_packet(&self, conn: &ConnHandle, h: VsockHeader, payload: &[u8]) {
        let mut send_credit_update = false;
        let mut send_rst = false;
        let mut forget = false;

        {
            let mut c = conn.inner.lock().unwrap();
            c.peer_buf_alloc = h.buf_alloc;
            c.peer_fwd_cnt = h.fwd_cnt;

            match h.op {
                OP_RESPONSE if c.state == ConnState::Connecting => {
                    c.state = ConnState::Established;
                }
                OP_RW => {
                    if c.state == ConnState::Established && !payload.is_empty() {
                        c.rx_cnt = c.rx_cnt.wrapping_add(payload.len() as u32);
                        c.rx_buf.extend(payload);
                    }
                }
                OP_SHUTDOWN => {
                    if (h.flags & SHUTDOWN_SEND) != 0 {
                        c.peer_shut_send = true;
                    }
                    if (h.flags & SHUTDOWN_RCV) != 0 {
                        c.peer_shut_rcv = true;
                    }
                    if c.peer_shut_send && c.peer_shut_rcv {
                        c.state = ConnState::Closed;
                        send_rst = true;
                        forget = true;
                    }
                }
                OP_RST => {
                    if c.state == ConnState::Connecting {
                        c.error = Some(io::ErrorKind::ConnectionRefused);
                    } else if !(c.peer_shut_send && (c.shut_sent & SHUTDOWN_SEND) != 0) {
                        c.error = Some(io::ErrorKind::ConnectionReset);
                    }
                    c.state = ConnState::Closed;
                    forget = true;
                }
                OP_CREDIT_REQUEST => {
                    send_credit_update = true;
                }
                OP_CREDIT_UPDATE => {}
                _ => {
                    c.state = ConnState::Closed;
                    c.error = Some(io::ErrorKind::ConnectionReset);
                    send_rst = true;
                    forget = true;
                }
            }
            conn.cv.notify_all();
        }

        if forget {
            self.forget(conn);
        }
        if send_rst {
            self.send_conn_packet(conn, OP_RST, 0, &[]);
        } else if send_credit_update {
            self.send_conn_packet(conn, OP_CREDIT_UPDATE, 0, &[]);
        }
    }
}

/// Blocking bidirectional stream over a guest-host virtio-vsock connection.
#[derive(Clone)]
pub struct VsockStream {
    host: Arc<VsockHost>,
    conn: Arc<ConnHandle>,
}

impl VsockStream {
    /// Read available bytes (blocking until >= 1 byte, EOF `Ok(0)`, or error).
    pub fn read_chunk(&self, buf: &mut [u8], deadline: Option<Instant>) -> io::Result<usize> {
        if buf.is_empty() {
            return Ok(0);
        }
        let (n, need_credit_update) = {
            let mut c = self.conn.inner.lock().unwrap();
            loop {
                if !c.rx_buf.is_empty() {
                    let take = buf.len().min(c.rx_buf.len());
                    for dst in buf.iter_mut().take(take) {
                        *dst = c.rx_buf.pop_front().unwrap();
                    }
                    c.fwd_cnt = c.fwd_cnt.wrapping_add(take as u32);
                    let in_flight = c.rx_cnt.wrapping_sub(c.sent_fwd);
                    let need_update = c.state == ConnState::Established
                        && DEFAULT_BUF_ALLOC.saturating_sub(in_flight) < DEFAULT_BUF_ALLOC / 2
                        && c.fwd_cnt != c.sent_fwd;
                    break (take, need_update);
                }
                if c.peer_shut_send {
                    return Ok(0);
                }
                if c.state == ConnState::Closed {
                    if let Some(kind) = c.error {
                        return Err(io::Error::new(kind, "vsock connection closed"));
                    }
                    return Ok(0);
                }
                if let Some(dl) = deadline {
                    let now = Instant::now();
                    if now >= dl {
                        return Err(io::Error::new(
                            io::ErrorKind::TimedOut,
                            "vsock read timed out",
                        ));
                    }
                    let (g, _) = self.conn.cv.wait_timeout(c, dl - now).unwrap();
                    c = g;
                } else {
                    c = self.conn.cv.wait(c).unwrap();
                }
            }
        };

        if need_credit_update {
            self.host
                .send_conn_packet(&self.conn, OP_CREDIT_UPDATE, 0, &[]);
        }
        Ok(n)
    }

    /// Read exact `buf.len()` bytes.
    pub fn read_exact_deadline(
        &self,
        mut buf: &mut [u8],
        deadline: Option<Instant>,
    ) -> io::Result<()> {
        while !buf.is_empty() {
            let n = self.read_chunk(buf, deadline)?;
            if n == 0 {
                return Err(io::Error::new(
                    io::ErrorKind::UnexpectedEof,
                    "vsock unexpected EOF",
                ));
            }
            buf = &mut buf[n..];
        }
        Ok(())
    }

    /// Write all of `data` respecting peer credit flow control and `max_payload`.
    pub fn write_all_deadline(&self, mut data: &[u8], deadline: Option<Instant>) -> io::Result<()> {
        let max_payload = self.host.state.lock().unwrap().max_payload;
        while !data.is_empty() {
            let chunk_len = {
                let mut c = self.conn.inner.lock().unwrap();
                let mut asked_credit = false;
                loop {
                    if c.state == ConnState::Closed {
                        return Err(io::Error::new(
                            c.error.unwrap_or(io::ErrorKind::BrokenPipe),
                            "vsock closed",
                        ));
                    }
                    if c.peer_shut_rcv {
                        return Err(io::Error::new(
                            io::ErrorKind::BrokenPipe,
                            "guest shut down receive side",
                        ));
                    }
                    let credit = ConnHandle::peer_credit(&c) as usize;
                    if credit > 0 {
                        let n = credit.min(max_payload).min(data.len());
                        c.tx_cnt = c.tx_cnt.wrapping_add(n as u32);
                        break n;
                    }
                    if !asked_credit {
                        asked_credit = true;
                        drop(c);
                        self.host
                            .send_conn_packet(&self.conn, OP_CREDIT_REQUEST, 0, &[]);
                        c = self.conn.inner.lock().unwrap();
                        continue;
                    }
                    let wait = if let Some(dl) = deadline {
                        let now = Instant::now();
                        if now >= dl {
                            return Err(io::Error::new(
                                io::ErrorKind::TimedOut,
                                "vsock write timed out",
                            ));
                        }
                        (dl - now).min(Duration::from_millis(200))
                    } else {
                        Duration::from_millis(200)
                    };
                    let (g, res) = self.conn.cv.wait_timeout(c, wait).unwrap();
                    c = g;
                    if res.timed_out() {
                        asked_credit = false;
                    }
                }
            };
            self.host
                .send_conn_packet(&self.conn, OP_RW, 0, &data[..chunk_len]);
            data = &data[chunk_len..];
        }
        Ok(())
    }

    pub fn shutdown_write(&self) {
        let should_send = {
            let mut c = self.conn.inner.lock().unwrap();
            if c.state != ConnState::Established || (c.shut_sent & SHUTDOWN_SEND) != 0 {
                None
            } else {
                c.shut_sent |= SHUTDOWN_SEND;
                Some(c.shut_sent)
            }
        };
        if let Some(flags) = should_send {
            self.host
                .send_conn_packet(&self.conn, OP_SHUTDOWN, flags, &[]);
        }
    }

    pub fn close(&self) {
        let send_shut = {
            let mut c = self.conn.inner.lock().unwrap();
            if c.state == ConnState::Closed {
                false
            } else {
                c.shut_sent = SHUTDOWN_RCV | SHUTDOWN_SEND;
                c.state = ConnState::Closed;
                self.conn.cv.notify_all();
                true
            }
        };
        if send_shut {
            self.host.forget(&self.conn);
            self.host
                .send_conn_packet(&self.conn, OP_SHUTDOWN, SHUTDOWN_RCV | SHUTDOWN_SEND, &[]);
        }
    }

    pub fn reset(&self) {
        self.host.reset_conn(&self.conn);
    }
}