author int64 658 755k | date stringlengths 19 19 | timezone int64 -46,800 43.2k | hash stringlengths 40 40 | message stringlengths 5 490 | mods list | language stringclasses 20 values | license stringclasses 3 values | repo stringlengths 5 68 | original_message stringlengths 12 491 |
|---|---|---|---|---|---|---|---|---|---|
20,244 | 29.03.2020 09:55:28 | 14,400 | 2847e16b30b2437cd47458a07edfed604430cfa5 | WIP: fix partial packet reading logic | [
{
"change_type": "MODIFY",
"old_path": "antenna_forwarding_client/src/lib.rs",
"new_path": "antenna_forwarding_client/src/lib.rs",
"diff": "@@ -145,9 +145,7 @@ pub fn start_antenna_forwarding_proxy(\nfn forward_connections(antenna_sockaddr: SocketAddr, server_stream: TcpStream) {\ntrace!(\"Forwarding connections!\");\nlet mut server_stream = server_stream;\n- let mut bytes_read;\nlet mut streams: HashMap<u64, TcpStream> = HashMap::new();\n- let mut start;\nlet mut last_message = Instant::now();\nloop {\nlet mut streams_to_remove: Vec<u64> = Vec::new();\n@@ -188,13 +186,12 @@ fn forward_connections(antenna_sockaddr: SocketAddr, server_stream: TcpStream) {\n}\nlet mut buffer: [u8; BUFFER_SIZE] = [0; BUFFER_SIZE];\n- match server_stream.read(&mut buffer) {\n+ let mut bytes_read = match server_stream.read(&mut buffer) {\nOk(bytes) => {\nif bytes > 0 {\ntrace!(\"Got {} bytes from the server\", bytes);\n}\n- bytes_read = bytes;\n- start = 0;\n+ bytes\n}\nErr(e) => {\nif e.kind() != WouldBlock {\n@@ -202,17 +199,19 @@ fn forward_connections(antenna_sockaddr: SocketAddr, server_stream: TcpStream) {\n}\ncontinue;\n}\n- }\n+ };\n+ let mut start = 0;\nwhile start < bytes_read {\n+ trace!(\"start {} bytes_read {}\", start, bytes_read);\nlet connection = ConnectionMessage::read_message(&buffer[start..bytes_read]);\nlet close = ConnectionClose::read_message(&buffer[start..bytes_read]);\nlet halt = ForwardingCloseMessage::read_message(&buffer[start..bytes_read]);\nmatch (connection, close, halt) {\n- (Ok((new_start, connection_message)), Err(_), Err(_)) => {\n+ (Ok((message_bytes_read, connection_message)), Err(_), Err(_)) => {\ntrace!(\"Got connection message\");\nlast_message = Instant::now();\n- start = new_start;\n+ start += message_bytes_read;\nlet stream_id = &connection_message.stream_id;\nif let Some(antenna_stream) = streams.get_mut(stream_id) {\ntrace!(\"Message for {}\", stream_id);\n@@ -233,10 +232,10 @@ fn forward_connections(antenna_sockaddr: SocketAddr, server_stream: TcpStream) {\nstreams.insert(*stream_id, new_stream);\n}\n}\n- (Err(_), Ok((new_start, close_message)), Err(_)) => {\n+ (Err(_), Ok((message_bytes_read, close_message)), Err(_)) => {\ntrace!(\"Got close message\");\nlast_message = Instant::now();\n- start = new_start;\n+ start += message_bytes_read;\nlet stream_id = &close_message.stream_id;\nlet stream = streams\n.get(stream_id)\n@@ -259,8 +258,21 @@ fn forward_connections(antenna_sockaddr: SocketAddr, server_stream: TcpStream) {\n.expect(\"Could not shutdown connection!\");\nreturn;\n}\n- (Err(_), Err(_), Err(_)) => {\n- break;\n+ (Err(a), Err(b), Err(c)) => {\n+ trace!(\"Triple error {:?} {:?} {:?}\", a, b, c);\n+ match server_stream.read(&mut buffer[start..]) {\n+ Ok(bytes) => {\n+ if bytes > 0 {\n+ trace!(\"Got {} bytes from the server\", bytes);\n+ }\n+ bytes_read += bytes;\n+ }\n+ Err(e) => {\n+ if e.kind() != WouldBlock {\n+ error!(\"Failed to read from server with {:?}\", e);\n+ }\n+ }\n+ }\n}\n(Ok(_), Ok(_), Ok(_)) => panic!(\"Impossible!\"),\n(Ok(_), Ok(_), Err(_)) => panic!(\"Impossible!\"),\n"
},
{
"change_type": "MODIFY",
"old_path": "antenna_forwarding_protocol/src/lib.rs",
"new_path": "antenna_forwarding_protocol/src/lib.rs",
"diff": "@@ -14,6 +14,7 @@ extern crate failure;\nuse althea_types::Identity;\nuse failure::Error;\nuse std::io::ErrorKind::WouldBlock;\n+use std::io::Read;\nuse std::io::Write;\nuse std::net::IpAddr;\nuse std::net::TcpStream;\n@@ -47,13 +48,6 @@ pub fn write_all_spinlock(stream: &mut TcpStream, buffer: &[u8]) -> Result<(), E\n}\n}\n-/// an excessively long protocol magic value that preceeds all\n-/// control traffic. A u32 would probably be sufficient to ensure\n-/// that we never try to interpret an actual packet as a control packet\n-/// but I don't see a reason to be stingy. This is totally random, but you\n-/// can never change it once there's a device deployed with it\n-const MAGIC: u128 = 266_244_417_876_907_680_150_892_848_205_622_258_774;\n-\npub const IDENTIFICATION_MESSAGE_TYPE: u16 = 0;\npub const FORWARD_MESSAGE_TYPE: u16 = 1;\npub const ERROR_MESSAGE_TYPE: u16 = 2;\n@@ -62,12 +56,111 @@ pub const CONNECTION_MESSAGE_TYPE: u16 = 4;\npub const FORWARDING_CLOSE_MESSAGE_TYPE: u16 = 5;\npub const KEEPALIVE_MESSAGE_TYPE: u16 = 6;\n+/// Reads all the currently available messages from the provided stream, this function will\n+/// also block until a currently in flight message is delivered, for a maximum of 500ms\n+pub fn read_message<T: ForwardingProtocolMessage + Clone>(\n+ input: &mut TcpStream,\n+) -> Result<Vec<T>, Error> {\n+ read_message_internal(input, Vec::new(), Vec::new())\n+}\n+\n+fn read_message_internal<T: ForwardingProtocolMessage + Clone>(\n+ input: &mut TcpStream,\n+ remaining_bytes: Vec<u8>,\n+ messages: Vec<T>,\n+) -> Result<Vec<T>, Error> {\n+ // these should match the full list of message types defined above\n+ let mut messages = messages;\n+ let mut unfinished_message = false;\n+\n+ remaining_bytes.extend_from_slice(&read_till_block(input)?);\n+\n+ let mut possible_messages: Vec<Result<(usize, T), Error>> = Vec::new();\n+ possible_messages.push(IdentificationMessage::read_message(&remaining_bytes));\n+ let forward = ForwardMessage::read_message(&remaining_bytes);\n+ let error = ErrorMessage::read_message(&remaining_bytes);\n+ let close = ConnectionClose::read_message(&remaining_bytes);\n+ let connection = ConnectionMessage::read_message(&remaining_bytes);\n+ let forwarding_close = ForwardingCloseMessage::read_message(&remaining_bytes);\n+ let keepalive = KeepAliveMessage::read_message(&remaining_bytes);\n+ if let Ok((bytes, id)) = id {\n+ (bytes, message) = get_successfull_message();\n+\n+ if bytes < remaining_bytes.len() {\n+ read_message_internal(input, remaining_bytes[bytes..].to_vec(), messages)\n+ } else {\n+ Ok(messages)\n+ }\n+ } else {\n+ Ok(messages)\n+ }\n+}\n+\n+/// Takes a vec of message parse results and returns the successful one, and error if\n+/// more than one is successful\n+fn get_successfull_message<T: ForwardingProtocolMessage + Clone>(\n+ possible_messages: Vec<Result<(usize, T), Error>>,\n+) -> Result<(usize, T), Error> {\n+ // this doesn't really need to be here, the same set of bytes\n+ // should never parse to two messages successfully, so guarding\n+ // is a little excessive.\n+ let mut num_ok = 0;\n+ let mut res: Option<(usize, T)> = None;\n+ for item in possible_messages {\n+ if let Ok(val) = item {\n+ num_ok += 1;\n+ res = Some(val)\n+ }\n+ }\n+ if num_ok > 1 {\n+ panic!(\"The same message parsed two ways!\");\n+ } else if num_ok == 0 {\n+ bail!(\"No successful messages\");\n+ } else {\n+ // we have exactly one success, this can't panic\n+ // because we must have found one to reach this block\n+ Ok(res.unwrap())\n+ }\n+}\n+\n+/// Reads the entire contents of a tcpstream into a buffer until it blocks\n+pub fn read_till_block(input: &mut TcpStream) -> Result<Vec<u8>, Error> {\n+ input.set_nonblocking(true)?;\n+ let mut out = Vec::new();\n+ loop {\n+ let mut buffer: [u8; BUFFER_SIZE] = [0; BUFFER_SIZE];\n+ match input.read(&mut buffer) {\n+ Ok(_bytes) => out.extend_from_slice(&buffer),\n+ Err(e) => {\n+ if e.kind() == WouldBlock {\n+ return Ok(out);\n+ } else {\n+ return Err(e.into());\n+ }\n+ }\n+ }\n+ }\n+}\n+\n+/// an excessively long protocol magic value that preceeds all\n+/// control traffic. A u32 would probably be sufficient to ensure\n+/// that we never try to interpret an actual packet as a control packet\n+/// but I don't see a reason to be stingy. This is totally random, but you\n+/// can never change it once there's a device deployed with it\n+const MAGIC: u128 = 266_244_417_876_907_680_150_892_848_205_622_258_774;\n+\n+pub enum ForwardingMessageType {\n+ IdentificationMessage,\n+}\n+\npub trait ForwardingProtocolMessage {\nfn get_message(&self) -> Vec<u8>;\nfn read_message(payload: &[u8]) -> Result<(usize, Self), Error>\nwhere\nSelf: std::marker::Sized;\nfn get_type(&self) -> u16;\n+ fn get_payload(&self) -> Option<Vec<u8>>;\n+ fn get_stream_id(&self) -> Option<u64>;\n}\n/// The serialized struct sent as the payload\n@@ -198,6 +291,14 @@ impl ForwardingProtocolMessage for ConnectionMessage {\nfn get_type(&self) -> u16 {\nCONNECTION_MESSAGE_TYPE\n}\n+\n+ fn get_payload(&self) -> Option<Vec<u8>> {\n+ Some(self.payload)\n+ }\n+\n+ fn get_stream_id(&self) -> Option<u64> {\n+ Some(self.stream_id)\n+ }\n}\nimpl ConnectionClose {\n@@ -262,6 +363,14 @@ impl ForwardingProtocolMessage for ConnectionClose {\nfn get_type(&self) -> u16 {\nCONNECTION_CLOSE_MESSAGE_TYPE\n}\n+\n+ fn get_payload(&self) -> Option<Vec<u8>> {\n+ None\n+ }\n+\n+ fn get_stream_id(&self) -> Option<u64> {\n+ Some(self.stream_id)\n+ }\n}\nimpl IdentificationMessage {\n@@ -329,6 +438,14 @@ impl ForwardingProtocolMessage for IdentificationMessage {\nfn get_type(&self) -> u16 {\nIDENTIFICATION_MESSAGE_TYPE\n}\n+\n+ fn get_payload(&self) -> Option<Vec<u8>> {\n+ None\n+ }\n+\n+ fn get_stream_id(&self) -> Option<u64> {\n+ None\n+ }\n}\nimpl ErrorMessage {\n@@ -393,6 +510,14 @@ impl ForwardingProtocolMessage for ErrorMessage {\nfn get_type(&self) -> u16 {\nERROR_MESSAGE_TYPE\n}\n+\n+ fn get_payload(&self) -> Option<Vec<u8>> {\n+ None\n+ }\n+\n+ fn get_stream_id(&self) -> Option<u64> {\n+ None\n+ }\n}\nimpl ForwardMessage {\n@@ -461,6 +586,14 @@ impl ForwardingProtocolMessage for ForwardMessage {\nfn get_type(&self) -> u16 {\nFORWARD_MESSAGE_TYPE\n}\n+\n+ fn get_payload(&self) -> Option<Vec<u8>> {\n+ None\n+ }\n+\n+ fn get_stream_id(&self) -> Option<u64> {\n+ None\n+ }\n}\nimpl ForwardingCloseMessage {\n@@ -525,6 +658,14 @@ impl ForwardingProtocolMessage for ForwardingCloseMessage {\nfn get_type(&self) -> u16 {\nFORWARDING_CLOSE_MESSAGE_TYPE\n}\n+\n+ fn get_payload(&self) -> Option<Vec<u8>> {\n+ None\n+ }\n+\n+ fn get_stream_id(&self) -> Option<u64> {\n+ None\n+ }\n}\nimpl KeepAliveMessage {\n@@ -589,6 +730,14 @@ impl ForwardingProtocolMessage for KeepAliveMessage {\nfn get_type(&self) -> u16 {\nKEEPALIVE_MESSAGE_TYPE\n}\n+\n+ fn get_payload(&self) -> Option<Vec<u8>> {\n+ None\n+ }\n+\n+ fn get_stream_id(&self) -> Option<u64> {\n+ None\n+ }\n}\n#[cfg(test)]\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | WIP: fix partial packet reading logic |
20,244 | 30.03.2020 09:41:56 | 14,400 | 1ca9e36ffcf35f0907cf5161acd25e4a56e976bb | Upgrade client to use enum forwarding | [
{
"change_type": "MODIFY",
"old_path": "antenna_forwarding_client/src/lib.rs",
"new_path": "antenna_forwarding_client/src/lib.rs",
"diff": "@@ -13,31 +13,23 @@ use althea_kernel_interface::KernelInterface;\nuse althea_kernel_interface::LinuxCommandRunner;\nuse althea_types::Identity;\nuse althea_types::WgKey;\n+use antenna_forwarding_protocol::read_till_block;\nuse antenna_forwarding_protocol::write_all_spinlock;\n-use antenna_forwarding_protocol::ConnectionClose;\n-use antenna_forwarding_protocol::ConnectionMessage;\n-use antenna_forwarding_protocol::ErrorMessage;\n-use antenna_forwarding_protocol::ForwardMessage;\n-use antenna_forwarding_protocol::ForwardingCloseMessage;\nuse antenna_forwarding_protocol::ForwardingProtocolMessage;\n-use antenna_forwarding_protocol::IdentificationMessage;\n-use antenna_forwarding_protocol::BUFFER_SIZE;\n+use antenna_forwarding_protocol::NET_TIMEOUT;\nuse antenna_forwarding_protocol::SPINLOCK_TIME;\nuse failure::Error;\nuse oping::Ping;\n-use rand::thread_rng;\nuse rand::Rng;\nuse std::collections::HashMap;\nuse std::collections::HashSet;\nuse std::io::ErrorKind::WouldBlock;\n-use std::io::Read;\nuse std::io::Write;\nuse std::net::IpAddr;\nuse std::net::Ipv4Addr;\nuse std::net::Shutdown;\nuse std::net::SocketAddr;\nuse std::net::TcpStream;\n-use std::process::ExitStatus;\nuse std::thread;\nuse std::time::Duration;\nuse std::time::Instant;\n@@ -46,21 +38,23 @@ lazy_static! {\npub static ref KI: Box<dyn KernelInterface> = Box::new(LinuxCommandRunner {});\n}\n-/// The network operation timeout for this library\n-const NET_TIMEOUT: Duration = Duration::from_secs(5);\n+const SLEEP_TIME: Duration = NET_TIMEOUT;\n/// The timeout time for pinging a local antenna, 25ms is very\n/// very generous here as they should all respond really within 5ms\nconst PING_TIMEOUT: Duration = Duration::from_millis(100);\n/// the amount of time with no activity before we close a forwarding session\nconst FORWARD_TIMEOUT: Duration = Duration::from_secs(600);\n-pub fn start_antenna_forwarding_proxy(\n+/// Starts a thread that will check in with the provided server repeatedly and forward antennas\n+/// when the right signal is recieved. The type bound is so that you can use custom hashers and\n+/// may not really be worth keeping around.\n+pub fn start_antenna_forwarding_proxy<S: 'static + std::marker::Send + ::std::hash::BuildHasher>(\ncheckin_address: String,\nour_id: Identity,\n- server_public_key: WgKey,\n- our_public_key: WgKey,\n- our_private_key: WgKey,\n- interfaces_to_search: HashSet<String>,\n+ _server_public_key: WgKey,\n+ _our_public_key: WgKey,\n+ _our_private_key: WgKey,\n+ interfaces_to_search: HashSet<String, S>,\n) {\ninfo!(\"Starting antenna forwarding proxy!\");\nlet socket: SocketAddr = match checkin_address.parse() {\n@@ -75,180 +69,108 @@ pub fn start_antenna_forwarding_proxy(\n// parse checkin address every loop iteration as a way\n// of resolving the domain name on each run\ntrace!(\"About to checkin with {}\", checkin_address);\n- if let Ok(mut stream) = TcpStream::connect_timeout(&socket, NET_TIMEOUT) {\n+ thread::sleep(SLEEP_TIME);\n+ if let Ok(mut server_stream) = TcpStream::connect_timeout(&socket, NET_TIMEOUT) {\ntrace!(\"connected to {}\", checkin_address);\n- stream\n- .set_read_timeout(Some(NET_TIMEOUT))\n- .expect(\"Failed to set read timeout on socket!\");\n// send our identifier\nlet _res = write_all_spinlock(\n- &mut stream,\n- &IdentificationMessage::new(our_id).get_message(),\n+ &mut server_stream,\n+ &ForwardingProtocolMessage::new_identification_message(our_id).get_message(),\n);\n- let mut buf: [u8; BUFFER_SIZE] = [0; BUFFER_SIZE];\n- let res = stream.read(&mut buf);\n- match res {\n- Ok(bytes) => match ForwardMessage::read_message(&buf) {\n- Ok(msg) => {\n- // we start nonblocking operation here, so that we\n- // can easily wait for the forward response after\n- // sending our ID message, now we need non-blocking\n- // to process messages\n- stream\n- .set_nonblocking(true)\n- .expect(\"Failed to get nonblocking socket!\");\n-\n- trace!(\"Got fwd message {}\", checkin_address);\n- let (bytes_read, forward_message) = msg;\n-\n- // todo it would be technically correct to have packets\n- // after the forward packet, but we don't package things that\n- // way on the server, we should handle the possibility\n- if bytes > bytes_read {\n- error!(\"Extra messages after forward packet dropped!\");\n+ // wait for a NET_TIMEOUT and see if the server responds, then read it's entire response\n+ thread::sleep(NET_TIMEOUT);\n+ match ForwardingProtocolMessage::read_messages(&mut server_stream) {\n+ Ok(messages) => {\n+ if messages.is_empty() {\n+ error!(\"Empty vector from read_messages?\");\n+ continue;\n}\n-\n- let s = setup_networking(forward_message, &interfaces_to_search);\n- match s {\n- Ok(s) => forward_connections(s, stream),\n- Err(e) => {\n- // the error message never reaches the server because the server\n- // will fail to read it, even if it enters the buffer once the\n- // connection is terminated.\n- stream.set_nodelay(true).expect(\"Failed to disble Nagle\");\n- let a = write_all_spinlock(\n- &mut stream,\n- &ErrorMessage::new(format!(\"{:?}\", e)).get_message(),\n+ // read messages will return a vec of at least one,\n+ if let ForwardingProtocolMessage::ForwardMessage {\n+ ip,\n+ server_port: _server_port,\n+ antenna_port,\n+ } = messages[0]\n+ {\n+ match setup_networking(ip, antenna_port, &interfaces_to_search) {\n+ Ok(antenna_sockaddr) => {\n+ forward_connections(\n+ antenna_sockaddr,\n+ server_stream,\n+ &messages[1..],\n);\n- let b = stream.shutdown(Shutdown::Both);\n- warn!(\"Error forwarding write {:?} shutdown {:?}\", a, b);\n- drop(stream);\n- }\n- }\n}\n- Err(e) => warn!(\"Failed to read forward message with {:?}\", e),\n- },\n- // if we don't read successfully we go off into the next\n- // iteration of the loop and repeat this all again\n- // we could try and keep a single connection open, but we\n- // face many of the same problems (keepalive etc)\n- Err(e) => trace!(\"Finished waiting with {:?}\", e),\n+ Err(e) => send_error_message(&mut server_stream, format!(\"{:?}\", e)),\n}\n}\n- trace!(\"Waiting for next checkin cycle\");\n- thread::sleep(NET_TIMEOUT);\n- });\n-}\n-\n-/// Actually forwards the connection by managing the reading and writing from\n-/// various tcp sockets\n-fn forward_connections(antenna_sockaddr: SocketAddr, server_stream: TcpStream) {\n- trace!(\"Forwarding connections!\");\n- let mut server_stream = server_stream;\n- let mut streams: HashMap<u64, TcpStream> = HashMap::new();\n- let mut last_message = Instant::now();\n- loop {\n- let mut streams_to_remove: Vec<u64> = Vec::new();\n- // First we we have to iterate over all of these connections\n- // and read to send messages up the server pipe. We need to do\n- // this first becuase we may exit in the next section if there's\n- // nothing to write\n- for (stream_id, antenna_stream) in streams.iter_mut() {\n- let mut buffer: [u8; BUFFER_SIZE] = [0; BUFFER_SIZE];\n- // in theory we will figure out if the connection is closed here\n- // and then send a closed message\n- match antenna_stream.read(&mut buffer) {\n- Ok(bytes) => {\n- if bytes != 0 {\n- trace!(\n- \"We have {} bytes to write from a antenna input socket\",\n- bytes\n- );\n- let msg = ConnectionMessage::new(*stream_id, buffer[0..bytes].to_vec());\n- write_all_spinlock(&mut server_stream, &msg.get_message())\n- .expect(&format!(\"Failed to write with stream {}\", *stream_id));\n- }\n}\nErr(e) => {\n- if e.kind() != WouldBlock {\n- error!(\"Could not read client socket with {:?}\", e);\n- let msg = ConnectionClose::new(*stream_id);\n- write_all_spinlock(&mut server_stream, &msg.get_message())\n- .expect(&format!(\"Failed to close stream {}\", *stream_id));\n- let _ = antenna_stream.shutdown(Shutdown::Write);\n- streams_to_remove.push(*stream_id);\n- }\n+ error!(\"Failed to read message from server with {:?}\", e);\n+ continue;\n}\n}\n}\n- for i in streams_to_remove {\n- streams.remove(&i);\n+ trace!(\"Waiting for next checkin cycle\");\n+ });\n}\n- let mut buffer: [u8; BUFFER_SIZE] = [0; BUFFER_SIZE];\n- let mut bytes_read = match server_stream.read(&mut buffer) {\n- Ok(bytes) => {\n- if bytes > 0 {\n- trace!(\"Got {} bytes from the server\", bytes);\n- }\n- bytes\n- }\n- Err(e) => {\n- if e.kind() != WouldBlock {\n- error!(\"Failed to read from server with {:?}\", e);\n- }\n- continue;\n+/// Processes an array of messages and takes the appropriate actions\n+/// returns if the forwarder should shutdown becuase a shutdown message\n+/// was found in the message batch.\n+fn process_messages(\n+ input: &[ForwardingProtocolMessage],\n+ streams: &mut HashMap<u64, TcpStream>,\n+ server_stream: &mut TcpStream,\n+ last_message: &mut Instant,\n+ antenna_sockaddr: SocketAddr,\n+) -> bool {\n+ for item in input {\n+ match item {\n+ // why would the server ID themselves to us?\n+ ForwardingProtocolMessage::IdentificationMessage { .. } => unimplemented!(),\n+ // two forward messages?\n+ ForwardingProtocolMessage::ForwardMessage { .. } => unimplemented!(),\n+ // the server doesn't send us error messages, what would we do with it?\n+ ForwardingProtocolMessage::ErrorMessage { .. } => unimplemented!(),\n+ ForwardingProtocolMessage::ConnectionCloseMessage { stream_id } => {\n+ trace!(\"Got close message\");\n+ *last_message = Instant::now();\n+ let stream_id = stream_id;\n+ let stream = streams\n+ .get(stream_id)\n+ .expect(\"How can we close a stream we don't have?\");\n+ stream\n+ .shutdown(Shutdown::Both)\n+ .expect(\"Failed to shutdown connection!\");\n+ streams.remove(stream_id);\n}\n- };\n- let mut start = 0;\n-\n- while start < bytes_read {\n- trace!(\"start {} bytes_read {}\", start, bytes_read);\n- let connection = ConnectionMessage::read_message(&buffer[start..bytes_read]);\n- let close = ConnectionClose::read_message(&buffer[start..bytes_read]);\n- let halt = ForwardingCloseMessage::read_message(&buffer[start..bytes_read]);\n- match (connection, close, halt) {\n- (Ok((message_bytes_read, connection_message)), Err(_), Err(_)) => {\n+ ForwardingProtocolMessage::ConnectionDataMessage { stream_id, payload } => {\ntrace!(\"Got connection message\");\n- last_message = Instant::now();\n- start += message_bytes_read;\n- let stream_id = &connection_message.stream_id;\n+ *last_message = Instant::now();\n+ let stream_id = stream_id;\nif let Some(antenna_stream) = streams.get_mut(stream_id) {\ntrace!(\"Message for {}\", stream_id);\nantenna_stream\n- .write_all(&connection_message.payload)\n+ .write_all(&payload)\n.expect(\"Failed to talk to antenna!\");\n} else {\ntrace!(\"Opening stream for {}\", stream_id);\n// we don't have a stream, we need to dial out to the server now\n- let mut new_stream = TcpStream::connect(antenna_sockaddr)\n- .expect(\"Could not contact antenna!\");\n+ let mut new_stream =\n+ TcpStream::connect(antenna_sockaddr).expect(\"Could not contact antenna!\");\nnew_stream\n.set_nonblocking(true)\n.expect(\"Could not get nonblocking connection\");\nnew_stream\n- .write_all(&connection_message.payload)\n+ .write_all(&payload)\n.expect(\"Failed to talk to antenna!\");\nstreams.insert(*stream_id, new_stream);\n}\n}\n- (Err(_), Ok((message_bytes_read, close_message)), Err(_)) => {\n- trace!(\"Got close message\");\n- last_message = Instant::now();\n- start += message_bytes_read;\n- let stream_id = &close_message.stream_id;\n- let stream = streams\n- .get(stream_id)\n- .expect(\"How can we close a stream we don't have?\");\n- stream\n- .shutdown(Shutdown::Both)\n- .expect(\"Failed to shutdown connection!\");\n- streams.remove(stream_id);\n- }\n- (Err(_), Err(_), Ok((_new_start, _halt_message))) => {\n+ ForwardingProtocolMessage::ForwardingCloseMessage => {\ntrace!(\"Got halt message\");\n// we have a close lets get out of here.\n- for (_id, stream) in streams {\n+ for stream in streams.values_mut() {\nstream\n.shutdown(Shutdown::Both)\n.expect(\"Failed to shutdown connection!\");\n@@ -256,29 +178,87 @@ fn forward_connections(antenna_sockaddr: SocketAddr, server_stream: TcpStream) {\nserver_stream\n.shutdown(Shutdown::Both)\n.expect(\"Could not shutdown connection!\");\n- return;\n+ return true;\n+ }\n+ // we don't use this yet\n+ ForwardingProtocolMessage::KeepAliveMessage => unimplemented!(),\n+ }\n+ }\n+ false\n}\n- (Err(a), Err(b), Err(c)) => {\n- trace!(\"Triple error {:?} {:?} {:?}\", a, b, c);\n- match server_stream.read(&mut buffer[start..]) {\n+\n+/// This function processes the antenna streams, meaning it handles taking messages from\n+/// known streams, packaging them, and sending them down the line to the server. It also handles\n+/// details like closing those streams when they hangup and notifying the server end.\n+fn process_streams(streams: &mut HashMap<u64, TcpStream>, server_stream: &mut TcpStream) {\n+ let mut streams_to_remove: Vec<u64> = Vec::new();\n+ // First we we have to iterate over all of these connections\n+ // and read to send messages up the server pipe. We need to do\n+ // this first becuase we may exit in the next section if there's\n+ // nothing to write\n+ for (stream_id, antenna_stream) in streams.iter_mut() {\n+ // in theory we will figure out if the connection is closed here\n+ // and then send a closed message\n+ match read_till_block(antenna_stream) {\nOk(bytes) => {\n- if bytes > 0 {\n- trace!(\"Got {} bytes from the server\", bytes);\n+ if !bytes.is_empty() {\n+ trace!(\n+ \"We have {} bytes to write from a antenna input socket\",\n+ bytes.len()\n+ );\n+ let msg =\n+ ForwardingProtocolMessage::new_connection_data_message(*stream_id, bytes);\n+ write_all_spinlock(server_stream, &msg.get_message())\n+ .unwrap_or_else(|_| panic!(\"Failed to write with stream {}\", *stream_id));\n}\n- bytes_read += bytes;\n}\nErr(e) => {\nif e.kind() != WouldBlock {\n- error!(\"Failed to read from server with {:?}\", e);\n+ error!(\"Could not read client socket with {:?}\", e);\n+ let msg = ForwardingProtocolMessage::new_connection_close_message(*stream_id);\n+ write_all_spinlock(server_stream, &msg.get_message())\n+ .unwrap_or_else(|_| panic!(\"Failed to close stream {}\", *stream_id));\n+ let _ = antenna_stream.shutdown(Shutdown::Write);\n+ streams_to_remove.push(*stream_id);\n+ }\n}\n}\n}\n+ for i in streams_to_remove {\n+ streams.remove(&i);\n}\n- (Ok(_), Ok(_), Ok(_)) => panic!(\"Impossible!\"),\n- (Ok(_), Ok(_), Err(_)) => panic!(\"Impossible!\"),\n- (Ok(_), Err(_), Ok(_)) => panic!(\"Impossible!\"),\n- (Err(_), Ok(_), Ok(_)) => panic!(\"Impossible!\"),\n}\n+\n+/// Actually forwards the connection by managing the reading and writing from\n+/// various tcp sockets\n+fn forward_connections(\n+ antenna_sockaddr: SocketAddr,\n+ server_stream: TcpStream,\n+ first_round_input: &[ForwardingProtocolMessage],\n+) {\n+ trace!(\"Forwarding connections!\");\n+ let mut server_stream = server_stream;\n+ let mut streams: HashMap<u64, TcpStream> = HashMap::new();\n+ let mut last_message = Instant::now();\n+ process_messages(\n+ first_round_input,\n+ &mut streams,\n+ &mut server_stream,\n+ &mut last_message,\n+ antenna_sockaddr,\n+ );\n+\n+ while let Ok(vec) = ForwardingProtocolMessage::read_messages(&mut server_stream) {\n+ process_streams(&mut streams, &mut server_stream);\n+ let should_shutdown = process_messages(\n+ &vec,\n+ &mut streams,\n+ &mut server_stream,\n+ &mut last_message,\n+ antenna_sockaddr,\n+ );\n+ if should_shutdown {\n+ break;\n}\nif Instant::now() - last_message > FORWARD_TIMEOUT {\n@@ -291,11 +271,11 @@ fn forward_connections(antenna_sockaddr: SocketAddr, server_stream: TcpStream) {\n/// handles the setup of networking to the selected antenna, including finding it and the like\n/// returns a socketaddr for the antenna\n-fn setup_networking(\n- msg: ForwardMessage,\n- interfaces: &HashSet<String>,\n+fn setup_networking<S: ::std::hash::BuildHasher>(\n+ antenna_ip: IpAddr,\n+ antenna_port: u16,\n+ interfaces: &HashSet<String, S>,\n) -> Result<SocketAddr, Error> {\n- let antenna_ip = msg.ip;\nmatch find_antenna(antenna_ip, interfaces) {\nOk(_iface) => {}\nErr(e) => {\n@@ -303,14 +283,17 @@ fn setup_networking(\nreturn Err(e);\n}\n};\n- Ok(SocketAddr::new(antenna_ip, 443))\n+ Ok(SocketAddr::new(antenna_ip, antenna_port))\n}\n/// Finds the antenna on the appropriate physical interface by iterating\n/// over the list of provided interfaces, attempting a ping\n/// and repeating until the appropriate interface is located\n/// TODO handle overlapping edge cases for gateway ip, lan ip, br-pbs etc\n-fn find_antenna(ip: IpAddr, interfaces: &HashSet<String>) -> Result<String, Error> {\n+fn find_antenna<S: ::std::hash::BuildHasher>(\n+ ip: IpAddr,\n+ interfaces: &HashSet<String, S>,\n+) -> Result<String, Error> {\nlet our_ip = get_local_ip(ip);\nfor iface in interfaces {\ntrace!(\"Trying interface {}, with test ip {}\", iface, our_ip);\n@@ -400,3 +383,9 @@ fn get_local_ip(target_ip: IpAddr) -> IpAddr {\nIpAddr::V6(_address) => unimplemented!(),\n}\n}\n+\n+fn send_error_message(server_stream: &mut TcpStream, message: String) {\n+ let msg = ForwardingProtocolMessage::new_error_message(message);\n+ let _res = write_all_spinlock(server_stream, &msg.get_message());\n+ let _res = server_stream.shutdown(Shutdown::Both);\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "antenna_forwarding_protocol/src/lib.rs",
"new_path": "antenna_forwarding_protocol/src/lib.rs",
"diff": "@@ -13,6 +13,7 @@ extern crate failure;\nuse althea_types::Identity;\nuse failure::Error;\n+use std::io::Error as IoError;\nuse std::io::ErrorKind::WouldBlock;\nuse std::io::Read;\nuse std::io::Write;\n@@ -24,6 +25,9 @@ use std::time::Duration;\n/// The amount of time to sleep a thread that's spinlocking on somthing\npub const SPINLOCK_TIME: Duration = Duration::from_millis(10);\n+/// The amount of time to wait for a blocking read\n+pub const NET_TIMEOUT: Duration = Duration::from_secs(1);\n+\n/// The size of the memory buffer for reading and writing packets\n/// currently 100kbytes\npub const BUFFER_SIZE: usize = 100_000;\n@@ -33,14 +37,14 @@ pub const HEADER_LEN: usize = 20;\n/// Writes data to a stream keeping in mind that we may encounter\n/// a buffer limit and have to partially complete our write\n-pub fn write_all_spinlock(stream: &mut TcpStream, buffer: &[u8]) -> Result<(), Error> {\n+pub fn write_all_spinlock(stream: &mut TcpStream, buffer: &[u8]) -> Result<(), IoError> {\nloop {\nlet res = stream.write_all(buffer);\nmatch res {\nOk(_val) => return Ok(()),\nErr(e) => {\nif e.kind() != WouldBlock {\n- return Err(e.into());\n+ return Err(e);\n}\n}\n}\n@@ -49,50 +53,50 @@ pub fn write_all_spinlock(stream: &mut TcpStream, buffer: &[u8]) -> Result<(), E\n}\n/// Reads the entire contents of a tcpstream into a buffer until it blocks\n-pub fn read_till_block(input: &mut TcpStream) -> Result<Vec<u8>, Error> {\n+/// if someone is sending a huge amount of TCP traffic this routine will\n+/// run until you run out of memory\n+pub fn read_till_block(input: &mut TcpStream) -> Result<Vec<u8>, IoError> {\ninput.set_nonblocking(true)?;\nlet mut out = Vec::new();\nloop {\nlet mut buffer: [u8; BUFFER_SIZE] = [0; BUFFER_SIZE];\nmatch input.read(&mut buffer) {\n- Ok(_bytes) => out.extend_from_slice(&buffer),\n+ Ok(bytes) => {\n+ if bytes == 0 {\n+ return Ok(out);\n+ }\n+ out.extend_from_slice(&buffer)\n+ }\nErr(e) => {\nif e.kind() == WouldBlock {\nreturn Ok(out);\n} else {\n- return Err(e.into());\n+ return Err(e);\n}\n}\n}\n}\n}\n-/// Reads all the currently available messages from the provided stream, this function will\n-/// also block until a currently in flight message is delivered, for a maximum of 500ms\n-pub fn read_message(input: &mut TcpStream) -> Result<Vec<ForwardingProtocolMessage>, Error> {\n- read_message_internal(input, Vec::new(), Vec::new())\n-}\n-\n-fn read_message_internal(\n- input: &mut TcpStream,\n- remaining_bytes: Vec<u8>,\n- messages: Vec<ForwardingProtocolMessage>,\n-) -> Result<Vec<ForwardingProtocolMessage>, Error> {\n- // these should match the full list of message types defined above\n- let mut messages = messages;\n- let mut remaining_bytes = remaining_bytes;\n-\n- remaining_bytes.extend_from_slice(&read_till_block(input)?);\n-\n- if let Ok((bytes, msg)) = ForwardingProtocolMessage::read_message(&remaining_bytes) {\n- messages.push(msg);\n- if bytes < remaining_bytes.len() {\n- read_message_internal(input, remaining_bytes[bytes..].to_vec(), messages)\n+/// Reads the entire contents of a tcpstream into a buffer until it times out\n+/// if it fills the buffer it will recurse and read until th buffer is empty\n+/// if the buffer is being filled faster than it can read it will run out of memory\n+pub fn read_till_timeout(input: &mut TcpStream) -> Result<Vec<u8>, IoError> {\n+ input.set_nonblocking(false)?;\n+ input.set_read_timeout(Some(NET_TIMEOUT))?;\n+ let mut out = Vec::new();\n+ let mut buffer: [u8; BUFFER_SIZE] = [0; BUFFER_SIZE];\n+ match input.read(&mut buffer) {\n+ Ok(bytes) => {\n+ if bytes == BUFFER_SIZE {\n+ out.extend_from_slice(&buffer);\n+ out.extend_from_slice(&read_till_block(input)?);\n+ Ok(out)\n} else {\n- Ok(messages)\n+ Ok(buffer.to_vec())\n}\n- } else {\n- Ok(messages)\n+ }\n+ Err(e) => Err(e),\n}\n}\n@@ -388,6 +392,39 @@ impl ForwardingProtocolMessage {\n_ => bail!(\"Unknown packet type!\"),\n}\n}\n+\n+ /// Reads all the currently available messages from the provided stream, this function will\n+ /// also block until a currently in flight message is delivered\n+ pub fn read_messages(input: &mut TcpStream) -> Result<Vec<ForwardingProtocolMessage>, Error> {\n+ ForwardingProtocolMessage::read_messages_internal(input, Vec::new(), Vec::new())\n+ }\n+\n+ fn read_messages_internal(\n+ input: &mut TcpStream,\n+ remaining_bytes: Vec<u8>,\n+ messages: Vec<ForwardingProtocolMessage>,\n+ ) -> Result<Vec<ForwardingProtocolMessage>, Error> {\n+ // these should match the full list of message types defined above\n+ let mut messages = messages;\n+ let mut remaining_bytes = remaining_bytes;\n+\n+ remaining_bytes.extend_from_slice(&read_till_block(input)?);\n+\n+ if let Ok((bytes, msg)) = ForwardingProtocolMessage::read_message(&remaining_bytes) {\n+ messages.push(msg);\n+ if bytes < remaining_bytes.len() {\n+ ForwardingProtocolMessage::read_messages_internal(\n+ input,\n+ remaining_bytes[bytes..].to_vec(),\n+ messages,\n+ )\n+ } else {\n+ Ok(messages)\n+ }\n+ } else {\n+ Ok(messages)\n+ }\n+ }\n}\n#[cfg(test)]\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Upgrade client to use enum forwarding |
20,244 | 30.03.2020 18:49:07 | 14,400 | f66fa554b82b057c093ddf8334ee102c7cf52117 | More deduplication for ForwardingProtocol
Additional functions where moved into the protocol library for use
by the server. | [
{
"change_type": "MODIFY",
"old_path": "antenna_forwarding_client/src/lib.rs",
"new_path": "antenna_forwarding_client/src/lib.rs",
"diff": "@@ -13,7 +13,7 @@ use althea_kernel_interface::KernelInterface;\nuse althea_kernel_interface::LinuxCommandRunner;\nuse althea_types::Identity;\nuse althea_types::WgKey;\n-use antenna_forwarding_protocol::read_till_block;\n+use antenna_forwarding_protocol::process_streams;\nuse antenna_forwarding_protocol::write_all_spinlock;\nuse antenna_forwarding_protocol::ForwardingProtocolMessage;\nuse antenna_forwarding_protocol::NET_TIMEOUT;\n@@ -23,8 +23,6 @@ use oping::Ping;\nuse rand::Rng;\nuse std::collections::HashMap;\nuse std::collections::HashSet;\n-use std::io::ErrorKind::WouldBlock;\n-use std::io::Write;\nuse std::net::IpAddr;\nuse std::net::Ipv4Addr;\nuse std::net::Shutdown;\n@@ -83,22 +81,26 @@ pub fn start_antenna_forwarding_proxy<S: 'static + std::marker::Send + ::std::ha\nOk(messages) => {\nif messages.is_empty() {\nerror!(\"Empty vector from read_messages?\");\n- continue;\n}\n// read messages will return a vec of at least one,\n- if let ForwardingProtocolMessage::ForwardMessage {\n+ else if let Some(ForwardingProtocolMessage::ForwardMessage {\nip,\nserver_port: _server_port,\nantenna_port,\n- } = messages[0]\n+ }) = messages.iter().next()\n{\n- match setup_networking(ip, antenna_port, &interfaces_to_search) {\n+ // if there are other messages in this batch safely form a slice\n+ // to pass on\n+ let slice = if messages.len() > 1 {\n+ &messages[1..]\n+ } else {\n+ // an empty slice\n+ &([] as [ForwardingProtocolMessage; 0])\n+ };\n+ // setup networking and process the rest of the messages in this batch\n+ match setup_networking(*ip, *antenna_port, &interfaces_to_search) {\nOk(antenna_sockaddr) => {\n- forward_connections(\n- antenna_sockaddr,\n- server_stream,\n- &messages[1..],\n- );\n+ forward_connections(antenna_sockaddr, server_stream, slice);\n}\nErr(e) => send_error_message(&mut server_stream, format!(\"{:?}\", e)),\n}\n@@ -133,7 +135,7 @@ fn process_messages(\n// the server doesn't send us error messages, what would we do with it?\nForwardingProtocolMessage::ErrorMessage { .. } => unimplemented!(),\nForwardingProtocolMessage::ConnectionCloseMessage { stream_id } => {\n- trace!(\"Got close message\");\n+ trace!(\"Got close message for stream {}\", stream_id);\n*last_message = Instant::now();\nlet stream_id = stream_id;\nlet stream = streams\n@@ -145,24 +147,22 @@ fn process_messages(\nstreams.remove(stream_id);\n}\nForwardingProtocolMessage::ConnectionDataMessage { stream_id, payload } => {\n- trace!(\"Got connection message\");\n+ trace!(\n+ \"Got connection message for stream {} payload {} bytes\",\n+ stream_id,\n+ payload.len()\n+ );\n*last_message = Instant::now();\nlet stream_id = stream_id;\n- if let Some(antenna_stream) = streams.get_mut(stream_id) {\n- trace!(\"Message for {}\", stream_id);\n- antenna_stream\n- .write_all(&payload)\n+ if let Some(mut antenna_stream) = streams.get_mut(stream_id) {\n+ write_all_spinlock(&mut antenna_stream, &payload)\n.expect(\"Failed to talk to antenna!\");\n} else {\ntrace!(\"Opening stream for {}\", stream_id);\n// we don't have a stream, we need to dial out to the server now\nlet mut new_stream =\nTcpStream::connect(antenna_sockaddr).expect(\"Could not contact antenna!\");\n- new_stream\n- .set_nonblocking(true)\n- .expect(\"Could not get nonblocking connection\");\n- new_stream\n- .write_all(&payload)\n+ write_all_spinlock(&mut new_stream, &payload)\n.expect(\"Failed to talk to antenna!\");\nstreams.insert(*stream_id, new_stream);\n}\n@@ -187,48 +187,6 @@ fn process_messages(\nfalse\n}\n-/// This function processes the antenna streams, meaning it handles taking messages from\n-/// known streams, packaging them, and sending them down the line to the server. It also handles\n-/// details like closing those streams when they hangup and notifying the server end.\n-fn process_streams(streams: &mut HashMap<u64, TcpStream>, server_stream: &mut TcpStream) {\n- let mut streams_to_remove: Vec<u64> = Vec::new();\n- // First we we have to iterate over all of these connections\n- // and read to send messages up the server pipe. We need to do\n- // this first becuase we may exit in the next section if there's\n- // nothing to write\n- for (stream_id, antenna_stream) in streams.iter_mut() {\n- // in theory we will figure out if the connection is closed here\n- // and then send a closed message\n- match read_till_block(antenna_stream) {\n- Ok(bytes) => {\n- if !bytes.is_empty() {\n- trace!(\n- \"We have {} bytes to write from a antenna input socket\",\n- bytes.len()\n- );\n- let msg =\n- ForwardingProtocolMessage::new_connection_data_message(*stream_id, bytes);\n- write_all_spinlock(server_stream, &msg.get_message())\n- .unwrap_or_else(|_| panic!(\"Failed to write with stream {}\", *stream_id));\n- }\n- }\n- Err(e) => {\n- if e.kind() != WouldBlock {\n- error!(\"Could not read client socket with {:?}\", e);\n- let msg = ForwardingProtocolMessage::new_connection_close_message(*stream_id);\n- write_all_spinlock(server_stream, &msg.get_message())\n- .unwrap_or_else(|_| panic!(\"Failed to close stream {}\", *stream_id));\n- let _ = antenna_stream.shutdown(Shutdown::Write);\n- streams_to_remove.push(*stream_id);\n- }\n- }\n- }\n- }\n- for i in streams_to_remove {\n- streams.remove(&i);\n- }\n-}\n-\n/// Actually forwards the connection by managing the reading and writing from\n/// various tcp sockets\nfn forward_connections(\n"
},
{
"change_type": "MODIFY",
"old_path": "antenna_forwarding_protocol/Cargo.toml",
"new_path": "antenna_forwarding_protocol/Cargo.toml",
"diff": "@@ -12,6 +12,7 @@ serde = \"1.0\"\nsodiumoxide = \"0.2\"\nfailure = \"0.1\"\nclarity = \"0.1\"\n+log = \"0.4\"\n[dev-dependencies]\nrand = \"0.7\"\n\\ No newline at end of file\n"
},
{
"change_type": "MODIFY",
"old_path": "antenna_forwarding_protocol/src/lib.rs",
"new_path": "antenna_forwarding_protocol/src/lib.rs",
"diff": "extern crate serde_derive;\n#[macro_use]\nextern crate failure;\n+#[macro_use]\n+extern crate log;\nuse althea_types::Identity;\nuse failure::Error;\n+use std::collections::HashMap;\nuse std::io::Error as IoError;\nuse std::io::ErrorKind::WouldBlock;\nuse std::io::Read;\nuse std::io::Write;\nuse std::net::IpAddr;\n+use std::net::Shutdown;\nuse std::net::TcpStream;\nuse std::thread;\nuse std::time::Duration;\n/// The amount of time to sleep a thread that's spinlocking on somthing\n-pub const SPINLOCK_TIME: Duration = Duration::from_millis(10);\n+pub const SPINLOCK_TIME: Duration = Duration::from_millis(50);\n/// The amount of time to wait for a blocking read\npub const NET_TIMEOUT: Duration = Duration::from_secs(1);\n@@ -38,6 +42,7 @@ pub const HEADER_LEN: usize = 20;\n/// Writes data to a stream keeping in mind that we may encounter\n/// a buffer limit and have to partially complete our write\npub fn write_all_spinlock(stream: &mut TcpStream, buffer: &[u8]) -> Result<(), IoError> {\n+ stream.set_nonblocking(true)?;\nloop {\nlet res = stream.write_all(buffer);\nmatch res {\n@@ -70,6 +75,8 @@ pub fn read_till_block(input: &mut TcpStream) -> Result<Vec<u8>, IoError> {\nErr(e) => {\nif e.kind() == WouldBlock {\nreturn Ok(out);\n+ } else if !out.is_empty() {\n+ return Ok(out);\n} else {\nreturn Err(e);\n}\n@@ -100,6 +107,47 @@ pub fn read_till_timeout(input: &mut TcpStream) -> Result<Vec<u8>, IoError> {\n}\n}\n+/// This function processes the antenna streams, meaning it handles taking messages from\n+/// known streams, packaging them, and sending them down the line to the server. It also handles\n+/// details like closing those streams when they hangup and notifying the other end.\n+pub fn process_streams<S: ::std::hash::BuildHasher>(\n+ streams: &mut HashMap<u64, TcpStream, S>,\n+ server_stream: &mut TcpStream,\n+) {\n+ let mut streams_to_remove: Vec<u64> = Vec::new();\n+ // First we we have to iterate over all of these connections\n+ // and read to send messages up the server pipe. We need to do\n+ // this first becuase we may exit in the next section if there's\n+ // nothing to write\n+ for (stream_id, antenna_stream) in streams.iter_mut() {\n+ // in theory we will figure out if the connection is closed here\n+ // and then send a closed message\n+ match read_till_block(antenna_stream) {\n+ Ok(bytes) => {\n+ if !bytes.is_empty() {\n+ let msg =\n+ ForwardingProtocolMessage::new_connection_data_message(*stream_id, bytes);\n+ write_all_spinlock(server_stream, &msg.get_message())\n+ .unwrap_or_else(|_| panic!(\"Failed to write with stream {}\", *stream_id));\n+ }\n+ }\n+ Err(e) => {\n+ if e.kind() != WouldBlock {\n+ error!(\"Closing antenna/client connection with {:?}\", e);\n+ let msg = ForwardingProtocolMessage::new_connection_close_message(*stream_id);\n+ write_all_spinlock(server_stream, &msg.get_message())\n+ .unwrap_or_else(|_| panic!(\"Failed to close stream {}\", *stream_id));\n+ let _ = antenna_stream.shutdown(Shutdown::Write);\n+ streams_to_remove.push(*stream_id);\n+ }\n+ }\n+ }\n+ }\n+ for i in streams_to_remove {\n+ streams.remove(&i);\n+ }\n+}\n+\n/// All valid packet types for the forwarding protocool, two of these\n/// types, ConnectionCloseMessage and ConnectionDataMessage are raw byte packets\n/// the rest have the byte based header but are followed by a struct object to\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | More deduplication for ForwardingProtocol
Additional functions where moved into the protocol library for use
by the server. |
20,244 | 30.03.2020 21:52:28 | 14,400 | 9a1fe9f109d0c5b75c51c5bf1ba4ae9604ee4377 | Use read_to_end for forwarding
If we're reading into a vector may as well use this trait function that's
much better implemented. | [
{
"change_type": "MODIFY",
"old_path": "antenna_forwarding_protocol/src/lib.rs",
"new_path": "antenna_forwarding_protocol/src/lib.rs",
"diff": "@@ -63,23 +63,14 @@ pub fn write_all_spinlock(stream: &mut TcpStream, buffer: &[u8]) -> Result<(), I\npub fn read_till_block(input: &mut TcpStream) -> Result<Vec<u8>, IoError> {\ninput.set_nonblocking(true)?;\nlet mut out = Vec::new();\n- loop {\n- let mut buffer: [u8; BUFFER_SIZE] = [0; BUFFER_SIZE];\n- match input.read(&mut buffer) {\n- Ok(bytes) => {\n- if bytes == 0 {\n- return Ok(out);\n- }\n- out.extend_from_slice(&buffer)\n- }\n+ match input.read_to_end(&mut out) {\n+ Ok(_bytes) => Ok(out),\nErr(e) => {\nif e.kind() == WouldBlock {\n- return Ok(out);\n- } else if !out.is_empty() {\n- return Ok(out);\n+ Ok(out)\n} else {\n- return Err(e);\n- }\n+ error!(\"Broken! {:?}\", e);\n+ Err(e)\n}\n}\n}\n@@ -125,6 +116,11 @@ pub fn process_streams<S: ::std::hash::BuildHasher>(\nmatch read_till_block(antenna_stream) {\nOk(bytes) => {\nif !bytes.is_empty() {\n+ info!(\n+ \"Got {} bytes for stream id {} from antenna/client\",\n+ bytes.len(),\n+ stream_id\n+ );\nlet msg =\nForwardingProtocolMessage::new_connection_data_message(*stream_id, bytes);\nwrite_all_spinlock(server_stream, &msg.get_message())\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Use read_to_end for forwarding
If we're reading into a vector may as well use this trait function that's
much better implemented. |
20,244 | 31.03.2020 07:22:48 | 14,400 | 0dd9a55be1747830621aa9fde908cbdd8d3b3382 | Remove unused functions and raise spinlock time to 100ms
The 100ms spinlock results in somewhat better performance on the routers. | [
{
"change_type": "MODIFY",
"old_path": "Cargo.lock",
"new_path": "Cargo.lock",
"diff": "@@ -221,6 +221,7 @@ dependencies = [\n\"althea_types\",\n\"clarity\",\n\"failure\",\n+ \"log\",\n\"rand 0.7.3\",\n\"serde 1.0.105\",\n\"serde_derive\",\n"
},
{
"change_type": "MODIFY",
"old_path": "antenna_forwarding_client/src/lib.rs",
"new_path": "antenna_forwarding_client/src/lib.rs",
"diff": "@@ -79,11 +79,8 @@ pub fn start_antenna_forwarding_proxy<S: 'static + std::marker::Send + ::std::ha\nthread::sleep(NET_TIMEOUT);\nmatch ForwardingProtocolMessage::read_messages(&mut server_stream) {\nOk(messages) => {\n- if messages.is_empty() {\n- error!(\"Empty vector from read_messages?\");\n- }\n// read messages will return a vec of at least one,\n- else if let Some(ForwardingProtocolMessage::ForwardMessage {\n+ if let Some(ForwardingProtocolMessage::ForwardMessage {\nip,\nserver_port: _server_port,\nantenna_port,\n@@ -104,6 +101,8 @@ pub fn start_antenna_forwarding_proxy<S: 'static + std::marker::Send + ::std::ha\n}\nErr(e) => send_error_message(&mut server_stream, format!(\"{:?}\", e)),\n}\n+ } else {\n+ error!(\"Wrong start message!\");\n}\n}\nErr(e) => {\n"
},
{
"change_type": "MODIFY",
"old_path": "antenna_forwarding_protocol/src/lib.rs",
"new_path": "antenna_forwarding_protocol/src/lib.rs",
"diff": "@@ -27,15 +27,11 @@ use std::thread;\nuse std::time::Duration;\n/// The amount of time to sleep a thread that's spinlocking on somthing\n-pub const SPINLOCK_TIME: Duration = Duration::from_millis(50);\n+pub const SPINLOCK_TIME: Duration = Duration::from_millis(100);\n/// The amount of time to wait for a blocking read\npub const NET_TIMEOUT: Duration = Duration::from_secs(1);\n-/// The size of the memory buffer for reading and writing packets\n-/// currently 100kbytes\n-pub const BUFFER_SIZE: usize = 100_000;\n-\n/// The size in bytes of our packet header, 16 byte magic, 2 byte type, 2 byte len\npub const HEADER_LEN: usize = 20;\n@@ -76,28 +72,6 @@ pub fn read_till_block(input: &mut TcpStream) -> Result<Vec<u8>, IoError> {\n}\n}\n-/// Reads the entire contents of a tcpstream into a buffer until it times out\n-/// if it fills the buffer it will recurse and read until th buffer is empty\n-/// if the buffer is being filled faster than it can read it will run out of memory\n-pub fn read_till_timeout(input: &mut TcpStream) -> Result<Vec<u8>, IoError> {\n- input.set_nonblocking(false)?;\n- input.set_read_timeout(Some(NET_TIMEOUT))?;\n- let mut out = Vec::new();\n- let mut buffer: [u8; BUFFER_SIZE] = [0; BUFFER_SIZE];\n- match input.read(&mut buffer) {\n- Ok(bytes) => {\n- if bytes == BUFFER_SIZE {\n- out.extend_from_slice(&buffer);\n- out.extend_from_slice(&read_till_block(input)?);\n- Ok(out)\n- } else {\n- Ok(buffer.to_vec())\n- }\n- }\n- Err(e) => Err(e),\n- }\n-}\n-\n/// This function processes the antenna streams, meaning it handles taking messages from\n/// known streams, packaging them, and sending them down the line to the server. It also handles\n/// details like closing those streams when they hangup and notifying the other end.\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Remove unused functions and raise spinlock time to 100ms
The 100ms spinlock results in somewhat better performance on the routers. |
20,244 | 31.03.2020 15:46:13 | 14,400 | 3c5fa58aabe3019ab59bcaf6da8eeab2a2179e07 | Don't use armv7 in cross tests
this is also behaving strangely in cross. I'm starting to think they
changed stuff upstream and I'm going to have to actually focus in on
fixing it. | [
{
"change_type": "MODIFY",
"old_path": "scripts/test.sh",
"new_path": "scripts/test.sh",
"diff": "#!/bin/bash\n-#set -eux\n+set -eux\nNODES=${NODES:='None'}\nRUST_TEST_THREADS=1 cargo test --all\n@@ -9,8 +9,6 @@ cross test --target mipsel-unknown-linux-gnu --verbose -p rita --bin rita -- --t\ncross test --target mips64-unknown-linux-gnuabi64 --verbose -p rita --bin rita -- --test-threads=1\ncross test --target mips64el-unknown-linux-gnuabi64 --verbose -p rita --bin rita -- --test-threads=1\ncross test --target aarch64-unknown-linux-gnu --verbose -p rita --bin rita -- --test-threads=1\n-cross test --target armv7-unknown-linux-gnueabi --verbose -p rita --bin rita -- --test-threads=1\n-cross test --target armv7-unknown-linux-gnueabihf --verbose -p rita --bin rita -- --test-threads=1\nif ! modprobe wireguard ; then\necho \"The container can't load modules into the host kernel\"\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Don't use armv7 in cross tests
this is also behaving strangely in cross. I'm starting to think they
changed stuff upstream and I'm going to have to actually focus in on
fixing it. |
20,244 | 02.04.2020 08:28:26 | 14,400 | 2f3986e05b7747f8b8c051fd561103789d86b3fc | Doc comment for utils | [
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_common/utils/mod.rs",
"new_path": "rita/src/rita_common/utils/mod.rs",
"diff": "+/// Random utilities that don't go anywhere else, many of these are used only in one or the other of rita_exit or rita_client so one will use it and the other will\n+/// throw a dead code warning.\npub mod ip_increment;\n#[allow(dead_code)]\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Doc comment for utils |
20,244 | 09.04.2020 07:28:09 | 14,400 | ca408c8e7a621ccf501b749cf964bee7d8133b61 | Clippy iterator nit in babel monitor | [
{
"change_type": "MODIFY",
"old_path": "babel_monitor/src/lib.rs",
"new_path": "babel_monitor/src/lib.rs",
"diff": "@@ -284,7 +284,7 @@ pub fn get_local_fee(stream: TcpStream) -> impl Future<Item = (TcpStream, u32),\n}\nfn get_local_fee_sync(babel_output: String) -> Result<u32, Error> {\n- let fee_entry = match babel_output.split('\\n').nth(0) {\n+ let fee_entry = match babel_output.split('\\n').next() {\nSome(entry) => entry,\n// Even an empty string wouldn't yield None\nNone => return Err(LocalFeeNotFound(String::from(\"<Babel output is None>\")).into()),\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Clippy iterator nit in babel monitor |
20,244 | 09.04.2020 07:28:27 | 14,400 | a7e94ef30b7e4428d9dc2c5811c6fc2b380dbab7 | Into fixed sized array for WgKey | [
{
"change_type": "MODIFY",
"old_path": "althea_types/src/wg_key.rs",
"new_path": "althea_types/src/wg_key.rs",
"diff": "@@ -17,6 +17,12 @@ impl AsRef<[u8]> for WgKey {\n}\n}\n+impl From<WgKey> for [u8; 32] {\n+ fn from(val: WgKey) -> [u8; 32] {\n+ val.0\n+ }\n+}\n+\n/// This is somewhat dangerous, since libsodium provides seperate\n/// public and private key types while we don't have those here.\n/// Be very careful not to use this on the public key! That would be bad\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Into fixed sized array for WgKey |
20,244 | 09.04.2020 07:48:36 | 14,400 | ef9be5ae58c23a440a200b76f91242243fabc3c8 | Make Rita loop it's own thread
I'm hoping this reduces some of the scale/blocking problems we've been
seeing over on the portland exit. | [
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_exit/rita_loop/mod.rs",
"new_path": "rita/src/rita_exit/rita_loop/mod.rs",
"diff": "@@ -28,10 +28,7 @@ use crate::rita_exit::network_endpoints::*;\nuse crate::rita_exit::traffic_watcher::{TrafficWatcher, Watch};\nuse crate::KI;\nuse crate::SETTING;\n-use actix::{\n- Actor, ActorContext, Addr, Arbiter, AsyncContext, Context, Handler, Message, Supervised,\n- SystemService,\n-};\n+use actix::{Arbiter, SystemService};\nuse actix_web::http::Method;\nuse actix_web::{server, App};\nuse althea_kernel_interface::ExitClient;\n@@ -39,94 +36,37 @@ use babel_monitor::open_babel_stream;\nuse babel_monitor::parse_routes;\nuse babel_monitor::start_connection;\nuse diesel::query_dsl::RunQueryDsl;\n-use diesel::r2d2::ConnectionManager;\n-use diesel::r2d2::PooledConnection;\n-use diesel::PgConnection;\nuse exit_db::models;\n-use failure::Error;\nuse futures01::future::Future;\nuse settings::exit::RitaExitSettings;\nuse settings::RitaCommonSettings;\n-use std::collections::HashMap;\nuse std::collections::HashSet;\n-use std::net::IpAddr;\n+use std::thread;\nuse std::time::Duration;\nuse std::time::Instant;\nuse tokio::util::FutureExt;\n// the speed in seconds for the exit loop\npub const EXIT_LOOP_SPEED: u64 = 5;\n+pub const EXIT_LOOP_SPEED_DURATION: Duration = Duration::from_secs(EXIT_LOOP_SPEED);\npub const EXIT_LOOP_TIMEOUT: Duration = Duration::from_secs(4);\n-#[derive(Default)]\n-pub struct RitaLoop {\n- /// a simple cache to prevent regularly asking Maxmind for the same geoip data\n- pub geoip_cache: HashMap<IpAddr, String>,\n- /// a cache of what tunnels we had setup last round, used to prevent extra setup ops\n- pub wg_clients: HashSet<ExitClient>,\n-}\n-\n-impl Actor for RitaLoop {\n- type Context = Context<Self>;\n-\n- fn started(&mut self, ctx: &mut Context<Self>) {\n- info!(\"exit loop started\");\n+pub fn start_rita_exit_loop() {\nsetup_exit_wg_tunnel();\n- ctx.run_interval(Duration::from_secs(EXIT_LOOP_SPEED), move |_act, ctx| {\n- let addr: Addr<Self> = ctx.address();\n- Arbiter::spawn(get_database_connection().then(move |database| {\n- match database {\n- Ok(database) => addr.do_send(Tick(database)),\n- Err(e) => error!(\"Could not reach database for Rita sync loop! {:?}\", e),\n- }\n- Ok(())\n- }));\n- });\n- }\n-}\n-\n-impl SystemService for RitaLoop {}\n-impl Supervised for RitaLoop {\n- fn restarting(&mut self, _ctx: &mut Context<RitaLoop>) {\n- error!(\"Rita Exit loop actor died! recovering!\");\n- }\n-}\n-\n-/// Used to test actor respawning\n-pub struct Crash;\n-\n-impl Message for Crash {\n- type Result = Result<(), Error>;\n-}\n-\n-impl Handler<Crash> for RitaLoop {\n- type Result = Result<(), Error>;\n- fn handle(&mut self, _: Crash, ctx: &mut Context<Self>) -> Self::Result {\n- ctx.stop();\n- Ok(())\n- }\n-}\n-\n-pub struct Tick(PooledConnection<ConnectionManager<PgConnection>>);\n-\n-impl Message for Tick {\n- type Result = Result<(), Error>;\n-}\n-\n-impl Handler<Tick> for RitaLoop {\n- type Result = Result<(), Error>;\n- fn handle(&mut self, msg: Tick, _ctx: &mut Context<Self>) -> Self::Result {\n+ // a cache of what tunnels we had setup last round, used to prevent extra setup ops\n+ let mut wg_clients: HashSet<ExitClient> = HashSet::new();\n+ thread::spawn(move || {\n+ loop {\n+ // opening a database connection takes at least several milliseconds, as the database server\n+ // may be across the country, so to save on back and forth we open on and reuse it as much\n+ // as possible\n+ if let Ok(conn) = get_database_connection().timeout(EXIT_LOOP_TIMEOUT).wait() {\nlet start = Instant::now();\nuse exit_db::schema::clients::dsl::clients;\nlet babel_port = SETTING.get_network().babel_port;\ninfo!(\"Exit tick!\");\n- // opening a database connection takes at least several milliseconds, as the database server\n- // may be across the country, so to save on back and forth we open on and reuse it as much\n- // as possible\n- let conn = msg.0;\n-\n- let clients_list = clients.load::<models::Client>(&conn)?;\n+ if let Ok(clients_list) = clients.load::<models::Client>(&conn) {\nlet ids = clients_to_ids(clients_list.clone());\n// watch and bill for traffic\n@@ -154,8 +94,8 @@ impl Handler<Tick> for RitaLoop {\n);\n// Create and update client tunnels\n- match setup_clients(&clients_list, &self.wg_clients) {\n- Ok(wg_clients) => self.wg_clients = wg_clients,\n+ match setup_clients(&clients_list, &wg_clients) {\n+ Ok(new_wg_clients) => wg_clients = new_wg_clients,\nErr(e) => error!(\"Setup clients failed with {:?}\", e),\n}\n@@ -180,9 +120,13 @@ impl Handler<Tick> for RitaLoop {\nstart.elapsed().as_secs(),\nstart.elapsed().subsec_millis(),\n);\n- Ok(())\n}\n}\n+ // sleep for 5 seconds\n+ thread::sleep(EXIT_LOOP_SPEED_DURATION);\n+ }\n+ });\n+}\nfn setup_exit_wg_tunnel() {\nif let Err(e) = KI.setup_wg_if_named(\"wg_exit\") {\n@@ -198,7 +142,7 @@ fn setup_exit_wg_tunnel() {\n}\npub fn check_rita_exit_actors() {\n- assert!(crate::rita_exit::rita_loop::RitaLoop::from_registry().connected());\n+ start_rita_exit_loop();\nassert!(crate::rita_exit::traffic_watcher::TrafficWatcher::from_registry().connected());\nassert!(crate::rita_exit::database::db_client::DbClient::from_registry().connected());\n}\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Make Rita loop it's own thread
I'm hoping this reduces some of the scale/blocking problems we've been
seeing over on the portland exit. |
20,244 | 09.04.2020 08:17:03 | 14,400 | ea45bc5fac08484f0844dc90e29e3c9cc094dda8 | Drive all Rita exit futures from the Rita exit loop thread
This essentially moves all of Rita exit's repeating components into
a loop. The hope here is that we manage to not interfere with the
rita_common futures loop by blocking for database requests. | [
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_exit/database/mod.rs",
"new_path": "rita/src/rita_exit/database/mod.rs",
"diff": "@@ -27,7 +27,6 @@ use crate::rita_exit::database::struct_tools::display_hashset;\nuse crate::rita_exit::database::struct_tools::to_exit_client;\nuse crate::rita_exit::database::struct_tools::to_identity;\nuse crate::rita_exit::database::struct_tools::verif_done;\n-use crate::rita_exit::rita_loop::EXIT_LOOP_TIMEOUT;\nuse crate::EXIT_ALLOWED_COUNTRIES;\nuse crate::EXIT_DESCRIPTION;\nuse crate::EXIT_NETWORK_SETTINGS;\n@@ -55,7 +54,6 @@ use std::collections::HashSet;\nuse std::net::IpAddr;\nuse std::time::Instant;\nuse std::time::{Duration, SystemTime, UNIX_EPOCH};\n-use tokio::util::FutureExt;\npub mod database_tools;\npub mod db_client;\n@@ -310,7 +308,7 @@ fn low_balance_notification(\n/// client that doesn't make status requests\npub fn validate_clients_region(\nclients_list: Vec<exit_db::models::Client>,\n-) -> impl Future<Item = (), Error = ()> {\n+) -> impl Future<Item = (), Error = Error> {\ninfo!(\"Starting exit region validation\");\nlet start = Instant::now();\n@@ -326,8 +324,7 @@ pub fn validate_clients_region(\nErr(_e) => error!(\"Database entry with invalid mesh ip! {:?}\", item),\n}\n}\n- get_gateway_ip_bulk(ip_vec)\n- .and_then(move |list| {\n+ get_gateway_ip_bulk(ip_vec).and_then(move |list| {\nget_database_connection().and_then(move |conn| {\nlet mut fut_vec = Vec::new();\nfor item in list.iter() {\n@@ -357,13 +354,6 @@ pub fn validate_clients_region(\n})\n})\n})\n- .timeout(EXIT_LOOP_TIMEOUT)\n- .then(|output| {\n- if output.is_err() {\n- error!(\"Validate clients region failed with {:?}\", output);\n- }\n- Ok(())\n- })\n}\n/// Iterates over the the database of clients, if a client's last_seen value\n@@ -495,12 +485,12 @@ pub fn setup_clients(\n/// ourselves from exceeding the upstream free tier. As an exit we are the upstream.\npub fn enforce_exit_clients(\nclients_list: Vec<exit_db::models::Client>,\n-) -> Box<dyn Future<Item = (), Error = ()>> {\n+) -> Box<dyn Future<Item = (), Error = Error>> {\nlet start = Instant::now();\nBox::new(\nDebtKeeper::from_registry()\n.send(GetDebtsList)\n- .timeout(Duration::from_secs(4))\n+ .timeout(Duration::from_secs(4)).from_err()\n.and_then(move |debts_list| match debts_list {\nOk(list) => {\nlet mut clients_by_id = HashMap::new();\n@@ -574,12 +564,5 @@ pub fn enforce_exit_clients(\nOk(())\n}\n})\n- .timeout(EXIT_LOOP_TIMEOUT)\n- .then(|res| {\n- if let Err(e) = res {\n- error!(\"Exit enforcement failed with {:?}\", e);\n- }\n- Ok(())\n- }),\n)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_exit/rita_loop/mod.rs",
"new_path": "rita/src/rita_exit/rita_loop/mod.rs",
"diff": "@@ -28,7 +28,7 @@ use crate::rita_exit::network_endpoints::*;\nuse crate::rita_exit::traffic_watcher::{TrafficWatcher, Watch};\nuse crate::KI;\nuse crate::SETTING;\n-use actix::{Arbiter, SystemService};\n+use actix::SystemService;\nuse actix_web::http::Method;\nuse actix_web::{server, App};\nuse althea_kernel_interface::ExitClient;\n@@ -57,21 +57,23 @@ pub fn start_rita_exit_loop() {\nlet mut wg_clients: HashSet<ExitClient> = HashSet::new();\nthread::spawn(move || {\nloop {\n+ let start = Instant::now();\n// opening a database connection takes at least several milliseconds, as the database server\n// may be across the country, so to save on back and forth we open on and reuse it as much\n// as possible\nif let Ok(conn) = get_database_connection().timeout(EXIT_LOOP_TIMEOUT).wait() {\n- let start = Instant::now();\nuse exit_db::schema::clients::dsl::clients;\nlet babel_port = SETTING.get_network().babel_port;\n- info!(\"Exit tick!\");\n+ info!(\n+ \"Exit tick! got DB connection after {}ms\",\n+ start.elapsed().as_millis(),\n+ );\nif let Ok(clients_list) = clients.load::<models::Client>(&conn) {\nlet ids = clients_to_ids(clients_list.clone());\n// watch and bill for traffic\n- Arbiter::spawn(\n- open_babel_stream(babel_port)\n+ let res = open_babel_stream(babel_port)\n.from_err()\n.and_then(|stream| {\nstart_connection(stream).and_then(|stream| {\n@@ -85,13 +87,19 @@ pub fn start_rita_exit_loop() {\n})\n})\n.timeout(EXIT_LOOP_TIMEOUT)\n- .then(|ret| {\n- if let Err(e) = ret {\n- error!(\"Failed to watch Exit traffic with {:?}\", e)\n- }\n- Ok(())\n- }),\n+ .wait();\n+ if let Err(e) = res {\n+ warn!(\n+ \"Failed to watch exit traffic with {} {}ms since start\",\n+ e,\n+ start.elapsed().as_millis()\n+ );\n+ } else {\n+ info!(\n+ \"Exit billing completed successfully {}ms since loop start\",\n+ start.elapsed().as_millis()\n);\n+ }\n// Create and update client tunnels\nmatch setup_clients(&clients_list, &wg_clients) {\n@@ -108,17 +116,44 @@ pub fn start_rita_exit_loop() {\n// Make sure no one we are setting up is geoip unauthorized\nif !SETTING.get_allowed_countries().is_empty() {\n- Arbiter::spawn(validate_clients_region(clients_list.clone()));\n+ let res = validate_clients_region(clients_list.clone())\n+ .timeout(EXIT_LOOP_TIMEOUT)\n+ .wait();\n+ if let Err(e) = res {\n+ warn!(\n+ \"Failed to validate client region with {} {}ms since start\",\n+ e,\n+ start.elapsed().as_millis()\n+ );\n+ } else {\n+ info!(\n+ \"Validated client region {}ms since loop start\",\n+ start.elapsed().as_millis()\n+ );\n+ }\n}\n// handle enforcement on client tunnels by querying debt keeper\n// this consumes client list, you can move it up in exchange for a clone\n- Arbiter::spawn(enforce_exit_clients(clients_list));\n+ let res = enforce_exit_clients(clients_list)\n+ .timeout(EXIT_LOOP_TIMEOUT)\n+ .wait();\n+ if let Err(e) = res {\n+ warn!(\n+ \"Failed enforce exit clients with {} {}ms since start\",\n+ e,\n+ start.elapsed().as_millis()\n+ );\n+ } else {\n+ info!(\n+ \"Enforced exit clients {}ms since loop start\",\n+ start.elapsed().as_millis()\n+ );\n+ }\ninfo!(\n- \"Completed Rita sync loop in {}s {}ms, all vars should be dropped\",\n- start.elapsed().as_secs(),\n- start.elapsed().subsec_millis(),\n+ \"Completed Rita sync loop in {}ms, all vars should be dropped\",\n+ start.elapsed().as_millis(),\n);\n}\n}\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Drive all Rita exit futures from the Rita exit loop thread
This essentially moves all of Rita exit's repeating components into
a loop. The hope here is that we manage to not interfere with the
rita_common futures loop by blocking for database requests. |
20,244 | 09.04.2020 11:01:55 | 14,400 | 4c275068ee8fc7918723d49e60964c3ecfb02b76 | Fix timeouts and actor references for Rita Exit thread
This fixes a lot of the runtime complexities of living outside
of the main arbiter thread.
TODO add poll with timeout utiliy function right now if any of
these futures blocks we will end up hanging on it. | [
{
"change_type": "MODIFY",
"old_path": "babel_monitor/src/lib.rs",
"new_path": "babel_monitor/src/lib.rs",
"diff": "@@ -28,13 +28,10 @@ use std::net::IpAddr;\nuse std::net::SocketAddr;\nuse std::str;\nuse std::str::FromStr;\n-use std::time::Duration;\n-use std::time::Instant;\nuse tokio::io::read;\nuse tokio::io::write_all;\nuse tokio::net::tcp::ConnectFuture;\nuse tokio::net::TcpStream;\n-use tokio::timer::Delay;\n#[derive(Debug, Fail)]\npub enum BabelMonitorError {\n@@ -181,13 +178,8 @@ fn read_babel(\n// our buffer was not full but we also did not find a terminator,\n// we must have caught babel while it was interupped (only really happens\n// in single cpu situations)\n- let when = Instant::now() + Duration::from_millis(100);\ntrace!(\"we didn't get the whole message yet, trying again\");\n- return Box::new(\n- Delay::new(when)\n- .map_err(move |e| panic!(\"timer failed; err={:?}\", e))\n- .and_then(move |_| read_babel(stream, full_message, depth + 1)),\n- );\n+ return Box::new(read_babel(stream, full_message, depth + 1));\n} else if let Err(e) = babel_data {\n// some other error\nwarn!(\"Babel read failed! {} {:?}\", output, e);\n"
},
{
"change_type": "MODIFY",
"old_path": "rita/src/exit.rs",
"new_path": "rita/src/exit.rs",
"diff": "@@ -64,6 +64,7 @@ use rita_common::rita_loop::start_core_rita_endpoints;\nuse rita_exit::rita_loop::check_rita_exit_actors;\nuse rita_exit::rita_loop::start_rita_exit_endpoints;\n+use rita_exit::rita_loop::start_rita_exit_loop;\nuse crate::rita_common::dashboard::auth::*;\nuse crate::rita_common::dashboard::babel::*;\n@@ -257,6 +258,7 @@ fn main() {\ncheck_rita_common_actors();\ncheck_rita_exit_actors();\n+ start_rita_exit_loop();\nlet workers = SETTING.get_workers();\nstart_core_rita_endpoints(workers as usize);\nstart_rita_exit_endpoints(workers as usize);\n"
},
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_exit/database/mod.rs",
"new_path": "rita/src/rita_exit/database/mod.rs",
"diff": "@@ -35,12 +35,11 @@ use crate::EXIT_SYSTEM_CHAIN;\nuse crate::EXIT_VERIF_SETTINGS;\nuse crate::KI;\nuse crate::SETTING;\n-use ::actix::SystemService;\n+use actix::Addr;\nuse althea_kernel_interface::ExitClient;\nuse althea_types::{ExitClientDetails, ExitClientIdentity, ExitDetails, ExitState, ExitVerifMode};\nuse diesel;\nuse diesel::prelude::PgConnection;\n-use exit_db::schema;\nuse failure::Error;\nuse futures01::future;\nuse futures01::future::join_all;\n@@ -422,14 +421,12 @@ pub fn setup_clients(\nclients_list: &[exit_db::models::Client],\nold_clients: &HashSet<ExitClient>,\n) -> Result<HashSet<ExitClient>, Error> {\n- use self::schema::clients::dsl::clients;\n-\nlet start = Instant::now();\n// use hashset to ensure uniqueness and check for duplicate db entries\nlet mut wg_clients = HashSet::new();\n- trace!(\"got clients from db {:?}\", clients);\n+ trace!(\"got clients from db {:?} {:?}\", clients_list, old_clients);\nfor c in clients_list.iter() {\nmatch (c.verified, to_exit_client(c.clone())) {\n@@ -485,12 +482,13 @@ pub fn setup_clients(\n/// ourselves from exceeding the upstream free tier. As an exit we are the upstream.\npub fn enforce_exit_clients(\nclients_list: Vec<exit_db::models::Client>,\n+ debt_keeper: Addr<DebtKeeper>,\n) -> Box<dyn Future<Item = (), Error = Error>> {\nlet start = Instant::now();\nBox::new(\n- DebtKeeper::from_registry()\n+ debt_keeper\n.send(GetDebtsList)\n- .timeout(Duration::from_secs(4)).from_err()\n+ .from_err()\n.and_then(move |debts_list| match debts_list {\nOk(list) => {\nlet mut clients_by_id = HashMap::new();\n"
},
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_exit/rita_loop/mod.rs",
"new_path": "rita/src/rita_exit/rita_loop/mod.rs",
"diff": "//! actix work together on this on properly, not that I've every seen simple actors like the loop crash\n//! very often.\n+use crate::rita_common::debt_keeper::DebtKeeper;\nuse crate::rita_exit::database::database_tools::get_database_connection;\nuse crate::rita_exit::database::struct_tools::clients_to_ids;\nuse crate::rita_exit::database::{\n@@ -44,7 +45,6 @@ use std::collections::HashSet;\nuse std::thread;\nuse std::time::Duration;\nuse std::time::Instant;\n-use tokio::util::FutureExt;\n// the speed in seconds for the exit loop\npub const EXIT_LOOP_SPEED: u64 = 5;\n@@ -55,13 +55,19 @@ pub fn start_rita_exit_loop() {\nsetup_exit_wg_tunnel();\n// a cache of what tunnels we had setup last round, used to prevent extra setup ops\nlet mut wg_clients: HashSet<ExitClient> = HashSet::new();\n- thread::spawn(move || {\n+ let tw = TrafficWatcher::from_registry();\n+ let dk = DebtKeeper::from_registry();\n+ let _res = thread::spawn(move || {\n+ // wait until the system gets started\n+ while !(dk.connected() && tw.connected()) {\n+ trace!(\"Waiting for actors to start\");\n+ }\nloop {\nlet start = Instant::now();\n// opening a database connection takes at least several milliseconds, as the database server\n// may be across the country, so to save on back and forth we open on and reuse it as much\n// as possible\n- if let Ok(conn) = get_database_connection().timeout(EXIT_LOOP_TIMEOUT).wait() {\n+ if let Ok(conn) = get_database_connection().wait() {\nuse exit_db::schema::clients::dsl::clients;\nlet babel_port = SETTING.get_network().babel_port;\ninfo!(\n@@ -70,15 +76,19 @@ pub fn start_rita_exit_loop() {\n);\nif let Ok(clients_list) = clients.load::<models::Client>(&conn) {\n+ trace!(\"got {:?} clients\", clients_list);\nlet ids = clients_to_ids(clients_list.clone());\n// watch and bill for traffic\n+ trace!(\"about to try opening babel stream\");\nlet res = open_babel_stream(babel_port)\n.from_err()\n.and_then(|stream| {\n+ trace!(\"got babel stream\");\nstart_connection(stream).and_then(|stream| {\nparse_routes(stream).and_then(|routes| {\n- TrafficWatcher::from_registry().do_send(Watch {\n+ trace!(\"Sending traffic watcher message?\");\n+ tw.do_send(Watch {\nusers: ids,\nroutes: routes.1,\n});\n@@ -86,42 +96,41 @@ pub fn start_rita_exit_loop() {\n})\n})\n})\n- .timeout(EXIT_LOOP_TIMEOUT)\n.wait();\nif let Err(e) = res {\nwarn!(\n- \"Failed to watch exit traffic with {} {}ms since start\",\n+ \"Failed to watch exit traffic with {:?} {}ms since start\",\ne,\nstart.elapsed().as_millis()\n);\n} else {\ninfo!(\n- \"Exit billing completed successfully {}ms since loop start\",\n+ \"watch exit traffic completed successfully {}ms since loop start\",\nstart.elapsed().as_millis()\n);\n}\n+ trace!(\"about to setup clients\");\n// Create and update client tunnels\nmatch setup_clients(&clients_list, &wg_clients) {\nOk(new_wg_clients) => wg_clients = new_wg_clients,\nErr(e) => error!(\"Setup clients failed with {:?}\", e),\n}\n+ trace!(\"about to cleanup clients\");\n// find users that have not been active within the configured time period\n// and remove them from the db\n- let res = cleanup_exit_clients(&clients_list, &conn);\n- if res.is_err() {\n- error!(\"Exit client cleanup failed with {:?}\", res);\n+ if let Err(e) = cleanup_exit_clients(&clients_list, &conn) {\n+ error!(\"Exit client cleanup failed with {:?}\", e);\n}\n// Make sure no one we are setting up is geoip unauthorized\n- if !SETTING.get_allowed_countries().is_empty() {\n- let res = validate_clients_region(clients_list.clone())\n- .timeout(EXIT_LOOP_TIMEOUT)\n- .wait();\n+ let val = SETTING.get_allowed_countries().is_empty();\n+ if !val {\n+ let res = validate_clients_region(clients_list.clone()).wait();\nif let Err(e) = res {\nwarn!(\n- \"Failed to validate client region with {} {}ms since start\",\n+ \"Failed to validate client region with {:?} {}ms since start\",\ne,\nstart.elapsed().as_millis()\n);\n@@ -135,12 +144,10 @@ pub fn start_rita_exit_loop() {\n// handle enforcement on client tunnels by querying debt keeper\n// this consumes client list, you can move it up in exchange for a clone\n- let res = enforce_exit_clients(clients_list)\n- .timeout(EXIT_LOOP_TIMEOUT)\n- .wait();\n+ let res = enforce_exit_clients(clients_list, dk.clone()).wait();\nif let Err(e) = res {\nwarn!(\n- \"Failed enforce exit clients with {} {}ms since start\",\n+ \"Failed enforce exit clients with {:?} {}ms since start\",\ne,\nstart.elapsed().as_millis()\n);\n@@ -177,7 +184,6 @@ fn setup_exit_wg_tunnel() {\n}\npub fn check_rita_exit_actors() {\n- start_rita_exit_loop();\nassert!(crate::rita_exit::traffic_watcher::TrafficWatcher::from_registry().connected());\nassert!(crate::rita_exit::database::db_client::DbClient::from_registry().connected());\n}\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Fix timeouts and actor references for Rita Exit thread
This fixes a lot of the runtime complexities of living outside
of the main arbiter thread.
TODO add poll with timeout utiliy function right now if any of
these futures blocks we will end up hanging on it. |
20,244 | 09.04.2020 12:09:40 | 14,400 | 967303eb61c6aef454317a54ace03328f088a3ce | Add timeouts to exit loop thread polling
Well at least we where barking up the right tree, this was
in production not 30 seconds before we hit somthing that likes to
block | [
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_exit/rita_loop/mod.rs",
"new_path": "rita/src/rita_exit/rita_loop/mod.rs",
"diff": "@@ -26,6 +26,8 @@ use crate::rita_exit::database::{\ncleanup_exit_clients, enforce_exit_clients, setup_clients, validate_clients_region,\n};\nuse crate::rita_exit::network_endpoints::*;\n+use crate::rita_exit::rita_loop::wait_timeout::wait_timeout;\n+use crate::rita_exit::rita_loop::wait_timeout::WaitResult;\nuse crate::rita_exit::traffic_watcher::{TrafficWatcher, Watch};\nuse crate::KI;\nuse crate::SETTING;\n@@ -46,6 +48,8 @@ use std::thread;\nuse std::time::Duration;\nuse std::time::Instant;\n+mod wait_timeout;\n+\n// the speed in seconds for the exit loop\npub const EXIT_LOOP_SPEED: u64 = 5;\npub const EXIT_LOOP_SPEED_DURATION: Duration = Duration::from_secs(EXIT_LOOP_SPEED);\n@@ -67,7 +71,8 @@ pub fn start_rita_exit_loop() {\n// opening a database connection takes at least several milliseconds, as the database server\n// may be across the country, so to save on back and forth we open on and reuse it as much\n// as possible\n- if let Ok(conn) = get_database_connection().wait() {\n+ match wait_timeout(get_database_connection(), EXIT_LOOP_TIMEOUT) {\n+ WaitResult::Ok(conn) => {\nuse exit_db::schema::clients::dsl::clients;\nlet babel_port = SETTING.get_network().babel_port;\ninfo!(\n@@ -81,9 +86,8 @@ pub fn start_rita_exit_loop() {\n// watch and bill for traffic\ntrace!(\"about to try opening babel stream\");\n- let res = open_babel_stream(babel_port)\n- .from_err()\n- .and_then(|stream| {\n+ let res = wait_timeout(\n+ open_babel_stream(babel_port).from_err().and_then(|stream| {\ntrace!(\"got babel stream\");\nstart_connection(stream).and_then(|stream| {\nparse_routes(stream).and_then(|routes| {\n@@ -95,29 +99,33 @@ pub fn start_rita_exit_loop() {\nOk(())\n})\n})\n- })\n- .wait();\n- if let Err(e) = res {\n- warn!(\n+ }),\n+ EXIT_LOOP_TIMEOUT,\n+ );\n+ match res {\n+ WaitResult::Err(e) => warn!(\n\"Failed to watch exit traffic with {:?} {}ms since start\",\ne,\nstart.elapsed().as_millis()\n- );\n- } else {\n- info!(\n+ ),\n+ WaitResult::Ok(_) => info!(\n\"watch exit traffic completed successfully {}ms since loop start\",\nstart.elapsed().as_millis()\n- );\n+ ),\n+ WaitResult::TimedOut(_) => error!(\n+ \"watch exit traffic timed out! {}ms since loop start\",\n+ start.elapsed().as_millis()\n+ ),\n}\n- trace!(\"about to setup clients\");\n+ info!(\"about to setup clients\");\n// Create and update client tunnels\nmatch setup_clients(&clients_list, &wg_clients) {\nOk(new_wg_clients) => wg_clients = new_wg_clients,\nErr(e) => error!(\"Setup clients failed with {:?}\", e),\n}\n- trace!(\"about to cleanup clients\");\n+ info!(\"about to cleanup clients\");\n// find users that have not been active within the configured time period\n// and remove them from the db\nif let Err(e) = cleanup_exit_clients(&clients_list, &conn) {\n@@ -127,45 +135,63 @@ pub fn start_rita_exit_loop() {\n// Make sure no one we are setting up is geoip unauthorized\nlet val = SETTING.get_allowed_countries().is_empty();\nif !val {\n- let res = validate_clients_region(clients_list.clone()).wait();\n- if let Err(e) = res {\n- warn!(\n+ let res = wait_timeout(\n+ validate_clients_region(clients_list.clone()),\n+ EXIT_LOOP_TIMEOUT,\n+ );\n+ match res {\n+ WaitResult::Err(e) => warn!(\n\"Failed to validate client region with {:?} {}ms since start\",\ne,\nstart.elapsed().as_millis()\n- );\n- } else {\n- info!(\n- \"Validated client region {}ms since loop start\",\n+ ),\n+ WaitResult::Ok(_) => info!(\n+ \"validate client region completed successfully {}ms since loop start\",\nstart.elapsed().as_millis()\n- );\n+ ),\n+ WaitResult::TimedOut(_) => error!(\n+ \"validate client region timed out! {}ms since loop start\",\n+ start.elapsed().as_millis()\n+ ),\n}\n}\n// handle enforcement on client tunnels by querying debt keeper\n// this consumes client list, you can move it up in exchange for a clone\n- let res = enforce_exit_clients(clients_list, dk.clone()).wait();\n- if let Err(e) = res {\n- warn!(\n- \"Failed enforce exit clients with {:?} {}ms since start\",\n+ let res = wait_timeout(\n+ enforce_exit_clients(clients_list, dk.clone()),\n+ EXIT_LOOP_TIMEOUT,\n+ );\n+ match res {\n+ WaitResult::Err(e) => warn!(\n+ \"Failed to enforce exit clients with {:?} {}ms since start\",\ne,\nstart.elapsed().as_millis()\n- );\n- } else {\n- info!(\n- \"Enforced exit clients {}ms since loop start\",\n+ ),\n+ WaitResult::Ok(_) => info!(\n+ \"exit client enforcement completed successfully {}ms since loop start\",\nstart.elapsed().as_millis()\n- );\n+ ),\n+ WaitResult::TimedOut(_) => error!(\n+ \"exit client enforcement timed out! {}ms since loop start\",\n+ start.elapsed().as_millis()\n+ ),\n}\ninfo!(\n- \"Completed Rita sync loop in {}ms, all vars should be dropped\",\n+ \"Completed Rita exit loop in {}ms, all vars should be dropped\",\nstart.elapsed().as_millis(),\n);\n}\n}\n- // sleep for 5 seconds\n- thread::sleep(EXIT_LOOP_SPEED_DURATION);\n+ WaitResult::Err(e) => error!(\"Failed to get database connection with {}\", e),\n+ WaitResult::TimedOut(_) => error!(\"Database connection timed out\"),\n+ }\n+ // sleep until it has been 5 seconds from start, whenever that may be\n+ // if it has been more than 5 seconds from start, go right ahead\n+ if start.elapsed() < EXIT_LOOP_SPEED_DURATION {\n+ thread::sleep(EXIT_LOOP_SPEED_DURATION - start.elapsed());\n+ }\n}\n});\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "rita/src/rita_exit/rita_loop/wait_timeout.rs",
"diff": "+/// Copied from here https://gist.github.com/alexcrichton/871b5bf058a2ce77ac4fedccf3fda9c9\n+/// turns out poll with timeout is quite complex, turned off warnings becuase we've already\n+/// scoped these as futures01\n+use futures01::executor::{self, Spawn};\n+#[allow(deprecated)]\n+use futures01::task::Unpark;\n+use futures01::{Async, Future};\n+use std::sync::atomic::{AtomicBool, Ordering};\n+use std::sync::Arc;\n+use std::thread;\n+use std::time::{Duration, Instant};\n+\n+pub enum WaitResult<F: Future> {\n+ Ok(F::Item),\n+ Err(F::Error),\n+ TimedOut(Spawn<F>),\n+}\n+\n+pub fn wait_timeout<F: Future>(f: F, dur: Duration) -> WaitResult<F> {\n+ let now = Instant::now();\n+ let mut task = executor::spawn(f);\n+ let thread = Arc::new(ThreadUnpark::new(thread::current()));\n+\n+ loop {\n+ let cur = Instant::now();\n+ if cur >= now + dur {\n+ return WaitResult::TimedOut(task);\n+ }\n+ #[allow(deprecated)]\n+ match task.poll_future(thread.clone()) {\n+ Ok(Async::Ready(e)) => return WaitResult::Ok(e),\n+ Ok(Async::NotReady) => {}\n+ Err(e) => return WaitResult::Err(e),\n+ }\n+\n+ thread.park(now + dur - cur);\n+ }\n+\n+ struct ThreadUnpark {\n+ thread: thread::Thread,\n+ ready: AtomicBool,\n+ }\n+\n+ impl ThreadUnpark {\n+ fn new(thread: thread::Thread) -> ThreadUnpark {\n+ ThreadUnpark {\n+ thread,\n+ ready: AtomicBool::new(false),\n+ }\n+ }\n+\n+ fn park(&self, dur: Duration) {\n+ if !self.ready.swap(false, Ordering::SeqCst) {\n+ thread::park_timeout(dur);\n+ }\n+ }\n+ }\n+\n+ #[allow(deprecated)]\n+ impl Unpark for ThreadUnpark {\n+ fn unpark(&self) {\n+ self.ready.store(true, Ordering::SeqCst);\n+ self.thread.unpark()\n+ }\n+ }\n+}\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Add timeouts to exit loop thread polling
Well at least we where barking up the right tree, this was
in production not 30 seconds before we hit somthing that likes to
block |
20,244 | 09.04.2020 14:11:47 | 14,400 | 27e69e044aeb01d18af02da31c711b708fc6f7b8 | Use syncronous geoip requests
We can no longer use actix client since we are making requests in
another thread now. This is unfortunate because this same codepath
is run by the worker threads for client checkins. | [
{
"change_type": "MODIFY",
"old_path": "Cargo.lock",
"new_path": "Cargo.lock",
"diff": "@@ -8,7 +8,7 @@ checksum = \"6c616db5fa4b0c40702fb75201c2af7f8aa8f3a2e2c1dda3b0655772aa949666\"\ndependencies = [\n\"actix_derive 0.3.2\",\n\"bitflags\",\n- \"bytes\",\n+ \"bytes 0.4.12\",\n\"crossbeam-channel\",\n\"failure\",\n\"fnv\",\n@@ -17,7 +17,7 @@ dependencies = [\n\"log\",\n\"parking_lot 0.7.1\",\n\"smallvec 0.6.13\",\n- \"tokio\",\n+ \"tokio 0.1.22\",\n\"tokio-codec\",\n\"tokio-executor\",\n\"tokio-io\",\n@@ -37,7 +37,7 @@ source = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"8bebfbe6629e0131730746718c9e032b58f02c6ce06ed7c982b9fef6c8545acd\"\ndependencies = [\n\"actix\",\n- \"bytes\",\n+ \"bytes 0.4.12\",\n\"futures 0.1.29\",\n\"log\",\n\"mio\",\n@@ -45,7 +45,7 @@ dependencies = [\n\"num_cpus\",\n\"openssl\",\n\"slab\",\n- \"tokio\",\n+ \"tokio 0.1.22\",\n\"tokio-codec\",\n\"tokio-current-thread\",\n\"tokio-io\",\n@@ -53,7 +53,7 @@ dependencies = [\n\"tokio-reactor\",\n\"tokio-tcp\",\n\"tokio-timer\",\n- \"tower-service\",\n+ \"tower-service 0.1.0\",\n\"trust-dns-resolver\",\n]\n@@ -68,14 +68,14 @@ dependencies = [\n\"base64 0.10.1\",\n\"bitflags\",\n\"byteorder\",\n- \"bytes\",\n+ \"bytes 0.4.12\",\n\"cookie\",\n\"encoding\",\n\"failure\",\n\"futures 0.1.29\",\n\"futures-cpupool\",\n- \"h2\",\n- \"http\",\n+ \"h2 0.1.26\",\n+ \"http 0.1.21\",\n\"httparse\",\n\"language-tags\",\n\"lazy_static\",\n@@ -93,19 +93,19 @@ dependencies = [\n\"regex\",\n\"serde 1.0.105\",\n\"serde_json\",\n- \"serde_urlencoded\",\n+ \"serde_urlencoded 0.5.5\",\n\"sha1\",\n\"slab\",\n\"smallvec 0.6.13\",\n\"time\",\n- \"tokio\",\n+ \"tokio 0.1.22\",\n\"tokio-current-thread\",\n\"tokio-io\",\n\"tokio-openssl\",\n\"tokio-reactor\",\n\"tokio-tcp\",\n\"tokio-timer\",\n- \"url\",\n+ \"url 1.7.2\",\n\"v_htmlescape\",\n\"version_check 0.1.5\",\n]\n@@ -117,7 +117,7 @@ source = \"git+https://github.com/althea-mesh/actix-web-httpauth#4d6bf7afee950668\ndependencies = [\n\"actix-web\",\n\"base64 0.10.1\",\n- \"bytes\",\n+ \"bytes 0.4.12\",\n]\n[[package]]\n@@ -328,7 +328,7 @@ dependencies = [\n\"log\",\n\"serde 1.0.105\",\n\"serde_derive\",\n- \"tokio\",\n+ \"tokio 0.1.22\",\n]\n[[package]]\n@@ -431,6 +431,12 @@ version = \"0.1.4\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"40e38929add23cdf8a366df9b0e088953150724bcbe5fc330b0d8eb3b328eec8\"\n+[[package]]\n+name = \"bumpalo\"\n+version = \"3.2.1\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"12ae9db68ad7fac5fe51304d20f016c911539251075a214f8e663babefa35187\"\n+\n[[package]]\nname = \"byte-tools\"\nversion = \"0.3.1\"\n@@ -459,6 +465,12 @@ dependencies = [\n\"iovec\",\n]\n+[[package]]\n+name = \"bytes\"\n+version = \"0.5.4\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"130aac562c0dd69c56b3b1cc8ffd2e17be31d0b6c25b61c96b76231aa23e39e1\"\n+\n[[package]]\nname = \"c_linked_list\"\nversion = \"1.1.1\"\n@@ -591,7 +603,7 @@ source = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"d9fac5e7bdefb6160fb181ee0eaa6f96704b625c70e6d61c465cb35750a4ea12\"\ndependencies = [\n\"time\",\n- \"url\",\n+ \"url 1.7.2\",\n]\n[[package]]\n@@ -833,6 +845,15 @@ version = \"0.1.4\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"a246d82be1c9d791c5dfde9a2bd045fc3cbba3fa2b11ad558f27d01712f00569\"\n+[[package]]\n+name = \"encoding_rs\"\n+version = \"0.8.22\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"cd8d03faa7fe0c1431609dfad7bbe827af30f82e1e2ae6f7ee4fca6bd764bc28\"\n+dependencies = [\n+ \"cfg-if\",\n+]\n+\n[[package]]\nname = \"env_logger\"\nversion = \"0.7.1\"\n@@ -1166,10 +1187,10 @@ source = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"a5b34c246847f938a410a03c5458c7fee2274436675e76d8b903c08efc29c462\"\ndependencies = [\n\"byteorder\",\n- \"bytes\",\n+ \"bytes 0.4.12\",\n\"fnv\",\n\"futures 0.1.29\",\n- \"http\",\n+ \"http 0.1.21\",\n\"indexmap\",\n\"log\",\n\"slab\",\n@@ -1177,6 +1198,25 @@ dependencies = [\n\"tokio-io\",\n]\n+[[package]]\n+name = \"h2\"\n+version = \"0.2.4\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"377038bf3c89d18d6ca1431e7a5027194fbd724ca10592b9487ede5e8e144f42\"\n+dependencies = [\n+ \"bytes 0.5.4\",\n+ \"fnv\",\n+ \"futures-core\",\n+ \"futures-sink\",\n+ \"futures-util\",\n+ \"http 0.2.1\",\n+ \"indexmap\",\n+ \"log\",\n+ \"slab\",\n+ \"tokio 0.2.16\",\n+ \"tokio-util\",\n+]\n+\n[[package]]\nname = \"handlebars\"\nversion = \"2.0.4\"\n@@ -1263,11 +1303,32 @@ version = \"0.1.21\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"d6ccf5ede3a895d8856620237b2f02972c1bbc78d2965ad7fe8838d4a0ed41f0\"\ndependencies = [\n- \"bytes\",\n+ \"bytes 0.4.12\",\n+ \"fnv\",\n+ \"itoa\",\n+]\n+\n+[[package]]\n+name = \"http\"\n+version = \"0.2.1\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"28d569972648b2c512421b5f2a405ad6ac9666547189d0c5477a3f200f3e02f9\"\n+dependencies = [\n+ \"bytes 0.5.4\",\n\"fnv\",\n\"itoa\",\n]\n+[[package]]\n+name = \"http-body\"\n+version = \"0.3.1\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"13d5ff830006f7646652e057693569bfe0d51760c0085a071769d142a205111b\"\n+dependencies = [\n+ \"bytes 0.5.4\",\n+ \"http 0.2.1\",\n+]\n+\n[[package]]\nname = \"httparse\"\nversion = \"1.3.4\"\n@@ -1283,6 +1344,43 @@ dependencies = [\n\"quick-error\",\n]\n+[[package]]\n+name = \"hyper\"\n+version = \"0.13.4\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"ed6081100e960d9d74734659ffc9cc91daf1c0fc7aceb8eaa94ee1a3f5046f2e\"\n+dependencies = [\n+ \"bytes 0.5.4\",\n+ \"futures-channel\",\n+ \"futures-core\",\n+ \"futures-util\",\n+ \"h2 0.2.4\",\n+ \"http 0.2.1\",\n+ \"http-body\",\n+ \"httparse\",\n+ \"itoa\",\n+ \"log\",\n+ \"net2\",\n+ \"pin-project\",\n+ \"time\",\n+ \"tokio 0.2.16\",\n+ \"tower-service 0.3.0\",\n+ \"want\",\n+]\n+\n+[[package]]\n+name = \"hyper-tls\"\n+version = \"0.4.1\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"3adcd308402b9553630734e9c36b77a7e48b3821251ca2493e8cd596763aafaa\"\n+dependencies = [\n+ \"bytes 0.5.4\",\n+ \"hyper\",\n+ \"native-tls\",\n+ \"tokio 0.2.16\",\n+ \"tokio-tls\",\n+]\n+\n[[package]]\nname = \"idna\"\nversion = \"0.1.5\"\n@@ -1294,6 +1392,17 @@ dependencies = [\n\"unicode-normalization\",\n]\n+[[package]]\n+name = \"idna\"\n+version = \"0.2.0\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"02e2673c30ee86b5b96a9cb52ad15718aa1f966f5ab9ad54a8b95d5ca33120a9\"\n+dependencies = [\n+ \"matches\",\n+ \"unicode-bidi\",\n+ \"unicode-normalization\",\n+]\n+\n[[package]]\nname = \"indexmap\"\nversion = \"1.3.2\"\n@@ -1328,7 +1437,7 @@ dependencies = [\n\"socket2\",\n\"widestring\",\n\"winapi 0.3.8\",\n- \"winreg\",\n+ \"winreg 0.5.1\",\n]\n[[package]]\n@@ -1380,6 +1489,15 @@ version = \"0.4.5\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"b8b7a7c0c47db5545ed3fef7468ee7bb5b74691498139e4b3f6a20685dc6dd8e\"\n+[[package]]\n+name = \"js-sys\"\n+version = \"0.3.37\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"6a27d435371a2fa5b6d2b028a74bbdb1234f308da363226a2854ca3ff8ba7055\"\n+dependencies = [\n+ \"wasm-bindgen\",\n+]\n+\n[[package]]\nname = \"keccak\"\nversion = \"0.1.0\"\n@@ -2072,6 +2190,32 @@ dependencies = [\n\"serde_derive\",\n]\n+[[package]]\n+name = \"pin-project\"\n+version = \"0.4.8\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"7804a463a8d9572f13453c516a5faea534a2403d7ced2f0c7e100eeff072772c\"\n+dependencies = [\n+ \"pin-project-internal\",\n+]\n+\n+[[package]]\n+name = \"pin-project-internal\"\n+version = \"0.4.8\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"385322a45f2ecf3410c68d2a549a4a2685e8051d0f278e39743ff4e451cb9b3f\"\n+dependencies = [\n+ \"proc-macro2 1.0.9\",\n+ \"quote 1.0.3\",\n+ \"syn 1.0.17\",\n+]\n+\n+[[package]]\n+name = \"pin-project-lite\"\n+version = \"0.1.4\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"237844750cfbb86f67afe27eee600dfbbcb6188d734139b534cbfbf4f96792ae\"\n+\n[[package]]\nname = \"pin-utils\"\nversion = \"0.1.0-alpha.4\"\n@@ -2436,6 +2580,42 @@ dependencies = [\n\"winapi 0.3.8\",\n]\n+[[package]]\n+name = \"reqwest\"\n+version = \"0.10.4\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"02b81e49ddec5109a9dcfc5f2a317ff53377c915e9ae9d4f2fb50914b85614e2\"\n+dependencies = [\n+ \"base64 0.11.0\",\n+ \"bytes 0.5.4\",\n+ \"encoding_rs\",\n+ \"futures-core\",\n+ \"futures-util\",\n+ \"http 0.2.1\",\n+ \"http-body\",\n+ \"hyper\",\n+ \"hyper-tls\",\n+ \"js-sys\",\n+ \"lazy_static\",\n+ \"log\",\n+ \"mime\",\n+ \"mime_guess\",\n+ \"native-tls\",\n+ \"percent-encoding 2.1.0\",\n+ \"pin-project-lite\",\n+ \"serde 1.0.105\",\n+ \"serde_json\",\n+ \"serde_urlencoded 0.6.1\",\n+ \"time\",\n+ \"tokio 0.2.16\",\n+ \"tokio-tls\",\n+ \"url 2.1.1\",\n+ \"wasm-bindgen\",\n+ \"wasm-bindgen-futures\",\n+ \"web-sys\",\n+ \"winreg 0.6.2\",\n+]\n+\n[[package]]\nname = \"resolv-conf\"\nversion = \"0.6.3\"\n@@ -2461,7 +2641,7 @@ dependencies = [\n\"auto-bridge\",\n\"babel_monitor\",\n\"byteorder\",\n- \"bytes\",\n+ \"bytes 0.4.12\",\n\"clarity\",\n\"clu\",\n\"compressed_log\",\n@@ -2492,13 +2672,14 @@ dependencies = [\n\"r2d2\",\n\"rand 0.7.3\",\n\"regex\",\n+ \"reqwest\",\n\"serde 1.0.105\",\n\"serde_derive\",\n\"serde_json\",\n\"settings\",\n\"sha3\",\n\"sodiumoxide\",\n- \"tokio\",\n+ \"tokio 0.1.22\",\n\"tokio-codec\",\n\"tokio-io\",\n\"trust-dns-resolver\",\n@@ -2739,7 +2920,19 @@ dependencies = [\n\"dtoa\",\n\"itoa\",\n\"serde 1.0.105\",\n- \"url\",\n+ \"url 1.7.2\",\n+]\n+\n+[[package]]\n+name = \"serde_urlencoded\"\n+version = \"0.6.1\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"9ec5d77e2d4c73717816afac02670d5c4f534ea95ed430442cad02e7a6e32c97\"\n+dependencies = [\n+ \"dtoa\",\n+ \"itoa\",\n+ \"serde 1.0.105\",\n+ \"url 2.1.1\",\n]\n[[package]]\n@@ -2865,7 +3058,7 @@ version = \"0.2.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"d24114bfcceb867ca7f71a0d3fe45d45619ec47a6fbfa98cb14e14250bfa5d6d\"\ndependencies = [\n- \"bytes\",\n+ \"bytes 0.4.12\",\n]\n[[package]]\n@@ -2986,7 +3179,7 @@ version = \"0.1.22\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"5a09c0b5bb588872ab2f09afa13ee6e9dac11e10a0ec9e8e3ba39a5a5d530af6\"\ndependencies = [\n- \"bytes\",\n+ \"bytes 0.4.12\",\n\"futures 0.1.29\",\n\"mio\",\n\"num_cpus\",\n@@ -3004,13 +3197,31 @@ dependencies = [\n\"tokio-uds\",\n]\n+[[package]]\n+name = \"tokio\"\n+version = \"0.2.16\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"ee5a0dd887e37d37390c13ff8ac830f992307fe30a1fff0ab8427af67211ba28\"\n+dependencies = [\n+ \"bytes 0.5.4\",\n+ \"fnv\",\n+ \"futures-core\",\n+ \"iovec\",\n+ \"lazy_static\",\n+ \"memchr\",\n+ \"mio\",\n+ \"num_cpus\",\n+ \"pin-project-lite\",\n+ \"slab\",\n+]\n+\n[[package]]\nname = \"tokio-codec\"\nversion = \"0.1.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"25b2998660ba0e70d18684de5d06b70b70a3a747469af9dea7618cc59e75976b\"\ndependencies = [\n- \"bytes\",\n+ \"bytes 0.4.12\",\n\"futures 0.1.29\",\n\"tokio-io\",\n]\n@@ -3052,7 +3263,7 @@ version = \"0.1.13\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"57fc868aae093479e3131e3d165c93b1c7474109d13c90ec0dda2a1bbfff0674\"\ndependencies = [\n- \"bytes\",\n+ \"bytes 0.4.12\",\n\"futures 0.1.29\",\n\"log\",\n]\n@@ -3120,7 +3331,7 @@ version = \"0.1.4\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"98df18ed66e3b72e742f185882a9e201892407957e45fbff8da17ae7a7c51f72\"\ndependencies = [\n- \"bytes\",\n+ \"bytes 0.4.12\",\n\"futures 0.1.29\",\n\"iovec\",\n\"mio\",\n@@ -3157,13 +3368,23 @@ dependencies = [\n\"tokio-executor\",\n]\n+[[package]]\n+name = \"tokio-tls\"\n+version = \"0.3.0\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"7bde02a3a5291395f59b06ec6945a3077602fac2b07eeeaf0dee2122f3619828\"\n+dependencies = [\n+ \"native-tls\",\n+ \"tokio 0.2.16\",\n+]\n+\n[[package]]\nname = \"tokio-udp\"\nversion = \"0.1.6\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"e2a0b10e610b39c38b031a2fcab08e4b82f16ece36504988dcbd81dbba650d82\"\ndependencies = [\n- \"bytes\",\n+ \"bytes 0.4.12\",\n\"futures 0.1.29\",\n\"log\",\n\"mio\",\n@@ -3178,7 +3399,7 @@ version = \"0.2.6\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"5076db410d6fdc6523df7595447629099a1fdc47b3d9f896220780fa48faf798\"\ndependencies = [\n- \"bytes\",\n+ \"bytes 0.4.12\",\n\"futures 0.1.29\",\n\"iovec\",\n\"libc\",\n@@ -3190,6 +3411,20 @@ dependencies = [\n\"tokio-reactor\",\n]\n+[[package]]\n+name = \"tokio-util\"\n+version = \"0.3.1\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"be8242891f2b6cbef26a2d7e8605133c2c554cd35b3e4948ea892d6d68436499\"\n+dependencies = [\n+ \"bytes 0.5.4\",\n+ \"futures-core\",\n+ \"futures-sink\",\n+ \"log\",\n+ \"pin-project-lite\",\n+ \"tokio 0.2.16\",\n+]\n+\n[[package]]\nname = \"toml\"\nversion = \"0.5.6\"\n@@ -3208,6 +3443,12 @@ dependencies = [\n\"futures 0.1.29\",\n]\n+[[package]]\n+name = \"tower-service\"\n+version = \"0.3.0\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"e987b6bf443f4b5b3b6f38704195592cca41c5bb7aedd3c3693c7081f8289860\"\n+\n[[package]]\nname = \"traitobject\"\nversion = \"0.1.0\"\n@@ -3223,7 +3464,7 @@ dependencies = [\n\"byteorder\",\n\"failure\",\n\"futures 0.1.29\",\n- \"idna\",\n+ \"idna 0.1.5\",\n\"lazy_static\",\n\"log\",\n\"rand 0.5.6\",\n@@ -3235,7 +3476,7 @@ dependencies = [\n\"tokio-tcp\",\n\"tokio-timer\",\n\"tokio-udp\",\n- \"url\",\n+ \"url 1.7.2\",\n]\n[[package]]\n@@ -3247,7 +3488,7 @@ dependencies = [\n\"byteorder\",\n\"failure\",\n\"futures 0.1.29\",\n- \"idna\",\n+ \"idna 0.1.5\",\n\"lazy_static\",\n\"log\",\n\"rand 0.5.6\",\n@@ -3259,7 +3500,7 @@ dependencies = [\n\"tokio-tcp\",\n\"tokio-timer\",\n\"tokio-udp\",\n- \"url\",\n+ \"url 1.7.2\",\n]\n[[package]]\n@@ -3277,10 +3518,16 @@ dependencies = [\n\"lru-cache\",\n\"resolv-conf\",\n\"smallvec 0.6.13\",\n- \"tokio\",\n+ \"tokio 0.1.22\",\n\"trust-dns-proto 0.6.3\",\n]\n+[[package]]\n+name = \"try-lock\"\n+version = \"0.2.2\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"e604eb7b43c06650e854be16a2a03155743d3752dd1c943f6829e26b7a36e382\"\n+\n[[package]]\nname = \"typeable\"\nversion = \"0.1.2\"\n@@ -3345,11 +3592,22 @@ source = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"dd4e7c0d531266369519a4aa4f399d748bd37043b00bde1e4ff1f60a120b355a\"\ndependencies = [\n\"encoding\",\n- \"idna\",\n+ \"idna 0.1.5\",\n\"matches\",\n\"percent-encoding 1.0.1\",\n]\n+[[package]]\n+name = \"url\"\n+version = \"2.1.1\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"829d4a8476c35c9bf0bbce5a3b23f4106f79728039b726d292bb93bc106787cb\"\n+dependencies = [\n+ \"idna 0.2.0\",\n+ \"matches\",\n+ \"percent-encoding 2.1.0\",\n+]\n+\n[[package]]\nname = \"uuid\"\nversion = \"0.7.4\"\n@@ -3419,12 +3677,100 @@ dependencies = [\n\"winapi-util\",\n]\n+[[package]]\n+name = \"want\"\n+version = \"0.3.0\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"1ce8a968cb1cd110d136ff8b819a556d6fb6d919363c61534f6860c7eb172ba0\"\n+dependencies = [\n+ \"log\",\n+ \"try-lock\",\n+]\n+\n[[package]]\nname = \"wasi\"\nversion = \"0.9.0+wasi-snapshot-preview1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519\"\n+[[package]]\n+name = \"wasm-bindgen\"\n+version = \"0.2.60\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"2cc57ce05287f8376e998cbddfb4c8cb43b84a7ec55cf4551d7c00eef317a47f\"\n+dependencies = [\n+ \"cfg-if\",\n+ \"serde 1.0.105\",\n+ \"serde_json\",\n+ \"wasm-bindgen-macro\",\n+]\n+\n+[[package]]\n+name = \"wasm-bindgen-backend\"\n+version = \"0.2.60\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"d967d37bf6c16cca2973ca3af071d0a2523392e4a594548155d89a678f4237cd\"\n+dependencies = [\n+ \"bumpalo\",\n+ \"lazy_static\",\n+ \"log\",\n+ \"proc-macro2 1.0.9\",\n+ \"quote 1.0.3\",\n+ \"syn 1.0.17\",\n+ \"wasm-bindgen-shared\",\n+]\n+\n+[[package]]\n+name = \"wasm-bindgen-futures\"\n+version = \"0.4.10\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"7add542ea1ac7fdaa9dc25e031a6af33b7d63376292bd24140c637d00d1c312a\"\n+dependencies = [\n+ \"cfg-if\",\n+ \"js-sys\",\n+ \"wasm-bindgen\",\n+ \"web-sys\",\n+]\n+\n+[[package]]\n+name = \"wasm-bindgen-macro\"\n+version = \"0.2.60\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"8bd151b63e1ea881bb742cd20e1d6127cef28399558f3b5d415289bc41eee3a4\"\n+dependencies = [\n+ \"quote 1.0.3\",\n+ \"wasm-bindgen-macro-support\",\n+]\n+\n+[[package]]\n+name = \"wasm-bindgen-macro-support\"\n+version = \"0.2.60\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"d68a5b36eef1be7868f668632863292e37739656a80fc4b9acec7b0bd35a4931\"\n+dependencies = [\n+ \"proc-macro2 1.0.9\",\n+ \"quote 1.0.3\",\n+ \"syn 1.0.17\",\n+ \"wasm-bindgen-backend\",\n+ \"wasm-bindgen-shared\",\n+]\n+\n+[[package]]\n+name = \"wasm-bindgen-shared\"\n+version = \"0.2.60\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"daf76fe7d25ac79748a37538b7daeed1c7a6867c92d3245c12c6222e4a20d639\"\n+\n+[[package]]\n+name = \"web-sys\"\n+version = \"0.3.37\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"2d6f51648d8c56c366144378a33290049eafdd784071077f6fe37dae64c1c4cb\"\n+dependencies = [\n+ \"js-sys\",\n+ \"wasm-bindgen\",\n+]\n+\n[[package]]\nname = \"web30\"\nversion = \"0.4.3\"\n@@ -3433,7 +3779,7 @@ dependencies = [\n\"actix\",\n\"actix-web\",\n\"assert-json-diff\",\n- \"bytes\",\n+ \"bytes 0.4.12\",\n\"clarity\",\n\"failure\",\n\"futures 0.1.29\",\n@@ -3443,7 +3789,7 @@ dependencies = [\n\"serde 1.0.105\",\n\"serde_derive\",\n\"serde_json\",\n- \"tokio\",\n+ \"tokio 0.1.22\",\n]\n[[package]]\n@@ -3504,6 +3850,15 @@ dependencies = [\n\"winapi 0.3.8\",\n]\n+[[package]]\n+name = \"winreg\"\n+version = \"0.6.2\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"b2986deb581c4fe11b621998a5e53361efe6b48a151178d0cd9eeffa4dc6acc9\"\n+dependencies = [\n+ \"winapi 0.3.8\",\n+]\n+\n[[package]]\nname = \"winutil\"\nversion = \"0.1.1\"\n"
},
{
"change_type": "MODIFY",
"old_path": "rita/Cargo.toml",
"new_path": "rita/Cargo.toml",
"diff": "@@ -67,6 +67,7 @@ hex-literal = \"0.2\"\nsodiumoxide = \"0.2\"\ncompressed_log = \"0.2\"\nflate2 = { version = \"1.0\", features = [\"rust_backend\"], default-features = false }\n+reqwest = { version = \"0.10\", features = [\"blocking\", \"json\"] }\n[dependencies.regex]\nversion = \"1.3\"\n"
},
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_exit/database/geoip.rs",
"new_path": "rita/src/rita_exit/database/geoip.rs",
"diff": "use crate::GEOIP_CACHE;\nuse crate::KI;\nuse crate::SETTING;\n-use actix_web::client as actix_client;\n-use actix_web::HttpMessage;\nuse babel_monitor::open_babel_stream;\nuse babel_monitor::parse_routes;\nuse babel_monitor::start_connection;\n@@ -15,6 +13,7 @@ use settings::exit::RitaExitSettings;\nuse settings::RitaCommonSettings;\nuse std::collections::HashMap;\nuse std::net::IpAddr;\n+use std::time::Duration;\n/// gets the gateway ip for a given mesh IP\npub fn get_gateway_ip_single(mesh_ip: IpAddr) -> Box<dyn Future<Item = IpAddr, Error = Error>> {\n@@ -151,22 +150,32 @@ pub fn get_country(ip: IpAddr) -> impl Future<Item = String, Error = Error> {\ngeo_ip_url,\nip.to_string()\n);\n- Either::B(\n- actix_client::get(&geo_ip_url)\n+ Either::B({\n+ let geo_ip_url = format!(\"https://geoip.maxmind.com/geoip/v2.1/country/{}\", ip);\n+ info!(\n+ \"making GeoIP request to {} for {}\",\n+ geo_ip_url,\n+ ip.to_string()\n+ );\n+ let client = reqwest::blocking::Client::new();\n+ if let Ok(res) = client\n+ .get(&geo_ip_url)\n.basic_auth(api_user, Some(api_key))\n- .finish()\n- .unwrap()\n+ .timeout(Duration::from_secs(1))\n.send()\n- .from_err()\n- .and_then(move |response| {\n- response.json().from_err().and_then(move |result| {\n- let value: GeoIPRet = result;\n+ {\n+ if let Ok(res) = res.json() {\n+ let value: GeoIPRet = res;\nlet code = value.country.iso_code;\nGEOIP_CACHE.write().unwrap().insert(ip, code.clone());\n- Ok(code)\n+ future::ok(code)\n+ } else {\n+ future::err(format_err!(\"Failed to deserialize geoip response\"))\n+ }\n+ } else {\n+ future::err(format_err!(\"request failed\"))\n+ }\n})\n- }),\n- )\n}\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_exit/rita_loop/mod.rs",
"new_path": "rita/src/rita_exit/rita_loop/mod.rs",
"diff": "@@ -133,6 +133,7 @@ pub fn start_rita_exit_loop() {\n}\n// Make sure no one we are setting up is geoip unauthorized\n+ info!(\"about to check regions\");\nlet val = SETTING.get_allowed_countries().is_empty();\nif !val {\nlet res = wait_timeout(\n@@ -156,6 +157,7 @@ pub fn start_rita_exit_loop() {\n}\n}\n+ info!(\"About to enforce exit clients\");\n// handle enforcement on client tunnels by querying debt keeper\n// this consumes client list, you can move it up in exchange for a clone\nlet res = wait_timeout(\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Use syncronous geoip requests
We can no longer use actix client since we are making requests in
another thread now. This is unfortunate because this same codepath
is run by the worker threads for client checkins. |
20,244 | 09.04.2020 14:33:52 | 14,400 | 7b5cb2470b883b2674e0c4aa5c1507c734c702c8 | Break up rita exit loop
Reduces the size of the exit loop function and helps keep
the logging messages from dominating readability | [
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_exit/rita_loop/mod.rs",
"new_path": "rita/src/rita_exit/rita_loop/mod.rs",
"diff": "@@ -31,10 +31,12 @@ use crate::rita_exit::rita_loop::wait_timeout::WaitResult;\nuse crate::rita_exit::traffic_watcher::{TrafficWatcher, Watch};\nuse crate::KI;\nuse crate::SETTING;\n+use actix::Addr;\nuse actix::SystemService;\nuse actix_web::http::Method;\nuse actix_web::{server, App};\nuse althea_kernel_interface::ExitClient;\n+use althea_types::Identity;\nuse babel_monitor::open_babel_stream;\nuse babel_monitor::parse_routes;\nuse babel_monitor::start_connection;\n@@ -85,6 +87,48 @@ pub fn start_rita_exit_loop() {\nlet ids = clients_to_ids(clients_list.clone());\n// watch and bill for traffic\n+ bill(babel_port, &tw, start, ids);\n+\n+ info!(\"about to setup clients\");\n+ // Create and update client tunnels\n+ match setup_clients(&clients_list, &wg_clients) {\n+ Ok(new_wg_clients) => wg_clients = new_wg_clients,\n+ Err(e) => error!(\"Setup clients failed with {:?}\", e),\n+ }\n+\n+ info!(\"about to cleanup clients\");\n+ // find users that have not been active within the configured time period\n+ // and remove them from the db\n+ if let Err(e) = cleanup_exit_clients(&clients_list, &conn) {\n+ error!(\"Exit client cleanup failed with {:?}\", e);\n+ }\n+\n+ // Make sure no one we are setting up is geoip unauthorized\n+ info!(\"about to check regions\");\n+ check_regions(start, clients_list.clone());\n+\n+ info!(\"About to enforce exit clients\");\n+ enforce(start, &dk, clients_list);\n+\n+ info!(\n+ \"Completed Rita exit loop in {}ms, all vars should be dropped\",\n+ start.elapsed().as_millis(),\n+ );\n+ }\n+ }\n+ WaitResult::Err(e) => error!(\"Failed to get database connection with {}\", e),\n+ WaitResult::TimedOut(_) => error!(\"Database connection timed out\"),\n+ }\n+ // sleep until it has been 5 seconds from start, whenever that may be\n+ // if it has been more than 5 seconds from start, go right ahead\n+ if start.elapsed() < EXIT_LOOP_SPEED_DURATION {\n+ thread::sleep(EXIT_LOOP_SPEED_DURATION - start.elapsed());\n+ }\n+ }\n+ });\n+}\n+\n+fn bill(babel_port: u16, tw: &Addr<TrafficWatcher>, start: Instant, ids: Vec<Identity>) {\ntrace!(\"about to try opening babel stream\");\nlet res = wait_timeout(\nopen_babel_stream(babel_port).from_err().and_then(|stream| {\n@@ -117,29 +161,12 @@ pub fn start_rita_exit_loop() {\nstart.elapsed().as_millis()\n),\n}\n-\n- info!(\"about to setup clients\");\n- // Create and update client tunnels\n- match setup_clients(&clients_list, &wg_clients) {\n- Ok(new_wg_clients) => wg_clients = new_wg_clients,\n- Err(e) => error!(\"Setup clients failed with {:?}\", e),\n}\n- info!(\"about to cleanup clients\");\n- // find users that have not been active within the configured time period\n- // and remove them from the db\n- if let Err(e) = cleanup_exit_clients(&clients_list, &conn) {\n- error!(\"Exit client cleanup failed with {:?}\", e);\n- }\n-\n- // Make sure no one we are setting up is geoip unauthorized\n- info!(\"about to check regions\");\n+fn check_regions(start: Instant, clients_list: Vec<models::Client>) {\nlet val = SETTING.get_allowed_countries().is_empty();\nif !val {\n- let res = wait_timeout(\n- validate_clients_region(clients_list.clone()),\n- EXIT_LOOP_TIMEOUT,\n- );\n+ let res = wait_timeout(validate_clients_region(clients_list), EXIT_LOOP_TIMEOUT);\nmatch res {\nWaitResult::Err(e) => warn!(\n\"Failed to validate client region with {:?} {}ms since start\",\n@@ -156,8 +183,9 @@ pub fn start_rita_exit_loop() {\n),\n}\n}\n+}\n- info!(\"About to enforce exit clients\");\n+fn enforce(start: Instant, dk: &Addr<DebtKeeper>, clients_list: Vec<models::Client>) {\n// handle enforcement on client tunnels by querying debt keeper\n// this consumes client list, you can move it up in exchange for a clone\nlet res = wait_timeout(\n@@ -179,23 +207,6 @@ pub fn start_rita_exit_loop() {\nstart.elapsed().as_millis()\n),\n}\n-\n- info!(\n- \"Completed Rita exit loop in {}ms, all vars should be dropped\",\n- start.elapsed().as_millis(),\n- );\n- }\n- }\n- WaitResult::Err(e) => error!(\"Failed to get database connection with {}\", e),\n- WaitResult::TimedOut(_) => error!(\"Database connection timed out\"),\n- }\n- // sleep until it has been 5 seconds from start, whenever that may be\n- // if it has been more than 5 seconds from start, go right ahead\n- if start.elapsed() < EXIT_LOOP_SPEED_DURATION {\n- thread::sleep(EXIT_LOOP_SPEED_DURATION - start.elapsed());\n- }\n- }\n- });\n}\nfn setup_exit_wg_tunnel() {\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Break up rita exit loop
Reduces the size of the exit loop function and helps keep
the logging messages from dominating readability |
20,244 | 10.04.2020 06:50:00 | 14,400 | 5fdb301dba84d82b8597bb912eca99c6b29b9572 | Bump for Beta 12 RC2 | [
{
"change_type": "MODIFY",
"old_path": "Cargo.lock",
"new_path": "Cargo.lock",
"diff": "@@ -2628,7 +2628,7 @@ dependencies = [\n[[package]]\nname = \"rita\"\n-version = \"0.5.38\"\n+version = \"0.5.39\"\ndependencies = [\n\"actix\",\n\"actix-web\",\n"
},
{
"change_type": "MODIFY",
"old_path": "rita/Cargo.toml",
"new_path": "rita/Cargo.toml",
"diff": "[package]\nname = \"rita\"\n-version = \"0.5.38\"\n+version = \"0.5.39\"\nauthors = [\"Jehan <jehan.tremback@gmail.com>\", \"Ben <wangben3@gmail.com>\"]\nbuild = \"build.rs\"\nedition = \"2018\"\n"
},
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_common/dashboard/own_info.rs",
"new_path": "rita/src/rita_common/dashboard/own_info.rs",
"diff": "@@ -6,7 +6,7 @@ use failure::Error;\nuse num256::{Int256, Uint256};\nuse settings::RitaCommonSettings;\n-pub static READABLE_VERSION: &str = \"Beta 12 RC1\";\n+pub static READABLE_VERSION: &str = \"Beta 12 RC2\";\n#[derive(Serialize)]\npub struct OwnInfo {\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Bump for Beta 12 RC2 |
20,244 | 10.04.2020 07:59:56 | 14,400 | fb5980621142715dffc0432578a299179cb017b8 | Fix GeoIP and SMS for sync exit loop | [
{
"change_type": "MODIFY",
"old_path": "rita/src/exit.rs",
"new_path": "rita/src/exit.rs",
"diff": "@@ -40,9 +40,7 @@ use openssl_probe;\nuse r2d2::Pool;\nuse settings::exit::ExitNetworkSettings;\nuse settings::exit::ExitVerifSettings;\n-use std::collections::HashMap;\nuse std::collections::HashSet;\n-use std::net::IpAddr;\nuse std::sync::{Arc, RwLock};\nuse std::time::Instant;\n@@ -133,11 +131,6 @@ lazy_static! {\n.unwrap_or_else(|e| e.exit());\n}\n-lazy_static! {\n- pub static ref GEOIP_CACHE: Arc<RwLock<HashMap<IpAddr, String>>> =\n- Arc::new(RwLock::new(HashMap::new()));\n-}\n-\n// These are a set of vars that are never updated during runtime. This means we can have\n// read only versions of them available here to prevent lock contention on large exits.\nlazy_static! {\n"
},
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_exit/database/geoip.rs",
"new_path": "rita/src/rita_exit/database/geoip.rs",
"diff": "-use crate::GEOIP_CACHE;\nuse crate::KI;\nuse crate::SETTING;\nuse babel_monitor::open_babel_stream;\n@@ -13,8 +12,14 @@ use settings::exit::RitaExitSettings;\nuse settings::RitaCommonSettings;\nuse std::collections::HashMap;\nuse std::net::IpAddr;\n+use std::sync::{Arc, RwLock};\nuse std::time::Duration;\n+lazy_static! {\n+ static ref GEOIP_CACHE: Arc<RwLock<HashMap<IpAddr, String>>> =\n+ Arc::new(RwLock::new(HashMap::new()));\n+}\n+\n/// gets the gateway ip for a given mesh IP\npub fn get_gateway_ip_single(mesh_ip: IpAddr) -> Box<dyn Future<Item = IpAddr, Error = Error>> {\nlet babel_port = SETTING.get_network().babel_port;\n@@ -141,8 +146,15 @@ pub fn get_country(ip: IpAddr) -> impl Future<Item = String, Error = Error> {\n.clone()\n.expect(\"No api key configured!\");\n- match GEOIP_CACHE.read().unwrap().get(&ip) {\n- Some(code) => Either::A(future::ok(code.clone())),\n+ // we have to turn this option into a string in order to avoid\n+ // the borrow checker trying to keep this lock open for a long period\n+ let cache_result = match GEOIP_CACHE.read().unwrap().get(&ip) {\n+ Some(val) => Some(val.to_string()),\n+ None => None,\n+ };\n+\n+ match cache_result {\n+ Some(code) => Either::A(future::ok(code)),\nNone => {\nlet geo_ip_url = format!(\"https://geoip.maxmind.com/geoip/v2.1/country/{}\", ip);\ninfo!(\n@@ -164,10 +176,13 @@ pub fn get_country(ip: IpAddr) -> impl Future<Item = String, Error = Error> {\n.timeout(Duration::from_secs(1))\n.send()\n{\n+ trace!(\"Got geoip result {:?}\", res);\nif let Ok(res) = res.json() {\nlet value: GeoIPRet = res;\nlet code = value.country.iso_code;\n+ trace!(\"Adding GeoIP value {:?} to cache\", code);\nGEOIP_CACHE.write().unwrap().insert(ip, code.clone());\n+ trace!(\"Added to cache, returning\");\nfuture::ok(code)\n} else {\nfuture::err(format_err!(\"Failed to deserialize geoip response\"))\n"
},
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_exit/database/mod.rs",
"new_path": "rita/src/rita_exit/database/mod.rs",
"diff": "@@ -110,9 +110,13 @@ pub fn secs_since_unix_epoch() -> i64 {\npub fn signup_client(client: ExitClientIdentity) -> impl Future<Item = ExitState, Error = Error> {\ntrace!(\"got setup request {:?}\", client);\nget_gateway_ip_single(client.global.mesh_ip).and_then(move |gateway_ip| {\n+ trace!(\"got gateway ip {:?}\", client);\nverify_ip(gateway_ip).and_then(move |verify_status| {\n+ trace!(\"verified the ip country {:?}\", client);\nget_country(gateway_ip).and_then(move |user_country| {\n+ trace!(\"got the country country {:?}\", client);\nget_database_connection().and_then(move |conn| {\n+ trace!(\"Doing database work for {:?} in country {} with verify_status {}\", client, user_country, verify_status);\n// check if we have any users with conflicting details\nmatch client_conflict(&client, &conn) {\nOk(true) => {\n"
},
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_exit/database/sms.rs",
"new_path": "rita/src/rita_exit/database/sms.rs",
"diff": "@@ -3,7 +3,6 @@ use crate::rita_exit::database::database_tools::verify_client;\nuse crate::rita_exit::database::get_database_connection;\nuse crate::rita_exit::database::get_exit_info;\nuse crate::rita_exit::database::struct_tools::texts_sent;\n-use actix::Arbiter;\nuse actix_web::client as actix_client;\nuse actix_web::client::ClientResponse;\nuse althea_types::{ExitClientDetails, ExitClientIdentity, ExitState};\n@@ -13,6 +12,7 @@ use futures01::future::Either;\nuse futures01::future::Future;\nuse phonenumber::PhoneNumber;\nuse settings::exit::PhoneVerifSettings;\n+use std::time::Duration;\n#[derive(Serialize)]\npub struct SmsCheck {\n@@ -205,25 +205,29 @@ pub fn send_low_balance_sms(number: &str, phone: PhoneVerifSettings) -> Result<(\nphone.twillio_account_id\n);\nlet number: PhoneNumber = number.parse()?;\n- let res = actix_client::post(&url)\n+ let client = reqwest::blocking::Client::new();\n+ match client\n+ .post(&url)\n.basic_auth(phone.twillio_account_id, Some(phone.twillio_auth_token))\n.form(&SmsNotification {\nto: number.to_string(),\nfrom: phone.notification_number,\nbody: phone.balance_notification_body,\n})\n- .unwrap()\n+ .timeout(Duration::from_secs(1))\n.send()\n- .then(move |result| {\n- if result.is_err() {\n- warn!(\n- \"Low balance text to {} failed with {:?}\",\n+ {\n+ Ok(val) => {\n+ info!(\"Low balance text sent successfully with {:?}\", val);\n+ Ok(())\n+ }\n+ Err(e) => {\n+ error!(\n+ \"Low blanace text to {} failed with {:?}\",\nnumber.to_string(),\n- result\n+ e\n);\n+ Err(e.into())\n+ }\n}\n- Ok(())\n- });\n- Arbiter::spawn(res);\n- Ok(())\n}\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Fix GeoIP and SMS for sync exit loop |
20,244 | 10.04.2020 09:28:59 | 14,400 | 4dd7362a7d0c89053745b9561edf04ad69f033f0 | No delay for db connections
This is particularly insidious because it waits to cause a panic
for quite some time. Replacing with a very traditional thread sleep | [
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_exit/database/database_tools.rs",
"new_path": "rita/src/rita_exit/database/database_tools.rs",
"diff": "@@ -20,10 +20,10 @@ use futures01::future::Future;\nuse settings::exit::RitaExitSettings;\nuse std::net::IpAddr;\nuse std::net::Ipv4Addr;\n+use std::thread;\nuse std::time::Duration;\n-use std::time::Instant;\n-use tokio::timer::Delay;\n-use tokio::util::FutureExt;\n+\n+const SLEEP_TIME: Duration = Duration::from_millis(100);\n/// Takes a list of clients and returns a sorted list of ip addresses spefically v4 since it\n/// can implement comparison operators\n@@ -329,20 +329,8 @@ pub fn get_database_connection(\n>,\nNone => {\ntrace!(\"No available db connection sleeping!\");\n- let when = Instant::now() + Duration::from_millis(100);\n- Box::new(\n- Delay::new(when)\n- .map_err(move |e| panic!(\"timer failed; err={:?}\", e))\n- .and_then(move |_| get_database_connection())\n- .timeout(Duration::from_secs(1))\n- .then(|result| match result {\n- Ok(v) => Ok(v),\n- Err(e) => {\n- error!(\"Failed to get DB connection with {:?}\", e);\n- Err(format_err!(\"{:?}\", e))\n- }\n- }),\n- )\n+ thread::sleep(SLEEP_TIME);\n+ Box::new(get_database_connection())\n}\n}\n}\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | No delay for db connections
This is particularly insidious because it waits to cause a panic
for quite some time. Replacing with a very traditional thread sleep |
20,244 | 10.04.2020 09:46:02 | 14,400 | d9f1da3dc98726df06ef0c1a44018ec9e3a3baef | Add very short sleep in BabelMonitor
This prevents spinlocks on single core machines | [
{
"change_type": "MODIFY",
"old_path": "babel_monitor/src/lib.rs",
"new_path": "babel_monitor/src/lib.rs",
"diff": "@@ -28,11 +28,21 @@ use std::net::IpAddr;\nuse std::net::SocketAddr;\nuse std::str;\nuse std::str::FromStr;\n+use std::thread;\n+use std::time::Duration;\nuse tokio::io::read;\nuse tokio::io::write_all;\nuse tokio::net::tcp::ConnectFuture;\nuse tokio::net::TcpStream;\n+/// we want to ceed the cpu just long enough for Babel\n+/// to finish what it's doing and warp up it's write\n+/// on multicore machines this is mostly a waste of time\n+/// on single core machines it avoids a spinlock until we\n+/// are pre-empted by the scheduler to allow Babel to finish the\n+/// job\n+const SLEEP_TIME: Duration = Duration::from_millis(1);\n+\n#[derive(Debug, Fail)]\npub enum BabelMonitorError {\n#[fail(display = \"variable '{}' not found in '{}'\", _0, _1)]\n@@ -178,6 +188,7 @@ fn read_babel(\n// our buffer was not full but we also did not find a terminator,\n// we must have caught babel while it was interupped (only really happens\n// in single cpu situations)\n+ thread::sleep(SLEEP_TIME);\ntrace!(\"we didn't get the whole message yet, trying again\");\nreturn Box::new(read_babel(stream, full_message, depth + 1));\n} else if let Err(e) = babel_data {\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Add very short sleep in BabelMonitor
This prevents spinlocks on single core machines |
20,244 | 10.04.2020 10:49:23 | 14,400 | 49be7665894d03bc1f2ab03124de78a307cf5a6d | Add settings toggle for debt forgiveness | [
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_common/debt_keeper/mod.rs",
"new_path": "rita/src/rita_common/debt_keeper/mod.rs",
"diff": "@@ -108,11 +108,13 @@ fn ser_to_debt_data(input: DebtDataSer) -> DebtData {\n// discard the entry, in the case that they do have some incoming payments the user\n// deserves to have that credit applied in the future so we must retain the entry and\n// reset the debt\n+ if SETTING.get_payment().forgive_on_reboot {\nif d.debt <= Int256::zero() && d.incoming_payments == Uint256::zero() {\ncontinue;\n} else if d.debt <= Int256::zero() {\nd.debt = Int256::from(0);\n}\n+ }\nret.insert(i, d);\n}\nret\n"
},
{
"change_type": "MODIFY",
"old_path": "settings/src/payment.rs",
"new_path": "settings/src/payment.rs",
"diff": "@@ -111,6 +111,11 @@ fn default_max_gas() -> u64 {\nXDAI_MAX_GAS\n}\n+/// By default we forgive nodes of their debts on reboot\n+fn default_forgive_on_reboot() -> bool {\n+ true\n+}\n+\n#[derive(Debug, Serialize, Deserialize, Clone, Eq, PartialEq)]\npub struct TokenBridgeAddresses {\npub uniswap_address: Address,\n@@ -218,6 +223,9 @@ pub struct PaymentSettings {\n/// the minimum we will pay for gas on our current blockchain\n#[serde(default = \"default_min_gas\")]\npub min_gas: u64,\n+ /// if we forgive all debts on reboot\n+ #[serde(default = \"default_forgive_on_reboot\")]\n+ pub forgive_on_reboot: bool,\n}\nimpl Default for PaymentSettings {\n@@ -254,6 +262,7 @@ impl Default for PaymentSettings {\nsimulated_transaction_fee: default_simulated_transaction_fee(),\nmin_gas: default_min_gas(),\nmax_gas: default_max_gas(),\n+ forgive_on_reboot: default_forgive_on_reboot(),\n}\n}\n}\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Add settings toggle for debt forgiveness |
20,244 | 10.04.2020 10:58:07 | 14,400 | 7a2aceafa8a2780b79b9995e367a1f4ed7e5d812 | Update operator server urls | [
{
"change_type": "MODIFY",
"old_path": "settings/src/logging.rs",
"new_path": "settings/src/logging.rs",
"diff": "@@ -11,11 +11,11 @@ fn default_logging_dest_url() -> String {\n}\nfn default_heartbeat_url() -> String {\n- \"stats.altheamesh.com:33333\".to_string()\n+ \"operator.althea.net:33333\".to_string()\n}\nfn default_forwarding_checkin_url() -> String {\n- \"stats.altheamesh.com:33334\".to_string()\n+ \"operator.althea.net:33334\".to_string()\n}\n/// Remote logging settings. Used to control remote logs being\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Update operator server urls |
20,244 | 10.04.2020 13:14:40 | 14,400 | 709b2bb4b8aaf0b770a4ea53a4986be4b5271a56 | Wait a few seconds between checkins | [
{
"change_type": "MODIFY",
"old_path": "antenna_forwarding_client/src/lib.rs",
"new_path": "antenna_forwarding_client/src/lib.rs",
"diff": "@@ -112,6 +112,7 @@ pub fn start_antenna_forwarding_proxy<S: 'static + std::marker::Send + ::std::ha\n}\n}\ntrace!(\"Waiting for next checkin cycle\");\n+ thread::sleep(SLEEP_TIME)\n});\n}\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Wait a few seconds between checkins |
20,244 | 10.04.2020 13:38:11 | 14,400 | 56ddafabe8a8d800b64452446ef474a8c512124f | Finish migration from DAO for heartbeat and prices endpoint
Frogot to catch these before, the actual front end needs to
see some variable renaming later | [
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_client/dashboard/prices.rs",
"new_path": "rita/src/rita_client/dashboard/prices.rs",
"diff": "@@ -14,13 +14,16 @@ use settings::RitaCommonSettings;\npub fn auto_pricing_status(_req: HttpRequest) -> Result<Json<bool>, Error> {\ndebug!(\"Get Auto pricing enabled hit!\");\n- Ok(Json(SETTING.get_dao().use_oracle_price))\n+ Ok(Json(SETTING.get_operator().use_operator_price))\n}\npub fn set_auto_pricing(path: Path<bool>) -> Result<HttpResponse, Error> {\nlet value = path.into_inner();\ndebug!(\"Set Auto pricing enabled hit!\");\n- SETTING.get_dao_mut().use_oracle_price = value;\n+ let mut op = SETTING.get_operator_mut();\n+ if !op.force_use_operator_price {\n+ op.use_operator_price = value;\n+ }\n// try and save the config and fail if we can't\nif let Err(e) = SETTING.write().unwrap().write(&ARGS.flag_config) {\n@@ -42,10 +45,10 @@ pub fn get_prices(_req: HttpRequest) -> Box<dyn Future<Item = Json<Prices>, Erro\nlet b = f.from_err().and_then(|exit_dest_price| {\nlet exit_dest_price = exit_dest_price.unwrap();\nlet simulated_tx_fee = SETTING.get_payment().simulated_transaction_fee;\n- let dao_fee = SETTING.get_dao().dao_fee.clone();\n+ let operator_fee = SETTING.get_operator().operator_fee.clone();\nlet p = Prices {\nexit_dest_price,\n- dao_fee,\n+ dao_fee: operator_fee,\nsimulated_tx_fee,\n};\nOk(Json(p))\n"
},
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_client/heartbeat/mod.rs",
"new_path": "rita/src/rita_client/heartbeat/mod.rs",
"diff": "@@ -11,7 +11,6 @@ use crate::rita_client::rita_loop::CLIENT_LOOP_TIMEOUT;\nuse crate::rita_common::network_monitor::GetNetworkInfo;\nuse crate::rita_common::network_monitor::NetworkMonitor;\nuse crate::rita_common::tunnel_manager::Neighbor as RitaNeighbor;\n-use crate::rita_common::utils::option_deref;\nuse crate::SETTING;\nuse actix::actors::resolver;\nuse actix::{Arbiter, SystemService};\n@@ -179,7 +178,7 @@ fn send_udp_heartbeat_packet(\nlet message = HeartbeatMessage {\nid: our_id,\n- organizer_address: option_deref(SETTING.get_dao().dao_addresses.get(0)),\n+ organizer_address: SETTING.get_operator().operator_address,\nbalance: SETTING.get_payment().balance.clone(),\nexit_dest_price: exit_price + exit_route.price as u64,\nupstream_id: exit_neighbor_id,\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Finish migration from DAO for heartbeat and prices endpoint
Frogot to catch these before, the actual front end needs to
see some variable renaming later |
20,244 | 10.04.2020 13:38:55 | 14,400 | 49dec145f6b52b871b93ab5b6bf0d9befb551f10 | Slow down forwarding client checkin
every five seconds is a little too often | [
{
"change_type": "MODIFY",
"old_path": "antenna_forwarding_client/src/lib.rs",
"new_path": "antenna_forwarding_client/src/lib.rs",
"diff": "@@ -36,7 +36,7 @@ lazy_static! {\npub static ref KI: Box<dyn KernelInterface> = Box::new(LinuxCommandRunner {});\n}\n-const SLEEP_TIME: Duration = NET_TIMEOUT;\n+const SLEEP_TIME: Duration = Duration::from_secs(10);\n/// The timeout time for pinging a local antenna, 25ms is very\n/// very generous here as they should all respond really within 5ms\nconst PING_TIMEOUT: Duration = Duration::from_millis(100);\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Slow down forwarding client checkin
every five seconds is a little too often |
20,244 | 11.04.2020 07:22:37 | 14,400 | 8c892649bd807f115ffc30eda7c0272ec07fd45e | Upgrade wait_timeout to use Notify
Good news, not a depricated api, bad news I'm not really sure my
adaptation here is correct. It seems to run ok and I think that it's
trivially correct because we're only running one future at a time. | [
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_exit/rita_loop/wait_timeout.rs",
"new_path": "rita/src/rita_exit/rita_loop/wait_timeout.rs",
"diff": "-/// Copied from here https://gist.github.com/alexcrichton/871b5bf058a2ce77ac4fedccf3fda9c9\n-/// turns out poll with timeout is quite complex, turned off warnings becuase we've already\n-/// scoped these as futures01\n+//! Copied from here https://gist.github.com/alexcrichton/871b5bf058a2ce77ac4fedccf3fda9c9\n+//! turns out poll with timeout is quite complex. It has also been adapted by myself to use\n+//! notify without a really good understanding of the internalls. The park/unpark version\n+//! paniced about every 24 hours this version is not correct I don't think for arbitrary futures\n+//! but is correct for our trivial case of a single future on a thread. We'll see how it holds up\n+use futures01::executor::Notify;\nuse futures01::executor::{self, Spawn};\n-#[allow(deprecated)]\n-use futures01::task::Unpark;\nuse futures01::{Async, Future};\nuse std::sync::atomic::{AtomicBool, Ordering};\nuse std::sync::Arc;\n@@ -19,15 +20,14 @@ pub enum WaitResult<F: Future> {\npub fn wait_timeout<F: Future>(f: F, dur: Duration) -> WaitResult<F> {\nlet now = Instant::now();\nlet mut task = executor::spawn(f);\n- let thread = Arc::new(ThreadUnpark::new(thread::current()));\n+ let thread = Arc::new(ThreadNotify::new(thread::current()));\nloop {\nlet cur = Instant::now();\nif cur >= now + dur {\nreturn WaitResult::TimedOut(task);\n}\n- #[allow(deprecated)]\n- match task.poll_future(thread.clone()) {\n+ match task.poll_future_notify(&thread, 0) {\nOk(Async::Ready(e)) => return WaitResult::Ok(e),\nOk(Async::NotReady) => {}\nErr(e) => return WaitResult::Err(e),\n@@ -36,14 +36,14 @@ pub fn wait_timeout<F: Future>(f: F, dur: Duration) -> WaitResult<F> {\nthread.park(now + dur - cur);\n}\n- struct ThreadUnpark {\n+ struct ThreadNotify {\nthread: thread::Thread,\nready: AtomicBool,\n}\n- impl ThreadUnpark {\n- fn new(thread: thread::Thread) -> ThreadUnpark {\n- ThreadUnpark {\n+ impl ThreadNotify {\n+ fn new(thread: thread::Thread) -> ThreadNotify {\n+ ThreadNotify {\nthread,\nready: AtomicBool::new(false),\n}\n@@ -56,9 +56,8 @@ pub fn wait_timeout<F: Future>(f: F, dur: Duration) -> WaitResult<F> {\n}\n}\n- #[allow(deprecated)]\n- impl Unpark for ThreadUnpark {\n- fn unpark(&self) {\n+ impl Notify for ThreadNotify {\n+ fn notify(&self, _id: usize) {\nself.ready.store(true, Ordering::SeqCst);\nself.thread.unpark()\n}\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Upgrade wait_timeout to use Notify
Good news, not a depricated api, bad news I'm not really sure my
adaptation here is correct. It seems to run ok and I think that it's
trivially correct because we're only running one future at a time. |
20,244 | 11.04.2020 16:22:45 | 14,400 | 8e1b6e6138755afaaade1add37d400ded3e6e96d | Use to_socket_addrs and don't panic on shutdown failure | [
{
"change_type": "MODIFY",
"old_path": "antenna_forwarding_client/src/lib.rs",
"new_path": "antenna_forwarding_client/src/lib.rs",
"diff": "@@ -28,6 +28,7 @@ use std::net::Ipv4Addr;\nuse std::net::Shutdown;\nuse std::net::SocketAddr;\nuse std::net::TcpStream;\n+use std::net::ToSocketAddrs;\nuse std::thread;\nuse std::time::Duration;\nuse std::time::Instant;\n@@ -55,8 +56,14 @@ pub fn start_antenna_forwarding_proxy<S: 'static + std::marker::Send + ::std::ha\ninterfaces_to_search: HashSet<String, S>,\n) {\ninfo!(\"Starting antenna forwarding proxy!\");\n- let socket: SocketAddr = match checkin_address.parse() {\n- Ok(socket) => socket,\n+ let socket: SocketAddr = match checkin_address.to_socket_addrs() {\n+ Ok(mut res) => match res.next() {\n+ Some(socket) => socket,\n+ None => {\n+ error!(\"Could not parse {}!\", checkin_address);\n+ return;\n+ }\n+ },\nErr(_) => {\nerror!(\"Could not parse {}!\", checkin_address);\nreturn;\n@@ -141,9 +148,7 @@ fn process_messages(\nlet stream = streams\n.get(stream_id)\n.expect(\"How can we close a stream we don't have?\");\n- stream\n- .shutdown(Shutdown::Both)\n- .expect(\"Failed to shutdown connection!\");\n+ let _res = stream.shutdown(Shutdown::Both);\nstreams.remove(stream_id);\n}\nForwardingProtocolMessage::ConnectionDataMessage { stream_id, payload } => {\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Use to_socket_addrs and don't panic on shutdown failure |
20,244 | 13.04.2020 12:50:19 | 14,400 | 8dfb790f4b63bcb394bcba82af4f90ff075ecde7 | Handle all starting message cases | [
{
"change_type": "MODIFY",
"old_path": "antenna_forwarding_client/src/lib.rs",
"new_path": "antenna_forwarding_client/src/lib.rs",
"diff": "@@ -87,12 +87,12 @@ pub fn start_antenna_forwarding_proxy<S: 'static + std::marker::Send + ::std::ha\nmatch ForwardingProtocolMessage::read_messages(&mut server_stream) {\nOk(messages) => {\n// read messages will return a vec of at least one,\n- if let Some(ForwardingProtocolMessage::ForwardMessage {\n+ match messages.iter().next() {\n+ Some(ForwardingProtocolMessage::ForwardMessage {\nip,\nserver_port: _server_port,\nantenna_port,\n- }) = messages.iter().next()\n- {\n+ }) => {\n// if there are other messages in this batch safely form a slice\n// to pass on\nlet slice = if messages.len() > 1 {\n@@ -106,10 +106,14 @@ pub fn start_antenna_forwarding_proxy<S: 'static + std::marker::Send + ::std::ha\nOk(antenna_sockaddr) => {\nforward_connections(antenna_sockaddr, server_stream, slice);\n}\n- Err(e) => send_error_message(&mut server_stream, format!(\"{:?}\", e)),\n+ Err(e) => {\n+ send_error_message(&mut server_stream, format!(\"{:?}\", e))\n}\n- } else {\n- error!(\"Wrong start message!\");\n+ }\n+ }\n+ Some(ForwardingProtocolMessage::ForwardingCloseMessage) => {}\n+ Some(m) => warn!(\"Wrong start message {:?}\", m),\n+ None => {}\n}\n}\nErr(e) => {\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Handle all starting message cases |
20,244 | 13.04.2020 18:34:01 | 14,400 | bbaa36ef3958468e07ade6a132961b652a44ad8e | Upgrade forwarding client to read encrypted forward message | [
{
"change_type": "MODIFY",
"old_path": "Cargo.lock",
"new_path": "Cargo.lock",
"diff": "@@ -221,7 +221,6 @@ dependencies = [\n\"althea_types\",\n\"clarity\",\n\"failure\",\n- \"lazy_static\",\n\"log\",\n\"rand 0.7.3\",\n\"serde 1.0.105\",\n"
},
{
"change_type": "MODIFY",
"old_path": "antenna_forwarding_client/src/lib.rs",
"new_path": "antenna_forwarding_client/src/lib.rs",
"diff": "@@ -50,9 +50,9 @@ const FORWARD_TIMEOUT: Duration = Duration::from_secs(600);\npub fn start_antenna_forwarding_proxy<S: 'static + std::marker::Send + ::std::hash::BuildHasher>(\ncheckin_address: String,\nour_id: Identity,\n- _server_public_key: WgKey,\n+ server_public_key: WgKey,\n_our_public_key: WgKey,\n- _our_private_key: WgKey,\n+ our_private_key: WgKey,\ninterfaces_to_search: HashSet<String, S>,\n) {\ninfo!(\"Starting antenna forwarding proxy!\");\n@@ -84,7 +84,11 @@ pub fn start_antenna_forwarding_proxy<S: 'static + std::marker::Send + ::std::ha\n);\n// wait for a NET_TIMEOUT and see if the server responds, then read it's entire response\nthread::sleep(NET_TIMEOUT);\n- match ForwardingProtocolMessage::read_messages(&mut server_stream) {\n+ match ForwardingProtocolMessage::read_messages_start(\n+ &mut server_stream,\n+ server_public_key,\n+ our_private_key,\n+ ) {\nOk(messages) => {\n// read messages will return a vec of at least one,\nmatch messages.iter().next() {\n"
},
{
"change_type": "MODIFY",
"old_path": "antenna_forwarding_protocol/Cargo.toml",
"new_path": "antenna_forwarding_protocol/Cargo.toml",
"diff": "@@ -13,7 +13,6 @@ sodiumoxide = \"0.2\"\nfailure = \"0.1\"\nclarity = \"0.1\"\nlog = \"0.4\"\n-lazy_static = \"1.4\"\n[dev-dependencies]\nrand = \"0.7\"\n\\ No newline at end of file\n"
},
{
"change_type": "MODIFY",
"old_path": "antenna_forwarding_protocol/src/lib.rs",
"new_path": "antenna_forwarding_protocol/src/lib.rs",
"diff": "@@ -12,8 +12,6 @@ extern crate serde_derive;\nextern crate failure;\n#[macro_use]\nextern crate log;\n-#[macro_use]\n-extern crate lazy_static;\nuse althea_types::Identity;\nuse althea_types::WgKey;\n@@ -32,13 +30,6 @@ use std::net::TcpStream;\nuse std::thread;\nuse std::time::Duration;\n-lazy_static! {\n- pub static ref FORWARDING_SERVER_PUBLIC_KEY: WgKey =\n- \"hizclQFo/ArWY+/9+AJ0LBY2dTiQK4smy5icM7GA5ng=\"\n- .parse()\n- .unwrap();\n-}\n-\n/// The amount of time to sleep a thread that's spinlocking on somthing\npub const SPINLOCK_TIME: Duration = Duration::from_millis(100);\n@@ -497,6 +488,26 @@ impl ForwardingProtocolMessage {\n}\n}\n+ /// Reads messages using read_messages, but expecting the first message to be an encrypted fowarding message\n+ /// this is useful at the start of a forwarding session to simplify verification\n+ pub fn read_messages_start(\n+ input: &mut TcpStream,\n+ server_publickey: WgKey,\n+ client_secretkey: WgKey,\n+ ) -> Result<Vec<ForwardingProtocolMessage>, Error> {\n+ let bytes = read_till_block(input)?;\n+ let (bytes_read, msg) = ForwardingProtocolMessage::read_encrypted_forward_message(\n+ &bytes,\n+ server_publickey,\n+ client_secretkey,\n+ )?;\n+ ForwardingProtocolMessage::read_messages_internal(\n+ input,\n+ bytes[bytes_read..].to_vec(),\n+ vec![msg],\n+ )\n+ }\n+\n/// Reads all the currently available messages from the provided stream, this function will\n/// also block until a currently in flight message is delivered\npub fn read_messages(input: &mut TcpStream) -> Result<Vec<ForwardingProtocolMessage>, Error> {\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Upgrade forwarding client to read encrypted forward message |
20,244 | 13.04.2020 20:12:37 | 14,400 | 51922dd70540e230a97c65d7f589b79d5bf3cb5d | Handle close messages for encrypted forwards
This message can be securely allowed and generally smooths the
interaction and error handling flows. | [
{
"change_type": "MODIFY",
"old_path": "antenna_forwarding_client/src/lib.rs",
"new_path": "antenna_forwarding_client/src/lib.rs",
"diff": "@@ -97,6 +97,7 @@ pub fn start_antenna_forwarding_proxy<S: 'static + std::marker::Send + ::std::ha\nserver_port: _server_port,\nantenna_port,\n}) => {\n+ info!(\"Got forwarding message, forwarding {}\", ip);\n// if there are other messages in this batch safely form a slice\n// to pass on\nlet slice = if messages.len() > 1 {\n"
},
{
"change_type": "MODIFY",
"old_path": "antenna_forwarding_protocol/src/lib.rs",
"new_path": "antenna_forwarding_protocol/src/lib.rs",
"diff": "@@ -496,6 +496,11 @@ impl ForwardingProtocolMessage {\nclient_secretkey: WgKey,\n) -> Result<Vec<ForwardingProtocolMessage>, Error> {\nlet bytes = read_till_block(input)?;\n+ if let Ok((_bytes, ForwardingProtocolMessage::ForwardingCloseMessage)) =\n+ ForwardingProtocolMessage::read_message(&bytes)\n+ {\n+ return Ok(vec![ForwardingProtocolMessage::ForwardingCloseMessage]);\n+ }\nlet (bytes_read, msg) = ForwardingProtocolMessage::read_encrypted_forward_message(\n&bytes,\nserver_publickey,\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Handle close messages for encrypted forwards
This message can be securely allowed and generally smooths the
interaction and error handling flows. |
20,244 | 14.04.2020 08:29:36 | 14,400 | fa03d518c8725af4074648367221a3aa4b3abaa5 | We need lazy_static for tests | [
{
"change_type": "MODIFY",
"old_path": "Cargo.lock",
"new_path": "Cargo.lock",
"diff": "@@ -221,6 +221,7 @@ dependencies = [\n\"althea_types\",\n\"clarity\",\n\"failure\",\n+ \"lazy_static\",\n\"log\",\n\"rand 0.7.3\",\n\"serde 1.0.105\",\n"
},
{
"change_type": "MODIFY",
"old_path": "antenna_forwarding_protocol/Cargo.toml",
"new_path": "antenna_forwarding_protocol/Cargo.toml",
"diff": "@@ -13,6 +13,7 @@ sodiumoxide = \"0.2\"\nfailure = \"0.1\"\nclarity = \"0.1\"\nlog = \"0.4\"\n+lazy_static = \"1.4\"\n[dev-dependencies]\nrand = \"0.7\"\n\\ No newline at end of file\n"
},
{
"change_type": "MODIFY",
"old_path": "antenna_forwarding_protocol/src/lib.rs",
"new_path": "antenna_forwarding_protocol/src/lib.rs",
"diff": "@@ -12,6 +12,9 @@ extern crate serde_derive;\nextern crate failure;\n#[macro_use]\nextern crate log;\n+#[cfg(test)]\n+#[macro_use]\n+extern crate lazy_static;\nuse althea_types::Identity;\nuse althea_types::WgKey;\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | We need lazy_static for tests |
20,244 | 14.04.2020 11:10:34 | 14,400 | 17d14a2f4fafea2551743878f5e1553156b8f865 | Remove unimplemented from antenna protocol and client code
This removes a lot of crash cases on bad messages or other unexpected
input. I might want to add this back in under a development feature flag
at a later date | [
{
"change_type": "MODIFY",
"old_path": "antenna_forwarding_client/src/lib.rs",
"new_path": "antenna_forwarding_client/src/lib.rs",
"diff": "@@ -74,7 +74,6 @@ pub fn start_antenna_forwarding_proxy<S: 'static + std::marker::Send + ::std::ha\n// parse checkin address every loop iteration as a way\n// of resolving the domain name on each run\ntrace!(\"About to checkin with {}\", checkin_address);\n- thread::sleep(SLEEP_TIME);\nif let Ok(mut server_stream) = TcpStream::connect_timeout(&socket, NET_TIMEOUT) {\ntrace!(\"connected to {}\", checkin_address);\n// send our identifier\n@@ -145,11 +144,17 @@ fn process_messages(\nfor item in input {\nmatch item {\n// why would the server ID themselves to us?\n- ForwardingProtocolMessage::IdentificationMessage { .. } => unimplemented!(),\n+ ForwardingProtocolMessage::IdentificationMessage { .. } => {\n+ error!(\"Why did the server identify?\")\n+ }\n// two forward messages?\n- ForwardingProtocolMessage::ForwardMessage { .. } => unimplemented!(),\n+ ForwardingProtocolMessage::ForwardMessage { .. } => {\n+ error!(\"Got second forward message?\")\n+ }\n// the server doesn't send us error messages, what would we do with it?\n- ForwardingProtocolMessage::ErrorMessage { .. } => unimplemented!(),\n+ ForwardingProtocolMessage::ErrorMessage { .. } => {\n+ error!(\"Server sent us an error message?\")\n+ }\nForwardingProtocolMessage::ConnectionCloseMessage { stream_id } => {\ntrace!(\"Got close message for stream {}\", stream_id);\n*last_message = Instant::now();\n@@ -195,7 +200,7 @@ fn process_messages(\nreturn true;\n}\n// we don't use this yet\n- ForwardingProtocolMessage::KeepAliveMessage => unimplemented!(),\n+ ForwardingProtocolMessage::KeepAliveMessage => {}\n}\n}\nfalse\n@@ -266,7 +271,7 @@ fn find_antenna<S: ::std::hash::BuildHasher>(\nip: IpAddr,\ninterfaces: &HashSet<String, S>,\n) -> Result<String, Error> {\n- let our_ip = get_local_ip(ip);\n+ let our_ip = get_local_ip(ip)?;\nfor iface in interfaces {\ntrace!(\"Trying interface {}, with test ip {}\", iface, our_ip);\n// this acts as a wildcard deletion across all interfaces, which is frankly really\n@@ -337,7 +342,7 @@ fn find_antenna<S: ::std::hash::BuildHasher>(\n/// Generates a random non overlapping ip within a /24 subnet of the provided\n/// target antenna ip.\n-fn get_local_ip(target_ip: IpAddr) -> IpAddr {\n+fn get_local_ip(target_ip: IpAddr) -> Result<IpAddr, Error> {\nmatch target_ip {\nIpAddr::V4(address) => {\nlet mut rng = rand::thread_rng();\n@@ -350,9 +355,9 @@ fn get_local_ip(target_ip: IpAddr) -> IpAddr {\nnew_ip = rng.gen()\n}\nbytes[3] = new_ip;\n- Ipv4Addr::new(bytes[0], bytes[1], bytes[2], bytes[3]).into()\n+ Ok(Ipv4Addr::new(bytes[0], bytes[1], bytes[2], bytes[3]).into())\n}\n- IpAddr::V6(_address) => unimplemented!(),\n+ IpAddr::V6(_address) => Err(format_err!(\"Not supported!\")),\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "antenna_forwarding_protocol/src/lib.rs",
"new_path": "antenna_forwarding_protocol/src/lib.rs",
"diff": "@@ -270,7 +270,7 @@ impl ForwardingProtocolMessage {\nmessage.extend_from_slice(&payload);\nOk(message)\n} else {\n- unimplemented!()\n+ Err(format_err!(\"Invalid operation!\"))\n}\n}\n@@ -428,7 +428,9 @@ impl ForwardingProtocolMessage {\n}\n}\n// you can not read encrypted packets with this function\n- ForwardingProtocolMessage::FORWARD_MESSAGE_TYPE => unimplemented!(),\n+ ForwardingProtocolMessage::FORWARD_MESSAGE_TYPE => {\n+ Err(format_err!(\"Invalid packet type\"))\n+ }\nForwardingProtocolMessage::ERROR_MESSAGE_TYPE => {\nlet bytes_read = HEADER_LEN + packet_len as usize;\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Remove unimplemented from antenna protocol and client code
This removes a lot of crash cases on bad messages or other unexpected
input. I might want to add this back in under a development feature flag
at a later date |
20,244 | 14.04.2020 14:29:58 | 14,400 | ab17067a26938f7db6b4db50043db710304689d4 | Add basic antenna blacklist | [
{
"change_type": "MODIFY",
"old_path": "antenna_forwarding_client/src/lib.rs",
"new_path": "antenna_forwarding_client/src/lib.rs",
"diff": "@@ -271,6 +271,7 @@ fn find_antenna<S: ::std::hash::BuildHasher>(\nip: IpAddr,\ninterfaces: &HashSet<String, S>,\n) -> Result<String, Error> {\n+ check_blacklist(ip)?;\nlet our_ip = get_local_ip(ip)?;\nfor iface in interfaces {\ntrace!(\"Trying interface {}, with test ip {}\", iface, our_ip);\n@@ -361,8 +362,46 @@ fn get_local_ip(target_ip: IpAddr) -> Result<IpAddr, Error> {\n}\n}\n+const IP_BLACKLIST: [Ipv4Addr; 2] = [Ipv4Addr::new(192, 168, 10, 0), Ipv4Addr::new(127, 0, 0, 0)];\n+\n+/// Checks the forwarding ip blacklist, these are ip's that we don't\n+/// want the forwarding client working on\n+fn check_blacklist(ip: IpAddr) -> Result<(), Error> {\n+ match ip {\n+ IpAddr::V4(address) => {\n+ for ip in IP_BLACKLIST.iter() {\n+ if compare_ipv4_octets(*ip, address) {\n+ return Err(format_err!(\"Blacklisted address!\"));\n+ }\n+ }\n+ Ok(())\n+ }\n+ IpAddr::V6(_address) => Ok(()),\n+ }\n+}\n+\n+fn compare_ipv4_octets(mask: Ipv4Addr, to_compare: Ipv4Addr) -> bool {\n+ let mut bytes = to_compare.octets();\n+ bytes[3] = 0;\n+ let out: Ipv4Addr = bytes.into();\n+ mask == out\n+}\n+\nfn send_error_message(server_stream: &mut TcpStream, message: String) {\nlet msg = ForwardingProtocolMessage::new_error_message(message);\nlet _res = write_all_spinlock(server_stream, &msg.get_message());\nlet _res = server_stream.shutdown(Shutdown::Both);\n}\n+\n+#[cfg(test)]\n+mod tests {\n+ use super::*;\n+\n+ #[test]\n+ fn test_blacklist() {\n+ let res = check_blacklist(Ipv4Addr::new(192, 168, 10, 1).into());\n+ assert!(res.is_err());\n+ let res = check_blacklist(Ipv4Addr::new(192, 168, 11, 1).into());\n+ assert!(res.is_ok());\n+ }\n+}\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Add basic antenna blacklist |
20,244 | 14.04.2020 14:42:46 | 14,400 | 79249cfdd1903f666ae811f50770663507355411 | Add phone number and email to heartbeat
This should let us have the instantaniously updated contact details
we want without any user privacy risk as this message is encrypted | [
{
"change_type": "MODIFY",
"old_path": "althea_types/src/interop.rs",
"new_path": "althea_types/src/interop.rs",
"diff": "@@ -385,6 +385,13 @@ pub struct OperatorCheckinMessage {\npub id: Identity,\n}\n+/// Struct for storing user contact details\n+#[derive(Debug, Clone, Serialize, Deserialize)]\n+pub struct ContactDetails {\n+ pub phone: Option<String>,\n+ pub email: Option<String>,\n+}\n+\n/// Heartbeat sent to the operator server to help monitor\n/// liveness and network state\n#[derive(Debug, Clone, Serialize, Deserialize)]\n@@ -408,4 +415,6 @@ pub struct HeartbeatMessage {\n/// The babel Neighbor over which our traffic flows, this gives us the Reach\n/// (packet loss over 16 seconds) as well as the neighbor RTT\npub exit_neighbor: Neighbor,\n+ /// The exit registration contact details. If set\n+ pub contact_details: ContactDetails,\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_client/heartbeat/mod.rs",
"new_path": "rita/src/rita_client/heartbeat/mod.rs",
"diff": "@@ -14,6 +14,7 @@ use crate::rita_common::tunnel_manager::Neighbor as RitaNeighbor;\nuse crate::SETTING;\nuse actix::actors::resolver;\nuse actix::{Arbiter, SystemService};\n+use althea_types::ContactDetails;\nuse althea_types::HeartbeatMessage;\nuse althea_types::Identity;\nuse althea_types::WgKey;\n@@ -152,6 +153,7 @@ fn send_udp_heartbeat_packet(\nexit_neighbor_id: Identity,\n) {\nlet network_settings = SETTING.get_network();\n+ let reg_details = SETTING.get_exit_client().reg_details.clone();\nlet our_publickey = network_settings.wg_public_key.expect(\"No public key?\");\nlet our_secretkey = network_settings\n.wg_private_key\n@@ -159,6 +161,17 @@ fn send_udp_heartbeat_packet(\n.into();\nlet their_publickey: WgKey = *HEARTBEAT_SERVER_KEY;\nlet their_publickey = their_publickey.into();\n+\n+ let contact_details = match reg_details {\n+ Some(details) => ContactDetails {\n+ phone: details.phone,\n+ email: details.email,\n+ },\n+ None => ContactDetails {\n+ phone: None,\n+ email: None,\n+ },\n+ };\ndrop(network_settings);\nlet remote_ip = dns_socket.ip();\n@@ -184,6 +197,7 @@ fn send_udp_heartbeat_packet(\nupstream_id: exit_neighbor_id,\nexit_route,\nexit_neighbor,\n+ contact_details,\n};\n// serde will only fail under specific circumstances with specific structs\n// given the fixed nature of our application here I think this is safe\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Add phone number and email to heartbeat
This should let us have the instantaniously updated contact details
we want without any user privacy risk as this message is encrypted |
20,244 | 14.04.2020 17:14:06 | 14,400 | ed5193221e0d411b4ac2042c55d57bdc3e773d0e | Working OperatorCheckin
Added some things we need to properly process this on the operator
tools server side of things. Plus testing of course. | [
{
"change_type": "MODIFY",
"old_path": "althea_types/src/interop.rs",
"new_path": "althea_types/src/interop.rs",
"diff": "@@ -383,6 +383,8 @@ pub struct OperatorUpdateMessage {\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct OperatorCheckinMessage {\npub id: Identity,\n+ pub operator_address: Option<Address>,\n+ pub system_chain: SystemChain,\n}\n/// Struct for storing user contact details\n"
},
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_client/operator_update/mod.rs",
"new_path": "rita/src/rita_client/operator_update/mod.rs",
"diff": "@@ -76,6 +76,7 @@ impl Handler<Update> for OperatorUpdate {\nfn checkin() {\nlet logging_enabled = SETTING.get_log().enabled;\nlet operator_settings = SETTING.get_operator();\n+ let system_chain = SETTING.get_payment().system_chain;\nlet url = operator_settings.checkin_url.clone();\nlet operator_address = operator_settings.operator_address;\nlet use_operator_price =\n@@ -91,23 +92,33 @@ fn checkin() {\nreturn;\n}\n- info!(\n- \"Starting Operator checkin using {} and {:?}\",\n- url, operator_address\n- );\n+ match operator_address {\n+ Some(address) => info!(\"Operator checkin using {} and {}\", url, address),\n+ None => info!(\n+ \"Operator checkin for default settings {} and {}\",\n+ url, system_chain\n+ ),\n+ }\nlet res = client::post(url)\n.header(\"User-Agent\", \"Actix-web\")\n- .json(OperatorCheckinMessage { id })\n+ .json(OperatorCheckinMessage {\n+ id,\n+ operator_address,\n+ system_chain,\n+ })\n.unwrap()\n.send()\n.timeout(OPERATOR_UPDATE_TIMEOUT)\n.from_err()\n.and_then(move |response| {\n+ trace!(\"Response is {:?}\", response.status());\n+ trace!(\"Response is {:?}\", response.headers());\nresponse\n.json()\n.from_err()\n.and_then(move |new_settings: OperatorUpdateMessage| {\n+ trace!(\"Updating from operator settings\");\nlet mut payment = SETTING.get_payment_mut();\nlet starting_token_bridge_core = payment.bridge_addresses.clone();\n@@ -133,10 +144,12 @@ fn checkin() {\npayment.withdraw_chain = new_chain;\n}\ndrop(payment);\n+ trace!(\"Done with payment\");\nlet mut operator = SETTING.get_operator_mut();\nlet new_operator_fee = Uint256::from(new_settings.operator_fee);\noperator.operator_fee = new_operator_fee;\n+ drop(operator);\nmerge_settings_safely(new_settings.merge_json);\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Working OperatorCheckin
Added some things we need to properly process this on the operator
tools server side of things. Plus testing of course. |
20,244 | 14.04.2020 17:25:00 | 14,400 | c65d2d2478c48e506c132bfb86a81455bc7bbcc1 | Add balance notification to Heartbeat
I would like to move the task of notifying users about their balance
to the operator tools server, since it's more accessible to operators | [
{
"change_type": "MODIFY",
"old_path": "althea_types/src/interop.rs",
"new_path": "althea_types/src/interop.rs",
"diff": "@@ -417,6 +417,8 @@ pub struct HeartbeatMessage {\n/// The babel Neighbor over which our traffic flows, this gives us the Reach\n/// (packet loss over 16 seconds) as well as the neighbor RTT\npub exit_neighbor: Neighbor,\n+ /// If this user wants to be notified when they have a low balance\n+ pub notify_balance: bool,\n/// The exit registration contact details. If set\npub contact_details: ContactDetails,\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_client/heartbeat/mod.rs",
"new_path": "rita/src/rita_client/heartbeat/mod.rs",
"diff": "@@ -154,6 +154,7 @@ fn send_udp_heartbeat_packet(\n) {\nlet network_settings = SETTING.get_network();\nlet reg_details = SETTING.get_exit_client().reg_details.clone();\n+ let low_balance_notification = SETTING.get_exit_client().low_balance_notification;\nlet our_publickey = network_settings.wg_public_key.expect(\"No public key?\");\nlet our_secretkey = network_settings\n.wg_private_key\n@@ -197,6 +198,7 @@ fn send_udp_heartbeat_packet(\nupstream_id: exit_neighbor_id,\nexit_route,\nexit_neighbor,\n+ notify_balance: low_balance_notification,\ncontact_details,\n};\n// serde will only fail under specific circumstances with specific structs\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Add balance notification to Heartbeat
I would like to move the task of notifying users about their balance
to the operator tools server, since it's more accessible to operators |
20,244 | 14.04.2020 17:33:01 | 14,400 | 3d71d377121d60c83556ae94f335a25c3a458fce | Bump For Beta 13 RC1 | [
{
"change_type": "MODIFY",
"old_path": "Cargo.lock",
"new_path": "Cargo.lock",
"diff": "@@ -2629,7 +2629,7 @@ dependencies = [\n[[package]]\nname = \"rita\"\n-version = \"0.5.39\"\n+version = \"0.5.40\"\ndependencies = [\n\"actix\",\n\"actix-web\",\n"
},
{
"change_type": "MODIFY",
"old_path": "rita/Cargo.toml",
"new_path": "rita/Cargo.toml",
"diff": "[package]\nname = \"rita\"\n-version = \"0.5.39\"\n+version = \"0.5.40\"\nauthors = [\"Jehan <jehan.tremback@gmail.com>\", \"Ben <wangben3@gmail.com>\"]\nbuild = \"build.rs\"\nedition = \"2018\"\n"
},
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_common/dashboard/own_info.rs",
"new_path": "rita/src/rita_common/dashboard/own_info.rs",
"diff": "@@ -6,7 +6,7 @@ use failure::Error;\nuse num256::{Int256, Uint256};\nuse settings::RitaCommonSettings;\n-pub static READABLE_VERSION: &str = \"Beta 12 RC2\";\n+pub static READABLE_VERSION: &str = \"Beta 13 RC1\";\n#[derive(Serialize)]\npub struct OwnInfo {\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Bump For Beta 13 RC1 |
20,244 | 14.04.2020 17:49:52 | 14,400 | db4fc0ee3cbf4ba9eb53c10997ab2dba4b2f7144 | Disable low balance notifications from the exit
During the transition between exit and operator tools for low balance
notifications some devices will be updated while others will not. Since
we can't disable the old system until the conversion is complete we should
short circuit it on new devices to avoid double notifying. | [
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_client/exit_manager/mod.rs",
"new_path": "rita/src/rita_client/exit_manager/mod.rs",
"diff": "@@ -329,11 +329,6 @@ fn exit_status_request(exit: String) -> impl Future<Item = (), Error = Error> {\nas Box<dyn Future<Item = (), Error = Error>>;\n}\n};\n- let balance_notification = if SETTING.get_exit_client().low_balance_notification {\n- low_balance()\n- } else {\n- false\n- };\nlet exit_server = current_exit.id.mesh_ip;\nlet exit_pubkey = current_exit.id.wg_public_key;\n@@ -348,7 +343,7 @@ fn exit_status_request(exit: String) -> impl Future<Item = (), Error = Error> {\n},\nwg_port: SETTING.get_exit_client().wg_listen_port,\nreg_details: SETTING.get_exit_client().reg_details.clone().unwrap(),\n- low_balance: Some(balance_notification),\n+ low_balance: Some(false),\n};\nlet endpoint = SocketAddr::new(exit_server, current_exit.registration_port);\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Disable low balance notifications from the exit
During the transition between exit and operator tools for low balance
notifications some devices will be updated while others will not. Since
we can't disable the old system until the conversion is complete we should
short circuit it on new devices to avoid double notifying. |
20,244 | 15.04.2020 13:21:29 | 14,400 | f7a2d1cae9c5f0588f3932b6da2db80ccf7fb3d9 | Add company name to LICENSE
This is an oversight when adding the LICENSE. | [
{
"change_type": "MODIFY",
"old_path": "LICENSE",
"new_path": "LICENSE",
"diff": "same \"printed page\" as the copyright notice for easier\nidentification within third-party archives.\n- Copyright [yyyy] [name of copyright owner]\n+ Copyright 2020 Hawk Networks INC\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Add company name to LICENSE
This is an oversight when adding the LICENSE. |
20,244 | 15.04.2020 15:32:59 | 14,400 | 88789d69f73ae60d93e01c9fbe8bde9b0c3fc351 | Don't restrict phone forwards by source
Preventing spoofed or lan packets is handled elsewhere, also
the phone sends packets with the dst field set to the internet
destination address. | [
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_client/light_client_manager/mod.rs",
"new_path": "rita/src/rita_client/light_client_manager/mod.rs",
"diff": "@@ -62,8 +62,6 @@ fn setup_light_client_forwarding(client_addr: Ipv4Addr, nic: &str) -> Result<(),\n&nic,\n\"--src\",\n&format!(\"{}/32\", client_addr),\n- \"--dst\",\n- \"192.168.20.0/24\",\n\"-j\",\n\"ACCEPT\",\n],\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Don't restrict phone forwards by source
Preventing spoofed or lan packets is handled elsewhere, also
the phone sends packets with the dst field set to the internet
destination address. |
20,244 | 15.04.2020 16:40:43 | 14,400 | 59cb0bcba243d0dd4d6c3d02ba01751968717678 | Fix deadlock when disabling automated pricing
Yet another implicit deadlock gotcha. There really needs to be a
static tool to detect these. | [
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_client/dashboard/prices.rs",
"new_path": "rita/src/rita_client/dashboard/prices.rs",
"diff": "@@ -24,6 +24,7 @@ pub fn set_auto_pricing(path: Path<bool>) -> Result<HttpResponse, Error> {\nif !op.force_use_operator_price {\nop.use_operator_price = value;\n}\n+ drop(op);\n// try and save the config and fail if we can't\nif let Err(e) = SETTING.write().unwrap().write(&ARGS.flag_config) {\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Fix deadlock when disabling automated pricing
Yet another implicit deadlock gotcha. There really needs to be a
static tool to detect these. |
20,244 | 16.04.2020 07:11:25 | 14,400 | 68e6786d6846a5359f0c3297633f3e6b975ea75d | Fix xdai serialization
I guess we've always used debug print before | [
{
"change_type": "MODIFY",
"old_path": "althea_types/src/interop.rs",
"new_path": "althea_types/src/interop.rs",
"diff": "@@ -106,7 +106,7 @@ impl Display for SystemChain {\nmatch self {\nSystemChain::Ethereum => write!(f, \"Ethereum\"),\nSystemChain::Rinkeby => write!(f, \"Rinkeby\"),\n- SystemChain::Xdai => write!(f, \"Xday\"),\n+ SystemChain::Xdai => write!(f, \"Xdai\"),\n}\n}\n}\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Fix xdai serialization
I guess we've always used debug print before |
20,244 | 16.04.2020 08:54:18 | 14,400 | 775c48ebe1264d0d01a651b9620bdc5d0bfabc29 | Add backend port for operator checkin
I could have redirected this using nginx but why bother? | [
{
"change_type": "MODIFY",
"old_path": "settings/src/operator.rs",
"new_path": "settings/src/operator.rs",
"diff": "@@ -27,7 +27,7 @@ fn default_force_use_operator_price() -> bool {\n/// The url for checking in with the operator server.\n/// if you are changing this double check the default currency and the default node url\nfn default_checkin_url() -> String {\n- \"https://operator.althea.net/checkin\".to_string()\n+ \"https://operator.althea.net:8080/checkin\".to_string()\n}\n#[derive(Debug, Serialize, Deserialize, Clone, Eq, PartialEq)]\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Add backend port for operator checkin
I could have redirected this using nginx but why bother? |
20,244 | 16.04.2020 12:16:18 | 14,400 | 9779c92249bfb70a1561e49a30eb1aabf62bae3d | Backoff for network monitor
Previously network monitor could reduce the speed of a link but would
never increase it again. This modifies the module to increase the the
speed if it determins (by heuristic) that the link is doing ok. This
is rate limited in order to prevent too much see-sawing in bandwidth. | [
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_common/network_monitor/mod.rs",
"new_path": "rita/src/rita_common/network_monitor/mod.rs",
"diff": "//! on traffic over every interface and base our action off of spikes in throughput as well as spikes in latency.\nuse crate::rita_common::rita_loop::fast_loop::FAST_LOOP_SPEED;\n-use crate::rita_common::tunnel_manager::GotBloat;\nuse crate::rita_common::tunnel_manager::Neighbor as RitaNeighbor;\n+use crate::rita_common::tunnel_manager::ShapingAdjust;\n+use crate::rita_common::tunnel_manager::ShapingAdjustAction;\nuse crate::rita_common::tunnel_manager::TunnelManager;\nuse actix::Actor;\nuse actix::Context;\n@@ -23,17 +24,24 @@ use babel_monitor::Neighbor as BabelNeighbor;\nuse babel_monitor::Route as BabelRoute;\nuse failure::Error;\nuse std::collections::HashMap;\n+use std::time::Duration;\n+use std::time::Instant;\nconst SAMPLE_PERIOD: u8 = FAST_LOOP_SPEED as u8;\nconst SAMPLES_IN_FIVE_MINUTES: usize = 300 / SAMPLE_PERIOD as usize;\n+/// 10 minutes in seconds, the amount of time we wait for an interface to be\n+/// 'good' before we start trying to increase it's speed\n+const BACK_OFF_TIME: Duration = Duration::from_secs(600);\n/// Implements https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Welford's_online_algorithm\n-/// to keep track of neighbor latency in an online fashion\n+/// to keep track of neighbor latency in an online fashion for a specific interface\n#[derive(Clone)]\npub struct RunningLatencyStats {\ncount: u32,\nmean: f32,\nm2: f32,\n+ /// the last time this counters interface was invalidated by a change\n+ last_changed: Instant,\n}\nimpl RunningLatencyStats {\n@@ -42,6 +50,7 @@ impl RunningLatencyStats {\ncount: 0u32,\nmean: 0f32,\nm2: 0f32,\n+ last_changed: Instant::now(),\n}\n}\npub fn get_avg(&self) -> Option<f32> {\n@@ -76,10 +85,22 @@ impl RunningLatencyStats {\n(None, None) => false,\n}\n}\n+ /// A hand tuned heuristic used to determine if a connection is good\n+ pub fn is_good(&self) -> bool {\n+ let avg = self.get_avg();\n+ let std_dev = self.get_std_dev();\n+ match (avg, std_dev) {\n+ (Some(avg), Some(std_dev)) => std_dev <= avg * 2f32,\n+ (Some(_avg), None) => false,\n+ (None, Some(_std_dev)) => false,\n+ (None, None) => false,\n+ }\n+ }\npub fn reset(&mut self) {\nself.count = 0u32;\nself.mean = 0f32;\nself.m2 = 0f32;\n+ self.last_changed = Instant::now();\n}\n}\n@@ -307,33 +328,52 @@ fn observe_network(\n}\nlet running_stats = latency_history.get_mut(iface).unwrap();\nmatch (\n- running_stats.is_bloated(),\nget_wg_key_by_ifname(neigh, rita_neighbors),\nrunning_stats.get_avg(),\nrunning_stats.get_std_dev(),\n) {\n- (true, Some(key), Some(avg), Some(std_dev)) => {\n+ (Some(key), Some(avg), Some(std_dev)) => {\n+ if running_stats.is_bloated() {\ninfo!(\n- \"{} is now defined as bloated with AVG {} STDDEV {} and CV {}!\",\n+ \"{} is defined as bloated with AVG {} STDDEV {} and CV {}!\",\nkey, avg, std_dev, neigh.rtt\n);\n// shape the misbehaving tunnel\n- TunnelManager::from_registry().do_send(GotBloat {\n+ TunnelManager::from_registry().do_send(ShapingAdjust {\niface: iface.to_string(),\n+ action: ShapingAdjustAction::ReduceSpeed,\n});\n// reset the values for this entry because we have modified\n// the qdisc and it's no longer an accurate representation\nrunning_stats.reset();\n- }\n- (false, Some(key), Some(avg), Some(std_dev)) => info!(\n+ } else if Instant::now() > running_stats.last_changed\n+ && Instant::now() - running_stats.last_changed > BACK_OFF_TIME\n+ && running_stats.is_good()\n+ {\n+ info!(\n+ \"Neighbor {} is increasing speed with AVG {} STDDEV {} and CV {}\",\n+ key, avg, std_dev, neigh.rtt\n+ );\n+ // shape the misbehaving tunnel\n+ TunnelManager::from_registry().do_send(ShapingAdjust {\n+ iface: iface.to_string(),\n+ action: ShapingAdjustAction::IncreaseSpeed,\n+ });\n+ // reset the values for this entry because we have modified\n+ // the qdisc and it's no longer an accurate representation\n+ running_stats.reset();\n+ } else {\n+ info!(\n\"Neighbor {} is ok with AVG {} STDDEV {} and CV {}\",\nkey, avg, std_dev, neigh.rtt\n- ),\n- (true, None, _, _) => error!(\n+ )\n+ }\n+ }\n+ (None, _, _) => error!(\n\"We have a bloated connection to {} but no Rita neighbor!\",\niface\n),\n- (_, _, _, _) => {}\n+ (_, _, _) => {}\n}\nrunning_stats.add_sample(neigh.rtt);\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_common/tunnel_manager/mod.rs",
"new_path": "rita/src/rita_common/tunnel_manager/mod.rs",
"diff": "@@ -330,18 +330,25 @@ impl Default for TunnelManager {\n}\n/// Message sent by network monitor when it determines that an iface is bloated\n-pub struct GotBloat {\n+pub struct ShapingAdjust {\npub iface: String,\n+ pub action: ShapingAdjustAction,\n}\n-impl Message for GotBloat {\n+pub enum ShapingAdjustAction {\n+ IncreaseSpeed,\n+ ReduceSpeed,\n+}\n+\n+impl Message for ShapingAdjust {\ntype Result = ();\n}\n-impl Handler<GotBloat> for TunnelManager {\n+impl Handler<ShapingAdjust> for TunnelManager {\ntype Result = ();\n- fn handle(&mut self, msg: GotBloat, _: &mut Context<Self>) -> Self::Result {\n+ fn handle(&mut self, msg: ShapingAdjust, _: &mut Context<Self>) -> Self::Result {\n+ let action = msg.action;\nlet network_settings = SETTING.get_network();\nlet minimum_bandwidth_limit = network_settings.minimum_bandwidth_limit;\nlet starting_bandwidth_limit = network_settings.starting_bandwidth_limit;\n@@ -364,14 +371,16 @@ impl Handler<GotBloat> for TunnelManager {\nfor (id, tunnel_list) in self.tunnels.iter_mut() {\nfor tunnel in tunnel_list {\nif tunnel.iface_name == iface {\n- match tunnel.speed_limit {\n+ match (tunnel.speed_limit, action) {\n+ // nothing to do in this case\n+ (None, ShapingAdjustAction::IncreaseSpeed) => {}\n// start at the starting limit\n- None => {\n+ (None, ShapingAdjustAction::ReduceSpeed) => {\ntunnel.speed_limit = Some(starting_bandwidth_limit);\nset_shaping_or_error(&iface, Some(starting_bandwidth_limit))\n}\n// after that cut the value by 20% each time\n- Some(val) => {\n+ (Some(val), ShapingAdjustAction::ReduceSpeed) => {\nlet new_val = (val as f32 * 0.8f32) as usize;\nif new_val < minimum_bandwidth_limit {\nerror!(\"Interface {} for peer {} is showing bloat but we can't reduce it's bandwidth any further. Current value {}\", iface, id.wg_public_key, val);\n@@ -384,6 +393,18 @@ impl Handler<GotBloat> for TunnelManager {\ntunnel.speed_limit = Some(new_val);\n}\n}\n+ // increase the value by 5% until we reach the starting value\n+ (Some(val), ShapingAdjustAction::IncreaseSpeed) => {\n+ let new_val = (val as f32 * 1.05f32) as usize;\n+ if new_val < starting_bandwidth_limit {\n+ info!(\n+ \"Interface {} for peer {} has not shown bloat new speed value {}\",\n+ iface, id.wg_public_key, new_val\n+ );\n+ set_shaping_or_error(&iface, Some(new_val));\n+ tunnel.speed_limit = Some(new_val);\n+ }\n+ }\n}\nreturn;\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Backoff for network monitor
Previously network monitor could reduce the speed of a link but would
never increase it again. This modifies the module to increase the the
speed if it determins (by heuristic) that the link is doing ok. This
is rate limited in order to prevent too much see-sawing in bandwidth. |
20,244 | 16.04.2020 14:00:36 | 14,400 | 48aa972db6ba3a8ebb7e7c177432c34ad699d30c | Show correct 5ghz channel options for ea6350v3 | [
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_client/dashboard/wifi.rs",
"new_path": "rita/src/rita_client/dashboard/wifi.rs",
"diff": "@@ -24,8 +24,8 @@ pub const ALLOWED_FIVE_20: [u16; 22] = [\npub const ALLOWED_FIVE_40: [u16; 12] = [36, 44, 52, 60, 100, 108, 116, 124, 132, 140, 149, 157];\n/// list of nonoverlapping 80mhz channels generally legal in NA, SA, EU, AU\npub const ALLOWED_FIVE_80: [u16; 6] = [36, 52, 100, 116, 132, 149];\n-/// list of nonoverlapping 80mhz channels for the GLB1300\n-pub const ALLOWED_FIVE_80_B1300: [u16; 2] = [36, 149];\n+/// list of nonoverlapping 80mhz channels for the GLB1300/EA6350v3\n+pub const ALLOWED_FIVE_80_IPQ40XX: [u16; 2] = [36, 149];\n/// list of nonoverlapping 160mhz channels generally legal in NA, SA, EU, AU\npub const ALLOWED_FIVE_160: [u16; 2] = [36, 100];\n@@ -280,14 +280,15 @@ fn validate_channel(\n))\n// model specific restrictions below this point\n} else if model.is_some()\n- && model.unwrap().contains(\"gl-b1300\")\n+ && (model.clone().unwrap().contains(\"gl-b1300\")\n+ || model.unwrap().contains(\"linksys_ea6350v3\"))\n&& new_is_five\n&& channel_width_is_80\n- && !ALLOWED_FIVE_80_B1300.contains(&new_val)\n+ && !ALLOWED_FIVE_80_IPQ40XX.contains(&new_val)\n{\nErr(ValidationError::BadChannel(\n\"80\".to_string(),\n- format!(\"{:?}\", ALLOWED_FIVE_80_B1300),\n+ format!(\"{:?}\", ALLOWED_FIVE_80_IPQ40XX),\n))\n} else {\nOk(())\n@@ -310,10 +311,11 @@ pub fn get_allowed_wifi_channels(radio: Path<String>) -> Result<HttpResponse, Er\n// model specific values start here\n} else if model.is_some()\n- && model.unwrap().contains(\"gl-b1300\")\n+ && (model.clone().unwrap().contains(\"gl-b1300\")\n+ || model.unwrap().contains(\"linksys_ea6350v3\"))\n&& five_channel_width.contains(\"80\")\n{\n- Ok(HttpResponse::Ok().json(ALLOWED_FIVE_80_B1300))\n+ Ok(HttpResponse::Ok().json(ALLOWED_FIVE_80_IPQ40XX))\n// model specific values end here\n} else if five_channel_width.contains(\"20\") {\nOk(HttpResponse::Ok().json(ALLOWED_FIVE_20))\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Show correct 5ghz channel options for ea6350v3 |
20,244 | 16.04.2020 15:15:47 | 14,400 | efd47db26d58d8d4c9aa42c736f57d2c7939f387 | Reset nat rules after wifi parameter change | [
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_client/dashboard/wifi.rs",
"new_path": "rita/src/rita_client/dashboard/wifi.rs",
"diff": "@@ -140,6 +140,9 @@ fn set_ssid(wifi_ssid: &WifiSSID) -> Result<HttpResponse, Error> {\n// if the ssid is too long but don't block on that\nlet _ = maybe_set_nickname(wifi_ssid.ssid.clone());\n+ // we have invalidated the old nat rules, update them\n+ KI.create_client_nat_rules()?;\n+\nOk(HttpResponse::Ok().json(ret))\n}\n@@ -183,6 +186,10 @@ fn set_pass(wifi_pass: &WifiPass) -> Result<HttpResponse, Error> {\n// We edited disk contents, force global sync\nKI.fs_sync()?;\n+\n+ // we have invalidated the old nat rules, update them\n+ KI.create_client_nat_rules()?;\n+\nOk(HttpResponse::Ok().json(()))\n}\n@@ -215,6 +222,9 @@ fn set_channel(wifi_channel: &WifiChannel) -> Result<HttpResponse, Error> {\n// We edited disk contents, force global sync\nKI.fs_sync()?;\n+ // we have invalidated the old nat rules, update them\n+ KI.create_client_nat_rules()?;\n+\nOk(HttpResponse::Ok().json(()))\n}\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Reset nat rules after wifi parameter change |
20,244 | 17.04.2020 12:32:20 | 14,400 | 6f1ded1abae1846cd8300cce9d2da443a71a075f | Improve operator update doc comments | [
{
"change_type": "MODIFY",
"old_path": "althea_types/src/interop.rs",
"new_path": "althea_types/src/interop.rs",
"diff": "@@ -365,17 +365,36 @@ impl FromStr for ReleaseStatus {\n/// Operator update that we get from the operator server during our checkin\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct OperatorUpdateMessage {\n+ /// This really should be 'relay' as it is the price that a normal\n+ /// 'client' changes other clients for bandwdith (aka the default relay price)\npub client: u32,\n+ /// The default 'gateway' price, this comes with a few caveats mainly that gateway\n+ /// auto detection is based around having a wan port and is not always accurate but\n+ /// generally gateways will always be detected as gateways and relays may sometimes\n+ /// declare themselves gateways if the user toggled in a WAN port even if that WAN port\n+ /// is not being used\npub gateway: u32,\n+ /// The maximum price any given router will pay in bandwidth, above this price the routers\n+ /// will only pay their peer the max price\npub max: u32,\n+ /// This is the pro-rated fee paid to the operator, defined as wei/second\npub operator_fee: u128,\n+ /// This is the balance level at which the user starts to see the little 'warning'\n+ /// message on their dashboard and also when the low balance text message is sent\npub warning: u128,\n+ /// The system blockchain that is currently being used, if it is 'none' here it is\n+ /// interpreted as \"don't change anything\"\npub system_chain: Option<SystemChain>,\n+ /// The wtihdraw blockchain that is currently being used, if it is 'none' here it is\n+ /// interpreted as \"don't change anything\"\npub withdraw_chain: Option<SystemChain>,\n/// A release feed to be applied to the /etc/opkg/customfeeds.config, None means do not\n/// change the currently configured release feed\npub release_feed: Option<String>,\n- /// A json payload to be merged into the existing settings\n+ /// A json payload to be merged into the existing settings, this payload is checked\n+ /// not to include a variety of things that might break the router but is still not\n+ /// risk free for example the url fields require http:// or https:// or the router will\n+ /// crash even though the value will be accepted as a valid string\npub merge_json: serde_json::Value,\n}\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Improve operator update doc comments |
20,244 | 18.04.2020 08:37:31 | 14,400 | 9d3c8b2e2f48dcba618738e53ebbbf39a1a26c82 | Rename OperatorUpdate 'client' to 'relay'
This will require some code changes in other places, but it's the
last chance I'll get to fix this naming mistake probably for years | [
{
"change_type": "MODIFY",
"old_path": "althea_types/src/interop.rs",
"new_path": "althea_types/src/interop.rs",
"diff": "@@ -365,9 +365,13 @@ impl FromStr for ReleaseStatus {\n/// Operator update that we get from the operator server during our checkin\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct OperatorUpdateMessage {\n- /// This really should be 'relay' as it is the price that a normal\n- /// 'client' changes other clients for bandwdith (aka the default relay price)\n- pub client: u32,\n+ /// The default relay price, which is the price that a normal client in the network\n+ /// will charge other clients to forward bandwidth. Remember that everyone has a\n+ /// relay price even if they have no one to sell to. Also remember that unless\n+ /// forbidden with 'force_operator_price' this value can be changed by the user\n+ /// see the situation described in the max bandwidth setting for what might happen\n+ /// if the user sets an insane price.\n+ pub relay: u32,\n/// The default 'gateway' price, this comes with a few caveats mainly that gateway\n/// auto detection is based around having a wan port and is not always accurate but\n/// generally gateways will always be detected as gateways and relays may sometimes\n@@ -375,7 +379,10 @@ pub struct OperatorUpdateMessage {\n/// is not being used\npub gateway: u32,\n/// The maximum price any given router will pay in bandwidth, above this price the routers\n- /// will only pay their peer the max price\n+ /// will only pay their peer the max price, this can cause situations where routers disagree\n+ /// about how much they have been paid and start enforcing. Remember this must be less than\n+ /// the relay price + gateway price + exit price of the deepest user in the network in terms\n+ /// of hops to prevent this from happening in 'intended' scenarios.\npub max: u32,\n/// This is the pro-rated fee paid to the operator, defined as wei/second\npub operator_fee: u128,\n"
},
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_client/operator_update/mod.rs",
"new_path": "rita/src/rita_client/operator_update/mod.rs",
"diff": "@@ -129,7 +129,7 @@ fn checkin() {\nif is_gateway {\npayment.local_fee = new_settings.gateway;\n} else {\n- payment.local_fee = new_settings.client;\n+ payment.local_fee = new_settings.relay;\n}\n} else {\ninfo!(\"User has disabled the OperatorUpdate!\");\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Rename OperatorUpdate 'client' to 'relay'
This will require some code changes in other places, but it's the
last chance I'll get to fix this naming mistake probably for years |
20,244 | 18.04.2020 15:18:57 | 14,400 | 37467aae503440ecd7b4a92dc601b2546cf4f83a | Note how long it takes enforcement to gather data
This is taking quite a bit of time in prod, probably because it re-runs tc
all the time but I want to be sure I'm barking up the right tree | [
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_exit/database/mod.rs",
"new_path": "rita/src/rita_exit/database/mod.rs",
"diff": "@@ -493,6 +493,11 @@ pub fn enforce_exit_clients(clients_list: Vec<exit_db::models::Client>) -> Resul\n}\n}\nlet list = get_debts_list_sync();\n+ info!(\n+ \"Exit enforcement finished grabbing data in {}s {}ms\",\n+ start.elapsed().as_secs(),\n+ start.elapsed().subsec_millis(),\n+ );\nfor debt_entry in list.iter() {\nmatch clients_by_id.get(&debt_entry.identity) {\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Note how long it takes enforcement to gather data
This is taking quite a bit of time in prod, probably because it re-runs tc
all the time but I want to be sure I'm barking up the right tree |
20,244 | 18.04.2020 16:04:08 | 14,400 | 5e9b0de35695fdb5ba622b82334937f6da5ef14f | Delta based exit enforcement
Right now we run hundreds of tc commands per loop in order to handle
enforcement. This is by far the longest time in the exit loop. Here we
implement the same delta strategy as the wg_exit tunnel to avoid setting
things up when we don't have to. | [
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_common/debt_keeper/mod.rs",
"new_path": "rita/src/rita_common/debt_keeper/mod.rs",
"diff": "@@ -303,7 +303,7 @@ impl Message for SendUpdate {\n/// Actions to be taken upon a neighbor's debt reaching either a negative or positive\n/// threshold.\n-#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]\n+#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Hash, Eq)]\npub enum DebtAction {\nSuspendTunnel,\nOpenTunnel,\n"
},
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_exit/database/mod.rs",
"new_path": "rita/src/rita_exit/database/mod.rs",
"diff": "@@ -35,6 +35,7 @@ use crate::EXIT_VERIF_SETTINGS;\nuse crate::KI;\nuse crate::SETTING;\nuse althea_kernel_interface::ExitClient;\n+use althea_types::Identity;\nuse althea_types::{ExitClientDetails, ExitClientIdentity, ExitDetails, ExitState, ExitVerifMode};\nuse diesel;\nuse diesel::prelude::PgConnection;\n@@ -482,7 +483,10 @@ pub fn setup_clients(\n/// setting the htb class they are assigned to to a maximum speed of the free tier value.\n/// Unlike intermediary enforcement we do not need to subdivide the free tier to prevent\n/// ourselves from exceeding the upstream free tier. As an exit we are the upstream.\n-pub fn enforce_exit_clients(clients_list: Vec<exit_db::models::Client>) -> Result<(), Error> {\n+pub fn enforce_exit_clients(\n+ clients_list: Vec<exit_db::models::Client>,\n+ old_debt_actions: &HashSet<(Identity, DebtAction)>,\n+) -> Result<HashSet<(Identity, DebtAction)>, Error> {\nlet start = Instant::now();\nlet mut clients_by_id = HashMap::new();\nlet free_tier_limit = SETTING.get_payment().free_tier_throughput;\n@@ -499,6 +503,23 @@ pub fn enforce_exit_clients(clients_list: Vec<exit_db::models::Client>) -> Resul\nstart.elapsed().subsec_millis(),\n);\n+ // build the new debt actions list and see if we need to do anything\n+ let mut new_debt_actions = HashSet::new();\n+ for debt_entry in list.iter() {\n+ new_debt_actions.insert((\n+ debt_entry.identity,\n+ debt_entry.payment_details.action.clone(),\n+ ));\n+ }\n+ if new_debt_actions\n+ .symmetric_difference(old_debt_actions)\n+ .count()\n+ == 0\n+ {\n+ info!(\"No change in enforcement list found, skipping tc calls\");\n+ return Ok(new_debt_actions);\n+ }\n+\nfor debt_entry in list.iter() {\nmatch clients_by_id.get(&debt_entry.identity) {\nSome(client) => {\n@@ -553,5 +574,5 @@ pub fn enforce_exit_clients(clients_list: Vec<exit_db::models::Client>) -> Resul\nerror!(\"{}\", fail_mesg);\npanic!(\"{}\", fail_mesg);\n}\n- Ok(())\n+ Ok(new_debt_actions)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_exit/rita_loop/mod.rs",
"new_path": "rita/src/rita_exit/rita_loop/mod.rs",
"diff": "//! actix work together on this on properly, not that I've every seen simple actors like the loop crash\n//! very often.\n+use crate::rita_common::debt_keeper::DebtAction;\nuse crate::rita_exit::database::database_tools::get_database_connection;\nuse crate::rita_exit::database::struct_tools::clients_to_ids;\nuse crate::rita_exit::database::{\n@@ -75,12 +76,14 @@ pub fn start_rita_exit_loop() {\nlet tw = system_ref.registry().get();\n// a cache of what tunnels we had setup last round, used to prevent extra setup ops\nlet mut wg_clients: HashSet<ExitClient> = HashSet::new();\n+ // a list of client debts from the last round, to prevent extra enforcement ops\n+ let mut debt_actions: HashSet<(Identity, DebtAction)> = HashSet::new();\n// wait until the system gets started\nwhile !tw.connected() {\ntrace!(\"Waiting for actors to start\");\n}\nloop {\n- rita_exit_loop(tw.clone(), &mut wg_clients)\n+ rita_exit_loop(tw.clone(), &mut wg_clients, &mut debt_actions)\n}\n})\n.join()\n@@ -90,7 +93,11 @@ pub fn start_rita_exit_loop() {\n});\n}\n-fn rita_exit_loop(tw: Addr<TrafficWatcher>, wg_clients: &mut HashSet<ExitClient>) {\n+fn rita_exit_loop(\n+ tw: Addr<TrafficWatcher>,\n+ wg_clients: &mut HashSet<ExitClient>,\n+ debt_actions: &mut HashSet<(Identity, DebtAction)>,\n+) {\nlet start = Instant::now();\n// opening a database connection takes at least several milliseconds, as the database server\n// may be across the country, so to save on back and forth we open on and reuse it as much\n@@ -130,7 +137,12 @@ fn rita_exit_loop(tw: Addr<TrafficWatcher>, wg_clients: &mut HashSet<ExitClient>\ncheck_regions(start, clients_list.clone());\ninfo!(\"About to enforce exit clients\");\n- enforce(start, clients_list);\n+ // handle enforcement on client tunnels by querying debt keeper\n+ // this consumes client list\n+ match enforce_exit_clients(clients_list, debt_actions) {\n+ Ok(new_debt_actions) => *debt_actions = new_debt_actions,\n+ Err(e) => warn!(\"Failed to enforce exit clients with {:?}\", e,),\n+ }\ninfo!(\n\"Completed Rita exit loop in {}ms, all vars should be dropped\",\n@@ -205,22 +217,6 @@ fn check_regions(start: Instant, clients_list: Vec<models::Client>) {\n}\n}\n-fn enforce(start: Instant, clients_list: Vec<models::Client>) {\n- // handle enforcement on client tunnels by querying debt keeper\n- // this consumes client list\n- match enforce_exit_clients(clients_list) {\n- Err(e) => warn!(\n- \"Failed to enforce exit clients with {:?} {}ms since start\",\n- e,\n- start.elapsed().as_millis()\n- ),\n- Ok(_) => info!(\n- \"exit client enforcement completed successfully {}ms since loop start\",\n- start.elapsed().as_millis()\n- ),\n- }\n-}\n-\nfn setup_exit_wg_tunnel() {\nif let Err(e) = KI.setup_wg_if_named(\"wg_exit\") {\nwarn!(\"exit setup returned {}\", e)\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Delta based exit enforcement
Right now we run hundreds of tc commands per loop in order to handle
enforcement. This is by far the longest time in the exit loop. Here we
implement the same delta strategy as the wg_exit tunnel to avoid setting
things up when we don't have to. |
20,244 | 19.04.2020 07:23:41 | 14,400 | f6d7a3addc3fd3e8259cb539dc8dd88b9f032759 | Refer to exit clients with wg keys | [
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_exit/database/mod.rs",
"new_path": "rita/src/rita_exit/database/mod.rs",
"diff": "@@ -379,13 +379,13 @@ pub fn cleanup_exit_clients(\nif client.last_seen == 0 {\ninfo!(\n\"{} does not have a last seen timestamp, adding one now \",\n- client.mesh_ip\n+ client.wg_pubkey\n);\nlet res = set_client_timestamp(client_id, conn);\nif res.is_err() {\nwarn!(\n- \"Unable to update the client timestamp for {:?} with {:?}\",\n- client, res\n+ \"Unable to update the client timestamp for {} with {:?}\",\n+ client.wg_pubkey, res\n);\n}\n}\n@@ -393,7 +393,7 @@ pub fn cleanup_exit_clients(\nelse if entry_timeout != 0 && time_delta > entry_timeout {\nwarn!(\n\"{} has been inactive for too long, deleting! \",\n- client.mesh_ip\n+ client.wg_pubkey\n);\nlet res = delete_client(client_id, conn);\nif res.is_err() {\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Refer to exit clients with wg keys |
20,244 | 19.04.2020 10:24:21 | 14,400 | e87497400cecebd1ed400f0c139e7fc8c055a071 | Add operator action
A basic struct for performing things an operator may like to do | [
{
"change_type": "MODIFY",
"old_path": "althea_types/src/interop.rs",
"new_path": "althea_types/src/interop.rs",
"diff": "@@ -362,6 +362,13 @@ impl FromStr for ReleaseStatus {\n}\n}\n+/// Somthing the operator may want to do to a router under their control\n+#[derive(Debug, Clone, Copy, Serialize, Deserialize, Hash, Eq, PartialEq)]\n+pub enum OperatorAction {\n+ ResetRouterPassword,\n+ ResetWiFiPassword,\n+}\n+\n/// Operator update that we get from the operator server during our checkin\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct OperatorUpdateMessage {\n@@ -403,6 +410,9 @@ pub struct OperatorUpdateMessage {\n/// risk free for example the url fields require http:// or https:// or the router will\n/// crash even though the value will be accepted as a valid string\npub merge_json: serde_json::Value,\n+ /// An action the operator wants to take to affect this router, examples may include reset\n+ /// password or change the wifi ssid\n+ pub operator_action: Option<OperatorAction>,\n}\n/// The message we send to the operator server to checkin\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Add operator action
A basic struct for performing things an operator may like to do |
20,244 | 19.04.2020 10:33:15 | 14,400 | 704a366514962bd9b414c62064d76a3ea0c5f93c | Sperate prices for light clients | [
{
"change_type": "MODIFY",
"old_path": "althea_types/src/interop.rs",
"new_path": "althea_types/src/interop.rs",
"diff": "@@ -378,13 +378,23 @@ pub struct OperatorUpdateMessage {\n/// forbidden with 'force_operator_price' this value can be changed by the user\n/// see the situation described in the max bandwidth setting for what might happen\n/// if the user sets an insane price.\n+ /// This field is denominated in wei/byte and is a u32 to reflect the maximum resolution\n+ /// of the price field we have set in babel.\npub relay: u32,\n/// The default 'gateway' price, this comes with a few caveats mainly that gateway\n/// auto detection is based around having a wan port and is not always accurate but\n/// generally gateways will always be detected as gateways and relays may sometimes\n/// declare themselves gateways if the user toggled in a WAN port even if that WAN port\n/// is not being used\n+ /// This field is denominated in wei/byte and is a u32 to reflect the maximum resolution\n+ /// of the price field we have set in babel.\npub gateway: u32,\n+ /// The price specifically charged to phone clients, above and beyond the price to reach\n+ /// the exit. For example if this value was 5c and the cost for the selling node to reach\n+ /// the exit was 10c the price presented to the phone client would be 15c. This field is also\n+ /// denominated in wei/byte but is not subject to same size restrictions and could in theory\n+ /// be a u64 or even a u128\n+ pub phone_relay: u32,\n/// The maximum price any given router will pay in bandwidth, above this price the routers\n/// will only pay their peer the max price, this can cause situations where routers disagree\n/// about how much they have been paid and start enforcing. Remember this must be less than\n"
},
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_client/light_client_manager/mod.rs",
"new_path": "rita/src/rita_client/light_client_manager/mod.rs",
"diff": "@@ -338,7 +338,7 @@ impl Handler<Watch> for LightClientManager {\nfn handle(&mut self, msg: Watch, _: &mut Context<Self>) -> Self::Result {\ntrace!(\"Starting light client traffic watcher\");\n- let our_price = SETTING.get_payment().local_fee as u128 + msg.exit_dest_price;\n+ let our_price = SETTING.get_payment().light_client_fee as u128 + msg.exit_dest_price;\nlet tunnels = msg.tunnels;\nlet mut debts: HashMap<Identity, i128> = HashMap::new();\nfor tunnel in tunnels.iter() {\n"
},
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_client/operator_update/mod.rs",
"new_path": "rita/src/rita_client/operator_update/mod.rs",
"diff": "@@ -131,6 +131,7 @@ fn checkin() {\n} else {\npayment.local_fee = new_settings.relay;\n}\n+ payment.light_client_fee = new_settings.phone_relay;\n} else {\ninfo!(\"User has disabled the OperatorUpdate!\");\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "settings/src/payment.rs",
"new_path": "settings/src/payment.rs",
"diff": "@@ -130,9 +130,13 @@ pub struct TokenBridgeAddresses {\n/// debt keeper\n#[derive(Debug, Serialize, Deserialize, Clone, Eq, PartialEq)]\npub struct PaymentSettings {\n- /// What we charge other nodes\n+ /// What we charge other nodes, denominated in wei/byte, represented by a u32 because that is\n+ /// the field size of the price field in Babel\n#[serde(default = \"default_local_fee\")]\npub local_fee: u32,\n+ /// What we charge light client (phone) nodes specifically, denominated in wei/byte\n+ #[serde(default = \"default_local_fee\")]\n+ pub light_client_fee: u32,\n/// A price limit, we will not pay more than this\n#[serde(default = \"default_max_fee\")]\npub max_fee: u32,\n@@ -232,6 +236,7 @@ impl Default for PaymentSettings {\nfn default() -> Self {\nPaymentSettings {\nlocal_fee: default_local_fee(),\n+ light_client_fee: default_local_fee(),\nmax_fee: default_max_fee(),\ndynamic_fee_multiplier: default_dynamic_fee_multiplier(),\nfree_tier_throughput: default_free_tier_throughput(),\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Sperate prices for light clients |
20,244 | 19.04.2020 11:47:38 | 14,400 | 65f272212d7a45ca4a2f5c988394d44d34d7c317 | Improve exit fast fail message | [
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_exit/rita_loop/mod.rs",
"new_path": "rita/src/rita_exit/rita_loop/mod.rs",
"diff": "@@ -168,9 +168,14 @@ fn rita_exit_loop(\nErr(e) => {\nerror!(\"Failed to get database connection with {}\", e);\nif !*successful_setup {\n- error!(\"Failed to get connection on first setup loop, exiting to allow failover\");\n+ let db_uri = SETTING.get_db_uri();\n+ let message = format!(\n+ \"Failed to get database connection to {} on first setup loop, the exit can not operate without the ability to get the clients list from the database exiting\",\n+ db_uri\n+ );\n+ error!(\"{}\", message);\nsystem.stop();\n- panic!(\"Failed to get connection on first setup loop, exiting to allow failover\");\n+ panic!(message);\n}\n}\n}\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Improve exit fast fail message |
20,244 | 19.04.2020 13:00:32 | 14,400 | 4983907b413f96d5fa733560088bfba145a85aa4 | Skip mesh interface for forwarding
there can't be any antennas there anyways | [
{
"change_type": "MODIFY",
"old_path": "antenna_forwarding_client/src/lib.rs",
"new_path": "antenna_forwarding_client/src/lib.rs",
"diff": "@@ -274,6 +274,10 @@ fn find_antenna<S: ::std::hash::BuildHasher>(\ncheck_blacklist(ip)?;\nlet our_ip = get_local_ip(ip)?;\nfor iface in interfaces {\n+ if iface == \"mesh\" {\n+ trace!(\"Skipping mesh interface\");\n+ continue;\n+ }\ntrace!(\"Trying interface {}, with test ip {}\", iface, our_ip);\n// this acts as a wildcard deletion across all interfaces, which is frankly really\n// dangerous if our default route overlaps, of if you enter an exit route ip\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Skip mesh interface for forwarding
there can't be any antennas there anyways |
20,244 | 19.04.2020 13:01:11 | 14,400 | ae3a2c9b44d741453853e0f200f38a39fcdea660 | Fix no available connection error message | [
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_exit/database/database_tools.rs",
"new_path": "rita/src/rita_exit/database/database_tools.rs",
"diff": "@@ -324,7 +324,7 @@ pub fn get_database_connection(\ndyn Future<Item = PooledConnection<ConnectionManager<PgConnection>>, Error = Error>,\n>,\nNone => {\n- error!(\"No available db connection sleeping!\");\n+ error!(\"No available db connection!\");\nBox::new(future::err(format_err!(\n\"No Database connection available!\"\n)))\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Fix no available connection error message |
20,244 | 19.04.2020 15:02:15 | 14,400 | fe5d3d0239e75211b19f35a0cabc6b4ae247f24f | Harden forwarding
There where still a number of expecs and unwraps that needed to be
removed here. | [
{
"change_type": "MODIFY",
"old_path": "antenna_forwarding_client/src/lib.rs",
"new_path": "antenna_forwarding_client/src/lib.rs",
"diff": "@@ -159,11 +159,12 @@ fn process_messages(\ntrace!(\"Got close message for stream {}\", stream_id);\n*last_message = Instant::now();\nlet stream_id = stream_id;\n- let stream = streams\n- .get(stream_id)\n- .expect(\"How can we close a stream we don't have?\");\n+ if let Some(stream) = streams.get(stream_id) {\nlet _res = stream.shutdown(Shutdown::Both);\nstreams.remove(stream_id);\n+ } else {\n+ error!(\"Tried to remove stream {} that we did not have\", stream_id);\n+ }\n}\nForwardingProtocolMessage::ConnectionDataMessage { stream_id, payload } => {\ntrace!(\n@@ -174,29 +175,35 @@ fn process_messages(\n*last_message = Instant::now();\nlet stream_id = stream_id;\nif let Some(mut antenna_stream) = streams.get_mut(stream_id) {\n- write_all_spinlock(&mut antenna_stream, &payload)\n- .expect(\"Failed to talk to antenna!\");\n+ if let Err(e) = write_all_spinlock(&mut antenna_stream, &payload) {\n+ error!(\n+ \"Failed to write to antenna stream id {} with {:?}\",\n+ stream_id, e\n+ );\n+ }\n} else {\ntrace!(\"Opening stream for {}\", stream_id);\n// we don't have a stream, we need to dial out to the server now\n- let mut new_stream =\n- TcpStream::connect(antenna_sockaddr).expect(\"Could not contact antenna!\");\n- write_all_spinlock(&mut new_stream, &payload)\n- .expect(\"Failed to talk to antenna!\");\n+ if let Ok(mut new_stream) = TcpStream::connect(antenna_sockaddr) {\n+ match write_all_spinlock(&mut new_stream, &payload) {\n+ Ok(_) => {\nstreams.insert(*stream_id, new_stream);\n}\n+ Err(e) => error!(\n+ \"Failed to write to anntenna stream id {} with {:?}\",\n+ stream_id, e\n+ ),\n+ }\n+ }\n+ }\n}\nForwardingProtocolMessage::ForwardingCloseMessage => {\ntrace!(\"Got halt message\");\n// we have a close lets get out of here.\nfor stream in streams.values_mut() {\n- stream\n- .shutdown(Shutdown::Both)\n- .expect(\"Failed to shutdown connection!\");\n+ let _ = stream.shutdown(Shutdown::Both);\n}\n- server_stream\n- .shutdown(Shutdown::Both)\n- .expect(\"Could not shutdown connection!\");\n+ let _ = server_stream.shutdown(Shutdown::Both);\nreturn true;\n}\n// we don't use this yet\n"
},
{
"change_type": "MODIFY",
"old_path": "antenna_forwarding_protocol/src/lib.rs",
"new_path": "antenna_forwarding_protocol/src/lib.rs",
"diff": "@@ -104,16 +104,18 @@ pub fn process_streams<S: ::std::hash::BuildHasher>(\n);\nlet msg =\nForwardingProtocolMessage::new_connection_data_message(*stream_id, bytes);\n- write_all_spinlock(server_stream, &msg.get_message())\n- .unwrap_or_else(|_| panic!(\"Failed to write with stream {}\", *stream_id));\n+ if let Err(e) = write_all_spinlock(server_stream, &msg.get_message()) {\n+ error!(\"Failed to write with stream {} with {:?}\", *stream_id, e);\n+ }\n}\n}\nErr(e) => {\nif e.kind() != WouldBlock {\nerror!(\"Closing antenna/client connection with {:?}\", e);\nlet msg = ForwardingProtocolMessage::new_connection_close_message(*stream_id);\n- write_all_spinlock(server_stream, &msg.get_message())\n- .unwrap_or_else(|_| panic!(\"Failed to close stream {}\", *stream_id));\n+ if let Err(e) = write_all_spinlock(server_stream, &msg.get_message()) {\n+ error!(\"Failed to close stream {} with {:?}\", *stream_id, e);\n+ }\nlet _ = antenna_stream.shutdown(Shutdown::Write);\nstreams_to_remove.push(*stream_id);\n}\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Harden forwarding
There where still a number of expecs and unwraps that needed to be
removed here. |
20,244 | 20.04.2020 07:24:49 | 14,400 | 9204cf44fb94d3ac4c7eb6c62f35b982ffc7849b | Fix wait timeout to actually timeout
did not do so before | [
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_exit/rita_loop/wait_timeout.rs",
"new_path": "rita/src/rita_exit/rita_loop/wait_timeout.rs",
"diff": "@@ -18,13 +18,13 @@ pub enum WaitResult<F: Future> {\n}\npub fn wait_timeout<F: Future>(f: F, dur: Duration) -> WaitResult<F> {\n- let now = Instant::now();\n+ let start = Instant::now();\nlet mut task = executor::spawn(f);\nlet thread = Arc::new(ThreadNotify::new(thread::current()));\nloop {\nlet cur = Instant::now();\n- if cur >= now + dur {\n+ if cur >= (start + dur) {\nreturn WaitResult::TimedOut(task);\n}\nmatch task.poll_future_notify(&thread, 0) {\n@@ -33,7 +33,7 @@ pub fn wait_timeout<F: Future>(f: F, dur: Duration) -> WaitResult<F> {\nErr(e) => return WaitResult::Err(e),\n}\n- thread.park(now + dur - cur);\n+ thread.park(dur);\n}\nstruct ThreadNotify {\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Fix wait timeout to actually timeout
did not do so before |
20,244 | 20.04.2020 08:23:28 | 14,400 | 6c3abfdafa91bfbb531509df15c5ac4faa1595eb | Fix heartbeat url for Beta 12 routers | [
{
"change_type": "MODIFY",
"old_path": "rita/src/client.rs",
"new_path": "rita/src/client.rs",
"diff": "@@ -191,7 +191,7 @@ fn wait_for_settings(settings_file: &str) -> RitaSettingsStruct {\n}\nfn main() {\n- // Remove in Beta 13, migrates settings from the old dao structure to\n+ // Remove in Beta 14, migrates settings from the old dao structure to\n// the operator structure in settings.\n{\nlet dao = { SETTING.get_dao().clone() };\n@@ -210,6 +210,12 @@ fn main() {\noperator.use_operator_price = dao.use_oracle_price;\n}\n}\n+ // some devices are on beta 12 and therefore have the old default heartbeat\n+ // url which is not correct in beta 13, remove this in beta 14\n+ {\n+ let mut log = SETTING.get_log_mut();\n+ log.heartbeat_url = \"operator.althea.net:33333\".to_string();\n+ }\n// On Linux static builds we need to probe ssl certs path to be able to\n// do TLS stuff.\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Fix heartbeat url for Beta 12 routers |
20,244 | 20.04.2020 09:43:57 | 14,400 | 915badb4e341049cc5925b453121ebaae0ea7c62 | We need to parse the checkin address every round
Otherwise DNS resolution may fail the first time and block us forever.
not to mention changing the underlying ip that points to would require
a reboot if we updated the dns entry. | [
{
"change_type": "MODIFY",
"old_path": "antenna_forwarding_client/src/lib.rs",
"new_path": "antenna_forwarding_client/src/lib.rs",
"diff": "@@ -56,6 +56,10 @@ pub fn start_antenna_forwarding_proxy<S: 'static + std::marker::Send + ::std::ha\ninterfaces_to_search: HashSet<String, S>,\n) {\ninfo!(\"Starting antenna forwarding proxy!\");\n+ thread::spawn(move || loop {\n+ trace!(\"About to checkin with {}\", checkin_address);\n+ // parse checkin address every loop iteration as a way\n+ // of resolving the domain name on each run\nlet socket: SocketAddr = match checkin_address.to_socket_addrs() {\nOk(mut res) => match res.next() {\nSome(socket) => socket,\n@@ -69,11 +73,6 @@ pub fn start_antenna_forwarding_proxy<S: 'static + std::marker::Send + ::std::ha\nreturn;\n}\n};\n-\n- thread::spawn(move || loop {\n- // parse checkin address every loop iteration as a way\n- // of resolving the domain name on each run\n- trace!(\"About to checkin with {}\", checkin_address);\nif let Ok(mut server_stream) = TcpStream::connect_timeout(&socket, NET_TIMEOUT) {\ntrace!(\"connected to {}\", checkin_address);\n// send our identifier\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | We need to parse the checkin address every round
Otherwise DNS resolution may fail the first time and block us forever.
not to mention changing the underlying ip that points to would require
a reboot if we updated the dns entry. |
20,244 | 20.04.2020 09:58:07 | 14,400 | 2024f1df1a52a727af52e6ffb8b4c788fe134dc1 | Better log babel heartbeat issues | [
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_client/heartbeat/mod.rs",
"new_path": "rita/src/rita_client/heartbeat/mod.rs",
"diff": "@@ -40,6 +40,7 @@ lazy_static! {\n}\npub fn send_udp_heartbeat() {\n+ trace!(\"attempting to send heartbeat\");\nlet dns_request = Resolver::from_registry()\n.send(resolver::Resolve::host(\nSETTING.get_log().heartbeat_url.clone(),\n@@ -59,19 +60,23 @@ pub fn send_udp_heartbeat() {\n} else {\nreturn;\n};\n+ trace!(\"we have heartbeat basic info\");\nlet res = dns_request.join(network_info).then(move |res| match res {\nOk((Ok(dnsresult), Ok(network_info))) => {\nif dnsresult.is_empty() {\ntrace!(\"Got zero length dns response: {:?}\", dnsresult);\n}\n+ trace!(\"we have heartbeat dns\");\n- if let Ok(route) = get_selected_exit_route(&network_info.babel_routes) {\n+ match get_selected_exit_route(&network_info.babel_routes) {\n+ Ok(route) => {\nlet neigh_option = get_neigh_given_route(&route, &network_info.babel_neighbors);\nlet neigh_option =\nget_rita_neigh_option(neigh_option, &network_info.rita_neighbors);\nif let Some((neigh, rita_neigh)) = neigh_option {\nfor dns_socket in dnsresult {\n+ trace!(\"sending heartbeat\");\nsend_udp_heartbeat_packet(\ndns_socket,\nour_id,\n@@ -81,7 +86,11 @@ pub fn send_udp_heartbeat() {\nrita_neigh.identity.global,\n);\n}\n+ } else {\n+ warn!(\"Failed to find neigh for heartbeat!\");\n+ }\n}\n+ Err(e) => warn!(\"Failed to geat heartbeat route with {:?}\", e),\n}\nOk(())\n}\n@@ -152,6 +161,7 @@ fn send_udp_heartbeat_packet(\nexit_neighbor: Neighbor,\nexit_neighbor_id: Identity,\n) {\n+ trace!(\"building heartbeat packet\");\nlet network_settings = SETTING.get_network();\nlet reg_details = SETTING.get_exit_client().reg_details.clone();\nlet low_balance_notification = SETTING.get_exit_client().low_balance_notification;\n@@ -219,7 +229,7 @@ fn send_udp_heartbeat_packet(\n}\nmatch local_socket.send_to(&packet_contents, &remote) {\n- Ok(bytes) => trace!(\"Sent {} heartbeat bytes\", bytes),\n+ Ok(bytes) => info!(\"Sent {} heartbeat bytes\", bytes),\nErr(e) => error!(\"Failed to send heartbeat with {:?}\", e),\n}\n}\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Better log babel heartbeat issues |
20,244 | 20.04.2020 10:29:47 | 14,400 | f11be5f1b96c4f737279b00723dedd9f12285de0 | Beta 13 RC3
* Waits longer for Babel in some cases where that's required
* Better logging for heartbeat failures
* Resolves the heartbeat address more reliably
* Ensures that Beta 12 routers have the right heartbeat address during
upgrades | [
{
"change_type": "MODIFY",
"old_path": "Cargo.lock",
"new_path": "Cargo.lock",
"diff": "@@ -2629,7 +2629,7 @@ dependencies = [\n[[package]]\nname = \"rita\"\n-version = \"0.5.40\"\n+version = \"0.5.42\"\ndependencies = [\n\"actix\",\n\"actix-web\",\n"
},
{
"change_type": "MODIFY",
"old_path": "rita/Cargo.toml",
"new_path": "rita/Cargo.toml",
"diff": "[package]\nname = \"rita\"\n-version = \"0.5.40\"\n+version = \"0.5.42\"\nauthors = [\"Jehan <jehan.tremback@gmail.com>\", \"Ben <wangben3@gmail.com>\"]\nbuild = \"build.rs\"\nedition = \"2018\"\n"
},
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_common/dashboard/own_info.rs",
"new_path": "rita/src/rita_common/dashboard/own_info.rs",
"diff": "@@ -6,7 +6,7 @@ use failure::Error;\nuse num256::{Int256, Uint256};\nuse settings::RitaCommonSettings;\n-pub static READABLE_VERSION: &str = \"Beta 13 RC1\";\n+pub static READABLE_VERSION: &str = \"Beta 13 RC3\";\n#[derive(Serialize)]\npub struct OwnInfo {\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Beta 13 RC3
* Waits longer for Babel in some cases where that's required
* Better logging for heartbeat failures
* Resolves the heartbeat address more reliably
* Ensures that Beta 12 routers have the right heartbeat address during
upgrades |
20,244 | 20.04.2020 10:33:17 | 14,400 | 835293c5272632c2d2249693c5a5b1af0e819d39 | Prevent heartbeat loop from exiting prematurely
We don't need to return here, instead we should continue, now that the
block has been moved down the context of the statement has changed | [
{
"change_type": "MODIFY",
"old_path": "antenna_forwarding_client/src/lib.rs",
"new_path": "antenna_forwarding_client/src/lib.rs",
"diff": "@@ -65,12 +65,12 @@ pub fn start_antenna_forwarding_proxy<S: 'static + std::marker::Send + ::std::ha\nSome(socket) => socket,\nNone => {\nerror!(\"Could not parse {}!\", checkin_address);\n- return;\n+ continue;\n}\n},\nErr(_) => {\nerror!(\"Could not parse {}!\", checkin_address);\n- return;\n+ continue;\n}\n};\nif let Ok(mut server_stream) = TcpStream::connect_timeout(&socket, NET_TIMEOUT) {\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Prevent heartbeat loop from exiting prematurely
We don't need to return here, instead we should continue, now that the
block has been moved down the context of the statement has changed |
20,244 | 20.04.2020 18:25:01 | 14,400 | 483e8a6da73b99db169cf16d61ca052c2066b618 | Better tracing for antenna forwarding | [
{
"change_type": "MODIFY",
"old_path": "antenna_forwarding_client/src/lib.rs",
"new_path": "antenna_forwarding_client/src/lib.rs",
"diff": "@@ -232,6 +232,9 @@ fn forward_connections(\n);\nwhile let Ok(vec) = ForwardingProtocolMessage::read_messages(&mut server_stream) {\n+ if !vec.is_empty() {\n+ trace!(\"In forwarding loop! got {} messages\", vec.len());\n+ }\nprocess_streams(&mut streams, &mut server_stream);\nlet should_shutdown = process_messages(\n&vec,\n"
},
{
"change_type": "MODIFY",
"old_path": "antenna_forwarding_protocol/src/lib.rs",
"new_path": "antenna_forwarding_protocol/src/lib.rs",
"diff": "@@ -49,9 +49,14 @@ pub fn write_all_spinlock(stream: &mut TcpStream, buffer: &[u8]) -> Result<(), I\nloop {\nlet res = stream.write_all(buffer);\nmatch res {\n- Ok(_val) => return Ok(()),\n+ Ok(_val) => {\n+ trace!(\"Spinlock wrote {} bytes\", buffer.len());\n+ return Ok(());\n+ }\nErr(e) => {\n+ error!(\"Problem in spinlock writing {} bytes\", buffer.len());\nif e.kind() != WouldBlock {\n+ error!(\"Socket write error is {:?}\", e);\nreturn Err(e);\n}\n}\n@@ -537,22 +542,48 @@ impl ForwardingProtocolMessage {\nremaining_bytes.extend_from_slice(&read_till_block(input)?);\n- if let Ok((bytes, msg)) = ForwardingProtocolMessage::read_message(&remaining_bytes) {\n+ match ForwardingProtocolMessage::read_message(&remaining_bytes) {\n+ Ok((bytes, msg)) => {\nmessages.push(msg);\n+ let num_remaining_bytes = remaining_bytes.len() - bytes;\n+\nif bytes < remaining_bytes.len() {\n+ trace!(\n+ \"Got message {:?} recursing for remaining bytes {}\",\n+ messages,\n+ num_remaining_bytes\n+ );\nForwardingProtocolMessage::read_messages_internal(\ninput,\nremaining_bytes[bytes..].to_vec(),\nmessages,\n)\n} else {\n+ if num_remaining_bytes != 0 {\n+ error!(\n+ \"Got message {:?} but with {} bytes remaining {:?}\",\n+ messages,\n+ num_remaining_bytes,\n+ remaining_bytes[bytes..].to_vec()\n+ );\n+ }\nOk(messages)\n}\n- } else {\n+ }\n+ Err(e) => {\n+ if !remaining_bytes.is_empty() {\n+ error!(\n+ \"Unparsed bytes! {} {:?} {:?}\",\n+ remaining_bytes.len(),\n+ e,\n+ remaining_bytes.to_vec()\n+ );\n+ }\nOk(messages)\n}\n}\n}\n+}\n#[cfg(test)]\nmod tests {\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Better tracing for antenna forwarding |
20,244 | 20.04.2020 19:54:24 | 14,400 | 994efa9940f0555e9ccfbd461222eb2e00f6efda | Panic when there are bytes remaining
trying to track down a parsing issue
I think this is caused by us coming in to read a packet as it
is half written | [
{
"change_type": "MODIFY",
"old_path": "antenna_forwarding_protocol/src/lib.rs",
"new_path": "antenna_forwarding_protocol/src/lib.rs",
"diff": "@@ -536,6 +536,7 @@ impl ForwardingProtocolMessage {\nremaining_bytes: Vec<u8>,\nmessages: Vec<ForwardingProtocolMessage>,\n) -> Result<Vec<ForwardingProtocolMessage>, Error> {\n+ trace!(\"in read message\");\n// these should match the full list of message types defined above\nlet mut messages = messages;\nlet mut remaining_bytes = remaining_bytes;\n@@ -547,7 +548,7 @@ impl ForwardingProtocolMessage {\nmessages.push(msg);\nlet num_remaining_bytes = remaining_bytes.len() - bytes;\n- if bytes < remaining_bytes.len() {\n+ if num_remaining_bytes != 0 {\ntrace!(\n\"Got message {:?} recursing for remaining bytes {}\",\nmessages,\n@@ -559,31 +560,20 @@ impl ForwardingProtocolMessage {\nmessages,\n)\n} else {\n- if num_remaining_bytes != 0 {\n- error!(\n- \"Got message {:?} but with {} bytes remaining {:?}\",\n- messages,\n- num_remaining_bytes,\n- remaining_bytes[bytes..].to_vec()\n- );\n- }\nOk(messages)\n}\n}\nErr(e) => {\nif !remaining_bytes.is_empty() {\n- error!(\n- \"Unparsed bytes! {} {:?} {:?}\",\n- remaining_bytes.len(),\n- e,\n- remaining_bytes.to_vec()\n- );\n- }\n+ error!(\"Unparsed bytes! {} {:?}\", remaining_bytes.len(), e);\n+ panic!(\"bytes unparsed {:#x?}\", remaining_bytes);\n+ } else {\nOk(messages)\n}\n}\n}\n}\n+}\n#[cfg(test)]\nmod tests {\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Panic when there are bytes remaining
trying to track down a parsing issue
I think this is caused by us coming in to read a packet as it
is half written |
20,244 | 21.04.2020 10:05:30 | 14,400 | 4c2fd299822d9613aa8f3a452d9eb4a36b675783 | Add error type for forwarding protocol
This should help us identify when packets are half written and keep
trying to read them | [
{
"change_type": "MODIFY",
"old_path": "antenna_forwarding_protocol/src/lib.rs",
"new_path": "antenna_forwarding_protocol/src/lib.rs",
"diff": "@@ -18,11 +18,15 @@ extern crate lazy_static;\nuse althea_types::Identity;\nuse althea_types::WgKey;\n-use failure::Error;\n+use failure::Error as FailureError;\nuse sodiumoxide::crypto::box_;\nuse sodiumoxide::crypto::box_::Nonce;\nuse sodiumoxide::crypto::box_::NONCEBYTES;\nuse std::collections::HashMap;\n+use std::error::Error;\n+use std::fmt;\n+use std::fmt::Display;\n+use std::fmt::Formatter;\nuse std::io::Error as IoError;\nuse std::io::ErrorKind::WouldBlock;\nuse std::io::Read;\n@@ -42,6 +46,41 @@ pub const NET_TIMEOUT: Duration = Duration::from_secs(1);\n/// The size in bytes of our packet header, 16 byte magic, 2 byte type, 2 byte len\npub const HEADER_LEN: usize = 20;\n+#[derive(Clone, Serialize, Deserialize, Debug, Eq, PartialEq)]\n+pub enum ForwardingProtocolError {\n+ SliceTooSmall { expected: u16, actual: u16 },\n+ SerdeError { message: String },\n+ BadMagic,\n+ InvalidLen,\n+ WrongPacketType,\n+ UnknownPacketType,\n+ DecryptionFailed,\n+}\n+\n+impl Error for ForwardingProtocolError {\n+ fn source(&self) -> Option<&(dyn Error + 'static)> {\n+ None\n+ }\n+}\n+\n+impl Display for ForwardingProtocolError {\n+ fn fmt(&self, f: &mut Formatter) -> fmt::Result {\n+ match self {\n+ ForwardingProtocolError::SliceTooSmall { expected, actual } => write!(\n+ f,\n+ \"SliceTooSmall expected {} bytes, got {} bytes\",\n+ expected, actual\n+ ),\n+ ForwardingProtocolError::BadMagic => write!(f, \"BadMagic\"),\n+ ForwardingProtocolError::InvalidLen => write!(f, \"InvalidLen\"),\n+ ForwardingProtocolError::WrongPacketType => write!(f, \"WrongPacketType\"),\n+ ForwardingProtocolError::UnknownPacketType => write!(f, \"UnknownPacketType\"),\n+ ForwardingProtocolError::DecryptionFailed => write!(f, \"DecryptionFailed\"),\n+ ForwardingProtocolError::SerdeError { message } => write!(f, \"SerdeError {}\", message),\n+ }\n+ }\n+}\n+\n/// Writes data to a stream keeping in mind that we may encounter\n/// a buffer limit and have to partially complete our write\npub fn write_all_spinlock(stream: &mut TcpStream, buffer: &[u8]) -> Result<(), IoError> {\n@@ -254,7 +293,7 @@ impl ForwardingProtocolMessage {\n&self,\nserver_secretkey: WgKey,\nclient_publickey: WgKey,\n- ) -> Result<Vec<u8>, Error> {\n+ ) -> Result<Vec<u8>, ForwardingProtocolError> {\nif let ForwardingProtocolMessage::ForwardMessage { .. } = self {\nlet client_publickey = client_publickey.into();\nlet server_secretkey = server_secretkey.into();\n@@ -277,7 +316,7 @@ impl ForwardingProtocolMessage {\nmessage.extend_from_slice(&payload);\nOk(message)\n} else {\n- Err(format_err!(\"Invalid operation!\"))\n+ Err(ForwardingProtocolError::WrongPacketType)\n}\n}\n@@ -285,9 +324,9 @@ impl ForwardingProtocolMessage {\npayload: &[u8],\nserver_publickey: WgKey,\nclient_secretkey: WgKey,\n- ) -> Result<(usize, ForwardingProtocolMessage), Error> {\n+ ) -> Result<(usize, ForwardingProtocolMessage), ForwardingProtocolError> {\nif payload.len() < HEADER_LEN {\n- return Err(format_err!(\"Packet too short!\"));\n+ return Err(ForwardingProtocolError::InvalidLen);\n}\nlet mut packet_magic: [u8; 16] = [0; 16];\n@@ -304,15 +343,14 @@ impl ForwardingProtocolMessage {\n// this needs to be updated when new packet types are added\nif packet_magic != ForwardingProtocolMessage::MAGIC {\n- return Err(format_err!(\"Packet magic incorrect!\"));\n+ return Err(ForwardingProtocolError::BadMagic);\n} else if packet_type != ForwardingProtocolMessage::FORWARD_MESSAGE_TYPE {\n- return Err(format_err!(\"Wrong packet type!\"));\n+ return Err(ForwardingProtocolError::WrongPacketType);\n} else if packet_len as usize + HEADER_LEN > payload.len() {\n- return Err(format_err!(\n- \"Our slice is {} bytes, but our packet_len {} bytes\",\n- payload.len(),\n- packet_len as usize + HEADER_LEN\n- ));\n+ return Err(ForwardingProtocolError::SliceTooSmall {\n+ actual: payload.len() as u16,\n+ expected: { packet_len + HEADER_LEN as u16 },\n+ });\n}\n// nonce is 24 bytes\n@@ -327,9 +365,11 @@ impl ForwardingProtocolMessage {\nmatch box_::open(&ciphertext, &nonce, &pk, &sk) {\nOk(plaintext) => match serde_json::from_slice(&plaintext) {\nOk(forward_message) => Ok((end_bytes, forward_message)),\n- Err(e) => Err(e.into()),\n+ Err(e) => Err(ForwardingProtocolError::SerdeError {\n+ message: e.to_string(),\n+ }),\n},\n- Err(_) => Err(format_err!(\"Decryption failed!\")),\n+ Err(_) => Err(ForwardingProtocolError::DecryptionFailed),\n}\n}\n@@ -395,9 +435,11 @@ impl ForwardingProtocolMessage {\n}\n}\n- pub fn read_message(payload: &[u8]) -> Result<(usize, ForwardingProtocolMessage), Error> {\n+ pub fn read_message(\n+ payload: &[u8],\n+ ) -> Result<(usize, ForwardingProtocolMessage), ForwardingProtocolError> {\nif payload.len() < HEADER_LEN {\n- return Err(format_err!(\"Packet too short!\"));\n+ return Err(ForwardingProtocolError::InvalidLen);\n}\nlet mut packet_magic: [u8; 16] = [0; 16];\n@@ -414,15 +456,14 @@ impl ForwardingProtocolMessage {\n// this needs to be updated when new packet types are added\nif packet_magic != ForwardingProtocolMessage::MAGIC {\n- return Err(format_err!(\"Packet magic incorrect!\"));\n+ return Err(ForwardingProtocolError::BadMagic);\n} else if packet_type > 6 {\n- return Err(format_err!(\"Wrong packet type!\"));\n+ return Err(ForwardingProtocolError::WrongPacketType);\n} else if packet_len as usize + HEADER_LEN > payload.len() {\n- return Err(format_err!(\n- \"Our slice is {} bytes, but our packet_len {} bytes\",\n- payload.len(),\n- packet_len as usize + HEADER_LEN\n- ));\n+ return Err(ForwardingProtocolError::SliceTooSmall {\n+ actual: payload.len() as u16,\n+ expected: { packet_len + HEADER_LEN as u16 },\n+ });\n}\nmatch packet_type {\n@@ -431,24 +472,28 @@ impl ForwardingProtocolMessage {\nmatch serde_json::from_slice(&payload[HEADER_LEN..bytes_read]) {\nOk(message) => Ok((bytes_read, message)),\n- Err(serde_error) => Err(serde_error.into()),\n+ Err(serde_error) => Err(ForwardingProtocolError::SerdeError {\n+ message: serde_error.to_string(),\n+ }),\n}\n}\n// you can not read encrypted packets with this function\nForwardingProtocolMessage::FORWARD_MESSAGE_TYPE => {\n- Err(format_err!(\"Invalid packet type\"))\n+ Err(ForwardingProtocolError::WrongPacketType)\n}\nForwardingProtocolMessage::ERROR_MESSAGE_TYPE => {\nlet bytes_read = HEADER_LEN + packet_len as usize;\nmatch serde_json::from_slice(&payload[HEADER_LEN..bytes_read]) {\nOk(message) => Ok((bytes_read, message)),\n- Err(serde_error) => Err(serde_error.into()),\n+ Err(serde_error) => Err(ForwardingProtocolError::SerdeError {\n+ message: serde_error.to_string(),\n+ }),\n}\n}\nForwardingProtocolMessage::CONNECTION_CLOSE_MESSAGE_TYPE => {\nif packet_len != 8 {\n- return Err(format_err!(\"Incorrect length for close message\"));\n+ return Err(ForwardingProtocolError::InvalidLen);\n}\nlet mut connection_id: [u8; 8] = [0; 8];\n@@ -485,7 +530,9 @@ impl ForwardingProtocolMessage {\nmatch serde_json::from_slice(&payload[HEADER_LEN..bytes_read]) {\nOk(message) => Ok((bytes_read, message)),\n- Err(serde_error) => Err(serde_error.into()),\n+ Err(serde_error) => Err(ForwardingProtocolError::SerdeError {\n+ message: serde_error.to_string(),\n+ }),\n}\n}\nForwardingProtocolMessage::KEEPALIVE_MESSAGE_TYPE => {\n@@ -493,10 +540,12 @@ impl ForwardingProtocolMessage {\nmatch serde_json::from_slice(&payload[HEADER_LEN..bytes_read]) {\nOk(message) => Ok((bytes_read, message)),\n- Err(serde_error) => Err(serde_error.into()),\n+ Err(serde_error) => Err(ForwardingProtocolError::SerdeError {\n+ message: serde_error.to_string(),\n+ }),\n}\n}\n- _ => bail!(\"Unknown packet type!\"),\n+ _ => Err(ForwardingProtocolError::UnknownPacketType),\n}\n}\n@@ -506,7 +555,7 @@ impl ForwardingProtocolMessage {\ninput: &mut TcpStream,\nserver_publickey: WgKey,\nclient_secretkey: WgKey,\n- ) -> Result<Vec<ForwardingProtocolMessage>, Error> {\n+ ) -> Result<Vec<ForwardingProtocolMessage>, FailureError> {\nlet bytes = read_till_block(input)?;\nif let Ok((_bytes, ForwardingProtocolMessage::ForwardingCloseMessage)) =\nForwardingProtocolMessage::read_message(&bytes)\n@@ -527,7 +576,9 @@ impl ForwardingProtocolMessage {\n/// Reads all the currently available messages from the provided stream, this function will\n/// also block until a currently in flight message is delivered\n- pub fn read_messages(input: &mut TcpStream) -> Result<Vec<ForwardingProtocolMessage>, Error> {\n+ pub fn read_messages(\n+ input: &mut TcpStream,\n+ ) -> Result<Vec<ForwardingProtocolMessage>, FailureError> {\nForwardingProtocolMessage::read_messages_internal(input, Vec::new(), Vec::new())\n}\n@@ -535,7 +586,7 @@ impl ForwardingProtocolMessage {\ninput: &mut TcpStream,\nremaining_bytes: Vec<u8>,\nmessages: Vec<ForwardingProtocolMessage>,\n- ) -> Result<Vec<ForwardingProtocolMessage>, Error> {\n+ ) -> Result<Vec<ForwardingProtocolMessage>, FailureError> {\ntrace!(\"in read message\");\n// these should match the full list of message types defined above\nlet mut messages = messages;\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Add error type for forwarding protocol
This should help us identify when packets are half written and keep
trying to read them |
20,244 | 21.04.2020 10:12:15 | 14,400 | c116d457dfc52ccef5146b534f2d91e7d2b4be74 | Read partial packets
Slice size errors are caused when we read packets that aren't quite done
writing yet. This patch continues to read large packets until they finish
or until the read times out. | [
{
"change_type": "MODIFY",
"old_path": "antenna_forwarding_protocol/src/lib.rs",
"new_path": "antenna_forwarding_protocol/src/lib.rs",
"diff": "@@ -571,6 +571,7 @@ impl ForwardingProtocolMessage {\ninput,\nbytes[bytes_read..].to_vec(),\nvec![msg],\n+ 0,\n)\n}\n@@ -579,15 +580,21 @@ impl ForwardingProtocolMessage {\npub fn read_messages(\ninput: &mut TcpStream,\n) -> Result<Vec<ForwardingProtocolMessage>, FailureError> {\n- ForwardingProtocolMessage::read_messages_internal(input, Vec::new(), Vec::new())\n+ ForwardingProtocolMessage::read_messages_internal(input, Vec::new(), Vec::new(), 0)\n}\nfn read_messages_internal(\ninput: &mut TcpStream,\nremaining_bytes: Vec<u8>,\nmessages: Vec<ForwardingProtocolMessage>,\n+ depth: u8,\n) -> Result<Vec<ForwardingProtocolMessage>, FailureError> {\n- trace!(\"in read message\");\n+ if depth > 1 && depth <= 10 {\n+ thread::sleep(SPINLOCK_TIME);\n+ } else if depth > 10 {\n+ error!(\"Never found the end of the message\");\n+ bail!(\"Never found the end of the message\");\n+ }\n// these should match the full list of message types defined above\nlet mut messages = messages;\nlet mut remaining_bytes = remaining_bytes;\n@@ -601,27 +608,38 @@ impl ForwardingProtocolMessage {\nif num_remaining_bytes != 0 {\ntrace!(\n- \"Got message {:?} recursing for remaining bytes {}\",\n- messages,\n+ \"Got message recursing for remaining bytes {}\",\nnum_remaining_bytes\n);\nForwardingProtocolMessage::read_messages_internal(\ninput,\nremaining_bytes[bytes..].to_vec(),\nmessages,\n+ depth + 1,\n)\n} else {\nOk(messages)\n}\n}\n- Err(e) => {\n+ Err(e) => match e {\n+ ForwardingProtocolError::SliceTooSmall { expected, actual } => {\n+ error!(\"Expected {} bytes, got {} bytes\", expected, actual);\n+ ForwardingProtocolMessage::read_messages_internal(\n+ input,\n+ remaining_bytes,\n+ messages,\n+ depth + 1,\n+ )\n+ }\n+ _ => {\nif !remaining_bytes.is_empty() {\nerror!(\"Unparsed bytes! {} {:?}\", remaining_bytes.len(), e);\n- panic!(\"bytes unparsed {:#x?}\", remaining_bytes);\n+ bail!(\"Unparsed bytes!\");\n} else {\nOk(messages)\n}\n}\n+ },\n}\n}\n}\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Read partial packets
Slice size errors are caused when we read packets that aren't quite done
writing yet. This patch continues to read large packets until they finish
or until the read times out. |
20,244 | 21.04.2020 12:46:42 | 14,400 | cee8f8f5e56b6c20baa7731b790042c34869712c | Read partial packets for encrypted start messages
The same situation applies here with a few more edge cases. We may
get partially completed messages and need to recurse to finish them | [
{
"change_type": "MODIFY",
"old_path": "antenna_forwarding_protocol/src/lib.rs",
"new_path": "antenna_forwarding_protocol/src/lib.rs",
"diff": "@@ -556,17 +556,54 @@ impl ForwardingProtocolMessage {\nserver_publickey: WgKey,\nclient_secretkey: WgKey,\n) -> Result<Vec<ForwardingProtocolMessage>, FailureError> {\n- let bytes = read_till_block(input)?;\n- if let Ok((_bytes, ForwardingProtocolMessage::ForwardingCloseMessage)) =\n- ForwardingProtocolMessage::read_message(&bytes)\n- {\n- return Ok(vec![ForwardingProtocolMessage::ForwardingCloseMessage]);\n+ trace!(\"read messages start\");\n+ ForwardingProtocolMessage::read_messages_start_internal(\n+ input,\n+ server_publickey,\n+ client_secretkey,\n+ Vec::new(),\n+ 0,\n+ )\n}\n- let (bytes_read, msg) = ForwardingProtocolMessage::read_encrypted_forward_message(\n+\n+ fn read_messages_start_internal(\n+ input: &mut TcpStream,\n+ server_publickey: WgKey,\n+ client_secretkey: WgKey,\n+ bytes: Vec<u8>,\n+ depth: u8,\n+ ) -> Result<Vec<ForwardingProtocolMessage>, FailureError> {\n+ // don't wait the first time in order to speed up execution\n+ // if we are recursing we want to wait for the message to finish\n+ // being written as the only reason we recuse is becuase we found\n+ // a write in progress\n+ if depth > 1 && depth <= 10 {\n+ thread::sleep(SPINLOCK_TIME);\n+ } else if depth > 10 {\n+ error!(\"Never found the end of the message\");\n+ bail!(\"Never found the end of the message\");\n+ }\n+\n+ let mut bytes = bytes;\n+ bytes.extend_from_slice(&read_till_block(input)?);\n+\n+ match (\n+ ForwardingProtocolMessage::read_message(&bytes),\n+ ForwardingProtocolMessage::read_encrypted_forward_message(\n&bytes,\nserver_publickey,\nclient_secretkey,\n- )?;\n+ ),\n+ ) {\n+ (Ok((_bytes, ForwardingProtocolMessage::ForwardingCloseMessage)), _) => {\n+ trace!(\"Got close message, not starting\");\n+ Ok(vec![ForwardingProtocolMessage::ForwardingCloseMessage])\n+ }\n+ (_, Ok((bytes_read, msg))) => {\n+ trace!(\n+ \"Got a forward message, recursing with {} bytes\",\n+ bytes.len() - bytes_read\n+ );\nForwardingProtocolMessage::read_messages_internal(\ninput,\nbytes[bytes_read..].to_vec(),\n@@ -574,6 +611,36 @@ impl ForwardingProtocolMessage {\n0,\n)\n}\n+ (Err(ForwardingProtocolError::SliceTooSmall { .. }), _) => {\n+ trace!(\"Got partial close message\");\n+ ForwardingProtocolMessage::read_messages_start_internal(\n+ input,\n+ server_publickey,\n+ client_secretkey,\n+ bytes,\n+ depth + 1,\n+ )\n+ }\n+ (_, Err(ForwardingProtocolError::SliceTooSmall { .. })) => {\n+ trace!(\"Got partial forward message\");\n+ ForwardingProtocolMessage::read_messages_start_internal(\n+ input,\n+ server_publickey,\n+ client_secretkey,\n+ bytes,\n+ depth + 1,\n+ )\n+ }\n+ (Err(a), Err(b)) => {\n+ trace!(\"Double read failure {:?} {:?}\", a, b);\n+ Err(format_err!(\"{:?} {:?}\", a, b))\n+ }\n+ (_, _) => {\n+ trace!(\"Impossible error\");\n+ Err(format_err!(\"Impossible\"))\n+ }\n+ }\n+ }\n/// Reads all the currently available messages from the provided stream, this function will\n/// also block until a currently in flight message is delivered\n@@ -589,6 +656,10 @@ impl ForwardingProtocolMessage {\nmessages: Vec<ForwardingProtocolMessage>,\ndepth: u8,\n) -> Result<Vec<ForwardingProtocolMessage>, FailureError> {\n+ // don't wait the first time in order to speed up execution\n+ // if we are recursing we want to wait for the message to finish\n+ // being written as the only reason we recuse is becuase we found\n+ // a write in progress\nif depth > 1 && depth <= 10 {\nthread::sleep(SPINLOCK_TIME);\n} else if depth > 10 {\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Read partial packets for encrypted start messages
The same situation applies here with a few more edge cases. We may
get partially completed messages and need to recurse to finish them |
20,244 | 21.04.2020 14:33:31 | 14,400 | c2d20ce4e84abb7f3658a69aaa26d72cc81a81bc | Consistent network monitor logging messages | [
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_common/network_monitor/mod.rs",
"new_path": "rita/src/rita_common/network_monitor/mod.rs",
"diff": "@@ -335,7 +335,7 @@ fn observe_network(\n(Some(key), Some(avg), Some(std_dev)) => {\nif running_stats.is_bloated() {\ninfo!(\n- \"{} is defined as bloated with AVG {} STDDEV {} and CV {}!\",\n+ \"Neighbor {} is defined as bloated with AVG {} STDDEV {} and CV {}!\",\nkey, avg, std_dev, neigh.rtt\n);\n// shape the misbehaving tunnel\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Consistent network monitor logging messages |
20,244 | 21.04.2020 15:38:53 | 14,400 | f900e43b1f2c3e2dfcd870fdf497768d50a9d3a0 | Rescue xdai bridge stuck in Depositing
This bug has been cropping up for months now right under my nose.
I never considered that do_send could fail. But in retrospect it's
outlined clearly in the doc comment that it often will | [
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_common/token_bridge/mod.rs",
"new_path": "rita/src/rita_common/token_bridge/mod.rs",
"diff": "@@ -73,8 +73,8 @@ use std::time::Duration;\nuse std::time::Instant;\nconst BRIDGE_TIMEOUT: Duration = Duration::from_secs(3600);\n-const UNISWAP_TIMEOUT: u64 = 600u64;\npub const ETH_TRANSFER_TIMEOUT: u64 = 600u64;\n+const UNISWAP_TIMEOUT: u64 = ETH_TRANSFER_TIMEOUT;\n/// 1c in of dai in wei\npub const DAI_WEI_CENT: u128 = 10_000_000_000_000_000u128;\n@@ -102,7 +102,9 @@ pub enum State {\n/// used to ensure that only the future chain that started an operation can end it\nformer_state: Option<Box<State>>,\n},\n- Depositing {},\n+ Depositing {\n+ timestamp: Instant,\n+ },\nWithdrawing {\namount: Uint256,\nto: Address,\n@@ -326,7 +328,10 @@ fn xdai_bridge(state: State, bridge: &TokenBridge) {\nbridge.own_address\n);\n// Go into State::Depositing right away to prevent multiple attempts\n- TokenBridge::from_registry().do_send(StateChange(State::Depositing {}));\n+ let state = State::Depositing {\n+ timestamp: Instant::now(),\n+ };\n+ TokenBridge::from_registry().do_send(StateChange(state.clone()));\nArbiter::spawn(\nrescue_dai(\nbridge.clone(),\n@@ -362,7 +367,7 @@ fn xdai_bridge(state: State, bridge: &TokenBridge) {\nBox::new(\nbridge\n// Convert to Dai in Uniswap\n- .eth_to_dai_swap(swap_amount, ETH_TRANSFER_TIMEOUT)\n+ .eth_to_dai_swap(swap_amount, UNISWAP_TIMEOUT)\n.and_then(move |dai_bought| {\nTokenBridge::from_registry().do_send(\nDetailedStateChange(\n@@ -393,7 +398,7 @@ fn xdai_bridge(state: State, bridge: &TokenBridge) {\n}\n})\n})\n- .then(|res| {\n+ .then(move |res| {\n// It goes back into State::Ready once the dai\n// is in the bridge or if failed. This prevents multiple simultaneous\n// attempts to bridge the same Dai.\n@@ -402,13 +407,33 @@ fn xdai_bridge(state: State, bridge: &TokenBridge) {\nerror!(\"Error in bridge State::Deposit Tick handler: {:?}\", res);\n}\nTokenBridge::from_registry().do_send(StateChange(State::Ready {\n- former_state: Some(Box::new(State::Depositing {})),\n+ former_state: Some(Box::new(state)),\n}));\nOk(())\n}),\n)\n}\n- State::Depositing {} => info!(\"Tried to tick in bridge State::Depositing\"),\n+ State::Depositing { timestamp } => {\n+ info!(\"Tried to tick in bridge State::Depositing\");\n+ // if the do_send at the end of state depositing fails we can get stuck here\n+ // at the time time we don't want to submit multiple eth transactions for each\n+ // step above, especially if they take a long time (note the timeouts are in the 10's of minutes)\n+ // so we often 'tick' in depositing because there's a background future we don't want to interuppt\n+ // if that future fails it's state change do_send a few lines up from here we're screwed and the bridge\n+ // forever sits in this no-op state. This is a rescue setup for that situation where we check that enough\n+ // time has elapsed. The theroretical max here is the uniswap timeout plus the eth transfer timeout\n+ let now = Instant::now();\n+ if now\n+ > timestamp\n+ + Duration::from_secs(UNISWAP_TIMEOUT)\n+ + Duration::from_secs(ETH_TRANSFER_TIMEOUT)\n+ {\n+ warn!(\"Rescued stuck bridge\");\n+ TokenBridge::from_registry().do_send(StateChange(State::Ready {\n+ former_state: Some(Box::new(State::Depositing { timestamp })),\n+ }));\n+ }\n+ }\nState::Withdrawing {\nto,\namount,\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Rescue xdai bridge stuck in Depositing
This bug has been cropping up for months now right under my nose.
I never considered that do_send could fail. But in retrospect it's
outlined clearly in the doc comment that it often will |
20,244 | 21.04.2020 17:21:26 | 14,400 | 51c8988c4f5316d215eee72c2741d86199aefe9a | Remove duplicate log for geoip
The log statement is a funny way to avoid the 'value is never used'
warning | [
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_exit/database/geoip.rs",
"new_path": "rita/src/rita_exit/database/geoip.rs",
"diff": "@@ -162,12 +162,6 @@ pub fn get_country(ip: IpAddr) -> Result<String, Error> {\nmatch cache_result {\nSome(code) => Ok(code),\nNone => {\n- let geo_ip_url = format!(\"https://geoip.maxmind.com/geoip/v2.1/country/{}\", ip);\n- info!(\n- \"making GeoIP request to {} for {}\",\n- geo_ip_url,\n- ip.to_string()\n- );\nlet geo_ip_url = format!(\"https://geoip.maxmind.com/geoip/v2.1/country/{}\", ip);\ninfo!(\n\"making GeoIP request to {} for {}\",\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Remove duplicate log for geoip
The log statement is a funny way to avoid the 'value is never used'
warning |
20,244 | 22.04.2020 07:29:46 | 14,400 | 3e39bdd44ee97937f6cdfbf145f14a08fcb07f46 | Support 32 byte packet lengths for forwarding protocol | [
{
"change_type": "MODIFY",
"old_path": "antenna_forwarding_protocol/src/lib.rs",
"new_path": "antenna_forwarding_protocol/src/lib.rs",
"diff": "@@ -43,12 +43,12 @@ pub const SPINLOCK_TIME: Duration = Duration::from_millis(100);\n/// The amount of time to wait for a blocking read\npub const NET_TIMEOUT: Duration = Duration::from_secs(1);\n-/// The size in bytes of our packet header, 16 byte magic, 2 byte type, 2 byte len\n-pub const HEADER_LEN: usize = 20;\n+/// The size in bytes of our packet header, 16 byte magic, 2 byte type, 4 byte len\n+pub const HEADER_LEN: usize = 22;\n#[derive(Clone, Serialize, Deserialize, Debug, Eq, PartialEq)]\npub enum ForwardingProtocolError {\n- SliceTooSmall { expected: u16, actual: u16 },\n+ SliceTooSmall { expected: u32, actual: u32 },\nSerdeError { message: String },\nBadMagic,\nInvalidLen,\n@@ -282,7 +282,7 @@ impl ForwardingProtocolMessage {\n// message type number index 16-18\nmessage.extend_from_slice(&message_type.to_be_bytes());\n// length, index 18-20\n- let len_bytes = payload.len() as u16;\n+ let len_bytes = payload.len() as u32;\nmessage.extend_from_slice(&len_bytes.to_be_bytes());\n// copy in the serialized struct\nmessage.extend_from_slice(&payload);\n@@ -310,7 +310,7 @@ impl ForwardingProtocolMessage {\nmessage\n.extend_from_slice(&ForwardingProtocolMessage::FORWARD_MESSAGE_TYPE.to_be_bytes());\n// length, index 18-20\n- let len_bytes = payload.len() as u16;\n+ let len_bytes = payload.len() as u32;\nmessage.extend_from_slice(&len_bytes.to_be_bytes());\n// copy in the encrypted struct\nmessage.extend_from_slice(&payload);\n@@ -337,9 +337,9 @@ impl ForwardingProtocolMessage {\npacket_type.clone_from_slice(&payload[16..18]);\nlet packet_type = u16::from_be_bytes(packet_type);\n- let mut packet_len: [u8; 2] = [0; 2];\n- packet_len.clone_from_slice(&payload[18..20]);\n- let packet_len = u16::from_be_bytes(packet_len);\n+ let mut packet_len: [u8; 4] = [0; 4];\n+ packet_len.clone_from_slice(&payload[18..22]);\n+ let packet_len = u32::from_be_bytes(packet_len);\n// this needs to be updated when new packet types are added\nif packet_magic != ForwardingProtocolMessage::MAGIC {\n@@ -348,17 +348,17 @@ impl ForwardingProtocolMessage {\nreturn Err(ForwardingProtocolError::WrongPacketType);\n} else if packet_len as usize + HEADER_LEN > payload.len() {\nreturn Err(ForwardingProtocolError::SliceTooSmall {\n- actual: payload.len() as u16,\n- expected: { packet_len + HEADER_LEN as u16 },\n+ actual: payload.len() as u32,\n+ expected: { packet_len + HEADER_LEN as u32 },\n});\n}\n// nonce is 24 bytes\n- let nonce_end = 20 + NONCEBYTES;\n+ let nonce_end = HEADER_LEN + NONCEBYTES;\nlet mut nonce: [u8; NONCEBYTES] = [0; NONCEBYTES];\n- nonce.clone_from_slice(&payload[20..nonce_end]);\n+ nonce.clone_from_slice(&payload[HEADER_LEN..nonce_end]);\nlet nonce = Nonce(nonce);\n- let end_bytes = 20 + packet_len as usize;\n+ let end_bytes = HEADER_LEN + packet_len as usize;\nlet ciphertext = &payload[nonce_end..end_bytes];\nlet sk = client_secretkey.into();\nlet pk = server_publickey.into();\n@@ -397,7 +397,7 @@ impl ForwardingProtocolMessage {\n&ForwardingProtocolMessage::CONNECTION_CLOSE_MESSAGE_TYPE.to_be_bytes(),\n);\n// len is only 8 byte stream id\n- let len_bytes = 8u16;\n+ let len_bytes = 8u32;\nmessage.extend_from_slice(&len_bytes.to_be_bytes());\nmessage.extend_from_slice(&stream_id.to_be_bytes());\n@@ -411,7 +411,7 @@ impl ForwardingProtocolMessage {\n&(ForwardingProtocolMessage::CONNECTION_DATA_MESSAGE_TYPE.to_be_bytes()),\n);\n// length is the stream id followed by the payload bytes\n- let len_bytes = payload.len() as u16 + 8;\n+ let len_bytes = payload.len() as u32 + 8;\nmessage.extend_from_slice(&len_bytes.to_be_bytes());\n// copy in stream id\nmessage.extend_from_slice(&stream_id.to_be_bytes());\n@@ -450,9 +450,9 @@ impl ForwardingProtocolMessage {\npacket_type.clone_from_slice(&payload[16..18]);\nlet packet_type = u16::from_be_bytes(packet_type);\n- let mut packet_len: [u8; 2] = [0; 2];\n- packet_len.clone_from_slice(&payload[18..20]);\n- let packet_len = u16::from_be_bytes(packet_len);\n+ let mut packet_len: [u8; 4] = [0; 4];\n+ packet_len.clone_from_slice(&payload[18..HEADER_LEN]);\n+ let packet_len = u32::from_be_bytes(packet_len);\n// this needs to be updated when new packet types are added\nif packet_magic != ForwardingProtocolMessage::MAGIC {\n@@ -461,8 +461,8 @@ impl ForwardingProtocolMessage {\nreturn Err(ForwardingProtocolError::WrongPacketType);\n} else if packet_len as usize + HEADER_LEN > payload.len() {\nreturn Err(ForwardingProtocolError::SliceTooSmall {\n- actual: payload.len() as u16,\n- expected: { packet_len + HEADER_LEN as u16 },\n+ actual: payload.len() as u32,\n+ expected: { packet_len + HEADER_LEN as u32 },\n});\n}\n@@ -497,10 +497,10 @@ impl ForwardingProtocolMessage {\n}\nlet mut connection_id: [u8; 8] = [0; 8];\n- connection_id.clone_from_slice(&payload[20..28]);\n+ connection_id.clone_from_slice(&payload[HEADER_LEN..HEADER_LEN + 8]);\nlet connection_id = u64::from_be_bytes(connection_id);\n- let bytes_read = 28;\n+ let bytes_read = HEADER_LEN + 8;\nOk((\nbytes_read,\n@@ -509,13 +509,13 @@ impl ForwardingProtocolMessage {\n}\nForwardingProtocolMessage::CONNECTION_DATA_MESSAGE_TYPE => {\nlet mut connection_id: [u8; 8] = [0; 8];\n- connection_id.clone_from_slice(&payload[20..28]);\n+ connection_id.clone_from_slice(&payload[HEADER_LEN..HEADER_LEN + 8]);\nlet connection_id = u64::from_be_bytes(connection_id);\nlet payload_bytes = packet_len as usize - 8;\nlet end = HEADER_LEN + 8 + payload_bytes;\nlet mut message_value = Vec::new();\n- message_value.extend_from_slice(&payload[28..end]);\n+ message_value.extend_from_slice(&payload[HEADER_LEN + 8..end]);\nOk((\nend,\n@@ -722,6 +722,7 @@ mod tests {\nuse super::WgKey;\nuse rand;\nuse rand::Rng;\n+ use std::u16::MAX as U16MAX;\nlazy_static! {\npub static ref FORWARDING_SERVER_PUBLIC_KEY: WgKey =\n@@ -763,7 +764,10 @@ mod tests {\nlet mut rng = rand::thread_rng();\n// should be small enough to be fast but long enough\n// to cause issues\n- let len: u16 = rng.gen();\n+ let mut len: u32 = rng.gen();\n+ while len > U16MAX as u32 * 4 {\n+ len = rng.gen();\n+ }\nlet mut out = Vec::new();\nfor _ in 0..len {\nlet byte: u8 = rng.gen();\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Support 32 byte packet lengths for forwarding protocol |
20,244 | 22.04.2020 07:29:46 | 14,400 | 08dcf03fdcfa3cc7aafd8747e6e3f911659275bd | More robust timeouts for tcp message parsing
This came down to a decision to discard packets and then find the
new correct parsing start point or just trusting the underlying transport
it seems that trusting the transport was a good decision because testing
with netem is quite positive. | [
{
"change_type": "MODIFY",
"old_path": "antenna_forwarding_client/src/lib.rs",
"new_path": "antenna_forwarding_client/src/lib.rs",
"diff": "@@ -57,7 +57,7 @@ pub fn start_antenna_forwarding_proxy<S: 'static + std::marker::Send + ::std::ha\n) {\ninfo!(\"Starting antenna forwarding proxy!\");\nthread::spawn(move || loop {\n- trace!(\"About to checkin with {}\", checkin_address);\n+ info!(\"About to checkin with {}\", checkin_address);\n// parse checkin address every loop iteration as a way\n// of resolving the domain name on each run\nlet socket: SocketAddr = match checkin_address.to_socket_addrs() {\n@@ -74,7 +74,7 @@ pub fn start_antenna_forwarding_proxy<S: 'static + std::marker::Send + ::std::ha\n}\n};\nif let Ok(mut server_stream) = TcpStream::connect_timeout(&socket, NET_TIMEOUT) {\n- trace!(\"connected to {}\", checkin_address);\n+ info!(\"connected to {}\", checkin_address);\n// send our identifier\nlet _res = write_all_spinlock(\n&mut server_stream,\n@@ -125,7 +125,7 @@ pub fn start_antenna_forwarding_proxy<S: 'static + std::marker::Send + ::std::ha\n}\n}\n}\n- trace!(\"Waiting for next checkin cycle\");\n+ info!(\"Waiting for next checkin cycle\");\nthread::sleep(SLEEP_TIME)\n});\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "antenna_forwarding_protocol/src/lib.rs",
"new_path": "antenna_forwarding_protocol/src/lib.rs",
"diff": "@@ -577,9 +577,10 @@ impl ForwardingProtocolMessage {\n// if we are recursing we want to wait for the message to finish\n// being written as the only reason we recuse is becuase we found\n// a write in progress\n- if depth > 1 && depth <= 10 {\n+ const WAIT_TIME: u8 = 10;\n+ if depth > 1 && depth <= WAIT_TIME {\nthread::sleep(SPINLOCK_TIME);\n- } else if depth > 10 {\n+ } else if depth > WAIT_TIME {\nerror!(\"Never found the end of the message\");\nbail!(\"Never found the end of the message\");\n}\n@@ -654,15 +655,19 @@ impl ForwardingProtocolMessage {\ninput: &mut TcpStream,\nremaining_bytes: Vec<u8>,\nmessages: Vec<ForwardingProtocolMessage>,\n- depth: u8,\n+ depth: u16,\n) -> Result<Vec<ForwardingProtocolMessage>, FailureError> {\n// don't wait the first time in order to speed up execution\n// if we are recursing we want to wait for the message to finish\n// being written as the only reason we recuse is becuase we found\n// a write in progress\n- if depth > 1 && depth <= 10 {\n+ // we wait up to 60 seconds, this may seem absurdly long but on very\n+ // bad connections it's better to trust in the transport (TCP) to resume\n+ // and keep the packets flowing\n+ const WAIT_TIME: u16 = 600;\n+ if depth > 1 && depth <= WAIT_TIME {\nthread::sleep(SPINLOCK_TIME);\n- } else if depth > 10 {\n+ } else if depth > WAIT_TIME {\nerror!(\"Never found the end of the message\");\nbail!(\"Never found the end of the message\");\n}\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | More robust timeouts for tcp message parsing
This came down to a decision to discard packets and then find the
new correct parsing start point or just trusting the underlying transport
it seems that trusting the transport was a good decision because testing
with netem is quite positive. |
20,244 | 22.04.2020 10:28:44 | 14,400 | 93fc818382afeae80a5168dc34d65b5b8b25094b | Add version string to heartbeats
This is generally useful to have so that we understand what device we're
dealing with | [
{
"change_type": "MODIFY",
"old_path": "althea_types/src/interop.rs",
"new_path": "althea_types/src/interop.rs",
"diff": "@@ -467,4 +467,6 @@ pub struct HeartbeatMessage {\npub notify_balance: bool,\n/// The exit registration contact details. If set\npub contact_details: ContactDetails,\n+ /// The router version stored in semver format as found in the Cargo.toml\n+ pub version: String,\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_client/heartbeat/mod.rs",
"new_path": "rita/src/rita_client/heartbeat/mod.rs",
"diff": "@@ -210,6 +210,7 @@ fn send_udp_heartbeat_packet(\nexit_neighbor,\nnotify_balance: low_balance_notification,\ncontact_details,\n+ version: env!(\"CARGO_PKG_VERSION\").to_string(),\n};\n// serde will only fail under specific circumstances with specific structs\n// given the fixed nature of our application here I think this is safe\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Add version string to heartbeats
This is generally useful to have so that we understand what device we're
dealing with |
20,244 | 22.04.2020 13:29:32 | 14,400 | 9acad40c1687f8e9f0a48ea7c6eee3ef8798446f | Print full packets on parsing errors
Looks like I'm not going to get this one today, have to investigate
another wonky parsing error tomorrow | [
{
"change_type": "MODIFY",
"old_path": "antenna_forwarding_protocol/src/lib.rs",
"new_path": "antenna_forwarding_protocol/src/lib.rs",
"diff": "@@ -684,7 +684,8 @@ impl ForwardingProtocolMessage {\nif num_remaining_bytes != 0 {\ntrace!(\n- \"Got message recursing for remaining bytes {}\",\n+ \"Got message of size {} recursing for remaining bytes {}\",\n+ bytes,\nnum_remaining_bytes\n);\nForwardingProtocolMessage::read_messages_internal(\n@@ -710,6 +711,10 @@ impl ForwardingProtocolMessage {\n_ => {\nif !remaining_bytes.is_empty() {\nerror!(\"Unparsed bytes! {} {:?}\", remaining_bytes.len(), e);\n+ error!(\n+ \"Messages {:#X?} Remaining bytes {:#X?}\",\n+ messages, remaining_bytes\n+ );\nbail!(\"Unparsed bytes!\");\n} else {\nOk(messages)\n@@ -781,6 +786,22 @@ mod tests {\nout\n}\n+ fn get_random_long_test_vector() -> Vec<u8> {\n+ let mut rng = rand::thread_rng();\n+ // should be small enough to be fast but long enough\n+ // to cause issues\n+ let mut len: u32 = rng.gen();\n+ while len > U16MAX as u32 * 4 || len < U16MAX as u32 {\n+ len = rng.gen();\n+ }\n+ let mut out = Vec::new();\n+ for _ in 0..len {\n+ let byte: u8 = rng.gen();\n+ out.push(byte);\n+ }\n+ out\n+ }\n+\nfn get_random_stream_id() -> u64 {\nlet mut rng = rand::thread_rng();\nlet out: u64 = rng.gen();\n@@ -1034,4 +1055,32 @@ mod tests {\nassert!(ForwardingProtocolMessage::read_message(&junk).is_err());\nassert!(ForwardingProtocolMessage::read_message(&junk).is_err());\n}\n+\n+ #[test]\n+ fn test_multiple_big_connection_messages() {\n+ let message_a = ForwardingProtocolMessage::new_connection_data_message(\n+ get_random_stream_id(),\n+ get_random_long_test_vector(),\n+ );\n+ let message_b = ForwardingProtocolMessage::new_connection_data_message(\n+ get_random_stream_id(),\n+ get_random_long_test_vector(),\n+ );\n+ let message_c = ForwardingProtocolMessage::new_connection_data_message(\n+ get_random_stream_id(),\n+ get_random_test_vector(),\n+ );\n+ let mut out = message_a.get_message();\n+ out.extend_from_slice(&message_b.get_message());\n+ out.extend_from_slice(&message_c.get_message());\n+ let (size_a, parsed) =\n+ ForwardingProtocolMessage::read_message(&out).expect(\"Failed to parse!\");\n+ assert_eq!(parsed, message_a);\n+ let (size_b, parsed) =\n+ ForwardingProtocolMessage::read_message(&out[size_a..]).expect(\"Failed to parse!\");\n+ assert_eq!(parsed, message_b);\n+ let (_size_c, parsed) = ForwardingProtocolMessage::read_message(&out[size_a + size_b..])\n+ .expect(\"Failed to parse!\");\n+ assert_eq!(parsed, message_c);\n+ }\n}\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Print full packets on parsing errors
Looks like I'm not going to get this one today, have to investigate
another wonky parsing error tomorrow |
20,244 | 22.04.2020 16:48:18 | 14,400 | b9c26d1f12382795b2605ed17dcaa78a7e0d7ab3 | Use write instead of write_all
Write all had some problematic semantics when combined with nonblocking
mainly that it would write but not wait for blocking, leaving you without
a way to know which bytes you had already written. Instead we can use
write directly with only a little extra complexity. | [
{
"change_type": "MODIFY",
"old_path": "antenna_forwarding_protocol/src/lib.rs",
"new_path": "antenna_forwarding_protocol/src/lib.rs",
"diff": "@@ -84,23 +84,33 @@ impl Display for ForwardingProtocolError {\n/// Writes data to a stream keeping in mind that we may encounter\n/// a buffer limit and have to partially complete our write\npub fn write_all_spinlock(stream: &mut TcpStream, buffer: &[u8]) -> Result<(), IoError> {\n+ assert!(!buffer.is_empty());\nstream.set_nonblocking(true)?;\n- loop {\n- let res = stream.write_all(buffer);\n+ let res = stream.write(buffer);\nmatch res {\n- Ok(_val) => {\n+ Ok(bytes) => {\ntrace!(\"Spinlock wrote {} bytes\", buffer.len());\n- return Ok(());\n+ if buffer.len() == bytes {\n+ Ok(())\n+ } else if bytes == 0 {\n+ Err(IoError::new(\n+ std::io::ErrorKind::WriteZero,\n+ format_err!(\"Probably a dead connection\"),\n+ ))\n+ } else {\n+ write_all_spinlock(stream, &buffer[bytes..])\n+ }\n}\nErr(e) => {\n- error!(\"Problem in spinlock writing {} bytes\", buffer.len());\n- if e.kind() != WouldBlock {\n+ error!(\"Problem {:?} in spinlock writing {} bytes\", e, buffer.len());\n+ if e.kind() == WouldBlock {\n+ thread::sleep(SPINLOCK_TIME);\n+ write_all_spinlock(stream, &buffer)\n+ } else {\nerror!(\"Socket write error is {:?}\", e);\n- return Err(e);\n- }\n+ Err(e)\n}\n}\n- thread::sleep(SPINLOCK_TIME);\n}\n}\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Use write instead of write_all
Write all had some problematic semantics when combined with nonblocking
mainly that it would write but not wait for blocking, leaving you without
a way to know which bytes you had already written. Instead we can use
write directly with only a little extra complexity. |
20,244 | 22.04.2020 17:27:30 | 14,400 | 2593d019816912925798e3685cebb125ba086e28 | Add depth limits to write recursion
An infinite recursion case can occur here if the operating system
does not allocate the require space to write to. Lets not make that
already bad situation worse. | [
{
"change_type": "MODIFY",
"old_path": "antenna_forwarding_protocol/src/lib.rs",
"new_path": "antenna_forwarding_protocol/src/lib.rs",
"diff": "@@ -84,12 +84,27 @@ impl Display for ForwardingProtocolError {\n/// Writes data to a stream keeping in mind that we may encounter\n/// a buffer limit and have to partially complete our write\npub fn write_all_spinlock(stream: &mut TcpStream, buffer: &[u8]) -> Result<(), IoError> {\n+ write_all_spinlock_internal(stream, buffer, 0)\n+}\n+\n+fn write_all_spinlock_internal(\n+ stream: &mut TcpStream,\n+ buffer: &[u8],\n+ depth: u8,\n+) -> Result<(), IoError> {\nassert!(!buffer.is_empty());\n+ if depth > 100 {\n+ return Err(IoError::new(\n+ std::io::ErrorKind::WriteZero,\n+ format_err!(\"Operating system won't allocate buffer space\"),\n+ ));\n+ }\n+\nstream.set_nonblocking(true)?;\nlet res = stream.write(buffer);\nmatch res {\nOk(bytes) => {\n- trace!(\"Spinlock wrote {} bytes\", buffer.len());\n+ trace!(\"Spinlock wrote {} bytes of {}\", bytes, buffer.len());\nif buffer.len() == bytes {\nOk(())\n} else if bytes == 0 {\n@@ -98,14 +113,20 @@ pub fn write_all_spinlock(stream: &mut TcpStream, buffer: &[u8]) -> Result<(), I\nformat_err!(\"Probably a dead connection\"),\n))\n} else {\n- write_all_spinlock(stream, &buffer[bytes..])\n+ trace!(\"Did not write all, recursing\",);\n+ write_all_spinlock_internal(stream, &buffer[bytes..], depth + 1)\n}\n}\nErr(e) => {\n- error!(\"Problem {:?} in spinlock writing {} bytes\", e, buffer.len());\n+ error!(\n+ \"Problem {:?} in spinlock trying to write {} bytes\",\n+ e,\n+ buffer.len()\n+ );\nif e.kind() == WouldBlock {\n+ // wait for the operating system to clear up some buffer space\nthread::sleep(SPINLOCK_TIME);\n- write_all_spinlock(stream, &buffer)\n+ write_all_spinlock_internal(stream, &buffer, depth + 1)\n} else {\nerror!(\"Socket write error is {:?}\", e);\nErr(e)\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Add depth limits to write recursion
An infinite recursion case can occur here if the operating system
does not allocate the require space to write to. Lets not make that
already bad situation worse. |
20,244 | 22.04.2020 18:58:43 | 14,400 | cb9d2a377f360592a5cade4371612c26bf6a5357 | Bump for Beta 13 RC4 | [
{
"change_type": "MODIFY",
"old_path": "Cargo.lock",
"new_path": "Cargo.lock",
"diff": "@@ -2629,7 +2629,7 @@ dependencies = [\n[[package]]\nname = \"rita\"\n-version = \"0.5.42\"\n+version = \"0.5.43\"\ndependencies = [\n\"actix\",\n\"actix-web\",\n"
},
{
"change_type": "MODIFY",
"old_path": "rita/Cargo.toml",
"new_path": "rita/Cargo.toml",
"diff": "[package]\nname = \"rita\"\n-version = \"0.5.42\"\n+version = \"0.5.43\"\nauthors = [\"Jehan <jehan.tremback@gmail.com>\", \"Ben <wangben3@gmail.com>\"]\nbuild = \"build.rs\"\nedition = \"2018\"\n"
},
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_common/dashboard/own_info.rs",
"new_path": "rita/src/rita_common/dashboard/own_info.rs",
"diff": "@@ -6,7 +6,7 @@ use failure::Error;\nuse num256::{Int256, Uint256};\nuse settings::RitaCommonSettings;\n-pub static READABLE_VERSION: &str = \"Beta 13 RC3\";\n+pub static READABLE_VERSION: &str = \"Beta 13 RC4\";\n#[derive(Serialize)]\npub struct OwnInfo {\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Bump for Beta 13 RC4 |
20,244 | 23.04.2020 18:05:35 | 14,400 | 9e3dd57ad33cc16cf9d148e8cfdc8a0683a2f5ed | Don't call set_system_blockchain every time
It zeros out the balance and that causes all sorts of trouble | [
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_client/operator_update/mod.rs",
"new_path": "rita/src/rita_client/operator_update/mod.rs",
"diff": "@@ -139,8 +139,10 @@ fn checkin() {\npayment.max_fee = new_settings.max;\npayment.balance_warning_level = new_settings.warning.into();\nif let Some(new_chain) = new_settings.system_chain {\n+ if payment.system_chain != new_chain {\nset_system_blockchain(new_chain, &mut payment);\n}\n+ }\nif let Some(new_chain) = new_settings.withdraw_chain {\npayment.withdraw_chain = new_chain;\n}\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Don't call set_system_blockchain every time
It zeros out the balance and that causes all sorts of trouble |
20,244 | 23.04.2020 18:11:02 | 14,400 | c179c72c4ed00f843da159b3e5f51b91d4e581ba | Fix a variety of new clippy nits | [
{
"change_type": "MODIFY",
"old_path": "rita/src/client.rs",
"new_path": "rita/src/client.rs",
"diff": "@@ -30,8 +30,6 @@ extern crate arrayvec;\nuse actix_web::http::Method;\nuse actix_web::{http, server, App};\nuse docopt::Docopt;\n-use env_logger;\n-use openssl_probe;\nuse settings::client::{RitaClientSettings, RitaSettingsStruct};\nuse settings::RitaCommonSettings;\nuse std::env;\n"
},
{
"change_type": "MODIFY",
"old_path": "rita/src/exit.rs",
"new_path": "rita/src/exit.rs",
"diff": "@@ -35,8 +35,6 @@ use althea_types::WgKey;\nuse diesel::r2d2::ConnectionManager;\nuse diesel::PgConnection;\nuse docopt::Docopt;\n-use env_logger;\n-use openssl_probe;\nuse r2d2::Pool;\nuse settings::exit::ExitNetworkSettings;\nuse settings::exit::ExitVerifSettings;\n"
},
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_client/heartbeat/mod.rs",
"new_path": "rita/src/rita_client/heartbeat/mod.rs",
"diff": "@@ -123,11 +123,7 @@ fn get_selected_exit_route(route_dump: &[Route]) -> Result<Route, Error> {\nfn get_selected_exit() -> Option<ExitServer> {\nlet exit_client = SETTING.get_exit_client();\n- let exit = if let Some(e) = exit_client.get_current_exit() {\n- e\n- } else {\n- return None;\n- };\n+ let exit = exit_client.get_current_exit()?;\nSome(exit.clone())\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_exit/database/database_tools.rs",
"new_path": "rita/src/rita_exit/database/database_tools.rs",
"diff": "@@ -7,7 +7,6 @@ use crate::SETTING;\nuse actix_web::Result;\nuse althea_kernel_interface::ExitClient;\nuse althea_types::ExitClientIdentity;\n-use diesel;\nuse diesel::dsl::{delete, exists};\nuse diesel::prelude::{ExpressionMethods, PgConnection, QueryDsl, RunQueryDsl};\nuse diesel::r2d2::ConnectionManager;\n"
},
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_exit/database/db_client.rs",
"new_path": "rita/src/rita_exit/database/db_client.rs",
"diff": "@@ -7,7 +7,6 @@ use actix::Message;\nuse actix::Supervised;\nuse actix::SystemService;\nuse actix_web::Result;\n-use diesel;\nuse diesel::dsl::delete;\nuse diesel::*;\nuse exit_db::schema;\n"
},
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_exit/database/email.rs",
"new_path": "rita/src/rita_exit/database/email.rs",
"diff": "@@ -5,7 +5,6 @@ use crate::rita_exit::database::secs_since_unix_epoch;\nuse crate::rita_exit::database::struct_tools::verif_done;\nuse crate::SETTING;\nuse althea_types::{ExitClientDetails, ExitClientIdentity, ExitState};\n-use diesel;\nuse diesel::prelude::PgConnection;\nuse exit_db::models;\nuse failure::Error;\n"
},
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_exit/database/mod.rs",
"new_path": "rita/src/rita_exit/database/mod.rs",
"diff": "@@ -42,7 +42,6 @@ use crate::SETTING;\nuse althea_kernel_interface::ExitClient;\nuse althea_types::Identity;\nuse althea_types::{ExitClientDetails, ExitClientIdentity, ExitDetails, ExitState, ExitVerifMode};\n-use diesel;\nuse diesel::prelude::PgConnection;\nuse failure::Error;\nuse futures01::future;\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Fix a variety of new clippy nits |
20,244 | 24.04.2020 10:30:42 | 14,400 | 68dd2e1909b41e482bf8052f7ec63cd1dd283348 | Bump for Beta 13 RC5 | [
{
"change_type": "MODIFY",
"old_path": "Cargo.lock",
"new_path": "Cargo.lock",
"diff": "@@ -2629,7 +2629,7 @@ dependencies = [\n[[package]]\nname = \"rita\"\n-version = \"0.5.43\"\n+version = \"0.5.44\"\ndependencies = [\n\"actix\",\n\"actix-web\",\n"
},
{
"change_type": "MODIFY",
"old_path": "rita/Cargo.toml",
"new_path": "rita/Cargo.toml",
"diff": "[package]\nname = \"rita\"\n-version = \"0.5.43\"\n+version = \"0.5.44\"\nauthors = [\"Jehan <jehan.tremback@gmail.com>\", \"Ben <wangben3@gmail.com>\"]\nbuild = \"build.rs\"\nedition = \"2018\"\n"
},
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_common/dashboard/own_info.rs",
"new_path": "rita/src/rita_common/dashboard/own_info.rs",
"diff": "@@ -6,7 +6,7 @@ use failure::Error;\nuse num256::{Int256, Uint256};\nuse settings::RitaCommonSettings;\n-pub static READABLE_VERSION: &str = \"Beta 13 RC4\";\n+pub static READABLE_VERSION: &str = \"Beta 13 RC5\";\n#[derive(Serialize)]\npub struct OwnInfo {\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Bump for Beta 13 RC5 |
20,244 | 25.04.2020 13:14:59 | 14,400 | f34f1a8f6f3e40ac344b18e438e8946efc8a9446 | Lift stats processing into Althea types
this way we can get statistics from anywhere and import them more
easily into for example the operator tools server | [
{
"change_type": "MODIFY",
"old_path": "althea_types/src/interop.rs",
"new_path": "althea_types/src/interop.rs",
"diff": "@@ -367,6 +367,7 @@ impl FromStr for ReleaseStatus {\npub enum OperatorAction {\nResetRouterPassword,\nResetWiFiPassword,\n+ ResetShaper,\n}\n/// Operator update that we get from the operator server during our checkin\n@@ -431,6 +432,15 @@ pub struct OperatorCheckinMessage {\npub id: Identity,\npub operator_address: Option<Address>,\npub system_chain: SystemChain,\n+ // below this is data too large to fit into the heartbeat but stuff we still want\n+ pub peers: Option<Vec<NeighborStatus>>,\n+}\n+\n+/// Struct for storing peer status data for reporting to the operator tools server\n+#[derive(Debug, Clone, Serialize, Deserialize)]\n+pub struct NeighborStatus {\n+ id: Identity,\n+ speed: u64,\n}\n/// Struct for storing user contact details\n"
},
{
"change_type": "MODIFY",
"old_path": "althea_types/src/lib.rs",
"new_path": "althea_types/src/lib.rs",
"diff": "@@ -6,10 +6,10 @@ extern crate failure;\nextern crate arrayvec;\npub mod interop;\n-pub mod rtt;\n+pub mod monitoring;\npub mod wg_key;\npub use crate::interop::*;\n-pub use crate::rtt::RTTimestamps;\n+pub use crate::monitoring::*;\npub use crate::wg_key::WgKey;\npub use std::str::FromStr;\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "althea_types/src/monitoring.rs",
"diff": "+use std::time::Instant;\n+use std::time::SystemTime;\n+\n+pub const SAMPLE_PERIOD: u8 = 5u8;\n+const SAMPLES_IN_FIVE_MINUTES: usize = 300 / SAMPLE_PERIOD as usize;\n+\n+/// This is a helper struct for measuring the round trip time over the exit tunnel independently\n+/// from Babel. In the future, `RTTimestamps` should aid in RTT-related overadvertisement detection.\n+#[derive(Serialize, Deserialize, Debug)]\n+pub struct RTTimestamps {\n+ pub exit_rx: SystemTime,\n+ pub exit_tx: SystemTime,\n+}\n+\n+/// Implements https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Welford's_online_algorithm\n+/// to keep track of neighbor latency in an online fashion for a specific interface\n+#[derive(Clone, Copy, Serialize, Deserialize)]\n+pub struct RunningLatencyStats {\n+ count: u32,\n+ mean: f32,\n+ m2: f32,\n+ last_value: Option<f32>,\n+ /// the last time this counters interface was invalidated by a change\n+ #[serde(skip_serializing, skip_deserializing)]\n+ last_changed: Option<Instant>,\n+}\n+\n+impl RunningLatencyStats {\n+ pub fn new() -> RunningLatencyStats {\n+ RunningLatencyStats {\n+ count: 0u32,\n+ mean: 0f32,\n+ m2: 0f32,\n+ last_value: None,\n+ last_changed: Some(Instant::now()),\n+ }\n+ }\n+ pub fn get_avg(&self) -> Option<f32> {\n+ if self.count > 2 {\n+ Some(self.mean)\n+ } else {\n+ None\n+ }\n+ }\n+ pub fn get_std_dev(&self) -> Option<f32> {\n+ if self.count > 2 {\n+ Some(self.m2 / self.count as f32)\n+ } else {\n+ None\n+ }\n+ }\n+ pub fn add_sample(&mut self, sample: f32) {\n+ self.count += 1;\n+ let delta = sample - self.mean;\n+ self.mean += delta / self.count as f32;\n+ let delta2 = sample - self.mean;\n+ self.m2 += delta * delta2;\n+ self.last_value = Some(sample);\n+ }\n+ /// A hand tuned heuristic used to determine if a connection is bloated\n+ pub fn is_bloated(&self) -> bool {\n+ let std_dev = self.get_std_dev();\n+ if let Some(std_dev) = std_dev {\n+ std_dev > 1000f32\n+ } else {\n+ false\n+ }\n+ }\n+ /// A hand tuned heuristic used to determine if a connection is good\n+ pub fn is_good(&self) -> bool {\n+ let std_dev = self.get_std_dev();\n+ if let Some(std_dev) = std_dev {\n+ std_dev < 100f32\n+ } else {\n+ false\n+ }\n+ }\n+ pub fn reset(&mut self) {\n+ self.count = 0u32;\n+ self.mean = 0f32;\n+ self.m2 = 0f32;\n+ self.last_changed = Some(Instant::now());\n+ }\n+ pub fn set_last_changed(&mut self) {\n+ self.last_changed = Some(Instant::now());\n+ }\n+ pub fn last_changed(&self) -> Instant {\n+ self.last_changed\n+ .expect(\"Tried to get changed on a serialized counter!\")\n+ }\n+}\n+\n+/// Due to the way babel communicates packet loss the functions here require slightly\n+/// more data processing to get correct values. 'Reach' is a 16 second bitvector of hello/IHU\n+/// outcomes, but we're sampling every 5 seconds, in order to keep samples from interfering with\n+/// each other we take the top 5 bits and use that to compute packet loss.\n+#[derive(Clone, Serialize, Deserialize)]\n+pub struct RunningPacketLossStats {\n+ /// the number of packets lost during each 5 second sample period over the last five minutes\n+ five_minute_loss: Vec<u8>,\n+ /// the 'front' of the looping five minute sample queue\n+ front: usize,\n+ /// Total packets observed since the system was started\n+ total_packets: u32,\n+ /// Total packets observed to be lost since the system was started\n+ total_lost: u32,\n+}\n+\n+impl RunningPacketLossStats {\n+ pub fn new() -> RunningPacketLossStats {\n+ let mut new = Vec::with_capacity(SAMPLES_IN_FIVE_MINUTES);\n+ new.extend_from_slice(&[0; SAMPLES_IN_FIVE_MINUTES]);\n+ RunningPacketLossStats {\n+ five_minute_loss: new,\n+ front: 0usize,\n+ total_packets: 0u32,\n+ total_lost: 0u32,\n+ }\n+ }\n+ pub fn add_sample(&mut self, sample: u16) {\n+ // babel displays a 16 second window of hellos, so adjust this based on\n+ // any changes in run rate of this function\n+ let lost_packets = SAMPLE_PERIOD - get_first_n_set_bits(sample, SAMPLE_PERIOD);\n+ self.total_lost += u32::from(lost_packets);\n+ self.total_packets += u32::from(SAMPLE_PERIOD);\n+ self.five_minute_loss[self.front] = lost_packets;\n+ self.front = (self.front + 1) % SAMPLES_IN_FIVE_MINUTES;\n+ }\n+ pub fn get_avg(&self) -> Option<f32> {\n+ if self.total_packets > 0 {\n+ Some(self.total_lost as f32 / self.total_packets as f32)\n+ } else {\n+ None\n+ }\n+ }\n+ pub fn get_five_min_average(&self) -> f32 {\n+ let total_packets = SAMPLES_IN_FIVE_MINUTES * SAMPLE_PERIOD as usize;\n+ let sum_loss: usize = self.five_minute_loss.iter().map(|i| *i as usize).sum();\n+ sum_loss as f32 / total_packets as f32\n+ }\n+}\n+\n+/// Counts the number of bits set to 1 in the first n bits (reading left to right so MSB first) of\n+/// the 16 bit bitvector\n+fn get_first_n_set_bits(sample: u16, n: u8) -> u8 {\n+ assert!(n <= 16);\n+ let mut mask = 0b1000_0000_0000_0000;\n+ let mut total_set_bits = 0u8;\n+ for i in ((16 - n)..16).rev() {\n+ // println!(\n+ // \"{:#b} {:#b} >> {} {:#b}\",\n+ // mask,\n+ // sample & mask,\n+ // i,\n+ // ((sample & mask) >> i)\n+ // );\n+ total_set_bits += ((sample & mask) >> i) as u8;\n+ mask >>= 1;\n+ }\n+ total_set_bits\n+}\n+\n+pub fn has_packet_loss(sample: u16) -> bool {\n+ let lost_packets = SAMPLE_PERIOD - get_first_n_set_bits(sample, SAMPLE_PERIOD);\n+ lost_packets > 0\n+}\n+\n+#[cfg(test)]\n+mod tests {\n+ use super::*;\n+ #[test]\n+ fn test_get_first_n_set_bits() {\n+ let count = get_first_n_set_bits(0b1110_0000_0000_0000, 5);\n+ assert_eq!(count, 3);\n+ }\n+ #[test]\n+ fn test_get_first_n_set_bits_limit() {\n+ let count = get_first_n_set_bits(0b1111_1100_0000_0000, 5);\n+ assert_eq!(count, 5);\n+ }\n+ #[test]\n+ fn test_get_first_n_set_bits_lower_bits() {\n+ let count = get_first_n_set_bits(0b1110_0000_0000_1100, 5);\n+ assert_eq!(count, 3);\n+ }\n+ #[test]\n+ fn test_get_first_n_set_bits_lower_longer_range() {\n+ let count = get_first_n_set_bits(0b1110_0000_0000_1100, 16);\n+ assert_eq!(count, 5);\n+ }\n+ #[test]\n+ fn test_all_set() {\n+ let count = get_first_n_set_bits(0b1111_1111_1111_1111, 16);\n+ assert_eq!(count, 16);\n+ }\n+ #[test]\n+ #[should_panic]\n+ fn test_get_first_n_set_bits_impossible() {\n+ let _count = get_first_n_set_bits(0b1110_0000_0000_1100, 32);\n+ }\n+}\n"
},
{
"change_type": "DELETE",
"old_path": "althea_types/src/rtt.rs",
"new_path": null,
"diff": "-use std::time::SystemTime;\n-\n-/// This is a helper struct for measuring the round trip time over the exit tunnel independently\n-/// from Babel. In the future, `RTTimestamps` should aid in RTT-related overadvertisement detection.\n-#[derive(Serialize, Deserialize, Debug)]\n-pub struct RTTimestamps {\n- pub exit_rx: SystemTime,\n- pub exit_tx: SystemTime,\n-}\n"
},
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_common/network_monitor/mod.rs",
"new_path": "rita/src/rita_common/network_monitor/mod.rs",
"diff": "@@ -20,6 +20,10 @@ use actix::Handler;\nuse actix::Message;\nuse actix::Supervised;\nuse actix::SystemService;\n+use althea_types::monitoring::has_packet_loss;\n+use althea_types::monitoring::SAMPLE_PERIOD;\n+use althea_types::RunningLatencyStats;\n+use althea_types::RunningPacketLossStats;\nuse althea_types::WgKey;\nuse babel_monitor::Neighbor as BabelNeighbor;\nuse babel_monitor::Route as BabelRoute;\n@@ -28,8 +32,6 @@ use std::collections::HashMap;\nuse std::time::Duration;\nuse std::time::Instant;\n-const SAMPLE_PERIOD: u8 = FAST_LOOP_SPEED as u8;\n-const SAMPLES_IN_FIVE_MINUTES: usize = 300 / SAMPLE_PERIOD as usize;\n/// 10 minutes in seconds, the amount of time we wait for an interface to be\n/// 'good' before we start trying to increase it's speed\nconst BACK_OFF_TIME: Duration = Duration::from_secs(600);\n@@ -37,149 +39,6 @@ const BACK_OFF_TIME: Duration = Duration::from_secs(600);\n/// become to insensitive to changes, currently 12 hours.\nconst WINDOW_TIME: Duration = Duration::from_secs(43200);\n-/// Implements https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Welford's_online_algorithm\n-/// to keep track of neighbor latency in an online fashion for a specific interface\n-#[derive(Clone, Copy)]\n-pub struct RunningLatencyStats {\n- count: u32,\n- mean: f32,\n- m2: f32,\n- last_value: Option<f32>,\n- /// the last time this counters interface was invalidated by a change\n- last_changed: Instant,\n-}\n-\n-impl RunningLatencyStats {\n- pub fn new() -> RunningLatencyStats {\n- RunningLatencyStats {\n- count: 0u32,\n- mean: 0f32,\n- m2: 0f32,\n- last_value: None,\n- last_changed: Instant::now(),\n- }\n- }\n- pub fn get_avg(&self) -> Option<f32> {\n- if self.count > 2 {\n- Some(self.mean)\n- } else {\n- None\n- }\n- }\n- pub fn get_std_dev(&self) -> Option<f32> {\n- if self.count > 2 {\n- Some(self.m2 / self.count as f32)\n- } else {\n- None\n- }\n- }\n- pub fn add_sample(&mut self, sample: f32) {\n- self.count += 1;\n- let delta = sample - self.mean;\n- self.mean += delta / self.count as f32;\n- let delta2 = sample - self.mean;\n- self.m2 += delta * delta2;\n- self.last_value = Some(sample);\n- }\n- /// A hand tuned heuristic used to determine if a connection is bloated\n- pub fn is_bloated(&self) -> bool {\n- let std_dev = self.get_std_dev();\n- if let Some(std_dev) = std_dev {\n- std_dev > 1000f32\n- } else {\n- false\n- }\n- }\n- /// A hand tuned heuristic used to determine if a connection is good\n- pub fn is_good(&self) -> bool {\n- let std_dev = self.get_std_dev();\n- if let Some(std_dev) = std_dev {\n- std_dev < 100f32\n- } else {\n- false\n- }\n- }\n- pub fn reset(&mut self) {\n- self.count = 0u32;\n- self.mean = 0f32;\n- self.m2 = 0f32;\n- self.last_changed = Instant::now();\n- }\n-}\n-\n-/// Due to the way babel communicates packet loss the functions here require slightly\n-/// more data processing to get correct values. 'Reach' is a 16 second bitvector of hello/IHU\n-/// outcomes, but we're sampling every 5 seconds, in order to keep samples from interfering with\n-/// each other we take the top 5 bits and use that to compute packet loss.\n-#[derive(Clone)]\n-pub struct RunningPacketLossStats {\n- /// the number of packets lost during each 5 second sample period over the last five minutes\n- five_minute_loss: [u8; SAMPLES_IN_FIVE_MINUTES],\n- /// the 'front' of the looping five minute sample queue\n- front: usize,\n- /// Total packets observed since the system was started\n- total_packets: u32,\n- /// Total packets observed to be lost since the system was started\n- total_lost: u32,\n-}\n-\n-impl RunningPacketLossStats {\n- pub fn new() -> RunningPacketLossStats {\n- RunningPacketLossStats {\n- five_minute_loss: [0u8; SAMPLES_IN_FIVE_MINUTES],\n- front: 0usize,\n- total_packets: 0u32,\n- total_lost: 0u32,\n- }\n- }\n- pub fn add_sample(&mut self, sample: u16) {\n- // babel displays a 16 second window of hellos, so adjust this based on\n- // any changes in run rate of this function\n- let lost_packets = SAMPLE_PERIOD - get_first_n_set_bits(sample, SAMPLE_PERIOD);\n- self.total_lost += u32::from(lost_packets);\n- self.total_packets += u32::from(SAMPLE_PERIOD);\n- self.five_minute_loss[self.front] = lost_packets;\n- self.front = (self.front + 1) % SAMPLES_IN_FIVE_MINUTES;\n- }\n- pub fn get_avg(&self) -> Option<f32> {\n- if self.total_packets > 0 {\n- Some(self.total_lost as f32 / self.total_packets as f32)\n- } else {\n- None\n- }\n- }\n- pub fn get_five_min_average(&self) -> f32 {\n- let total_packets = SAMPLES_IN_FIVE_MINUTES * SAMPLE_PERIOD as usize;\n- let sum_loss: usize = self.five_minute_loss.iter().map(|i| *i as usize).sum();\n- sum_loss as f32 / total_packets as f32\n- }\n-}\n-\n-/// Counts the number of bits set to 1 in the first n bits (reading left to right so MSB first) of\n-/// the 16 bit bitvector\n-fn get_first_n_set_bits(sample: u16, n: u8) -> u8 {\n- assert!(n <= 16);\n- let mut mask = 0b1000_0000_0000_0000;\n- let mut total_set_bits = 0u8;\n- for i in ((16 - n)..16).rev() {\n- trace!(\n- \"{:#b} {:#b} >> {} {:#b}\",\n- mask,\n- sample & mask,\n- i,\n- ((sample & mask) >> i)\n- );\n- total_set_bits += ((sample & mask) >> i) as u8;\n- mask >>= 1;\n- }\n- total_set_bits\n-}\n-\n-fn has_packet_loss(sample: u16) -> bool {\n- let lost_packets = SAMPLE_PERIOD - get_first_n_set_bits(sample, SAMPLE_PERIOD);\n- lost_packets > 0\n-}\n-\n#[derive(Clone)]\npub struct NetworkMonitor {\nlatency_history: HashMap<String, RunningLatencyStats>,\n@@ -195,8 +54,10 @@ impl Supervised for NetworkMonitor {}\nimpl SystemService for NetworkMonitor {\nfn service_started(&mut self, _ctx: &mut Context<Self>) {\ninfo!(\"NetworkMonitor started\");\n+\n// if this assertion is failing you're running this slowly enough\n// that all the sample period logic is not relevent, go disable it\n+ assert_eq!(SAMPLE_PERIOD as u64, FAST_LOOP_SPEED);\nif !SAMPLE_PERIOD <= 16 {\npanic!(\"NetworkMonitor is running too slowly! Please adjust constants\");\n}\n@@ -347,9 +208,9 @@ fn observe_network(\niface: iface.to_string(),\naction: ShapingAdjustAction::ReduceSpeed,\n});\n- running_stats.last_changed = Instant::now();\n- } else if Instant::now() > running_stats.last_changed\n- && Instant::now() - running_stats.last_changed > BACK_OFF_TIME\n+ running_stats.set_last_changed();\n+ } else if Instant::now() > running_stats.last_changed()\n+ && Instant::now() - running_stats.last_changed() > BACK_OFF_TIME\n&& running_stats.is_good()\n{\ninfo!(\n@@ -361,7 +222,7 @@ fn observe_network(\niface: iface.to_string(),\naction: ShapingAdjustAction::IncreaseSpeed,\n});\n- running_stats.last_changed = Instant::now();\n+ running_stats.set_last_changed();\n} else {\ninfo!(\n\"Neighbor {} is ok with AVG {} STDDEV {} and CV {}\",\n@@ -376,8 +237,8 @@ fn observe_network(\n(_, _, _) => {}\n}\nrunning_stats.add_sample(neigh.rtt);\n- if Instant::now() > running_stats.last_changed\n- && Instant::now() - running_stats.last_changed > WINDOW_TIME\n+ if Instant::now() > running_stats.last_changed()\n+ && Instant::now() - running_stats.last_changed() > WINDOW_TIME\n{\nrunning_stats.reset();\n}\n@@ -472,38 +333,3 @@ fn mean(data: &[f32]) -> Option<f32> {\n_ => None,\n}\n}\n-\n-#[cfg(test)]\n-mod tests {\n- use super::*;\n- #[test]\n- fn test_get_first_n_set_bits() {\n- let count = get_first_n_set_bits(0b1110_0000_0000_0000, 5);\n- assert_eq!(count, 3);\n- }\n- #[test]\n- fn test_get_first_n_set_bits_limit() {\n- let count = get_first_n_set_bits(0b1111_1100_0000_0000, 5);\n- assert_eq!(count, 5);\n- }\n- #[test]\n- fn test_get_first_n_set_bits_lower_bits() {\n- let count = get_first_n_set_bits(0b1110_0000_0000_1100, 5);\n- assert_eq!(count, 3);\n- }\n- #[test]\n- fn test_get_first_n_set_bits_lower_longer_range() {\n- let count = get_first_n_set_bits(0b1110_0000_0000_1100, 16);\n- assert_eq!(count, 5);\n- }\n- #[test]\n- fn test_all_set() {\n- let count = get_first_n_set_bits(0b1111_1111_1111_1111, 16);\n- assert_eq!(count, 16);\n- }\n- #[test]\n- #[should_panic]\n- fn test_get_first_n_set_bits_impossible() {\n- let _count = get_first_n_set_bits(0b1110_0000_0000_1100, 32);\n- }\n-}\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Lift stats processing into Althea types
this way we can get statistics from anywhere and import them more
easily into for example the operator tools server |
20,244 | 25.04.2020 16:48:16 | 14,400 | 934a0b0c34d0ce5ac34c70d1ff1ff36ed1e9f162 | Bump for Beta 13 RC6 | [
{
"change_type": "MODIFY",
"old_path": "Cargo.lock",
"new_path": "Cargo.lock",
"diff": "@@ -2629,7 +2629,7 @@ dependencies = [\n[[package]]\nname = \"rita\"\n-version = \"0.5.44\"\n+version = \"0.5.45\"\ndependencies = [\n\"actix\",\n\"actix-web\",\n"
},
{
"change_type": "MODIFY",
"old_path": "rita/Cargo.toml",
"new_path": "rita/Cargo.toml",
"diff": "[package]\nname = \"rita\"\n-version = \"0.5.44\"\n+version = \"0.5.45\"\nauthors = [\"Jehan <jehan.tremback@gmail.com>\", \"Ben <wangben3@gmail.com>\"]\nbuild = \"build.rs\"\nedition = \"2018\"\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Bump for Beta 13 RC6 |
20,244 | 26.04.2020 08:28:48 | 14,400 | 4957e31c9d78718336c7fb77c5671122fb8d19a7 | Forgot to update the human readable version | [
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_common/dashboard/own_info.rs",
"new_path": "rita/src/rita_common/dashboard/own_info.rs",
"diff": "@@ -6,7 +6,7 @@ use failure::Error;\nuse num256::{Int256, Uint256};\nuse settings::RitaCommonSettings;\n-pub static READABLE_VERSION: &str = \"Beta 13 RC5\";\n+pub static READABLE_VERSION: &str = \"Beta 13 RC6\";\n#[derive(Serialize)]\npub struct OwnInfo {\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Forgot to update the human readable version |
20,244 | 26.04.2020 08:44:32 | 14,400 | 95bd87eaea0506a519a3c67d27af61aad8f26699 | Add eq to some types | [
{
"change_type": "MODIFY",
"old_path": "althea_types/src/interop.rs",
"new_path": "althea_types/src/interop.rs",
"diff": "@@ -462,7 +462,7 @@ pub struct OperatorCheckinMessage {\n/// Struct for storing peer status data for reporting to the operator tools server\n/// the goal is to give a full picture of all links in the network to the operator\n/// so we include not only the link speed but also the stats history of the link\n-#[derive(Debug, Clone, Serialize, Deserialize)]\n+#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]\npub struct NeighborStatus {\n/// the id of the neighbor\npub id: Identity,\n@@ -471,7 +471,7 @@ pub struct NeighborStatus {\n}\n/// Struct for storing user contact details\n-#[derive(Debug, Clone, Serialize, Deserialize)]\n+#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]\npub struct ContactDetails {\npub phone: Option<String>,\npub email: Option<String>,\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Add eq to some types |
20,244 | 26.04.2020 12:46:07 | 14,400 | 11bc0a6e776ce84ce237acfd9ee889f8f05da354 | Reset on speed reduction
I've found that it's very easy to pollute a connection's history
such that the std-dev will amost never reach back to normal levels.
This quickly results in a cycle of connection downgrade operations
all the way to zero, lets see how this operates instead | [
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_common/network_monitor/mod.rs",
"new_path": "rita/src/rita_common/network_monitor/mod.rs",
"diff": "@@ -208,7 +208,7 @@ fn observe_network(\niface: iface.to_string(),\naction: ShapingAdjustAction::ReduceSpeed,\n});\n- running_stats.set_last_changed();\n+ running_stats.reset();\n} else if Instant::now() > running_stats.last_changed()\n&& Instant::now() - running_stats.last_changed() > BACK_OFF_TIME\n&& running_stats.is_good()\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Reset on speed reduction
I've found that it's very easy to pollute a connection's history
such that the std-dev will amost never reach back to normal levels.
This quickly results in a cycle of connection downgrade operations
all the way to zero, lets see how this operates instead |
20,244 | 26.04.2020 20:10:50 | 14,400 | b1ed3e110c0029a23219a4556ce7c6bd1f1b1655 | Reject BS identity packets | [
{
"change_type": "MODIFY",
"old_path": "antenna_forwarding_protocol/src/lib.rs",
"new_path": "antenna_forwarding_protocol/src/lib.rs",
"diff": "@@ -491,6 +491,16 @@ impl ForwardingProtocolMessage {\n} else if packet_type > 6 {\nreturn Err(ForwardingProtocolError::WrongPacketType);\n} else if packet_len as usize + HEADER_LEN > payload.len() {\n+ // look here for strange errors with identity packets if you're trying\n+ // to make them larger\n+ if packet_type == ForwardingProtocolMessage::IDENTIFICATION_MESSAGE_TYPE\n+ && packet_len > 10000\n+ {\n+ // identity is fixed size struct, if we get a bs big packet like this\n+ // we are probably dealing with an old client that has 2 byte packet len\n+ return Err(ForwardingProtocolError::WrongPacketType);\n+ }\n+\nreturn Err(ForwardingProtocolError::SliceTooSmall {\nactual: payload.len() as u32,\nexpected: { packet_len + HEADER_LEN as u32 },\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Reject BS identity packets |
20,244 | 27.04.2020 09:00:57 | 14,400 | c3a039f6241c07dc1c1726133f444c77dc3b47cc | Return to old method for shaping down
This simply has less false positives and works better somehow.
I'll keep iterating on the upward metric. | [
{
"change_type": "MODIFY",
"old_path": "althea_types/src/monitoring.rs",
"new_path": "althea_types/src/monitoring.rs",
"diff": "@@ -73,12 +73,11 @@ impl RunningLatencyStats {\npub fn is_bloated(&self) -> bool {\nlet std_dev = self.get_std_dev();\nlet avg = self.get_avg();\n- let lowest = self.lowest;\n- match (std_dev, avg, lowest) {\n- (Some(std_dev), Some(avg), Some(lowest)) => {\n- std_dev > 1000f32 || (avg > 10f32 * lowest && avg > 20f32)\n- }\n- (_, _, _) => false,\n+ match (std_dev, avg) {\n+ // you probably don't want to touch this, I have no idea why it works so well\n+ // but almost anything else you come up with will be much worse\n+ (Some(std_dev), Some(avg)) => std_dev > 10f32 * avg,\n+ (_, _) => false,\n}\n}\n/// A hand tuned heuristic used to determine if a connection is good\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Return to old method for shaping down
This simply has less false positives and works better somehow.
I'll keep iterating on the upward metric. |
20,244 | 27.04.2020 09:03:05 | 14,400 | ca13cfe3a6c1ee7039acc3a7ce363d17ffac9ddd | Remove incorrect logging message
Since we removed the continue and other control flow operators this
is no longer correct | [
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_common/tunnel_manager/shaping.rs",
"new_path": "rita/src/rita_common/tunnel_manager/shaping.rs",
"diff": "@@ -148,10 +148,6 @@ impl Handler<ShapeMany> for TunnelManager {\n}\n}\n}\n- error!(\n- \"Could not find tunnel for banwdith limit with iface {}\",\n- iface\n- );\n}\n}\n}\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Remove incorrect logging message
Since we removed the continue and other control flow operators this
is no longer correct |
20,244 | 27.04.2020 09:23:04 | 14,400 | 0f567f21a7006df1c43ed2558f7cb566ea2c5a9a | Better comments for shaping | [
{
"change_type": "MODIFY",
"old_path": "althea_types/src/monitoring.rs",
"new_path": "althea_types/src/monitoring.rs",
"diff": "@@ -74,8 +74,23 @@ impl RunningLatencyStats {\nlet std_dev = self.get_std_dev();\nlet avg = self.get_avg();\nmatch (std_dev, avg) {\n- // you probably don't want to touch this, I have no idea why it works so well\n- // but almost anything else you come up with will be much worse\n+ // you probably don't want to touch this, yes I know it doesn't make\n+ // much sense from a stats perspective but here's why it works. Often\n+ // when links start you get a lot of transient bad states, like 2000ms\n+ // latency and the like. Because the history is reset in network_monitor after\n+ // this is triggered it doesn't immeidately trigger again. The std_dev and average\n+ // are both high and this protects connections from rapid excessive down shaping.\n+ // the other key is that as things run longer the average goes down so spikes in\n+ // std-dev are properly responded to. This is *not* a good metric for up-shaping\n+ // it's too subject to not being positive when it should be whereas those false\n+ // negatives are probably better here.\n+ //\n+ // If for some reason you feel the need to edit this you should probably not\n+ // do anything until you have more than 100 or so samples and then carve out\n+ // exceptions for conditions like avgerage latency under 10ms becuase fiber lines\n+ // are a different beast than the wireless connections. Do remember that exits can\n+ // be a lot more than 50ms away so you need to account for distant but stable connections\n+ // as well. This somehow does all of that at once, so here it stands\n(Some(std_dev), Some(avg)) => std_dev > 10f32 * avg,\n(_, _) => false,\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_common/network_monitor/mod.rs",
"new_path": "rita/src/rita_common/network_monitor/mod.rs",
"diff": "@@ -208,6 +208,8 @@ fn observe_network(\niface: iface.to_string(),\naction: ShapingAdjustAction::ReduceSpeed,\n});\n+ // go see the comment in is_bloated() before you consider\n+ // touching this, here there be dragons\nrunning_stats.reset();\n} else if Instant::now() > running_stats.last_changed()\n&& Instant::now() - running_stats.last_changed() > BACK_OFF_TIME\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Better comments for shaping |
20,244 | 27.04.2020 09:25:04 | 14,400 | e31e6f3cc9e1ded0e12b6c082bc834655e127e80 | Bump for Beta 13 RC7 | [
{
"change_type": "MODIFY",
"old_path": "Cargo.lock",
"new_path": "Cargo.lock",
"diff": "@@ -2629,7 +2629,7 @@ dependencies = [\n[[package]]\nname = \"rita\"\n-version = \"0.5.45\"\n+version = \"0.5.46\"\ndependencies = [\n\"actix\",\n\"actix-web\",\n"
},
{
"change_type": "MODIFY",
"old_path": "rita/Cargo.toml",
"new_path": "rita/Cargo.toml",
"diff": "[package]\nname = \"rita\"\n-version = \"0.5.45\"\n+version = \"0.5.46\"\nauthors = [\"Jehan <jehan.tremback@gmail.com>\", \"Ben <wangben3@gmail.com>\"]\nbuild = \"build.rs\"\nedition = \"2018\"\n"
},
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_common/dashboard/own_info.rs",
"new_path": "rita/src/rita_common/dashboard/own_info.rs",
"diff": "@@ -6,7 +6,7 @@ use failure::Error;\nuse num256::{Int256, Uint256};\nuse settings::RitaCommonSettings;\n-pub static READABLE_VERSION: &str = \"Beta 13 RC6\";\n+pub static READABLE_VERSION: &str = \"Beta 13 RC7\";\n#[derive(Serialize)]\npub struct OwnInfo {\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Bump for Beta 13 RC7 |
20,244 | 27.04.2020 18:34:48 | 14,400 | 6cf306a2a8d1781440dcc020913bc3b5e32cb322 | Advertise light_client_fee
Right now we use light_client_fee in billing but do not advertise it to phones
this will break things when users actually try and buy bandwidth and the router
considers it an underpayment | [
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_client/light_client_manager/mod.rs",
"new_path": "rita/src/rita_client/light_client_manager/mod.rs",
"diff": "@@ -169,7 +169,8 @@ pub fn light_client_hello_response(\nwg_port: tunnel.listen_port,\nhave_tunnel: Some(have_tunnel),\ntunnel_address: light_client_address,\n- price: SETTING.get_payment().local_fee as u128 + exit_dest_price,\n+ price: SETTING.get_payment().light_client_fee as u128\n+ + exit_dest_price,\n};\n// Two bools -> 4 state truth table, in 3 of\n// those states we need to re-add these rules\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Advertise light_client_fee
Right now we use light_client_fee in billing but do not advertise it to phones
this will break things when users actually try and buy bandwidth and the router
considers it an underpayment |
20,244 | 28.04.2020 07:15:06 | 14,400 | ef71992410bd058dd91539b58cb979844e130d84 | Open should use the tunnel speed | [
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_common/tunnel_manager/mod.rs",
"new_path": "rita/src/rita_common/tunnel_manager/mod.rs",
"diff": "@@ -199,7 +199,7 @@ impl Tunnel {\n&mut SETTING.get_network_mut().default_route,\nlight_client_details,\n)?;\n- KI.set_codel_shaping(&self.iface_name, None)\n+ KI.set_codel_shaping(&self.iface_name, self.speed_limit)\n}\n/// Register this tunnel into Babel monitor\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Open should use the tunnel speed |
20,244 | 02.05.2020 16:50:14 | 14,400 | 13a38bd381dfb9782b36f885cc6e36826750056f | Wait on failure
If we failed to connect to the antenna forwarding server we should
wait the timeout before trying again. Otherwise we will overwhelm the
server eventually | [
{
"change_type": "MODIFY",
"old_path": "antenna_forwarding_client/src/lib.rs",
"new_path": "antenna_forwarding_client/src/lib.rs",
"diff": "@@ -121,7 +121,6 @@ pub fn start_antenna_forwarding_proxy<S: 'static + std::marker::Send + ::std::ha\n}\nErr(e) => {\nerror!(\"Failed to read message from server with {:?}\", e);\n- continue;\n}\n}\n}\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Wait on failure
If we failed to connect to the antenna forwarding server we should
wait the timeout before trying again. Otherwise we will overwhelm the
server eventually |
20,244 | 08.05.2020 16:50:44 | 14,400 | 9e1539ab1549dcac8aa24a7b28a59d3a44c830c2 | Handle withdraws that move the DAI exchange rate
Larger withdraws would always fail at the last step of sending over
the Eth. This solves that case. | [
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_common/token_bridge/mod.rs",
"new_path": "rita/src/rita_common/token_bridge/mod.rs",
"diff": "@@ -458,7 +458,6 @@ fn xdai_bridge(state: State, bridge: &TokenBridge) {\n})),\n}));\n} else {\n- let amount_a = amount.clone();\nArbiter::spawn(\nbridge\n.get_dai_balance(bridge.own_address)\n@@ -467,18 +466,44 @@ fn xdai_bridge(state: State, bridge: &TokenBridge) {\nbridge.dai_to_eth_price(DAI_WEI_CENT.into()),\nbridge.eth_web3.eth_gas_price())\n.and_then(move |(our_dai_balance, our_eth_balance, wei_per_dollar, wei_per_cent, eth_gas_price)| {\n- info!(\"withdraw state is {} dai {} eth {} wei per dollar\", our_dai_balance, our_eth_balance, wei_per_dollar);\n- let transferred_eth = eth_equal(amount_a.clone(), wei_per_cent);\n+ info!(\"bridge withdraw state is {} dai {} eth {} wei per dollar\", our_dai_balance, our_eth_balance, wei_per_dollar);\n+ let transferred_eth = eth_equal(amount.clone(), wei_per_cent);\n+\n+ // the amount we must leave behind to continue to pay for eth operations\n+ let reserve = wei_per_dollar.clone() * reserve_amount.into();\n+ // the reserve value with some margin, to deal with exchange rate fluctuations\n+ let reserve_with_margin = reserve.clone() * 10u32.into();\n+\n+ // this code handles the case where you are withdrawing a large amount and\n+ // the exchange rate meaningfully goes down during your exchange and withdraw.\n+ // What occurs in this case is that your new eth balance is now no longer as much\n+ // as your withdraw amount. For small withdraws you A) don't move the price much\n+ // and B) the reserve amount can make up small shortfalls. For large withdraws you\n+ // may lose something like 1/2 dollars out of $500+ but then the eth would sit around\n+ // not enough to finish the withdraw. So what we do instead is withdraw what we can\n+ // over the reserve amount. If the balance is less than $10 (10x the current reserve)\n+ // then we can be pretty sure it at least wasn't us that moved the price that much\n+ let transferred_eth = if our_eth_balance < transferred_eth &&\n+ our_eth_balance.clone() / wei_per_dollar.clone() > reserve_with_margin {\n+ if withdraw_all {\n+ our_eth_balance.clone()\n+ } else {\n+ our_eth_balance.clone() - reserve\n+ }\n+ } else {\n+ transferred_eth\n+ };\n+\n// Money has come over the bridge\nif our_dai_balance >= amount {\nTokenBridge::from_registry().do_send(DetailedStateChange(DetailedBridgeState::DaiToEth{\n- amount_of_dai: amount_a.clone(),\n+ amount_of_dai: amount.clone(),\nwei_per_dollar\n}));\nBox::new(\nbridge\n// Then it converts to eth\n- .dai_to_eth_swap(amount, UNISWAP_TIMEOUT).and_then(|_| Ok(()))\n+ .dai_to_eth_swap(amount, UNISWAP_TIMEOUT).and_then(|_amount_actually_exchanged| Ok(()))\n)\nas Box<dyn Future<Item = (), Error = Error>>\n// all other steps are done and the eth is sitting and waiting\n@@ -506,7 +531,7 @@ fn xdai_bridge(state: State, bridge: &TokenBridge) {\n.and_then(move |_| {\ninfo!(\"Issued an eth transfer for withdraw! Now complete!\");\n// we only exit the withdraw state on success or timeout\n- TokenBridge::from_registry().do_send(StateChange(State::Ready {former_state: Some(Box::new(State::Withdrawing{to, amount: amount_a, timestamp, withdraw_all}))}));\n+ TokenBridge::from_registry().do_send(StateChange(State::Ready {former_state: Some(Box::new(State::Withdrawing{to, amount: amount, timestamp, withdraw_all}))}));\nOk(())}))\n} else {\ninfo!(\"withdraw is waiting on bridge\");\n@@ -551,10 +576,9 @@ impl Handler<Withdraw> for TokenBridge {\nlet amount = msg.amount.clone();\nlet withdraw_all = msg.withdraw_all;\n- trace!(\n- \"Withdraw handler amount {} withdraw_all {}\",\n- amount,\n- withdraw_all\n+ info!(\n+ \"bridge withdraw handler amount {} withdraw_all {}\",\n+ amount, withdraw_all\n);\nlet bridge = self.bridge.clone();\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Handle withdraws that move the DAI exchange rate
Larger withdraws would always fail at the last step of sending over
the Eth. This solves that case. |
20,244 | 10.05.2020 07:08:36 | 14,400 | 24f4da78a613960668e923a2954514dde56f8576 | Improve settings merge logging | [
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_client/operator_update/mod.rs",
"new_path": "rita/src/rita_client/operator_update/mod.rs",
"diff": "@@ -252,6 +252,7 @@ fn handle_release_feed_update(val: Option<String>) {\n/// Merges an arbitrary settings string, after first filtering for several\n/// forbidden values\nfn merge_settings_safely(new_settings: Value) {\n+ trace!(\"Got new settings from server {:?}\", new_settings);\n// merge in arbitrary setting change string if it's not blank\nif new_settings != \"\" {\nif let Value::Object(map) = new_settings.clone() {\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Improve settings merge logging |
20,244 | 10.05.2020 07:08:59 | 14,400 | 840fb778b6ce0a85224e612b1cff6f3dc2b95253 | Remove forced heartbeat address | [
{
"change_type": "MODIFY",
"old_path": "rita/src/client.rs",
"new_path": "rita/src/client.rs",
"diff": "@@ -208,12 +208,6 @@ fn main() {\noperator.use_operator_price = dao.use_oracle_price;\n}\n}\n- // some devices are on beta 12 and therefore have the old default heartbeat\n- // url which is not correct in beta 13, remove this in beta 14\n- {\n- let mut log = SETTING.get_log_mut();\n- log.heartbeat_url = \"operator.althea.net:33333\".to_string();\n- }\n// On Linux static builds we need to probe ssl certs path to be able to\n// do TLS stuff.\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Remove forced heartbeat address |
20,244 | 10.05.2020 07:16:03 | 14,400 | 123f91b91b347e2354c1517e74730f7f74468d3d | Use jemalloc as the Exit allocator
Much faster performance in highly multithreaded scenarios | [
{
"change_type": "MODIFY",
"old_path": "Cargo.lock",
"new_path": "Cargo.lock",
"diff": "@@ -994,6 +994,12 @@ version = \"0.1.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b\"\n+[[package]]\n+name = \"fs_extra\"\n+version = \"1.1.0\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"5f2a4a2034423744d2cc7ca2068453168dcdb82c438419e639a26bd87839c674\"\n+\n[[package]]\nname = \"fuchsia-cprng\"\nversion = \"0.1.1\"\n@@ -1490,6 +1496,27 @@ version = \"0.4.5\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"b8b7a7c0c47db5545ed3fef7468ee7bb5b74691498139e4b3f6a20685dc6dd8e\"\n+[[package]]\n+name = \"jemalloc-sys\"\n+version = \"0.3.2\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"0d3b9f3f5c9b31aa0f5ed3260385ac205db665baa41d49bb8338008ae94ede45\"\n+dependencies = [\n+ \"cc\",\n+ \"fs_extra\",\n+ \"libc\",\n+]\n+\n+[[package]]\n+name = \"jemallocator\"\n+version = \"0.3.2\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"43ae63fcfc45e99ab3d1b29a46782ad679e98436c3169d15a167a1108a724b69\"\n+dependencies = [\n+ \"jemalloc-sys\",\n+ \"libc\",\n+]\n+\n[[package]]\nname = \"js-sys\"\nversion = \"0.3.37\"\n@@ -2659,6 +2686,7 @@ dependencies = [\n\"handlebars\",\n\"hex-literal\",\n\"ipnetwork 0.14.0\",\n+ \"jemallocator\",\n\"lazy_static\",\n\"lettre\",\n\"lettre_email\",\n"
},
{
"change_type": "MODIFY",
"old_path": "rita/Cargo.toml",
"new_path": "rita/Cargo.toml",
"diff": "@@ -68,6 +68,7 @@ sodiumoxide = \"0.2\"\ncompressed_log = \"0.2\"\nflate2 = { version = \"1.0\", features = [\"rust_backend\"], default-features = false }\nreqwest = { version = \"0.10\", features = [\"blocking\", \"json\"] }\n+jemallocator = \"0.3\"\n[dependencies.regex]\nversion = \"1.3\"\n"
},
{
"change_type": "MODIFY",
"old_path": "rita/src/exit.rs",
"new_path": "rita/src/exit.rs",
"diff": "#![allow(clippy::pedantic)]\n#![forbid(unsafe_code)]\n+use jemallocator::Jemalloc;\n+#[global_allocator]\n+static GLOBAL: Jemalloc = Jemalloc;\n+\n#[macro_use]\nextern crate failure;\n#[macro_use]\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Use jemalloc as the Exit allocator
Much faster performance in highly multithreaded scenarios |
20,244 | 10.05.2020 21:24:27 | 14,400 | f7c2336d81a7647f148d7f2cf1c89b9f18ba0b50 | Update shaper configuration
Having the shaper config just littered out in the main network settings
isn't really appropriate as it becomes a more essential part of our system.
Also it creates complexity where there doesn't need to be any when it comes
to the way updates from the operator dash function. | [
{
"change_type": "MODIFY",
"old_path": "althea_types/src/interop.rs",
"new_path": "althea_types/src/interop.rs",
"diff": "@@ -424,16 +424,28 @@ pub struct OperatorUpdateMessage {\n/// An action the operator wants to take to affect this router, examples may include reset\n/// password or change the wifi ssid\npub operator_action: Option<OperatorAction>,\n+ /// being phased out, see shaper settings TODO Remove in Beta 15\n+ pub max_shaper_speed: Option<usize>,\n+ /// being phased out, see shaper settings TODO Remove in Beta 15\n+ pub min_shaper_speed: Option<usize>,\n+ /// settings for the device bandwidth shaper\n+ pub shaper_settings: ShaperSettings,\n+}\n+\n+/// Settings for the bandwidth shaper\n+#[derive(Debug, Clone, Copy, Serialize, Deserialize, Hash, Eq, PartialEq)]\n+pub struct ShaperSettings {\n+ pub enabled: bool,\n/// The speed the bandwidth shaper will start at, keep in mind this is not the maximum device\n/// speed as all interfaces start at 'unlmited' this is instead the speed the shaper will deploy\n/// when it detects problems on the interface and a speed it will not go above when it's increasing\n/// the speed after the problem is gone\n- pub max_shaper_speed: Option<usize>,\n+ pub max_speed: usize,\n/// this is the minimum speed the shaper will assign to an interface under any circumstances\n/// when the first bad behavior on a link is experienced the value goes from 'unlimited' to\n/// max_shaper_speed and heads downward from there. Set this value based on what you think the\n/// worst realistic performance of any link in the network may be.\n- pub min_shaper_speed: Option<usize>,\n+ pub min_speed: usize,\n}\n/// The message we send to the operator server to checkin, this allows us to customize\n"
},
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_client/operator_update/mod.rs",
"new_path": "rita/src/rita_client/operator_update/mod.rs",
"diff": "@@ -203,12 +203,7 @@ fn checkin() {\n}\nlet mut network = SETTING.get_network_mut();\n- if let Some(new_speed) = new_settings.max_shaper_speed {\n- network.starting_bandwidth_limit = new_speed;\n- }\n- if let Some(new_speed) = new_settings.min_shaper_speed {\n- network.minimum_bandwidth_limit = new_speed;\n- }\n+ network.shaper_settings = new_settings.shaper_settings;\ndrop(network);\ntrace!(\"Successfully completed OperatorUpdate\");\n"
},
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_common/tunnel_manager/shaping.rs",
"new_path": "rita/src/rita_common/tunnel_manager/shaping.rs",
"diff": "@@ -58,9 +58,9 @@ impl Handler<ShapeMany> for TunnelManager {\nfn handle(&mut self, msg: ShapeMany, _: &mut Context<Self>) -> Self::Result {\nlet network_settings = SETTING.get_network();\n- let minimum_bandwidth_limit = network_settings.minimum_bandwidth_limit;\n- let starting_bandwidth_limit = network_settings.starting_bandwidth_limit;\n- let bandwidth_limit_enabled = network_settings.bandwidth_limit_enabled;\n+ let minimum_bandwidth_limit = network_settings.shaper_settings.min_speed;\n+ let starting_bandwidth_limit = network_settings.shaper_settings.max_speed;\n+ let bandwidth_limit_enabled = network_settings.shaper_settings.enabled;\ndrop(network_settings);\n// removes shaping without requiring a restart if the flag is set or\n"
},
{
"change_type": "MODIFY",
"old_path": "settings/src/network.rs",
"new_path": "settings/src/network.rs",
"diff": "+use althea_types::ShaperSettings;\nuse std::collections::HashSet;\nuse std::net::{IpAddr, Ipv4Addr, Ipv6Addr};\n@@ -21,16 +22,12 @@ fn default_usage_tracker_file() -> String {\n\"/etc/rita-usage-tracker.json\".to_string()\n}\n-fn default_bandwidth_limit_enabled() -> bool {\n- true\n+fn default_shaper_settings() -> ShaperSettings {\n+ ShaperSettings {\n+ enabled: true,\n+ max_speed: 10000,\n+ min_speed: 50,\n}\n-\n-fn default_minimum_bandwidth_limit() -> usize {\n- 50\n-}\n-\n-fn default_starting_bandwidth_limit() -> usize {\n- 10_000\n}\nfn default_light_client_hello_port() -> u16 {\n@@ -118,23 +115,14 @@ pub struct NetworkSettings {\n/// Determines if this device will try and shape interface speeds when latency\n/// spikes are detected. You probably don't want to have this on in networks\n/// where there is significant jitter that's not caused by traffic load\n- #[serde(default = \"default_bandwidth_limit_enabled\")]\n- pub bandwidth_limit_enabled: bool,\n- /// The minimum to which this device will shape an interface\n- #[serde(default = \"default_minimum_bandwidth_limit\")]\n- pub minimum_bandwidth_limit: usize,\n- /// The starting value for banwidth interface shaping, should be equal to or greater than\n- /// the maximum bandwidth of the fastest interface of the device.\n- #[serde(default = \"default_starting_bandwidth_limit\")]\n- pub starting_bandwidth_limit: usize,\n+ #[serde(default = \"default_shaper_settings\")]\n+ pub shaper_settings: ShaperSettings,\n}\nimpl Default for NetworkSettings {\nfn default() -> Self {\nNetworkSettings {\n- bandwidth_limit_enabled: default_bandwidth_limit_enabled(),\n- minimum_bandwidth_limit: default_minimum_bandwidth_limit(),\n- starting_bandwidth_limit: default_starting_bandwidth_limit(),\n+ shaper_settings: default_shaper_settings(),\nbackup_created: false,\nmetric_factor: default_metric_factor(),\nmesh_ip: None,\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Update shaper configuration
Having the shaper config just littered out in the main network settings
isn't really appropriate as it becomes a more essential part of our system.
Also it creates complexity where there doesn't need to be any when it comes
to the way updates from the operator dash function. |
20,244 | 10.05.2020 21:37:51 | 14,400 | 207a0d2f34e4d53422985fbb5c4d54ec5106c8e5 | Update external reference even if the shaper isn't enabled | [
{
"change_type": "MODIFY",
"old_path": "rita/src/rita_common/tunnel_manager/shaping.rs",
"new_path": "rita/src/rita_common/tunnel_manager/shaping.rs",
"diff": "@@ -21,7 +21,7 @@ lazy_static! {\n/// A cross thread accessible object representing the shaping level of a given interface, this is not perfect as it's\n/// a mapping by identity, meaning that if a given id has multiple tunnels using different shaped speeds it may not\n/// paint the full picture, that being said my observation is that this never seems to be the case, I can of course be wrong\n-/// TODO we only ever interact with tunnel speed shaping here, we should consdier moving this subcomponent to locked data\n+/// TODO we only ever interact with tunnel speed shaping here, we should consider moving this subcomponent to locked data\n/// rather than actor data as part of the actix-removal refactor\n#[allow(dead_code)]\npub fn get_shaping_status() -> HashMap<Identity, Option<usize>> {\n@@ -63,21 +63,6 @@ impl Handler<ShapeMany> for TunnelManager {\nlet bandwidth_limit_enabled = network_settings.shaper_settings.enabled;\ndrop(network_settings);\n- // removes shaping without requiring a restart if the flag is set or\n- // if it's set in the settings\n- if !bandwidth_limit_enabled || RESET_FLAG.load(Ordering::Relaxed) {\n- for (_id, tunnel_list) in self.tunnels.iter_mut() {\n- for tunnel in tunnel_list {\n- if tunnel.speed_limit != None {\n- set_shaping_or_error(&tunnel.iface_name, None);\n- tunnel.speed_limit = None;\n- }\n- }\n- }\n- RESET_FLAG.store(false, Ordering::Relaxed);\n- return;\n- }\n-\n// get the lowest speed from each set of tunnels by\n// id and store that for external reference\nlet mut external_list = INTERFACE_MBPS.write().unwrap();\n@@ -99,6 +84,21 @@ impl Handler<ShapeMany> for TunnelManager {\n}\ndrop(external_list);\n+ // removes shaping without requiring a restart if the flag is set or\n+ // if it's set in the settings\n+ if !bandwidth_limit_enabled || RESET_FLAG.load(Ordering::Relaxed) {\n+ for (_id, tunnel_list) in self.tunnels.iter_mut() {\n+ for tunnel in tunnel_list {\n+ if tunnel.speed_limit != None {\n+ set_shaping_or_error(&tunnel.iface_name, None);\n+ tunnel.speed_limit = None;\n+ }\n+ }\n+ }\n+ RESET_FLAG.store(false, Ordering::Relaxed);\n+ return;\n+ }\n+\nfor shaping_command in msg.to_shape {\nlet action = shaping_command.action;\nlet iface = shaping_command.iface;\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Update external reference even if the shaper isn't enabled |
20,244 | 11.05.2020 07:44:03 | 14,400 | b0d745b233549fb00ed73fa3054571a1ce052494 | Default for ShaperSettings | [
{
"change_type": "MODIFY",
"old_path": "althea_types/src/interop.rs",
"new_path": "althea_types/src/interop.rs",
"diff": "@@ -429,6 +429,7 @@ pub struct OperatorUpdateMessage {\n/// being phased out, see shaper settings TODO Remove in Beta 15\npub min_shaper_speed: Option<usize>,\n/// settings for the device bandwidth shaper\n+ #[serde(default=\"default_shaper_settings\")]\npub shaper_settings: ShaperSettings,\n}\n@@ -448,6 +449,14 @@ pub struct ShaperSettings {\npub min_speed: usize,\n}\n+fn default_shaper_settings() -> ShaperSettings {\n+ ShaperSettings {\n+ max_speed: 1000,\n+ min_speed: 50,\n+ enabled: true,\n+ }\n+}\n+\n/// The message we send to the operator server to checkin, this allows us to customize\n/// the operator checkin response to the device based on it's network and any commands\n/// the operator may wish to send\n"
}
] | Rust | Apache License 2.0 | althea-net/althea_rs | Default for ShaperSettings |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.