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

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

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

@ -1,8 +1,9 @@
use std::convert::TryInto;
use blakeout::Blakeout;
use sha2::{Digest, Sha256};
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
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 identity = hash_sha256(&base);
match key {
None => { Bytes::from_bytes(&identity) }
None => Bytes::from_bytes(&identity),
Some(key) => {
let mut buf = Vec::new();
buf.append(&mut base.clone());
@ -85,9 +86,10 @@ pub fn hash_sha256(data: &[u8]) -> Vec<u8> {
#[cfg(test)]
mod tests {
use crate::blockchain::hash_utils::hash_sha256;
use std::convert::TryInto;
use crate::blockchain::hash_utils::hash_sha256;
#[test]
#[ignore]
pub fn test_hash() {
@ -111,9 +113,9 @@ mod tests {
#[test]
#[ignore]
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 int = u64::from_be_bytes(bytes);
println!("int = {}", int);
}
}
}

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

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

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

@ -4,15 +4,14 @@ extern crate serde_json;
use std::cmp::Ordering;
use std::convert::TryInto;
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 serde::{Deserialize, Deserializer, Serialize, Serializer};
// For deserialization
use serde::de::{Error as DeError, Visitor};
use std::ops::Deref;
use std::hash::{Hash, Hasher};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
#[derive(Clone)]
pub struct Bytes {
@ -132,8 +131,7 @@ impl fmt::Debug for Bytes {
}
impl Serialize for Bytes {
fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> where
S: Serializer {
fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> where S: Serializer {
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")
}
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 {
Ok(Bytes::new(crate::from_hex(value).unwrap()))
} 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() {
Ok(Bytes::from_bytes(value))
} else {
@ -174,8 +172,8 @@ impl<'dd> Deserialize<'dd> for Bytes {
#[cfg(test)]
mod tests {
use crate::bytes::Bytes;
use crate::blockchain::hash_utils::same_hash;
use crate::bytes::Bytes;
#[test]
pub fn test_tail_bytes() {
@ -186,6 +184,6 @@ mod tests {
#[test]
pub fn test_deref() {
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 lazy_static::lazy_static;
use uuid::Uuid;
use crate::event::Event;
use crate::simplebus::Bus;
lazy_static! {
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))
}

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

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

@ -1,7 +1,8 @@
use crate::{Chain, Keystore, Settings, Bytes};
#[allow(unused_imports)]
use log::{trace, debug, info, warn, error};
use log::{debug, error, info, trace, warn};
use crate::miner::MinerState;
use crate::{Bytes, Chain, Keystore, Settings};
pub struct Context {
pub app_version: String,
@ -9,20 +10,13 @@ pub struct Context {
pub keystores: Vec<Keystore>,
active_key: usize,
pub chain: Chain,
pub miner_state: MinerState,
pub miner_state: MinerState
}
impl Context {
/// Creating an essential context to work with
pub fn new(app_version: String, settings: Settings, keystores: Vec<Keystore>, chain: Chain) -> Context {
Context {
app_version,
settings,
keystores,
active_key: 0,
chain,
miner_state: MinerState { mining: false, full: false }
}
Context { app_version, settings, keystores, active_key: 0, chain, miner_state: MinerState { mining: false, full: false } }
}
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::{Debug, Formatter};
use chacha20poly1305::aead::{Aead, Error, NewAead};
use chacha20poly1305::{ChaCha20Poly1305, Key, Nonce};
pub const ZERO_NONCE: [u8; 12] = [0u8; 12];
@ -45,7 +46,7 @@ impl Debug for Chacha {
#[cfg(test)]
mod tests {
use crate::crypto::Chacha;
use crate::{to_hex};
use crate::to_hex;
#[test]
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::{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(crate) secret: SecretKey,
pub(crate) public: PublicKey,
pub(crate) public: PublicKey
}
impl CryptoBox {
@ -67,6 +69,7 @@ impl Clone for CryptoBox {
#[cfg(test)]
mod tests {
use rand::RngCore;
use crate::crypto::CryptoBox;
const TEXT: &str = "Some very secret message";

@ -1,6 +1,5 @@
mod crypto_box;
mod chacha;
mod crypto_box;
pub use chacha::{Chacha, ZERO_NONCE};
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::sync::{LockResult, RwLock, RwLockReadGuard, RwLockWriteGuard};
use derive_more::{Display, Error, From};
#[allow(unused_imports)]
use log::{trace, debug, info, warn, error};
use derive_more::{Display, From, Error};
use log::{debug, error, info, trace, warn};
use crate::dns::buffer::{PacketBuffer, StreamPacketBuffer, VectorPacketBuffer};
use crate::dns::protocol::{DnsPacket, DnsRecord, QueryType, ResultCode, TransientTtl};
@ -18,7 +18,7 @@ pub enum AuthorityError {
Buffer(crate::dns::buffer::BufferError),
Protocol(crate::dns::protocol::ProtocolError),
Io(std::io::Error),
PoisonedLock,
PoisonedLock
}
type Result<T> = std::result::Result<T, AuthorityError>;
@ -33,7 +33,7 @@ pub struct Zone {
pub retry: u32,
pub expire: u32,
pub minimum: u32,
pub records: BTreeSet<DnsRecord>,
pub records: BTreeSet<DnsRecord>
}
impl Zone {
@ -62,19 +62,17 @@ impl Zone {
#[derive(Default)]
pub struct Zones {
zones: BTreeMap<String, Zone>,
zones: BTreeMap<String, Zone>
}
impl<'a> Zones {
pub fn new() -> Zones {
Zones {
zones: BTreeMap::new(),
}
Zones { zones: BTreeMap::new() }
}
pub fn load(&mut self) -> Result<()> {
let zones_dir = match Path::new("zones").read_dir() {
Ok(result) => { result }
Ok(result) => result,
Err(_) => {
debug!("Authority dir (zones) not found, skipping.");
return Ok(());
@ -84,12 +82,12 @@ impl<'a> Zones {
for wrapped_filename in zones_dir {
let filename = match wrapped_filename {
Ok(x) => x,
Err(_) => continue,
Err(_) => continue
};
let mut zone_file = match File::open(filename.path()) {
Ok(x) => x,
Err(_) => continue,
Err(_) => continue
};
let mut buffer = StreamPacketBuffer::new(&mut zone_file);
@ -171,14 +169,12 @@ impl<'a> Zones {
#[derive(Default)]
pub struct Authority {
zones: RwLock<Zones>,
zones: RwLock<Zones>
}
impl Authority {
pub fn new() -> Authority {
Authority {
zones: RwLock::new(Zones::new()),
}
Authority { zones: RwLock::new(Zones::new()) }
}
pub fn load(&self) -> Result<()> {
@ -194,7 +190,7 @@ impl Authority {
pub fn query(&self, qname: &str, qtype: QueryType) -> Option<DnsPacket> {
let zones = match self.zones.read().ok() {
Some(x) => x,
None => return None,
None => return None
};
let mut best_match = None;
@ -214,7 +210,7 @@ impl Authority {
let zone = match best_match {
Some((_, zone)) => zone,
None => return None,
None => return None
};
let mut packet = DnsPacket::new();
@ -223,7 +219,7 @@ impl Authority {
for rec in &zone.records {
let domain = match rec.get_domain() {
Some(x) => x,
None => continue,
None => continue
};
if &domain != qname {
@ -248,7 +244,7 @@ impl Authority {
retry: zone.retry,
expire: zone.expire,
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)]
pub enum BufferError {
Io(std::io::Error),
EndOfBuffer,
EndOfBuffer
}
type Result<T> = std::result::Result<T, BufferError>;
@ -155,16 +155,12 @@ pub trait PacketBuffer {
pub struct VectorPacketBuffer {
pub buffer: Vec<u8>,
pub pos: usize,
pub label_lookup: BTreeMap<String, usize>,
pub label_lookup: BTreeMap<String, usize>
}
impl VectorPacketBuffer {
pub fn new() -> VectorPacketBuffer {
VectorPacketBuffer {
buffer: Vec::new(),
pos: 0,
label_lookup: BTreeMap::new(),
}
VectorPacketBuffer { 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 buffer: Vec<u8>,
pub pos: usize,
pub pos: usize
}
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 buf: [u8; 512],
pub pos: usize,
pub pos: usize
}
impl BytePacketBuffer {
pub fn new() -> BytePacketBuffer {
BytePacketBuffer {
buf: [0; 512],
pos: 0,
}
BytePacketBuffer { buf: [0; 512], pos: 0 }
}
}
@ -401,7 +395,7 @@ mod tests {
// First write the standard string
match buffer.write_qname(&instr1) {
Ok(_) => {}
Err(_) => panic!(),
Err(_) => panic!()
}
// 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 {
match buffer.write_u8(*b) {
Ok(_) => {}
Err(_) => panic!(),
Err(_) => panic!()
}
}
@ -421,7 +415,7 @@ mod tests {
let mut outstr1 = String::new();
match buffer.read_qname(&mut outstr1) {
Ok(_) => {}
Err(_) => panic!(),
Err(_) => panic!()
}
assert_eq!(instr1, outstr1);
@ -430,7 +424,7 @@ mod tests {
let mut outstr2 = String::new();
match buffer.read_qname(&mut outstr2) {
Ok(_) => {}
Err(_) => panic!(),
Err(_) => panic!()
}
assert_eq!(instr2, outstr2);
@ -445,24 +439,24 @@ mod tests {
match buffer.write_qname(&"ns1.google.com".to_string()) {
Ok(_) => {}
Err(_) => panic!(),
Err(_) => panic!()
}
match buffer.write_qname(&"ns2.google.com".to_string()) {
Ok(_) => {}
Err(_) => panic!(),
Err(_) => panic!()
}
assert_eq!(22, buffer.pos());
match buffer.seek(0) {
Ok(_) => {}
Err(_) => panic!(),
Err(_) => panic!()
}
let mut str1 = String::new();
match buffer.read_qname(&mut str1) {
Ok(_) => {}
Err(_) => panic!(),
Err(_) => panic!()
}
assert_eq!("ns1.google.com", str1);
@ -470,7 +464,7 @@ mod tests {
let mut str2 = String::new();
match buffer.read_qname(&mut str2) {
Ok(_) => {}
Err(_) => panic!(),
Err(_) => panic!()
}
assert_eq!("ns2.google.com", str2);

@ -15,7 +15,7 @@ use crate::dns::protocol::{DnsPacket, DnsRecord, QueryType, ResultCode};
#[derive(Debug, Display, From, Error)]
pub enum CacheError {
Io(std::io::Error),
PoisonedLock,
PoisonedLock
}
type Result<T> = std::result::Result<T, CacheError>;
@ -23,13 +23,13 @@ type Result<T> = std::result::Result<T, CacheError>;
pub enum CacheState {
PositiveCache,
NegativeCache,
NotCached,
NotCached
}
#[derive(Clone, Eq, Debug, Serialize, Deserialize)]
pub struct RecordEntry {
pub record: DnsRecord,
pub timestamp: DateTime<Local>,
pub timestamp: DateTime<Local>
}
impl PartialEq<RecordEntry> for RecordEntry {
@ -47,7 +47,7 @@ impl Hash for RecordEntry {
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum RecordSet {
NoRecords { qtype: QueryType, ttl: u32, timestamp: DateTime<Local> },
Records { qtype: QueryType, records: HashSet<RecordEntry> },
Records { qtype: QueryType, records: HashSet<RecordEntry> }
}
#[derive(Clone, Debug)]
@ -55,7 +55,7 @@ pub struct DomainEntry {
pub domain: String,
pub record_types: HashMap<QueryType, RecordSet>,
pub hits: u32,
pub updates: u32,
pub updates: u32
}
impl DomainEntry {
@ -128,7 +128,7 @@ impl DomainEntry {
CacheState::NegativeCache
}
}
None => CacheState::NotCached,
None => CacheState::NotCached
}
}
@ -137,7 +137,7 @@ impl DomainEntry {
let current_set = match self.record_types.get(&qtype) {
Some(x) => x,
None => return,
None => return
};
if let RecordSet::Records { ref records, .. } = *current_set {
@ -158,7 +158,7 @@ impl DomainEntry {
#[derive(Default)]
pub struct Cache {
domain_entries: BTreeMap<String, Arc<DomainEntry>>,
domain_entries: BTreeMap<String, Arc<DomainEntry>>
}
impl Cache {
@ -169,11 +169,11 @@ impl Cache {
fn get_cache_state(&mut self, qname: &str, qtype: QueryType) -> CacheState {
match self.domain_entries.get(qname) {
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 increment_stats {
domain_entry.hits += 1
@ -198,7 +198,7 @@ impl Cache {
Some(qr)
}
CacheState::NotCached => None,
CacheState::NotCached => None
}
}
@ -206,7 +206,7 @@ impl Cache {
for rec in records {
let domain = match rec.get_domain() {
Some(x) => x,
None => continue,
None => continue
};
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)]
pub struct SynchronizedCache {
pub cache: RwLock<Cache>,
pub cache: RwLock<Cache>
}
impl SynchronizedCache {
@ -257,7 +257,7 @@ impl SynchronizedCache {
pub fn lookup(&self, qname: &str, qtype: QueryType) -> Option<DnsPacket> {
let mut cache = match self.cache.write() {
Ok(x) => x,
Err(_) => return None,
Err(_) => return None
};
cache.lookup(qname, qtype)
@ -284,7 +284,6 @@ impl SynchronizedCache {
mod tests {
use super::*;
use crate::dns::protocol::{DnsRecord, QueryType, ResultCode, TransientTtl};
#[test]
@ -318,17 +317,17 @@ mod tests {
records.push(DnsRecord::A {
domain: "www.google.com".to_string(),
addr: "127.0.0.1".parse().unwrap(),
ttl: TransientTtl(3600),
ttl: TransientTtl(3600)
});
records.push(DnsRecord::A {
domain: "www.yahoo.com".to_string(),
addr: "127.0.0.2".parse().unwrap(),
ttl: TransientTtl(0),
ttl: TransientTtl(0)
});
records.push(DnsRecord::CNAME {
domain: "www.microsoft.com".to_string(),
host: "www.somecdn.com".to_string(),
ttl: TransientTtl(3600),
ttl: TransientTtl(3600)
});
cache.store(&records);
@ -361,7 +360,7 @@ mod tests {
records2.push(DnsRecord::A {
domain: "www.yahoo.com".to_string(),
addr: "127.0.0.2".parse().unwrap(),
ttl: TransientTtl(3600),
ttl: TransientTtl(3600)
});
cache.store(&records2);
@ -373,53 +372,11 @@ mod tests {
// Check stat counter behavior
assert_eq!(3, cache.domain_entries.len());
assert_eq!(
1,
cache
.domain_entries
.get(&"www.google.com".to_string())
.unwrap()
.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
);
assert_eq!(1, cache.domain_entries.get(&"www.google.com".to_string()).unwrap().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::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::mpsc::{channel, Sender};
use std::sync::{Arc, Mutex};
@ -22,7 +22,7 @@ pub enum ClientError {
Io(std::io::Error),
PoisonedLock,
LookupFailed,
TimeOut,
TimeOut
}
type Result<T> = std::result::Result<T, ClientError>;
@ -56,7 +56,7 @@ pub struct DnsNetworkClient {
socket_ipv6: UdpSocket,
/// 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
@ -65,7 +65,7 @@ pub struct DnsNetworkClient {
struct PendingQuery {
seq: u16,
timestamp: DateTime<Local>,
tx: Sender<Option<DnsPacket>>,
tx: Sender<Option<DnsPacket>>
}
unsafe impl Send for DnsNetworkClient {}
@ -80,7 +80,7 @@ impl DnsNetworkClient {
seq: AtomicUsize::new(0),
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"),
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(())
}
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)?;
if !packet.header.truncated_message {
return Ok(packet);
@ -350,7 +350,7 @@ pub mod tests {
pub type StubCallback = dyn Fn(&str, QueryType, &str, bool) -> Result<DnsPacket>;
pub struct DnsStubClient {
callback: Box<StubCallback>,
callback: Box<StubCallback>
}
impl<'a> DnsStubClient {
@ -376,7 +376,7 @@ pub mod tests {
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)
}
}
@ -386,9 +386,7 @@ pub mod tests {
let client = DnsNetworkClient::new(31456);
client.run().unwrap();
let res = client
.send_udp_query("google.com", QueryType::A, ("8.8.8.8", 53), true)
.unwrap();
let res = client.send_udp_query("google.com", QueryType::A, ("8.8.8.8", 53), true).unwrap();
assert_eq!(res.questions[0].name, "google.com");
assert!(res.answers.len() > 0);
@ -397,16 +395,14 @@ pub mod tests {
DnsRecord::A { ref domain, .. } => {
assert_eq!("google.com", domain);
}
_ => panic!(),
_ => panic!()
}
}
#[test]
pub fn test_tcp_client() {
let client = DnsNetworkClient::new(31458);
let res = client
.send_tcp_query("google.com", QueryType::A, ("8.8.8.8", 53), true)
.unwrap();
let res = client.send_tcp_query("google.com", QueryType::A, ("8.8.8.8", 53), true).unwrap();
assert_eq!(res.questions[0].name, "google.com");
assert!(res.answers.len() > 0);
@ -415,7 +411,7 @@ pub mod tests {
DnsRecord::A { ref 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::cache::SynchronizedCache;
use crate::dns::client::{DnsClient, DnsNetworkClient};
use crate::dns::resolve::{DnsResolver, ForwardingDnsResolver, RecursiveDnsResolver};
use crate::dns::filter::DnsFilter;
use crate::dns::resolve::{DnsResolver, ForwardingDnsResolver, RecursiveDnsResolver};
#[derive(Debug, Display, From, Error)]
pub enum ContextError {
Authority(crate::dns::authority::AuthorityError),
Client(crate::dns::client::ClientError),
Io(std::io::Error),
Io(std::io::Error)
}
type Result<T> = std::result::Result<T, ContextError>;
pub struct ServerStatistics {
pub tcp_query_count: AtomicUsize,
pub udp_query_count: AtomicUsize,
pub udp_query_count: AtomicUsize
}
impl ServerStatistics {
@ -37,7 +37,7 @@ impl ServerStatistics {
pub enum ResolveStrategy {
Recursive,
Forward { upstreams: Vec<String> },
Forward { upstreams: Vec<String> }
}
pub struct ServerContext {
@ -76,11 +76,8 @@ impl ServerContext {
enable_udp: true,
enable_tcp: true,
enable_api: false,
statistics: ServerStatistics {
tcp_query_count: AtomicUsize::new(0),
udp_query_count: AtomicUsize::new(0),
},
zones_dir: "zones",
statistics: ServerStatistics { tcp_query_count: AtomicUsize::new(0), udp_query_count: AtomicUsize::new(0) },
zones_dir: "zones"
}
}
@ -110,13 +107,11 @@ pub mod tests {
use std::sync::atomic::AtomicUsize;
use std::sync::Arc;
use super::*;
use crate::dns::authority::Authority;
use crate::dns::cache::SynchronizedCache;
use crate::dns::client::tests::{DnsStubClient, StubCallback};
use super::*;
pub fn create_test_context(callback: Box<StubCallback>) -> Arc<ServerContext> {
Arc::new(ServerContext {
authority: Authority::new(),
@ -130,11 +125,8 @@ pub mod tests {
enable_udp: true,
enable_tcp: true,
enable_api: false,
statistics: ServerStatistics {
tcp_query_count: AtomicUsize::new(0),
udp_query_count: AtomicUsize::new(0),
},
zones_dir: "zones",
statistics: ServerStatistics { tcp_query_count: AtomicUsize::new(0), 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 {
fn lookup(&self, qname: &str, qtype: QueryType) -> Option<DnsPacket>;
}
pub struct DummyFilter {
}
pub struct DummyFilter {}
#[allow(unused_variables)]
impl DnsFilter for DummyFilter {

@ -1,11 +1,12 @@
use std::net::IpAddr;
use std::collections::HashMap;
use std::fs::File;
use std::io::Read;
use std::net::IpAddr;
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 {
hosts: HashMap<String, Vec<IpAddr>>
@ -33,16 +34,14 @@ impl HostsFilter {
let domain = parts[1].trim().to_owned();
if let Ok(addr) = ip.parse::<IpAddr>() {
if !domain.is_empty() {
map.entry(domain).or_insert(vec!(addr));
map.entry(domain).or_insert(vec![addr]);
}
}
}
map
}
Err(..) => {
HashMap::new()
}
Err(..) => HashMap::new()
};
HostsFilter { hosts }
}
@ -70,7 +69,11 @@ impl DnsFilter for HostsFilter {
packet.header.authoritative_answer = true;
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);
}
@ -80,9 +83,10 @@ impl DnsFilter for HostsFilter {
#[cfg(test)]
mod tests {
use crate::dns::hosts::HostsFilter;
use std::env;
use crate::dns::hosts::HostsFilter;
#[test]
#[ignore]
pub fn load_hosts() {

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

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

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

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

@ -1,13 +1,14 @@
use std::sync::{Arc, Mutex};
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)]
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::server::{DnsServer, DnsTcpServer, DnsUdpServer};
use crate::{Context, Settings};
/// Starts UDP and TCP DNS-servers
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.dns_listen = settings.dns.listen.clone();
server_context.resolve_strategy = match settings.dns.forwarders.is_empty() {
true => { ResolveStrategy::Recursive }
false => { ResolveStrategy::Forward { upstreams: settings.dns.forwarders.clone() } }
true => ResolveStrategy::Recursive,
false => ResolveStrategy::Forward { upstreams: settings.dns.forwarders.clone() }
};
// Add host filters
for host in &settings.dns.hosts {

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

@ -12,15 +12,14 @@ pub use crate::p2p::Network;
pub use crate::settings::Settings;
pub mod blockchain;
pub mod bytes;
pub mod commons;
pub mod keystore;
pub mod miner;
pub mod context;
pub mod event;
pub mod p2p;
pub mod crypto;
pub mod dns;
pub mod dns_utils;
pub mod event;
pub mod keystore;
pub mod miner;
pub mod p2p;
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.
#![windows_subsystem = "windows"]
use std::env;
use std::path::Path;
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
use std::{env, thread};
use getopts::{Options, Matches};
use getopts::{Matches, Options};
#[allow(unused_imports)]
use log::{debug, error, info, trace, warn, LevelFilter};
use simplelog::*;
#[cfg(windows)]
use winapi::um::wincon::{ATTACH_PARENT_PROCESS, AttachConsole, FreeConsole};
use winapi::um::wincon::{AttachConsole, FreeConsole, ATTACH_PARENT_PROCESS};
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::process::exit;
use std::io::{Seek, SeekFrom};
use std::process::exit;
use std::sync::atomic::{AtomicBool, Ordering};
use alfis::keystore::create_key;
use alfis::event::Event;
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")]
mod web_ui;
@ -60,7 +62,7 @@ fn main() {
let opt_matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => panic!("{}", f.to_string()),
Err(f) => panic!("{}", f.to_string())
};
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));
}
let config_name = match opt_matches.opt_str("c") {
None => { SETTINGS_FILENAME.to_owned() }
Some(path) => { path }
None => SETTINGS_FILENAME.to_owned(),
Some(path) => path
};
setup_logger(&opt_matches);
@ -125,7 +127,9 @@ fn main() {
if settings.key_files.len() > 0 {
for name in &settings.key_files {
match Keystore::from_file(name, "") {
None => { warn!("Error loading keyfile from {}", name); }
None => {
warn!("Error loading keyfile from {}", name);
}
Some(keystore) => {
info!("Successfully loaded keyfile {}", name);
keys.push(keystore);
@ -144,7 +148,7 @@ fn main() {
let context_copy = Arc::clone(&context);
// Register key-mined event listener
register(move |_uuid, e| {
if matches!(e, Event::KeyCreated {..}) {
if matches!(e, Event::KeyCreated { .. }) {
let context_copy = Arc::clone(&context_copy);
let mining_copy = Arc::clone(&mining_copy);
let filename = filename.clone();
@ -172,8 +176,12 @@ fn main() {
if let Ok(mut context) = context.lock() {
context.chain.check_chain(settings_copy.check_blocks);
match context.chain.get_block(1) {
None => { info!(target: LOG_TARGET_MAIN, "No blocks found in DB"); }
Some(block) => { trace!(target: LOG_TARGET_MAIN, "Loaded DB with origin {:?}", &block.hash); }
None => {
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);
}
};
CombinedLogger::init(
vec![
TermLogger::new(level, config.clone(), TerminalMode::Stdout, ColorChoice::Auto),
WriteLogger::new(level, config, file),
]
).unwrap();
CombinedLogger::init(vec![
TermLogger::new(level, config.clone(), TerminalMode::Stdout, ColorChoice::Auto),
WriteLogger::new(level, config, file),
])
.unwrap();
}
}
}

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

@ -2,12 +2,13 @@ extern crate serde;
extern crate serde_json;
use serde::{Deserialize, Serialize};
use crate::Bytes;
#[derive(Debug, Serialize, Deserialize)]
pub enum Message {
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 },
Ping { height: u64, hash: Bytes },
Pong { height: u64, hash: Bytes },
@ -16,7 +17,7 @@ pub enum Message {
GetPeers,
Peers { peers: Vec<String> },
GetBlock { index: u64 },
Block { index: u64, block: Vec<u8> },
Block { index: u64, block: Vec<u8> }
}
impl Message {

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

@ -1,30 +1,31 @@
extern crate serde;
extern crate serde_json;
use std::{io, thread};
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::sync::{Arc, Mutex};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Instant;
use std::{io, thread};
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
#[allow(unused_imports)]
use log::{debug, error, info, trace, warn};
use mio::{Events, Interest, Poll, Registry, Token};
use mio::event::Event;
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 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::commons::*;
use crate::eventbus::{register, post};
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);
@ -36,7 +37,7 @@ pub struct Network {
// States of peer connections, and some data to send when sockets become writable
peers: Peers,
// Orphan blocks from future
future_blocks: HashMap<u64, Block>,
future_blocks: HashMap<u64, Block>
}
impl Network {
@ -116,7 +117,9 @@ impl Network {
if yggdrasil_only && !is_yggdrasil(&address.ip()) {
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);
continue;
}
@ -137,8 +140,8 @@ impl Network {
if !self.handle_connection_event(&poll.registry(), &event) {
let _ = self.peers.close_peer(poll.registry(), &token);
let blocks = self.context.lock().unwrap().chain.get_height();
let keys = self.context.lock().unwrap().chain.get_users_count();
let domains = self.context.lock().unwrap().chain.get_domains_count();
let keys = self.context.lock().unwrap().chain.get_users_count();
let domains = self.context.lock().unwrap().chain.get_domains_count();
post(crate::event::Event::NetworkStatus { blocks, domains, keys, nodes: self.peers.get_peers_active_count() });
}
}
@ -165,8 +168,8 @@ impl Network {
let nodes = self.peers.get_peers_active_count();
let banned = self.peers.get_peers_banned_count();
let keys = context.chain.get_users_count();
let domains = context.chain.get_domains_count();
let keys = context.chain.get_users_count();
let domains = context.chain.get_domains_count();
post(crate::event::Event::NetworkStatus { blocks, domains, keys, nodes });
if log_timer.elapsed().as_secs() > LOG_REFRESH_DELAY_SEC {
@ -237,7 +240,7 @@ impl Network {
debug!("Error reading client handshake from {}.", peer.get_addr());
false
}
}
};
}
State::ServerHandshake => {
let mut stream = peer.get_stream();
@ -264,7 +267,7 @@ impl Network {
debug!("Error reading client handshake from {}", peer.get_addr());
false
}
}
};
}
_ => {
let mut stream = peer.get_stream();
@ -281,9 +284,7 @@ impl Network {
Some(peer) => {
let data = data.unwrap();
match decode_message(&data, peer.get_cipher()) {
Ok(data) => {
data
}
Ok(data) => data,
Err(_) => {
vec![]
}
@ -344,8 +345,8 @@ impl Network {
} else {
let error = data.err().unwrap();
let addr = match self.peers.get_peer(&event.token()) {
None => { String::from("unknown") }
Some(peer) => { peer.get_addr().to_string() }
None => String::from("unknown"),
Some(peer) => peer.get_addr().to_string()
};
debug!("Error reading message from {}, error = {}", addr, error);
return false;
@ -475,7 +476,7 @@ impl Network {
State::idle()
}
}
Message::Error => { State::Error }
Message::Error => State::Error,
Message::Ping { height, hash } => {
let peer = self.peers.get_mut_peer(token).unwrap();
peer.set_height(height);
@ -546,7 +547,7 @@ impl Network {
Ok(block) => block,
Err(e) => {
warn!("Error deserializing block! {}", e);
return State::Banned
return State::Banned;
}
};
if index != block.index {
@ -555,8 +556,8 @@ impl Network {
info!("Received block {} with hash {:?}", block.index, &block.hash);
self.handle_block(token, block)
}
Message::Twin => { State::Twin }
Message::Loop => { State::Loop }
Message::Twin => State::Twin,
Message::Loop => State::Loop
};
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> {
match cipher {
None => { Ok(data.clone()) }
Some(chacha) => {
chacha.encrypt(data.as_slice())
}
None => Ok(data.clone()),
Some(chacha) => 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> {
match cipher {
None => { Ok(data.clone()) }
Some(chacha) => {
chacha.decrypt(data.as_slice())
}
None => Ok(data.clone()),
Some(chacha) => 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> {
// First, we read garbage size
let data_size = match stream.read_u8() {
Ok(size) => { (size ^ 0xA) as usize }
Ok(size) => (size ^ 0xA) as usize,
Err(e) => {
error!("Error reading from socket! {}", e);
return Err(e)
return Err(e);
}
};
// Read the garbage
let mut buf = vec![0u8; data_size];
match stream.read_exact(&mut buf) {
Ok(_) => {}
Err(e) => { return Err(e); }
Err(e) => {
return Err(e);
}
}
// Then we have public key for ECDH
let mut buf = vec![0u8; 32];
match stream.read_exact(&mut buf) {
Ok(_) => { Ok(buf) }
Ok(_) => Ok(buf),
Err(e) => {
warn!("Error reading handshake!");
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> {
// First, we read garbage size
let data_size = match stream.read_u8() {
Ok(size) => { (size ^ 0xA) as usize }
Ok(size) => (size ^ 0xA) as usize,
Err(e) => {
error!("Error reading from socket! {}", e);
return Err(e)
return Err(e);
}
};
// Read the garbage
let mut buf = vec![0u8; data_size];
match stream.read_exact(&mut buf) {
Ok(_) => {}
Err(e) => { return Err(e); }
Err(e) => {
return Err(e);
}
}
// Then we have public key for ECDH, plus nonce 12 bytes
let mut buf = vec![0u8; 32 + 12];
match stream.read_exact(&mut buf) {
Ok(_) => { Ok(buf) }
Ok(_) => Ok(buf),
Err(e) => {
warn!("Error reading handshake!");
Err(e)

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

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

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

@ -1,9 +1,9 @@
use std::fs::File;
use std::io::Read;
use serde::{Deserialize, Serialize};
#[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;
@ -20,7 +20,7 @@ pub struct Settings {
#[serde(default)]
pub dns: Dns,
#[serde(default)]
pub mining: Mining,
pub mining: Mining
}
impl Settings {
@ -34,9 +34,7 @@ impl Settings {
}
None
}
Err(..) => {
None
}
Err(..) => None
}
}
@ -70,7 +68,7 @@ pub struct Dns {
pub threads: usize,
pub forwarders: Vec<String>,
#[serde(default)]
pub hosts: Vec<String>,
pub hosts: Vec<String>
}
impl Default for Dns {
@ -101,7 +99,7 @@ pub struct Net {
#[serde(default)]
pub public: bool,
#[serde(default)]
pub yggdrasil_only: bool,
pub yggdrasil_only: bool
}
impl Default for Net {

@ -8,25 +8,23 @@ use std::sync::{Arc, Mutex, MutexGuard};
use std::thread;
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::types::MineResult;
use alfis::commons::*;
use alfis::crypto::CryptoBox;
use alfis::dns::protocol::DnsRecord;
use alfis::event::Event;
use alfis::eventbus::{post, register};
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 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>>) {
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");
String::from("setLeftStatusBarText('Mining...'); showMiningIndicator(true, false);")
}
Event::MinerStopped { success, full} => {
Event::MinerStopped { success, full } => {
status.mining = false;
status.max_diff = 0;
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)
}
}
Event::BlockchainChanged {index} => {
Event::BlockchainChanged { index } => {
debug!("Current blockchain height is {}", index);
event_handle_info(&handle, &format!("Blockchain changed, current block count is {} now.", index));
String::new() // Nothing
}
_ => { String::new() }
_ => String::new()
};
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));
}
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);
}
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 pub_key = keystore.get_public();
let data = match serde_json::from_str::<DomainData>(&data) {
Ok(data) => { data }
Ok(data) => data,
Err(e) => {
show_warning(web_view, "Something wrong with domain data. I cannot mine it.");
let _ = web_view.eval("domainMiningUnavailable();");
@ -587,7 +589,7 @@ pub enum Cmd {
MineDomain { name: String, data: String, signing: String, encryption: String },
TransferDomain { name: String, owner: String },
StopMining,
Open { link: String },
Open { link: String }
}
struct Status {
@ -629,4 +631,4 @@ fn inline_style(s: &str) -> String {
fn inline_script(s: &str) -> String {
format!(r#"<script type="text/javascript">{}</script>"#, s)
}
}
Loading…
Cancel
Save