udp.rs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. use managed::Managed;
  2. use Error;
  3. use wire::{IpProtocol, IpEndpoint};
  4. use wire::{UdpPacket, UdpRepr};
  5. use socket::{Socket, IpRepr, IpPayload};
  6. /// A buffered UDP packet.
  7. #[derive(Debug)]
  8. pub struct PacketBuffer<'a> {
  9. endpoint: IpEndpoint,
  10. size: usize,
  11. payload: Managed<'a, [u8]>
  12. }
  13. impl<'a> PacketBuffer<'a> {
  14. /// Create a buffered packet.
  15. pub fn new<T>(payload: T) -> PacketBuffer<'a>
  16. where T: Into<Managed<'a, [u8]>> {
  17. PacketBuffer {
  18. endpoint: IpEndpoint::default(),
  19. size: 0,
  20. payload: payload.into()
  21. }
  22. }
  23. fn as_ref<'b>(&'b self) -> &'b [u8] {
  24. &self.payload[..self.size]
  25. }
  26. fn as_mut<'b>(&'b mut self) -> &'b mut [u8] {
  27. &mut self.payload[..self.size]
  28. }
  29. }
  30. /// An UDP packet ring buffer.
  31. #[derive(Debug)]
  32. pub struct SocketBuffer<'a, 'b: 'a> {
  33. storage: Managed<'a, [PacketBuffer<'b>]>,
  34. read_at: usize,
  35. length: usize
  36. }
  37. impl<'a, 'b> SocketBuffer<'a, 'b> {
  38. /// Create a packet buffer with the given storage.
  39. pub fn new<T>(storage: T) -> SocketBuffer<'a, 'b>
  40. where T: Into<Managed<'a, [PacketBuffer<'b>]>> {
  41. let mut storage = storage.into();
  42. for elem in storage.iter_mut() {
  43. elem.endpoint = Default::default();
  44. elem.size = 0;
  45. }
  46. SocketBuffer {
  47. storage: storage,
  48. read_at: 0,
  49. length: 0
  50. }
  51. }
  52. fn mask(&self, index: usize) -> usize {
  53. index % self.storage.len()
  54. }
  55. fn incr(&self, index: usize) -> usize {
  56. self.mask(index + 1)
  57. }
  58. /// Query whether the buffer is empty.
  59. pub fn empty(&self) -> bool {
  60. self.length == 0
  61. }
  62. /// Query whether the buffer is full.
  63. pub fn full(&self) -> bool {
  64. self.length == self.storage.len()
  65. }
  66. /// Enqueue an element into the buffer, and return a pointer to it, or return
  67. /// `Err(())` if the buffer is full.
  68. pub fn enqueue(&mut self) -> Result<&mut PacketBuffer<'b>, ()> {
  69. if self.full() {
  70. Err(())
  71. } else {
  72. let index = self.mask(self.read_at + self.length);
  73. let result = &mut self.storage[index];
  74. self.length += 1;
  75. Ok(result)
  76. }
  77. }
  78. /// Dequeue an element from the buffer, and return a pointer to it, or return
  79. /// `Err(())` if the buffer is empty.
  80. pub fn dequeue(&mut self) -> Result<&PacketBuffer<'b>, ()> {
  81. if self.empty() {
  82. Err(())
  83. } else {
  84. self.length -= 1;
  85. let result = &self.storage[self.read_at];
  86. self.read_at = self.incr(self.read_at);
  87. Ok(result)
  88. }
  89. }
  90. }
  91. /// An User Datagram Protocol socket.
  92. ///
  93. /// An UDP socket is bound to a specific endpoint, and owns transmit and receive
  94. /// packet buffers.
  95. #[derive(Debug)]
  96. pub struct UdpSocket<'a, 'b: 'a> {
  97. endpoint: IpEndpoint,
  98. rx_buffer: SocketBuffer<'a, 'b>,
  99. tx_buffer: SocketBuffer<'a, 'b>,
  100. debug_id: usize
  101. }
  102. impl<'a, 'b> UdpSocket<'a, 'b> {
  103. /// Create an UDP socket with the given buffers.
  104. pub fn new(rx_buffer: SocketBuffer<'a, 'b>,
  105. tx_buffer: SocketBuffer<'a, 'b>) -> Socket<'a, 'b> {
  106. Socket::Udp(UdpSocket {
  107. endpoint: IpEndpoint::default(),
  108. rx_buffer: rx_buffer,
  109. tx_buffer: tx_buffer,
  110. debug_id: 0
  111. })
  112. }
  113. /// Return the debug identifier.
  114. pub fn debug_id(&self) -> usize {
  115. self.debug_id
  116. }
  117. /// Set the debug identifier.
  118. ///
  119. /// The debug identifier is a number printed in socket trace messages.
  120. /// It could as well be used by the user code.
  121. pub fn set_debug_id(&mut self, id: usize) {
  122. self.debug_id = id
  123. }
  124. /// Return the bound endpoint.
  125. #[inline]
  126. pub fn endpoint(&self) -> IpEndpoint {
  127. self.endpoint
  128. }
  129. /// Bind the socket to the given endpoint.
  130. pub fn bind<T: Into<IpEndpoint>>(&mut self, endpoint: T) {
  131. self.endpoint = endpoint.into()
  132. }
  133. /// Check whether the transmit buffer is full.
  134. pub fn can_send(&self) -> bool {
  135. !self.tx_buffer.full()
  136. }
  137. /// Check whether the receive buffer is not empty.
  138. pub fn can_recv(&self) -> bool {
  139. !self.rx_buffer.empty()
  140. }
  141. /// Enqueue a packet to be sent to a given remote endpoint, and return a pointer
  142. /// to its payload.
  143. ///
  144. /// This function returns `Err(())` if the size is greater than what
  145. /// the transmit buffer can accomodate.
  146. pub fn send(&mut self, size: usize, endpoint: IpEndpoint) -> Result<&mut [u8], ()> {
  147. let packet_buf = try!(self.tx_buffer.enqueue());
  148. packet_buf.endpoint = endpoint;
  149. packet_buf.size = size;
  150. net_trace!("[{}]{}:{}: buffer to send {} octets",
  151. self.debug_id, self.endpoint,
  152. packet_buf.endpoint, packet_buf.size);
  153. Ok(&mut packet_buf.as_mut()[..size])
  154. }
  155. /// Enqueue a packet to be sent to a given remote endpoint, and fill it from a slice.
  156. ///
  157. /// See also [send](#method.send).
  158. pub fn send_slice(&mut self, data: &[u8], endpoint: IpEndpoint) -> Result<usize, ()> {
  159. let buffer = try!(self.send(data.len(), endpoint));
  160. let data = &data[..buffer.len()];
  161. buffer.copy_from_slice(data);
  162. Ok(data.len())
  163. }
  164. /// Dequeue a packet received from a remote endpoint, and return the endpoint as well
  165. /// as a pointer to the payload.
  166. ///
  167. /// This function returns `Err(())` if the receive buffer is empty.
  168. pub fn recv(&mut self) -> Result<(&[u8], IpEndpoint), ()> {
  169. let packet_buf = try!(self.rx_buffer.dequeue());
  170. net_trace!("[{}]{}:{}: receive {} buffered octets",
  171. self.debug_id, self.endpoint,
  172. packet_buf.endpoint, packet_buf.size);
  173. Ok((&packet_buf.as_ref()[..packet_buf.size], packet_buf.endpoint))
  174. }
  175. /// Dequeue a packet received from a remote endpoint, and return the endpoint as well
  176. /// as copy the payload into the given slice.
  177. ///
  178. /// See also [recv](#method.recv).
  179. pub fn recv_slice(&mut self, data: &mut [u8]) -> Result<(usize, IpEndpoint), ()> {
  180. let (buffer, endpoint) = try!(self.recv());
  181. data[..buffer.len()].copy_from_slice(buffer);
  182. Ok((buffer.len(), endpoint))
  183. }
  184. /// See [Socket::process](enum.Socket.html#method.process).
  185. pub fn process(&mut self, _timestamp: u64, ip_repr: &IpRepr,
  186. payload: &[u8]) -> Result<(), Error> {
  187. if ip_repr.protocol() != IpProtocol::Udp { return Err(Error::Rejected) }
  188. let packet = try!(UdpPacket::new(&payload[..ip_repr.payload_len()]));
  189. let repr = try!(UdpRepr::parse(&packet, &ip_repr.src_addr(), &ip_repr.dst_addr()));
  190. if repr.dst_port != self.endpoint.port { return Err(Error::Rejected) }
  191. if !self.endpoint.addr.is_unspecified() {
  192. if self.endpoint.addr != ip_repr.dst_addr() { return Err(Error::Rejected) }
  193. }
  194. let packet_buf = try!(self.rx_buffer.enqueue().map_err(|()| Error::Exhausted));
  195. packet_buf.endpoint = IpEndpoint { addr: ip_repr.src_addr(), port: repr.src_port };
  196. packet_buf.size = repr.payload.len();
  197. packet_buf.as_mut()[..repr.payload.len()].copy_from_slice(repr.payload);
  198. net_trace!("[{}]{}:{}: receiving {} octets",
  199. self.debug_id, self.endpoint,
  200. packet_buf.endpoint, packet_buf.size);
  201. Ok(())
  202. }
  203. /// See [Socket::dispatch](enum.Socket.html#method.dispatch).
  204. pub fn dispatch<F, R>(&mut self, _timestamp: u64, _mtu: usize,
  205. emit: &mut F) -> Result<R, Error>
  206. where F: FnMut(&IpRepr, &IpPayload) -> Result<R, Error> {
  207. let packet_buf = try!(self.tx_buffer.dequeue().map_err(|()| Error::Exhausted));
  208. net_trace!("[{}]{}:{}: sending {} octets",
  209. self.debug_id, self.endpoint,
  210. packet_buf.endpoint, packet_buf.size);
  211. let repr = UdpRepr {
  212. src_port: self.endpoint.port,
  213. dst_port: packet_buf.endpoint.port,
  214. payload: &packet_buf.as_ref()[..]
  215. };
  216. let ip_repr = IpRepr::Unspecified {
  217. src_addr: self.endpoint.addr,
  218. dst_addr: packet_buf.endpoint.addr,
  219. protocol: IpProtocol::Udp,
  220. payload_len: repr.buffer_len()
  221. };
  222. emit(&ip_repr, &repr)
  223. }
  224. }
  225. impl<'a> IpPayload for UdpRepr<'a> {
  226. fn buffer_len(&self) -> usize {
  227. self.buffer_len()
  228. }
  229. fn emit(&self, repr: &IpRepr, payload: &mut [u8]) {
  230. let mut packet = UdpPacket::new(payload).expect("undersized payload");
  231. self.emit(&mut packet, &repr.src_addr(), &repr.dst_addr())
  232. }
  233. }
  234. #[cfg(test)]
  235. mod test {
  236. use super::*;
  237. #[test]
  238. pub fn test_buffer() {
  239. let mut storage = vec![];
  240. for _ in 0..5 {
  241. storage.push(PacketBuffer::new(vec![0]))
  242. }
  243. let mut buffer = SocketBuffer::new(&mut storage[..]);
  244. assert_eq!(buffer.empty(), true);
  245. assert_eq!(buffer.full(), false);
  246. buffer.enqueue().unwrap().size = 1;
  247. assert_eq!(buffer.empty(), false);
  248. assert_eq!(buffer.full(), false);
  249. buffer.enqueue().unwrap().size = 2;
  250. buffer.enqueue().unwrap().size = 3;
  251. assert_eq!(buffer.dequeue().unwrap().size, 1);
  252. assert_eq!(buffer.dequeue().unwrap().size, 2);
  253. buffer.enqueue().unwrap().size = 4;
  254. buffer.enqueue().unwrap().size = 5;
  255. buffer.enqueue().unwrap().size = 6;
  256. buffer.enqueue().unwrap().size = 7;
  257. assert_eq!(buffer.enqueue().unwrap_err(), ());
  258. assert_eq!(buffer.empty(), false);
  259. assert_eq!(buffer.full(), true);
  260. assert_eq!(buffer.dequeue().unwrap().size, 3);
  261. assert_eq!(buffer.dequeue().unwrap().size, 4);
  262. assert_eq!(buffer.dequeue().unwrap().size, 5);
  263. assert_eq!(buffer.dequeue().unwrap().size, 6);
  264. assert_eq!(buffer.dequeue().unwrap().size, 7);
  265. assert_eq!(buffer.dequeue().unwrap_err(), ());
  266. assert_eq!(buffer.empty(), true);
  267. assert_eq!(buffer.full(), false);
  268. }
  269. }