2016-12-28 02:34:13 +08:00
|
|
|
use core::{i32, ops, cmp, fmt};
|
2016-12-19 05:42:44 +08:00
|
|
|
use byteorder::{ByteOrder, NetworkEndian};
|
|
|
|
|
2020-12-27 07:11:30 +08:00
|
|
|
use crate::{Error, Result};
|
|
|
|
use crate::phy::ChecksumCapabilities;
|
|
|
|
use crate::wire::{IpProtocol, IpAddress};
|
|
|
|
use crate::wire::ip::checksum;
|
2016-12-19 05:42:44 +08:00
|
|
|
|
2016-12-28 02:34:13 +08:00
|
|
|
/// A TCP sequence number.
|
|
|
|
///
|
|
|
|
/// A sequence number is a monotonically advancing integer modulo 2<sup>32</sup>.
|
|
|
|
/// Sequence numbers do not have a discontiguity when compared pairwise across a signed overflow.
|
2017-08-23 06:32:05 +08:00
|
|
|
#[derive(Debug, PartialEq, Eq, Clone, Copy, Default)]
|
2016-12-28 02:34:13 +08:00
|
|
|
pub struct SeqNumber(pub i32);
|
|
|
|
|
|
|
|
impl fmt::Display for SeqNumber {
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
|
|
write!(f, "{}", self.0 as u32)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl ops::Add<usize> for SeqNumber {
|
|
|
|
type Output = SeqNumber;
|
|
|
|
|
|
|
|
fn add(self, rhs: usize) -> SeqNumber {
|
|
|
|
if rhs > i32::MAX as usize {
|
|
|
|
panic!("attempt to add to sequence number with unsigned overflow")
|
|
|
|
}
|
|
|
|
SeqNumber(self.0.wrapping_add(rhs as i32))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-12-31 09:24:55 +08:00
|
|
|
impl ops::Sub<usize> for SeqNumber {
|
|
|
|
type Output = SeqNumber;
|
|
|
|
|
|
|
|
fn sub(self, rhs: usize) -> SeqNumber {
|
|
|
|
if rhs > i32::MAX as usize {
|
|
|
|
panic!("attempt to subtract to sequence number with unsigned overflow")
|
|
|
|
}
|
|
|
|
SeqNumber(self.0.wrapping_sub(rhs as i32))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-12-28 02:34:13 +08:00
|
|
|
impl ops::AddAssign<usize> for SeqNumber {
|
|
|
|
fn add_assign(&mut self, rhs: usize) {
|
|
|
|
*self = *self + rhs;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl ops::Sub for SeqNumber {
|
|
|
|
type Output = usize;
|
|
|
|
|
|
|
|
fn sub(self, rhs: SeqNumber) -> usize {
|
2017-12-21 20:33:32 +08:00
|
|
|
let result = self.0.wrapping_sub(rhs.0);
|
|
|
|
if result < 0 {
|
|
|
|
panic!("attempt to subtract sequence numbers with underflow")
|
|
|
|
}
|
|
|
|
result as usize
|
2016-12-28 02:34:13 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl cmp::PartialOrd for SeqNumber {
|
|
|
|
fn partial_cmp(&self, other: &SeqNumber) -> Option<cmp::Ordering> {
|
2017-11-13 16:45:07 +08:00
|
|
|
self.0.wrapping_sub(other.0).partial_cmp(&0)
|
2016-12-28 02:34:13 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-01-27 05:20:48 +08:00
|
|
|
/// A read/write wrapper around a Transmission Control Protocol packet buffer.
|
2018-02-05 19:42:05 +08:00
|
|
|
#[derive(Debug, PartialEq, Clone)]
|
2016-12-19 05:42:44 +08:00
|
|
|
pub struct Packet<T: AsRef<[u8]>> {
|
|
|
|
buffer: T
|
|
|
|
}
|
|
|
|
|
|
|
|
mod field {
|
|
|
|
#![allow(non_snake_case)]
|
|
|
|
|
2020-12-27 07:11:30 +08:00
|
|
|
use crate::wire::field::*;
|
2016-12-19 05:42:44 +08:00
|
|
|
|
|
|
|
pub const SRC_PORT: Field = 0..2;
|
|
|
|
pub const DST_PORT: Field = 2..4;
|
|
|
|
pub const SEQ_NUM: Field = 4..8;
|
|
|
|
pub const ACK_NUM: Field = 8..12;
|
|
|
|
pub const FLAGS: Field = 12..14;
|
|
|
|
pub const WIN_SIZE: Field = 14..16;
|
|
|
|
pub const CHECKSUM: Field = 16..18;
|
|
|
|
pub const URGENT: Field = 18..20;
|
|
|
|
|
2017-06-24 20:02:17 +08:00
|
|
|
pub fn OPTIONS(length: u8) -> Field {
|
|
|
|
URGENT.end..(length as usize)
|
|
|
|
}
|
|
|
|
|
2016-12-19 05:42:44 +08:00
|
|
|
pub const FLG_FIN: u16 = 0x001;
|
|
|
|
pub const FLG_SYN: u16 = 0x002;
|
|
|
|
pub const FLG_RST: u16 = 0x004;
|
|
|
|
pub const FLG_PSH: u16 = 0x008;
|
|
|
|
pub const FLG_ACK: u16 = 0x010;
|
|
|
|
pub const FLG_URG: u16 = 0x020;
|
|
|
|
pub const FLG_ECE: u16 = 0x040;
|
|
|
|
pub const FLG_CWR: u16 = 0x080;
|
|
|
|
pub const FLG_NS: u16 = 0x100;
|
2017-01-27 08:17:13 +08:00
|
|
|
|
|
|
|
pub const OPT_END: u8 = 0x00;
|
|
|
|
pub const OPT_NOP: u8 = 0x01;
|
|
|
|
pub const OPT_MSS: u8 = 0x02;
|
|
|
|
pub const OPT_WS: u8 = 0x03;
|
2019-01-01 04:45:20 +08:00
|
|
|
pub const OPT_SACKPERM: u8 = 0x04;
|
|
|
|
pub const OPT_SACKRNG: u8 = 0x05;
|
2016-12-19 05:42:44 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
impl<T: AsRef<[u8]>> Packet<T> {
|
Do not attempt to validate length of packets being emitted.
This is a form of an uninitialized read bug; although safe it caused
panics. In short, transmit buffers received from the network stack
should be considered uninitialized (in practice they will often
contain previously transmitted packets or parts thereof). Wrapping
them with the only method we had (e.g. Ipv4Packet) treated the buffer
as if it contained a valid incoming packet, which can easily fail
with Error::Truncated.
This commit splits every `fn new(buffer: T) -> Result<Self, Error>`
method on a `Packet` into three smaller ones:
* `fn check_len(&self) -> Result<(), Error>`, purely a validator;
* `fn new(T) -> Self`, purely a wrapper;
* `fn new_checked(T) -> Result<Self, Error>`, a validating wrapper.
This makes it easy to process ingress packets (using `new_checked`),
egress packets (using `new`), and, if needed, maintain the invariants
at any point during packet construction (using `check_len`).
Fixes #17.
2017-06-24 17:15:22 +08:00
|
|
|
/// Imbue a raw octet buffer with TCP packet structure.
|
2018-07-11 08:22:43 +08:00
|
|
|
pub fn new_unchecked(buffer: T) -> Packet<T> {
|
Do not attempt to validate length of packets being emitted.
This is a form of an uninitialized read bug; although safe it caused
panics. In short, transmit buffers received from the network stack
should be considered uninitialized (in practice they will often
contain previously transmitted packets or parts thereof). Wrapping
them with the only method we had (e.g. Ipv4Packet) treated the buffer
as if it contained a valid incoming packet, which can easily fail
with Error::Truncated.
This commit splits every `fn new(buffer: T) -> Result<Self, Error>`
method on a `Packet` into three smaller ones:
* `fn check_len(&self) -> Result<(), Error>`, purely a validator;
* `fn new(T) -> Self`, purely a wrapper;
* `fn new_checked(T) -> Result<Self, Error>`, a validating wrapper.
This makes it easy to process ingress packets (using `new_checked`),
egress packets (using `new`), and, if needed, maintain the invariants
at any point during packet construction (using `check_len`).
Fixes #17.
2017-06-24 17:15:22 +08:00
|
|
|
Packet { buffer }
|
|
|
|
}
|
|
|
|
|
2018-07-11 08:22:43 +08:00
|
|
|
/// Shorthand for a combination of [new_unchecked] and [check_len].
|
Do not attempt to validate length of packets being emitted.
This is a form of an uninitialized read bug; although safe it caused
panics. In short, transmit buffers received from the network stack
should be considered uninitialized (in practice they will often
contain previously transmitted packets or parts thereof). Wrapping
them with the only method we had (e.g. Ipv4Packet) treated the buffer
as if it contained a valid incoming packet, which can easily fail
with Error::Truncated.
This commit splits every `fn new(buffer: T) -> Result<Self, Error>`
method on a `Packet` into three smaller ones:
* `fn check_len(&self) -> Result<(), Error>`, purely a validator;
* `fn new(T) -> Self`, purely a wrapper;
* `fn new_checked(T) -> Result<Self, Error>`, a validating wrapper.
This makes it easy to process ingress packets (using `new_checked`),
egress packets (using `new`), and, if needed, maintain the invariants
at any point during packet construction (using `check_len`).
Fixes #17.
2017-06-24 17:15:22 +08:00
|
|
|
///
|
2018-07-11 08:22:43 +08:00
|
|
|
/// [new_unchecked]: #method.new_unchecked
|
Do not attempt to validate length of packets being emitted.
This is a form of an uninitialized read bug; although safe it caused
panics. In short, transmit buffers received from the network stack
should be considered uninitialized (in practice they will often
contain previously transmitted packets or parts thereof). Wrapping
them with the only method we had (e.g. Ipv4Packet) treated the buffer
as if it contained a valid incoming packet, which can easily fail
with Error::Truncated.
This commit splits every `fn new(buffer: T) -> Result<Self, Error>`
method on a `Packet` into three smaller ones:
* `fn check_len(&self) -> Result<(), Error>`, purely a validator;
* `fn new(T) -> Self`, purely a wrapper;
* `fn new_checked(T) -> Result<Self, Error>`, a validating wrapper.
This makes it easy to process ingress packets (using `new_checked`),
egress packets (using `new`), and, if needed, maintain the invariants
at any point during packet construction (using `check_len`).
Fixes #17.
2017-06-24 17:15:22 +08:00
|
|
|
/// [check_len]: #method.check_len
|
2017-07-27 21:51:02 +08:00
|
|
|
pub fn new_checked(buffer: T) -> Result<Packet<T>> {
|
2018-07-11 08:22:43 +08:00
|
|
|
let packet = Self::new_unchecked(buffer);
|
2017-06-25 00:34:32 +08:00
|
|
|
packet.check_len()?;
|
Do not attempt to validate length of packets being emitted.
This is a form of an uninitialized read bug; although safe it caused
panics. In short, transmit buffers received from the network stack
should be considered uninitialized (in practice they will often
contain previously transmitted packets or parts thereof). Wrapping
them with the only method we had (e.g. Ipv4Packet) treated the buffer
as if it contained a valid incoming packet, which can easily fail
with Error::Truncated.
This commit splits every `fn new(buffer: T) -> Result<Self, Error>`
method on a `Packet` into three smaller ones:
* `fn check_len(&self) -> Result<(), Error>`, purely a validator;
* `fn new(T) -> Self`, purely a wrapper;
* `fn new_checked(T) -> Result<Self, Error>`, a validating wrapper.
This makes it easy to process ingress packets (using `new_checked`),
egress packets (using `new`), and, if needed, maintain the invariants
at any point during packet construction (using `check_len`).
Fixes #17.
2017-06-24 17:15:22 +08:00
|
|
|
Ok(packet)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Ensure that no accessor method will panic if called.
|
|
|
|
/// Returns `Err(Error::Truncated)` if the buffer is too short.
|
2017-06-24 20:29:39 +08:00
|
|
|
/// Returns `Err(Error::Malformed)` if the header length field has a value smaller
|
|
|
|
/// than the minimal header length.
|
Do not attempt to validate length of packets being emitted.
This is a form of an uninitialized read bug; although safe it caused
panics. In short, transmit buffers received from the network stack
should be considered uninitialized (in practice they will often
contain previously transmitted packets or parts thereof). Wrapping
them with the only method we had (e.g. Ipv4Packet) treated the buffer
as if it contained a valid incoming packet, which can easily fail
with Error::Truncated.
This commit splits every `fn new(buffer: T) -> Result<Self, Error>`
method on a `Packet` into three smaller ones:
* `fn check_len(&self) -> Result<(), Error>`, purely a validator;
* `fn new(T) -> Self`, purely a wrapper;
* `fn new_checked(T) -> Result<Self, Error>`, a validating wrapper.
This makes it easy to process ingress packets (using `new_checked`),
egress packets (using `new`), and, if needed, maintain the invariants
at any point during packet construction (using `check_len`).
Fixes #17.
2017-06-24 17:15:22 +08:00
|
|
|
///
|
|
|
|
/// The result of this check is invalidated by calling [set_header_len].
|
|
|
|
///
|
|
|
|
/// [set_header_len]: #method.set_header_len
|
2017-07-27 21:51:02 +08:00
|
|
|
pub fn check_len(&self) -> Result<()> {
|
Do not attempt to validate length of packets being emitted.
This is a form of an uninitialized read bug; although safe it caused
panics. In short, transmit buffers received from the network stack
should be considered uninitialized (in practice they will often
contain previously transmitted packets or parts thereof). Wrapping
them with the only method we had (e.g. Ipv4Packet) treated the buffer
as if it contained a valid incoming packet, which can easily fail
with Error::Truncated.
This commit splits every `fn new(buffer: T) -> Result<Self, Error>`
method on a `Packet` into three smaller ones:
* `fn check_len(&self) -> Result<(), Error>`, purely a validator;
* `fn new(T) -> Self`, purely a wrapper;
* `fn new_checked(T) -> Result<Self, Error>`, a validating wrapper.
This makes it easy to process ingress packets (using `new_checked`),
egress packets (using `new`), and, if needed, maintain the invariants
at any point during packet construction (using `check_len`).
Fixes #17.
2017-06-24 17:15:22 +08:00
|
|
|
let len = self.buffer.as_ref().len();
|
2016-12-19 05:42:44 +08:00
|
|
|
if len < field::URGENT.end {
|
|
|
|
Err(Error::Truncated)
|
|
|
|
} else {
|
2017-06-24 19:47:24 +08:00
|
|
|
let header_len = self.header_len() as usize;
|
|
|
|
if len < header_len {
|
|
|
|
Err(Error::Truncated)
|
2017-06-24 20:29:39 +08:00
|
|
|
} else if header_len < field::URGENT.end {
|
|
|
|
Err(Error::Malformed)
|
2017-06-24 19:47:24 +08:00
|
|
|
} else {
|
|
|
|
Ok(())
|
|
|
|
}
|
2016-12-19 05:42:44 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
Do not attempt to validate length of packets being emitted.
This is a form of an uninitialized read bug; although safe it caused
panics. In short, transmit buffers received from the network stack
should be considered uninitialized (in practice they will often
contain previously transmitted packets or parts thereof). Wrapping
them with the only method we had (e.g. Ipv4Packet) treated the buffer
as if it contained a valid incoming packet, which can easily fail
with Error::Truncated.
This commit splits every `fn new(buffer: T) -> Result<Self, Error>`
method on a `Packet` into three smaller ones:
* `fn check_len(&self) -> Result<(), Error>`, purely a validator;
* `fn new(T) -> Self`, purely a wrapper;
* `fn new_checked(T) -> Result<Self, Error>`, a validating wrapper.
This makes it easy to process ingress packets (using `new_checked`),
egress packets (using `new`), and, if needed, maintain the invariants
at any point during packet construction (using `check_len`).
Fixes #17.
2017-06-24 17:15:22 +08:00
|
|
|
/// Consume the packet, returning the underlying buffer.
|
2016-12-19 05:42:44 +08:00
|
|
|
pub fn into_inner(self) -> T {
|
|
|
|
self.buffer
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Return the source port field.
|
2016-12-31 00:55:31 +08:00
|
|
|
#[inline]
|
2016-12-19 05:42:44 +08:00
|
|
|
pub fn src_port(&self) -> u16 {
|
|
|
|
let data = self.buffer.as_ref();
|
|
|
|
NetworkEndian::read_u16(&data[field::SRC_PORT])
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Return the destination port field.
|
2016-12-31 00:55:31 +08:00
|
|
|
#[inline]
|
2016-12-19 05:42:44 +08:00
|
|
|
pub fn dst_port(&self) -> u16 {
|
|
|
|
let data = self.buffer.as_ref();
|
|
|
|
NetworkEndian::read_u16(&data[field::DST_PORT])
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Return the sequence number field.
|
2016-12-31 00:55:31 +08:00
|
|
|
#[inline]
|
2016-12-28 02:34:13 +08:00
|
|
|
pub fn seq_number(&self) -> SeqNumber {
|
2016-12-19 05:42:44 +08:00
|
|
|
let data = self.buffer.as_ref();
|
2016-12-28 02:34:13 +08:00
|
|
|
SeqNumber(NetworkEndian::read_i32(&data[field::SEQ_NUM]))
|
2016-12-19 05:42:44 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Return the acknowledgement number field.
|
2016-12-31 00:55:31 +08:00
|
|
|
#[inline]
|
2016-12-28 02:34:13 +08:00
|
|
|
pub fn ack_number(&self) -> SeqNumber {
|
2016-12-19 05:42:44 +08:00
|
|
|
let data = self.buffer.as_ref();
|
2016-12-28 02:34:13 +08:00
|
|
|
SeqNumber(NetworkEndian::read_i32(&data[field::ACK_NUM]))
|
2016-12-19 05:42:44 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Return the FIN flag.
|
2016-12-31 00:55:31 +08:00
|
|
|
#[inline]
|
2016-12-19 05:42:44 +08:00
|
|
|
pub fn fin(&self) -> bool {
|
|
|
|
let data = self.buffer.as_ref();
|
|
|
|
let raw = NetworkEndian::read_u16(&data[field::FLAGS]);
|
|
|
|
raw & field::FLG_FIN != 0
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Return the SYN flag.
|
2016-12-31 00:55:31 +08:00
|
|
|
#[inline]
|
2016-12-19 05:42:44 +08:00
|
|
|
pub fn syn(&self) -> bool {
|
|
|
|
let data = self.buffer.as_ref();
|
|
|
|
let raw = NetworkEndian::read_u16(&data[field::FLAGS]);
|
|
|
|
raw & field::FLG_SYN != 0
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Return the RST flag.
|
2016-12-31 00:55:31 +08:00
|
|
|
#[inline]
|
2016-12-19 05:42:44 +08:00
|
|
|
pub fn rst(&self) -> bool {
|
|
|
|
let data = self.buffer.as_ref();
|
|
|
|
let raw = NetworkEndian::read_u16(&data[field::FLAGS]);
|
|
|
|
raw & field::FLG_RST != 0
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Return the PSH flag.
|
2016-12-31 00:55:31 +08:00
|
|
|
#[inline]
|
2016-12-19 05:42:44 +08:00
|
|
|
pub fn psh(&self) -> bool {
|
|
|
|
let data = self.buffer.as_ref();
|
|
|
|
let raw = NetworkEndian::read_u16(&data[field::FLAGS]);
|
|
|
|
raw & field::FLG_PSH != 0
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Return the ACK flag.
|
2016-12-31 00:55:31 +08:00
|
|
|
#[inline]
|
2016-12-19 05:42:44 +08:00
|
|
|
pub fn ack(&self) -> bool {
|
|
|
|
let data = self.buffer.as_ref();
|
|
|
|
let raw = NetworkEndian::read_u16(&data[field::FLAGS]);
|
|
|
|
raw & field::FLG_ACK != 0
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Return the URG flag.
|
2016-12-31 00:55:31 +08:00
|
|
|
#[inline]
|
2016-12-19 05:42:44 +08:00
|
|
|
pub fn urg(&self) -> bool {
|
|
|
|
let data = self.buffer.as_ref();
|
|
|
|
let raw = NetworkEndian::read_u16(&data[field::FLAGS]);
|
|
|
|
raw & field::FLG_URG != 0
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Return the ECE flag.
|
2016-12-31 00:55:31 +08:00
|
|
|
#[inline]
|
2016-12-19 05:42:44 +08:00
|
|
|
pub fn ece(&self) -> bool {
|
|
|
|
let data = self.buffer.as_ref();
|
|
|
|
let raw = NetworkEndian::read_u16(&data[field::FLAGS]);
|
|
|
|
raw & field::FLG_ECE != 0
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Return the CWR flag.
|
2016-12-31 00:55:31 +08:00
|
|
|
#[inline]
|
2016-12-19 05:42:44 +08:00
|
|
|
pub fn cwr(&self) -> bool {
|
|
|
|
let data = self.buffer.as_ref();
|
|
|
|
let raw = NetworkEndian::read_u16(&data[field::FLAGS]);
|
|
|
|
raw & field::FLG_CWR != 0
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Return the NS flag.
|
2016-12-31 00:55:31 +08:00
|
|
|
#[inline]
|
2016-12-19 05:42:44 +08:00
|
|
|
pub fn ns(&self) -> bool {
|
|
|
|
let data = self.buffer.as_ref();
|
|
|
|
let raw = NetworkEndian::read_u16(&data[field::FLAGS]);
|
|
|
|
raw & field::FLG_NS != 0
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Return the header length, in octets.
|
2016-12-31 00:55:31 +08:00
|
|
|
#[inline]
|
2016-12-19 05:42:44 +08:00
|
|
|
pub fn header_len(&self) -> u8 {
|
|
|
|
let data = self.buffer.as_ref();
|
|
|
|
let raw = NetworkEndian::read_u16(&data[field::FLAGS]);
|
|
|
|
((raw >> 12) * 4) as u8
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Return the window size field.
|
2016-12-31 00:55:31 +08:00
|
|
|
#[inline]
|
2016-12-19 05:42:44 +08:00
|
|
|
pub fn window_len(&self) -> u16 {
|
|
|
|
let data = self.buffer.as_ref();
|
|
|
|
NetworkEndian::read_u16(&data[field::WIN_SIZE])
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Return the checksum field.
|
2016-12-31 00:55:31 +08:00
|
|
|
#[inline]
|
2016-12-19 05:42:44 +08:00
|
|
|
pub fn checksum(&self) -> u16 {
|
|
|
|
let data = self.buffer.as_ref();
|
|
|
|
NetworkEndian::read_u16(&data[field::CHECKSUM])
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Return the urgent pointer field.
|
2016-12-31 00:55:31 +08:00
|
|
|
#[inline]
|
2016-12-19 05:42:44 +08:00
|
|
|
pub fn urgent_at(&self) -> u16 {
|
|
|
|
let data = self.buffer.as_ref();
|
|
|
|
NetworkEndian::read_u16(&data[field::URGENT])
|
|
|
|
}
|
|
|
|
|
2016-12-23 15:31:15 +08:00
|
|
|
/// Return the length of the segment, in terms of sequence space.
|
2016-12-28 02:34:13 +08:00
|
|
|
pub fn segment_len(&self) -> usize {
|
2016-12-23 15:31:15 +08:00
|
|
|
let data = self.buffer.as_ref();
|
|
|
|
let mut length = data.len() - self.header_len() as usize;
|
2016-12-25 19:09:50 +08:00
|
|
|
if self.syn() { length += 1 }
|
|
|
|
if self.fin() { length += 1 }
|
2016-12-28 02:34:13 +08:00
|
|
|
length
|
2016-12-23 15:31:15 +08:00
|
|
|
}
|
|
|
|
|
2019-01-01 04:45:20 +08:00
|
|
|
/// Returns whether the selective acknowledgement SYN flag is set or not.
|
|
|
|
pub fn selective_ack_permitted(&self) -> Result<bool> {
|
|
|
|
let data = self.buffer.as_ref();
|
|
|
|
let mut options = &data[field::OPTIONS(self.header_len())];
|
|
|
|
while options.len() > 0 {
|
|
|
|
let (next_options, option) = TcpOption::parse(options)?;
|
|
|
|
match option {
|
|
|
|
TcpOption::SackPermitted => {
|
|
|
|
return Ok(true);
|
|
|
|
},
|
|
|
|
_ => {},
|
|
|
|
}
|
|
|
|
options = next_options;
|
|
|
|
}
|
|
|
|
Ok(false)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Return the selective acknowledgement ranges, if any. If there are none in the packet, an
|
|
|
|
/// array of ``None`` values will be returned.
|
|
|
|
///
|
|
|
|
pub fn selective_ack_ranges<'s>(
|
|
|
|
&'s self
|
|
|
|
) -> Result<[Option<(u32, u32)>; 3]> {
|
|
|
|
let data = self.buffer.as_ref();
|
|
|
|
let mut options = &data[field::OPTIONS(self.header_len())];
|
|
|
|
while options.len() > 0 {
|
|
|
|
let (next_options, option) = TcpOption::parse(options)?;
|
|
|
|
match option {
|
|
|
|
TcpOption::SackRange(slice) => {
|
|
|
|
return Ok(slice);
|
|
|
|
},
|
|
|
|
_ => {},
|
|
|
|
}
|
|
|
|
options = next_options;
|
|
|
|
}
|
|
|
|
Ok([None, None, None])
|
|
|
|
}
|
|
|
|
|
2016-12-19 05:42:44 +08:00
|
|
|
/// Validate the packet checksum.
|
|
|
|
///
|
|
|
|
/// # Panics
|
|
|
|
/// This function panics unless `src_addr` and `dst_addr` belong to the same family,
|
|
|
|
/// and that family is IPv4 or IPv6.
|
2017-06-24 23:26:15 +08:00
|
|
|
///
|
|
|
|
/// # Fuzzing
|
|
|
|
/// This function always returns `true` when fuzzing.
|
2016-12-20 21:54:11 +08:00
|
|
|
pub fn verify_checksum(&self, src_addr: &IpAddress, dst_addr: &IpAddress) -> bool {
|
2017-06-24 23:26:15 +08:00
|
|
|
if cfg!(fuzzing) { return true }
|
|
|
|
|
2016-12-19 05:42:44 +08:00
|
|
|
let data = self.buffer.as_ref();
|
|
|
|
checksum::combine(&[
|
2016-12-20 21:54:11 +08:00
|
|
|
checksum::pseudo_header(src_addr, dst_addr, IpProtocol::Tcp,
|
2016-12-19 05:42:44 +08:00
|
|
|
data.len() as u32),
|
|
|
|
checksum::data(data)
|
|
|
|
]) == !0
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a, T: AsRef<[u8]> + ?Sized> Packet<&'a T> {
|
2017-01-27 08:17:13 +08:00
|
|
|
/// Return a pointer to the options.
|
|
|
|
#[inline]
|
|
|
|
pub fn options(&self) -> &'a [u8] {
|
2017-06-24 20:02:17 +08:00
|
|
|
let header_len = self.header_len();
|
2017-01-27 08:17:13 +08:00
|
|
|
let data = self.buffer.as_ref();
|
2017-06-24 20:02:17 +08:00
|
|
|
&data[field::OPTIONS(header_len)]
|
2017-01-27 08:17:13 +08:00
|
|
|
}
|
|
|
|
|
2016-12-19 05:42:44 +08:00
|
|
|
/// Return a pointer to the payload.
|
2016-12-31 00:55:31 +08:00
|
|
|
#[inline]
|
2016-12-19 05:42:44 +08:00
|
|
|
pub fn payload(&self) -> &'a [u8] {
|
|
|
|
let header_len = self.header_len() as usize;
|
|
|
|
let data = self.buffer.as_ref();
|
|
|
|
&data[header_len..]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T: AsRef<[u8]> + AsMut<[u8]>> Packet<T> {
|
|
|
|
/// Set the source port field.
|
2016-12-31 00:55:31 +08:00
|
|
|
#[inline]
|
2016-12-19 05:42:44 +08:00
|
|
|
pub fn set_src_port(&mut self, value: u16) {
|
2017-09-25 08:55:54 +08:00
|
|
|
let data = self.buffer.as_mut();
|
2016-12-19 05:42:44 +08:00
|
|
|
NetworkEndian::write_u16(&mut data[field::SRC_PORT], value)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Set the destination port field.
|
2016-12-31 00:55:31 +08:00
|
|
|
#[inline]
|
2016-12-19 05:42:44 +08:00
|
|
|
pub fn set_dst_port(&mut self, value: u16) {
|
2017-09-25 08:55:54 +08:00
|
|
|
let data = self.buffer.as_mut();
|
2016-12-19 05:42:44 +08:00
|
|
|
NetworkEndian::write_u16(&mut data[field::DST_PORT], value)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Set the sequence number field.
|
2016-12-31 00:55:31 +08:00
|
|
|
#[inline]
|
2016-12-28 02:34:13 +08:00
|
|
|
pub fn set_seq_number(&mut self, value: SeqNumber) {
|
2017-09-25 08:55:54 +08:00
|
|
|
let data = self.buffer.as_mut();
|
2016-12-28 02:34:13 +08:00
|
|
|
NetworkEndian::write_i32(&mut data[field::SEQ_NUM], value.0)
|
2016-12-19 05:42:44 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Set the acknowledgement number field.
|
2016-12-31 00:55:31 +08:00
|
|
|
#[inline]
|
2016-12-28 02:34:13 +08:00
|
|
|
pub fn set_ack_number(&mut self, value: SeqNumber) {
|
2017-09-25 08:55:54 +08:00
|
|
|
let data = self.buffer.as_mut();
|
2016-12-28 02:34:13 +08:00
|
|
|
NetworkEndian::write_i32(&mut data[field::ACK_NUM], value.0)
|
2016-12-19 05:42:44 +08:00
|
|
|
}
|
|
|
|
|
2016-12-20 17:41:08 +08:00
|
|
|
/// Clear the entire flags field.
|
2016-12-31 00:55:31 +08:00
|
|
|
#[inline]
|
2016-12-20 17:41:08 +08:00
|
|
|
pub fn clear_flags(&mut self) {
|
|
|
|
let data = self.buffer.as_mut();
|
2016-12-20 20:52:33 +08:00
|
|
|
let raw = NetworkEndian::read_u16(&data[field::FLAGS]);
|
|
|
|
let raw = raw & !0x0fff;
|
|
|
|
NetworkEndian::write_u16(&mut data[field::FLAGS], raw)
|
2016-12-20 17:41:08 +08:00
|
|
|
}
|
|
|
|
|
2016-12-19 05:42:44 +08:00
|
|
|
/// Set the FIN flag.
|
2016-12-31 00:55:31 +08:00
|
|
|
#[inline]
|
2016-12-19 05:42:44 +08:00
|
|
|
pub fn set_fin(&mut self, value: bool) {
|
2017-09-25 08:55:54 +08:00
|
|
|
let data = self.buffer.as_mut();
|
2016-12-19 05:42:44 +08:00
|
|
|
let raw = NetworkEndian::read_u16(&data[field::FLAGS]);
|
|
|
|
let raw = if value { raw | field::FLG_FIN } else { raw & !field::FLG_FIN };
|
|
|
|
NetworkEndian::write_u16(&mut data[field::FLAGS], raw)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Set the SYN flag.
|
2016-12-31 00:55:31 +08:00
|
|
|
#[inline]
|
2016-12-19 05:42:44 +08:00
|
|
|
pub fn set_syn(&mut self, value: bool) {
|
2017-09-25 08:55:54 +08:00
|
|
|
let data = self.buffer.as_mut();
|
2016-12-19 05:42:44 +08:00
|
|
|
let raw = NetworkEndian::read_u16(&data[field::FLAGS]);
|
|
|
|
let raw = if value { raw | field::FLG_SYN } else { raw & !field::FLG_SYN };
|
|
|
|
NetworkEndian::write_u16(&mut data[field::FLAGS], raw)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Set the RST flag.
|
2016-12-31 00:55:31 +08:00
|
|
|
#[inline]
|
2016-12-19 05:42:44 +08:00
|
|
|
pub fn set_rst(&mut self, value: bool) {
|
2017-09-25 08:55:54 +08:00
|
|
|
let data = self.buffer.as_mut();
|
2016-12-19 05:42:44 +08:00
|
|
|
let raw = NetworkEndian::read_u16(&data[field::FLAGS]);
|
|
|
|
let raw = if value { raw | field::FLG_RST } else { raw & !field::FLG_RST };
|
|
|
|
NetworkEndian::write_u16(&mut data[field::FLAGS], raw)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Set the PSH flag.
|
2016-12-31 00:55:31 +08:00
|
|
|
#[inline]
|
2016-12-19 05:42:44 +08:00
|
|
|
pub fn set_psh(&mut self, value: bool) {
|
2017-09-25 08:55:54 +08:00
|
|
|
let data = self.buffer.as_mut();
|
2016-12-19 05:42:44 +08:00
|
|
|
let raw = NetworkEndian::read_u16(&data[field::FLAGS]);
|
|
|
|
let raw = if value { raw | field::FLG_PSH } else { raw & !field::FLG_PSH };
|
|
|
|
NetworkEndian::write_u16(&mut data[field::FLAGS], raw)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Set the ACK flag.
|
2016-12-31 00:55:31 +08:00
|
|
|
#[inline]
|
2016-12-19 05:42:44 +08:00
|
|
|
pub fn set_ack(&mut self, value: bool) {
|
2017-09-25 08:55:54 +08:00
|
|
|
let data = self.buffer.as_mut();
|
2016-12-19 05:42:44 +08:00
|
|
|
let raw = NetworkEndian::read_u16(&data[field::FLAGS]);
|
|
|
|
let raw = if value { raw | field::FLG_ACK } else { raw & !field::FLG_ACK };
|
|
|
|
NetworkEndian::write_u16(&mut data[field::FLAGS], raw)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Set the URG flag.
|
2016-12-31 00:55:31 +08:00
|
|
|
#[inline]
|
2016-12-19 05:42:44 +08:00
|
|
|
pub fn set_urg(&mut self, value: bool) {
|
2017-09-25 08:55:54 +08:00
|
|
|
let data = self.buffer.as_mut();
|
2016-12-19 05:42:44 +08:00
|
|
|
let raw = NetworkEndian::read_u16(&data[field::FLAGS]);
|
|
|
|
let raw = if value { raw | field::FLG_URG } else { raw & !field::FLG_URG };
|
|
|
|
NetworkEndian::write_u16(&mut data[field::FLAGS], raw)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Set the ECE flag.
|
2016-12-31 00:55:31 +08:00
|
|
|
#[inline]
|
2016-12-19 05:42:44 +08:00
|
|
|
pub fn set_ece(&mut self, value: bool) {
|
2017-09-25 08:55:54 +08:00
|
|
|
let data = self.buffer.as_mut();
|
2016-12-19 05:42:44 +08:00
|
|
|
let raw = NetworkEndian::read_u16(&data[field::FLAGS]);
|
|
|
|
let raw = if value { raw | field::FLG_ECE } else { raw & !field::FLG_ECE };
|
|
|
|
NetworkEndian::write_u16(&mut data[field::FLAGS], raw)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Set the CWR flag.
|
2016-12-31 00:55:31 +08:00
|
|
|
#[inline]
|
2016-12-19 05:42:44 +08:00
|
|
|
pub fn set_cwr(&mut self, value: bool) {
|
2017-09-25 08:55:54 +08:00
|
|
|
let data = self.buffer.as_mut();
|
2016-12-19 05:42:44 +08:00
|
|
|
let raw = NetworkEndian::read_u16(&data[field::FLAGS]);
|
|
|
|
let raw = if value { raw | field::FLG_CWR } else { raw & !field::FLG_CWR };
|
|
|
|
NetworkEndian::write_u16(&mut data[field::FLAGS], raw)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Set the NS flag.
|
2016-12-31 00:55:31 +08:00
|
|
|
#[inline]
|
2016-12-19 05:42:44 +08:00
|
|
|
pub fn set_ns(&mut self, value: bool) {
|
2017-09-25 08:55:54 +08:00
|
|
|
let data = self.buffer.as_mut();
|
2016-12-19 05:42:44 +08:00
|
|
|
let raw = NetworkEndian::read_u16(&data[field::FLAGS]);
|
|
|
|
let raw = if value { raw | field::FLG_NS } else { raw & !field::FLG_NS };
|
|
|
|
NetworkEndian::write_u16(&mut data[field::FLAGS], raw)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Set the header length, in octets.
|
2016-12-31 00:55:31 +08:00
|
|
|
#[inline]
|
2016-12-19 05:42:44 +08:00
|
|
|
pub fn set_header_len(&mut self, value: u8) {
|
2017-09-25 08:55:54 +08:00
|
|
|
let data = self.buffer.as_mut();
|
2016-12-19 05:42:44 +08:00
|
|
|
let raw = NetworkEndian::read_u16(&data[field::FLAGS]);
|
|
|
|
let raw = (raw & !0xf000) | ((value as u16) / 4) << 12;
|
|
|
|
NetworkEndian::write_u16(&mut data[field::FLAGS], raw)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Return the window size field.
|
2016-12-31 00:55:31 +08:00
|
|
|
#[inline]
|
2016-12-19 05:42:44 +08:00
|
|
|
pub fn set_window_len(&mut self, value: u16) {
|
2017-09-25 08:55:54 +08:00
|
|
|
let data = self.buffer.as_mut();
|
2016-12-19 05:42:44 +08:00
|
|
|
NetworkEndian::write_u16(&mut data[field::WIN_SIZE], value)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Set the checksum field.
|
2016-12-31 00:55:31 +08:00
|
|
|
#[inline]
|
2016-12-19 05:42:44 +08:00
|
|
|
pub fn set_checksum(&mut self, value: u16) {
|
2017-09-25 08:55:54 +08:00
|
|
|
let data = self.buffer.as_mut();
|
2016-12-19 05:42:44 +08:00
|
|
|
NetworkEndian::write_u16(&mut data[field::CHECKSUM], value)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Set the urgent pointer field.
|
2016-12-31 00:55:31 +08:00
|
|
|
#[inline]
|
2016-12-19 05:42:44 +08:00
|
|
|
pub fn set_urgent_at(&mut self, value: u16) {
|
2017-09-25 08:55:54 +08:00
|
|
|
let data = self.buffer.as_mut();
|
2016-12-19 05:42:44 +08:00
|
|
|
NetworkEndian::write_u16(&mut data[field::URGENT], value)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Compute and fill in the header checksum.
|
|
|
|
///
|
|
|
|
/// # Panics
|
|
|
|
/// This function panics unless `src_addr` and `dst_addr` belong to the same family,
|
|
|
|
/// and that family is IPv4 or IPv6.
|
2016-12-20 21:54:11 +08:00
|
|
|
pub fn fill_checksum(&mut self, src_addr: &IpAddress, dst_addr: &IpAddress) {
|
2016-12-19 05:42:44 +08:00
|
|
|
self.set_checksum(0);
|
|
|
|
let checksum = {
|
|
|
|
let data = self.buffer.as_ref();
|
|
|
|
!checksum::combine(&[
|
2016-12-20 21:54:11 +08:00
|
|
|
checksum::pseudo_header(src_addr, dst_addr, IpProtocol::Tcp,
|
2016-12-19 05:42:44 +08:00
|
|
|
data.len() as u32),
|
|
|
|
checksum::data(data)
|
|
|
|
])
|
|
|
|
};
|
|
|
|
self.set_checksum(checksum)
|
|
|
|
}
|
|
|
|
|
2017-01-27 08:17:13 +08:00
|
|
|
/// Return a pointer to the options.
|
|
|
|
#[inline]
|
|
|
|
pub fn options_mut(&mut self) -> &mut [u8] {
|
2017-06-24 20:02:17 +08:00
|
|
|
let header_len = self.header_len();
|
2017-01-27 08:17:13 +08:00
|
|
|
let data = self.buffer.as_mut();
|
2017-06-24 20:02:17 +08:00
|
|
|
&mut data[field::OPTIONS(header_len)]
|
2017-01-27 08:17:13 +08:00
|
|
|
}
|
|
|
|
|
2016-12-19 05:42:44 +08:00
|
|
|
/// Return a mutable pointer to the payload data.
|
2016-12-31 00:55:31 +08:00
|
|
|
#[inline]
|
2016-12-19 05:42:44 +08:00
|
|
|
pub fn payload_mut(&mut self) -> &mut [u8] {
|
|
|
|
let header_len = self.header_len() as usize;
|
2017-09-25 08:55:54 +08:00
|
|
|
let data = self.buffer.as_mut();
|
2016-12-19 05:42:44 +08:00
|
|
|
&mut data[header_len..]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-02-08 16:54:50 +08:00
|
|
|
impl<T: AsRef<[u8]>> AsRef<[u8]> for Packet<T> {
|
|
|
|
fn as_ref(&self) -> &[u8] {
|
|
|
|
self.buffer.as_ref()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-01-27 08:17:13 +08:00
|
|
|
/// A representation of a single TCP option.
|
|
|
|
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
|
|
|
|
pub enum TcpOption<'a> {
|
|
|
|
EndOfList,
|
|
|
|
NoOperation,
|
|
|
|
MaxSegmentSize(u16),
|
|
|
|
WindowScale(u8),
|
2019-01-01 04:45:20 +08:00
|
|
|
SackPermitted,
|
|
|
|
SackRange([Option<(u32, u32)>; 3]),
|
2017-01-27 08:17:13 +08:00
|
|
|
Unknown { kind: u8, data: &'a [u8] }
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a> TcpOption<'a> {
|
2017-07-27 21:51:02 +08:00
|
|
|
pub fn parse(buffer: &'a [u8]) -> Result<(&'a [u8], TcpOption<'a>)> {
|
2017-01-27 08:17:13 +08:00
|
|
|
let (length, option);
|
|
|
|
match *buffer.get(0).ok_or(Error::Truncated)? {
|
|
|
|
field::OPT_END => {
|
|
|
|
length = 1;
|
|
|
|
option = TcpOption::EndOfList;
|
|
|
|
}
|
|
|
|
field::OPT_NOP => {
|
|
|
|
length = 1;
|
|
|
|
option = TcpOption::NoOperation;
|
|
|
|
}
|
|
|
|
kind => {
|
|
|
|
length = *buffer.get(1).ok_or(Error::Truncated)? as usize;
|
2017-06-24 19:25:48 +08:00
|
|
|
let data = buffer.get(2..length).ok_or(Error::Truncated)?;
|
2017-01-27 08:17:13 +08:00
|
|
|
match (kind, length) {
|
|
|
|
(field::OPT_END, _) |
|
|
|
|
(field::OPT_NOP, _) =>
|
|
|
|
unreachable!(),
|
|
|
|
(field::OPT_MSS, 4) =>
|
|
|
|
option = TcpOption::MaxSegmentSize(NetworkEndian::read_u16(data)),
|
|
|
|
(field::OPT_MSS, _) =>
|
|
|
|
return Err(Error::Malformed),
|
|
|
|
(field::OPT_WS, 3) =>
|
|
|
|
option = TcpOption::WindowScale(data[0]),
|
|
|
|
(field::OPT_WS, _) =>
|
|
|
|
return Err(Error::Malformed),
|
2019-01-01 04:45:20 +08:00
|
|
|
(field::OPT_SACKPERM, 2) =>
|
|
|
|
option = TcpOption::SackPermitted,
|
|
|
|
(field::OPT_SACKPERM, _) =>
|
|
|
|
return Err(Error::Malformed),
|
|
|
|
(field::OPT_SACKRNG, n) => {
|
|
|
|
if n < 10 || (n-2) % 8 != 0 {
|
|
|
|
return Err(Error::Malformed)
|
|
|
|
}
|
|
|
|
if n > 26 {
|
|
|
|
// It's possible for a remote to send 4 SACK blocks, but extremely rare.
|
|
|
|
// Better to "lose" that 4th block and save the extra RAM and CPU
|
|
|
|
// cycles in the vastly more common case.
|
|
|
|
//
|
|
|
|
// RFC 2018: SACK option that specifies n blocks will have a length of
|
|
|
|
// 8*n+2 bytes, so the 40 bytes available for TCP options can specify a
|
|
|
|
// maximum of 4 blocks. It is expected that SACK will often be used in
|
|
|
|
// conjunction with the Timestamp option used for RTTM [...] thus a
|
|
|
|
// maximum of 3 SACK blocks will be allowed in this case.
|
|
|
|
net_debug!("sACK with >3 blocks, truncating to 3");
|
|
|
|
}
|
|
|
|
let mut sack_ranges: [Option<(u32, u32)>; 3] = [None; 3];
|
|
|
|
|
|
|
|
// RFC 2018: Each contiguous block of data queued at the data receiver is
|
|
|
|
// defined in the SACK option by two 32-bit unsigned integers in network
|
|
|
|
// byte order[...]
|
|
|
|
sack_ranges.iter_mut().enumerate().for_each(|(i, nmut)| {
|
|
|
|
let left = i * 8;
|
|
|
|
*nmut = if left < data.len() {
|
|
|
|
let mid = left + 4;
|
|
|
|
let right = mid + 4;
|
|
|
|
let range_left = NetworkEndian::read_u32(
|
|
|
|
&data[left..mid]);
|
|
|
|
let range_right = NetworkEndian::read_u32(
|
|
|
|
&data[mid..right]);
|
|
|
|
Some((range_left, range_right))
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
};
|
|
|
|
});
|
|
|
|
option = TcpOption::SackRange(sack_ranges);
|
|
|
|
},
|
2017-01-27 08:17:13 +08:00
|
|
|
(_, _) =>
|
|
|
|
option = TcpOption::Unknown { kind: kind, data: data }
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Ok((&buffer[length..], option))
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn buffer_len(&self) -> usize {
|
2020-12-26 16:28:05 +08:00
|
|
|
match *self {
|
|
|
|
TcpOption::EndOfList => 1,
|
|
|
|
TcpOption::NoOperation => 1,
|
|
|
|
TcpOption::MaxSegmentSize(_) => 4,
|
|
|
|
TcpOption::WindowScale(_) => 3,
|
|
|
|
TcpOption::SackPermitted => 2,
|
|
|
|
TcpOption::SackRange(s) => s.iter().filter(|s| s.is_some()).count() * 8 + 2,
|
|
|
|
TcpOption::Unknown { data, .. } => 2 + data.len()
|
2017-01-27 08:17:13 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn emit<'b>(&self, buffer: &'b mut [u8]) -> &'b mut [u8] {
|
|
|
|
let length;
|
2020-12-26 16:28:05 +08:00
|
|
|
match *self {
|
|
|
|
TcpOption::EndOfList => {
|
2017-01-27 08:17:13 +08:00
|
|
|
length = 1;
|
2018-06-28 16:44:18 +08:00
|
|
|
// There may be padding space which also should be initialized.
|
|
|
|
for p in buffer.iter_mut() {
|
|
|
|
*p = field::OPT_END;
|
|
|
|
}
|
2017-01-27 08:17:13 +08:00
|
|
|
}
|
2020-12-26 16:28:05 +08:00
|
|
|
TcpOption::NoOperation => {
|
2017-01-27 08:17:13 +08:00
|
|
|
length = 1;
|
|
|
|
buffer[0] = field::OPT_NOP;
|
|
|
|
}
|
|
|
|
_ => {
|
|
|
|
length = self.buffer_len();
|
|
|
|
buffer[1] = length as u8;
|
|
|
|
match self {
|
|
|
|
&TcpOption::EndOfList |
|
|
|
|
&TcpOption::NoOperation =>
|
|
|
|
unreachable!(),
|
|
|
|
&TcpOption::MaxSegmentSize(value) => {
|
|
|
|
buffer[0] = field::OPT_MSS;
|
|
|
|
NetworkEndian::write_u16(&mut buffer[2..], value)
|
|
|
|
}
|
|
|
|
&TcpOption::WindowScale(value) => {
|
|
|
|
buffer[0] = field::OPT_WS;
|
|
|
|
buffer[2] = value;
|
|
|
|
}
|
2019-01-01 04:45:20 +08:00
|
|
|
&TcpOption::SackPermitted => {
|
|
|
|
buffer[0] = field::OPT_SACKPERM;
|
|
|
|
}
|
|
|
|
&TcpOption::SackRange(slice) => {
|
|
|
|
buffer[0] = field::OPT_SACKRNG;
|
|
|
|
slice.iter().filter(|s| s.is_some()).enumerate().for_each(|(i, s)| {
|
|
|
|
let (first, second) = *s.as_ref().unwrap();
|
|
|
|
let pos = i * 8 + 2;
|
|
|
|
NetworkEndian::write_u32(&mut buffer[pos..], first);
|
|
|
|
NetworkEndian::write_u32(&mut buffer[pos+4..], second);
|
|
|
|
});
|
|
|
|
}
|
2017-01-27 08:17:13 +08:00
|
|
|
&TcpOption::Unknown { kind, data: provided } => {
|
|
|
|
buffer[0] = kind;
|
|
|
|
buffer[2..].copy_from_slice(provided)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
&mut buffer[length..]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
Radically simplify and optimize TCP packet dispatch.
This commit completely reworks packet dispatch in TCP sockets,
and brings significant improvements to processing as well.
In particular:
* Challenge ACKs now do not reset retransmit timer; instead,
TcpSocket::process directly returns a TcpRepr without altering
any internal state at all.
* Retransmit and close (aka TIME-WAIT) timers are unified
and restructured into a enum that actually matches semantics
of the timers.
* If a packet cannot be emitted, no internal state is changed.
* The dispatch of RST packets in case of connection abort
is brought in line with dispatch of all other packets.
* Packet dispatch now follows a series of steps with clean
separation of concerns, like packet processing:
1. If we should retransmit, update state to assume that
all in-flight packets are lost.
2. Prepare the packet that would be sent next, considering
the in-flight packets, if any.
3. Check if the packet contains anything new, or it's the same
as the one already in flight. If it is, bail.
4. Finalize and try to actually transmit the packet.
If we can't do that, bail.
5. Update the internal state to reflect that the packet
we've just sent is in flight.
2017-08-25 10:59:51 +08:00
|
|
|
/// The possible control flags of a Transmission Control Protocol packet.
|
2016-12-25 19:09:50 +08:00
|
|
|
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
|
|
|
|
pub enum Control {
|
|
|
|
None,
|
2017-08-25 14:03:54 +08:00
|
|
|
Psh,
|
2016-12-25 19:09:50 +08:00
|
|
|
Syn,
|
|
|
|
Fin,
|
|
|
|
Rst
|
|
|
|
}
|
|
|
|
|
Radically simplify and optimize TCP packet dispatch.
This commit completely reworks packet dispatch in TCP sockets,
and brings significant improvements to processing as well.
In particular:
* Challenge ACKs now do not reset retransmit timer; instead,
TcpSocket::process directly returns a TcpRepr without altering
any internal state at all.
* Retransmit and close (aka TIME-WAIT) timers are unified
and restructured into a enum that actually matches semantics
of the timers.
* If a packet cannot be emitted, no internal state is changed.
* The dispatch of RST packets in case of connection abort
is brought in line with dispatch of all other packets.
* Packet dispatch now follows a series of steps with clean
separation of concerns, like packet processing:
1. If we should retransmit, update state to assume that
all in-flight packets are lost.
2. Prepare the packet that would be sent next, considering
the in-flight packets, if any.
3. Check if the packet contains anything new, or it's the same
as the one already in flight. If it is, bail.
4. Finalize and try to actually transmit the packet.
If we can't do that, bail.
5. Update the internal state to reflect that the packet
we've just sent is in flight.
2017-08-25 10:59:51 +08:00
|
|
|
impl Control {
|
|
|
|
/// Return the length of a control flag, in terms of sequence space.
|
|
|
|
pub fn len(self) -> usize {
|
|
|
|
match self {
|
|
|
|
Control::Syn | Control::Fin => 1,
|
2017-08-25 14:03:54 +08:00
|
|
|
_ => 0
|
Radically simplify and optimize TCP packet dispatch.
This commit completely reworks packet dispatch in TCP sockets,
and brings significant improvements to processing as well.
In particular:
* Challenge ACKs now do not reset retransmit timer; instead,
TcpSocket::process directly returns a TcpRepr without altering
any internal state at all.
* Retransmit and close (aka TIME-WAIT) timers are unified
and restructured into a enum that actually matches semantics
of the timers.
* If a packet cannot be emitted, no internal state is changed.
* The dispatch of RST packets in case of connection abort
is brought in line with dispatch of all other packets.
* Packet dispatch now follows a series of steps with clean
separation of concerns, like packet processing:
1. If we should retransmit, update state to assume that
all in-flight packets are lost.
2. Prepare the packet that would be sent next, considering
the in-flight packets, if any.
3. Check if the packet contains anything new, or it's the same
as the one already in flight. If it is, bail.
4. Finalize and try to actually transmit the packet.
If we can't do that, bail.
5. Update the internal state to reflect that the packet
we've just sent is in flight.
2017-08-25 10:59:51 +08:00
|
|
|
}
|
|
|
|
}
|
2017-09-22 14:29:25 +08:00
|
|
|
|
|
|
|
/// Turn the PSH flag into no flag, and keep the rest as-is.
|
|
|
|
pub fn quash_psh(self) -> Control {
|
|
|
|
match self {
|
|
|
|
Control::Psh => Control::None,
|
|
|
|
_ => self
|
|
|
|
}
|
|
|
|
}
|
Radically simplify and optimize TCP packet dispatch.
This commit completely reworks packet dispatch in TCP sockets,
and brings significant improvements to processing as well.
In particular:
* Challenge ACKs now do not reset retransmit timer; instead,
TcpSocket::process directly returns a TcpRepr without altering
any internal state at all.
* Retransmit and close (aka TIME-WAIT) timers are unified
and restructured into a enum that actually matches semantics
of the timers.
* If a packet cannot be emitted, no internal state is changed.
* The dispatch of RST packets in case of connection abort
is brought in line with dispatch of all other packets.
* Packet dispatch now follows a series of steps with clean
separation of concerns, like packet processing:
1. If we should retransmit, update state to assume that
all in-flight packets are lost.
2. Prepare the packet that would be sent next, considering
the in-flight packets, if any.
3. Check if the packet contains anything new, or it's the same
as the one already in flight. If it is, bail.
4. Finalize and try to actually transmit the packet.
If we can't do that, bail.
5. Update the internal state to reflect that the packet
we've just sent is in flight.
2017-08-25 10:59:51 +08:00
|
|
|
}
|
|
|
|
|
2016-12-20 20:52:33 +08:00
|
|
|
/// A high-level representation of a Transmission Control Protocol packet.
|
|
|
|
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
|
|
|
|
pub struct Repr<'a> {
|
2017-01-27 09:09:34 +08:00
|
|
|
pub src_port: u16,
|
|
|
|
pub dst_port: u16,
|
|
|
|
pub control: Control,
|
|
|
|
pub seq_number: SeqNumber,
|
|
|
|
pub ack_number: Option<SeqNumber>,
|
|
|
|
pub window_len: u16,
|
2018-06-24 22:35:29 +08:00
|
|
|
pub window_scale: Option<u8>,
|
2017-01-27 09:09:34 +08:00
|
|
|
pub max_seg_size: Option<u16>,
|
2019-01-01 04:45:20 +08:00
|
|
|
pub sack_permitted: bool,
|
|
|
|
pub sack_ranges: [Option<(u32, u32)>; 3],
|
2017-01-27 09:09:34 +08:00
|
|
|
pub payload: &'a [u8]
|
2016-12-20 20:52:33 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a> Repr<'a> {
|
|
|
|
/// Parse a Transmission Control Protocol packet and return a high-level representation.
|
2017-10-03 05:51:43 +08:00
|
|
|
pub fn parse<T>(packet: &Packet<&'a T>, src_addr: &IpAddress, dst_addr: &IpAddress,
|
|
|
|
checksum_caps: &ChecksumCapabilities) -> Result<Repr<'a>>
|
|
|
|
where T: AsRef<[u8]> + ?Sized {
|
2016-12-20 20:52:33 +08:00
|
|
|
// Source and destination ports must be present.
|
|
|
|
if packet.src_port() == 0 { return Err(Error::Malformed) }
|
|
|
|
if packet.dst_port() == 0 { return Err(Error::Malformed) }
|
2017-10-03 05:51:43 +08:00
|
|
|
// Valid checksum is expected.
|
2018-05-28 08:32:50 +08:00
|
|
|
if checksum_caps.tcp.rx() && !packet.verify_checksum(src_addr, dst_addr) {
|
2017-10-03 05:51:43 +08:00
|
|
|
return Err(Error::Checksum)
|
2017-10-02 18:47:51 +08:00
|
|
|
}
|
2016-12-20 20:52:33 +08:00
|
|
|
|
|
|
|
let control =
|
2017-08-25 14:03:54 +08:00
|
|
|
match (packet.syn(), packet.fin(), packet.rst(), packet.psh()) {
|
|
|
|
(false, false, false, false) => Control::None,
|
|
|
|
(false, false, false, true) => Control::Psh,
|
|
|
|
(true, false, false, _) => Control::Syn,
|
|
|
|
(false, true, false, _) => Control::Fin,
|
|
|
|
(false, false, true , _) => Control::Rst,
|
2016-12-20 20:52:33 +08:00
|
|
|
_ => return Err(Error::Malformed)
|
|
|
|
};
|
|
|
|
let ack_number =
|
|
|
|
match packet.ack() {
|
|
|
|
true => Some(packet.ack_number()),
|
|
|
|
false => None
|
|
|
|
};
|
|
|
|
// The PSH flag is ignored.
|
|
|
|
// The URG flag and the urgent field is ignored. This behavior is standards-compliant,
|
|
|
|
// however, most deployed systems (e.g. Linux) are *not* standards-compliant, and would
|
|
|
|
// cut the byte at the urgent pointer from the stream.
|
|
|
|
|
2017-01-27 09:09:34 +08:00
|
|
|
let mut max_seg_size = None;
|
2018-06-24 22:35:29 +08:00
|
|
|
let mut window_scale = None;
|
2017-01-27 09:09:34 +08:00
|
|
|
let mut options = packet.options();
|
2019-01-01 04:45:20 +08:00
|
|
|
let mut sack_permitted = false;
|
|
|
|
let mut sack_ranges = [None, None, None];
|
2017-01-27 09:09:34 +08:00
|
|
|
while options.len() > 0 {
|
|
|
|
let (next_options, option) = TcpOption::parse(options)?;
|
|
|
|
match option {
|
|
|
|
TcpOption::EndOfList => break,
|
|
|
|
TcpOption::NoOperation => (),
|
|
|
|
TcpOption::MaxSegmentSize(value) =>
|
|
|
|
max_seg_size = Some(value),
|
2018-06-24 22:35:29 +08:00
|
|
|
TcpOption::WindowScale(value) => {
|
|
|
|
// RFC 1323: Thus, the shift count must be limited to 14 (which allows windows
|
|
|
|
// of 2**30 = 1 Gbyte). If a Window Scale option is received with a shift.cnt
|
|
|
|
// value exceeding 14, the TCP should log the error but use 14 instead of the
|
|
|
|
// specified value.
|
|
|
|
window_scale = if value > 14 {
|
|
|
|
net_debug!("{}:{}:{}:{}: parsed window scaling factor >14, setting to 14", src_addr, packet.src_port(), dst_addr, packet.dst_port());
|
|
|
|
Some(14)
|
|
|
|
} else {
|
|
|
|
Some(value)
|
|
|
|
};
|
2019-01-01 04:45:20 +08:00
|
|
|
},
|
|
|
|
TcpOption::SackPermitted =>
|
|
|
|
sack_permitted = true,
|
|
|
|
TcpOption::SackRange(slice) =>
|
|
|
|
sack_ranges = slice,
|
2018-06-24 22:35:29 +08:00
|
|
|
_ => (),
|
2017-01-27 09:09:34 +08:00
|
|
|
}
|
|
|
|
options = next_options;
|
|
|
|
}
|
|
|
|
|
2016-12-20 20:52:33 +08:00
|
|
|
Ok(Repr {
|
2017-01-27 09:09:34 +08:00
|
|
|
src_port: packet.src_port(),
|
|
|
|
dst_port: packet.dst_port(),
|
|
|
|
control: control,
|
|
|
|
seq_number: packet.seq_number(),
|
|
|
|
ack_number: ack_number,
|
|
|
|
window_len: packet.window_len(),
|
2018-06-24 22:35:29 +08:00
|
|
|
window_scale: window_scale,
|
2017-01-27 09:09:34 +08:00
|
|
|
max_seg_size: max_seg_size,
|
2019-01-01 04:45:20 +08:00
|
|
|
sack_permitted: sack_permitted,
|
|
|
|
sack_ranges: sack_ranges,
|
2017-01-27 09:09:34 +08:00
|
|
|
payload: packet.payload()
|
2016-12-20 20:52:33 +08:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2017-01-27 09:09:34 +08:00
|
|
|
/// Return the length of a header that will be emitted from this high-level representation.
|
2018-06-24 22:35:29 +08:00
|
|
|
///
|
|
|
|
/// This should be used for buffer space calculations.
|
2018-06-28 16:44:18 +08:00
|
|
|
/// The TCP header length is a multiple of 4.
|
2017-01-27 09:09:34 +08:00
|
|
|
pub fn header_len(&self) -> usize {
|
|
|
|
let mut length = field::URGENT.end;
|
|
|
|
if self.max_seg_size.is_some() {
|
|
|
|
length += 4
|
|
|
|
}
|
2018-06-24 22:35:29 +08:00
|
|
|
if self.window_scale.is_some() {
|
|
|
|
length += 3
|
|
|
|
}
|
2019-01-01 04:45:20 +08:00
|
|
|
if self.sack_permitted {
|
|
|
|
length += 2;
|
|
|
|
}
|
|
|
|
let sack_range_len: usize = self.sack_ranges.iter().map(
|
|
|
|
|o| o.map(|_| 8).unwrap_or(0)
|
|
|
|
).sum();
|
|
|
|
if sack_range_len > 0 {
|
|
|
|
length += sack_range_len + 2;
|
|
|
|
}
|
2018-06-28 16:44:18 +08:00
|
|
|
if length % 4 != 0 {
|
|
|
|
length += 4 - length % 4;
|
|
|
|
}
|
2017-01-27 09:09:34 +08:00
|
|
|
length
|
|
|
|
}
|
|
|
|
|
2018-06-24 22:35:29 +08:00
|
|
|
/// Return the length of the header for the TCP protocol.
|
|
|
|
///
|
|
|
|
/// Per RFC 6691, this should be used for MSS calculations. It may be smaller than the buffer
|
|
|
|
/// space required to accomodate this packet's data.
|
|
|
|
pub fn mss_header_len(&self) -> usize {
|
|
|
|
field::URGENT.end
|
|
|
|
}
|
|
|
|
|
2016-12-20 20:52:33 +08:00
|
|
|
/// Return the length of a packet that will be emitted from this high-level representation.
|
|
|
|
pub fn buffer_len(&self) -> usize {
|
2017-01-27 09:09:34 +08:00
|
|
|
self.header_len() + self.payload.len()
|
2016-12-20 20:52:33 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Emit a high-level representation into a Transmission Control Protocol packet.
|
2017-10-03 05:51:43 +08:00
|
|
|
pub fn emit<T>(&self, packet: &mut Packet<&mut T>, src_addr: &IpAddress, dst_addr: &IpAddress,
|
|
|
|
checksum_caps: &ChecksumCapabilities)
|
2017-08-23 06:32:05 +08:00
|
|
|
where T: AsRef<[u8]> + AsMut<[u8]> + ?Sized {
|
2016-12-20 20:52:33 +08:00
|
|
|
packet.set_src_port(self.src_port);
|
|
|
|
packet.set_dst_port(self.dst_port);
|
|
|
|
packet.set_seq_number(self.seq_number);
|
2016-12-28 02:34:13 +08:00
|
|
|
packet.set_ack_number(self.ack_number.unwrap_or(SeqNumber(0)));
|
2016-12-20 20:52:33 +08:00
|
|
|
packet.set_window_len(self.window_len);
|
2017-01-27 09:09:34 +08:00
|
|
|
packet.set_header_len(self.header_len() as u8);
|
2016-12-20 20:52:33 +08:00
|
|
|
packet.clear_flags();
|
|
|
|
match self.control {
|
|
|
|
Control::None => (),
|
2017-08-25 14:03:54 +08:00
|
|
|
Control::Psh => packet.set_psh(true),
|
2016-12-20 20:52:33 +08:00
|
|
|
Control::Syn => packet.set_syn(true),
|
|
|
|
Control::Fin => packet.set_fin(true),
|
|
|
|
Control::Rst => packet.set_rst(true)
|
|
|
|
}
|
2016-12-21 03:18:35 +08:00
|
|
|
packet.set_ack(self.ack_number.is_some());
|
2017-01-27 09:09:34 +08:00
|
|
|
{
|
|
|
|
let mut options = packet.options_mut();
|
|
|
|
if let Some(value) = self.max_seg_size {
|
|
|
|
let tmp = options; options = TcpOption::MaxSegmentSize(value).emit(tmp);
|
|
|
|
}
|
2019-11-02 06:04:19 +08:00
|
|
|
if let Some(value) = self.window_scale {
|
|
|
|
let tmp = options; options = TcpOption::WindowScale(value).emit(tmp);
|
|
|
|
}
|
2019-01-01 04:45:20 +08:00
|
|
|
if self.sack_permitted {
|
|
|
|
let tmp = options; options = TcpOption::SackPermitted.emit(tmp);
|
|
|
|
} else if self.ack_number.is_some() && self.sack_ranges.iter().any(|s| s.is_some()) {
|
|
|
|
let tmp = options; options = TcpOption::SackRange(self.sack_ranges).emit(tmp);
|
|
|
|
}
|
|
|
|
|
2017-01-27 09:09:34 +08:00
|
|
|
if options.len() > 0 {
|
|
|
|
TcpOption::EndOfList.emit(options);
|
|
|
|
}
|
|
|
|
}
|
2017-06-26 11:44:36 +08:00
|
|
|
packet.set_urgent_at(0);
|
2018-09-16 04:09:47 +08:00
|
|
|
packet.payload_mut()[..self.payload.len()].copy_from_slice(self.payload);
|
2017-10-03 05:51:43 +08:00
|
|
|
|
2018-05-28 08:32:50 +08:00
|
|
|
if checksum_caps.tcp.tx() {
|
2017-10-02 18:47:51 +08:00
|
|
|
packet.fill_checksum(src_addr, dst_addr)
|
|
|
|
} else {
|
2018-01-27 01:28:52 +08:00
|
|
|
// make sure we get a consistently zeroed checksum,
|
|
|
|
// since implementations might rely on it
|
2017-10-02 18:47:51 +08:00
|
|
|
packet.set_checksum(0);
|
|
|
|
}
|
2016-12-20 20:52:33 +08:00
|
|
|
}
|
2017-08-23 06:32:05 +08:00
|
|
|
|
|
|
|
/// Return the length of the segment, in terms of sequence space.
|
|
|
|
pub fn segment_len(&self) -> usize {
|
Radically simplify and optimize TCP packet dispatch.
This commit completely reworks packet dispatch in TCP sockets,
and brings significant improvements to processing as well.
In particular:
* Challenge ACKs now do not reset retransmit timer; instead,
TcpSocket::process directly returns a TcpRepr without altering
any internal state at all.
* Retransmit and close (aka TIME-WAIT) timers are unified
and restructured into a enum that actually matches semantics
of the timers.
* If a packet cannot be emitted, no internal state is changed.
* The dispatch of RST packets in case of connection abort
is brought in line with dispatch of all other packets.
* Packet dispatch now follows a series of steps with clean
separation of concerns, like packet processing:
1. If we should retransmit, update state to assume that
all in-flight packets are lost.
2. Prepare the packet that would be sent next, considering
the in-flight packets, if any.
3. Check if the packet contains anything new, or it's the same
as the one already in flight. If it is, bail.
4. Finalize and try to actually transmit the packet.
If we can't do that, bail.
5. Update the internal state to reflect that the packet
we've just sent is in flight.
2017-08-25 10:59:51 +08:00
|
|
|
self.payload.len() + self.control.len()
|
2017-08-23 06:32:05 +08:00
|
|
|
}
|
2017-09-18 19:05:40 +08:00
|
|
|
|
|
|
|
/// Return whether the segment has no flags set (except PSH) and no data.
|
|
|
|
pub fn is_empty(&self) -> bool {
|
|
|
|
match self.control {
|
|
|
|
_ if self.payload.len() != 0 => false,
|
|
|
|
Control::Syn | Control::Fin | Control::Rst => false,
|
|
|
|
Control::None | Control::Psh => true
|
|
|
|
}
|
|
|
|
}
|
2016-12-20 20:52:33 +08:00
|
|
|
}
|
|
|
|
|
2016-12-20 21:16:29 +08:00
|
|
|
impl<'a, T: AsRef<[u8]> + ?Sized> fmt::Display for Packet<&'a T> {
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
|
|
// Cannot use Repr::parse because we don't have the IP addresses.
|
2017-06-25 00:34:32 +08:00
|
|
|
write!(f, "TCP src={} dst={}",
|
|
|
|
self.src_port(), self.dst_port())?;
|
|
|
|
if self.syn() { write!(f, " syn")? }
|
|
|
|
if self.fin() { write!(f, " fin")? }
|
|
|
|
if self.rst() { write!(f, " rst")? }
|
|
|
|
if self.psh() { write!(f, " psh")? }
|
|
|
|
if self.ece() { write!(f, " ece")? }
|
|
|
|
if self.cwr() { write!(f, " cwr")? }
|
|
|
|
if self.ns() { write!(f, " ns" )? }
|
|
|
|
write!(f, " seq={}", self.seq_number())?;
|
2016-12-20 21:16:29 +08:00
|
|
|
if self.ack() {
|
2017-06-25 00:34:32 +08:00
|
|
|
write!(f, " ack={}", self.ack_number())?;
|
2016-12-20 21:16:29 +08:00
|
|
|
}
|
2017-06-25 00:34:32 +08:00
|
|
|
write!(f, " win={}", self.window_len())?;
|
2016-12-20 21:16:29 +08:00
|
|
|
if self.urg() {
|
2017-06-25 00:34:32 +08:00
|
|
|
write!(f, " urg={}", self.urgent_at())?;
|
2016-12-20 21:16:29 +08:00
|
|
|
}
|
2017-06-25 00:34:32 +08:00
|
|
|
write!(f, " len={}", self.payload().len())?;
|
2017-06-24 19:23:27 +08:00
|
|
|
|
2017-01-27 09:09:34 +08:00
|
|
|
let mut options = self.options();
|
|
|
|
while options.len() > 0 {
|
|
|
|
let (next_options, option) =
|
|
|
|
match TcpOption::parse(options) {
|
|
|
|
Ok(res) => res,
|
|
|
|
Err(err) => return write!(f, " ({})", err)
|
|
|
|
};
|
|
|
|
match option {
|
|
|
|
TcpOption::EndOfList => break,
|
|
|
|
TcpOption::NoOperation => (),
|
|
|
|
TcpOption::MaxSegmentSize(value) =>
|
2017-06-25 00:34:32 +08:00
|
|
|
write!(f, " mss={}", value)?,
|
2017-01-27 09:09:34 +08:00
|
|
|
TcpOption::WindowScale(value) =>
|
2017-06-25 00:34:32 +08:00
|
|
|
write!(f, " ws={}", value)?,
|
2019-01-01 04:45:20 +08:00
|
|
|
TcpOption::SackPermitted =>
|
|
|
|
write!(f, " sACK")?,
|
|
|
|
TcpOption::SackRange(slice) =>
|
|
|
|
write!(f, " sACKr{:?}", slice)?, // debug print conveniently includes the []s
|
2017-01-27 09:09:34 +08:00
|
|
|
TcpOption::Unknown { kind, .. } =>
|
2017-06-25 00:34:32 +08:00
|
|
|
write!(f, " opt({})", kind)?,
|
2017-01-27 09:09:34 +08:00
|
|
|
}
|
|
|
|
options = next_options;
|
|
|
|
}
|
2016-12-20 21:16:29 +08:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a> fmt::Display for Repr<'a> {
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
2017-06-25 00:34:32 +08:00
|
|
|
write!(f, "TCP src={} dst={}",
|
|
|
|
self.src_port, self.dst_port)?;
|
2016-12-20 21:16:29 +08:00
|
|
|
match self.control {
|
2017-06-25 00:34:32 +08:00
|
|
|
Control::Syn => write!(f, " syn")?,
|
|
|
|
Control::Fin => write!(f, " fin")?,
|
|
|
|
Control::Rst => write!(f, " rst")?,
|
2017-08-25 14:03:54 +08:00
|
|
|
Control::Psh => write!(f, " psh")?,
|
2016-12-20 21:16:29 +08:00
|
|
|
Control::None => ()
|
|
|
|
}
|
2017-06-25 00:34:32 +08:00
|
|
|
write!(f, " seq={}", self.seq_number)?;
|
2016-12-20 21:16:29 +08:00
|
|
|
if let Some(ack_number) = self.ack_number {
|
2017-06-25 00:34:32 +08:00
|
|
|
write!(f, " ack={}", ack_number)?;
|
2016-12-20 21:16:29 +08:00
|
|
|
}
|
2017-06-25 00:34:32 +08:00
|
|
|
write!(f, " win={}", self.window_len)?;
|
|
|
|
write!(f, " len={}", self.payload.len())?;
|
2017-01-27 09:09:34 +08:00
|
|
|
if let Some(max_seg_size) = self.max_seg_size {
|
2017-06-25 00:34:32 +08:00
|
|
|
write!(f, " mss={}", max_seg_size)?;
|
2017-01-27 09:09:34 +08:00
|
|
|
}
|
2016-12-20 21:16:29 +08:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-12-27 07:11:30 +08:00
|
|
|
use crate::wire::pretty_print::{PrettyPrint, PrettyIndent};
|
2016-12-20 21:16:29 +08:00
|
|
|
|
|
|
|
impl<T: AsRef<[u8]>> PrettyPrint for Packet<T> {
|
2019-06-22 16:19:39 +08:00
|
|
|
fn pretty_print(buffer: &dyn AsRef<[u8]>, f: &mut fmt::Formatter,
|
2016-12-20 21:16:29 +08:00
|
|
|
indent: &mut PrettyIndent) -> fmt::Result {
|
Do not attempt to validate length of packets being emitted.
This is a form of an uninitialized read bug; although safe it caused
panics. In short, transmit buffers received from the network stack
should be considered uninitialized (in practice they will often
contain previously transmitted packets or parts thereof). Wrapping
them with the only method we had (e.g. Ipv4Packet) treated the buffer
as if it contained a valid incoming packet, which can easily fail
with Error::Truncated.
This commit splits every `fn new(buffer: T) -> Result<Self, Error>`
method on a `Packet` into three smaller ones:
* `fn check_len(&self) -> Result<(), Error>`, purely a validator;
* `fn new(T) -> Self`, purely a wrapper;
* `fn new_checked(T) -> Result<Self, Error>`, a validating wrapper.
This makes it easy to process ingress packets (using `new_checked`),
egress packets (using `new`), and, if needed, maintain the invariants
at any point during packet construction (using `check_len`).
Fixes #17.
2017-06-24 17:15:22 +08:00
|
|
|
match Packet::new_checked(buffer) {
|
2017-12-17 05:42:19 +08:00
|
|
|
Err(err) => write!(f, "{}({})", indent, err),
|
|
|
|
Ok(packet) => write!(f, "{}{}", indent, packet)
|
2016-12-20 21:16:29 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-12-19 05:42:44 +08:00
|
|
|
#[cfg(test)]
|
|
|
|
mod test {
|
2017-12-24 21:28:59 +08:00
|
|
|
#[cfg(feature = "proto-ipv4")]
|
2020-12-27 07:11:30 +08:00
|
|
|
use crate::wire::Ipv4Address;
|
2016-12-19 05:42:44 +08:00
|
|
|
use super::*;
|
|
|
|
|
2017-12-24 21:28:59 +08:00
|
|
|
#[cfg(feature = "proto-ipv4")]
|
2016-12-19 05:42:44 +08:00
|
|
|
const SRC_ADDR: Ipv4Address = Ipv4Address([192, 168, 1, 1]);
|
2017-12-24 21:28:59 +08:00
|
|
|
#[cfg(feature = "proto-ipv4")]
|
2016-12-19 05:42:44 +08:00
|
|
|
const DST_ADDR: Ipv4Address = Ipv4Address([192, 168, 1, 2]);
|
|
|
|
|
2017-12-24 21:28:59 +08:00
|
|
|
#[cfg(feature = "proto-ipv4")]
|
2017-01-27 08:17:13 +08:00
|
|
|
static PACKET_BYTES: [u8; 28] =
|
2016-12-19 05:42:44 +08:00
|
|
|
[0xbf, 0x00, 0x00, 0x50,
|
|
|
|
0x01, 0x23, 0x45, 0x67,
|
|
|
|
0x89, 0xab, 0xcd, 0xef,
|
2017-01-27 08:17:13 +08:00
|
|
|
0x60, 0x35, 0x01, 0x23,
|
|
|
|
0x01, 0xb6, 0x02, 0x01,
|
|
|
|
0x03, 0x03, 0x0c, 0x01,
|
2016-12-19 05:42:44 +08:00
|
|
|
0xaa, 0x00, 0x00, 0xff];
|
|
|
|
|
2017-12-24 21:28:59 +08:00
|
|
|
#[cfg(feature = "proto-ipv4")]
|
2017-01-27 08:17:13 +08:00
|
|
|
static OPTION_BYTES: [u8; 4] =
|
|
|
|
[0x03, 0x03, 0x0c, 0x01];
|
|
|
|
|
2017-12-24 21:28:59 +08:00
|
|
|
#[cfg(feature = "proto-ipv4")]
|
2016-12-19 05:42:44 +08:00
|
|
|
static PAYLOAD_BYTES: [u8; 4] =
|
|
|
|
[0xaa, 0x00, 0x00, 0xff];
|
|
|
|
|
|
|
|
#[test]
|
2017-12-24 21:28:59 +08:00
|
|
|
#[cfg(feature = "proto-ipv4")]
|
2016-12-19 05:42:44 +08:00
|
|
|
fn test_deconstruct() {
|
2018-07-11 08:22:43 +08:00
|
|
|
let packet = Packet::new_unchecked(&PACKET_BYTES[..]);
|
2016-12-19 05:42:44 +08:00
|
|
|
assert_eq!(packet.src_port(), 48896);
|
|
|
|
assert_eq!(packet.dst_port(), 80);
|
2016-12-28 02:34:13 +08:00
|
|
|
assert_eq!(packet.seq_number(), SeqNumber(0x01234567));
|
|
|
|
assert_eq!(packet.ack_number(), SeqNumber(0x89abcdefu32 as i32));
|
2017-01-27 08:17:13 +08:00
|
|
|
assert_eq!(packet.header_len(), 24);
|
2016-12-19 05:42:44 +08:00
|
|
|
assert_eq!(packet.fin(), true);
|
|
|
|
assert_eq!(packet.syn(), false);
|
|
|
|
assert_eq!(packet.rst(), true);
|
|
|
|
assert_eq!(packet.psh(), false);
|
|
|
|
assert_eq!(packet.ack(), true);
|
|
|
|
assert_eq!(packet.urg(), true);
|
|
|
|
assert_eq!(packet.window_len(), 0x0123);
|
|
|
|
assert_eq!(packet.urgent_at(), 0x0201);
|
2017-01-27 08:17:13 +08:00
|
|
|
assert_eq!(packet.checksum(), 0x01b6);
|
|
|
|
assert_eq!(packet.options(), &OPTION_BYTES[..]);
|
2016-12-19 05:42:44 +08:00
|
|
|
assert_eq!(packet.payload(), &PAYLOAD_BYTES[..]);
|
|
|
|
assert_eq!(packet.verify_checksum(&SRC_ADDR.into(), &DST_ADDR.into()), true);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
2017-12-24 21:28:59 +08:00
|
|
|
#[cfg(feature = "proto-ipv4")]
|
2016-12-19 05:42:44 +08:00
|
|
|
fn test_construct() {
|
2017-06-26 11:44:36 +08:00
|
|
|
let mut bytes = vec![0xa5; PACKET_BYTES.len()];
|
2018-07-11 08:22:43 +08:00
|
|
|
let mut packet = Packet::new_unchecked(&mut bytes);
|
2016-12-19 05:42:44 +08:00
|
|
|
packet.set_src_port(48896);
|
|
|
|
packet.set_dst_port(80);
|
2016-12-28 02:34:13 +08:00
|
|
|
packet.set_seq_number(SeqNumber(0x01234567));
|
|
|
|
packet.set_ack_number(SeqNumber(0x89abcdefu32 as i32));
|
2017-01-27 08:17:13 +08:00
|
|
|
packet.set_header_len(24);
|
2017-06-26 11:44:36 +08:00
|
|
|
packet.clear_flags();
|
2016-12-19 05:42:44 +08:00
|
|
|
packet.set_fin(true);
|
|
|
|
packet.set_syn(false);
|
|
|
|
packet.set_rst(true);
|
|
|
|
packet.set_psh(false);
|
|
|
|
packet.set_ack(true);
|
|
|
|
packet.set_urg(true);
|
|
|
|
packet.set_window_len(0x0123);
|
|
|
|
packet.set_urgent_at(0x0201);
|
|
|
|
packet.set_checksum(0xEEEE);
|
2017-01-27 08:17:13 +08:00
|
|
|
packet.options_mut().copy_from_slice(&OPTION_BYTES[..]);
|
2016-12-19 05:42:44 +08:00
|
|
|
packet.payload_mut().copy_from_slice(&PAYLOAD_BYTES[..]);
|
|
|
|
packet.fill_checksum(&SRC_ADDR.into(), &DST_ADDR.into());
|
|
|
|
assert_eq!(&packet.into_inner()[..], &PACKET_BYTES[..]);
|
|
|
|
}
|
2016-12-20 20:52:33 +08:00
|
|
|
|
2017-06-24 19:47:24 +08:00
|
|
|
#[test]
|
2017-12-24 21:28:59 +08:00
|
|
|
#[cfg(feature = "proto-ipv4")]
|
2017-06-24 19:47:24 +08:00
|
|
|
fn test_truncated() {
|
2018-07-11 08:22:43 +08:00
|
|
|
let packet = Packet::new_unchecked(&PACKET_BYTES[..23]);
|
2017-06-24 19:47:24 +08:00
|
|
|
assert_eq!(packet.check_len(), Err(Error::Truncated));
|
|
|
|
}
|
|
|
|
|
2017-06-24 20:29:39 +08:00
|
|
|
#[test]
|
|
|
|
fn test_impossible_len() {
|
|
|
|
let mut bytes = vec![0; 20];
|
2018-07-11 08:22:43 +08:00
|
|
|
let mut packet = Packet::new_unchecked(&mut bytes);
|
2017-06-24 20:29:39 +08:00
|
|
|
packet.set_header_len(10);
|
|
|
|
assert_eq!(packet.check_len(), Err(Error::Malformed));
|
|
|
|
}
|
|
|
|
|
2017-12-24 21:28:59 +08:00
|
|
|
#[cfg(feature = "proto-ipv4")]
|
2016-12-20 20:52:33 +08:00
|
|
|
static SYN_PACKET_BYTES: [u8; 24] =
|
|
|
|
[0xbf, 0x00, 0x00, 0x50,
|
|
|
|
0x01, 0x23, 0x45, 0x67,
|
|
|
|
0x00, 0x00, 0x00, 0x00,
|
2017-08-25 14:03:54 +08:00
|
|
|
0x50, 0x02, 0x01, 0x23,
|
|
|
|
0x7a, 0x8d, 0x00, 0x00,
|
2016-12-20 20:52:33 +08:00
|
|
|
0xaa, 0x00, 0x00, 0xff];
|
|
|
|
|
2017-12-24 21:28:59 +08:00
|
|
|
#[cfg(feature = "proto-ipv4")]
|
2016-12-20 20:52:33 +08:00
|
|
|
fn packet_repr() -> Repr<'static> {
|
|
|
|
Repr {
|
2017-01-27 09:09:34 +08:00
|
|
|
src_port: 48896,
|
|
|
|
dst_port: 80,
|
|
|
|
seq_number: SeqNumber(0x01234567),
|
|
|
|
ack_number: None,
|
|
|
|
window_len: 0x0123,
|
2018-06-24 22:35:29 +08:00
|
|
|
window_scale: None,
|
2017-01-27 09:09:34 +08:00
|
|
|
control: Control::Syn,
|
|
|
|
max_seg_size: None,
|
2019-01-01 04:45:20 +08:00
|
|
|
sack_permitted: false,
|
|
|
|
sack_ranges: [None, None, None],
|
2017-01-27 09:09:34 +08:00
|
|
|
payload: &PAYLOAD_BYTES
|
2016-12-20 20:52:33 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
2017-12-24 21:28:59 +08:00
|
|
|
#[cfg(feature = "proto-ipv4")]
|
2016-12-20 20:52:33 +08:00
|
|
|
fn test_parse() {
|
2018-07-11 08:22:43 +08:00
|
|
|
let packet = Packet::new_unchecked(&SYN_PACKET_BYTES[..]);
|
2017-10-02 18:47:51 +08:00
|
|
|
let repr = Repr::parse(&packet, &SRC_ADDR.into(), &DST_ADDR.into(), &ChecksumCapabilities::default()).unwrap();
|
2016-12-20 20:52:33 +08:00
|
|
|
assert_eq!(repr, packet_repr());
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
2017-12-24 21:28:59 +08:00
|
|
|
#[cfg(feature = "proto-ipv4")]
|
2016-12-20 20:52:33 +08:00
|
|
|
fn test_emit() {
|
|
|
|
let repr = packet_repr();
|
2017-06-26 11:44:36 +08:00
|
|
|
let mut bytes = vec![0xa5; repr.buffer_len()];
|
2018-07-11 08:22:43 +08:00
|
|
|
let mut packet = Packet::new_unchecked(&mut bytes);
|
2017-10-02 18:47:51 +08:00
|
|
|
repr.emit(&mut packet, &SRC_ADDR.into(), &DST_ADDR.into(), &ChecksumCapabilities::default());
|
2016-12-20 20:52:33 +08:00
|
|
|
assert_eq!(&packet.into_inner()[..], &SYN_PACKET_BYTES[..]);
|
|
|
|
}
|
2017-01-27 08:17:13 +08:00
|
|
|
|
2018-06-28 16:44:18 +08:00
|
|
|
#[test]
|
|
|
|
#[cfg(feature = "proto-ipv4")]
|
|
|
|
fn test_header_len_multiple_of_4() {
|
|
|
|
let mut repr = packet_repr();
|
|
|
|
repr.window_scale = Some(0); // This TCP Option needs 3 bytes.
|
|
|
|
assert_eq!(repr.header_len() % 4, 0); // Should e.g. be 28 instead of 27.
|
|
|
|
}
|
|
|
|
|
2017-01-27 08:17:13 +08:00
|
|
|
macro_rules! assert_option_parses {
|
|
|
|
($opt:expr, $data:expr) => ({
|
|
|
|
assert_eq!(TcpOption::parse($data), Ok((&[][..], $opt)));
|
2019-01-01 04:45:20 +08:00
|
|
|
let buffer = &mut [0; 40][..$opt.buffer_len()];
|
2017-01-27 08:17:13 +08:00
|
|
|
assert_eq!($opt.emit(buffer), &mut []);
|
|
|
|
assert_eq!(&*buffer, $data);
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_tcp_options() {
|
|
|
|
assert_option_parses!(TcpOption::EndOfList,
|
|
|
|
&[0x00]);
|
|
|
|
assert_option_parses!(TcpOption::NoOperation,
|
|
|
|
&[0x01]);
|
|
|
|
assert_option_parses!(TcpOption::MaxSegmentSize(1500),
|
|
|
|
&[0x02, 0x04, 0x05, 0xdc]);
|
|
|
|
assert_option_parses!(TcpOption::WindowScale(12),
|
|
|
|
&[0x03, 0x03, 0x0c]);
|
2019-01-01 04:45:20 +08:00
|
|
|
assert_option_parses!(TcpOption::SackPermitted,
|
|
|
|
&[0x4, 0x02]);
|
|
|
|
assert_option_parses!(TcpOption::SackRange([Some((500, 1500)), None, None]),
|
|
|
|
&[0x05, 0x0a,
|
|
|
|
0x00, 0x00, 0x01, 0xf4, 0x00, 0x00, 0x05, 0xdc]);
|
|
|
|
assert_option_parses!(TcpOption::SackRange([Some((875, 1225)), Some((1500, 2500)), None]),
|
|
|
|
&[0x05, 0x12,
|
|
|
|
0x00, 0x00, 0x03, 0x6b, 0x00, 0x00, 0x04, 0xc9,
|
|
|
|
0x00, 0x00, 0x05, 0xdc, 0x00, 0x00, 0x09, 0xc4]);
|
|
|
|
assert_option_parses!(TcpOption::SackRange([Some((875000, 1225000)),
|
|
|
|
Some((1500000, 2500000)),
|
|
|
|
Some((876543210, 876654320))]),
|
|
|
|
&[0x05, 0x1a,
|
|
|
|
0x00, 0x0d, 0x59, 0xf8, 0x00, 0x12, 0xb1, 0x28,
|
|
|
|
0x00, 0x16, 0xe3, 0x60, 0x00, 0x26, 0x25, 0xa0,
|
|
|
|
0x34, 0x3e, 0xfc, 0xea, 0x34, 0x40, 0xae, 0xf0]);
|
2017-01-27 08:17:13 +08:00
|
|
|
assert_option_parses!(TcpOption::Unknown { kind: 12, data: &[1, 2, 3][..] },
|
|
|
|
&[0x0c, 0x05, 0x01, 0x02, 0x03])
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_malformed_tcp_options() {
|
|
|
|
assert_eq!(TcpOption::parse(&[]),
|
|
|
|
Err(Error::Truncated));
|
|
|
|
assert_eq!(TcpOption::parse(&[0xc]),
|
|
|
|
Err(Error::Truncated));
|
|
|
|
assert_eq!(TcpOption::parse(&[0xc, 0x05, 0x01, 0x02]),
|
|
|
|
Err(Error::Truncated));
|
2017-06-24 19:25:48 +08:00
|
|
|
assert_eq!(TcpOption::parse(&[0xc, 0x01]),
|
|
|
|
Err(Error::Truncated));
|
2017-01-27 08:17:13 +08:00
|
|
|
assert_eq!(TcpOption::parse(&[0x2, 0x02]),
|
|
|
|
Err(Error::Malformed));
|
|
|
|
assert_eq!(TcpOption::parse(&[0x3, 0x02]),
|
|
|
|
Err(Error::Malformed));
|
|
|
|
}
|
2016-12-19 05:42:44 +08:00
|
|
|
}
|