tcp.rs 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. use Error;
  2. use Managed;
  3. use wire::{IpProtocol, IpAddress, IpEndpoint};
  4. use wire::{TcpPacket, TcpRepr, TcpControl};
  5. use socket::{Socket};
  6. /// A TCP stream ring buffer.
  7. #[derive(Debug)]
  8. pub struct SocketBuffer<'a> {
  9. storage: Managed<'a, [u8]>,
  10. read_at: usize,
  11. length: usize
  12. }
  13. impl<'a> SocketBuffer<'a> {
  14. /// Create a packet buffer with the given storage.
  15. pub fn new<T>(storage: T) -> SocketBuffer<'a>
  16. where T: Into<Managed<'a, [u8]>> {
  17. SocketBuffer {
  18. storage: storage.into(),
  19. read_at: 0,
  20. length: 0
  21. }
  22. }
  23. /// Enqueue a slice of octets up to the given size into the buffer, and return a pointer
  24. /// to the slice.
  25. ///
  26. /// The returned slice may be shorter than requested, as short as an empty slice,
  27. /// if there is not enough contiguous free space in the buffer.
  28. pub fn enqueue(&mut self, mut size: usize) -> &mut [u8] {
  29. let write_at = (self.read_at + self.length) % self.storage.len();
  30. // We can't enqueue more than there is free space.
  31. let free = self.storage.len() - self.length;
  32. if size > free { size = free }
  33. // We can't contiguously enqueue past the beginning of the storage.
  34. let until_end = self.storage.len() - write_at;
  35. if size > until_end { size = until_end }
  36. self.length += size;
  37. &mut self.storage[write_at..write_at + size]
  38. }
  39. /// Dequeue a slice of octets up to the given size from the buffer, and return a pointer
  40. /// to the slice.
  41. ///
  42. /// The returned slice may be shorter than requested, as short as an empty slice,
  43. /// if there is not enough contiguous filled space in the buffer.
  44. pub fn dequeue(&mut self, mut size: usize) -> &[u8] {
  45. let read_at = self.read_at;
  46. // We can't dequeue more than was queued.
  47. if size > self.length { size = self.length }
  48. // We can't contiguously dequeue past the end of the storage.
  49. let until_end = self.storage.len() - self.read_at;
  50. if size > until_end { size = until_end }
  51. self.read_at = (self.read_at + size) % self.storage.len();
  52. self.length -= size;
  53. &self.storage[read_at..read_at + size]
  54. }
  55. }
  56. /// A description of incoming TCP connection.
  57. #[derive(Debug)]
  58. pub struct Incoming {
  59. local_end: IpEndpoint,
  60. remote_end: IpEndpoint,
  61. seq_number: u32
  62. }
  63. impl Incoming {
  64. /// Return the local endpoint.
  65. pub fn local_end(&self) -> IpEndpoint {
  66. self.local_end
  67. }
  68. /// Return the remote endpoint.
  69. pub fn remote_end(&self) -> IpEndpoint {
  70. self.remote_end
  71. }
  72. }
  73. /// A Transmission Control Protocol server socket.
  74. #[derive(Debug)]
  75. pub struct Listener<'a> {
  76. endpoint: IpEndpoint,
  77. backlog: Managed<'a, [Option<Incoming>]>,
  78. accept_at: usize,
  79. length: usize
  80. }
  81. impl<'a> Listener<'a> {
  82. /// Create a server socket with the given backlog.
  83. pub fn new<T>(endpoint: IpEndpoint, backlog: T) -> Socket<'a, 'static>
  84. where T: Into<Managed<'a, [Option<Incoming>]>> {
  85. Socket::TcpServer(Listener {
  86. endpoint: endpoint,
  87. backlog: backlog.into(),
  88. accept_at: 0,
  89. length: 0
  90. })
  91. }
  92. /// Accept a connection from this server socket,
  93. pub fn accept(&mut self) -> Option<Incoming> {
  94. if self.length == 0 { return None }
  95. let accept_at = self.accept_at;
  96. self.accept_at = (self.accept_at + 1) % self.backlog.len();
  97. self.length -= 1;
  98. self.backlog[accept_at].take()
  99. }
  100. /// See [Socket::collect](enum.Socket.html#method.collect).
  101. pub fn collect(&mut self, src_addr: &IpAddress, dst_addr: &IpAddress,
  102. protocol: IpProtocol, payload: &[u8])
  103. -> Result<(), Error> {
  104. if protocol != IpProtocol::Tcp { return Err(Error::Rejected) }
  105. let packet = try!(TcpPacket::new(payload));
  106. let repr = try!(TcpRepr::parse(&packet, src_addr, dst_addr));
  107. if repr.dst_port != self.endpoint.port { return Err(Error::Rejected) }
  108. if !self.endpoint.addr.is_unspecified() {
  109. if self.endpoint.addr != *dst_addr { return Err(Error::Rejected) }
  110. }
  111. match (repr.control, repr.ack_number) {
  112. (TcpControl::Syn, None) => {
  113. if self.length == self.backlog.len() { return Err(Error::Exhausted) }
  114. let inject_at = (self.accept_at + self.length) % self.backlog.len();
  115. self.length += 1;
  116. assert!(self.backlog[inject_at].is_none());
  117. self.backlog[inject_at] = Some(Incoming {
  118. local_end: IpEndpoint::new(*dst_addr, repr.dst_port),
  119. remote_end: IpEndpoint::new(*src_addr, repr.src_port),
  120. seq_number: repr.seq_number
  121. });
  122. Ok(())
  123. }
  124. _ => Err(Error::Rejected)
  125. }
  126. }
  127. }
  128. #[cfg(test)]
  129. mod test {
  130. use super::*;
  131. #[test]
  132. fn test_buffer() {
  133. let mut buffer = SocketBuffer::new(vec![0; 8]); // ........
  134. buffer.enqueue(6).copy_from_slice(b"foobar"); // foobar..
  135. assert_eq!(buffer.dequeue(3), b"foo"); // ...bar..
  136. buffer.enqueue(6).copy_from_slice(b"ba"); // ...barba
  137. buffer.enqueue(4).copy_from_slice(b"zho"); // zhobarba
  138. assert_eq!(buffer.dequeue(6), b"barba"); // zho.....
  139. assert_eq!(buffer.dequeue(8), b"zho"); // ........
  140. buffer.enqueue(8).copy_from_slice(b"gefug"); // ...gefug
  141. }
  142. }