Code reformatting.

pull/133/head
Revertron 3 years ago
parent 2d12fd0447
commit d513c29cfe

@ -0,0 +1,13 @@
brace_style = "PreferSameLine"
comment_width = 140
fn_args_layout = "Compressed"
group_imports = "StdExternalCrate"
imports_granularity = "Module"
max_width = 140
newline_style = "Unix"
reorder_impl_items = true
trailing_comma = "Never"
unstable_features = true
use_field_init_shorthand = true
use_small_heuristics = "Max"
where_single_line = true

@ -2,11 +2,13 @@ extern crate serde;
extern crate serde_json; extern crate serde_json;
use std::fmt::Debug; use std::fmt::Debug;
use serde::{Serialize, Deserialize};
use crate::bytes::Bytes; use serde::{Deserialize, Serialize};
use crate::Transaction;
use crate::blockchain::hash_utils::{hash_difficulty, key_hash_difficulty}; use crate::blockchain::hash_utils::{hash_difficulty, key_hash_difficulty};
use crate::blockchain::transaction::TransactionType; use crate::blockchain::transaction::TransactionType;
use crate::bytes::Bytes;
use crate::Transaction;
#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)] #[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
pub struct Block { pub struct Block {
@ -25,7 +27,7 @@ pub struct Block {
#[serde(default, skip_serializing_if = "Bytes::is_zero")] #[serde(default, skip_serializing_if = "Bytes::is_zero")]
pub signature: Bytes, pub signature: Bytes,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub transaction: Option<Transaction>, pub transaction: Option<Transaction>
} }
impl Block { impl Block {

@ -10,15 +10,15 @@ use chrono::Utc;
use log::{debug, error, info, trace, warn}; use log::{debug, error, info, trace, warn};
use sqlite::{Connection, State, Statement}; use sqlite::{Connection, State, Statement};
use crate::{Block, Bytes, check_domain, get_domain_zone, is_yggdrasil_record, Keystore, Transaction};
use crate::blockchain::hash_utils::*; use crate::blockchain::hash_utils::*;
use crate::blockchain::transaction::DomainData; use crate::blockchain::transaction::DomainData;
use crate::blockchain::types::{BlockQuality, MineResult, Options, ZoneData};
use crate::blockchain::types::BlockQuality::*; use crate::blockchain::types::BlockQuality::*;
use crate::blockchain::types::MineResult::*; use crate::blockchain::types::MineResult::*;
use crate::blockchain::types::{BlockQuality, MineResult, Options, ZoneData};
use crate::commons::constants::*; use crate::commons::constants::*;
use crate::keystore::check_public_key_strength; use crate::keystore::check_public_key_strength;
use crate::settings::Settings; use crate::settings::Settings;
use crate::{check_domain, get_domain_zone, is_yggdrasil_record, Block, Bytes, Keystore, Transaction};
use rand::prelude::IteratorRandom; use rand::prelude::IteratorRandom;
const TEMP_DB_NAME: &str = ":memory:"; const TEMP_DB_NAME: &str = ":memory:";
@ -43,7 +43,7 @@ const SQL_GET_USERS_COUNT: &str = "SELECT count(DISTINCT pub_key) FROM blocks;";
const SQL_GET_OPTIONS: &str = "SELECT * FROM options;"; const SQL_GET_OPTIONS: &str = "SELECT * FROM options;";
/// Max possible block index /// Max possible block index
const MAX:u64 = i64::MAX as u64; const MAX: u64 = i64::MAX as u64;
pub struct Chain { pub struct Chain {
origin: Bytes, origin: Bytes,
@ -52,7 +52,7 @@ pub struct Chain {
max_height: u64, max_height: u64,
db: Connection, db: Connection,
zones: Vec<ZoneData>, zones: Vec<ZoneData>,
signers: RefCell<SignersCache>, signers: RefCell<SignersCache>
} }
impl Chain { impl Chain {
@ -104,8 +104,8 @@ impl Chain {
last_block = self.get_block(start - 1); last_block = self.get_block(start - 1);
if let Some(last) = &last_block { if let Some(last) = &last_block {
last_full_block = match &last.transaction { last_full_block = match &last.transaction {
None => { self.get_last_full_block(last.index, None) } None => self.get_last_full_block(last.index, None),
Some(_) => { Some(last.clone()) } Some(_) => Some(last.clone())
}; };
} }
} }
@ -271,8 +271,10 @@ impl Chain {
} }
let block = match self.last_full_block { let block = match self.last_full_block {
None => { return None; } None => {
Some(ref block) => { block.clone() } return None;
}
Some(ref block) => block.clone()
}; };
// TODO maybe make some config option to mine signing blocks above? // TODO maybe make some config option to mine signing blocks above?
let sign_count = self.get_height() - block.index; let sign_count = self.get_height() - block.index;
@ -293,7 +295,8 @@ impl Chain {
let signers: HashSet<Bytes> = self.get_block_signers(&block).into_iter().collect(); let signers: HashSet<Bytes> = self.get_block_signers(&block).into_iter().collect();
let mut rng = rand::thread_rng(); let mut rng = rand::thread_rng();
let keystore = keys.iter() let keystore = keys
.iter()
.filter(|keystore| signers.contains(&keystore.get_public())) .filter(|keystore| signers.contains(&keystore.get_public()))
.filter(|keystore| { .filter(|keystore| {
for index in block.index..=self.get_height() { for index in block.index..=self.get_height() {
@ -304,7 +307,8 @@ impl Chain {
} }
} }
true true
}).choose(&mut rng); })
.choose(&mut rng);
if let Some(keystore) = keystore { if let Some(keystore) = keystore {
info!("We have an honor to mine signing block!"); info!("We have an honor to mine signing block!");
let mut block = Block::new(None, Bytes::default(), last_hash, SIGNER_DIFFICULTY); let mut block = Block::new(None, Bytes::default(), last_hash, SIGNER_DIFFICULTY);
@ -356,7 +360,9 @@ impl Chain {
statement.bind(5, block.random as i64)?; statement.bind(5, block.random as i64)?;
statement.bind(6, block.nonce as i64)?; statement.bind(6, block.nonce as i64)?;
match &block.transaction { match &block.transaction {
None => { statement.bind(7, "")?; } None => {
statement.bind(7, "")?;
}
Some(transaction) => { Some(transaction) => {
statement.bind(7, transaction.to_string().as_str())?; statement.bind(7, transaction.to_string().as_str())?;
} }
@ -417,7 +423,9 @@ impl Chain {
if let Some(block) = &self.last_full_block { if let Some(block) = &self.last_full_block {
if block.index < before { if block.index < before {
match pub_key { match pub_key {
None => { return Some(block.clone()); } None => {
return Some(block.clone());
}
Some(key) => { Some(key) => {
if block.pub_key.deref().eq(key) { if block.pub_key.deref().eq(key) {
return Some(block.clone()); return Some(block.clone());
@ -500,7 +508,7 @@ impl Chain {
let zones: Vec<_> = zones_text.split("\n").collect(); let zones: Vec<_> = zones_text.split("\n").collect();
for zone in zones { for zone in zones {
let yggdrasil = zone == "ygg" || zone == "anon"; let yggdrasil = zone == "ygg" || zone == "anon";
result.push(ZoneData {name: zone.to_owned(), yggdrasil}) result.push(ZoneData { name: zone.to_owned(), yggdrasil })
} }
result result
} }
@ -553,7 +561,7 @@ impl Chain {
let new_id = !self.is_domain_in_blockchain(height, &identity_hash); let new_id = !self.is_domain_in_blockchain(height, &identity_hash);
let time = last.timestamp + NEW_DOMAINS_INTERVAL - Utc::now().timestamp(); let time = last.timestamp + NEW_DOMAINS_INTERVAL - Utc::now().timestamp();
if new_id && time > 0 { if new_id && time > 0 {
return Cooldown { time } return Cooldown { time };
} }
} }
@ -598,8 +606,8 @@ impl Chain {
pub fn get_domain_info(&self, domain: &str) -> Option<String> { pub fn get_domain_info(&self, domain: &str) -> Option<String> {
match self.get_domain_transaction(domain) { match self.get_domain_transaction(domain) {
None => { None } None => None,
Some(transaction) => { Some(transaction.data) } Some(transaction) => Some(transaction.data)
} }
} }
@ -668,30 +676,28 @@ impl Chain {
pub fn get_height(&self) -> u64 { pub fn get_height(&self) -> u64 {
match self.last_block { match self.last_block {
None => { 0u64 } None => 0u64,
Some(ref block) => { Some(ref block) => block.index
block.index
}
} }
} }
pub fn get_last_hash(&self) -> Bytes { pub fn get_last_hash(&self) -> Bytes {
match &self.last_block { match &self.last_block {
None => { Bytes::default() } None => Bytes::default(),
Some(block) => { block.hash.clone() } Some(block) => block.hash.clone()
} }
} }
pub fn get_soa_serial(&self) -> u32 { pub fn get_soa_serial(&self) -> u32 {
match &self.last_full_block { match &self.last_full_block {
None => { 0 } None => 0,
Some(block) => { block.timestamp as u32 } Some(block) => block.timestamp as u32
} }
} }
pub fn next_allowed_full_block(&self) -> u64 { pub fn next_allowed_full_block(&self) -> u64 {
match self.last_full_block { match self.last_full_block {
None => { self.get_height() + 1 } None => self.get_height() + 1,
Some(ref block) => { Some(ref block) => {
if block.index < BLOCK_SIGNERS_START { if block.index < BLOCK_SIGNERS_START {
self.get_height() + 1 self.get_height() + 1
@ -743,7 +749,7 @@ impl Chain {
SIGNER_DIFFICULTY SIGNER_DIFFICULTY
} }
} }
Some(t) => { self.get_difficulty_for_transaction(&t) } Some(t) => self.get_difficulty_for_transaction(&t)
}; };
if block.difficulty < difficulty { if block.difficulty < difficulty {
warn!("Block difficulty is lower than needed"); warn!("Block difficulty is lower than needed");
@ -776,8 +782,8 @@ impl Chain {
if let Some(transaction) = &block.transaction { if let Some(transaction) = &block.transaction {
let current_height = match last_block { let current_height = match last_block {
None => { 0 } None => 0,
Some(block) => { block.index } Some(block) => block.index
}; };
// If this domain is available to this public key // If this domain is available to this public key
if !self.is_id_available(current_height, &transaction.identity, &block.pub_key) { if !self.is_id_available(current_height, &transaction.identity, &block.pub_key) {
@ -921,17 +927,15 @@ impl Chain {
match transaction.class.as_ref() { match transaction.class.as_ref() {
CLASS_DOMAIN => { CLASS_DOMAIN => {
return match serde_json::from_str::<DomainData>(&transaction.data) { return match serde_json::from_str::<DomainData>(&transaction.data) {
Ok(_) => { Ok(_) => DOMAIN_DIFFICULTY,
DOMAIN_DIFFICULTY
}
Err(_) => { Err(_) => {
warn!("Error parsing DomainData from {:?}", transaction); warn!("Error parsing DomainData from {:?}", transaction);
u32::MAX u32::MAX
} }
} }
} }
CLASS_ORIGIN => { ORIGIN_DIFFICULTY } CLASS_ORIGIN => ORIGIN_DIFFICULTY,
_ => { u32::MAX } _ => u32::MAX
} }
} }
@ -1009,11 +1013,11 @@ impl SignersCache {
#[cfg(test)] #[cfg(test)]
pub mod tests { pub mod tests {
use log::LevelFilter; use log::LevelFilter;
use simplelog::{ColorChoice, ConfigBuilder, TerminalMode, TermLogger};
#[allow(unused_imports)] #[allow(unused_imports)]
use log::{debug, error, info, trace, warn}; use log::{debug, error, info, trace, warn};
use simplelog::{ColorChoice, ConfigBuilder, TermLogger, TerminalMode};
use crate::{Chain, Settings, Block}; use crate::{Block, Chain, Settings};
fn init_logger() { fn init_logger() {
let config = ConfigBuilder::new() let config = ConfigBuilder::new()

@ -1,10 +1,12 @@
use crate::Context; use std::sync::{Arc, Mutex};
use std::sync::{Mutex, Arc};
use crate::dns::filter::DnsFilter;
use crate::dns::protocol::{DnsPacket, QueryType, DnsRecord, DnsQuestion, ResultCode, TransientTtl};
#[allow(unused_imports)] #[allow(unused_imports)]
use log::{trace, debug, info, warn, error}; use log::{debug, error, info, trace, warn};
use crate::blockchain::transaction::DomainData; use crate::blockchain::transaction::DomainData;
use crate::dns::filter::DnsFilter;
use crate::dns::protocol::{DnsPacket, DnsQuestion, DnsRecord, QueryType, ResultCode, TransientTtl};
use crate::Context;
pub struct BlockchainFilter { pub struct BlockchainFilter {
context: Arc<Mutex<Context>> context: Arc<Mutex<Context>>
@ -16,8 +18,8 @@ impl BlockchainFilter {
} }
} }
const NAME_SERVER: & str = "ns.alfis.name"; const NAME_SERVER: &str = "ns.alfis.name";
const SERVER_ADMIN: & str = "admin.alfis.name"; const SERVER_ADMIN: &str = "admin.alfis.name";
impl DnsFilter for BlockchainFilter { impl DnsFilter for BlockchainFilter {
fn lookup(&self, qname: &str, qtype: QueryType) -> Option<DnsPacket> { fn lookup(&self, qname: &str, qtype: QueryType) -> Option<DnsPacket> {
@ -64,8 +66,10 @@ impl DnsFilter for BlockchainFilter {
Some(data) => { Some(data) => {
trace!("Found data for domain {}", &search); trace!("Found data for domain {}", &search);
let mut data: DomainData = match serde_json::from_str(&data) { let mut data: DomainData = match serde_json::from_str(&data) {
Err(_) => { return None; } Err(_) => {
Ok(data) => { data } return None;
}
Ok(data) => data
}; };
let mut answers: Vec<DnsRecord> = Vec::new(); let mut answers: Vec<DnsRecord> = Vec::new();
let a_record = qtype == QueryType::A || qtype == QueryType::AAAA; let a_record = qtype == QueryType::A || qtype == QueryType::AAAA;
@ -153,11 +157,7 @@ impl DnsFilter for BlockchainFilter {
for answer in answers { for answer in answers {
packet.answers.push(answer); packet.answers.push(answer);
} }
packet.authorities.push( DnsRecord::NS { packet.authorities.push(DnsRecord::NS { domain: zone, host: String::from(NAME_SERVER), ttl: TransientTtl(600) });
domain: zone,
host: String::from(NAME_SERVER),
ttl: TransientTtl(600)
});
//trace!("Returning packet: {:?}", &packet); //trace!("Returning packet: {:?}", &packet);
Some(packet) Some(packet)
} else { } else {
@ -170,7 +170,7 @@ impl DnsFilter for BlockchainFilter {
BlockchainFilter::add_soa_record(zone, serial, &mut packet); BlockchainFilter::add_soa_record(zone, serial, &mut packet);
//trace!("Returning packet: {:?}", &packet); //trace!("Returning packet: {:?}", &packet);
Some(packet) Some(packet)
} };
} }
} }
@ -189,7 +189,7 @@ impl BlockchainFilter {
retry: 300, retry: 300,
expire: 604800, expire: 604800,
minimum: 60, minimum: 60,
ttl: TransientTtl(60), ttl: TransientTtl(60)
}); });
} }

@ -1,8 +1,9 @@
use std::convert::TryInto;
use blakeout::Blakeout; use blakeout::Blakeout;
use sha2::{Digest, Sha256};
use crate::{Block, Bytes, Keystore}; use crate::{Block, Bytes, Keystore};
use sha2::{Sha256, Digest};
use std::convert::TryInto;
/// Checks block's hash and returns true on valid hash or false otherwise /// Checks block's hash and returns true on valid hash or false otherwise
pub fn check_block_hash(block: &Block) -> bool { pub fn check_block_hash(block: &Block) -> bool {
@ -32,7 +33,7 @@ pub fn hash_identity(identity: &str, key: Option<&Bytes>) -> Bytes {
let base = hash_sha256(identity.as_bytes()); let base = hash_sha256(identity.as_bytes());
let identity = hash_sha256(&base); let identity = hash_sha256(&base);
match key { match key {
None => { Bytes::from_bytes(&identity) } None => Bytes::from_bytes(&identity),
Some(key) => { Some(key) => {
let mut buf = Vec::new(); let mut buf = Vec::new();
buf.append(&mut base.clone()); buf.append(&mut base.clone());
@ -85,9 +86,10 @@ pub fn hash_sha256(data: &[u8]) -> Vec<u8> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::blockchain::hash_utils::hash_sha256;
use std::convert::TryInto; use std::convert::TryInto;
use crate::blockchain::hash_utils::hash_sha256;
#[test] #[test]
#[ignore] #[ignore]
pub fn test_hash() { pub fn test_hash() {
@ -111,7 +113,7 @@ mod tests {
#[test] #[test]
#[ignore] #[ignore]
fn test_hash_is_good() { fn test_hash_is_good() {
let hash = vec!(0u8,0u8,0u8,255,255,255,255,255); let hash = vec![0u8, 0u8, 0u8, 255, 255, 255, 255, 255];
let bytes: [u8; 8] = hash[..8].try_into().unwrap(); let bytes: [u8; 8] = hash[..8].try_into().unwrap();
let int = u64::from_be_bytes(bytes); let int = u64::from_be_bytes(bytes);
println!("int = {}", int); println!("int = {}", int);

@ -2,10 +2,9 @@ pub use block::Block;
pub use chain::Chain; pub use chain::Chain;
pub use transaction::Transaction; pub use transaction::Transaction;
pub mod transaction;
pub mod block; pub mod block;
pub mod chain; pub mod chain;
pub mod filter; pub mod filter;
pub mod hash_utils; pub mod hash_utils;
pub mod transaction;
pub mod types; pub mod types;

@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize};
use crate::blockchain::hash_utils::*; use crate::blockchain::hash_utils::*;
use crate::bytes::Bytes; use crate::bytes::Bytes;
use crate::dns::protocol::DnsRecord; use crate::dns::protocol::DnsRecord;
use crate::{CLASS_ORIGIN, CLASS_DOMAIN}; use crate::{CLASS_DOMAIN, CLASS_ORIGIN};
extern crate serde; extern crate serde;
extern crate serde_json; extern crate serde_json;
@ -23,7 +23,7 @@ pub struct Transaction {
#[serde(default, skip_serializing_if = "Bytes::is_zero")] #[serde(default, skip_serializing_if = "Bytes::is_zero")]
pub encryption: Bytes, pub encryption: Bytes,
#[serde(default, skip_serializing_if = "String::is_empty")] #[serde(default, skip_serializing_if = "String::is_empty")]
pub data: String, pub data: String
} }
impl Transaction { impl Transaction {
@ -64,7 +64,7 @@ impl Transaction {
pub fn get_domain_data(&self) -> Option<DomainData> { pub fn get_domain_data(&self) -> Option<DomainData> {
if self.class == CLASS_DOMAIN { if self.class == CLASS_DOMAIN {
if let Ok(data) = serde_json::from_str::<DomainData>(&self.data) { if let Ok(data) = serde_json::from_str::<DomainData>(&self.data) {
return Some(data) return Some(data);
} }
} }
None None
@ -73,7 +73,7 @@ impl Transaction {
/// Gets a type of transaction /// Gets a type of transaction
pub fn get_type(what: &Option<Transaction>) -> TransactionType { pub fn get_type(what: &Option<Transaction>) -> TransactionType {
match what { match what {
None => { TransactionType::Signing } None => TransactionType::Signing,
Some(transaction) => { Some(transaction) => {
if transaction.class == CLASS_DOMAIN { if transaction.class == CLASS_DOMAIN {
return TransactionType::Domain; return TransactionType::Domain;
@ -116,7 +116,7 @@ pub struct DomainData {
#[serde(default, skip_serializing_if = "Vec::is_empty")] #[serde(default, skip_serializing_if = "Vec::is_empty")]
pub records: Vec<DnsRecord>, pub records: Vec<DnsRecord>,
#[serde(default, skip_serializing_if = "Vec::is_empty")] #[serde(default, skip_serializing_if = "Vec::is_empty")]
pub contacts: Vec<ContactsData>, pub contacts: Vec<ContactsData>
} }
impl DomainData { impl DomainData {

@ -1,4 +1,5 @@
use std::fmt::{Display, Formatter}; use std::fmt::{Display, Formatter};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
/// Represents a result of block check on block's arrival /// Represents a result of block check on block's arrival
@ -9,7 +10,7 @@ pub enum BlockQuality {
Future, Future,
Rewind, Rewind,
Bad, Bad,
Fork, Fork
} }
#[derive(Debug)] #[derive(Debug)]
@ -20,13 +21,13 @@ pub enum MineResult {
WrongKey, WrongKey,
WrongZone, WrongZone,
NotOwned, NotOwned,
Cooldown { time: i64 }, Cooldown { time: i64 }
} }
#[derive(Debug)] #[derive(Debug)]
pub struct Options { pub struct Options {
pub origin: String, pub origin: String,
pub version: u32, pub version: u32
} }
impl Options { impl Options {
@ -42,7 +43,7 @@ impl Options {
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct ZoneData { pub struct ZoneData {
pub name: String, pub name: String,
pub yggdrasil: bool, pub yggdrasil: bool
} }
impl Display for ZoneData { impl Display for ZoneData {

@ -4,15 +4,14 @@ extern crate serde_json;
use std::cmp::Ordering; use std::cmp::Ordering;
use std::convert::TryInto; use std::convert::TryInto;
use std::fmt; use std::fmt;
use std::fmt::{Formatter, Error}; use std::fmt::{Error, Formatter};
use std::hash::{Hash, Hasher};
use std::ops::Deref;
use num_bigint::BigUint; use num_bigint::BigUint;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
// For deserialization // For deserialization
use serde::de::{Error as DeError, Visitor}; use serde::de::{Error as DeError, Visitor};
use std::ops::Deref; use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::hash::{Hash, Hasher};
#[derive(Clone)] #[derive(Clone)]
pub struct Bytes { pub struct Bytes {
@ -132,8 +131,7 @@ impl fmt::Debug for Bytes {
} }
impl Serialize for Bytes { impl Serialize for Bytes {
fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> where fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> where S: Serializer {
S: Serializer {
serializer.serialize_str(&crate::commons::to_hex(&self.data)) serializer.serialize_str(&crate::commons::to_hex(&self.data))
} }
} }
@ -147,7 +145,7 @@ impl<'de> Visitor<'de> for BytesVisitor {
formatter.write_str("bytes in HEX format") formatter.write_str("bytes in HEX format")
} }
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: DeError, { fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: DeError {
if !value.is_empty() && value.len() % 2 == 0 { if !value.is_empty() && value.len() % 2 == 0 {
Ok(Bytes::new(crate::from_hex(value).unwrap())) Ok(Bytes::new(crate::from_hex(value).unwrap()))
} else if value.is_empty() { } else if value.is_empty() {
@ -157,7 +155,7 @@ impl<'de> Visitor<'de> for BytesVisitor {
} }
} }
fn visit_bytes<E>(self, value: &[u8]) -> Result<Self::Value, E> where E: DeError, { fn visit_bytes<E>(self, value: &[u8]) -> Result<Self::Value, E> where E: DeError {
if !value.is_empty() { if !value.is_empty() {
Ok(Bytes::from_bytes(value)) Ok(Bytes::from_bytes(value))
} else { } else {
@ -174,8 +172,8 @@ impl<'dd> Deserialize<'dd> for Bytes {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::bytes::Bytes;
use crate::blockchain::hash_utils::same_hash; use crate::blockchain::hash_utils::same_hash;
use crate::bytes::Bytes;
#[test] #[test]
pub fn test_tail_bytes() { pub fn test_tail_bytes() {
@ -186,6 +184,6 @@ mod tests {
#[test] #[test]
pub fn test_deref() { pub fn test_deref() {
let bytes = Bytes::zero32(); let bytes = Bytes::zero32();
assert!(same_hash(&bytes, &vec!(0u8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0))); assert!(same_hash(&bytes, &vec!(0u8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)));
} }
} }

@ -1,14 +1,17 @@
use crate::event::Event;
use crate::simplebus::Bus;
use std::sync::Mutex; use std::sync::Mutex;
use lazy_static::lazy_static; use lazy_static::lazy_static;
use uuid::Uuid; use uuid::Uuid;
use crate::event::Event;
use crate::simplebus::Bus;
lazy_static! { lazy_static! {
static ref STATIC_BUS: Mutex<Bus<Event>> = Mutex::new(Bus::new()); static ref STATIC_BUS: Mutex<Bus<Event>> = Mutex::new(Bus::new());
} }
pub fn register<F>(closure: F) -> Uuid where F: FnMut(&Uuid, Event) -> bool + Send + Sync + 'static { pub fn register<F>(closure: F) -> Uuid
where F: FnMut(&Uuid, Event) -> bool + Send + Sync + 'static {
STATIC_BUS.lock().unwrap().register(Box::new(closure)) STATIC_BUS.lock().unwrap().register(Box::new(closure))
} }

@ -1,17 +1,16 @@
use std::net::IpAddr; use std::net::IpAddr;
use std::num; use std::num;
pub use constants::*;
use rand::Rng; use rand::Rng;
#[cfg(not(target_os = "macos"))] #[cfg(not(target_os = "macos"))]
use thread_priority::*; use thread_priority::*;
pub use constants::*;
use crate::dns::protocol::DnsRecord; use crate::dns::protocol::DnsRecord;
pub mod constants; pub mod constants;
pub mod simplebus;
pub mod eventbus; pub mod eventbus;
pub mod simplebus;
/// Convert bytes array to HEX format /// Convert bytes array to HEX format
pub fn to_hex(buf: &[u8]) -> String { pub fn to_hex(buf: &[u8]) -> String {
@ -120,14 +119,14 @@ pub fn is_yggdrasil(addr: &IpAddr) -> bool {
pub fn is_yggdrasil_record(record: &DnsRecord) -> bool { pub fn is_yggdrasil_record(record: &DnsRecord) -> bool {
match record { match record {
DnsRecord::UNKNOWN { .. } => {} DnsRecord::UNKNOWN { .. } => {}
DnsRecord::A { .. } => { return false } DnsRecord::A { .. } => return false,
DnsRecord::NS { .. } => {} DnsRecord::NS { .. } => {}
DnsRecord::CNAME { .. } => {} DnsRecord::CNAME { .. } => {}
DnsRecord::SOA { .. } => {} DnsRecord::SOA { .. } => {}
DnsRecord::PTR { .. } => {} DnsRecord::PTR { .. } => {}
DnsRecord::MX { .. } => {} DnsRecord::MX { .. } => {}
DnsRecord::TXT { .. } => {} DnsRecord::TXT { .. } => {}
DnsRecord::AAAA { addr, .. } => { return is_yggdrasil(&IpAddr::from(*addr))} DnsRecord::AAAA { addr, .. } => return is_yggdrasil(&IpAddr::from(*addr)),
DnsRecord::SRV { .. } => {} DnsRecord::SRV { .. } => {}
DnsRecord::OPT { .. } => {} DnsRecord::OPT { .. } => {}
} }

@ -1,6 +1,7 @@
use uuid::Uuid;
use std::collections::HashMap; use std::collections::HashMap;
use uuid::Uuid;
pub struct Bus<T> { pub struct Bus<T> {
listeners: HashMap<Uuid, Box<dyn FnMut(&Uuid, T) -> bool + Send + Sync>> listeners: HashMap<Uuid, Box<dyn FnMut(&Uuid, T) -> bool + Send + Sync>>
} }
@ -33,8 +34,8 @@ mod tests {
use std::thread; use std::thread;
use std::time::Duration; use std::time::Duration;
use crate::Bus;
use crate::event::Event; use crate::event::Event;
use crate::Bus;
#[test] #[test]
fn test1() { fn test1() {

@ -1,7 +1,8 @@
use crate::{Chain, Keystore, Settings, Bytes};
#[allow(unused_imports)] #[allow(unused_imports)]
use log::{trace, debug, info, warn, error}; use log::{debug, error, info, trace, warn};
use crate::miner::MinerState; use crate::miner::MinerState;
use crate::{Bytes, Chain, Keystore, Settings};
pub struct Context { pub struct Context {
pub app_version: String, pub app_version: String,
@ -9,20 +10,13 @@ pub struct Context {
pub keystores: Vec<Keystore>, pub keystores: Vec<Keystore>,
active_key: usize, active_key: usize,
pub chain: Chain, pub chain: Chain,
pub miner_state: MinerState, pub miner_state: MinerState
} }
impl Context { impl Context {
/// Creating an essential context to work with /// Creating an essential context to work with
pub fn new(app_version: String, settings: Settings, keystores: Vec<Keystore>, chain: Chain) -> Context { pub fn new(app_version: String, settings: Settings, keystores: Vec<Keystore>, chain: Chain) -> Context {
Context { Context { app_version, settings, keystores, active_key: 0, chain, miner_state: MinerState { mining: false, full: false } }
app_version,
settings,
keystores,
active_key: 0,
chain,
miner_state: MinerState { mining: false, full: false }
}
} }
pub fn get_keystore(&self) -> Option<&Keystore> { pub fn get_keystore(&self) -> Option<&Keystore> {

@ -1,7 +1,8 @@
use chacha20poly1305::{ChaCha20Poly1305, Key, Nonce};
use chacha20poly1305::aead::{Aead, NewAead, Error};
use std::fmt::{Debug, Formatter};
use std::fmt; use std::fmt;
use std::fmt::{Debug, Formatter};
use chacha20poly1305::aead::{Aead, Error, NewAead};
use chacha20poly1305::{ChaCha20Poly1305, Key, Nonce};
pub const ZERO_NONCE: [u8; 12] = [0u8; 12]; pub const ZERO_NONCE: [u8; 12] = [0u8; 12];
@ -45,7 +46,7 @@ impl Debug for Chacha {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::crypto::Chacha; use crate::crypto::Chacha;
use crate::{to_hex}; use crate::to_hex;
#[test] #[test]
pub fn test_chacha() { pub fn test_chacha() {

@ -1,12 +1,14 @@
use ecies_ed25519::{SecretKey, PublicKey, Error, encrypt, decrypt};
use rand_old::{CryptoRng, RngCore};
use std::fmt::{Debug, Formatter};
use crate::{to_hex, from_hex};
use std::fmt; use std::fmt;
use std::fmt::{Debug, Formatter};
use ecies_ed25519::{decrypt, encrypt, Error, PublicKey, SecretKey};
use rand_old::{CryptoRng, RngCore};
use crate::{from_hex, to_hex};
pub struct CryptoBox { pub struct CryptoBox {
pub(crate) secret: SecretKey, pub(crate) secret: SecretKey,
pub(crate) public: PublicKey, pub(crate) public: PublicKey
} }
impl CryptoBox { impl CryptoBox {
@ -67,6 +69,7 @@ impl Clone for CryptoBox {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use rand::RngCore; use rand::RngCore;
use crate::crypto::CryptoBox; use crate::crypto::CryptoBox;
const TEXT: &str = "Some very secret message"; const TEXT: &str = "Some very secret message";

@ -1,6 +1,5 @@
mod crypto_box;
mod chacha; mod chacha;
mod crypto_box;
pub use chacha::{Chacha, ZERO_NONCE};
pub use crypto_box::CryptoBox; pub use crypto_box::CryptoBox;
pub use chacha::Chacha;
pub use chacha::ZERO_NONCE;

@ -6,9 +6,9 @@ use std::io::Write;
use std::path::Path; use std::path::Path;
use std::sync::{LockResult, RwLock, RwLockReadGuard, RwLockWriteGuard}; use std::sync::{LockResult, RwLock, RwLockReadGuard, RwLockWriteGuard};
use derive_more::{Display, Error, From};
#[allow(unused_imports)] #[allow(unused_imports)]
use log::{trace, debug, info, warn, error}; use log::{debug, error, info, trace, warn};
use derive_more::{Display, From, Error};
use crate::dns::buffer::{PacketBuffer, StreamPacketBuffer, VectorPacketBuffer}; use crate::dns::buffer::{PacketBuffer, StreamPacketBuffer, VectorPacketBuffer};
use crate::dns::protocol::{DnsPacket, DnsRecord, QueryType, ResultCode, TransientTtl}; use crate::dns::protocol::{DnsPacket, DnsRecord, QueryType, ResultCode, TransientTtl};
@ -18,7 +18,7 @@ pub enum AuthorityError {
Buffer(crate::dns::buffer::BufferError), Buffer(crate::dns::buffer::BufferError),
Protocol(crate::dns::protocol::ProtocolError), Protocol(crate::dns::protocol::ProtocolError),
Io(std::io::Error), Io(std::io::Error),
PoisonedLock, PoisonedLock
} }
type Result<T> = std::result::Result<T, AuthorityError>; type Result<T> = std::result::Result<T, AuthorityError>;
@ -33,7 +33,7 @@ pub struct Zone {
pub retry: u32, pub retry: u32,
pub expire: u32, pub expire: u32,
pub minimum: u32, pub minimum: u32,
pub records: BTreeSet<DnsRecord>, pub records: BTreeSet<DnsRecord>
} }
impl Zone { impl Zone {
@ -62,19 +62,17 @@ impl Zone {
#[derive(Default)] #[derive(Default)]
pub struct Zones { pub struct Zones {
zones: BTreeMap<String, Zone>, zones: BTreeMap<String, Zone>
} }
impl<'a> Zones { impl<'a> Zones {
pub fn new() -> Zones { pub fn new() -> Zones {
Zones { Zones { zones: BTreeMap::new() }
zones: BTreeMap::new(),
}
} }
pub fn load(&mut self) -> Result<()> { pub fn load(&mut self) -> Result<()> {
let zones_dir = match Path::new("zones").read_dir() { let zones_dir = match Path::new("zones").read_dir() {
Ok(result) => { result } Ok(result) => result,
Err(_) => { Err(_) => {
debug!("Authority dir (zones) not found, skipping."); debug!("Authority dir (zones) not found, skipping.");
return Ok(()); return Ok(());
@ -84,12 +82,12 @@ impl<'a> Zones {
for wrapped_filename in zones_dir { for wrapped_filename in zones_dir {
let filename = match wrapped_filename { let filename = match wrapped_filename {
Ok(x) => x, Ok(x) => x,
Err(_) => continue, Err(_) => continue
}; };
let mut zone_file = match File::open(filename.path()) { let mut zone_file = match File::open(filename.path()) {
Ok(x) => x, Ok(x) => x,
Err(_) => continue, Err(_) => continue
}; };
let mut buffer = StreamPacketBuffer::new(&mut zone_file); let mut buffer = StreamPacketBuffer::new(&mut zone_file);
@ -171,14 +169,12 @@ impl<'a> Zones {
#[derive(Default)] #[derive(Default)]
pub struct Authority { pub struct Authority {
zones: RwLock<Zones>, zones: RwLock<Zones>
} }
impl Authority { impl Authority {
pub fn new() -> Authority { pub fn new() -> Authority {
Authority { Authority { zones: RwLock::new(Zones::new()) }
zones: RwLock::new(Zones::new()),
}
} }
pub fn load(&self) -> Result<()> { pub fn load(&self) -> Result<()> {
@ -194,7 +190,7 @@ impl Authority {
pub fn query(&self, qname: &str, qtype: QueryType) -> Option<DnsPacket> { pub fn query(&self, qname: &str, qtype: QueryType) -> Option<DnsPacket> {
let zones = match self.zones.read().ok() { let zones = match self.zones.read().ok() {
Some(x) => x, Some(x) => x,
None => return None, None => return None
}; };
let mut best_match = None; let mut best_match = None;
@ -214,7 +210,7 @@ impl Authority {
let zone = match best_match { let zone = match best_match {
Some((_, zone)) => zone, Some((_, zone)) => zone,
None => return None, None => return None
}; };
let mut packet = DnsPacket::new(); let mut packet = DnsPacket::new();
@ -223,7 +219,7 @@ impl Authority {
for rec in &zone.records { for rec in &zone.records {
let domain = match rec.get_domain() { let domain = match rec.get_domain() {
Some(x) => x, Some(x) => x,
None => continue, None => continue
}; };
if &domain != qname { if &domain != qname {
@ -248,7 +244,7 @@ impl Authority {
retry: zone.retry, retry: zone.retry,
expire: zone.expire, expire: zone.expire,
minimum: zone.minimum, minimum: zone.minimum,
ttl: TransientTtl(zone.minimum), ttl: TransientTtl(zone.minimum)
}); });
} }

@ -8,7 +8,7 @@ use derive_more::{Display, Error, From};
#[derive(Debug, Display, From, Error)] #[derive(Debug, Display, From, Error)]
pub enum BufferError { pub enum BufferError {
Io(std::io::Error), Io(std::io::Error),
EndOfBuffer, EndOfBuffer
} }
type Result<T> = std::result::Result<T, BufferError>; type Result<T> = std::result::Result<T, BufferError>;
@ -155,16 +155,12 @@ pub trait PacketBuffer {
pub struct VectorPacketBuffer { pub struct VectorPacketBuffer {
pub buffer: Vec<u8>, pub buffer: Vec<u8>,
pub pos: usize, pub pos: usize,
pub label_lookup: BTreeMap<String, usize>, pub label_lookup: BTreeMap<String, usize>
} }
impl VectorPacketBuffer { impl VectorPacketBuffer {
pub fn new() -> VectorPacketBuffer { pub fn new() -> VectorPacketBuffer {
VectorPacketBuffer { VectorPacketBuffer { buffer: Vec::new(), pos: 0, label_lookup: BTreeMap::new() }
buffer: Vec::new(),
pos: 0,
label_lookup: BTreeMap::new(),
}
} }
} }
@ -222,10 +218,11 @@ impl PacketBuffer for VectorPacketBuffer {
} }
} }
pub struct StreamPacketBuffer<'a, T> where T: Read { pub struct StreamPacketBuffer<'a, T>
where T: Read {
pub stream: &'a mut T, pub stream: &'a mut T,
pub buffer: Vec<u8>, pub buffer: Vec<u8>,
pub pos: usize, pub pos: usize
} }
impl<'a, T> StreamPacketBuffer<'a, T> where T: Read + 'a { impl<'a, T> StreamPacketBuffer<'a, T> where T: Read + 'a {
@ -305,15 +302,12 @@ impl<'a, T> PacketBuffer for StreamPacketBuffer<'a, T> where T: Read + 'a {
pub struct BytePacketBuffer { pub struct BytePacketBuffer {
pub buf: [u8; 512], pub buf: [u8; 512],
pub pos: usize, pub pos: usize
} }
impl BytePacketBuffer { impl BytePacketBuffer {
pub fn new() -> BytePacketBuffer { pub fn new() -> BytePacketBuffer {
BytePacketBuffer { BytePacketBuffer { buf: [0; 512], pos: 0 }
buf: [0; 512],
pos: 0,
}
} }
} }
@ -401,7 +395,7 @@ mod tests {
// First write the standard string // First write the standard string
match buffer.write_qname(&instr1) { match buffer.write_qname(&instr1) {
Ok(_) => {} Ok(_) => {}
Err(_) => panic!(), Err(_) => panic!()
} }
// Then we set up a slight variation with relies on a jump back to the data of // Then we set up a slight variation with relies on a jump back to the data of
@ -410,7 +404,7 @@ mod tests {
for b in &crafted_data { for b in &crafted_data {
match buffer.write_u8(*b) { match buffer.write_u8(*b) {
Ok(_) => {} Ok(_) => {}
Err(_) => panic!(), Err(_) => panic!()
} }
} }
@ -421,7 +415,7 @@ mod tests {
let mut outstr1 = String::new(); let mut outstr1 = String::new();
match buffer.read_qname(&mut outstr1) { match buffer.read_qname(&mut outstr1) {
Ok(_) => {} Ok(_) => {}
Err(_) => panic!(), Err(_) => panic!()
} }
assert_eq!(instr1, outstr1); assert_eq!(instr1, outstr1);
@ -430,7 +424,7 @@ mod tests {
let mut outstr2 = String::new(); let mut outstr2 = String::new();
match buffer.read_qname(&mut outstr2) { match buffer.read_qname(&mut outstr2) {
Ok(_) => {} Ok(_) => {}
Err(_) => panic!(), Err(_) => panic!()
} }
assert_eq!(instr2, outstr2); assert_eq!(instr2, outstr2);
@ -445,24 +439,24 @@ mod tests {
match buffer.write_qname(&"ns1.google.com".to_string()) { match buffer.write_qname(&"ns1.google.com".to_string()) {
Ok(_) => {} Ok(_) => {}
Err(_) => panic!(), Err(_) => panic!()
} }
match buffer.write_qname(&"ns2.google.com".to_string()) { match buffer.write_qname(&"ns2.google.com".to_string()) {
Ok(_) => {} Ok(_) => {}
Err(_) => panic!(), Err(_) => panic!()
} }
assert_eq!(22, buffer.pos()); assert_eq!(22, buffer.pos());
match buffer.seek(0) { match buffer.seek(0) {
Ok(_) => {} Ok(_) => {}
Err(_) => panic!(), Err(_) => panic!()
} }
let mut str1 = String::new(); let mut str1 = String::new();
match buffer.read_qname(&mut str1) { match buffer.read_qname(&mut str1) {
Ok(_) => {} Ok(_) => {}
Err(_) => panic!(), Err(_) => panic!()
} }
assert_eq!("ns1.google.com", str1); assert_eq!("ns1.google.com", str1);
@ -470,7 +464,7 @@ mod tests {
let mut str2 = String::new(); let mut str2 = String::new();
match buffer.read_qname(&mut str2) { match buffer.read_qname(&mut str2) {
Ok(_) => {} Ok(_) => {}
Err(_) => panic!(), Err(_) => panic!()
} }
assert_eq!("ns2.google.com", str2); assert_eq!("ns2.google.com", str2);

@ -15,7 +15,7 @@ use crate::dns::protocol::{DnsPacket, DnsRecord, QueryType, ResultCode};
#[derive(Debug, Display, From, Error)] #[derive(Debug, Display, From, Error)]
pub enum CacheError { pub enum CacheError {
Io(std::io::Error), Io(std::io::Error),
PoisonedLock, PoisonedLock
} }
type Result<T> = std::result::Result<T, CacheError>; type Result<T> = std::result::Result<T, CacheError>;
@ -23,13 +23,13 @@ type Result<T> = std::result::Result<T, CacheError>;
pub enum CacheState { pub enum CacheState {
PositiveCache, PositiveCache,
NegativeCache, NegativeCache,
NotCached, NotCached
} }
#[derive(Clone, Eq, Debug, Serialize, Deserialize)] #[derive(Clone, Eq, Debug, Serialize, Deserialize)]
pub struct RecordEntry { pub struct RecordEntry {
pub record: DnsRecord, pub record: DnsRecord,
pub timestamp: DateTime<Local>, pub timestamp: DateTime<Local>
} }
impl PartialEq<RecordEntry> for RecordEntry { impl PartialEq<RecordEntry> for RecordEntry {
@ -47,7 +47,7 @@ impl Hash for RecordEntry {
#[derive(Clone, Debug, Serialize, Deserialize)] #[derive(Clone, Debug, Serialize, Deserialize)]
pub enum RecordSet { pub enum RecordSet {
NoRecords { qtype: QueryType, ttl: u32, timestamp: DateTime<Local> }, NoRecords { qtype: QueryType, ttl: u32, timestamp: DateTime<Local> },
Records { qtype: QueryType, records: HashSet<RecordEntry> }, Records { qtype: QueryType, records: HashSet<RecordEntry> }
} }
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
@ -55,7 +55,7 @@ pub struct DomainEntry {
pub domain: String, pub domain: String,
pub record_types: HashMap<QueryType, RecordSet>, pub record_types: HashMap<QueryType, RecordSet>,
pub hits: u32, pub hits: u32,
pub updates: u32, pub updates: u32
} }
impl DomainEntry { impl DomainEntry {
@ -128,7 +128,7 @@ impl DomainEntry {
CacheState::NegativeCache CacheState::NegativeCache
} }
} }
None => CacheState::NotCached, None => CacheState::NotCached
} }
} }
@ -137,7 +137,7 @@ impl DomainEntry {
let current_set = match self.record_types.get(&qtype) { let current_set = match self.record_types.get(&qtype) {
Some(x) => x, Some(x) => x,
None => return, None => return
}; };
if let RecordSet::Records { ref records, .. } = *current_set { if let RecordSet::Records { ref records, .. } = *current_set {
@ -158,7 +158,7 @@ impl DomainEntry {
#[derive(Default)] #[derive(Default)]
pub struct Cache { pub struct Cache {
domain_entries: BTreeMap<String, Arc<DomainEntry>>, domain_entries: BTreeMap<String, Arc<DomainEntry>>
} }
impl Cache { impl Cache {
@ -169,11 +169,11 @@ impl Cache {
fn get_cache_state(&mut self, qname: &str, qtype: QueryType) -> CacheState { fn get_cache_state(&mut self, qname: &str, qtype: QueryType) -> CacheState {
match self.domain_entries.get(qname) { match self.domain_entries.get(qname) {
Some(x) => x.get_cache_state(qtype), Some(x) => x.get_cache_state(qtype),
None => CacheState::NotCached, None => CacheState::NotCached
} }
} }
fn fill_queryresult(&mut self,qname: &str, qtype: QueryType, result_vec: &mut Vec<DnsRecord>, increment_stats: bool) { fn fill_queryresult(&mut self, qname: &str, qtype: QueryType, result_vec: &mut Vec<DnsRecord>, increment_stats: bool) {
if let Some(domain_entry) = self.domain_entries.get_mut(qname).and_then(Arc::get_mut) { if let Some(domain_entry) = self.domain_entries.get_mut(qname).and_then(Arc::get_mut) {
if increment_stats { if increment_stats {
domain_entry.hits += 1 domain_entry.hits += 1
@ -198,7 +198,7 @@ impl Cache {
Some(qr) Some(qr)
} }
CacheState::NotCached => None, CacheState::NotCached => None
} }
} }
@ -206,7 +206,7 @@ impl Cache {
for rec in records { for rec in records {
let domain = match rec.get_domain() { let domain = match rec.get_domain() {
Some(x) => x, Some(x) => x,
None => continue, None => continue
}; };
if let Some(ref mut rs) = self.domain_entries.get_mut(&domain).and_then(Arc::get_mut) { if let Some(ref mut rs) = self.domain_entries.get_mut(&domain).and_then(Arc::get_mut) {
@ -234,7 +234,7 @@ impl Cache {
#[derive(Default)] #[derive(Default)]
pub struct SynchronizedCache { pub struct SynchronizedCache {
pub cache: RwLock<Cache>, pub cache: RwLock<Cache>
} }
impl SynchronizedCache { impl SynchronizedCache {
@ -257,7 +257,7 @@ impl SynchronizedCache {
pub fn lookup(&self, qname: &str, qtype: QueryType) -> Option<DnsPacket> { pub fn lookup(&self, qname: &str, qtype: QueryType) -> Option<DnsPacket> {
let mut cache = match self.cache.write() { let mut cache = match self.cache.write() {
Ok(x) => x, Ok(x) => x,
Err(_) => return None, Err(_) => return None
}; };
cache.lookup(qname, qtype) cache.lookup(qname, qtype)
@ -284,7 +284,6 @@ impl SynchronizedCache {
mod tests { mod tests {
use super::*; use super::*;
use crate::dns::protocol::{DnsRecord, QueryType, ResultCode, TransientTtl}; use crate::dns::protocol::{DnsRecord, QueryType, ResultCode, TransientTtl};
#[test] #[test]
@ -318,17 +317,17 @@ mod tests {
records.push(DnsRecord::A { records.push(DnsRecord::A {
domain: "www.google.com".to_string(), domain: "www.google.com".to_string(),
addr: "127.0.0.1".parse().unwrap(), addr: "127.0.0.1".parse().unwrap(),
ttl: TransientTtl(3600), ttl: TransientTtl(3600)
}); });
records.push(DnsRecord::A { records.push(DnsRecord::A {
domain: "www.yahoo.com".to_string(), domain: "www.yahoo.com".to_string(),
addr: "127.0.0.2".parse().unwrap(), addr: "127.0.0.2".parse().unwrap(),
ttl: TransientTtl(0), ttl: TransientTtl(0)
}); });
records.push(DnsRecord::CNAME { records.push(DnsRecord::CNAME {
domain: "www.microsoft.com".to_string(), domain: "www.microsoft.com".to_string(),
host: "www.somecdn.com".to_string(), host: "www.somecdn.com".to_string(),
ttl: TransientTtl(3600), ttl: TransientTtl(3600)
}); });
cache.store(&records); cache.store(&records);
@ -361,7 +360,7 @@ mod tests {
records2.push(DnsRecord::A { records2.push(DnsRecord::A {
domain: "www.yahoo.com".to_string(), domain: "www.yahoo.com".to_string(),
addr: "127.0.0.2".parse().unwrap(), addr: "127.0.0.2".parse().unwrap(),
ttl: TransientTtl(3600), ttl: TransientTtl(3600)
}); });
cache.store(&records2); cache.store(&records2);
@ -373,53 +372,11 @@ mod tests {
// Check stat counter behavior // Check stat counter behavior
assert_eq!(3, cache.domain_entries.len()); assert_eq!(3, cache.domain_entries.len());
assert_eq!( assert_eq!(1, cache.domain_entries.get(&"www.google.com".to_string()).unwrap().hits);
1, assert_eq!(2, cache.domain_entries.get(&"www.google.com".to_string()).unwrap().updates);
cache assert_eq!(1, cache.domain_entries.get(&"www.yahoo.com".to_string()).unwrap().hits);
.domain_entries assert_eq!(3, cache.domain_entries.get(&"www.yahoo.com".to_string()).unwrap().updates);
.get(&"www.google.com".to_string()) assert_eq!(1, cache.domain_entries.get(&"www.microsoft.com".to_string()).unwrap().updates);
.unwrap() assert_eq!(1, cache.domain_entries.get(&"www.microsoft.com".to_string()).unwrap().hits);
.hits
);
assert_eq!(
2,
cache
.domain_entries
.get(&"www.google.com".to_string())
.unwrap()
.updates
);
assert_eq!(
1,
cache
.domain_entries
.get(&"www.yahoo.com".to_string())
.unwrap()
.hits
);
assert_eq!(
3,
cache
.domain_entries
.get(&"www.yahoo.com".to_string())
.unwrap()
.updates
);
assert_eq!(
1,
cache
.domain_entries
.get(&"www.microsoft.com".to_string())
.unwrap()
.updates
);
assert_eq!(
1,
cache
.domain_entries
.get(&"www.microsoft.com".to_string())
.unwrap()
.hits
);
} }
} }

@ -2,7 +2,7 @@
use std::io::Write; use std::io::Write;
use std::marker::{Send, Sync}; use std::marker::{Send, Sync};
use std::net::{TcpStream, UdpSocket, ToSocketAddrs, SocketAddr}; use std::net::{SocketAddr, TcpStream, ToSocketAddrs, UdpSocket};
use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::{channel, Sender}; use std::sync::mpsc::{channel, Sender};
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
@ -22,7 +22,7 @@ pub enum ClientError {
Io(std::io::Error), Io(std::io::Error),
PoisonedLock, PoisonedLock,
LookupFailed, LookupFailed,
TimeOut, TimeOut
} }
type Result<T> = std::result::Result<T, ClientError>; type Result<T> = std::result::Result<T, ClientError>;
@ -56,7 +56,7 @@ pub struct DnsNetworkClient {
socket_ipv6: UdpSocket, socket_ipv6: UdpSocket,
/// Queries in progress /// Queries in progress
pending_queries: Arc<Mutex<Vec<PendingQuery>>>, pending_queries: Arc<Mutex<Vec<PendingQuery>>>
} }
/// A query in progress. This struct holds the `id` if the request, and a channel /// A query in progress. This struct holds the `id` if the request, and a channel
@ -65,7 +65,7 @@ pub struct DnsNetworkClient {
struct PendingQuery { struct PendingQuery {
seq: u16, seq: u16,
timestamp: DateTime<Local>, timestamp: DateTime<Local>,
tx: Sender<Option<DnsPacket>>, tx: Sender<Option<DnsPacket>>
} }
unsafe impl Send for DnsNetworkClient {} unsafe impl Send for DnsNetworkClient {}
@ -80,7 +80,7 @@ impl DnsNetworkClient {
seq: AtomicUsize::new(0), seq: AtomicUsize::new(0),
socket_ipv4: UdpSocket::bind(format!("0.0.0.0:{}", port)).expect("Error binding IPv4"), socket_ipv4: UdpSocket::bind(format!("0.0.0.0:{}", port)).expect("Error binding IPv4"),
socket_ipv6: UdpSocket::bind(format!("[::]:{}", port + 1)).expect("Error binding IPv6"), socket_ipv6: UdpSocket::bind(format!("[::]:{}", port + 1)).expect("Error binding IPv6"),
pending_queries: Arc::new(Mutex::new(Vec::new())), pending_queries: Arc::new(Mutex::new(Vec::new()))
} }
} }
@ -331,7 +331,7 @@ impl DnsClient for DnsNetworkClient {
Ok(()) Ok(())
} }
fn send_query(&self,qname: &str, qtype: QueryType, server: &str, recursive: bool) -> Result<DnsPacket> { fn send_query(&self, qname: &str, qtype: QueryType, server: &str, recursive: bool) -> Result<DnsPacket> {
let packet = self.send_udp_query(qname, qtype, server, recursive)?; let packet = self.send_udp_query(qname, qtype, server, recursive)?;
if !packet.header.truncated_message { if !packet.header.truncated_message {
return Ok(packet); return Ok(packet);
@ -350,7 +350,7 @@ pub mod tests {
pub type StubCallback = dyn Fn(&str, QueryType, &str, bool) -> Result<DnsPacket>; pub type StubCallback = dyn Fn(&str, QueryType, &str, bool) -> Result<DnsPacket>;
pub struct DnsStubClient { pub struct DnsStubClient {
callback: Box<StubCallback>, callback: Box<StubCallback>
} }
impl<'a> DnsStubClient { impl<'a> DnsStubClient {
@ -376,7 +376,7 @@ pub mod tests {
Ok(()) Ok(())
} }
fn send_query(&self,qname: &str, qtype: QueryType, server: &str, recursive: bool) -> Result<DnsPacket> { fn send_query(&self, qname: &str, qtype: QueryType, server: &str, recursive: bool) -> Result<DnsPacket> {
(self.callback)(qname, qtype, server, recursive) (self.callback)(qname, qtype, server, recursive)
} }
} }
@ -386,9 +386,7 @@ pub mod tests {
let client = DnsNetworkClient::new(31456); let client = DnsNetworkClient::new(31456);
client.run().unwrap(); client.run().unwrap();
let res = client let res = client.send_udp_query("google.com", QueryType::A, ("8.8.8.8", 53), true).unwrap();
.send_udp_query("google.com", QueryType::A, ("8.8.8.8", 53), true)
.unwrap();
assert_eq!(res.questions[0].name, "google.com"); assert_eq!(res.questions[0].name, "google.com");
assert!(res.answers.len() > 0); assert!(res.answers.len() > 0);
@ -397,16 +395,14 @@ pub mod tests {
DnsRecord::A { ref domain, .. } => { DnsRecord::A { ref domain, .. } => {
assert_eq!("google.com", domain); assert_eq!("google.com", domain);
} }
_ => panic!(), _ => panic!()
} }
} }
#[test] #[test]
pub fn test_tcp_client() { pub fn test_tcp_client() {
let client = DnsNetworkClient::new(31458); let client = DnsNetworkClient::new(31458);
let res = client let res = client.send_tcp_query("google.com", QueryType::A, ("8.8.8.8", 53), true).unwrap();
.send_tcp_query("google.com", QueryType::A, ("8.8.8.8", 53), true)
.unwrap();
assert_eq!(res.questions[0].name, "google.com"); assert_eq!(res.questions[0].name, "google.com");
assert!(res.answers.len() > 0); assert!(res.answers.len() > 0);
@ -415,7 +411,7 @@ pub mod tests {
DnsRecord::A { ref domain, .. } => { DnsRecord::A { ref domain, .. } => {
assert_eq!("google.com", domain); assert_eq!("google.com", domain);
} }
_ => panic!(), _ => panic!()
} }
} }
} }

@ -8,21 +8,21 @@ use derive_more::{Display, Error, From};
use crate::dns::authority::Authority; use crate::dns::authority::Authority;
use crate::dns::cache::SynchronizedCache; use crate::dns::cache::SynchronizedCache;
use crate::dns::client::{DnsClient, DnsNetworkClient}; use crate::dns::client::{DnsClient, DnsNetworkClient};
use crate::dns::resolve::{DnsResolver, ForwardingDnsResolver, RecursiveDnsResolver};
use crate::dns::filter::DnsFilter; use crate::dns::filter::DnsFilter;
use crate::dns::resolve::{DnsResolver, ForwardingDnsResolver, RecursiveDnsResolver};
#[derive(Debug, Display, From, Error)] #[derive(Debug, Display, From, Error)]
pub enum ContextError { pub enum ContextError {
Authority(crate::dns::authority::AuthorityError), Authority(crate::dns::authority::AuthorityError),
Client(crate::dns::client::ClientError), Client(crate::dns::client::ClientError),
Io(std::io::Error), Io(std::io::Error)
} }
type Result<T> = std::result::Result<T, ContextError>; type Result<T> = std::result::Result<T, ContextError>;
pub struct ServerStatistics { pub struct ServerStatistics {
pub tcp_query_count: AtomicUsize, pub tcp_query_count: AtomicUsize,
pub udp_query_count: AtomicUsize, pub udp_query_count: AtomicUsize
} }
impl ServerStatistics { impl ServerStatistics {
@ -37,7 +37,7 @@ impl ServerStatistics {
pub enum ResolveStrategy { pub enum ResolveStrategy {
Recursive, Recursive,
Forward { upstreams: Vec<String> }, Forward { upstreams: Vec<String> }
} }
pub struct ServerContext { pub struct ServerContext {
@ -76,11 +76,8 @@ impl ServerContext {
enable_udp: true, enable_udp: true,
enable_tcp: true, enable_tcp: true,
enable_api: false, enable_api: false,
statistics: ServerStatistics { statistics: ServerStatistics { tcp_query_count: AtomicUsize::new(0), udp_query_count: AtomicUsize::new(0) },
tcp_query_count: AtomicUsize::new(0), zones_dir: "zones"
udp_query_count: AtomicUsize::new(0),
},
zones_dir: "zones",
} }
} }
@ -110,13 +107,11 @@ pub mod tests {
use std::sync::atomic::AtomicUsize; use std::sync::atomic::AtomicUsize;
use std::sync::Arc; use std::sync::Arc;
use super::*;
use crate::dns::authority::Authority; use crate::dns::authority::Authority;
use crate::dns::cache::SynchronizedCache; use crate::dns::cache::SynchronizedCache;
use crate::dns::client::tests::{DnsStubClient, StubCallback}; use crate::dns::client::tests::{DnsStubClient, StubCallback};
use super::*;
pub fn create_test_context(callback: Box<StubCallback>) -> Arc<ServerContext> { pub fn create_test_context(callback: Box<StubCallback>) -> Arc<ServerContext> {
Arc::new(ServerContext { Arc::new(ServerContext {
authority: Authority::new(), authority: Authority::new(),
@ -130,11 +125,8 @@ pub mod tests {
enable_udp: true, enable_udp: true,
enable_tcp: true, enable_tcp: true,
enable_api: false, enable_api: false,
statistics: ServerStatistics { statistics: ServerStatistics { tcp_query_count: AtomicUsize::new(0), udp_query_count: AtomicUsize::new(0) },
tcp_query_count: AtomicUsize::new(0), zones_dir: "zones"
udp_query_count: AtomicUsize::new(0),
},
zones_dir: "zones",
}) })
} }
} }

@ -1,12 +1,10 @@
use crate::dns::protocol::{QueryType, DnsPacket}; use crate::dns::protocol::{DnsPacket, QueryType};
pub trait DnsFilter { pub trait DnsFilter {
fn lookup(&self, qname: &str, qtype: QueryType) -> Option<DnsPacket>; fn lookup(&self, qname: &str, qtype: QueryType) -> Option<DnsPacket>;
} }
pub struct DummyFilter { pub struct DummyFilter {}
}
#[allow(unused_variables)] #[allow(unused_variables)]
impl DnsFilter for DummyFilter { impl DnsFilter for DummyFilter {

@ -1,11 +1,12 @@
use std::net::IpAddr;
use std::collections::HashMap; use std::collections::HashMap;
use std::fs::File; use std::fs::File;
use std::io::Read; use std::io::Read;
use std::net::IpAddr;
use crate::dns::filter::DnsFilter; use crate::dns::filter::DnsFilter;
use crate::dns::protocol::{DnsPacket, QueryType, DnsRecord, TransientTtl, DnsQuestion}; use crate::dns::protocol::{DnsPacket, DnsQuestion, DnsRecord, QueryType, TransientTtl};
const NAME_SERVER: & str = "hosts"; const NAME_SERVER: &str = "hosts";
pub struct HostsFilter { pub struct HostsFilter {
hosts: HashMap<String, Vec<IpAddr>> hosts: HashMap<String, Vec<IpAddr>>
@ -33,16 +34,14 @@ impl HostsFilter {
let domain = parts[1].trim().to_owned(); let domain = parts[1].trim().to_owned();
if let Ok(addr) = ip.parse::<IpAddr>() { if let Ok(addr) = ip.parse::<IpAddr>() {
if !domain.is_empty() { if !domain.is_empty() {
map.entry(domain).or_insert(vec!(addr)); map.entry(domain).or_insert(vec![addr]);
} }
} }
} }
map map
} }
Err(..) => { Err(..) => HashMap::new()
HashMap::new()
}
}; };
HostsFilter { hosts } HostsFilter { hosts }
} }
@ -70,7 +69,11 @@ impl DnsFilter for HostsFilter {
packet.header.authoritative_answer = true; packet.header.authoritative_answer = true;
packet.questions.push(DnsQuestion::new(String::from(qname), qtype)); packet.questions.push(DnsQuestion::new(String::from(qname), qtype));
packet.authorities.push(DnsRecord::NS { domain: String::from("hosts"), host: String::from(NAME_SERVER), ttl: TransientTtl(600) }); packet.authorities.push(DnsRecord::NS {
domain: String::from("hosts"),
host: String::from(NAME_SERVER),
ttl: TransientTtl(600)
});
return Some(packet); return Some(packet);
} }
@ -80,9 +83,10 @@ impl DnsFilter for HostsFilter {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::dns::hosts::HostsFilter;
use std::env; use std::env;
use crate::dns::hosts::HostsFilter;
#[test] #[test]
#[ignore] #[ignore]
pub fn load_hosts() { pub fn load_hosts() {

@ -19,10 +19,10 @@ pub mod buffer;
pub mod cache; pub mod cache;
pub mod client; pub mod client;
pub mod context; pub mod context;
pub mod filter;
pub mod hosts;
pub mod protocol; pub mod protocol;
pub mod resolve; pub mod resolve;
pub mod server; pub mod server;
pub mod filter;
pub mod hosts;
mod netutil; mod netutil;

@ -15,7 +15,7 @@ use crate::dns::buffer::{PacketBuffer, VectorPacketBuffer};
#[derive(Debug, Display, From, Error)] #[derive(Debug, Display, From, Error)]
pub enum ProtocolError { pub enum ProtocolError {
Buffer(crate::dns::buffer::BufferError), Buffer(crate::dns::buffer::BufferError),
Io(std::io::Error), Io(std::io::Error)
} }
type Result<T> = std::result::Result<T, ProtocolError>; type Result<T> = std::result::Result<T, ProtocolError>;
@ -91,10 +91,7 @@ impl PartialOrd<TransientTtl> for TransientTtl {
} }
impl Hash for TransientTtl { impl Hash for TransientTtl {
fn hash<H>(&self, _: &mut H) fn hash<H>(&self, _: &mut H) where H: Hasher {
where
H: Hasher,
{
// purposely left empty // purposely left empty
} }
} }
@ -110,22 +107,22 @@ pub enum DnsRecord {
domain: String, domain: String,
qtype: u16, qtype: u16,
data_len: u16, data_len: u16,
ttl: TransientTtl, ttl: TransientTtl
}, // 0 }, // 0
A { A {
domain: String, domain: String,
addr: Ipv4Addr, addr: Ipv4Addr,
ttl: TransientTtl, ttl: TransientTtl
}, // 1 }, // 1
NS { NS {
domain: String, domain: String,
host: String, host: String,
ttl: TransientTtl, ttl: TransientTtl
}, // 2 }, // 2
CNAME { CNAME {
domain: String, domain: String,
host: String, host: String,
ttl: TransientTtl, ttl: TransientTtl
}, // 5 }, // 5
SOA { SOA {
domain: String, domain: String,
@ -136,28 +133,28 @@ pub enum DnsRecord {
retry: u32, retry: u32,
expire: u32, expire: u32,
minimum: u32, minimum: u32,
ttl: TransientTtl, ttl: TransientTtl
}, // 6 }, // 6
PTR { PTR {
domain: String, domain: String,
data: String, data: String,
ttl: TransientTtl, ttl: TransientTtl
}, // 12 }, // 12
MX { MX {
domain: String, domain: String,
priority: u16, priority: u16,
host: String, host: String,
ttl: TransientTtl, ttl: TransientTtl
}, // 15 }, // 15
TXT { TXT {
domain: String, domain: String,
data: String, data: String,
ttl: TransientTtl, ttl: TransientTtl
}, // 16 }, // 16
AAAA { AAAA {
domain: String, domain: String,
addr: Ipv6Addr, addr: Ipv6Addr,
ttl: TransientTtl, ttl: TransientTtl
}, // 28 }, // 28
SRV { SRV {
domain: String, domain: String,
@ -165,12 +162,12 @@ pub enum DnsRecord {
weight: u16, weight: u16,
port: u16, port: u16,
host: String, host: String,
ttl: TransientTtl, ttl: TransientTtl
}, // 33 }, // 33
OPT { OPT {
packet_len: u16, packet_len: u16,
flags: u32, flags: u32,
data: String, data: String
}, // 41 }, // 41
} }
@ -192,14 +189,10 @@ impl DnsRecord {
((raw_addr >> 24) & 0xFF) as u8, ((raw_addr >> 24) & 0xFF) as u8,
((raw_addr >> 16) & 0xFF) as u8, ((raw_addr >> 16) & 0xFF) as u8,
((raw_addr >> 8) & 0xFF) as u8, ((raw_addr >> 8) & 0xFF) as u8,
((raw_addr >> 0) & 0xFF) as u8, ((raw_addr >> 0) & 0xFF) as u8
); );
Ok(DnsRecord::A { Ok(DnsRecord::A { domain, addr, ttl: TransientTtl(ttl) })
domain,
addr,
ttl: TransientTtl(ttl),
})
} }
QueryType::AAAA => { QueryType::AAAA => {
let raw_addr1 = buffer.read_u32()?; let raw_addr1 = buffer.read_u32()?;
@ -214,34 +207,22 @@ impl DnsRecord {
((raw_addr3 >> 16) & 0xFFFF) as u16, ((raw_addr3 >> 16) & 0xFFFF) as u16,
((raw_addr3 >> 0) & 0xFFFF) as u16, ((raw_addr3 >> 0) & 0xFFFF) as u16,
((raw_addr4 >> 16) & 0xFFFF) as u16, ((raw_addr4 >> 16) & 0xFFFF) as u16,
((raw_addr4 >> 0) & 0xFFFF) as u16, ((raw_addr4 >> 0) & 0xFFFF) as u16
); );
Ok(DnsRecord::AAAA { Ok(DnsRecord::AAAA { domain, addr, ttl: TransientTtl(ttl) })
domain,
addr,
ttl: TransientTtl(ttl),
})
} }
QueryType::NS => { QueryType::NS => {
let mut ns = String::new(); let mut ns = String::new();
buffer.read_qname(&mut ns)?; buffer.read_qname(&mut ns)?;
Ok(DnsRecord::NS { Ok(DnsRecord::NS { domain, host: ns, ttl: TransientTtl(ttl) })
domain,
host: ns,
ttl: TransientTtl(ttl),
})
} }
QueryType::CNAME => { QueryType::CNAME => {
let mut cname = String::new(); let mut cname = String::new();
buffer.read_qname(&mut cname)?; buffer.read_qname(&mut cname)?;
Ok(DnsRecord::CNAME { Ok(DnsRecord::CNAME { domain, host: cname, ttl: TransientTtl(ttl) })
domain,
host: cname,
ttl: TransientTtl(ttl),
})
} }
QueryType::SRV => { QueryType::SRV => {
let priority = buffer.read_u16()?; let priority = buffer.read_u16()?;
@ -251,36 +232,20 @@ impl DnsRecord {
let mut srv = String::new(); let mut srv = String::new();
buffer.read_qname(&mut srv)?; buffer.read_qname(&mut srv)?;
Ok(DnsRecord::SRV { Ok(DnsRecord::SRV { domain, priority, weight, port, host: srv, ttl: TransientTtl(ttl) })
domain,
priority,
weight,
port,
host: srv,
ttl: TransientTtl(ttl),
})
} }
QueryType::PTR => { QueryType::PTR => {
let mut ptr = String::new(); let mut ptr = String::new();
buffer.read_qname(&mut ptr)?; buffer.read_qname(&mut ptr)?;
Ok(DnsRecord::PTR { Ok(DnsRecord::PTR { domain, data: ptr, ttl: TransientTtl(ttl) })
domain,
data: ptr,
ttl: TransientTtl(ttl),
})
} }
QueryType::MX => { QueryType::MX => {
let priority = buffer.read_u16()?; let priority = buffer.read_u16()?;
let mut mx = String::new(); let mut mx = String::new();
buffer.read_qname(&mut mx)?; buffer.read_qname(&mut mx)?;
Ok(DnsRecord::MX { Ok(DnsRecord::MX { domain, priority, host: mx, ttl: TransientTtl(ttl) })
domain,
priority,
host: mx,
ttl: TransientTtl(ttl),
})
} }
QueryType::SOA => { QueryType::SOA => {
let mut m_name = String::new(); let mut m_name = String::new();
@ -295,58 +260,31 @@ impl DnsRecord {
let expire = buffer.read_u32()?; let expire = buffer.read_u32()?;
let minimum = buffer.read_u32()?; let minimum = buffer.read_u32()?;
Ok(DnsRecord::SOA { Ok(DnsRecord::SOA { domain, m_name, r_name, serial, refresh, retry, expire, minimum, ttl: TransientTtl(ttl) })
domain,
m_name,
r_name,
serial,
refresh,
retry,
expire,
minimum,
ttl: TransientTtl(ttl),
})
} }
QueryType::TXT => { QueryType::TXT => {
let mut txt = String::new(); let mut txt = String::new();
let cur_pos = buffer.pos(); let cur_pos = buffer.pos();
txt.push_str(&String::from_utf8_lossy( txt.push_str(&String::from_utf8_lossy(buffer.get_range(cur_pos, data_len as usize)?));
buffer.get_range(cur_pos, data_len as usize)?,
));
buffer.step(data_len as usize)?; buffer.step(data_len as usize)?;
Ok(DnsRecord::TXT { Ok(DnsRecord::TXT { domain, data: txt, ttl: TransientTtl(ttl) })
domain,
data: txt,
ttl: TransientTtl(ttl),
})
} }
QueryType::OPT => { QueryType::OPT => {
let mut data = String::new(); let mut data = String::new();
let cur_pos = buffer.pos(); let cur_pos = buffer.pos();
data.push_str(&String::from_utf8_lossy( data.push_str(&String::from_utf8_lossy(buffer.get_range(cur_pos, data_len as usize)?));
buffer.get_range(cur_pos, data_len as usize)?,
));
buffer.step(data_len as usize)?; buffer.step(data_len as usize)?;
Ok(DnsRecord::OPT { Ok(DnsRecord::OPT { packet_len: class, flags: ttl, data })
packet_len: class,
flags: ttl,
data,
})
} }
QueryType::UNKNOWN(_) => { QueryType::UNKNOWN(_) => {
buffer.step(data_len as usize)?; buffer.step(data_len as usize)?;
Ok(DnsRecord::UNKNOWN { Ok(DnsRecord::UNKNOWN { domain, qtype: qtype_num, data_len, ttl: TransientTtl(ttl) })
domain,
qtype: qtype_num,
data_len,
ttl: TransientTtl(ttl),
})
} }
} }
} }
@ -355,11 +293,7 @@ impl DnsRecord {
let start_pos = buffer.pos(); let start_pos = buffer.pos();
match *self { match *self {
DnsRecord::A { DnsRecord::A { ref domain, ref addr, ttl: TransientTtl(ttl) } => {
ref domain,
ref addr,
ttl: TransientTtl(ttl),
} => {
buffer.write_qname(domain)?; buffer.write_qname(domain)?;
buffer.write_u16(QueryType::A.to_num())?; buffer.write_u16(QueryType::A.to_num())?;
buffer.write_u16(1)?; buffer.write_u16(1)?;
@ -372,11 +306,7 @@ impl DnsRecord {
buffer.write_u8(octets[2])?; buffer.write_u8(octets[2])?;
buffer.write_u8(octets[3])?; buffer.write_u8(octets[3])?;
} }
DnsRecord::AAAA { DnsRecord::AAAA { ref domain, ref addr, ttl: TransientTtl(ttl) } => {
ref domain,
ref addr,
ttl: TransientTtl(ttl),
} => {
buffer.write_qname(domain)?; buffer.write_qname(domain)?;
buffer.write_u16(QueryType::AAAA.to_num())?; buffer.write_u16(QueryType::AAAA.to_num())?;
buffer.write_u16(1)?; buffer.write_u16(1)?;
@ -387,11 +317,7 @@ impl DnsRecord {
buffer.write_u16(*octet)?; buffer.write_u16(*octet)?;
} }
} }
DnsRecord::NS { DnsRecord::NS { ref domain, ref host, ttl: TransientTtl(ttl) } => {
ref domain,
ref host,
ttl: TransientTtl(ttl),
} => {
buffer.write_qname(domain)?; buffer.write_qname(domain)?;
buffer.write_u16(QueryType::NS.to_num())?; buffer.write_u16(QueryType::NS.to_num())?;
buffer.write_u16(1)?; buffer.write_u16(1)?;
@ -405,11 +331,7 @@ impl DnsRecord {
let size = buffer.pos() - (pos + 2); let size = buffer.pos() - (pos + 2);
buffer.set_u16(pos, size as u16)?; buffer.set_u16(pos, size as u16)?;
} }
DnsRecord::CNAME { DnsRecord::CNAME { ref domain, ref host, ttl: TransientTtl(ttl) } => {
ref domain,
ref host,
ttl: TransientTtl(ttl),
} => {
buffer.write_qname(domain)?; buffer.write_qname(domain)?;
buffer.write_u16(QueryType::CNAME.to_num())?; buffer.write_u16(QueryType::CNAME.to_num())?;
buffer.write_u16(1)?; buffer.write_u16(1)?;
@ -423,14 +345,7 @@ impl DnsRecord {
let size = buffer.pos() - (pos + 2); let size = buffer.pos() - (pos + 2);
buffer.set_u16(pos, size as u16)?; buffer.set_u16(pos, size as u16)?;
} }
DnsRecord::SRV { DnsRecord::SRV { ref domain, priority, weight, port, ref host, ttl: TransientTtl(ttl) } => {
ref domain,
priority,
weight,
port,
ref host,
ttl: TransientTtl(ttl),
} => {
buffer.write_qname(domain)?; buffer.write_qname(domain)?;
buffer.write_u16(QueryType::SRV.to_num())?; buffer.write_u16(QueryType::SRV.to_num())?;
buffer.write_u16(1)?; buffer.write_u16(1)?;
@ -461,12 +376,7 @@ impl DnsRecord {
let size = buffer.pos() - (pos + 2); let size = buffer.pos() - (pos + 2);
buffer.set_u16(pos, size as u16)?; buffer.set_u16(pos, size as u16)?;
} }
DnsRecord::MX { DnsRecord::MX { ref domain, priority, ref host, ttl: TransientTtl(ttl) } => {
ref domain,
priority,
ref host,
ttl: TransientTtl(ttl),
} => {
buffer.write_qname(domain)?; buffer.write_qname(domain)?;
buffer.write_u16(QueryType::MX.to_num())?; buffer.write_u16(QueryType::MX.to_num())?;
buffer.write_u16(1)?; buffer.write_u16(1)?;
@ -481,17 +391,7 @@ impl DnsRecord {
let size = buffer.pos() - (pos + 2); let size = buffer.pos() - (pos + 2);
buffer.set_u16(pos, size as u16)?; buffer.set_u16(pos, size as u16)?;
} }
DnsRecord::SOA { DnsRecord::SOA { ref domain, ref m_name, ref r_name, serial, refresh, retry, expire, minimum, ttl: TransientTtl(ttl) } => {
ref domain,
ref m_name,
ref r_name,
serial,
refresh,
retry,
expire,
minimum,
ttl: TransientTtl(ttl),
} => {
buffer.write_qname(domain)?; buffer.write_qname(domain)?;
buffer.write_u16(QueryType::SOA.to_num())?; buffer.write_u16(QueryType::SOA.to_num())?;
buffer.write_u16(1)?; buffer.write_u16(1)?;
@ -511,11 +411,7 @@ impl DnsRecord {
let size = buffer.pos() - (pos + 2); let size = buffer.pos() - (pos + 2);
buffer.set_u16(pos, size as u16)?; buffer.set_u16(pos, size as u16)?;
} }
DnsRecord::TXT { DnsRecord::TXT { ref domain, ref data, ttl: TransientTtl(ttl) } => {
ref domain,
ref data,
ttl: TransientTtl(ttl),
} => {
buffer.write_qname(domain)?; buffer.write_qname(domain)?;
buffer.write_u16(QueryType::TXT.to_num())?; buffer.write_u16(QueryType::TXT.to_num())?;
buffer.write_u16(1)?; buffer.write_u16(1)?;
@ -590,47 +486,17 @@ impl DnsRecord {
pub fn get_ttl(&self) -> u32 { pub fn get_ttl(&self) -> u32 {
match *self { match *self {
DnsRecord::A { DnsRecord::A { ttl: TransientTtl(ttl), .. }
ttl: TransientTtl(ttl), | DnsRecord::AAAA { ttl: TransientTtl(ttl), .. }
.. | DnsRecord::NS { ttl: TransientTtl(ttl), .. }
} | DnsRecord::CNAME { ttl: TransientTtl(ttl), .. }
| DnsRecord::AAAA { | DnsRecord::SRV { ttl: TransientTtl(ttl), .. }
ttl: TransientTtl(ttl), | DnsRecord::PTR { ttl: TransientTtl(ttl), .. }
.. | DnsRecord::MX { ttl: TransientTtl(ttl), .. }
} | DnsRecord::UNKNOWN { ttl: TransientTtl(ttl), .. }
| DnsRecord::NS { | DnsRecord::SOA { ttl: TransientTtl(ttl), .. }
ttl: TransientTtl(ttl), | DnsRecord::TXT { ttl: TransientTtl(ttl), .. } => ttl,
.. DnsRecord::OPT { .. } => 0
}
| DnsRecord::CNAME {
ttl: TransientTtl(ttl),
..
}
| DnsRecord::SRV {
ttl: TransientTtl(ttl),
..
}
| DnsRecord::PTR {
ttl: TransientTtl(ttl),
..
}
| DnsRecord::MX {
ttl: TransientTtl(ttl),
..
}
| DnsRecord::UNKNOWN {
ttl: TransientTtl(ttl),
..
}
| DnsRecord::SOA {
ttl: TransientTtl(ttl),
..
}
| DnsRecord::TXT {
ttl: TransientTtl(ttl),
..
} => ttl,
DnsRecord::OPT { .. } => 0,
} }
} }
} }
@ -643,7 +509,7 @@ pub enum ResultCode {
SERVFAIL = 2, SERVFAIL = 2,
NXDOMAIN = 3, NXDOMAIN = 3,
NOTIMP = 4, NOTIMP = 4,
REFUSED = 5, REFUSED = 5
} }
impl Default for ResultCode { impl Default for ResultCode {
@ -660,7 +526,7 @@ impl ResultCode {
3 => ResultCode::NXDOMAIN, 3 => ResultCode::NXDOMAIN,
4 => ResultCode::NOTIMP, 4 => ResultCode::NOTIMP,
5 => ResultCode::REFUSED, 5 => ResultCode::REFUSED,
0 | _ => ResultCode::NOERROR, 0 | _ => ResultCode::NOERROR
} }
} }
} }
@ -685,7 +551,7 @@ pub struct DnsHeader {
pub questions: u16, // 16 bits pub questions: u16, // 16 bits
pub answers: u16, // 16 bits pub answers: u16, // 16 bits
pub authoritative_entries: u16, // 16 bits pub authoritative_entries: u16, // 16 bits
pub resource_entries: u16, // 16 bits pub resource_entries: u16 // 16 bits
} }
impl DnsHeader { impl DnsHeader {
@ -708,7 +574,7 @@ impl DnsHeader {
questions: 0, questions: 0,
answers: 0, answers: 0,
authoritative_entries: 0, authoritative_entries: 0,
resource_entries: 0, resource_entries: 0
} }
} }
@ -720,7 +586,7 @@ impl DnsHeader {
| ((self.truncated_message as u8) << 1) | ((self.truncated_message as u8) << 1)
| ((self.authoritative_answer as u8) << 2) | ((self.authoritative_answer as u8) << 2)
| (self.opcode << 3) | (self.opcode << 3)
| ((self.response as u8) << 7) as u8, | ((self.response as u8) << 7) as u8
)?; )?;
buffer.write_u8( buffer.write_u8(
@ -728,7 +594,7 @@ impl DnsHeader {
| ((self.checking_disabled as u8) << 4) | ((self.checking_disabled as u8) << 4)
| ((self.authed_data as u8) << 5) | ((self.authed_data as u8) << 5)
| ((self.z as u8) << 6) | ((self.z as u8) << 6)
| ((self.recursion_available as u8) << 7), | ((self.recursion_available as u8) << 7)
)?; )?;
buffer.write_u16(self.questions)?; buffer.write_u16(self.questions)?;
@ -778,11 +644,7 @@ impl fmt::Display for DnsHeader {
write!(f, "\trecursion_desired: {0}\n", self.recursion_desired)?; write!(f, "\trecursion_desired: {0}\n", self.recursion_desired)?;
write!(f, "\ttruncated_message: {0}\n", self.truncated_message)?; write!(f, "\ttruncated_message: {0}\n", self.truncated_message)?;
write!( write!(f, "\tauthoritative_answer: {0}\n", self.authoritative_answer)?;
f,
"\tauthoritative_answer: {0}\n",
self.authoritative_answer
)?;
write!(f, "\topcode: {0}\n", self.opcode)?; write!(f, "\topcode: {0}\n", self.opcode)?;
write!(f, "\tresponse: {0}\n", self.response)?; write!(f, "\tresponse: {0}\n", self.response)?;
@ -794,11 +656,7 @@ impl fmt::Display for DnsHeader {
write!(f, "\tquestions: {0}\n", self.questions)?; write!(f, "\tquestions: {0}\n", self.questions)?;
write!(f, "\tanswers: {0}\n", self.answers)?; write!(f, "\tanswers: {0}\n", self.answers)?;
write!( write!(f, "\tauthoritative_entries: {0}\n", self.authoritative_entries)?;
f,
"\tauthoritative_entries: {0}\n",
self.authoritative_entries
)?;
write!(f, "\tresource_entries: {0}\n", self.resource_entries)?; write!(f, "\tresource_entries: {0}\n", self.resource_entries)?;
Ok(()) Ok(())
@ -809,7 +667,7 @@ impl fmt::Display for DnsHeader {
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct DnsQuestion { pub struct DnsQuestion {
pub name: String, pub name: String,
pub qtype: QueryType, pub qtype: QueryType
} }
impl DnsQuestion { impl DnsQuestion {
@ -818,10 +676,7 @@ impl DnsQuestion {
} }
pub fn binary_len(&self) -> usize { pub fn binary_len(&self) -> usize {
self.name self.name.split('.').map(|x| x.len() + 1).fold(1, |x, y| x + y)
.split('.')
.map(|x| x.len() + 1)
.fold(1, |x, y| x + y)
} }
pub fn write<T: PacketBuffer>(&self, buffer: &mut T) -> Result<()> { pub fn write<T: PacketBuffer>(&self, buffer: &mut T) -> Result<()> {
@ -864,18 +719,12 @@ pub struct DnsPacket {
pub questions: Vec<DnsQuestion>, pub questions: Vec<DnsQuestion>,
pub answers: Vec<DnsRecord>, pub answers: Vec<DnsRecord>,
pub authorities: Vec<DnsRecord>, pub authorities: Vec<DnsRecord>,
pub resources: Vec<DnsRecord>, pub resources: Vec<DnsRecord>
} }
impl DnsPacket { impl DnsPacket {
pub fn new() -> DnsPacket { pub fn new() -> DnsPacket {
DnsPacket { DnsPacket { header: DnsHeader::new(), questions: Vec::new(), answers: Vec::new(), authorities: Vec::new(), resources: Vec::new() }
header: DnsHeader::new(),
questions: Vec::new(),
answers: Vec::new(),
authorities: Vec::new(),
resources: Vec::new(),
}
} }
pub fn from_buffer<T: PacketBuffer>(buffer: &mut T) -> Result<DnsPacket> { pub fn from_buffer<T: PacketBuffer>(buffer: &mut T) -> Result<DnsPacket> {
@ -977,32 +826,18 @@ impl DnsPacket {
pub fn get_resolved_ns(&self, qname: &str) -> Option<String> { pub fn get_resolved_ns(&self, qname: &str) -> Option<String> {
let mut new_authorities = Vec::new(); let mut new_authorities = Vec::new();
for auth in &self.authorities { for auth in &self.authorities {
if let DnsRecord::NS { if let DnsRecord::NS { ref domain, ref host, .. } = *auth {
ref domain,
ref host,
..
} = *auth
{
if !qname.ends_with(domain) { if !qname.ends_with(domain) {
continue; continue;
} }
for rsrc in &self.resources { for rsrc in &self.resources {
if let DnsRecord::A { if let DnsRecord::A { ref domain, ref addr, ttl: TransientTtl(ttl) } = *rsrc {
ref domain,
ref addr,
ttl: TransientTtl(ttl),
} = *rsrc
{
if domain != host { if domain != host {
continue; continue;
} }
let rec = DnsRecord::A { let rec = DnsRecord::A { domain: host.clone(), addr: *addr, ttl: TransientTtl(ttl) };
domain: host.clone(),
addr: *addr,
ttl: TransientTtl(ttl),
};
new_authorities.push(rec); new_authorities.push(rec);
} }
@ -1023,12 +858,7 @@ impl DnsPacket {
pub fn get_unresolved_ns(&self, qname: &str) -> Option<String> { pub fn get_unresolved_ns(&self, qname: &str) -> Option<String> {
let mut new_authorities = Vec::new(); let mut new_authorities = Vec::new();
for auth in &self.authorities { for auth in &self.authorities {
if let DnsRecord::NS { if let DnsRecord::NS { ref domain, ref host, .. } = *auth {
ref domain,
ref host,
..
} = *auth
{
if !qname.ends_with(domain) { if !qname.ends_with(domain) {
continue; continue;
} }
@ -1056,13 +886,7 @@ impl DnsPacket {
let mut record_count = self.answers.len() + self.authorities.len() + self.resources.len(); let mut record_count = self.answers.len() + self.authorities.len() + self.resources.len();
for (i, rec) in self for (i, rec) in self.answers.iter().chain(self.authorities.iter()).chain(self.resources.iter()).enumerate() {
.answers
.iter()
.chain(self.authorities.iter())
.chain(self.resources.iter())
.enumerate()
{
size += rec.write(&mut test_buffer)?; size += rec.write(&mut test_buffer)?;
if size > max_size { if size > max_size {
record_count = i; record_count = i;
@ -1085,13 +909,7 @@ impl DnsPacket {
question.write(buffer)?; question.write(buffer)?;
} }
for rec in self for rec in self.answers.iter().chain(self.authorities.iter()).chain(self.resources.iter()).take(record_count) {
.answers
.iter()
.chain(self.authorities.iter())
.chain(self.resources.iter())
.take(record_count)
{
rec.write(buffer)?; rec.write(buffer)?;
} }
@ -1111,29 +929,27 @@ mod tests {
packet.header.id = 1337; packet.header.id = 1337;
packet.header.response = true; packet.header.response = true;
packet packet.questions.push(DnsQuestion::new("google.com".to_string(), QueryType::NS));
.questions
.push(DnsQuestion::new("google.com".to_string(), QueryType::NS));
//packet.answers.push(DnsRecord::A("ns1.google.com".to_string(), "127.0.0.1".parse::<Ipv4Addr>().unwrap(), 3600)); //packet.answers.push(DnsRecord::A("ns1.google.com".to_string(), "127.0.0.1".parse::<Ipv4Addr>().unwrap(), 3600));
packet.answers.push(DnsRecord::NS { packet.answers.push(DnsRecord::NS {
domain: "google.com".to_string(), domain: "google.com".to_string(),
host: "ns1.google.com".to_string(), host: "ns1.google.com".to_string(),
ttl: TransientTtl(3600), ttl: TransientTtl(3600)
}); });
packet.answers.push(DnsRecord::NS { packet.answers.push(DnsRecord::NS {
domain: "google.com".to_string(), domain: "google.com".to_string(),
host: "ns2.google.com".to_string(), host: "ns2.google.com".to_string(),
ttl: TransientTtl(3600), ttl: TransientTtl(3600)
}); });
packet.answers.push(DnsRecord::NS { packet.answers.push(DnsRecord::NS {
domain: "google.com".to_string(), domain: "google.com".to_string(),
host: "ns3.google.com".to_string(), host: "ns3.google.com".to_string(),
ttl: TransientTtl(3600), ttl: TransientTtl(3600)
}); });
packet.answers.push(DnsRecord::NS { packet.answers.push(DnsRecord::NS {
domain: "google.com".to_string(), domain: "google.com".to_string(),
host: "ns4.google.com".to_string(), host: "ns4.google.com".to_string(),
ttl: TransientTtl(3600), ttl: TransientTtl(3600)
}); });
let mut buffer = VectorPacketBuffer::new(); let mut buffer = VectorPacketBuffer::new();

@ -5,17 +5,17 @@ use std::sync::Arc;
use std::vec::Vec; use std::vec::Vec;
use derive_more::{Display, Error, From}; use derive_more::{Display, Error, From};
use rand::seq::IteratorRandom;
use crate::dns::context::ServerContext; use crate::dns::context::ServerContext;
use crate::dns::protocol::{DnsPacket, QueryType, ResultCode}; use crate::dns::protocol::{DnsPacket, QueryType, ResultCode};
use rand::seq::IteratorRandom;
#[derive(Debug, Display, From, Error)] #[derive(Debug, Display, From, Error)]
pub enum ResolveError { pub enum ResolveError {
Client(crate::dns::client::ClientError), Client(crate::dns::client::ClientError),
Cache(crate::dns::cache::CacheError), Cache(crate::dns::cache::CacheError),
Io(std::io::Error), Io(std::io::Error),
NoServerFound, NoServerFound
} }
type Result<T> = std::result::Result<T, ResolveError>; type Result<T> = std::result::Result<T, ResolveError>;
@ -69,7 +69,7 @@ pub trait DnsResolver {
/// This resolver uses an external DNS server to service a query /// This resolver uses an external DNS server to service a query
pub struct ForwardingDnsResolver { pub struct ForwardingDnsResolver {
context: Arc<ServerContext>, context: Arc<ServerContext>,
upstreams: Vec<String>, upstreams: Vec<String>
} }
impl ForwardingDnsResolver { impl ForwardingDnsResolver {
@ -87,9 +87,7 @@ impl DnsResolver for ForwardingDnsResolver {
let mut random = rand::thread_rng(); let mut random = rand::thread_rng();
let upstream = self.upstreams.iter().choose(&mut random).unwrap(); let upstream = self.upstreams.iter().choose(&mut random).unwrap();
let result = match self.context.cache.lookup(qname, qtype) { let result = match self.context.cache.lookup(qname, qtype) {
None => { None => self.context.client.send_query(qname, qtype, upstream, true)?,
self.context.client.send_query(qname, qtype, upstream, true)?
}
Some(packet) => packet Some(packet) => packet
}; };
@ -103,7 +101,7 @@ impl DnsResolver for ForwardingDnsResolver {
/// ///
/// This resolver can answer any request using the root servers of the internet /// This resolver can answer any request using the root servers of the internet
pub struct RecursiveDnsResolver { pub struct RecursiveDnsResolver {
context: Arc<ServerContext>, context: Arc<ServerContext>
} }
impl RecursiveDnsResolver { impl RecursiveDnsResolver {
@ -139,7 +137,7 @@ impl DnsResolver for RecursiveDnsResolver {
tentative_ns = Some(addr); tentative_ns = Some(addr);
break; break;
} }
None => continue, None => continue
} }
} }
@ -152,10 +150,7 @@ impl DnsResolver for RecursiveDnsResolver {
let ns_copy = ns.clone(); let ns_copy = ns.clone();
let server = format!("{}:{}", ns_copy.as_str(), 53); let server = format!("{}:{}", ns_copy.as_str(), 53);
let response = self let response = self.context.client.send_query(qname, qtype.clone(), &server, false)?;
.context
.client
.send_query(qname, qtype.clone(), &server, false)?;
// If we've got an actual answer, we're done! // If we've got an actual answer, we're done!
if !response.answers.is_empty() && response.header.rescode == ResultCode::NOERROR { if !response.answers.is_empty() && response.header.rescode == ResultCode::NOERROR {
@ -187,7 +182,7 @@ impl DnsResolver for RecursiveDnsResolver {
// If not, we'll have to resolve the ip of a NS record // If not, we'll have to resolve the ip of a NS record
let new_ns_name = match response.get_unresolved_ns(qname) { let new_ns_name = match response.get_unresolved_ns(qname) {
Some(x) => x, Some(x) => x,
None => return Ok(response.clone()), None => return Ok(response.clone())
}; };
// Recursively resolve the NS // Recursively resolve the NS
@ -208,12 +203,10 @@ mod tests {
use std::sync::Arc; use std::sync::Arc;
use crate::dns::protocol::{DnsPacket, DnsRecord, QueryType, ResultCode, TransientTtl};
use super::*; use super::*;
use crate::dns::context::tests::create_test_context; use crate::dns::context::tests::create_test_context;
use crate::dns::context::ResolveStrategy; use crate::dns::context::ResolveStrategy;
use crate::dns::protocol::{DnsPacket, DnsRecord, QueryType, ResultCode, TransientTtl};
#[test] #[test]
fn test_forwarding_resolver() { fn test_forwarding_resolver() {
@ -224,7 +217,7 @@ mod tests {
packet.answers.push(DnsRecord::A { packet.answers.push(DnsRecord::A {
domain: "google.com".to_string(), domain: "google.com".to_string(),
addr: "127.0.0.1".parse().unwrap(), addr: "127.0.0.1".parse().unwrap(),
ttl: TransientTtl(3600), ttl: TransientTtl(3600)
}); });
} else { } else {
packet.header.rescode = ResultCode::NXDOMAIN; packet.header.rescode = ResultCode::NXDOMAIN;
@ -235,11 +228,9 @@ mod tests {
match Arc::get_mut(&mut context) { match Arc::get_mut(&mut context) {
Some(mut ctx) => { Some(mut ctx) => {
ctx.resolve_strategy = ResolveStrategy::Forward { ctx.resolve_strategy = ResolveStrategy::Forward { upstreams: vec![String::from("127.0.0.1:53")] };
upstreams: vec![String::from("127.0.0.1:53")]
};
} }
None => panic!(), None => panic!()
} }
let mut resolver = context.create_resolver(Arc::clone(&context)); let mut resolver = context.create_resolver(Arc::clone(&context));
@ -248,7 +239,7 @@ mod tests {
{ {
let res = match resolver.resolve("google.com", QueryType::A, true) { let res = match resolver.resolve("google.com", QueryType::A, true) {
Ok(x) => x, Ok(x) => x,
Err(_) => panic!(), Err(_) => panic!()
}; };
assert_eq!(1, res.answers.len()); assert_eq!(1, res.answers.len());
@ -257,7 +248,7 @@ mod tests {
DnsRecord::A { ref domain, .. } => { DnsRecord::A { ref domain, .. } => {
assert_eq!("google.com", domain); assert_eq!("google.com", domain);
} }
_ => panic!(), _ => panic!()
} }
}; };
@ -266,14 +257,14 @@ mod tests {
{ {
let res = match resolver.resolve("google.com", QueryType::A, true) { let res = match resolver.resolve("google.com", QueryType::A, true) {
Ok(x) => x, Ok(x) => x,
Err(_) => panic!(), Err(_) => panic!()
}; };
assert_eq!(1, res.answers.len()); assert_eq!(1, res.answers.len());
let list = match context.cache.list() { let list = match context.cache.list() {
Ok(x) => x, Ok(x) => x,
Err(_) => panic!(), Err(_) => panic!()
}; };
assert_eq!(1, list.len()); assert_eq!(1, list.len());
@ -287,7 +278,7 @@ mod tests {
{ {
let res = match resolver.resolve("yahoo.com", QueryType::A, true) { let res = match resolver.resolve("yahoo.com", QueryType::A, true) {
Ok(x) => x, Ok(x) => x,
Err(_) => panic!(), Err(_) => panic!()
}; };
assert_eq!(0, res.answers.len()); assert_eq!(0, res.answers.len());
@ -328,11 +319,7 @@ mod tests {
// Insert name server, but no corresponding A record // Insert name server, but no corresponding A record
let mut nameservers = Vec::new(); let mut nameservers = Vec::new();
nameservers.push(DnsRecord::NS { nameservers.push(DnsRecord::NS { domain: "".to_string(), host: "a.myroot.net".to_string(), ttl: TransientTtl(3600) });
domain: "".to_string(),
host: "a.myroot.net".to_string(),
ttl: TransientTtl(3600),
});
let _ = context.cache.store(&nameservers); let _ = context.cache.store(&nameservers);
@ -352,7 +339,7 @@ mod tests {
packet.answers.push(DnsRecord::A { packet.answers.push(DnsRecord::A {
domain: "a.google.com".to_string(), domain: "a.google.com".to_string(),
addr: "127.0.0.1".parse().unwrap(), addr: "127.0.0.1".parse().unwrap(),
ttl: TransientTtl(3600), ttl: TransientTtl(3600)
}); });
return Ok(packet); return Ok(packet);
@ -362,7 +349,7 @@ mod tests {
packet.answers.push(DnsRecord::A { packet.answers.push(DnsRecord::A {
domain: "b.google.com".to_string(), domain: "b.google.com".to_string(),
addr: "127.0.0.1".parse().unwrap(), addr: "127.0.0.1".parse().unwrap(),
ttl: TransientTtl(3600), ttl: TransientTtl(3600)
}); });
return Ok(packet); return Ok(packet);
@ -372,7 +359,7 @@ mod tests {
packet.answers.push(DnsRecord::A { packet.answers.push(DnsRecord::A {
domain: "c.google.com".to_string(), domain: "c.google.com".to_string(),
addr: "127.0.0.1".parse().unwrap(), addr: "127.0.0.1".parse().unwrap(),
ttl: TransientTtl(3600), ttl: TransientTtl(3600)
}); });
return Ok(packet); return Ok(packet);
@ -393,15 +380,11 @@ mod tests {
// Insert root servers // Insert root servers
{ {
let mut nameservers = Vec::new(); let mut nameservers = Vec::new();
nameservers.push(DnsRecord::NS { nameservers.push(DnsRecord::NS { domain: "".to_string(), host: "a.myroot.net".to_string(), ttl: TransientTtl(3600) });
domain: "".to_string(),
host: "a.myroot.net".to_string(),
ttl: TransientTtl(3600),
});
nameservers.push(DnsRecord::A { nameservers.push(DnsRecord::A {
domain: "a.myroot.net".to_string(), domain: "a.myroot.net".to_string(),
addr: "127.0.0.1".parse().unwrap(), addr: "127.0.0.1".parse().unwrap(),
ttl: TransientTtl(3600), ttl: TransientTtl(3600)
}); });
let _ = context.cache.store(&nameservers); let _ = context.cache.store(&nameservers);
@ -411,21 +394,17 @@ mod tests {
Ok(packet) => { Ok(packet) => {
assert_eq!(1, packet.header.id); assert_eq!(1, packet.header.id);
} }
Err(_) => panic!(), Err(_) => panic!()
} }
// Insert TLD servers // Insert TLD servers
{ {
let mut nameservers = Vec::new(); let mut nameservers = Vec::new();
nameservers.push(DnsRecord::NS { nameservers.push(DnsRecord::NS { domain: "com".to_string(), host: "a.mytld.net".to_string(), ttl: TransientTtl(3600) });
domain: "com".to_string(),
host: "a.mytld.net".to_string(),
ttl: TransientTtl(3600),
});
nameservers.push(DnsRecord::A { nameservers.push(DnsRecord::A {
domain: "a.mytld.net".to_string(), domain: "a.mytld.net".to_string(),
addr: "127.0.0.2".parse().unwrap(), addr: "127.0.0.2".parse().unwrap(),
ttl: TransientTtl(3600), ttl: TransientTtl(3600)
}); });
let _ = context.cache.store(&nameservers); let _ = context.cache.store(&nameservers);
@ -435,7 +414,7 @@ mod tests {
Ok(packet) => { Ok(packet) => {
assert_eq!(2, packet.header.id); assert_eq!(2, packet.header.id);
} }
Err(_) => panic!(), Err(_) => panic!()
} }
// Insert authoritative servers // Insert authoritative servers
@ -444,12 +423,12 @@ mod tests {
nameservers.push(DnsRecord::NS { nameservers.push(DnsRecord::NS {
domain: "google.com".to_string(), domain: "google.com".to_string(),
host: "ns1.google.com".to_string(), host: "ns1.google.com".to_string(),
ttl: TransientTtl(3600), ttl: TransientTtl(3600)
}); });
nameservers.push(DnsRecord::A { nameservers.push(DnsRecord::A {
domain: "ns1.google.com".to_string(), domain: "ns1.google.com".to_string(),
addr: "127.0.0.3".parse().unwrap(), addr: "127.0.0.3".parse().unwrap(),
ttl: TransientTtl(3600), ttl: TransientTtl(3600)
}); });
let _ = context.cache.store(&nameservers); let _ = context.cache.store(&nameservers);
@ -459,7 +438,7 @@ mod tests {
Ok(packet) => { Ok(packet) => {
assert_eq!(3, packet.header.id); assert_eq!(3, packet.header.id);
} }
Err(_) => panic!(), Err(_) => panic!()
} }
} }
@ -472,7 +451,7 @@ mod tests {
packet.answers.push(DnsRecord::A { packet.answers.push(DnsRecord::A {
domain: "google.com".to_string(), domain: "google.com".to_string(),
addr: "127.0.0.1".parse().unwrap(), addr: "127.0.0.1".parse().unwrap(),
ttl: TransientTtl(3600), ttl: TransientTtl(3600)
}); });
} else { } else {
packet.header.rescode = ResultCode::NXDOMAIN; packet.header.rescode = ResultCode::NXDOMAIN;
@ -486,7 +465,7 @@ mod tests {
retry: 3600, retry: 3600,
expire: 3600, expire: 3600,
minimum: 3600, minimum: 3600,
ttl: TransientTtl(3600), ttl: TransientTtl(3600)
}); });
} }
@ -497,15 +476,11 @@ mod tests {
// Insert name servers // Insert name servers
let mut nameservers = Vec::new(); let mut nameservers = Vec::new();
nameservers.push(DnsRecord::NS { nameservers.push(DnsRecord::NS { domain: "google.com".to_string(), host: "ns1.google.com".to_string(), ttl: TransientTtl(3600) });
domain: "google.com".to_string(),
host: "ns1.google.com".to_string(),
ttl: TransientTtl(3600),
});
nameservers.push(DnsRecord::A { nameservers.push(DnsRecord::A {
domain: "ns1.google.com".to_string(), domain: "ns1.google.com".to_string(),
addr: "127.0.0.1".parse().unwrap(), addr: "127.0.0.1".parse().unwrap(),
ttl: TransientTtl(3600), ttl: TransientTtl(3600)
}); });
let _ = context.cache.store(&nameservers); let _ = context.cache.store(&nameservers);
@ -514,7 +489,7 @@ mod tests {
{ {
let res = match resolver.resolve("google.com", QueryType::A, true) { let res = match resolver.resolve("google.com", QueryType::A, true) {
Ok(x) => x, Ok(x) => x,
Err(_) => panic!(), Err(_) => panic!()
}; };
assert_eq!(1, res.answers.len()); assert_eq!(1, res.answers.len());
@ -523,7 +498,7 @@ mod tests {
DnsRecord::A { ref domain, .. } => { DnsRecord::A { ref domain, .. } => {
assert_eq!("google.com", domain); assert_eq!("google.com", domain);
} }
_ => panic!(), _ => panic!()
} }
}; };
@ -531,7 +506,7 @@ mod tests {
{ {
let res = match resolver.resolve("foobar.google.com", QueryType::A, true) { let res = match resolver.resolve("foobar.google.com", QueryType::A, true) {
Ok(x) => x, Ok(x) => x,
Err(_) => panic!(), Err(_) => panic!()
}; };
assert_eq!(ResultCode::NXDOMAIN, res.header.rescode); assert_eq!(ResultCode::NXDOMAIN, res.header.rescode);
@ -542,7 +517,7 @@ mod tests {
{ {
let res = match resolver.resolve("google.com", QueryType::A, true) { let res = match resolver.resolve("google.com", QueryType::A, true) {
Ok(x) => x, Ok(x) => x,
Err(_) => panic!(), Err(_) => panic!()
}; };
assert_eq!(1, res.answers.len()); assert_eq!(1, res.answers.len());
@ -552,7 +527,7 @@ mod tests {
{ {
let list = match context.cache.list() { let list = match context.cache.list() {
Ok(x) => x, Ok(x) => x,
Err(_) => panic!(), Err(_) => panic!()
}; };
assert_eq!(3, list.len()); assert_eq!(3, list.len());

@ -2,16 +2,15 @@
use std::collections::VecDeque; use std::collections::VecDeque;
use std::io::Write; use std::io::Write;
use std::net::SocketAddr; use std::net::{Shutdown, SocketAddr, TcpListener, TcpStream, UdpSocket};
use std::net::{Shutdown, TcpListener, TcpStream, UdpSocket};
use std::sync::atomic::Ordering; use std::sync::atomic::Ordering;
use std::sync::mpsc::{channel, Sender}; use std::sync::mpsc::{channel, Sender};
use std::sync::{Arc, Condvar, Mutex}; use std::sync::{Arc, Condvar, Mutex};
use std::thread::Builder; use std::thread::Builder;
use derive_more::{Display, Error, From}; use derive_more::{Display, Error, From};
use log::{debug, error, warn};
use rand::random; use rand::random;
use log::{error, warn, debug};
use crate::dns::buffer::{BytePacketBuffer, PacketBuffer, StreamPacketBuffer, VectorPacketBuffer}; use crate::dns::buffer::{BytePacketBuffer, PacketBuffer, StreamPacketBuffer, VectorPacketBuffer};
use crate::dns::context::ServerContext; use crate::dns::context::ServerContext;
@ -21,7 +20,7 @@ use crate::dns::resolve::DnsResolver;
#[derive(Debug, Display, From, Error)] #[derive(Debug, Display, From, Error)]
pub enum ServerError { pub enum ServerError {
Io(std::io::Error), Io(std::io::Error)
} }
type Result<T> = std::result::Result<T, ServerError>; type Result<T> = std::result::Result<T, ServerError>;
@ -61,7 +60,7 @@ pub trait DnsServer {
/// Utility function for resolving domains referenced in for example CNAME or SRV /// Utility function for resolving domains referenced in for example CNAME or SRV
/// records. This usually spares the client from having to perform additional lookups. /// records. This usually spares the client from having to perform additional lookups.
fn resolve_cnames(lookup_list: &[DnsRecord], results: &mut Vec<DnsPacket>, resolver: &mut Box<dyn DnsResolver>, depth: u16,) { fn resolve_cnames(lookup_list: &[DnsRecord], results: &mut Vec<DnsPacket>, resolver: &mut Box<dyn DnsResolver>, depth: u16) {
if depth > 10 { if depth > 10 {
return; return;
} }
@ -161,17 +160,12 @@ pub struct DnsUdpServer {
context: Arc<ServerContext>, context: Arc<ServerContext>,
request_queue: Arc<Mutex<VecDeque<(SocketAddr, DnsPacket)>>>, request_queue: Arc<Mutex<VecDeque<(SocketAddr, DnsPacket)>>>,
request_cond: Arc<Condvar>, request_cond: Arc<Condvar>,
thread_count: usize, thread_count: usize
} }
impl DnsUdpServer { impl DnsUdpServer {
pub fn new(context: Arc<ServerContext>, thread_count: usize) -> DnsUdpServer { pub fn new(context: Arc<ServerContext>, thread_count: usize) -> DnsUdpServer {
DnsUdpServer { DnsUdpServer { context, request_queue: Arc::new(Mutex::new(VecDeque::new())), request_cond: Arc::new(Condvar::new()), thread_count }
context,
request_queue: Arc::new(Mutex::new(VecDeque::new())),
request_cond: Arc::new(Condvar::new()),
thread_count,
}
} }
} }
@ -292,7 +286,7 @@ impl DnsServer for DnsUdpServer {
pub struct DnsTcpServer { pub struct DnsTcpServer {
context: Arc<ServerContext>, context: Arc<ServerContext>,
senders: Vec<Sender<TcpStream>>, senders: Vec<Sender<TcpStream>>,
thread_count: usize, thread_count: usize
} }
impl DnsTcpServer { impl DnsTcpServer {
@ -318,7 +312,7 @@ impl DnsServer for DnsTcpServer {
loop { loop {
let mut stream = match rx.recv() { let mut stream = match rx.recv() {
Ok(x) => x, Ok(x) => x,
Err(_) => continue, Err(_) => continue
}; };
let _ = context.statistics.tcp_query_count.fetch_add(1, Ordering::Release); let _ = context.statistics.tcp_query_count.fetch_add(1, Ordering::Release);
@ -392,22 +386,16 @@ mod tests {
use std::net::Ipv4Addr; use std::net::Ipv4Addr;
use std::sync::Arc; use std::sync::Arc;
use crate::dns::protocol::{
DnsPacket, DnsQuestion, DnsRecord, QueryType, ResultCode, TransientTtl,
};
use super::*; use super::*;
use crate::dns::context::tests::create_test_context; use crate::dns::context::tests::create_test_context;
use crate::dns::context::ResolveStrategy; use crate::dns::context::ResolveStrategy;
use crate::dns::protocol::{DnsPacket, DnsQuestion, DnsRecord, QueryType, ResultCode, TransientTtl};
fn build_query(qname: &str, qtype: QueryType) -> DnsPacket { fn build_query(qname: &str, qtype: QueryType) -> DnsPacket {
let mut query_packet = DnsPacket::new(); let mut query_packet = DnsPacket::new();
query_packet.header.recursion_desired = true; query_packet.header.recursion_desired = true;
query_packet query_packet.questions.push(DnsQuestion::new(qname.into(), qtype));
.questions
.push(DnsQuestion::new(qname.into(), qtype));
query_packet query_packet
} }
@ -422,30 +410,30 @@ mod tests {
packet.answers.push(DnsRecord::A { packet.answers.push(DnsRecord::A {
domain: "google.com".to_string(), domain: "google.com".to_string(),
addr: "127.0.0.1".parse::<Ipv4Addr>().unwrap(), addr: "127.0.0.1".parse::<Ipv4Addr>().unwrap(),
ttl: TransientTtl(3600), ttl: TransientTtl(3600)
}); });
} else if qname == "www.facebook.com" && qtype == QueryType::CNAME { } else if qname == "www.facebook.com" && qtype == QueryType::CNAME {
packet.answers.push(DnsRecord::CNAME { packet.answers.push(DnsRecord::CNAME {
domain: "www.facebook.com".to_string(), domain: "www.facebook.com".to_string(),
host: "cdn.facebook.com".to_string(), host: "cdn.facebook.com".to_string(),
ttl: TransientTtl(3600), ttl: TransientTtl(3600)
}); });
packet.answers.push(DnsRecord::A { packet.answers.push(DnsRecord::A {
domain: "cdn.facebook.com".to_string(), domain: "cdn.facebook.com".to_string(),
addr: "127.0.0.1".parse::<Ipv4Addr>().unwrap(), addr: "127.0.0.1".parse::<Ipv4Addr>().unwrap(),
ttl: TransientTtl(3600), ttl: TransientTtl(3600)
}); });
} else if qname == "www.microsoft.com" && qtype == QueryType::CNAME { } else if qname == "www.microsoft.com" && qtype == QueryType::CNAME {
packet.answers.push(DnsRecord::CNAME { packet.answers.push(DnsRecord::CNAME {
domain: "www.microsoft.com".to_string(), domain: "www.microsoft.com".to_string(),
host: "cdn.microsoft.com".to_string(), host: "cdn.microsoft.com".to_string(),
ttl: TransientTtl(3600), ttl: TransientTtl(3600)
}); });
} else if qname == "cdn.microsoft.com" && qtype == QueryType::A { } else if qname == "cdn.microsoft.com" && qtype == QueryType::A {
packet.answers.push(DnsRecord::A { packet.answers.push(DnsRecord::A {
domain: "cdn.microsoft.com".to_string(), domain: "cdn.microsoft.com".to_string(),
addr: "127.0.0.1".parse::<Ipv4Addr>().unwrap(), addr: "127.0.0.1".parse::<Ipv4Addr>().unwrap(),
ttl: TransientTtl(3600), ttl: TransientTtl(3600)
}); });
} else { } else {
packet.header.rescode = ResultCode::NXDOMAIN; packet.header.rescode = ResultCode::NXDOMAIN;
@ -456,11 +444,9 @@ mod tests {
match Arc::get_mut(&mut context) { match Arc::get_mut(&mut context) {
Some(mut ctx) => { Some(mut ctx) => {
ctx.resolve_strategy = ResolveStrategy::Forward { ctx.resolve_strategy = ResolveStrategy::Forward { upstreams: vec![String::from("127.0.0.1:53")] };
upstreams: vec![String::from("127.0.0.1:53")]
};
} }
None => panic!(), None => panic!()
} }
// A successful resolve // A successful resolve
@ -472,53 +458,47 @@ mod tests {
DnsRecord::A { ref domain, .. } => { DnsRecord::A { ref domain, .. } => {
assert_eq!("google.com", domain); assert_eq!("google.com", domain);
} }
_ => panic!(), _ => panic!()
} }
}; };
// A successful resolve, that also resolves a CNAME without recursive lookup // A successful resolve, that also resolves a CNAME without recursive lookup
{ {
let res = execute_query( let res = execute_query(Arc::clone(&context), &build_query("www.facebook.com", QueryType::CNAME));
Arc::clone(&context),
&build_query("www.facebook.com", QueryType::CNAME),
);
assert_eq!(2, res.answers.len()); assert_eq!(2, res.answers.len());
match res.answers[0] { match res.answers[0] {
DnsRecord::CNAME { ref domain, .. } => { DnsRecord::CNAME { ref domain, .. } => {
assert_eq!("www.facebook.com", domain); assert_eq!("www.facebook.com", domain);
} }
_ => panic!(), _ => panic!()
} }
match res.answers[1] { match res.answers[1] {
DnsRecord::A { ref domain, .. } => { DnsRecord::A { ref domain, .. } => {
assert_eq!("cdn.facebook.com", domain); assert_eq!("cdn.facebook.com", domain);
} }
_ => panic!(), _ => panic!()
} }
}; };
// A successful resolve, that also resolves a CNAME through recursive lookup // A successful resolve, that also resolves a CNAME through recursive lookup
{ {
let res = execute_query( let res = execute_query(Arc::clone(&context), &build_query("www.microsoft.com", QueryType::CNAME));
Arc::clone(&context),
&build_query("www.microsoft.com", QueryType::CNAME),
);
assert_eq!(2, res.answers.len()); assert_eq!(2, res.answers.len());
match res.answers[0] { match res.answers[0] {
DnsRecord::CNAME { ref domain, .. } => { DnsRecord::CNAME { ref domain, .. } => {
assert_eq!("www.microsoft.com", domain); assert_eq!("www.microsoft.com", domain);
} }
_ => panic!(), _ => panic!()
} }
match res.answers[1] { match res.answers[1] {
DnsRecord::A { ref domain, .. } => { DnsRecord::A { ref domain, .. } => {
assert_eq!("cdn.microsoft.com", domain); assert_eq!("cdn.microsoft.com", domain);
} }
_ => panic!(), _ => panic!()
} }
}; };
@ -534,7 +514,7 @@ mod tests {
Some(mut ctx) => { Some(mut ctx) => {
ctx.allow_recursive = false; ctx.allow_recursive = false;
} }
None => panic!(), None => panic!()
} }
// This should generate an error code, since recursive resolves are // This should generate an error code, since recursive resolves are
@ -555,19 +535,14 @@ mod tests {
// Now construct a context where the dns client will return a failure // Now construct a context where the dns client will return a failure
let mut context2 = create_test_context(Box::new(|_, _, _, _| { let mut context2 = create_test_context(Box::new(|_, _, _, _| {
Err(crate::dns::client::ClientError::Io(std::io::Error::new( Err(crate::dns::client::ClientError::Io(std::io::Error::new(std::io::ErrorKind::NotFound, "Fail")))
std::io::ErrorKind::NotFound,
"Fail",
)))
})); }));
match Arc::get_mut(&mut context2) { match Arc::get_mut(&mut context2) {
Some(mut ctx) => { Some(mut ctx) => {
ctx.resolve_strategy = ResolveStrategy::Forward { ctx.resolve_strategy = ResolveStrategy::Forward { upstreams: vec![String::from("127.0.0.1:53")] };
upstreams: vec![String::from("127.0.0.1:53")]
};
} }
None => panic!(), None => panic!()
} }
// We expect this to set the server failure rescode // We expect this to set the server failure rescode

@ -1,13 +1,14 @@
use std::sync::{Arc, Mutex};
use std::env; use std::env;
use std::sync::{Arc, Mutex};
use crate::{Context, Settings};
use crate::blockchain::filter::BlockchainFilter;
use crate::dns::server::{DnsServer, DnsUdpServer, DnsTcpServer};
use crate::dns::context::{ServerContext, ResolveStrategy};
#[allow(unused_imports)] #[allow(unused_imports)]
use log::{debug, error, info, LevelFilter, trace, warn}; use log::{debug, error, info, trace, warn, LevelFilter};
use crate::blockchain::filter::BlockchainFilter;
use crate::dns::context::{ResolveStrategy, ServerContext};
use crate::dns::hosts::HostsFilter; use crate::dns::hosts::HostsFilter;
use crate::dns::server::{DnsServer, DnsTcpServer, DnsUdpServer};
use crate::{Context, Settings};
/// Starts UDP and TCP DNS-servers /// Starts UDP and TCP DNS-servers
pub fn start_dns_server(context: &Arc<Mutex<Context>>, settings: &Settings) { pub fn start_dns_server(context: &Arc<Mutex<Context>>, settings: &Settings) {
@ -34,8 +35,8 @@ fn create_server_context(context: Arc<Mutex<Context>>, settings: &Settings) -> A
server_context.allow_recursive = true; server_context.allow_recursive = true;
server_context.dns_listen = settings.dns.listen.clone(); server_context.dns_listen = settings.dns.listen.clone();
server_context.resolve_strategy = match settings.dns.forwarders.is_empty() { server_context.resolve_strategy = match settings.dns.forwarders.is_empty() {
true => { ResolveStrategy::Recursive } true => ResolveStrategy::Recursive,
false => { ResolveStrategy::Forward { upstreams: settings.dns.forwarders.clone() } } false => ResolveStrategy::Forward { upstreams: settings.dns.forwarders.clone() }
}; };
// Add host filters // Add host filters
for host in &settings.dns.hosts { for host in &settings.dns.hosts {

@ -1,34 +1,33 @@
extern crate rand;
extern crate ed25519_dalek; extern crate ed25519_dalek;
extern crate rand;
extern crate serde; extern crate serde;
extern crate serde_json; extern crate serde_json;
use std::thread; use std::cell::RefCell;
use std::fs;
use std::fs::File; use std::fs::File;
use std::io::Write; use std::io::Write;
use std::path::Path; use std::path::Path;
use std::sync::{Arc, atomic, Mutex};
use std::sync::atomic::{AtomicBool, AtomicUsize}; use std::sync::atomic::{AtomicBool, AtomicUsize};
use std::sync::{atomic, Arc, Mutex};
use std::time::Instant;
use std::{fs, thread};
use serde::{Deserialize, Serialize}; use blakeout::Blakeout;
use ed25519_dalek::Keypair; use ed25519_dalek::Keypair;
#[allow(unused_imports)] #[allow(unused_imports)]
use log::{debug, error, info, trace, warn}; use log::{debug, error, info, trace, warn};
use rand_old::{CryptoRng, RngCore};
use serde::{Deserialize, Serialize};
use self::ed25519_dalek::ed25519::signature::Signature;
use self::ed25519_dalek::{PublicKey, SecretKey, Signer, Verifier};
use crate::blockchain::hash_utils::*; use crate::blockchain::hash_utils::*;
use crate::{Context, setup_miner_thread, to_hex, from_hex};
use crate::event::Event;
use crate::commons::KEYSTORE_DIFFICULTY;
use crate::eventbus::{register, post};
use crate::bytes::Bytes; use crate::bytes::Bytes;
use crate::commons::KEYSTORE_DIFFICULTY;
use crate::crypto::CryptoBox; use crate::crypto::CryptoBox;
use blakeout::Blakeout; use crate::event::Event;
use std::time::Instant; use crate::eventbus::{post, register};
use std::cell::RefCell; use crate::{from_hex, setup_miner_thread, to_hex, Context};
use self::ed25519_dalek::{Signer, PublicKey, Verifier, SecretKey};
use self::ed25519_dalek::ed25519::signature::Signature;
use rand_old::{CryptoRng, RngCore};
#[derive(Debug)] #[derive(Debug)]
pub struct Keystore { pub struct Keystore {
@ -149,8 +148,8 @@ impl Keystore {
let key = PublicKey::from_bytes(public_key).expect("Wrong public key!"); let key = PublicKey::from_bytes(public_key).expect("Wrong public key!");
let signature = Signature::from_bytes(signature).unwrap(); let signature = Signature::from_bytes(signature).unwrap();
match key.verify(message, &signature) { match key.verify(message, &signature) {
Ok(_) => { true } Ok(_) => true,
Err(_) => { false } Err(_) => false
} }
} }
@ -161,7 +160,7 @@ impl Keystore {
pub fn decrypt(&self, message: &[u8]) -> Bytes { pub fn decrypt(&self, message: &[u8]) -> Bytes {
match self.crypto_box.reveal(message) { match self.crypto_box.reveal(message) {
Ok(decrypted) => { Bytes::from_bytes(&decrypted) } Ok(decrypted) => Bytes::from_bytes(&decrypted),
Err(_) => { Err(_) => {
warn!("Decryption failed"); warn!("Decryption failed");
Bytes::default() Bytes::default()

@ -12,15 +12,14 @@ pub use crate::p2p::Network;
pub use crate::settings::Settings; pub use crate::settings::Settings;
pub mod blockchain; pub mod blockchain;
pub mod bytes;
pub mod commons; pub mod commons;
pub mod keystore;
pub mod miner;
pub mod context; pub mod context;
pub mod event; pub mod crypto;
pub mod p2p;
pub mod dns; pub mod dns;
pub mod dns_utils; pub mod dns_utils;
pub mod event;
pub mod keystore;
pub mod miner;
pub mod p2p;
pub mod settings; pub mod settings;
pub mod bytes;
pub mod crypto;

@ -3,28 +3,30 @@
// See https://msdn.microsoft.com/en-us/library/4cc7ya5b.aspx for more details. // See https://msdn.microsoft.com/en-us/library/4cc7ya5b.aspx for more details.
#![windows_subsystem = "windows"] #![windows_subsystem = "windows"]
use std::env;
use std::path::Path; use std::path::Path;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration; use std::time::Duration;
use std::{env, thread};
use getopts::{Options, Matches}; use getopts::{Matches, Options};
#[allow(unused_imports)] #[allow(unused_imports)]
use log::{debug, error, info, trace, warn, LevelFilter}; use log::{debug, error, info, trace, warn, LevelFilter};
use simplelog::*; use simplelog::*;
#[cfg(windows)] #[cfg(windows)]
use winapi::um::wincon::{ATTACH_PARENT_PROCESS, AttachConsole, FreeConsole}; use winapi::um::wincon::{AttachConsole, FreeConsole, ATTACH_PARENT_PROCESS};
extern crate lazy_static; extern crate lazy_static;
use alfis::{Block, Bytes, Chain, Miner, Context, Network, Settings, dns_utils, Keystore, ORIGIN_DIFFICULTY, ALFIS_DEBUG, DB_NAME, Transaction};
use alfis::event::Event;
use std::fs::OpenOptions; use std::fs::OpenOptions;
use std::process::exit;
use std::io::{Seek, SeekFrom}; use std::io::{Seek, SeekFrom};
use std::process::exit;
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::atomic::{AtomicBool, Ordering};
use alfis::keystore::create_key;
use alfis::event::Event;
use alfis::eventbus::register; use alfis::eventbus::register;
use alfis::keystore::create_key;
use alfis::{
dns_utils, Block, Bytes, Chain, Context, Keystore, Miner, Network, Settings, Transaction, ALFIS_DEBUG, DB_NAME, ORIGIN_DIFFICULTY
};
#[cfg(feature = "webgui")] #[cfg(feature = "webgui")]
mod web_ui; mod web_ui;
@ -60,7 +62,7 @@ fn main() {
let opt_matches = match opts.parse(&args[1..]) { let opt_matches = match opts.parse(&args[1..]) {
Ok(m) => m, Ok(m) => m,
Err(f) => panic!("{}", f.to_string()), Err(f) => panic!("{}", f.to_string())
}; };
if opt_matches.opt_present("h") { if opt_matches.opt_present("h") {
@ -101,8 +103,8 @@ fn main() {
env::set_current_dir(Path::new(&path)).expect(&format!("Unable to change working directory to '{}'", &path)); env::set_current_dir(Path::new(&path)).expect(&format!("Unable to change working directory to '{}'", &path));
} }
let config_name = match opt_matches.opt_str("c") { let config_name = match opt_matches.opt_str("c") {
None => { SETTINGS_FILENAME.to_owned() } None => SETTINGS_FILENAME.to_owned(),
Some(path) => { path } Some(path) => path
}; };
setup_logger(&opt_matches); setup_logger(&opt_matches);
@ -125,7 +127,9 @@ fn main() {
if settings.key_files.len() > 0 { if settings.key_files.len() > 0 {
for name in &settings.key_files { for name in &settings.key_files {
match Keystore::from_file(name, "") { match Keystore::from_file(name, "") {
None => { warn!("Error loading keyfile from {}", name); } None => {
warn!("Error loading keyfile from {}", name);
}
Some(keystore) => { Some(keystore) => {
info!("Successfully loaded keyfile {}", name); info!("Successfully loaded keyfile {}", name);
keys.push(keystore); keys.push(keystore);
@ -144,7 +148,7 @@ fn main() {
let context_copy = Arc::clone(&context); let context_copy = Arc::clone(&context);
// Register key-mined event listener // Register key-mined event listener
register(move |_uuid, e| { register(move |_uuid, e| {
if matches!(e, Event::KeyCreated {..}) { if matches!(e, Event::KeyCreated { .. }) {
let context_copy = Arc::clone(&context_copy); let context_copy = Arc::clone(&context_copy);
let mining_copy = Arc::clone(&mining_copy); let mining_copy = Arc::clone(&mining_copy);
let filename = filename.clone(); let filename = filename.clone();
@ -172,8 +176,12 @@ fn main() {
if let Ok(mut context) = context.lock() { if let Ok(mut context) = context.lock() {
context.chain.check_chain(settings_copy.check_blocks); context.chain.check_chain(settings_copy.check_blocks);
match context.chain.get_block(1) { match context.chain.get_block(1) {
None => { info!(target: LOG_TARGET_MAIN, "No blocks found in DB"); } None => {
Some(block) => { trace!(target: LOG_TARGET_MAIN, "Loaded DB with origin {:?}", &block.hash); } info!(target: LOG_TARGET_MAIN, "No blocks found in DB");
}
Some(block) => {
trace!(target: LOG_TARGET_MAIN, "Loaded DB with origin {:?}", &block.hash);
}
} }
} }
@ -240,12 +248,11 @@ fn setup_logger(opt_matches: &Matches) {
exit(1); exit(1);
} }
}; };
CombinedLogger::init( CombinedLogger::init(vec![
vec![
TermLogger::new(level, config.clone(), TerminalMode::Stdout, ColorChoice::Auto), TermLogger::new(level, config.clone(), TerminalMode::Stdout, ColorChoice::Auto),
WriteLogger::new(level, config, file), WriteLogger::new(level, config, file),
] ])
).unwrap(); .unwrap();
} }
} }
} }

@ -1,22 +1,22 @@
use std::sync::{Arc, Condvar, Mutex};
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use std::sync::{Arc, Condvar, Mutex};
use std::thread; use std::thread;
use std::thread::sleep;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
use blakeout::Blakeout;
use chrono::Utc; use chrono::Utc;
#[allow(unused_imports)] #[allow(unused_imports)]
use log::{debug, error, info, trace, warn}; use log::{debug, error, info, trace, warn};
use num_cpus; use num_cpus;
use crate::{Block, Bytes, Context, Keystore, setup_miner_thread};
use crate::commons::*;
use crate::blockchain::types::BlockQuality;
use crate::blockchain::hash_utils::*; use crate::blockchain::hash_utils::*;
use crate::keystore::check_public_key_strength; use crate::blockchain::types::BlockQuality;
use crate::commons::*;
use crate::event::Event; use crate::event::Event;
use blakeout::Blakeout; use crate::eventbus::{post, register};
use std::thread::sleep; use crate::keystore::check_public_key_strength;
use crate::eventbus::{register, post}; use crate::{setup_miner_thread, Block, Bytes, Context, Keystore};
#[derive(Clone)] #[derive(Clone)]
pub struct MineJob { pub struct MineJob {
@ -98,7 +98,7 @@ impl Miner {
match e { match e {
Event::ActionQuit => { running.store(false, Ordering::Relaxed); } Event::ActionQuit => { running.store(false, Ordering::Relaxed); }
Event::NewBlockReceived => {} Event::NewBlockReceived => {}
Event::BlockchainChanged {..} => {} Event::BlockchainChanged { .. } => {}
Event::ActionStopMining => { Event::ActionStopMining => {
mining.store(false, Ordering::SeqCst); mining.store(false, Ordering::SeqCst);
} }
@ -231,8 +231,8 @@ impl Miner {
} else { } else {
job.block.index = context.lock().unwrap().chain.get_height() + 1; job.block.index = context.lock().unwrap().chain.get_height() + 1;
job.block.prev_block_hash = match context.lock().unwrap().chain.last_block() { job.block.prev_block_hash = match context.lock().unwrap().chain.last_block() {
None => { Bytes::default() } None => Bytes::default(),
Some(block) => { block.hash } Some(block) => block.hash
}; };
} }
@ -276,7 +276,7 @@ impl Miner {
} }
post(Event::MinerStopped { success: false, full }); post(Event::MinerStopped { success: false, full });
} }
}, }
Some(mut block) => { Some(mut block) => {
let index = block.index; let index = block.index;
let mut context = context.lock().unwrap(); let mut context = context.lock().unwrap();
@ -298,7 +298,7 @@ impl Miner {
context.miner_state.mining = false; context.miner_state.mining = false;
post(Event::MinerStopped { success, full }); post(Event::MinerStopped { success, full });
mining.store(false, Ordering::SeqCst); mining.store(false, Ordering::SeqCst);
}, }
} }
}); });
thread::sleep(thread_spawn_interval); thread::sleep(thread_spawn_interval);

@ -2,12 +2,13 @@ extern crate serde;
extern crate serde_json; extern crate serde_json;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::Bytes; use crate::Bytes;
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
pub enum Message { pub enum Message {
Error, Error,
Hand { app_version: String, origin: String, version: u32, public: bool, rand_id: String, }, Hand { app_version: String, origin: String, version: u32, public: bool, rand_id: String },
Shake { app_version: String, origin: String, version: u32, public: bool, rand_id: String, height: u64 }, Shake { app_version: String, origin: String, version: u32, public: bool, rand_id: String, height: u64 },
Ping { height: u64, hash: Bytes }, Ping { height: u64, hash: Bytes },
Pong { height: u64, hash: Bytes }, Pong { height: u64, hash: Bytes },
@ -16,7 +17,7 @@ pub enum Message {
GetPeers, GetPeers,
Peers { peers: Vec<String> }, Peers { peers: Vec<String> },
GetBlock { index: u64 }, GetBlock { index: u64 },
Block { index: u64, block: Vec<u8> }, Block { index: u64, block: Vec<u8> }
} }
impl Message { impl Message {

@ -1,12 +1,11 @@
pub mod network;
pub mod message; pub mod message;
pub mod state; pub mod network;
pub mod peer; pub mod peer;
pub mod peers; pub mod peers;
pub mod state;
pub use network::Network;
pub use message::Message; pub use message::Message;
pub use state::State; pub use network::Network;
pub use peer::Peer; pub use peer::Peer;
pub use peers::Peers; pub use peers::Peers;
pub use state::State;

@ -1,30 +1,31 @@
extern crate serde; extern crate serde;
extern crate serde_json; extern crate serde_json;
use std::{io, thread};
use std::cmp::max; use std::cmp::max;
use std::io::{Read, Write, Error, ErrorKind}; use std::collections::{HashMap, HashSet};
use std::io::{Error, ErrorKind, Read, Write};
use std::net::{IpAddr, Shutdown, SocketAddr, SocketAddrV4}; use std::net::{IpAddr, Shutdown, SocketAddr, SocketAddrV4};
use std::sync::{Arc, Mutex};
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Instant; use std::time::Instant;
use std::{io, thread};
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
#[allow(unused_imports)] #[allow(unused_imports)]
use log::{debug, error, info, trace, warn}; use log::{debug, error, info, trace, warn};
use mio::{Events, Interest, Poll, Registry, Token};
use mio::event::Event; use mio::event::Event;
use mio::net::{TcpListener, TcpStream}; use mio::net::{TcpListener, TcpStream};
use rand::{random, RngCore, Rng}; use mio::{Events, Interest, Poll, Registry, Token};
use rand::{random, Rng, RngCore};
use rand_old::prelude::thread_rng; use rand_old::prelude::thread_rng;
use x25519_dalek::{StaticSecret, PublicKey}; use x25519_dalek::{PublicKey, StaticSecret};
use crate::{Block, Context, p2p::Message, p2p::Peer, p2p::Peers, p2p::State};
use crate::blockchain::types::BlockQuality; use crate::blockchain::types::BlockQuality;
use crate::commons::*; use crate::commons::*;
use crate::eventbus::{register, post};
use crate::crypto::Chacha; use crate::crypto::Chacha;
use std::collections::{HashMap, HashSet}; use crate::eventbus::{post, register};
use crate::p2p::{Message, Peer, Peers, State};
use crate::{Block, Context};
const SERVER: Token = Token(0); const SERVER: Token = Token(0);
@ -36,7 +37,7 @@ pub struct Network {
// States of peer connections, and some data to send when sockets become writable // States of peer connections, and some data to send when sockets become writable
peers: Peers, peers: Peers,
// Orphan blocks from future // Orphan blocks from future
future_blocks: HashMap<u64, Block>, future_blocks: HashMap<u64, Block>
} }
impl Network { impl Network {
@ -116,7 +117,9 @@ impl Network {
if yggdrasil_only && !is_yggdrasil(&address.ip()) { if yggdrasil_only && !is_yggdrasil(&address.ip()) {
debug!("Dropping connection from Internet"); debug!("Dropping connection from Internet");
stream.shutdown(Shutdown::Both).unwrap_or_else(|e|{ warn!("Error in shutdown, {}", e); }); stream.shutdown(Shutdown::Both).unwrap_or_else(|e| {
warn!("Error in shutdown, {}", e);
});
let _ = poll.registry().reregister(&mut server, SERVER, Interest::READABLE); let _ = poll.registry().reregister(&mut server, SERVER, Interest::READABLE);
continue; continue;
} }
@ -237,7 +240,7 @@ impl Network {
debug!("Error reading client handshake from {}.", peer.get_addr()); debug!("Error reading client handshake from {}.", peer.get_addr());
false false
} }
} };
} }
State::ServerHandshake => { State::ServerHandshake => {
let mut stream = peer.get_stream(); let mut stream = peer.get_stream();
@ -264,7 +267,7 @@ impl Network {
debug!("Error reading client handshake from {}", peer.get_addr()); debug!("Error reading client handshake from {}", peer.get_addr());
false false
} }
} };
} }
_ => { _ => {
let mut stream = peer.get_stream(); let mut stream = peer.get_stream();
@ -281,9 +284,7 @@ impl Network {
Some(peer) => { Some(peer) => {
let data = data.unwrap(); let data = data.unwrap();
match decode_message(&data, peer.get_cipher()) { match decode_message(&data, peer.get_cipher()) {
Ok(data) => { Ok(data) => data,
data
}
Err(_) => { Err(_) => {
vec![] vec![]
} }
@ -344,8 +345,8 @@ impl Network {
} else { } else {
let error = data.err().unwrap(); let error = data.err().unwrap();
let addr = match self.peers.get_peer(&event.token()) { let addr = match self.peers.get_peer(&event.token()) {
None => { String::from("unknown") } None => String::from("unknown"),
Some(peer) => { peer.get_addr().to_string() } Some(peer) => peer.get_addr().to_string()
}; };
debug!("Error reading message from {}, error = {}", addr, error); debug!("Error reading message from {}, error = {}", addr, error);
return false; return false;
@ -475,7 +476,7 @@ impl Network {
State::idle() State::idle()
} }
} }
Message::Error => { State::Error } Message::Error => State::Error,
Message::Ping { height, hash } => { Message::Ping { height, hash } => {
let peer = self.peers.get_mut_peer(token).unwrap(); let peer = self.peers.get_mut_peer(token).unwrap();
peer.set_height(height); peer.set_height(height);
@ -546,7 +547,7 @@ impl Network {
Ok(block) => block, Ok(block) => block,
Err(e) => { Err(e) => {
warn!("Error deserializing block! {}", e); warn!("Error deserializing block! {}", e);
return State::Banned return State::Banned;
} }
}; };
if index != block.index { if index != block.index {
@ -555,8 +556,8 @@ impl Network {
info!("Received block {} with hash {:?}", block.index, &block.hash); info!("Received block {} with hash {:?}", block.index, &block.hash);
self.handle_block(token, block) self.handle_block(token, block)
} }
Message::Twin => { State::Twin } Message::Twin => State::Twin,
Message::Loop => { State::Loop } Message::Loop => State::Loop
}; };
answer answer
} }
@ -658,13 +659,10 @@ fn subscribe_to_bus(running: Arc<AtomicBool>) {
}); });
} }
fn encode_bytes(data: &Vec<u8>, cipher: &Option<Chacha>) -> Result<Vec<u8>, chacha20poly1305::aead::Error> { fn encode_bytes(data: &Vec<u8>, cipher: &Option<Chacha>) -> Result<Vec<u8>, chacha20poly1305::aead::Error> {
match cipher { match cipher {
None => { Ok(data.clone()) } None => Ok(data.clone()),
Some(chacha) => { Some(chacha) => chacha.encrypt(data.as_slice())
chacha.encrypt(data.as_slice())
}
} }
} }
@ -691,10 +689,8 @@ fn encode_message(message: &Message, cipher: &Option<Chacha>) -> Result<Vec<u8>,
fn decode_message(data: &Vec<u8>, cipher: &Option<Chacha>) -> Result<Vec<u8>, chacha20poly1305::aead::Error> { fn decode_message(data: &Vec<u8>, cipher: &Option<Chacha>) -> Result<Vec<u8>, chacha20poly1305::aead::Error> {
match cipher { match cipher {
None => { Ok(data.clone()) } None => Ok(data.clone()),
Some(chacha) => { Some(chacha) => chacha.decrypt(data.as_slice())
chacha.decrypt(data.as_slice())
}
} }
} }
@ -727,22 +723,24 @@ fn send_client_handshake(stream: &mut TcpStream, public_key: &[u8]) -> io::Resul
fn read_client_handshake(stream: &mut TcpStream) -> Result<Vec<u8>, Error> { fn read_client_handshake(stream: &mut TcpStream) -> Result<Vec<u8>, Error> {
// First, we read garbage size // First, we read garbage size
let data_size = match stream.read_u8() { let data_size = match stream.read_u8() {
Ok(size) => { (size ^ 0xA) as usize } Ok(size) => (size ^ 0xA) as usize,
Err(e) => { Err(e) => {
error!("Error reading from socket! {}", e); error!("Error reading from socket! {}", e);
return Err(e) return Err(e);
} }
}; };
// Read the garbage // Read the garbage
let mut buf = vec![0u8; data_size]; let mut buf = vec![0u8; data_size];
match stream.read_exact(&mut buf) { match stream.read_exact(&mut buf) {
Ok(_) => {} Ok(_) => {}
Err(e) => { return Err(e); } Err(e) => {
return Err(e);
}
} }
// Then we have public key for ECDH // Then we have public key for ECDH
let mut buf = vec![0u8; 32]; let mut buf = vec![0u8; 32];
match stream.read_exact(&mut buf) { match stream.read_exact(&mut buf) {
Ok(_) => { Ok(buf) } Ok(_) => Ok(buf),
Err(e) => { Err(e) => {
warn!("Error reading handshake!"); warn!("Error reading handshake!");
Err(e) Err(e)
@ -773,22 +771,24 @@ fn send_server_handshake(peer: &mut Peer, public_key: &[u8]) -> io::Result<()> {
fn read_server_handshake(stream: &mut TcpStream) -> Result<Vec<u8>, Error> { fn read_server_handshake(stream: &mut TcpStream) -> Result<Vec<u8>, Error> {
// First, we read garbage size // First, we read garbage size
let data_size = match stream.read_u8() { let data_size = match stream.read_u8() {
Ok(size) => { (size ^ 0xA) as usize } Ok(size) => (size ^ 0xA) as usize,
Err(e) => { Err(e) => {
error!("Error reading from socket! {}", e); error!("Error reading from socket! {}", e);
return Err(e) return Err(e);
} }
}; };
// Read the garbage // Read the garbage
let mut buf = vec![0u8; data_size]; let mut buf = vec![0u8; data_size];
match stream.read_exact(&mut buf) { match stream.read_exact(&mut buf) {
Ok(_) => {} Ok(_) => {}
Err(e) => { return Err(e); } Err(e) => {
return Err(e);
}
} }
// Then we have public key for ECDH, plus nonce 12 bytes // Then we have public key for ECDH, plus nonce 12 bytes
let mut buf = vec![0u8; 32 + 12]; let mut buf = vec![0u8; 32 + 12];
match stream.read_exact(&mut buf) { match stream.read_exact(&mut buf) {
Ok(_) => { Ok(buf) } Ok(_) => Ok(buf),
Err(e) => { Err(e) => {
warn!("Error reading handshake!"); warn!("Error reading handshake!");
Err(e) Err(e)

@ -1,9 +1,11 @@
use std::net::SocketAddr;
use std::collections::HashMap; use std::collections::HashMap;
use std::net::SocketAddr;
use mio::net::TcpStream; use mio::net::TcpStream;
use crate::crypto::Chacha;
use crate::p2p::State; use crate::p2p::State;
use crate::Block; use crate::Block;
use crate::crypto::Chacha;
#[derive(Debug)] #[derive(Debug)]
pub struct Peer { pub struct Peer {
@ -49,8 +51,8 @@ impl Peer {
pub fn get_nonce(&self) -> &[u8; 12] { pub fn get_nonce(&self) -> &[u8; 12] {
match &self.cipher { match &self.cipher {
None => { &crate::crypto::ZERO_NONCE } None => &crate::crypto::ZERO_NONCE,
Some(chacha) => { chacha.get_nonce() } Some(chacha) => chacha.get_nonce()
} }
} }

@ -1,19 +1,19 @@
use std::cmp::min;
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
use std::io;
use std::net::{IpAddr, Shutdown, SocketAddr, ToSocketAddrs}; use std::net::{IpAddr, Shutdown, SocketAddr, ToSocketAddrs};
use chrono::Utc; use chrono::Utc;
#[allow(unused_imports)] #[allow(unused_imports)]
use log::{debug, error, info, trace, warn}; use log::{debug, error, info, trace, warn};
use mio::{Interest, Registry, Token};
use mio::net::TcpStream; use mio::net::TcpStream;
use mio::{Interest, Registry, Token};
use rand::random; use rand::random;
use rand::seq::IteratorRandom; use rand::seq::IteratorRandom;
use crate::{Bytes, commons};
use crate::commons::*; use crate::commons::*;
use crate::p2p::{Message, Peer, State}; use crate::p2p::{Message, Peer, State};
use std::io; use crate::{commons, Bytes};
use std::cmp::min;
const PING_PERIOD: u64 = 30; const PING_PERIOD: u64 = 30;
@ -22,7 +22,7 @@ pub struct Peers {
new_peers: Vec<SocketAddr>, new_peers: Vec<SocketAddr>,
ignored: HashSet<IpAddr>, ignored: HashSet<IpAddr>,
my_id: String, my_id: String,
behind_ping_sent_time: i64, behind_ping_sent_time: i64
} }
impl Peers { impl Peers {
@ -383,7 +383,7 @@ impl Peers {
for peer in peers_addrs.iter() { for peer in peers_addrs.iter() {
info!("Resolving address {}", peer); info!("Resolving address {}", peer);
let mut addresses: Vec<SocketAddr> = match peer.to_socket_addrs() { let mut addresses: Vec<SocketAddr> = match peer.to_socket_addrs() {
Ok(peers) => { peers.collect() } Ok(peers) => peers.collect(),
Err(_) => { error!("Can't resolve address {}", &peer); continue; } Err(_) => { error!("Can't resolve address {}", &peer); continue; }
}; };
info!("Got addresses: {:?}", &addresses); info!("Got addresses: {:?}", &addresses);
@ -424,7 +424,7 @@ impl Peers {
} }
trace!("Connecting to peer {}", &addr); trace!("Connecting to peer {}", &addr);
match TcpStream::connect(addr.clone()) { match TcpStream::connect(addr.clone()) {
Ok(mut stream ) => { Ok(mut stream) => {
//stream.set_nodelay(true)?; //stream.set_nodelay(true)?;
let token = next(unique_token); let token = next(unique_token);
trace!("Created connection {}, to peer {}", &token.0, &addr); trace!("Created connection {}, to peer {}", &token.0, &addr);
@ -434,7 +434,7 @@ impl Peers {
self.peers.insert(token, peer); self.peers.insert(token, peer);
Ok(()) Ok(())
} }
Err(e) => { Err(e) } Err(e) => Err(e)
} }
} }

@ -1,4 +1,5 @@
use std::time::Instant; use std::time::Instant;
use crate::p2p::Message; use crate::p2p::Message;
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
@ -14,7 +15,7 @@ pub enum State {
SendLoop, SendLoop,
Loop, Loop,
Twin, Twin,
Offline { from: Instant }, Offline { from: Instant }
} }
impl State { impl State {
@ -33,34 +34,34 @@ impl State {
pub fn is_idle(&self) -> bool { pub fn is_idle(&self) -> bool {
match self { match self {
State::Idle { .. } => { true } State::Idle { .. } => true,
_ => { false } _ => false
} }
} }
pub fn is_loop(&self) -> bool { pub fn is_loop(&self) -> bool {
match self { match self {
State::Loop { .. } => { true } State::Loop { .. } => true,
State::SendLoop { .. } => { true } State::SendLoop { .. } => true,
_ => { false } _ => false
} }
} }
pub fn disabled(&self) -> bool { pub fn disabled(&self) -> bool {
match self { match self {
State::Error => { true } State::Error => true,
State::Banned => { true } State::Banned => true,
State::Offline { from} => { State::Offline { from } => {
from.elapsed().as_secs() < 60 // We check offline peers to become online every 5 minutes from.elapsed().as_secs() < 60 // We check offline peers to become online every 5 minutes
} }
_ => { false } _ => false
} }
} }
pub fn need_reconnect(&self) -> bool { pub fn need_reconnect(&self) -> bool {
match self { match self {
State::Offline { from } => { from.elapsed().as_secs() > 60 } State::Offline { from } => from.elapsed().as_secs() > 60,
_ => { false } _ => false
} }
} }
} }

@ -1,9 +1,9 @@
use std::fs::File; use std::fs::File;
use std::io::Read; use std::io::Read;
use serde::{Deserialize, Serialize};
#[allow(unused_imports)] #[allow(unused_imports)]
use log::{debug, error, info, LevelFilter, trace, warn}; use log::{debug, error, info, trace, warn, LevelFilter};
use serde::{Deserialize, Serialize};
use crate::Bytes; use crate::Bytes;
@ -20,7 +20,7 @@ pub struct Settings {
#[serde(default)] #[serde(default)]
pub dns: Dns, pub dns: Dns,
#[serde(default)] #[serde(default)]
pub mining: Mining, pub mining: Mining
} }
impl Settings { impl Settings {
@ -34,9 +34,7 @@ impl Settings {
} }
None None
} }
Err(..) => { Err(..) => None
None
}
} }
} }
@ -70,7 +68,7 @@ pub struct Dns {
pub threads: usize, pub threads: usize,
pub forwarders: Vec<String>, pub forwarders: Vec<String>,
#[serde(default)] #[serde(default)]
pub hosts: Vec<String>, pub hosts: Vec<String>
} }
impl Default for Dns { impl Default for Dns {
@ -101,7 +99,7 @@ pub struct Net {
#[serde(default)] #[serde(default)]
pub public: bool, pub public: bool,
#[serde(default)] #[serde(default)]
pub yggdrasil_only: bool, pub yggdrasil_only: bool
} }
impl Default for Net { impl Default for Net {

@ -8,25 +8,23 @@ use std::sync::{Arc, Mutex, MutexGuard};
use std::thread; use std::thread;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
use chrono::{DateTime, Local};
#[allow(unused_imports)]
use log::{debug, error, info, LevelFilter, trace, warn};
use serde::{Serialize, Deserialize};
use web_view::Content;
use alfis::{Block, Bytes, Context, Keystore, Transaction};
use alfis::keystore;
use alfis::blockchain::transaction::DomainData; use alfis::blockchain::transaction::DomainData;
use alfis::blockchain::types::MineResult; use alfis::blockchain::types::MineResult;
use alfis::commons::*; use alfis::commons::*;
use alfis::crypto::CryptoBox;
use alfis::dns::protocol::DnsRecord; use alfis::dns::protocol::DnsRecord;
use alfis::event::Event; use alfis::event::Event;
use alfis::eventbus::{post, register};
use alfis::miner::Miner; use alfis::miner::Miner;
use alfis::{keystore, Block, Bytes, Context, Keystore, Transaction};
use chrono::{DateTime, Local};
#[allow(unused_imports)]
use log::{debug, error, info, trace, warn, LevelFilter};
use serde::{Deserialize, Serialize};
use web_view::Content;
use Cmd::*; use Cmd::*;
use self::web_view::{Handle, WebView}; use self::web_view::{Handle, WebView};
use alfis::crypto::CryptoBox;
use alfis::eventbus::{register, post};
pub fn run_interface(context: Arc<Mutex<Context>>, miner: Arc<Mutex<Miner>>) { pub fn run_interface(context: Arc<Mutex<Context>>, miner: Arc<Mutex<Miner>>) {
let file_content = include_str!("webview/index.html"); let file_content = include_str!("webview/index.html");
@ -117,7 +115,10 @@ fn action_check_record(web_view: &mut WebView<()>, data: String) {
} }
} }
} }
Err(e) => { web_view.eval("recordOkay(false)").expect("Error evaluating!"); dbg!(e); } Err(e) => {
web_view.eval("recordOkay(false)").expect("Error evaluating!");
dbg!(e);
}
} }
} }
@ -238,7 +239,7 @@ fn action_loaded(context: &Arc<Mutex<Context>>, web_view: &mut WebView<()>) {
event_handle_info(&handle, "Mining started"); event_handle_info(&handle, "Mining started");
String::from("setLeftStatusBarText('Mining...'); showMiningIndicator(true, false);") String::from("setLeftStatusBarText('Mining...'); showMiningIndicator(true, false);")
} }
Event::MinerStopped { success, full} => { Event::MinerStopped { success, full } => {
status.mining = false; status.mining = false;
status.max_diff = 0; status.max_diff = 0;
let mut s = if status.syncing { let mut s = if status.syncing {
@ -310,12 +311,12 @@ fn action_loaded(context: &Arc<Mutex<Context>>, web_view: &mut WebView<()>) {
format!("setLeftStatusBarText('Idle'); setStats({}, {}, {}, {});", blocks, domains, keys, nodes) format!("setLeftStatusBarText('Idle'); setStats({}, {}, {}, {});", blocks, domains, keys, nodes)
} }
} }
Event::BlockchainChanged {index} => { Event::BlockchainChanged { index } => {
debug!("Current blockchain height is {}", index); debug!("Current blockchain height is {}", index);
event_handle_info(&handle, &format!("Blockchain changed, current block count is {} now.", index)); event_handle_info(&handle, &format!("Blockchain changed, current block count is {} now.", index));
String::new() // Nothing String::new() // Nothing
} }
_ => { String::new() } _ => String::new()
}; };
if !eval.is_empty() { if !eval.is_empty() {
@ -343,7 +344,8 @@ fn action_loaded(context: &Arc<Mutex<Context>>, web_view: &mut WebView<()>) {
let _ = web_view.eval(&format!("zonesChanged('{}');", &zones)); let _ = web_view.eval(&format!("zonesChanged('{}');", &zones));
} }
send_keys_to_ui(&c, &web_view.handle()); send_keys_to_ui(&c, &web_view.handle());
if let Err(e) = web_view.eval(&format!("setStats({}, {}, {}, {});", c.chain.get_height(), c.chain.get_domains_count(), c.chain.get_users_count(), 0)) { let command = format!("setStats({}, {}, {}, {});", c.chain.get_height(), c.chain.get_domains_count(), c.chain.get_users_count(), 0);
if let Err(e) = web_view.eval(&command) {
error!("Error evaluating stats: {}", e); error!("Error evaluating stats: {}", e);
} }
event_info(web_view, "Application loaded"); event_info(web_view, "Application loaded");
@ -404,7 +406,7 @@ fn action_create_domain(context: Arc<Mutex<Context>>, miner: Arc<Mutex<Miner>>,
let keystore = context.get_keystore().unwrap().clone(); let keystore = context.get_keystore().unwrap().clone();
let pub_key = keystore.get_public(); let pub_key = keystore.get_public();
let data = match serde_json::from_str::<DomainData>(&data) { let data = match serde_json::from_str::<DomainData>(&data) {
Ok(data) => { data } Ok(data) => data,
Err(e) => { Err(e) => {
show_warning(web_view, "Something wrong with domain data. I cannot mine it."); show_warning(web_view, "Something wrong with domain data. I cannot mine it.");
let _ = web_view.eval("domainMiningUnavailable();"); let _ = web_view.eval("domainMiningUnavailable();");
@ -587,7 +589,7 @@ pub enum Cmd {
MineDomain { name: String, data: String, signing: String, encryption: String }, MineDomain { name: String, data: String, signing: String, encryption: String },
TransferDomain { name: String, owner: String }, TransferDomain { name: String, owner: String },
StopMining, StopMining,
Open { link: String }, Open { link: String }
} }
struct Status { struct Status {

Loading…
Cancel
Save