ethox 0.0.2

A standalone network stack for user-space networking and unikernels
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
//! The user facing packet interface.
//!
//! The interface differs from other layers in that the `In` packet has many different variants it
//! represents, depending on the state of the underlying connection.
use crate::layer;
use crate::wire::{Payload, PayloadMut};
use crate::wire::{ip, tcp};

use super::connection::{AvailableBytes, Endpoint, InPacket, Operator, OutSignals, ReceivedSegment, Segment, Signals};
use super::endpoint::{FourTuple, SlotKey};

/// An incoming tcp packet.
///
/// Don't worry, you can't really do anything with it yet. Not that you'd want to because
/// connections are always closed or not actually responding.
pub enum In<'a, P: PayloadMut> {
    /// A packet that elicited an immediate response.
    ///
    /// May be interesting for logging this but you may as well drop this variant immediately.
    Sending(Sending<'a>),

    /// There is an open connection and you may send and receive data.
    Open(Open<'a, P>),

    /// A packet from us will close the connection.
    ///
    /// This is very similar to `Sending` but it no longer contains a valid connection.
    Closing(Closing<'a>),

    /// Connection has just been closed by the packet.
    Closed(Closed<'a, P>),

    /// A packet for no connection arrived.
    ///
    /// Maybe you are interested anyways? At least the packet was valid tcp traffic and maybe you
    /// want to retro-actively open a new, due some funny port-knocking business or w/e. Your hacks
    /// stay your own, and keep the bugs you find along the way.
    Stray(Stray<'a, P>),
}

/// A user defined (re-)transmission buffer.
/// TODO: a better guide on how to customize
pub trait SendBuf {
    /// Check the available data.
    ///
    /// This should be the total of sent-but-unacknowledged bytes and unsent bytes.
    fn available(&self) -> AvailableBytes;

    /// Fill in some (re-)transmitted data.
    ///
    /// The tcp connection layer will take care to never call this with a buffer outside the
    /// indicated available data length. Bytes that have already been sent are not supposed to
    /// change afterwards, i.e. the `SendBuf` is also utilized as the retransmit buffer.
    fn fill(&mut self, buf: &mut [u8], begin: tcp::SeqNumber);

    /// Notify the buffer that some data can be safely discarded.
    ///
    /// The tcp layer will ensure that no data before the new `begin` is requested again.
    fn ack(&mut self, begin: tcp::SeqNumber);
}

/// A user defined segment reassembly buffer.
/// TODO: a better guide on how to customize
pub trait RecvBuf {
    /// Accept some incoming data.
    ///
    /// Report back the new unreceived byte. This allows the receive buffer to choose the strategy
    /// for partially acknowledged data.
    fn receive(&mut self, buf: &[u8], segment: ReceivedSegment);

    /// Get the highest completed sequence number.
    fn ack(&mut self) -> tcp::SeqNumber;

    /// Get the current window size.
    ///
    /// Shrinking the window size without having accepted new data is allowed but strongly
    /// discouraged.
    fn window(&self) -> usize;
}

/// Informational signals to the user.
///
/// These are intended to be asynchronous 'signals' to the user space process in the original tcp
/// specification but are simple boolean flags here. A socket interface may queue proper messages
/// to its listener of course.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct UserSignals {
    /// An unexpected connection reset occurred.
    pub reset: bool,

    /// The tcp data stream was closed by the remote end.
    ///
    /// The actual connection may still be half-open until our side closes the connection as well.
    ///
    /// WIP: this is not implemented yet and always `false`.
    pub half_closed: bool,

    /// There is new data to be read.
    pub data: bool,

    /// A listening socket returned to its listen state.
    ///
    /// WIP: this is not implemented yet and always `false`.
    pub relisten: bool,
}

/// Packet representation *after* it has been applied to its connection.
///
/// This is purely internal to transition to the handled `In` state.
enum Unhandled<'a, P: Payload> {
    Open {
        operator: Operator<'a>,
        tcp: tcp::Packet<layer::ip::IpPacket<'a, P>>,
    },
    Closed {
        endpoint: &'a mut dyn Endpoint,
        tcp: tcp::Packet<layer::ip::IpPacket<'a, P>>,
    },
}

/// There was some content to send **immediately**.
///
/// The packet has been prepared and already queued on the socket. Not handling or dropping the
/// packet structure now will emit the packet.
///
/// Note that there may still be data that can be received, or the possibility to piggy-back more
/// data to be sent onto the packet. There are flags to test for this.
pub struct Sending<'a> {
    operator: Operator<'a>,
    // FIXME: this should utilize its own 'Signals' that only contain those to the user.
    signals: UserSignals,
}

/// A closing message from us.
///
/// Same as `Sending`, the packet has already been prepared and queue.
pub struct Closing<'a> {
    #[allow(dead_code)] // This attribute exists for parity with other message structs.
    endpoint: &'a mut dyn Endpoint,
    previous: SlotKey,
    signals: UserSignals,
}

/// A connection was closed by a remote packet.
///
/// Similar to a `Stray` packet but we retain which connection was closed.
pub struct Closed<'a, P: PayloadMut> {
    ip: layer::ip::Controller<'a>,
    endpoint: &'a mut dyn Endpoint,
    previous: SlotKey,
    tcp: tcp::Packet<layer::ip::IpPacket<'a, P>>,
}

/// An open connection on which we might want to send and receive data.
///
/// Reading of incoming data and sending of ones own is largely independent of each other.
///
/// On the receiving path it is recommended to call `read` sometimes to ensure the remote is not
/// stalled indefinitely.
pub struct Open<'a, P: PayloadMut> {
    ip: layer::ip::Controller<'a>,
    operator: Operator<'a>,
    signals: UserSignals,
    packet: OpenPacket<'a, P>,
}

/// A valid tcp packet not belonging to a connection.
pub struct Stray<'a, P: PayloadMut> {
    ip: layer::ip::Controller<'a>,
    endpoint: &'a mut dyn Endpoint,
    tcp: tcp::Packet<layer::ip::IpPacket<'a, P>>,
}

enum OpenPacket<'a, P: PayloadMut> {
    /// There is an incoming packet and data to be read.
    In {
        tcp: tcp::Packet<layer::ip::IpPacket<'a, P>>,
        segment: ReceivedSegment,
    },

    /// An incoming packet without data.
    Control {
        tcp: tcp::Packet<layer::ip::IpPacket<'a, P>>,
    },

    /// We got this from the outgoing direction, no data to read.
    Out {
        raw: &'a mut P,
    },
}

/// A raw opportunity to create a packet.
pub struct Raw<'a, P: PayloadMut> {
    pub(super) ip: layer::ip::RawPacket<'a, P>,
    pub(super) endpoint: &'a mut dyn Endpoint,
}

impl<'a, P: PayloadMut> Unhandled<'a, P> {
    fn try_open(
        endpoint: &'a mut dyn Endpoint,
        tcp: tcp::Packet<layer::ip::IpPacket<'a, P>>,
    ) -> Self {
        let tcp_repr = tcp.repr();
        let ip_repr = tcp.inner().repr();

        let connection = FourTuple {
            local: ip_repr.dst_addr(),
            local_port: tcp_repr.dst_port,
            remote: ip_repr.src_addr(),
            remote_port: tcp_repr.src_port,
        };

        match Operator::from_tuple(endpoint, connection) {
            Ok(operator) => Unhandled::Open {
                operator,
                tcp,
            },
            Err(endpoint) => Unhandled::Closed {
                endpoint,
                tcp,
            }
        }
    }
}

impl<'a, P: PayloadMut> In<'a, P> {
    /// Handle an incoming TCP packet returning a representation indicating appropriate options.
    pub fn from_arriving(
        endpoint: &'a mut dyn Endpoint,
        ip_control: layer::ip::Controller<'a>,
        tcp: tcp::Packet<layer::ip::IpPacket<'a, P>>,
    ) -> Result<Self, crate::layer::Error> {
        let (mut operator, tcp) = match Unhandled::try_open(endpoint, tcp) {
            Unhandled::Open { operator, tcp } => (operator, tcp),
            Unhandled::Closed { endpoint, tcp } => {
                return Ok(In::Stray(Stray {
                    endpoint,
                    ip: ip_control,
                    tcp,
                }));
            }
        };

        let from = tcp.inner().repr().src_addr();
        let time = ip_control.info().timestamp();
        let in_packet = InPacket {
            segment: tcp.repr(),
            from,
            time,
        };

        let mut signals = operator.arrives(&in_packet);
        let user = UserSignals::new(&signals);

        // Deleting the connection nothing to be sent.
        if signals.delete && signals.answer.is_none() {
            let previous = operator.connection_key;
            let endpoint = operator.delete();
            return Ok(In::Closed(Closed {
                ip: ip_control,
                endpoint,
                previous,
                tcp,
            }));
        }

        // If no answer we are free to send anything.
        let answer = match signals.answer.take() {
            Some(answer) => answer,
            None => {
                return Ok(In::Open(Open {
                    ip: ip_control,
                    operator,
                    signals: user,
                    // Determine if this is with or without data.
                    packet: match signals.receive {
                        Some(segment) => OpenPacket::In { tcp, segment },
                        None => OpenPacket::Control { tcp },
                    },
                }));
            },
        };

        // Prepare the answer packet itself.
        control_answer(tcp, answer, ip_control)?;

        // We need to close the connection. The sent packet should be an RST.
        if signals.delete {
            let previous = operator.connection_key;
            let endpoint = operator.delete();
            return Ok(In::Closing(Closing {
                endpoint,
                previous,
                signals: user,
            }));
        }

        debug_assert_eq!(signals.reset, false);
        Ok(In::Sending(Sending {
            operator,
            signals: user,
        }))
    }

    /// Get the key of the connection associated with the packet.
    pub fn key(&self) -> Option<SlotKey> {
        match self {
            In::Sending(sending) => Some(sending.key()),
            In::Open(open) => Some(open.key()),
            In::Closing(closing) => Some(closing.key()),
            In::Closed(closed) => Some(closed.key()),
            In::Stray(_) => None,
        }
    }

    /// Get a descriptor for state changes that would usually send a signal to the user.
    pub fn user_signals(&self) -> UserSignals {
        match self {
            In::Sending(sending) => sending.signals,
            In::Open(open) => open.signals,
            In::Closing(closing) => closing.signals,
            In::Closed(_) => UserSignals::default(),
            In::Stray(_) => UserSignals::default(),
        }
    }
}

impl<'a, P: PayloadMut> Open<'a, P> {
    /// Get the slot key of the connection corresponding to this packet.
    pub fn key(&self) -> SlotKey {
        self.operator.connection_key
    }

    /// Receive data contained in the TCP segment.
    pub fn read(&mut self, with: &mut impl RecvBuf) {
        let connection = self.operator.connection_mut();
        connection.recv.update_window(with.window());

        if let OpenPacket::In { tcp, segment } = &self.packet {
            with.receive(tcp.payload_slice(), *segment);
            let progress = segment.acked_until(with.ack());
            connection.set_recv_ack(progress);
        }
    }

    /// Try to send parts of the available data.
    ///
    /// If the method succeeds returns a view on the packet being sent. Else, it will return a
    /// handle to the connection again (this struct).
    ///
    /// Any data that is currently held as an incoming packet will be lost, even if this method fails.
    pub fn write(self, with: &mut impl SendBuf) -> Result<Result<Sending<'a>, Closing<'a>>, crate::layer::Error> {
        let Open { ip, mut operator, signals: mut user, packet, } = self;
        let payload: &'a mut P = match packet {
            OpenPacket::In { tcp, .. } | OpenPacket::Control { tcp }
                => tcp.into_inner().into_inner().into_inner(),
            OpenPacket::Out { raw } => raw,
        };

        let tcp_seq = operator.connection().get_send_ack();
        with.ack(tcp_seq);
        let available = with.available();
        let time = ip.info().timestamp();

        let signals = operator.next_send_segment(available, time);
        user.update(&signals);

        if let Some(Segment { repr, range }) = signals.segment {
            let raw_ip = layer::ip::RawPacket {
                control: ip,
                payload,
            };

            let mut out_ip = prepare(raw_ip, &mut operator, repr)?;

            let ip_repr = out_ip.repr();
            let mut tcp = tcp::Packet::new_unchecked(out_ip.payload_mut_slice(), repr);
            with.fill(tcp.payload_mut_slice(), tcp_seq + range.start);
            tcp.fill_checksum(ip_repr.src_addr(), ip_repr.dst_addr());

            out_ip.send()?;
        }

        Ok(if signals.delete {
            let previous = operator.key();
            let endpoint = operator.delete();
            Err(Closing {
                endpoint,
                previous,
                signals: user,
            })
        } else {
            Ok(Sending {
                operator,
                signals: user,
            })
        })
    }
}

impl<'a, P: PayloadMut> Raw<'a, P> {
    /// Create a new connection.
    pub fn open(self, addr: ip::Address, port: u16) -> Result<Open<'a, P>, crate::layer::Error> {
        let local = self.source(addr)?;
        let local_port = self.endpoint.source_port(local)
            .ok_or(crate::layer::Error::Exhausted)?;

        let new = FourTuple {
            local,
            local_port,
            remote: addr,
            remote_port: port,
        };

        let mut operator = match self.endpoint.open(new) {
            None => return Err(crate::layer::Error::Exhausted),
            Some(key) => Operator::new(self.endpoint, key).unwrap(),
        };

        let time = self.ip.control.info().timestamp();
        assert!(operator.open(time).is_ok());

        let layer::ip::RawPacket {
            control: ip,
            payload: raw,
        } = self.ip;

        Ok(Open {
            ip,
            operator,
            signals: UserSignals::default(),
            packet: OpenPacket::Out { raw },
        })
    }

    /// Attach to an existing connection.
    ///
    /// If successful, this return an `Open` packet with which you can send data on the connection.
    pub fn attach(self, key: SlotKey) -> Result<Open<'a, P>, Self> {
        if self.endpoint.get(key).is_none() {
            return Err(self);
        };

        let operator = Operator::new(self.endpoint, key).unwrap();

        let layer::ip::RawPacket {
            control: ip,
            payload: raw,
        } = self.ip;

        Ok(Open {
            ip,
            operator,
            signals: UserSignals::default(),
            packet: OpenPacket::Out { raw },
        })
    }

    fn source(&self, dst: ip::Address) -> Result<ip::Address, crate::layer::Error> {
        // Find a suitable ip source address.
        let source = match dst {
            ip::Address::Ipv4(_) => ip::Subnet::Ipv4(ip::v4::Subnet::ANY),
            ip::Address::Ipv6(_) => ip::Subnet::Ipv6(ip::v6::Subnet::ANY),
            _ => return Err(crate::layer::Error::Illegal),
        };

        self.ip.control().local_ip(source)
            .ok_or(crate::layer::Error::Unreachable)
    }
}

impl<'a> Sending<'a> {
    /// Get a the slot key identifying the connection the sending segment belongs to.
    pub fn key(&self) -> SlotKey {
        self.operator.connection_key
    }
}

impl<'a> Closing<'a> {
    /// Get a the slot key identifying the connection which closes.
    pub fn key(&self) -> SlotKey {
        self.previous
    }
}

impl<'a, P: PayloadMut> Closed<'a, P> {
    /// Get a the slot key identifying the connection which just got closed.
    pub fn key(&self) -> SlotKey {
        self.previous
    }

    /// Unwrap the packet buffer for reuse.
    ///
    /// Since there is no longer a connection, the attachement no longer has a purpose. It's also
    /// not incredibly sensible to try and send more segments to the previously connected remote.
    /// For most systems, the answer are resets or challenge ACKs.
    pub fn into_raw(self) -> Raw<'a, P> {
        let raw_ip = layer::ip::RawPacket {
            control: self.ip,
            payload: self.tcp.into_inner().into_inner().into_inner(),
        };

        Raw {
            ip: raw_ip,
            endpoint: self.endpoint,
        }
    }
}

impl<'a, P: PayloadMut> Stray<'a, P> {
    /// Unwrap the packet buffer for reuse.
    ///
    /// There was no connection that the packet belonged to and thus no response required. This
    /// allows the user to use the packet buffer for arbitrary other communication.
    pub fn into_raw(self) -> Raw<'a, P> {
        let raw_ip = layer::ip::RawPacket {
            control: self.ip,
            payload: self.tcp.into_inner().into_inner().into_inner(),
        };

        Raw {
            ip: raw_ip,
            endpoint: self.endpoint,
        }
    }
}

impl UserSignals {
    fn new(signals: &Signals) -> Self {
        UserSignals {
            reset: signals.reset,
            data: signals.receive.is_some(),
            half_closed: false,
            relisten: false,
        }
    }

    fn update(&mut self, _signals: &OutSignals) {
        // TODO: anything to set?
    }
}

fn control_answer<'a, P: PayloadMut>(
    tcp: tcp::Packet<layer::ip::IpPacket<'a, P>>,
    answer: tcp::Repr,
    ip: layer::ip::Controller<'a>,
) -> Result<(), crate::layer::Error> {
    assert_eq!(answer.payload_len, 0, "Control answer can not handle data");

    let raw_buffer = tcp.into_inner();
    let ip_repr = raw_buffer.repr();
    let ip_payload_len = answer.header_len();

    let packet = layer::ip::InPacket {
        control: ip,
        packet: raw_buffer,
    };

    // Send a packet back.
    let layer::ip::InPacket { control, mut packet, } = packet.reinit(layer::ip::Init {
        source: layer::ip::Source::Exact(ip_repr.dst_addr()),
        dst_addr: ip_repr.src_addr(),
        protocol: ip::Protocol::Tcp,
        payload: ip_payload_len,
    })?.into_incoming();

    // FIXME: make initialization nicer.
    let raw_packet = tcp::Packet::new_unchecked(&mut packet, answer.clone());
    answer.emit(raw_packet);
    let mut raw_packet = tcp::Packet::new_unchecked(&mut packet, answer.clone());
    raw_packet.fill_checksum(ip_repr.src_addr(), ip_repr.dst_addr());

    layer::ip::OutPacket::new_unchecked(control, packet)
        .send()
}

fn prepare<'a, P: PayloadMut>(
    packet: layer::ip::RawPacket<'a, P>,
    operator: &mut Operator,
    repr: tcp::Repr,
) -> Result<layer::ip::OutPacket<'a, P>, crate::layer::Error> {

    let tuple = operator.four_tuple();
    let init_ip = packet.prepare(layer::ip::Init {
        dst_addr: tuple.remote,
        source: layer::ip::Source::Exact(tuple.local),
        protocol: ip::Protocol::Tcp,
        payload: repr.header_len() + usize::from(repr.payload_len),
    })?;

    let layer::ip::InPacket { control, mut packet } = init_ip.into_incoming();

    let tcp = tcp::Packet::new_unchecked(&mut packet, repr);
    repr.emit(tcp);

    Ok(layer::ip::OutPacket::new_unchecked(control, packet))
}