Advertisement
Guest User

Untitled

a guest
Sep 26th, 2017
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.92 KB | None | 0 0
  1. use nom::*;
  2. use cookie_factory::*;
  3.  
  4. use bytes::BytesMut;
  5. use std::io;
  6. use tokio_io::codec::{Decoder, Encoder};
  7.  
  8. trait FromBytes : Sized {
  9. fn from_bytes(i: &[u8]) -> IResult<&[u8], Self>;
  10. }
  11.  
  12. trait ToBytes : Sized {
  13. fn to_bytes<'a>(buf: (&'a mut [u8], usize), packet: Self) -> Result<(&'a mut [u8], usize), GenError>;
  14. }
  15.  
  16. #[derive(Debug, PartialEq, Clone)]
  17. pub struct Get { key: Vec<u8> }
  18.  
  19. #[derive(Debug, PartialEq, Clone)]
  20. pub struct Set { key: Vec<u8>, value: Vec<u8> }
  21.  
  22. #[derive(Debug, PartialEq, Clone)]
  23. pub struct Data { id: u8, payload: Vec<u8> }
  24.  
  25. #[derive(Debug, PartialEq, Clone)]
  26. pub enum Packet {
  27. Get(Get),
  28. Set(Set),
  29. Data(Data)
  30. }
  31.  
  32. impl FromBytes for Get {
  33. named!(from_bytes<Get>, do_parse!(
  34. tag!("\x00") >>
  35. key: length_data!(be_u8) >>
  36. ( Get { key: key.to_owned() } )
  37. ));
  38. }
  39.  
  40. impl ToBytes for Get {
  41. fn to_bytes<'a>(buf: (&'a mut [u8], usize), packet: Get) -> Result<(&'a mut [u8], usize), GenError> {
  42. do_gen!(buf,
  43. gen_be_u8!(0x00) >>
  44. gen_be_u8!(packet.key.len() as u8) >>
  45. gen_slice!(&packet.key)
  46. )
  47. }
  48. }
  49.  
  50. impl FromBytes for Set {
  51. named!(from_bytes<Set>, do_parse!(
  52. tag!("\x01") >>
  53. key: length_data!(be_u8) >>
  54. value: length_data!(be_u8) >>
  55. ( Set { key: key.to_owned(), value: value.to_owned() } )
  56. ));
  57. }
  58.  
  59. impl ToBytes for Set {
  60. fn to_bytes<'a>(buf: (&'a mut [u8], usize), packet: Set) -> Result<(&'a mut [u8], usize), GenError> {
  61. do_gen!(buf,
  62. gen_be_u8!(0x01) >>
  63. gen_be_u8!(packet.key.len() as u8) >>
  64. gen_slice!(&packet.key) >>
  65. gen_be_u8!(packet.value.len() as u8) >>
  66. gen_slice!(&packet.value)
  67. )
  68. }
  69. }
  70.  
  71. impl FromBytes for Data {
  72. named!(from_bytes<Data>, do_parse!(
  73. id: be_u8 >>
  74. payload: length_data!(be_u8) >>
  75. ( Data { id: id, payload: payload.to_owned() } )
  76. ));
  77. }
  78.  
  79. impl ToBytes for Data {
  80. fn to_bytes<'a>(buf: (&'a mut [u8], usize), packet: Data) -> Result<(&'a mut [u8], usize), GenError> {
  81. do_gen!(buf,
  82. gen_be_u8!(packet.id) >>
  83. gen_be_u8!(packet.payload.len() as u8) >>
  84. gen_slice!(&packet.payload)
  85. )
  86. }
  87. }
  88.  
  89. impl FromBytes for Packet {
  90. named!(from_bytes<Packet>, alt!(
  91. map!(Get::from_bytes, Packet::Get) |
  92. map!(Set::from_bytes, Packet::Set) |
  93. map!(Data::from_bytes, Packet::Data)
  94. ));
  95. }
  96.  
  97. impl ToBytes for Packet {
  98. fn to_bytes<'a>(buf: (&'a mut [u8], usize), packet: Packet) -> Result<(&'a mut [u8], usize), GenError> {
  99. match packet {
  100. Packet::Get(inner) => ToBytes::to_bytes(buf, inner),
  101. Packet::Set(inner) => ToBytes::to_bytes(buf, inner),
  102. Packet::Data(inner) => ToBytes::to_bytes(buf, inner),
  103. }
  104. }
  105. }
  106.  
  107.  
  108. /// implements tokio-io's Decoder and Encoder
  109. pub struct Codec;
  110.  
  111. impl Decoder for Codec {
  112. type Item = Packet;
  113. type Error = io::Error;
  114.  
  115. fn decode(&mut self, buf: &mut BytesMut) -> Result<Option<Packet>, io::Error> {
  116. let (consumed, packet) = match Packet::from_bytes(buf) {
  117. IResult::Incomplete(_) => {
  118. return Ok(None)
  119. },
  120. IResult::Error(e) => {
  121. return Err(io::Error::new(io::ErrorKind::Other, format!("decode error: {:?}", e)))
  122. },
  123. IResult::Done(i, packet) => {
  124. (buf.offset(i), packet)
  125. }
  126. };
  127.  
  128. // TODO memzero buf[..consumed] ?
  129. buf.split_to(consumed);
  130.  
  131. Ok(Some(packet))
  132. }
  133. }
  134.  
  135. impl Encoder for Codec {
  136. type Item = Packet;
  137. type Error = io::Error;
  138.  
  139. fn encode(&mut self, packet: Packet, buf: &mut BytesMut) -> Result<(), Self::Error> {
  140. let mut stack_buf = [0; 2050];
  141. match Packet::to_bytes((&mut stack_buf, 0), packet).map(|tup| tup.1) {
  142. Ok(produced) => {
  143. buf.extend_from_slice(&stack_buf);
  144. // TODO memzero stack_buf ?
  145. trace!("serialized packet: {} bytes", produced);
  146. Ok(())
  147. },
  148. Err(e) => {
  149. Err(io::Error::new(io::ErrorKind::Other, format!("encode error: {:?}", e)))
  150. }
  151. }
  152. }
  153. }
  154.  
  155. #[cfg(test)]
  156. mod tests {
  157. use ::toxcore::tcp::parse_test::*;
  158. #[test]
  159. fn get_from_bytes() {
  160. assert_eq!(Get::from_bytes(b"\x00"), IResult::Incomplete(Needed::Size(1)));
  161. assert_eq!(Get::from_bytes(b"\x00\x03abcd"), IResult::Done(&b"d"[..], Get{ key: b"abc".to_vec() }));
  162. }
  163. fn check_packet(packet: Packet) {
  164. let mut buf = BytesMut::new();
  165. let mut codec = Codec {};
  166. codec.encode(packet.clone() , &mut buf ).expect("Should encode");
  167. let res = codec.decode(&mut buf).unwrap().expect("Should decode");
  168. assert_eq!(packet, res);
  169. }
  170. #[test]
  171. fn encoder_decoder() {
  172. check_packet( Packet::Get( Get { key: b"abc".to_vec() } ) );
  173. check_packet( Packet::Set( Set { key: b"abc".to_vec(), value: b"qwe".to_vec() } ) );
  174. }
  175. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement