rustfmt tree

Signed-off-by: Erik Hollensbe <git@hollensbe.org>
This commit is contained in:
Erik Hollensbe 2022-04-18 14:22:57 -07:00
parent f1439980e3
commit c5b9036b9e
No known key found for this signature in database
GPG key ID: 4BB0E241A863B389
45 changed files with 828 additions and 649 deletions

View file

@ -122,7 +122,8 @@ impl AesGmacSiv {
pub fn encrypt_first_pass_finish(&mut self) { pub fn encrypt_first_pass_finish(&mut self) {
let _ = self.gmac.flush(); let _ = self.gmac.flush();
let _ = self.gmac.get_mac(&mut self.tmp); let _ = self.gmac.get_mac(&mut self.tmp);
unsafe { // tag[8..16] = tmp[0..8] ^ tmp[8..16] unsafe {
// tag[8..16] = tmp[0..8] ^ tmp[8..16]
let tmp = self.tmp.as_mut_ptr().cast::<u64>(); let tmp = self.tmp.as_mut_ptr().cast::<u64>();
*self.tag.as_mut_ptr().cast::<u64>().offset(1) = *tmp ^ *tmp.offset(1); *self.tag.as_mut_ptr().cast::<u64>().offset(1) = *tmp ^ *tmp.offset(1);
} }
@ -158,7 +159,8 @@ impl AesGmacSiv {
self.tmp[12] &= 0x7f; self.tmp[12] &= 0x7f;
let _ = self.ctr.set_ctr(&self.tmp); let _ = self.ctr.set_ctr(&self.tmp);
let _ = self.ecb.decrypt_inplace(&mut self.tag); let _ = self.ecb.decrypt_inplace(&mut self.tag);
unsafe { // tmp[0..8] = tag[0..8], tmp[8..16] = 0 unsafe {
// tmp[0..8] = tag[0..8], tmp[8..16] = 0
let tmp = self.tmp.as_mut_ptr().cast::<u64>(); let tmp = self.tmp.as_mut_ptr().cast::<u64>();
*tmp = *self.tag.as_mut_ptr().cast::<u64>(); *tmp = *self.tag.as_mut_ptr().cast::<u64>();
*tmp.offset(1) = 0; *tmp.offset(1) = 0;
@ -203,7 +205,8 @@ impl AesGmacSiv {
pub fn decrypt_finish(&mut self) -> bool { pub fn decrypt_finish(&mut self) -> bool {
let _ = self.gmac.flush(); let _ = self.gmac.flush();
let _ = self.gmac.get_mac(&mut self.tmp); let _ = self.gmac.get_mac(&mut self.tmp);
unsafe { // tag[8..16] == tmp[0..8] ^ tmp[8..16] unsafe {
// tag[8..16] == tmp[0..8] ^ tmp[8..16]
let tmp = self.tmp.as_mut_ptr().cast::<u64>(); let tmp = self.tmp.as_mut_ptr().cast::<u64>();
*self.tag.as_mut_ptr().cast::<u64>().offset(1) == *tmp ^ *tmp.offset(1) *self.tag.as_mut_ptr().cast::<u64>().offset(1) == *tmp ^ *tmp.offset(1)
} }

View file

@ -8,8 +8,8 @@
// AES-GMAC-SIV implemented using MacOS/iOS CommonCrypto (MacOS 10.13 or newer required). // AES-GMAC-SIV implemented using MacOS/iOS CommonCrypto (MacOS 10.13 or newer required).
use std::os::raw::{c_void, c_int}; use std::os::raw::{c_int, c_void};
use std::ptr::{null_mut, null}; use std::ptr::{null, null_mut};
#[allow(non_upper_case_globals)] #[allow(non_upper_case_globals)]
const kCCModeECB: i32 = 1; const kCCModeECB: i32 = 1;

View file

@ -45,10 +45,14 @@ impl C25519KeyPair {
} }
#[inline(always)] #[inline(always)]
pub fn public_bytes(&self) -> [u8; C25519_PUBLIC_KEY_SIZE] { self.1.to_bytes() } pub fn public_bytes(&self) -> [u8; C25519_PUBLIC_KEY_SIZE] {
self.1.to_bytes()
}
#[inline(always)] #[inline(always)]
pub fn secret_bytes(&self) -> Secret<{ C25519_SECRET_KEY_SIZE }> { Secret(self.0.to_bytes()) } pub fn secret_bytes(&self) -> Secret<{ C25519_SECRET_KEY_SIZE }> {
Secret(self.0.to_bytes())
}
/// Execute ECDH agreement and return a raw (un-hashed) shared secret key. /// Execute ECDH agreement and return a raw (un-hashed) shared secret key.
pub fn agree(&self, their_public: &[u8]) -> Secret<{ C25519_SHARED_SECRET_SIZE }> { pub fn agree(&self, their_public: &[u8]) -> Secret<{ C25519_SHARED_SECRET_SIZE }> {
@ -60,7 +64,9 @@ impl C25519KeyPair {
} }
impl Clone for C25519KeyPair { impl Clone for C25519KeyPair {
fn clone(&self) -> Self { Self(x25519_dalek::StaticSecret::from(self.0.to_bytes()), x25519_dalek::PublicKey::from(self.1.to_bytes())) } fn clone(&self) -> Self {
Self(x25519_dalek::StaticSecret::from(self.0.to_bytes()), x25519_dalek::PublicKey::from(self.1.to_bytes()))
}
} }
/// Ed25519 key pair for EDDSA signatures. /// Ed25519 key pair for EDDSA signatures.
@ -78,10 +84,7 @@ impl Ed25519KeyPair {
let pk = ed25519_dalek::PublicKey::from_bytes(public_bytes); let pk = ed25519_dalek::PublicKey::from_bytes(public_bytes);
let sk = ed25519_dalek::SecretKey::from_bytes(secret_bytes); let sk = ed25519_dalek::SecretKey::from_bytes(secret_bytes);
if pk.is_ok() && sk.is_ok() { if pk.is_ok() && sk.is_ok() {
Some(Ed25519KeyPair(ed25519_dalek::Keypair { Some(Ed25519KeyPair(ed25519_dalek::Keypair { public: pk.unwrap(), secret: sk.unwrap() }))
public: pk.unwrap(),
secret: sk.unwrap(),
}))
} else { } else {
None None
} }
@ -91,10 +94,14 @@ impl Ed25519KeyPair {
} }
#[inline(always)] #[inline(always)]
pub fn public_bytes(&self) -> [u8; ED25519_PUBLIC_KEY_SIZE] { self.0.public.to_bytes() } pub fn public_bytes(&self) -> [u8; ED25519_PUBLIC_KEY_SIZE] {
self.0.public.to_bytes()
}
#[inline(always)] #[inline(always)]
pub fn secret_bytes(&self) -> Secret<{ ED25519_SECRET_KEY_SIZE }> { Secret(self.0.secret.to_bytes()) } pub fn secret_bytes(&self) -> Secret<{ ED25519_SECRET_KEY_SIZE }> {
Secret(self.0.secret.to_bytes())
}
pub fn sign(&self, msg: &[u8]) -> [u8; ED25519_SIGNATURE_SIZE] { pub fn sign(&self, msg: &[u8]) -> [u8; ED25519_SIGNATURE_SIZE] {
let mut h = ed25519_dalek::Sha512::new(); let mut h = ed25519_dalek::Sha512::new();
@ -118,7 +125,9 @@ impl Ed25519KeyPair {
} }
impl Clone for Ed25519KeyPair { impl Clone for Ed25519KeyPair {
fn clone(&self) -> Self { Self(ed25519_dalek::Keypair::from_bytes(&self.0.to_bytes()).unwrap()) } fn clone(&self) -> Self {
Self(ed25519_dalek::Keypair::from_bytes(&self.0.to_bytes()).unwrap())
}
} }
pub fn ed25519_verify(public_key: &[u8], signature: &[u8], msg: &[u8]) -> bool { pub fn ed25519_verify(public_key: &[u8], signature: &[u8], msg: &[u8]) -> bool {

View file

@ -52,7 +52,9 @@ impl Write for SHA512 {
} }
#[inline(always)] #[inline(always)]
fn flush(&mut self) -> std::io::Result<()> { Ok(()) } fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
} }
pub struct SHA384(Option<openssl::sha::Sha384>); pub struct SHA384(Option<openssl::sha::Sha384>);
@ -92,7 +94,9 @@ impl Write for SHA384 {
} }
#[inline(always)] #[inline(always)]
fn flush(&mut self) -> std::io::Result<()> { Ok(()) } fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
} }
//#[link(name="crypto")] //#[link(name="crypto")]
@ -109,22 +113,18 @@ extern "C" {
pub struct HMACSHA512 { pub struct HMACSHA512 {
ctx: *mut c_void, ctx: *mut c_void,
evp_md: *const c_void evp_md: *const c_void,
} }
impl HMACSHA512 { impl HMACSHA512 {
#[inline(always)] #[inline(always)]
pub fn new(key: &[u8]) -> Self { pub fn new(key: &[u8]) -> Self {
unsafe { unsafe {
let hm = Self { let hm = Self { ctx: HMAC_CTX_new(), evp_md: EVP_sha512() };
ctx: HMAC_CTX_new(),
evp_md: EVP_sha512()
};
assert!(!hm.ctx.is_null()); assert!(!hm.ctx.is_null());
assert_ne!(HMAC_Init_ex(hm.ctx, key.as_ptr().cast(), key.len() as c_int, hm.evp_md, null()), 0); assert_ne!(HMAC_Init_ex(hm.ctx, key.as_ptr().cast(), key.len() as c_int, hm.evp_md, null()), 0);
hm hm
} }
} }
#[inline(always)] #[inline(always)]
@ -172,22 +172,18 @@ unsafe impl Send for HMACSHA512 {}
pub struct HMACSHA384 { pub struct HMACSHA384 {
ctx: *mut c_void, ctx: *mut c_void,
evp_md: *const c_void evp_md: *const c_void,
} }
impl HMACSHA384 { impl HMACSHA384 {
#[inline(always)] #[inline(always)]
pub fn new(key: &[u8]) -> Self { pub fn new(key: &[u8]) -> Self {
unsafe { unsafe {
let hm = Self { let hm = Self { ctx: HMAC_CTX_new(), evp_md: EVP_sha384() };
ctx: HMAC_CTX_new(),
evp_md: EVP_sha384()
};
assert!(!hm.ctx.is_null()); assert!(!hm.ctx.is_null());
assert_ne!(HMAC_Init_ex(hm.ctx, key.as_ptr().cast(), key.len() as c_int, hm.evp_md, null()), 0); assert_ne!(HMAC_Init_ex(hm.ctx, key.as_ptr().cast(), key.len() as c_int, hm.evp_md, null()), 0);
hm hm
} }
} }
#[inline(always)] #[inline(always)]

View file

@ -12,29 +12,43 @@ use crate::secret::Secret;
// See: https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-108.pdf page 12 // See: https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-108.pdf page 12
pub fn zt_kbkdf_hmac_sha384(key: &[u8], label: u8, context: u8, iter: u32) -> Secret<48> { pub fn zt_kbkdf_hmac_sha384(key: &[u8], label: u8, context: u8, iter: u32) -> Secret<48> {
Secret(crate::hash::hmac_sha384(key, &[ Secret(crate::hash::hmac_sha384(
key,
&[
(iter >> 24) as u8, (iter >> 24) as u8,
(iter >> 16) as u8, (iter >> 16) as u8,
(iter >> 8) as u8, (iter >> 8) as u8,
iter as u8, iter as u8,
b'Z', b'T', // can also be considered part of "label" b'Z',
b'T', // can also be considered part of "label"
label, label,
0, 0,
context, context,
0, 0, 0x01, 0x80 // 384 bits 0,
])) 0,
0x01,
0x80, // 384 bits
],
))
} }
pub fn zt_kbkdf_hmac_sha512(key: &[u8], label: u8, context: u8, iter: u32) -> Secret<64> { pub fn zt_kbkdf_hmac_sha512(key: &[u8], label: u8, context: u8, iter: u32) -> Secret<64> {
Secret(crate::hash::hmac_sha512(key, &[ Secret(crate::hash::hmac_sha512(
key,
&[
(iter >> 24) as u8, (iter >> 24) as u8,
(iter >> 16) as u8, (iter >> 16) as u8,
(iter >> 8) as u8, (iter >> 8) as u8,
iter as u8, iter as u8,
b'Z', b'T', // can also be considered part of "label" b'Z',
b'T', // can also be considered part of "label"
label, label,
0, 0,
context, context,
0, 0, 0x01, 0x80 // 384 bits 0,
])) 0,
0x01,
0x80, // 384 bits
],
))
} }

View file

@ -8,13 +8,13 @@
pub mod c25519; pub mod c25519;
pub mod hash; pub mod hash;
pub mod p384;
pub mod salsa;
pub mod poly1305;
pub mod kbkdf;
pub mod random;
pub mod secret;
pub mod hex; pub mod hex;
pub mod kbkdf;
pub mod p384;
pub mod poly1305;
pub mod random;
pub mod salsa;
pub mod secret;
pub mod varint; pub mod varint;
pub use aes_gmac_siv; pub use aes_gmac_siv;

View file

@ -10,13 +10,13 @@ use std::convert::TryInto;
use std::os::raw::{c_int, c_ulong, c_void}; use std::os::raw::{c_int, c_ulong, c_void};
use std::ptr::{null, write_volatile}; use std::ptr::{null, write_volatile};
use foreign_types::{ForeignType, ForeignTypeRef};
use lazy_static::lazy_static; use lazy_static::lazy_static;
use openssl::bn::{BigNum, BigNumContext}; use openssl::bn::{BigNum, BigNumContext};
use openssl::ec::{EcKey, EcPoint, EcPointRef, PointConversionForm}; use openssl::ec::{EcKey, EcPoint, EcPointRef, PointConversionForm};
use openssl::ecdsa::EcdsaSig; use openssl::ecdsa::EcdsaSig;
use openssl::nid::Nid; use openssl::nid::Nid;
use openssl::pkey::{Private, Public}; use openssl::pkey::{Private, Public};
use foreign_types::{ForeignType, ForeignTypeRef};
use crate::hash::SHA384; use crate::hash::SHA384;
use crate::secret::Secret; use crate::secret::Secret;
@ -39,7 +39,7 @@ lazy_static! {
#[derive(Clone)] #[derive(Clone)]
pub struct P384PublicKey { pub struct P384PublicKey {
key: EcKey<Public>, key: EcKey<Public>,
bytes: [u8; 49] bytes: [u8; 49],
} }
impl P384PublicKey { impl P384PublicKey {
@ -50,7 +50,7 @@ impl P384PublicKey {
bytes[(49 - kb.len())..].copy_from_slice(kb.as_slice()); bytes[(49 - kb.len())..].copy_from_slice(kb.as_slice());
Self { Self {
key: EcKey::from_public_key(GROUP_P384.as_ref(), key).unwrap(), key: EcKey::from_public_key(GROUP_P384.as_ref(), key).unwrap(),
bytes bytes,
} }
} }
@ -63,10 +63,7 @@ impl P384PublicKey {
if key.is_on_curve(GROUP_P384.as_ref(), &mut bnc).unwrap_or(false) { if key.is_on_curve(GROUP_P384.as_ref(), &mut bnc).unwrap_or(false) {
let key = EcKey::from_public_key(GROUP_P384.as_ref(), key.as_ref()); let key = EcKey::from_public_key(GROUP_P384.as_ref(), key.as_ref());
if key.is_ok() { if key.is_ok() {
return Some(Self { return Some(Self { key: key.unwrap(), bytes: b.try_into().unwrap() });
key: key.unwrap(),
bytes: b.try_into().unwrap()
});
} }
} }
} }
@ -89,12 +86,16 @@ impl P384PublicKey {
} }
#[inline(always)] #[inline(always)]
pub fn as_bytes(&self) -> &[u8; 49] { &self.bytes } pub fn as_bytes(&self) -> &[u8; 49] {
&self.bytes
}
} }
impl PartialEq for P384PublicKey { impl PartialEq for P384PublicKey {
#[inline(always)] #[inline(always)]
fn eq(&self, other: &Self) -> bool { self.bytes == other.bytes } fn eq(&self, other: &Self) -> bool {
self.bytes == other.bytes
}
} }
unsafe impl Send for P384PublicKey {} unsafe impl Send for P384PublicKey {}
@ -113,10 +114,7 @@ impl P384KeyPair {
let pair = EcKey::generate(GROUP_P384.as_ref()).unwrap(); // failure implies a serious problem let pair = EcKey::generate(GROUP_P384.as_ref()).unwrap(); // failure implies a serious problem
assert!(pair.check_key().is_ok()); // also would imply a serious problem assert!(pair.check_key().is_ok()); // also would imply a serious problem
let public = P384PublicKey::new_from_point(pair.public_key()); let public = P384PublicKey::new_from_point(pair.public_key());
Self { Self { pair, public }
pair,
public,
}
} }
pub fn from_bytes(public_bytes: &[u8], secret_bytes: &[u8]) -> Option<P384KeyPair> { pub fn from_bytes(public_bytes: &[u8], secret_bytes: &[u8]) -> Option<P384KeyPair> {
@ -127,10 +125,7 @@ impl P384KeyPair {
if pair.is_ok() { if pair.is_ok() {
let pair = pair.unwrap(); let pair = pair.unwrap();
if pair.check_key().is_ok() { if pair.check_key().is_ok() {
Some(Self { Some(Self { pair, public })
pair,
public
})
} else { } else {
None None
} }
@ -145,10 +140,14 @@ impl P384KeyPair {
} }
#[inline(always)] #[inline(always)]
pub fn public_key(&self) -> &P384PublicKey { &self.public } pub fn public_key(&self) -> &P384PublicKey {
&self.public
}
#[inline(always)] #[inline(always)]
pub fn public_key_bytes(&self) -> &[u8; P384_PUBLIC_KEY_SIZE] { &self.public.bytes } pub fn public_key_bytes(&self) -> &[u8; P384_PUBLIC_KEY_SIZE] {
&self.public.bytes
}
pub fn secret_key_bytes(&self) -> Secret<P384_SECRET_KEY_SIZE> { pub fn secret_key_bytes(&self) -> Secret<P384_SECRET_KEY_SIZE> {
let mut tmp: Secret<P384_SECRET_KEY_SIZE> = Secret::default(); let mut tmp: Secret<P384_SECRET_KEY_SIZE> = Secret::default();

View file

@ -6,8 +6,8 @@
* https://www.zerotier.com/ * https://www.zerotier.com/
*/ */
use std::mem::MaybeUninit;
use openssl::rand::rand_bytes; use openssl::rand::rand_bytes;
use std::mem::MaybeUninit;
pub struct SecureRandom; pub struct SecureRandom;
@ -43,18 +43,26 @@ pub fn get_bytes_secure<const COUNT: usize>() -> [u8; COUNT] {
impl SecureRandom { impl SecureRandom {
#[inline(always)] #[inline(always)]
pub fn get() -> Self { Self } pub fn get() -> Self {
Self
}
} }
impl rand_core::RngCore for SecureRandom { impl rand_core::RngCore for SecureRandom {
#[inline(always)] #[inline(always)]
fn next_u32(&mut self) -> u32 { next_u32_secure() } fn next_u32(&mut self) -> u32 {
next_u32_secure()
}
#[inline(always)] #[inline(always)]
fn next_u64(&mut self) -> u64 { next_u64_secure() } fn next_u64(&mut self) -> u64 {
next_u64_secure()
}
#[inline(always)] #[inline(always)]
fn fill_bytes(&mut self, dest: &mut [u8]) { fill_bytes_secure(dest); } fn fill_bytes(&mut self, dest: &mut [u8]) {
fill_bytes_secure(dest);
}
#[inline(always)] #[inline(always)]
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> { fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> {

View file

@ -19,7 +19,7 @@ const CONSTANTS: [u32; 4] = [ u32::from_le_bytes(*b"expa"), u32::from_le_bytes(*
/// transport encryption in ZeroTier anyway, but is still used to derive addresses from /// transport encryption in ZeroTier anyway, but is still used to derive addresses from
/// identity public keys. /// identity public keys.
pub struct Salsa<const ROUNDS: usize> { pub struct Salsa<const ROUNDS: usize> {
state: [u32; 16] state: [u32; 16],
} }
impl<const ROUNDS: usize> Salsa<ROUNDS> { impl<const ROUNDS: usize> Salsa<ROUNDS> {
@ -45,13 +45,14 @@ impl<const ROUNDS: usize> Salsa<ROUNDS> {
u32::from_le_bytes((&key[20..24]).try_into().unwrap()), u32::from_le_bytes((&key[20..24]).try_into().unwrap()),
u32::from_le_bytes((&key[24..28]).try_into().unwrap()), u32::from_le_bytes((&key[24..28]).try_into().unwrap()),
u32::from_le_bytes((&key[28..32]).try_into().unwrap()), u32::from_le_bytes((&key[28..32]).try_into().unwrap()),
CONSTANTS[3] CONSTANTS[3],
] ],
} }
} }
pub fn crypt(&mut self, mut plaintext: &[u8], mut ciphertext: &mut [u8]) { pub fn crypt(&mut self, mut plaintext: &[u8], mut ciphertext: &mut [u8]) {
let (j0, j1, j2, j3, j4, j5, j6, j7, mut j8, mut j9, j10, j11, j12, j13, j14, j15) = (self.state[0], self.state[1], self.state[2], self.state[3], self.state[4], self.state[5], self.state[6], self.state[7], self.state[8], self.state[9], self.state[10], self.state[11], self.state[12], self.state[13], self.state[14], self.state[15]); let (j0, j1, j2, j3, j4, j5, j6, j7, mut j8, mut j9, j10, j11, j12, j13, j14, j15) =
(self.state[0], self.state[1], self.state[2], self.state[3], self.state[4], self.state[5], self.state[6], self.state[7], self.state[8], self.state[9], self.state[10], self.state[11], self.state[12], self.state[13], self.state[14], self.state[15]);
loop { loop {
let (mut x0, mut x1, mut x2, mut x3, mut x4, mut x5, mut x6, mut x7, mut x8, mut x9, mut x10, mut x11, mut x12, mut x13, mut x14, mut x15) = (j0, j1, j2, j3, j4, j5, j6, j7, j8, j9, j10, j11, j12, j13, j14, j15); let (mut x0, mut x1, mut x2, mut x3, mut x4, mut x5, mut x6, mut x7, mut x8, mut x9, mut x10, mut x11, mut x12, mut x13, mut x14, mut x15) = (j0, j1, j2, j3, j4, j5, j6, j7, j8, j9, j10, j11, j12, j13, j14, j15);
@ -108,7 +109,8 @@ impl<const ROUNDS: usize> Salsa<ROUNDS> {
x15 = x15.wrapping_add(j15); x15 = x15.wrapping_add(j15);
if plaintext.len() >= 64 { if plaintext.len() >= 64 {
#[cfg(any(target_arch = "x86", target_arch = "x86_64", target_arch = "aarch64"))] { #[cfg(any(target_arch = "x86", target_arch = "x86_64", target_arch = "aarch64"))]
{
// Slightly faster keystream XOR for little-endian platforms with unaligned load/store. // Slightly faster keystream XOR for little-endian platforms with unaligned load/store.
unsafe { unsafe {
*ciphertext.as_mut_ptr().cast::<u32>() = *plaintext.as_ptr().cast::<u32>() ^ x0; *ciphertext.as_mut_ptr().cast::<u32>() = *plaintext.as_ptr().cast::<u32>() ^ x0;
@ -129,7 +131,8 @@ impl<const ROUNDS: usize> Salsa<ROUNDS> {
*ciphertext.as_mut_ptr().cast::<u32>().add(15) = *plaintext.as_ptr().cast::<u32>().add(15) ^ x15; *ciphertext.as_mut_ptr().cast::<u32>().add(15) = *plaintext.as_ptr().cast::<u32>().add(15) ^ x15;
} }
} }
#[cfg(not(any(target_arch = "x86", target_arch = "x86_64", target_arch = "aarch64")))] { #[cfg(not(any(target_arch = "x86", target_arch = "x86_64", target_arch = "aarch64")))]
{
// Portable keystream XOR with alignment-safe access and native to little-endian conversion. // Portable keystream XOR with alignment-safe access and native to little-endian conversion.
ciphertext[0..4].copy_from_slice(&(u32::from_ne_bytes(unsafe { *plaintext.as_ptr().cast::<[u8; 4]>() }) ^ x0.to_le()).to_ne_bytes()); ciphertext[0..4].copy_from_slice(&(u32::from_ne_bytes(unsafe { *plaintext.as_ptr().cast::<[u8; 4]>() }) ^ x0.to_le()).to_ne_bytes());
ciphertext[4..8].copy_from_slice(&(u32::from_ne_bytes(unsafe { *plaintext.as_ptr().add(4).cast::<[u8; 4]>() }) ^ x1.to_le()).to_ne_bytes()); ciphertext[4..8].copy_from_slice(&(u32::from_ne_bytes(unsafe { *plaintext.as_ptr().add(4).cast::<[u8; 4]>() }) ^ x1.to_le()).to_ne_bytes());
@ -171,8 +174,6 @@ impl<const ROUNDS: usize> Salsa<ROUNDS> {
#[inline(always)] #[inline(always)]
pub fn crypt_in_place(&mut self, data: &mut [u8]) { pub fn crypt_in_place(&mut self, data: &mut [u8]) {
unsafe { unsafe { self.crypt(&*slice_from_raw_parts(data.as_ptr(), data.len()), &mut *slice_from_raw_parts_mut(data.as_mut_ptr(), data.len())) }
self.crypt(&*slice_from_raw_parts(data.as_ptr(), data.len()), &mut *slice_from_raw_parts_mut(data.as_mut_ptr(), data.len()))
}
} }
} }

View file

@ -24,14 +24,20 @@ pub struct Secret<const L: usize>(pub [u8; L]);
impl<const L: usize> Secret<L> { impl<const L: usize> Secret<L> {
#[inline(always)] #[inline(always)]
pub fn new() -> Self { Self([0_u8; L]) } pub fn new() -> Self {
Self([0_u8; L])
}
/// Copy bytes into secret, will panic if size does not match. /// Copy bytes into secret, will panic if size does not match.
#[inline(always)] #[inline(always)]
pub fn from_bytes(b: &[u8]) -> Self { Self(b.try_into().unwrap()) } pub fn from_bytes(b: &[u8]) -> Self {
Self(b.try_into().unwrap())
}
#[inline(always)] #[inline(always)]
pub fn as_bytes(&self) -> &[u8; L] { return &self.0 } pub fn as_bytes(&self) -> &[u8; L] {
return &self.0;
}
/// Get a clone of the first N bytes of this secret. /// Get a clone of the first N bytes of this secret.
#[inline(always)] #[inline(always)]
@ -54,25 +60,35 @@ impl<const L: usize> Drop for Secret<L> {
impl<const L: usize> Default for Secret<L> { impl<const L: usize> Default for Secret<L> {
#[inline(always)] #[inline(always)]
fn default() -> Self { Self([0_u8; L]) } fn default() -> Self {
Self([0_u8; L])
}
} }
impl<const L: usize> AsRef<[u8]> for Secret<L> { impl<const L: usize> AsRef<[u8]> for Secret<L> {
#[inline(always)] #[inline(always)]
fn as_ref(&self) -> &[u8] { &self.0 } fn as_ref(&self) -> &[u8] {
&self.0
}
} }
impl<const L: usize> AsRef<[u8; L]> for Secret<L> { impl<const L: usize> AsRef<[u8; L]> for Secret<L> {
#[inline(always)] #[inline(always)]
fn as_ref(&self) -> &[u8; L] { &self.0 } fn as_ref(&self) -> &[u8; L] {
&self.0
}
} }
impl<const L: usize> AsMut<[u8]> for Secret<L> { impl<const L: usize> AsMut<[u8]> for Secret<L> {
#[inline(always)] #[inline(always)]
fn as_mut(&mut self) -> &mut [u8] { &mut self.0 } fn as_mut(&mut self) -> &mut [u8] {
&mut self.0
}
} }
impl<const L: usize> AsMut<[u8; L]> for Secret<L> { impl<const L: usize> AsMut<[u8; L]> for Secret<L> {
#[inline(always)] #[inline(always)]
fn as_mut(&mut self) -> &mut [u8; L] { &mut self.0 } fn as_mut(&mut self) -> &mut [u8; L] {
&mut self.0
}
} }

View file

@ -73,7 +73,9 @@ impl Encoded {
impl AsRef<[u8]> for Encoded { impl AsRef<[u8]> for Encoded {
#[inline(always)] #[inline(always)]
fn as_ref(&self) -> &[u8] { &self.0[0..(self.1 as usize)] } fn as_ref(&self) -> &[u8] {
&self.0[0..(self.1 as usize)]
}
} }
#[cfg(test)] #[cfg(test)]

View file

@ -7,7 +7,7 @@
*/ */
use std::error::Error; use std::error::Error;
use std::fmt::{Display, Debug}; use std::fmt::{Debug, Display};
pub struct InvalidFormatError; pub struct InvalidFormatError;

View file

@ -13,8 +13,8 @@ pub const VERSION_MAJOR: u8 = 1;
pub const VERSION_MINOR: u8 = 99; pub const VERSION_MINOR: u8 = 99;
pub const VERSION_REVISION: u8 = 1; pub const VERSION_REVISION: u8 = 1;
pub mod util;
pub mod error; pub mod error;
pub mod util;
pub mod vl1; pub mod vl1;
pub mod vl2; pub mod vl2;

View file

@ -10,7 +10,7 @@ use std::num::NonZeroI64;
use std::time::Duration; use std::time::Duration;
use crate::error::InvalidParameterError; use crate::error::InvalidParameterError;
use crate::vl1::{Address, Identity, Endpoint, SystemInterface, Node}; use crate::vl1::{Address, Endpoint, Identity, Node, SystemInterface};
use crate::vl2::{Switch, SwitchInterface}; use crate::vl2::{Switch, SwitchInterface};
use crate::PacketBuffer; use crate::PacketBuffer;
@ -33,13 +33,19 @@ impl NetworkHypervisor {
/// ///
/// The returned object is a Pooled<Buffer<>> instance. The buffer is returned to the pool when the container is destroyed. /// The returned object is a Pooled<Buffer<>> instance. The buffer is returned to the pool when the container is destroyed.
#[inline(always)] #[inline(always)]
pub fn get_packet_buffer(&self) -> PacketBuffer { self.vl1.get_packet_buffer() } pub fn get_packet_buffer(&self) -> PacketBuffer {
self.vl1.get_packet_buffer()
}
#[inline(always)] #[inline(always)]
pub fn address(&self) -> Address { self.vl1.identity.address } pub fn address(&self) -> Address {
self.vl1.identity.address
}
#[inline(always)] #[inline(always)]
pub fn identity(&self) -> &Identity { &self.vl1.identity } pub fn identity(&self) -> &Identity {
&self.vl1.identity
}
pub fn do_background_tasks<I: Interface>(&self, ii: &I) -> Duration { pub fn do_background_tasks<I: Interface>(&self, ii: &I) -> Duration {
self.vl1.do_background_tasks(ii) self.vl1.do_background_tasks(ii)

View file

@ -6,9 +6,9 @@
* https://www.zerotier.com/ * https://www.zerotier.com/
*/ */
use std::io::Write;
use std::mem::{MaybeUninit, size_of};
use crate::util::{array_range, array_range_mut}; use crate::util::{array_range, array_range_mut};
use std::io::Write;
use std::mem::{size_of, MaybeUninit};
use crate::util::pool::PoolFactory; use crate::util::pool::PoolFactory;
@ -27,7 +27,9 @@ unsafe impl<const L: usize> RawObject for Buffer<L> {}
impl<const L: usize> Default for Buffer<L> { impl<const L: usize> Default for Buffer<L> {
#[inline(always)] #[inline(always)]
fn default() -> Self { Self(0, [0_u8; L]) } fn default() -> Self {
Self(0, [0_u8; L])
}
} }
const OVERFLOW_ERR_MSG: &'static str = "overflow"; const OVERFLOW_ERR_MSG: &'static str = "overflow";
@ -35,14 +37,20 @@ const OVERFLOW_ERR_MSG: &'static str = "overflow";
impl<const L: usize> Buffer<L> { impl<const L: usize> Buffer<L> {
pub const CAPACITY: usize = L; pub const CAPACITY: usize = L;
pub const fn capacity(&self) -> usize { L } pub const fn capacity(&self) -> usize {
L
}
#[inline(always)] #[inline(always)]
pub fn new() -> Self { Self(0, [0_u8; L]) } pub fn new() -> Self {
Self(0, [0_u8; L])
}
/// Create an empty buffer without zeroing its memory (saving a bit of CPU). /// Create an empty buffer without zeroing its memory (saving a bit of CPU).
#[inline(always)] #[inline(always)]
pub unsafe fn new_without_memzero() -> Self { Self(0, MaybeUninit::uninit().assume_init()) } pub unsafe fn new_without_memzero() -> Self {
Self(0, MaybeUninit::uninit().assume_init())
}
#[inline(always)] #[inline(always)]
pub fn from_bytes(b: &[u8]) -> std::io::Result<Self> { pub fn from_bytes(b: &[u8]) -> std::io::Result<Self> {
@ -58,22 +66,34 @@ impl<const L: usize> Buffer<L> {
} }
#[inline(always)] #[inline(always)]
pub fn as_bytes(&self) -> &[u8] { &self.1[0..self.0] } pub fn as_bytes(&self) -> &[u8] {
&self.1[0..self.0]
}
#[inline(always)] #[inline(always)]
pub fn as_bytes_mut(&mut self) -> &mut [u8] { &mut self.1[0..self.0] } pub fn as_bytes_mut(&mut self) -> &mut [u8] {
&mut self.1[0..self.0]
}
#[inline(always)] #[inline(always)]
pub fn as_range_fixed<const START: usize, const LEN: usize>(&self) -> &[u8; LEN] { array_range::<u8, L, START, LEN>(&self.1) } pub fn as_range_fixed<const START: usize, const LEN: usize>(&self) -> &[u8; LEN] {
array_range::<u8, L, START, LEN>(&self.1)
}
#[inline(always)] #[inline(always)]
pub fn as_ptr(&self) -> *const u8 { self.1.as_ptr() } pub fn as_ptr(&self) -> *const u8 {
self.1.as_ptr()
}
#[inline(always)] #[inline(always)]
pub fn as_mut_ptr(&mut self) -> *mut u8 { self.1.as_mut_ptr() } pub fn as_mut_ptr(&mut self) -> *mut u8 {
self.1.as_mut_ptr()
}
#[inline(always)] #[inline(always)]
pub fn as_mut_range_fixed<const START: usize, const LEN: usize>(&mut self) -> &mut [u8; LEN] { array_range_mut::<u8, L, START, LEN>(&mut self.1) } pub fn as_mut_range_fixed<const START: usize, const LEN: usize>(&mut self) -> &mut [u8; LEN] {
array_range_mut::<u8, L, START, LEN>(&mut self.1)
}
/// Get all bytes after a given position. /// Get all bytes after a given position.
#[inline(always)] #[inline(always)]
@ -106,10 +126,14 @@ impl<const L: usize> Buffer<L> {
} }
#[inline(always)] #[inline(always)]
pub fn len(&self) -> usize { self.0 } pub fn len(&self) -> usize {
self.0
}
#[inline(always)] #[inline(always)]
pub fn is_empty(&self) -> bool { self.0 == 0 } pub fn is_empty(&self) -> bool {
self.0 == 0
}
/// Set the size of this buffer's data. /// Set the size of this buffer's data.
/// ///
@ -127,10 +151,14 @@ impl<const L: usize> Buffer<L> {
} }
#[inline(always)] #[inline(always)]
pub unsafe fn set_size_unchecked(&mut self, s: usize) { self.0 = s; } pub unsafe fn set_size_unchecked(&mut self, s: usize) {
self.0 = s;
}
#[inline(always)] #[inline(always)]
pub unsafe fn get_unchecked(&self, i: usize) -> u8 { *self.1.get_unchecked(i) } pub unsafe fn get_unchecked(&self, i: usize) -> u8 {
*self.1.get_unchecked(i)
}
/// Append a structure and return a mutable reference to its memory. /// Append a structure and return a mutable reference to its memory.
#[inline(always)] #[inline(always)]
@ -314,9 +342,7 @@ impl<const L: usize> Buffer<L> {
#[inline(always)] #[inline(always)]
pub fn struct_at<T: RawObject>(&self, ptr: usize) -> std::io::Result<&T> { pub fn struct_at<T: RawObject>(&self, ptr: usize) -> std::io::Result<&T> {
if (ptr + size_of::<T>()) <= self.0 { if (ptr + size_of::<T>()) <= self.0 {
unsafe { unsafe { Ok(&*self.1.as_ptr().cast::<u8>().offset(ptr as isize).cast::<T>()) }
Ok(&*self.1.as_ptr().cast::<u8>().offset(ptr as isize).cast::<T>())
}
} else { } else {
Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, OVERFLOW_ERR_MSG)) Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, OVERFLOW_ERR_MSG))
} }
@ -326,9 +352,7 @@ impl<const L: usize> Buffer<L> {
#[inline(always)] #[inline(always)]
pub fn struct_mut_at<T: RawObject>(&mut self, ptr: usize) -> std::io::Result<&mut T> { pub fn struct_mut_at<T: RawObject>(&mut self, ptr: usize) -> std::io::Result<&mut T> {
if (ptr + size_of::<T>()) <= self.0 { if (ptr + size_of::<T>()) <= self.0 {
unsafe { unsafe { Ok(&mut *self.1.as_mut_ptr().cast::<u8>().offset(ptr as isize).cast::<T>()) }
Ok(&mut *self.1.as_mut_ptr().cast::<u8>().offset(ptr as isize).cast::<T>())
}
} else { } else {
Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, OVERFLOW_ERR_MSG)) Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, OVERFLOW_ERR_MSG))
} }
@ -351,9 +375,7 @@ impl<const L: usize> Buffer<L> {
debug_assert!(end <= L); debug_assert!(end <= L);
if end <= self.0 { if end <= self.0 {
*cursor = end; *cursor = end;
unsafe { unsafe { Ok(&*self.1.as_ptr().cast::<u8>().offset(ptr as isize).cast::<T>()) }
Ok(&*self.1.as_ptr().cast::<u8>().offset(ptr as isize).cast::<T>())
}
} else { } else {
Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, OVERFLOW_ERR_MSG)) Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, OVERFLOW_ERR_MSG))
} }
@ -366,9 +388,7 @@ impl<const L: usize> Buffer<L> {
debug_assert!(end <= L); debug_assert!(end <= L);
if end <= self.0 { if end <= self.0 {
*cursor = end; *cursor = end;
unsafe { unsafe { Ok(&*self.1.as_ptr().cast::<u8>().offset(ptr as isize).cast::<[u8; S]>()) }
Ok(&*self.1.as_ptr().cast::<u8>().offset(ptr as isize).cast::<[u8; S]>())
}
} else { } else {
Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, OVERFLOW_ERR_MSG)) Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, OVERFLOW_ERR_MSG))
} }
@ -501,7 +521,9 @@ impl<const L: usize> Buffer<L> {
impl<const L: usize> PartialEq for Buffer<L> { impl<const L: usize> PartialEq for Buffer<L> {
#[inline(always)] #[inline(always)]
fn eq(&self, other: &Self) -> bool { self.1[0..self.0].eq(&other.1[0..other.0]) } fn eq(&self, other: &Self) -> bool {
self.1[0..self.0].eq(&other.1[0..other.0])
}
} }
impl<const L: usize> Eq for Buffer<L> {} impl<const L: usize> Eq for Buffer<L> {}
@ -521,30 +543,42 @@ impl<const L: usize> Write for Buffer<L> {
} }
#[inline(always)] #[inline(always)]
fn flush(&mut self) -> std::io::Result<()> { Ok(()) } fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
} }
impl<const L: usize> AsRef<[u8]> for Buffer<L> { impl<const L: usize> AsRef<[u8]> for Buffer<L> {
#[inline(always)] #[inline(always)]
fn as_ref(&self) -> &[u8] { self.as_bytes() } fn as_ref(&self) -> &[u8] {
self.as_bytes()
}
} }
impl<const L: usize> AsMut<[u8]> for Buffer<L> { impl<const L: usize> AsMut<[u8]> for Buffer<L> {
#[inline(always)] #[inline(always)]
fn as_mut(&mut self) -> &mut [u8] { self.as_bytes_mut() } fn as_mut(&mut self) -> &mut [u8] {
self.as_bytes_mut()
}
} }
pub struct PooledBufferFactory<const L: usize>; pub struct PooledBufferFactory<const L: usize>;
impl<const L: usize> PooledBufferFactory<L> { impl<const L: usize> PooledBufferFactory<L> {
#[inline(always)] #[inline(always)]
pub fn new() -> Self { Self{} } pub fn new() -> Self {
Self {}
}
} }
impl<const L: usize> PoolFactory<Buffer<L>> for PooledBufferFactory<L> { impl<const L: usize> PoolFactory<Buffer<L>> for PooledBufferFactory<L> {
#[inline(always)] #[inline(always)]
fn create(&self) -> Buffer<L> { Buffer::new() } fn create(&self) -> Buffer<L> {
Buffer::new()
}
#[inline(always)] #[inline(always)]
fn reset(&self, obj: &mut Buffer<L>) { obj.clear(); } fn reset(&self, obj: &mut Buffer<L>) {
obj.clear();
}
} }

View file

@ -14,15 +14,21 @@ pub struct IntervalGate<const FREQ: i64>(i64);
impl<const FREQ: i64> Default for IntervalGate<FREQ> { impl<const FREQ: i64> Default for IntervalGate<FREQ> {
#[inline(always)] #[inline(always)]
fn default() -> Self { Self(0) } fn default() -> Self {
Self(0)
}
} }
impl<const FREQ: i64> IntervalGate<FREQ> { impl<const FREQ: i64> IntervalGate<FREQ> {
#[inline(always)] #[inline(always)]
pub fn new(initial_ts: i64) -> Self { Self(initial_ts) } pub fn new(initial_ts: i64) -> Self {
Self(initial_ts)
}
#[inline(always)] #[inline(always)]
pub fn reset(&mut self) { self.0 = 0; } pub fn reset(&mut self) {
self.0 = 0;
}
#[inline(always)] #[inline(always)]
pub fn gate(&mut self, time: i64) -> bool { pub fn gate(&mut self, time: i64) -> bool {
@ -41,15 +47,21 @@ pub struct AtomicIntervalGate<const FREQ: i64>(AtomicI64);
impl<const FREQ: i64> Default for AtomicIntervalGate<FREQ> { impl<const FREQ: i64> Default for AtomicIntervalGate<FREQ> {
#[inline(always)] #[inline(always)]
fn default() -> Self { Self(AtomicI64::new(0)) } fn default() -> Self {
Self(AtomicI64::new(0))
}
} }
impl<const FREQ: i64> AtomicIntervalGate<FREQ> { impl<const FREQ: i64> AtomicIntervalGate<FREQ> {
#[inline(always)] #[inline(always)]
pub fn new(initial_ts: i64) -> Self { Self(AtomicI64::new(initial_ts)) } pub fn new(initial_ts: i64) -> Self {
Self(AtomicI64::new(initial_ts))
}
#[inline(always)] #[inline(always)]
pub fn reset(&self) { self.0.store(0, Ordering::Relaxed); } pub fn reset(&self) {
self.0.store(0, Ordering::Relaxed);
}
#[inline(always)] #[inline(always)]
pub fn gate(&self, mut time: i64) -> bool { pub fn gate(&self, mut time: i64) -> bool {

View file

@ -6,9 +6,9 @@
* https://www.zerotier.com/ * https://www.zerotier.com/
*/ */
pub(crate) mod pool;
pub(crate) mod gate;
pub mod buffer; pub mod buffer;
pub(crate) mod gate;
pub(crate) mod pool;
pub use zerotier_core_crypto::hex; pub use zerotier_core_crypto::hex;
pub use zerotier_core_crypto::varint; pub use zerotier_core_crypto::varint;
@ -31,7 +31,9 @@ pub(crate) fn array_range_mut<T, const A: usize, const START: usize, const LEN:
/// Cast a u64 to a byte array. /// Cast a u64 to a byte array.
#[inline(always)] #[inline(always)]
pub(crate) fn u64_as_bytes(i: &u64) -> &[u8; 8] { unsafe { &*(i as *const u64).cast() } } pub(crate) fn u64_as_bytes(i: &u64) -> &[u8; 8] {
unsafe { &*(i as *const u64).cast() }
}
lazy_static! { lazy_static! {
static ref HIGHWAYHASHER_KEY: [u64; 4] = [zerotier_core_crypto::random::next_u64_secure(), zerotier_core_crypto::random::next_u64_secure(), zerotier_core_crypto::random::next_u64_secure(), zerotier_core_crypto::random::next_u64_secure()]; static ref HIGHWAYHASHER_KEY: [u64; 4] = [zerotier_core_crypto::random::next_u64_secure(), zerotier_core_crypto::random::next_u64_secure(), zerotier_core_crypto::random::next_u64_secure(), zerotier_core_crypto::random::next_u64_secure()];
@ -40,7 +42,9 @@ lazy_static! {
/// Get an instance of HighwayHasher initialized with a secret per-process random salt. /// Get an instance of HighwayHasher initialized with a secret per-process random salt.
/// The random salt is generated at process start and so will differ for each invocation of whatever process this is inside. /// The random salt is generated at process start and so will differ for each invocation of whatever process this is inside.
#[inline(always)] #[inline(always)]
pub(crate) fn highwayhasher() -> highway::HighwayHasher { highway::HighwayHasher::new(highway::Key(HIGHWAYHASHER_KEY.clone())) } pub(crate) fn highwayhasher() -> highway::HighwayHasher {
highway::HighwayHasher::new(highway::Key(HIGHWAYHASHER_KEY.clone()))
}
/// Non-cryptographic 64-bit bit mixer for things like local hashing. /// Non-cryptographic 64-bit bit mixer for things like local hashing.
#[inline(always)] #[inline(always)]
@ -59,12 +63,16 @@ pub(crate) struct U64NoOpHasher(u64);
impl U64NoOpHasher { impl U64NoOpHasher {
#[inline(always)] #[inline(always)]
pub fn new() -> Self { Self(0) } pub fn new() -> Self {
Self(0)
}
} }
impl std::hash::Hasher for U64NoOpHasher { impl std::hash::Hasher for U64NoOpHasher {
#[inline(always)] #[inline(always)]
fn finish(&self) -> u64 { self.0 } fn finish(&self) -> u64 {
self.0
}
#[inline(always)] #[inline(always)]
fn write(&mut self, _: &[u8]) { fn write(&mut self, _: &[u8]) {
@ -72,15 +80,21 @@ impl std::hash::Hasher for U64NoOpHasher {
} }
#[inline(always)] #[inline(always)]
fn write_u64(&mut self, i: u64) { self.0 += i; } fn write_u64(&mut self, i: u64) {
self.0 += i;
}
#[inline(always)] #[inline(always)]
fn write_i64(&mut self, i: i64) { self.0 += i as u64; } fn write_i64(&mut self, i: i64) {
self.0 += i as u64;
}
} }
impl std::hash::BuildHasher for U64NoOpHasher { impl std::hash::BuildHasher for U64NoOpHasher {
type Hasher = Self; type Hasher = Self;
#[inline(always)] #[inline(always)]
fn build_hasher(&self) -> Self::Hasher { Self(0) } fn build_hasher(&self) -> Self::Hasher {
Self(0)
}
} }

View file

@ -129,13 +129,11 @@ impl<O, F: PoolFactory<O>> Pool<O, F> {
#[inline(always)] #[inline(always)]
pub fn get(&self) -> Pooled<O, F> { pub fn get(&self) -> Pooled<O, F> {
//let _ = self.0.outstanding_count.fetch_add(1, Ordering::Acquire); //let _ = self.0.outstanding_count.fetch_add(1, Ordering::Acquire);
Pooled::<O, F>(self.0.pool.lock().pop().unwrap_or_else(|| { Pooled::<O, F>(self.0.pool.lock().pop().unwrap_or_else(|| unsafe {
unsafe {
NonNull::new_unchecked(Box::into_raw(Box::new(PoolEntry::<O, F> { NonNull::new_unchecked(Box::into_raw(Box::new(PoolEntry::<O, F> {
obj: self.0.factory.create(), obj: self.0.factory.create(),
return_pool: Arc::downgrade(&self.0), return_pool: Arc::downgrade(&self.0),
}))) })))
}
})) }))
} }
@ -169,8 +167,8 @@ unsafe impl<O, F: PoolFactory<O>> Send for Pool<O, F> {}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::Duration; use std::time::Duration;
use crate::util::pool::*; use crate::util::pool::*;

View file

@ -11,8 +11,8 @@ use std::num::NonZeroU64;
use std::str::FromStr; use std::str::FromStr;
use crate::error::InvalidFormatError; use crate::error::InvalidFormatError;
use crate::util::hex::HEX_CHARS;
use crate::util::buffer::Buffer; use crate::util::buffer::Buffer;
use crate::util::hex::HEX_CHARS;
use crate::vl1::protocol::{ADDRESS_RESERVED_PREFIX, ADDRESS_SIZE}; use crate::vl1::protocol::{ADDRESS_RESERVED_PREFIX, ADDRESS_SIZE};
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
@ -24,13 +24,7 @@ impl Address {
#[inline(always)] #[inline(always)]
pub fn from_u64(mut i: u64) -> Option<Address> { pub fn from_u64(mut i: u64) -> Option<Address> {
i &= 0xffffffffff; i &= 0xffffffffff;
NonZeroU64::new(i).and_then(|ii| { NonZeroU64::new(i).and_then(|ii| if (i >> 32) != ADDRESS_RESERVED_PREFIX as u64 { Some(Address(ii)) } else { None })
if (i >> 32) != ADDRESS_RESERVED_PREFIX as u64 {
Some(Address(ii))
} else {
None
}
})
} }
#[inline(always)] #[inline(always)]
@ -54,7 +48,9 @@ impl Address {
} }
#[inline(always)] #[inline(always)]
pub fn to_u64(&self) -> u64 { self.0.get() } pub fn to_u64(&self) -> u64 {
self.0.get()
}
#[inline(always)] #[inline(always)]
pub(crate) fn marshal<const BL: usize>(&self, buf: &mut Buffer<BL>) -> std::io::Result<()> { pub(crate) fn marshal<const BL: usize>(&self, buf: &mut Buffer<BL>) -> std::io::Result<()> {

View file

@ -25,12 +25,24 @@ fn write_escaped<W: Write>(b: &[u8], w: &mut W) -> std::io::Result<()> {
while i < l { while i < l {
let ii = i + 1; let ii = i + 1;
match b[i] { match b[i] {
0 => { w.write_all(&[b'\\', b'0'])?; } 0 => {
b'\n' => { w.write_all(&[b'\\', b'n'])?; } w.write_all(&[b'\\', b'0'])?;
b'\r' => { w.write_all(&[b'\\', b'r'])?; } }
b'=' => { w.write_all(&[b'\\', b'e'])?; } b'\n' => {
b'\\' => { w.write_all(&[b'\\', b'\\'])?; } w.write_all(&[b'\\', b'n'])?;
_ => { w.write_all(&b[i..ii])?; } }
b'\r' => {
w.write_all(&[b'\\', b'r'])?;
}
b'=' => {
w.write_all(&[b'\\', b'e'])?;
}
b'\\' => {
w.write_all(&[b'\\', b'\\'])?;
}
_ => {
w.write_all(&b[i..ii])?;
}
} }
i = ii; i = ii;
} }
@ -52,15 +64,23 @@ fn append_printable(s: &mut String, b: &[u8]) {
} }
impl Dictionary { impl Dictionary {
pub fn new() -> Self { Self(BTreeMap::new()) } pub fn new() -> Self {
Self(BTreeMap::new())
}
pub fn clear(&mut self) { self.0.clear() } pub fn clear(&mut self) {
self.0.clear()
}
#[inline(always)] #[inline(always)]
pub fn len(&self) -> usize { self.0.len() } pub fn len(&self) -> usize {
self.0.len()
}
#[inline(always)] #[inline(always)]
pub fn is_empty(&self) -> bool { self.0.is_empty() } pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn get_str(&self, k: &str) -> Option<&str> { pub fn get_str(&self, k: &str) -> Option<&str> {
self.0.get(k).map_or(None, |v| std::str::from_utf8(v.as_slice()).map_or(None, |s| Some(s))) self.0.get(k).map_or(None, |v| std::str::from_utf8(v.as_slice()).map_or(None, |s| Some(s)))
@ -131,7 +151,7 @@ impl Dictionary {
b'0' => 0, b'0' => 0,
b'n' => b'\n', b'n' => b'\n',
b'r' => b'\r', b'r' => b'\r',
_ => c // =, \, and escapes before other characters are unnecessary but not errors _ => c, // =, \, and escapes before other characters are unnecessary but not errors
}); });
} else if c == b'\\' { } else if c == b'\\' {
escape = true; escape = true;

View file

@ -11,9 +11,9 @@ use std::hash::{Hash, Hasher};
use zerotier_core_crypto::hash::SHA384_HASH_SIZE; use zerotier_core_crypto::hash::SHA384_HASH_SIZE;
use crate::vl1::{Address, MAC};
use crate::vl1::inetaddress::InetAddress;
use crate::util::buffer::Buffer; use crate::util::buffer::Buffer;
use crate::vl1::inetaddress::InetAddress;
use crate::vl1::{Address, MAC};
pub const TYPE_NIL: u8 = 0; pub const TYPE_NIL: u8 = 0;
pub const TYPE_ZEROTIER: u8 = 1; pub const TYPE_ZEROTIER: u8 = 1;
@ -70,7 +70,9 @@ pub enum Endpoint {
impl Default for Endpoint { impl Default for Endpoint {
#[inline(always)] #[inline(always)]
fn default() -> Endpoint { Endpoint::Nil } fn default() -> Endpoint {
Endpoint::Nil
}
} }
impl Endpoint { impl Endpoint {
@ -81,7 +83,7 @@ impl Endpoint {
Endpoint::Ip(ip) => Some((&ip, TYPE_IP)), Endpoint::Ip(ip) => Some((&ip, TYPE_IP)),
Endpoint::IpUdp(ip) => Some((&ip, TYPE_IPUDP)), Endpoint::IpUdp(ip) => Some((&ip, TYPE_IPUDP)),
Endpoint::IpTcp(ip) => Some((&ip, TYPE_IPTCP)), Endpoint::IpTcp(ip) => Some((&ip, TYPE_IPTCP)),
_ => None _ => None,
} }
} }
@ -102,7 +104,9 @@ impl Endpoint {
} }
#[inline(always)] #[inline(always)]
pub fn is_nil(&self) -> bool { matches!(self, Endpoint::Nil) } pub fn is_nil(&self) -> bool {
matches!(self, Endpoint::Nil)
}
#[inline(always)] #[inline(always)]
pub fn to_bytes(&self) -> Vec<u8> { pub fn to_bytes(&self) -> Vec<u8> {
@ -113,9 +117,7 @@ impl Endpoint {
pub fn marshal<const BL: usize>(&self, buf: &mut Buffer<BL>) -> std::io::Result<()> { pub fn marshal<const BL: usize>(&self, buf: &mut Buffer<BL>) -> std::io::Result<()> {
match self { match self {
Endpoint::Nil => { Endpoint::Nil => buf.append_u8(TYPE_NIL),
buf.append_u8(TYPE_NIL)
}
Endpoint::ZeroTier(a, h) => { Endpoint::ZeroTier(a, h) => {
buf.append_u8(16 + TYPE_ZEROTIER)?; buf.append_u8(16 + TYPE_ZEROTIER)?;
buf.append_bytes_fixed(&a.to_bytes())?; buf.append_bytes_fixed(&a.to_bytes())?;
@ -201,7 +203,7 @@ impl Endpoint {
} else { } else {
Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid ZeroTier address")) Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid ZeroTier address"))
} }
}, }
TYPE_ETHERNET => Ok(Endpoint::Ethernet(read_mac(buf, cursor)?)), TYPE_ETHERNET => Ok(Endpoint::Ethernet(read_mac(buf, cursor)?)),
TYPE_WIFIDIRECT => Ok(Endpoint::WifiDirect(read_mac(buf, cursor)?)), TYPE_WIFIDIRECT => Ok(Endpoint::WifiDirect(read_mac(buf, cursor)?)),
TYPE_BLUETOOTH => Ok(Endpoint::Bluetooth(read_mac(buf, cursor)?)), TYPE_BLUETOOTH => Ok(Endpoint::Bluetooth(read_mac(buf, cursor)?)),
@ -218,8 +220,8 @@ impl Endpoint {
} else { } else {
Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid ZeroTier address")) Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid ZeroTier address"))
} }
}, }
_ => Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "unrecognized endpoint type in stream")) _ => Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "unrecognized endpoint type in stream")),
} }
} }
} }
@ -290,14 +292,16 @@ impl Ord for Endpoint {
(Endpoint::Http(a), Endpoint::Http(b)) => a.cmp(b), (Endpoint::Http(a), Endpoint::Http(b)) => a.cmp(b),
(Endpoint::WebRTC(a), Endpoint::WebRTC(b)) => a.cmp(b), (Endpoint::WebRTC(a), Endpoint::WebRTC(b)) => a.cmp(b),
(Endpoint::ZeroTierEncap(a, ah), Endpoint::ZeroTierEncap(b, bh)) => a.cmp(b).then_with(|| ah.cmp(bh)), (Endpoint::ZeroTierEncap(a, ah), Endpoint::ZeroTierEncap(b, bh)) => a.cmp(b).then_with(|| ah.cmp(bh)),
_ => self.type_id().cmp(&other.type_id()) _ => self.type_id().cmp(&other.type_id()),
} }
} }
} }
impl PartialOrd for Endpoint { impl PartialOrd for Endpoint {
#[inline(always)] #[inline(always)]
fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
} }
impl ToString for Endpoint { impl ToString for Endpoint {

View file

@ -6,8 +6,8 @@
* https://www.zerotier.com/ * https://www.zerotier.com/
*/ */
use crate::PacketBuffer;
use crate::vl1::protocol::*; use crate::vl1::protocol::*;
use crate::PacketBuffer;
/// Packet fragment re-assembler and container. /// Packet fragment re-assembler and container.
/// ///

View file

@ -8,9 +8,9 @@
use std::io::Write; use std::io::Write;
use zerotier_core_crypto::c25519::{C25519_PUBLIC_KEY_SIZE, C25519KeyPair}; use zerotier_core_crypto::c25519::{C25519KeyPair, C25519_PUBLIC_KEY_SIZE};
use zerotier_core_crypto::hash::{hmac_sha512, SHA512}; use zerotier_core_crypto::hash::{hmac_sha512, SHA512};
use zerotier_core_crypto::p384::{P384_PUBLIC_KEY_SIZE, P384KeyPair, P384PublicKey}; use zerotier_core_crypto::p384::{P384KeyPair, P384PublicKey, P384_PUBLIC_KEY_SIZE};
use zerotier_core_crypto::secret::Secret; use zerotier_core_crypto::secret::Secret;
pub const ALGORITHM_C25519: u8 = 0x01; pub const ALGORITHM_C25519: u8 = 0x01;
@ -22,14 +22,14 @@ pub const ALGORITHM_ECC_NIST_P384: u8 = 0x02;
#[derive(Clone)] #[derive(Clone)]
pub struct HybridKeyPair { pub struct HybridKeyPair {
pub c25519: C25519KeyPair, pub c25519: C25519KeyPair,
pub p384: P384KeyPair pub p384: P384KeyPair,
} }
impl HybridKeyPair { impl HybridKeyPair {
pub fn generate() -> HybridKeyPair { pub fn generate() -> HybridKeyPair {
Self { Self {
c25519: C25519KeyPair::generate(), c25519: C25519KeyPair::generate(),
p384: P384KeyPair::generate() p384: P384KeyPair::generate(),
} }
} }
@ -77,7 +77,7 @@ unsafe impl Send for HybridKeyPair {}
#[derive(Clone)] #[derive(Clone)]
pub struct HybridPublicKey { pub struct HybridPublicKey {
pub c25519: Option<[u8; C25519_PUBLIC_KEY_SIZE]>, pub c25519: Option<[u8; C25519_PUBLIC_KEY_SIZE]>,
pub p384: Option<P384PublicKey> pub p384: Option<P384PublicKey>,
} }
impl HybridPublicKey { impl HybridPublicKey {

View file

@ -6,9 +6,9 @@
* https://www.zerotier.com/ * https://www.zerotier.com/
*/ */
use std::hash::{Hash, Hasher};
use std::num::NonZeroU64; use std::num::NonZeroU64;
use std::str::FromStr; use std::str::FromStr;
use std::hash::{Hash, Hasher};
use crate::error::InvalidFormatError; use crate::error::InvalidFormatError;
use crate::util::buffer::Buffer; use crate::util::buffer::Buffer;
@ -19,7 +19,9 @@ pub struct MAC(NonZeroU64);
impl MAC { impl MAC {
#[inline(always)] #[inline(always)]
pub fn from_u64(i: u64) -> Option<MAC> { NonZeroU64::new(i & 0xffffffffffff).map(|i| MAC(i)) } pub fn from_u64(i: u64) -> Option<MAC> {
NonZeroU64::new(i & 0xffffffffffff).map(|i| MAC(i))
}
#[inline(always)] #[inline(always)]
pub fn from_bytes(b: &[u8]) -> Option<MAC> { pub fn from_bytes(b: &[u8]) -> Option<MAC> {
@ -42,7 +44,9 @@ impl MAC {
} }
#[inline(always)] #[inline(always)]
pub fn to_u64(&self) -> u64 { self.0.get() } pub fn to_u64(&self) -> u64 {
self.0.get()
}
#[inline(always)] #[inline(always)]
pub(crate) fn marshal<const BL: usize>(&self, buf: &mut Buffer<BL>) -> std::io::Result<()> { pub(crate) fn marshal<const BL: usize>(&self, buf: &mut Buffer<BL>) -> std::io::Result<()> {

View file

@ -6,31 +6,31 @@
* https://www.zerotier.com/ * https://www.zerotier.com/
*/ */
pub mod inetaddress;
pub mod endpoint; pub mod endpoint;
pub mod identity; pub mod identity;
pub mod inetaddress;
#[allow(unused)] pub(crate) mod address;
pub(crate) mod protocol; pub(crate) mod dictionary;
pub(crate) mod fragmentedpacket;
pub(crate) mod hybridkey;
pub(crate) mod mac;
pub(crate) mod node; pub(crate) mod node;
pub(crate) mod path; pub(crate) mod path;
pub(crate) mod peer; pub(crate) mod peer;
pub(crate) mod dictionary; #[allow(unused)]
pub(crate) mod address; pub(crate) mod protocol;
pub(crate) mod mac;
pub(crate) mod fragmentedpacket;
pub(crate) mod whoisqueue;
pub(crate) mod symmetricsecret; pub(crate) mod symmetricsecret;
pub(crate) mod hybridkey; pub(crate) mod whoisqueue;
pub use address::Address; pub use address::Address;
pub use mac::MAC;
pub use identity::Identity;
pub use endpoint::Endpoint;
pub use dictionary::Dictionary; pub use dictionary::Dictionary;
pub use endpoint::Endpoint;
pub use identity::Identity;
pub use inetaddress::InetAddress; pub use inetaddress::InetAddress;
pub use peer::Peer; pub use mac::MAC;
pub use path::Path;
pub use node::{Node, SystemInterface}; pub use node::{Node, SystemInterface};
pub use path::Path;
pub use peer::Peer;
pub use protocol::{PACKET_SIZE_MAX, PACKET_FRAGMENT_COUNT_MAX}; pub use protocol::{PACKET_FRAGMENT_COUNT_MAX, PACKET_SIZE_MAX};

View file

@ -14,15 +14,15 @@ use std::time::Duration;
use dashmap::DashMap; use dashmap::DashMap;
use parking_lot::Mutex; use parking_lot::Mutex;
use crate::{PacketBuffer, PacketBufferFactory, PacketBufferPool};
use crate::error::InvalidParameterError; use crate::error::InvalidParameterError;
use crate::util::buffer::Buffer; use crate::util::buffer::Buffer;
use crate::util::gate::IntervalGate; use crate::util::gate::IntervalGate;
use crate::vl1::{Address, Endpoint, Identity};
use crate::vl1::path::Path; use crate::vl1::path::Path;
use crate::vl1::peer::Peer; use crate::vl1::peer::Peer;
use crate::vl1::protocol::*; use crate::vl1::protocol::*;
use crate::vl1::whoisqueue::{QueuedPacket, WhoisQueue}; use crate::vl1::whoisqueue::{QueuedPacket, WhoisQueue};
use crate::vl1::{Address, Endpoint, Identity};
use crate::{PacketBuffer, PacketBufferFactory, PacketBufferPool};
/// Trait implemented by external code to handle events and provide an interface to the system or application. /// Trait implemented by external code to handle events and provide an interface to the system or application.
/// ///
@ -180,10 +180,14 @@ impl Node {
/// Get a packet buffer that will automatically check itself back into the pool on drop. /// Get a packet buffer that will automatically check itself back into the pool on drop.
#[inline(always)] #[inline(always)]
pub fn get_packet_buffer(&self) -> PacketBuffer { self.buffer_pool.get() } pub fn get_packet_buffer(&self) -> PacketBuffer {
self.buffer_pool.get()
}
/// Get a peer by address. /// Get a peer by address.
pub fn peer(&self, a: Address) -> Option<Arc<Peer>> { self.peers.get(&a).map(|peer| peer.value().clone()) } pub fn peer(&self, a: Address) -> Option<Arc<Peer>> {
self.peers.get(&a).map(|peer| peer.value().clone())
}
/// Get all peers currently in the peer cache. /// Get all peers currently in the peer cache.
pub fn peers(&self) -> Vec<Arc<Peer>> { pub fn peers(&self) -> Vec<Arc<Peer>> {
@ -239,7 +243,6 @@ impl Node {
path.log_receive_anything(time_ticks); path.log_receive_anything(time_ticks);
if fragment_header.is_fragment() { if fragment_header.is_fragment() {
if let Some(assembled_packet) = path.receive_fragment(u64::from_ne_bytes(fragment_header.id), fragment_header.fragment_no(), fragment_header.total_fragments(), data, time_ticks) { if let Some(assembled_packet) = path.receive_fragment(u64::from_ne_bytes(fragment_header.id), fragment_header.fragment_no(), fragment_header.total_fragments(), data, time_ticks) {
if let Some(frag0) = assembled_packet.frags[0].as_ref() { if let Some(frag0) = assembled_packet.frags[0].as_ref() {
let packet_header = frag0.struct_at::<PacketHeader>(0); let packet_header = frag0.struct_at::<PacketHeader>(0);
@ -255,9 +258,7 @@ impl Node {
} }
} }
} }
} else { } else {
if let Ok(packet_header) = data.struct_at::<PacketHeader>(0) { if let Ok(packet_header) = data.struct_at::<PacketHeader>(0) {
if let Some(source) = Address::from_bytes(&packet_header.src) { if let Some(source) = Address::from_bytes(&packet_header.src) {
if let Some(peer) = self.peer(source) { if let Some(peer) = self.peer(source) {
@ -267,9 +268,7 @@ impl Node {
} }
} }
} }
} }
} else { } else {
// Forward packets not destined for this node. // Forward packets not destined for this node.
// TODO: need to add check for whether this node should forward. Regular nodes should only forward if a trust relationship exists. // TODO: need to add check for whether this node should forward. Regular nodes should only forward if a trust relationship exists.
@ -296,10 +295,14 @@ impl Node {
} }
/// Get the current best root peer that we should use for WHOIS, relaying, etc. /// Get the current best root peer that we should use for WHOIS, relaying, etc.
pub fn root(&self) -> Option<Arc<Peer>> { self.roots.lock().first().cloned() } pub fn root(&self) -> Option<Arc<Peer>> {
self.roots.lock().first().cloned()
}
/// Return true if a peer is a root. /// Return true if a peer is a root.
pub fn is_peer_root(&self, peer: &Peer) -> bool { self.roots.lock().iter().any(|p| Arc::as_ptr(p) == (peer as *const Peer)) } pub fn is_peer_root(&self, peer: &Peer) -> bool {
self.roots.lock().iter().any(|p| Arc::as_ptr(p) == (peer as *const Peer))
}
/// Get the canonical Path object for a given endpoint and local socket information. /// Get the canonical Path object for a given endpoint and local socket information.
/// ///

View file

@ -10,19 +10,19 @@ use std::collections::HashMap;
use std::hash::Hasher; use std::hash::Hasher;
use std::io::Write; use std::io::Write;
use std::num::NonZeroI64; use std::num::NonZeroI64;
use std::sync::Arc;
use std::sync::atomic::{AtomicI64, Ordering}; use std::sync::atomic::{AtomicI64, Ordering};
use std::sync::Arc;
use highway::HighwayHash; use highway::HighwayHash;
use parking_lot::Mutex; use parking_lot::Mutex;
use zerotier_core_crypto::hash::SHA384_HASH_SIZE; use zerotier_core_crypto::hash::SHA384_HASH_SIZE;
use crate::PacketBuffer;
use crate::util::{array_range, highwayhasher, U64NoOpHasher}; use crate::util::{array_range, highwayhasher, U64NoOpHasher};
use crate::vl1::Endpoint;
use crate::vl1::fragmentedpacket::FragmentedPacket; use crate::vl1::fragmentedpacket::FragmentedPacket;
use crate::vl1::node::SystemInterface; use crate::vl1::node::SystemInterface;
use crate::vl1::protocol::*; use crate::vl1::protocol::*;
use crate::vl1::Endpoint;
use crate::PacketBuffer;
/// Keepalive interval for paths in milliseconds. /// Keepalive interval for paths in milliseconds.
pub(crate) const PATH_KEEPALIVE_INTERVAL: i64 = 20000; pub(crate) const PATH_KEEPALIVE_INTERVAL: i64 = 20000;
@ -93,19 +93,29 @@ impl Path {
} }
#[inline(always)] #[inline(always)]
pub fn endpoint(&self) -> Arc<Endpoint> { self.endpoint.lock().clone() } pub fn endpoint(&self) -> Arc<Endpoint> {
self.endpoint.lock().clone()
}
#[inline(always)] #[inline(always)]
pub fn local_socket(&self) -> Option<NonZeroI64> { self.local_socket } pub fn local_socket(&self) -> Option<NonZeroI64> {
self.local_socket
}
#[inline(always)] #[inline(always)]
pub fn local_interface(&self) -> Option<NonZeroI64> { self.local_interface } pub fn local_interface(&self) -> Option<NonZeroI64> {
self.local_interface
}
#[inline(always)] #[inline(always)]
pub fn last_send_time_ticks(&self) -> i64 { self.last_send_time_ticks.load(Ordering::Relaxed) } pub fn last_send_time_ticks(&self) -> i64 {
self.last_send_time_ticks.load(Ordering::Relaxed)
}
#[inline(always)] #[inline(always)]
pub fn last_receive_time_ticks(&self) -> i64 { self.last_receive_time_ticks.load(Ordering::Relaxed) } pub fn last_receive_time_ticks(&self) -> i64 {
self.last_receive_time_ticks.load(Ordering::Relaxed)
}
/// Receive a fragment and return a FragmentedPacket if the entire packet was assembled. /// Receive a fragment and return a FragmentedPacket if the entire packet was assembled.
/// This returns None if more fragments are needed to assemble the packet. /// This returns None if more fragments are needed to assemble the packet.
@ -152,10 +162,10 @@ impl Path {
if ip_orig.port() != ip.port() { if ip_orig.port() != ip.port() {
replace = true; replace = true;
} }
}, }
_ => {} _ => {}
} }
}, }
_ => {} _ => {}
} }
if replace { if replace {

View file

@ -9,8 +9,8 @@
use std::convert::TryFrom; use std::convert::TryFrom;
use std::mem::MaybeUninit; use std::mem::MaybeUninit;
use crate::util::buffer::{Buffer, RawObject};
use crate::vl1::Address; use crate::vl1::Address;
use crate::util::buffer::{RawObject, Buffer};
pub const VERB_VL1_NOP: u8 = 0x00; pub const VERB_VL1_NOP: u8 = 0x00;
pub const VERB_VL1_HELLO: u8 = 0x01; pub const VERB_VL1_HELLO: u8 = 0x01;
@ -224,10 +224,14 @@ unsafe impl RawObject for PacketHeader {}
impl PacketHeader { impl PacketHeader {
#[inline(always)] #[inline(always)]
pub fn cipher(&self) -> u8 { self.flags_cipher_hops & HEADER_FLAGS_FIELD_MASK_CIPHER } pub fn cipher(&self) -> u8 {
self.flags_cipher_hops & HEADER_FLAGS_FIELD_MASK_CIPHER
}
#[inline(always)] #[inline(always)]
pub fn hops(&self) -> u8 { self.flags_cipher_hops & HEADER_FLAGS_FIELD_MASK_HOPS } pub fn hops(&self) -> u8 {
self.flags_cipher_hops & HEADER_FLAGS_FIELD_MASK_HOPS
}
#[inline(always)] #[inline(always)]
pub fn increment_hops(&mut self) -> u8 { pub fn increment_hops(&mut self) -> u8 {
@ -238,10 +242,14 @@ impl PacketHeader {
} }
#[inline(always)] #[inline(always)]
pub fn is_fragmented(&self) -> bool { (self.flags_cipher_hops & HEADER_FLAG_FRAGMENTED) != 0 } pub fn is_fragmented(&self) -> bool {
(self.flags_cipher_hops & HEADER_FLAG_FRAGMENTED) != 0
}
#[inline(always)] #[inline(always)]
pub fn as_bytes(&self) -> &[u8; PACKET_HEADER_SIZE] { unsafe { &*(self as *const Self).cast::<[u8; PACKET_HEADER_SIZE]>() } } pub fn as_bytes(&self) -> &[u8; PACKET_HEADER_SIZE] {
unsafe { &*(self as *const Self).cast::<[u8; PACKET_HEADER_SIZE]>() }
}
#[inline(always)] #[inline(always)]
pub fn aad_bytes(&self) -> [u8; 11] { pub fn aad_bytes(&self) -> [u8; 11] {
@ -280,16 +288,24 @@ unsafe impl RawObject for FragmentHeader {}
impl FragmentHeader { impl FragmentHeader {
#[inline(always)] #[inline(always)]
pub fn is_fragment(&self) -> bool { self.fragment_indicator == PACKET_FRAGMENT_INDICATOR } pub fn is_fragment(&self) -> bool {
self.fragment_indicator == PACKET_FRAGMENT_INDICATOR
}
#[inline(always)] #[inline(always)]
pub fn total_fragments(&self) -> u8 { self.total_and_fragment_no >> 4 } pub fn total_fragments(&self) -> u8 {
self.total_and_fragment_no >> 4
}
#[inline(always)] #[inline(always)]
pub fn fragment_no(&self) -> u8 { self.total_and_fragment_no & 0x0f } pub fn fragment_no(&self) -> u8 {
self.total_and_fragment_no & 0x0f
}
#[inline(always)] #[inline(always)]
pub fn hops(&self) -> u8 { self.reserved_hops & HEADER_FLAGS_FIELD_MASK_HOPS } pub fn hops(&self) -> u8 {
self.reserved_hops & HEADER_FLAGS_FIELD_MASK_HOPS
}
#[inline(always)] #[inline(always)]
pub fn increment_hops(&mut self) -> u8 { pub fn increment_hops(&mut self) -> u8 {
@ -300,7 +316,9 @@ impl FragmentHeader {
} }
#[inline(always)] #[inline(always)]
pub fn as_bytes(&self) -> &[u8; FRAGMENT_HEADER_SIZE] { unsafe { &*(self as *const Self).cast::<[u8; FRAGMENT_HEADER_SIZE]>() } } pub fn as_bytes(&self) -> &[u8; FRAGMENT_HEADER_SIZE] {
unsafe { &*(self as *const Self).cast::<[u8; FRAGMENT_HEADER_SIZE]>() }
}
} }
pub(crate) mod message_component_structs { pub(crate) mod message_component_structs {

View file

@ -19,10 +19,14 @@ pub(crate) struct AesGmacSivPoolFactory(Secret<32>, Secret<32>);
impl PoolFactory<AesGmacSiv> for AesGmacSivPoolFactory { impl PoolFactory<AesGmacSiv> for AesGmacSivPoolFactory {
#[inline(always)] #[inline(always)]
fn create(&self) -> AesGmacSiv { AesGmacSiv::new(&self.0.0, &self.1.0) } fn create(&self) -> AesGmacSiv {
AesGmacSiv::new(&self.0 .0, &self.1 .0)
}
#[inline(always)] #[inline(always)]
fn reset(&self, obj: &mut AesGmacSiv) { obj.reset(); } fn reset(&self, obj: &mut AesGmacSiv) {
obj.reset();
}
} }
/// A symmetric secret key negotiated between peers. /// A symmetric secret key negotiated between peers.
@ -37,7 +41,9 @@ pub(crate) struct SymmetricSecret {
impl PartialEq for SymmetricSecret { impl PartialEq for SymmetricSecret {
#[inline(always)] #[inline(always)]
fn eq(&self, other: &Self) -> bool { self.key.0.eq(&other.key.0) } fn eq(&self, other: &Self) -> bool {
self.key.0.eq(&other.key.0)
}
} }
impl Eq for SymmetricSecret {} impl Eq for SymmetricSecret {}
@ -47,9 +53,7 @@ impl SymmetricSecret {
pub fn new(key: Secret<64>) -> SymmetricSecret { pub fn new(key: Secret<64>) -> SymmetricSecret {
let packet_hmac_key = zt_kbkdf_hmac_sha512(&key.0, KBKDF_KEY_USAGE_LABEL_PACKET_HMAC, 0, 0); let packet_hmac_key = zt_kbkdf_hmac_sha512(&key.0, KBKDF_KEY_USAGE_LABEL_PACKET_HMAC, 0, 0);
let ephemeral_ratchet_key = zt_kbkdf_hmac_sha512(&key.0, KBKDF_KEY_USAGE_LABEL_EPHEMERAL_RATCHET_KEY, 0, 0); let ephemeral_ratchet_key = zt_kbkdf_hmac_sha512(&key.0, KBKDF_KEY_USAGE_LABEL_EPHEMERAL_RATCHET_KEY, 0, 0);
let aes_factory = AesGmacSivPoolFactory( let aes_factory = AesGmacSivPoolFactory(zt_kbkdf_hmac_sha384(&key.0[0..48], KBKDF_KEY_USAGE_LABEL_AES_GMAC_SIV_K0, 0, 0).first_n(), zt_kbkdf_hmac_sha384(&key.0[0..48], KBKDF_KEY_USAGE_LABEL_AES_GMAC_SIV_K1, 0, 0).first_n());
zt_kbkdf_hmac_sha384(&key.0[0..48], KBKDF_KEY_USAGE_LABEL_AES_GMAC_SIV_K0, 0, 0).first_n(),
zt_kbkdf_hmac_sha384(&key.0[0..48], KBKDF_KEY_USAGE_LABEL_AES_GMAC_SIV_K1, 0, 0).first_n());
SymmetricSecret { SymmetricSecret {
key, key,
packet_hmac_key, packet_hmac_key,

View file

@ -11,15 +11,15 @@ use std::collections::{HashMap, LinkedList};
use parking_lot::Mutex; use parking_lot::Mutex;
use crate::util::gate::IntervalGate; use crate::util::gate::IntervalGate;
use crate::vl1::Address;
use crate::vl1::fragmentedpacket::FragmentedPacket; use crate::vl1::fragmentedpacket::FragmentedPacket;
use crate::vl1::node::{Node, SystemInterface}; use crate::vl1::node::{Node, SystemInterface};
use crate::vl1::protocol::{WHOIS_RETRY_INTERVAL, WHOIS_MAX_WAITING_PACKETS, WHOIS_RETRY_MAX}; use crate::vl1::protocol::{WHOIS_MAX_WAITING_PACKETS, WHOIS_RETRY_INTERVAL, WHOIS_RETRY_MAX};
use crate::vl1::Address;
use crate::PacketBuffer; use crate::PacketBuffer;
pub(crate) enum QueuedPacket { pub(crate) enum QueuedPacket {
Unfragmented(PacketBuffer), Unfragmented(PacketBuffer),
Fragmented(FragmentedPacket) Fragmented(FragmentedPacket),
} }
struct WhoisQueueItem { struct WhoisQueueItem {
@ -33,7 +33,9 @@ pub(crate) struct WhoisQueue(Mutex<HashMap<Address, WhoisQueueItem>>);
impl WhoisQueue { impl WhoisQueue {
pub(crate) const INTERVAL: i64 = WHOIS_RETRY_INTERVAL; pub(crate) const INTERVAL: i64 = WHOIS_RETRY_INTERVAL;
pub fn new() -> Self { Self(Mutex::new(HashMap::new())) } pub fn new() -> Self {
Self(Mutex::new(HashMap::new()))
}
/// Launch or renew a WHOIS query and enqueue a packet to be processed when (if) it is received. /// Launch or renew a WHOIS query and enqueue a packet to be processed when (if) it is received.
pub fn query<SI: SystemInterface>(&self, node: &Node, si: &SI, target: Address, packet: Option<QueuedPacket>) { pub fn query<SI: SystemInterface>(&self, node: &Node, si: &SI, target: Address, packet: Option<QueuedPacket>) {

View file

@ -6,8 +6,8 @@
* https://www.zerotier.com/ * https://www.zerotier.com/
*/ */
mod switch;
mod multicastgroup; mod multicastgroup;
mod switch;
pub use multicastgroup::MulticastGroup; pub use multicastgroup::MulticastGroup;
pub use switch::{SwitchInterface, Switch}; pub use switch::{Switch, SwitchInterface};

View file

@ -19,20 +19,14 @@ pub struct MulticastGroup {
impl From<&MAC> for MulticastGroup { impl From<&MAC> for MulticastGroup {
#[inline(always)] #[inline(always)]
fn from(mac: &MAC) -> Self { fn from(mac: &MAC) -> Self {
Self { Self { mac: mac.clone(), adi: 0 }
mac: mac.clone(),
adi: 0,
}
} }
} }
impl From<MAC> for MulticastGroup { impl From<MAC> for MulticastGroup {
#[inline(always)] #[inline(always)]
fn from(mac: MAC) -> Self { fn from(mac: MAC) -> Self {
Self { Self { mac, adi: 0 }
mac,
adi: 0,
}
} }
} }
@ -42,14 +36,16 @@ impl Ord for MulticastGroup {
let o = self.mac.cmp(&other.mac); let o = self.mac.cmp(&other.mac);
match o { match o {
Ordering::Equal => self.adi.cmp(&other.adi), Ordering::Equal => self.adi.cmp(&other.adi),
_ => o _ => o,
} }
} }
} }
impl PartialOrd for MulticastGroup { impl PartialOrd for MulticastGroup {
#[inline(always)] #[inline(always)]
fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
} }
impl Hash for MulticastGroup { impl Hash for MulticastGroup {

View file

@ -10,14 +10,12 @@ use std::sync::Arc;
use crate::util::buffer::Buffer; use crate::util::buffer::Buffer;
use crate::vl1::node::VL1VirtualInterface; use crate::vl1::node::VL1VirtualInterface;
use crate::vl1::{Peer, Path, Identity};
use crate::vl1::protocol::*; use crate::vl1::protocol::*;
use crate::vl1::{Identity, Path, Peer};
pub trait SwitchInterface: Sync + Send { pub trait SwitchInterface: Sync + Send {}
}
pub struct Switch { pub struct Switch {}
}
impl VL1VirtualInterface for Switch { impl VL1VirtualInterface for Switch {
fn handle_packet(&self, peer: &Peer, source_path: &Arc<Path>, forward_secrecy: bool, extended_authentication: bool, verb: u8, payload: &Buffer<{ PACKET_SIZE_MAX }>) -> bool { fn handle_packet(&self, peer: &Peer, source_path: &Arc<Path>, forward_secrecy: bool, extended_authentication: bool, verb: u8, payload: &Buffer<{ PACKET_SIZE_MAX }>) -> bool {

View file

@ -12,18 +12,18 @@
* for each thread using options like SO_REUSEPORT and concurrent packet listening. * for each thread using options like SO_REUSEPORT and concurrent packet listening.
*/ */
use std::mem::{MaybeUninit, transmute, zeroed}; use std::mem::{transmute, zeroed, MaybeUninit};
use std::num::NonZeroI64; use std::num::NonZeroI64;
use std::os::raw::c_int; use std::os::raw::c_int;
use std::ptr::null_mut; use std::ptr::null_mut;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use num_traits::cast::AsPrimitive; use num_traits::cast::AsPrimitive;
use crate::debug;
use zerotier_network_hypervisor::vl1::InetAddress; use zerotier_network_hypervisor::vl1::InetAddress;
use zerotier_network_hypervisor::{PacketBuffer, PacketBufferPool}; use zerotier_network_hypervisor::{PacketBuffer, PacketBufferPool};
use crate::debug;
const FAST_UDP_SOCKET_MAX_THREADS: usize = 4; const FAST_UDP_SOCKET_MAX_THREADS: usize = 4;
@ -65,12 +65,14 @@ fn bind_udp_socket(_device_name: &str, address: &InetAddress) -> Result<FastUDPR
setsockopt_results |= libc::setsockopt(s, libc::IPPROTO_IPV6.as_(), libc::IPV6_V6ONLY.as_(), (&mut fl as *mut c_int).cast(), fl_size); setsockopt_results |= libc::setsockopt(s, libc::IPPROTO_IPV6.as_(), libc::IPV6_V6ONLY.as_(), (&mut fl as *mut c_int).cast(), fl_size);
} }
#[cfg(any(target_os = "macos", target_os = "ios"))] { #[cfg(any(target_os = "macos", target_os = "ios"))]
{
fl = 1; fl = 1;
setsockopt_results |= libc::setsockopt(s, libc::SOL_SOCKET.as_(), libc::SO_NOSIGPIPE.as_(), (&mut fl as *mut c_int).cast(), fl_size) setsockopt_results |= libc::setsockopt(s, libc::SOL_SOCKET.as_(), libc::SO_NOSIGPIPE.as_(), (&mut fl as *mut c_int).cast(), fl_size)
} }
#[cfg(target_os = "linux")] { #[cfg(target_os = "linux")]
{
if !_device_name.is_empty() { if !_device_name.is_empty() {
let _ = std::ffi::CString::new(_device_name).map(|dn| { let _ = std::ffi::CString::new(_device_name).map(|dn| {
let dnb = dn.as_bytes_with_nul(); let dnb = dn.as_bytes_with_nul();
@ -85,11 +87,13 @@ fn bind_udp_socket(_device_name: &str, address: &InetAddress) -> Result<FastUDPR
} }
if af == libc::AF_INET { if af == libc::AF_INET {
#[cfg(not(target_os = "linux"))] { #[cfg(not(target_os = "linux"))]
{
fl = 0; fl = 0;
libc::setsockopt(s, libc::IPPROTO_IP.as_(), libc::IP_DF.as_(), (&mut fl as *mut c_int).cast(), fl_size); libc::setsockopt(s, libc::IPPROTO_IP.as_(), libc::IP_DF.as_(), (&mut fl as *mut c_int).cast(), fl_size);
} }
#[cfg(target_os = "linux")] { #[cfg(target_os = "linux")]
{
fl = libc::IP_PMTUDISC_DONT as c_int; fl = libc::IP_PMTUDISC_DONT as c_int;
libc::setsockopt(s, libc::IPPROTO_IP.as_(), libc::IP_MTU_DISCOVER.as_(), (&mut fl as *mut c_int).cast(), fl_size); libc::setsockopt(s, libc::IPPROTO_IP.as_(), libc::IP_MTU_DISCOVER.as_(), (&mut fl as *mut c_int).cast(), fl_size);
} }
@ -135,7 +139,9 @@ pub(crate) struct FastUDPSocket {
#[cfg(unix)] #[cfg(unix)]
#[inline(always)] #[inline(always)]
fn fast_udp_socket_close(socket: &FastUDPRawOsSocket) { fn fast_udp_socket_close(socket: &FastUDPRawOsSocket) {
unsafe { libc::close(socket.get().as_()); } unsafe {
libc::close(socket.get().as_());
}
} }
/// Send to a raw UDP socket with optional packet TTL. /// Send to a raw UDP socket with optional packet TTL.
@ -165,7 +171,7 @@ pub(crate) fn fast_udp_socket_sendto(socket: &FastUDPRawOsSocket, to_address: &I
msg_iovlen: data_len.as_(), msg_iovlen: data_len.as_(),
msg_control: null_mut(), msg_control: null_mut(),
msg_controllen: 0, msg_controllen: 0,
msg_flags: 0 msg_flags: 0,
}; };
if packet_ttl == 0 || to_address.is_ipv6() { if packet_ttl == 0 || to_address.is_ipv6() {
@ -216,7 +222,10 @@ impl FastUDPSocket {
let thread_run = s.thread_run.clone(); let thread_run = s.thread_run.clone();
let handler_copy = handler.clone(); let handler_copy = handler.clone();
let packet_buffer_pool_copy = packet_buffer_pool.clone(); let packet_buffer_pool_copy = packet_buffer_pool.clone();
s.threads.push(std::thread::Builder::new().stack_size(zerotier_core::RECOMMENDED_THREAD_STACK_SIZE).spawn(move || { s.threads.push(
std::thread::Builder::new()
.stack_size(zerotier_core::RECOMMENDED_THREAD_STACK_SIZE)
.spawn(move || {
let mut from_address = InetAddress::new(); let mut from_address = InetAddress::new();
while thread_run.load(Ordering::Relaxed) { while thread_run.load(Ordering::Relaxed) {
let mut buf = packet_buffer_pool_copy.get_packet_buffer(); let mut buf = packet_buffer_pool_copy.get_packet_buffer();
@ -227,7 +236,9 @@ impl FastUDPSocket {
break; break;
} }
} }
}).unwrap()); })
.unwrap(),
);
} else { } else {
bind_failed_reason = thread_socket.err().unwrap(); bind_failed_reason = thread_socket.err().unwrap();
} }
@ -292,7 +303,7 @@ mod tests {
use std::sync::atomic::{AtomicU32, Ordering}; use std::sync::atomic::{AtomicU32, Ordering};
use crate::fastudpsocket::*; use crate::fastudpsocket::*;
use zerotier_network_hypervisor::{PacketBufferPool, PacketBufferFactory, PacketBuffer}; use zerotier_network_hypervisor::{PacketBuffer, PacketBufferFactory, PacketBufferPool};
#[test] #[test]
fn test_udp_bind_and_transfer() { fn test_udp_bind_and_transfer() {

View file

@ -13,7 +13,9 @@ use zerotier_network_hypervisor::vl1::InetAddress;
#[allow(unused)] #[allow(unused)]
#[inline(always)] #[inline(always)]
fn s6_addr_as_ptr<A>(a: &A) -> *const A { a as *const A } fn s6_addr_as_ptr<A>(a: &A) -> *const A {
a as *const A
}
/// Call supplied function or closure for each physical IP address in the system. /// Call supplied function or closure for each physical IP address in the system.
#[cfg(unix)] #[cfg(unix)]
@ -88,9 +90,7 @@ mod tests {
#[test] #[test]
fn test_getifaddrs() { fn test_getifaddrs() {
println!("starting getifaddrs..."); println!("starting getifaddrs...");
crate::getifaddrs::for_each_address(|a: &InetAddress, dev: &str| { crate::getifaddrs::for_each_address(|a: &InetAddress, dev: &str| println!(" {} {}", dev, a.to_string()));
println!(" {} {}", dev, a.to_string())
});
println!("done.") println!("done.")
} }
} }

View file

@ -13,62 +13,23 @@ use serde::{Deserialize, Serialize};
use zerotier_network_hypervisor::vl1::{Address, InetAddress}; use zerotier_network_hypervisor::vl1::{Address, InetAddress};
pub const UNASSIGNED_PRIVILEGED_PORTS: [u16; 299] = [ pub const UNASSIGNED_PRIVILEGED_PORTS: [u16; 299] = [
4, 4, 6, 8, 10, 12, 14, 15, 16, 26, 28, 30, 32, 34, 36, 40, 60, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 285, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 334, 335, 336, 337, 338,
6, 339, 340, 341, 342, 343, 703, 708, 713, 714, 715, 716, 717, 718, 719, 720, 721, 722, 723, 724, 725, 726, 727, 728, 732, 733, 734, 735, 736, 737, 738, 739, 740, 743, 745, 746, 755, 756, 766, 768, 778, 779, 781, 782, 783, 784, 785, 786, 787, 788, 789, 790, 791, 792, 793, 794, 795, 796, 797, 798,
8, 799, 802, 803, 804, 805, 806, 807, 808, 809, 811, 812, 813, 814, 815, 816, 817, 818, 819, 820, 821, 822, 823, 824, 825, 826, 827, 834, 835, 836, 837, 838, 839, 840, 841, 842, 843, 844, 845, 846, 849, 850, 851, 852, 853, 854, 855, 856, 857, 858, 859, 862, 863, 864, 865, 866, 867, 868, 869, 870,
10, 871, 872, 874, 875, 876, 877, 878, 879, 880, 881, 882, 883, 884, 885, 889, 890, 891, 892, 893, 894, 895, 896, 897, 898, 899, 904, 905, 906, 907, 908, 909, 910, 911, 914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924, 925, 926, 927, 928, 929, 930, 931, 932, 933, 934, 935, 936, 937, 938, 939,
12, 940, 941, 942, 943, 944, 945, 946, 947, 948, 949, 950, 951, 952, 953, 954, 955, 956, 957, 958, 959, 960, 961, 962, 963, 964, 965, 966, 967, 968, 969, 970, 971, 972, 973, 974, 975, 976, 977, 978, 979, 980, 981, 982, 983, 984, 985, 986, 987, 988, 1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008,
14, 1009, 1023,
15,
16,
26,
28,
30,
32,
34,
36,
40,
60,
269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279,
285,
288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307,
323, 324, 325, 326, 327, 328, 329, 330, 331, 332,
334, 335, 336, 337, 338, 339, 340, 341, 342, 343,
703,
708,
713, 714, 715, 716, 717, 718, 719, 720, 721, 722, 723, 724, 725, 726, 727, 728,
732, 733, 734, 735, 736, 737, 738, 739, 740,
743,
745, 746,
755, 756,
766,
768,
778, 779,
781, 782, 783, 784, 785, 786, 787, 788, 789, 790, 791, 792, 793, 794, 795, 796, 797, 798, 799,
802, 803, 804, 805, 806, 807, 808, 809,
811, 812, 813, 814, 815, 816, 817, 818, 819, 820, 821, 822, 823, 824, 825, 826, 827,
834, 835, 836, 837, 838, 839, 840, 841, 842, 843, 844, 845, 846,
849, 850, 851, 852, 853, 854, 855, 856, 857, 858, 859,
862, 863, 864, 865, 866, 867, 868, 869, 870, 871, 872,
874, 875, 876, 877, 878, 879, 880, 881, 882, 883, 884, 885,
889, 890, 891, 892, 893, 894, 895, 896, 897, 898, 899,
904, 905, 906, 907, 908, 909, 910, 911,
914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924, 925, 926, 927, 928, 929, 930, 931, 932, 933, 934, 935, 936, 937, 938, 939, 940, 941, 942, 943, 944, 945, 946, 947, 948, 949, 950, 951, 952, 953, 954, 955, 956, 957, 958, 959, 960, 961, 962, 963, 964, 965, 966, 967, 968, 969, 970, 971, 972, 973, 974, 975, 976, 977, 978, 979, 980, 981, 982, 983, 984, 985, 986, 987, 988,
1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009,
1023,
]; ];
#[derive(Serialize, Deserialize, Clone, PartialEq, Eq)] #[derive(Serialize, Deserialize, Clone, PartialEq, Eq)]
#[serde(default)] #[serde(default)]
pub struct LocalConfigPhysicalPathConfig { pub struct LocalConfigPhysicalPathConfig {
pub blacklist: bool pub blacklist: bool,
} }
impl Default for LocalConfigPhysicalPathConfig { impl Default for LocalConfigPhysicalPathConfig {
fn default() -> Self { fn default() -> Self {
LocalConfigPhysicalPathConfig { LocalConfigPhysicalPathConfig { blacklist: false }
blacklist: false
}
} }
} }
@ -76,14 +37,12 @@ impl Default for LocalConfigPhysicalPathConfig {
#[serde(default)] #[serde(default)]
pub struct LocalConfigVirtualConfig { pub struct LocalConfigVirtualConfig {
#[serde(rename = "try")] #[serde(rename = "try")]
pub try_: Vec<InetAddress> pub try_: Vec<InetAddress>,
} }
impl Default for LocalConfigVirtualConfig { impl Default for LocalConfigVirtualConfig {
fn default() -> Self { fn default() -> Self {
LocalConfigVirtualConfig { LocalConfigVirtualConfig { try_: Vec::new() }
try_: Vec::new()
}
} }
} }
@ -109,7 +68,7 @@ impl Default for LocalConfigNetworkSettings {
allow_global_ips: false, allow_global_ips: false,
allow_managed_routes: true, allow_managed_routes: true,
allow_global_routes: false, allow_global_routes: false,
allow_default_route_override: false allow_default_route_override: false,
} }
} }
} }
@ -174,7 +133,7 @@ impl Default for LocalConfigSettings {
port_mapping: true, port_mapping: true,
log: LocalConfigLogSettings::default(), log: LocalConfigLogSettings::default(),
interface_prefix_blacklist: bl, interface_prefix_blacklist: bl,
explicit_addresses: Vec::new() explicit_addresses: Vec::new(),
} }
} }
} }
@ -215,7 +174,7 @@ impl Default for LocalConfig {
physical: BTreeMap::new(), physical: BTreeMap::new(),
virtual_: BTreeMap::new(), virtual_: BTreeMap::new(),
network: BTreeMap::new(), network: BTreeMap::new(),
settings: LocalConfigSettings::default() settings: LocalConfigSettings::default(),
} }
} }
} }

View file

@ -7,7 +7,7 @@
*/ */
use std::fs::{File, OpenOptions}; use std::fs::{File, OpenOptions};
use std::io::{Seek, SeekFrom, stderr, Write}; use std::io::{stderr, Seek, SeekFrom, Write};
use std::sync::Arc; use std::sync::Arc;
use parking_lot::Mutex; use parking_lot::Mutex;

View file

@ -16,19 +16,20 @@ use zerotier_network_hypervisor::{VERSION_MAJOR, VERSION_MINOR, VERSION_REVISION
use crate::store::platform_default_home_path; use crate::store::platform_default_home_path;
mod fastudpsocket; mod fastudpsocket;
mod localconfig;
mod getifaddrs; mod getifaddrs;
mod localconfig;
#[macro_use] #[macro_use]
mod log; mod log;
mod store;
mod vnic;
mod service; mod service;
mod store;
mod utils; mod utils;
mod vnic;
pub const HTTP_API_OBJECT_SIZE_LIMIT: usize = 131072; pub const HTTP_API_OBJECT_SIZE_LIMIT: usize = 131072;
fn make_help(long_help: bool) -> String { fn make_help(long_help: bool) -> String {
format!(r###"ZeroTier Network Hypervisor Service Version {}.{}.{} format!(
r###"ZeroTier Network Hypervisor Service Version {}.{}.{}
(c)2013-2021 ZeroTier, Inc. (c)2013-2021 ZeroTier, Inc.
Licensed under the Mozilla Public License (MPL) 2.0 (see LICENSE.txt) Licensed under the Mozilla Public License (MPL) 2.0 (see LICENSE.txt)
@ -77,7 +78,9 @@ Common Operations:
· join <network> Join a virtual network · join <network> Join a virtual network
· leave <network> Leave a virtual network · leave <network> Leave a virtual network
{}"###, {}"###,
VERSION_MAJOR, VERSION_MINOR, VERSION_REVISION, VERSION_MAJOR,
VERSION_MINOR,
VERSION_REVISION,
if long_help { if long_help {
r###" r###"
Advanced Operations: Advanced Operations:
@ -105,7 +108,10 @@ Advanced Operations:
@ Argument is the path to a file containing the object. @ Argument is the path to a file containing the object.
? Argument can be either the object or a path to it (auto-detected). ? Argument can be either the object or a path to it (auto-detected).
"### "###
} else { "" }) } else {
""
}
)
} }
pub fn print_help(long_help: bool) { pub fn print_help(long_help: bool) {
@ -117,7 +123,7 @@ pub struct GlobalCommandLineFlags {
pub json_output: bool, pub json_output: bool,
pub base_path: String, pub base_path: String,
pub auth_token_path_override: Option<String>, pub auth_token_path_override: Option<String>,
pub auth_token_override: Option<String> pub auth_token_override: Option<String>,
} }
fn main() { fn main() {
@ -131,69 +137,45 @@ fn main() {
.subcommand(App::new("help")) .subcommand(App::new("help"))
.subcommand(App::new("version")) .subcommand(App::new("version"))
.subcommand(App::new("status")) .subcommand(App::new("status"))
.subcommand(App::new("set") .subcommand(
.subcommand(App::new("port") App::new("set")
.arg(Arg::with_name("port#").index(1).validator(utils::is_valid_port))) .subcommand(App::new("port").arg(Arg::with_name("port#").index(1).validator(utils::is_valid_port)))
.subcommand(App::new("secondaryport") .subcommand(App::new("secondaryport").arg(Arg::with_name("port#").index(1).validator(utils::is_valid_port)))
.arg(Arg::with_name("port#").index(1).validator(utils::is_valid_port))) .subcommand(
.subcommand(App::new("blacklist") App::new("blacklist")
.subcommand(App::new("cidr") .subcommand(App::new("cidr").arg(Arg::with_name("ip_bits").index(1)).arg(Arg::with_name("boolean").index(2).validator(utils::is_valid_bool)))
.arg(Arg::with_name("ip_bits").index(1)) .subcommand(App::new("if").arg(Arg::with_name("prefix").index(1)).arg(Arg::with_name("boolean").index(2).validator(utils::is_valid_bool))),
.arg(Arg::with_name("boolean").index(2).validator(utils::is_valid_bool))) )
.subcommand(App::new("if") .subcommand(App::new("portmap").arg(Arg::with_name("boolean").index(1).validator(utils::is_valid_bool))),
.arg(Arg::with_name("prefix").index(1)) )
.arg(Arg::with_name("boolean").index(2).validator(utils::is_valid_bool)))) .subcommand(App::new("peer").subcommand(App::new("show").arg(Arg::with_name("address").index(1).required(true))).subcommand(App::new("list")).subcommand(App::new("listroots")).subcommand(App::new("try")))
.subcommand(App::new("portmap") .subcommand(
.arg(Arg::with_name("boolean").index(1).validator(utils::is_valid_bool)))) App::new("network")
.subcommand(App::new("peer") .subcommand(App::new("show").arg(Arg::with_name("nwid").index(1).required(true)))
.subcommand(App::new("show")
.arg(Arg::with_name("address").index(1).required(true)))
.subcommand(App::new("list")) .subcommand(App::new("list"))
.subcommand(App::new("listroots")) .subcommand(App::new("set").arg(Arg::with_name("nwid").index(1).required(true)).arg(Arg::with_name("setting").index(2).required(false)).arg(Arg::with_name("value").index(3).required(false))),
.subcommand(App::new("try"))) )
.subcommand(App::new("network") .subcommand(App::new("join").arg(Arg::with_name("nwid").index(1).required(true)))
.subcommand(App::new("show") .subcommand(App::new("leave").arg(Arg::with_name("nwid").index(1).required(true)))
.arg(Arg::with_name("nwid").index(1).required(true)))
.subcommand(App::new("list"))
.subcommand(App::new("set")
.arg(Arg::with_name("nwid").index(1).required(true))
.arg(Arg::with_name("setting").index(2).required(false))
.arg(Arg::with_name("value").index(3).required(false))))
.subcommand(App::new("join")
.arg(Arg::with_name("nwid").index(1).required(true)))
.subcommand(App::new("leave")
.arg(Arg::with_name("nwid").index(1).required(true)))
.subcommand(App::new("service")) .subcommand(App::new("service"))
.subcommand(App::new("controller") .subcommand(
App::new("controller")
.subcommand(App::new("list")) .subcommand(App::new("list"))
.subcommand(App::new("new")) .subcommand(App::new("new"))
.subcommand(App::new("set") .subcommand(App::new("set").arg(Arg::with_name("id").index(1).required(true)).arg(Arg::with_name("setting").index(2)).arg(Arg::with_name("value").index(3)))
.arg(Arg::with_name("id").index(1).required(true)) .subcommand(App::new("show").arg(Arg::with_name("id").index(1).required(true)).arg(Arg::with_name("member").index(2)))
.arg(Arg::with_name("setting").index(2)) .subcommand(App::new("auth").arg(Arg::with_name("member").index(1).required(true)))
.arg(Arg::with_name("value").index(3))) .subcommand(App::new("deauth").arg(Arg::with_name("member").index(1).required(true))),
.subcommand(App::new("show") )
.arg(Arg::with_name("id").index(1).required(true)) .subcommand(
.arg(Arg::with_name("member").index(2))) App::new("identity")
.subcommand(App::new("auth") .subcommand(App::new("new").arg(Arg::with_name("type").possible_value("p384").possible_value("c25519").default_value("c25519").index(1)))
.arg(Arg::with_name("member").index(1).required(true))) .subcommand(App::new("getpublic").arg(Arg::with_name("identity").index(1).required(true)))
.subcommand(App::new("deauth") .subcommand(App::new("fingerprint").arg(Arg::with_name("identity").index(1).required(true)))
.arg(Arg::with_name("member").index(1).required(true)))) .subcommand(App::new("validate").arg(Arg::with_name("identity").index(1).required(true)))
.subcommand(App::new("identity") .subcommand(App::new("sign").arg(Arg::with_name("identity").index(1).required(true)).arg(Arg::with_name("path").index(2).required(true)))
.subcommand(App::new("new") .subcommand(App::new("verify").arg(Arg::with_name("identity").index(1).required(true)).arg(Arg::with_name("path").index(2).required(true)).arg(Arg::with_name("signature").index(3).required(true))),
.arg(Arg::with_name("type").possible_value("p384").possible_value("c25519").default_value("c25519").index(1))) )
.subcommand(App::new("getpublic")
.arg(Arg::with_name("identity").index(1).required(true)))
.subcommand(App::new("fingerprint")
.arg(Arg::with_name("identity").index(1).required(true)))
.subcommand(App::new("validate")
.arg(Arg::with_name("identity").index(1).required(true)))
.subcommand(App::new("sign")
.arg(Arg::with_name("identity").index(1).required(true))
.arg(Arg::with_name("path").index(2).required(true)))
.subcommand(App::new("verify")
.arg(Arg::with_name("identity").index(1).required(true))
.arg(Arg::with_name("path").index(2).required(true))
.arg(Arg::with_name("signature").index(3).required(true))))
.help(help.as_str()) .help(help.as_str())
.get_matches_from_safe(std::env::args()); .get_matches_from_safe(std::env::args());
if args.is_err() { if args.is_err() {
@ -215,7 +197,7 @@ fn main() {
json_output: cli_args.is_present("json"), json_output: cli_args.is_present("json"),
base_path: cli_args.value_of("path").map_or_else(|| platform_default_home_path(), |p| p.into_string()), base_path: cli_args.value_of("path").map_or_else(|| platform_default_home_path(), |p| p.into_string()),
auth_token_path_override: cli_args.value_of("token_path").map(|p| p.into_string()), auth_token_path_override: cli_args.value_of("token_path").map(|p| p.into_string()),
auth_token_override: cli_args.value_of("token").map(|t| t.into_string()) auth_token_override: cli_args.value_of("token").map(|t| t.into_string()),
}; };
std::process::exit({ std::process::exit({

View file

@ -7,21 +7,21 @@
*/ */
use std::num::NonZeroI64; use std::num::NonZeroI64;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::Arc;
use parking_lot::Mutex; use parking_lot::Mutex;
use zerotier_network_hypervisor::{Interface, NetworkHypervisor}; use crate::fastudpsocket::{fast_udp_socket_sendto, FastUDPRawOsSocket};
use zerotier_network_hypervisor::vl1::{Endpoint, Identity, IdentityType, Node, VL1SystemInterface}; use zerotier_network_hypervisor::vl1::{Endpoint, Identity, IdentityType, Node, VL1SystemInterface};
use zerotier_network_hypervisor::vl2::SwitchInterface; use zerotier_network_hypervisor::vl2::SwitchInterface;
use crate::fastudpsocket::{fast_udp_socket_sendto, FastUDPRawOsSocket}; use zerotier_network_hypervisor::{Interface, NetworkHypervisor};
use crate::GlobalCommandLineFlags;
use crate::log::Log;
use crate::utils::{ms_monotonic, ms_since_epoch};
use crate::localconfig::LocalConfig; use crate::localconfig::LocalConfig;
use crate::log::Log;
use crate::store::{platform_default_home_path, StateObjectType, Store}; use crate::store::{platform_default_home_path, StateObjectType, Store};
use crate::utils::{ms_monotonic, ms_since_epoch};
use crate::GlobalCommandLineFlags;
struct ServiceInterface { struct ServiceInterface {
pub store: Store, pub store: Store,
@ -59,7 +59,8 @@ impl VL1SystemInterface for ServiceInterface {
fn wire_send(&self, endpoint: &Endpoint, local_socket: Option<NonZeroI64>, local_interface: Option<NonZeroI64>, data: &[&[u8]], packet_ttl: u8) -> bool { fn wire_send(&self, endpoint: &Endpoint, local_socket: Option<NonZeroI64>, local_interface: Option<NonZeroI64>, data: &[&[u8]], packet_ttl: u8) -> bool {
match endpoint { match endpoint {
Endpoint::IpUdp(ip) => { Endpoint::IpUdp(ip) => {
local_socket.map_or_else(|| { local_socket.map_or_else(
|| {
let ptr = self.all_sockets_spin_ptr.fetch_add(1, Ordering::Relaxed); let ptr = self.all_sockets_spin_ptr.fetch_add(1, Ordering::Relaxed);
let all_sockets = self.all_sockets.lock(); let all_sockets = self.all_sockets.lock();
if !all_sockets.is_empty() { if !all_sockets.is_empty() {
@ -70,12 +71,14 @@ impl VL1SystemInterface for ServiceInterface {
} else { } else {
false false
} }
}, |local_socket| { },
|local_socket| {
fast_udp_socket_sendto(&local_socket, ip, data, packet_ttl); fast_udp_socket_sendto(&local_socket, ip, data, packet_ttl);
true true
}) },
)
} }
_ => false _ => false,
} }
} }
@ -90,10 +93,14 @@ impl VL1SystemInterface for ServiceInterface {
} }
#[inline(always)] #[inline(always)]
fn time_ticks(&self) -> i64 { ms_monotonic() } fn time_ticks(&self) -> i64 {
ms_monotonic()
}
#[inline(always)] #[inline(always)]
fn time_clock(&self) -> i64 { ms_since_epoch() } fn time_clock(&self) -> i64 {
ms_since_epoch()
}
} }
impl SwitchInterface for ServiceInterface {} impl SwitchInterface for ServiceInterface {}
@ -102,8 +109,7 @@ impl Interface for ServiceInterface {}
pub fn run(global_cli_flags: &GlobalCommandLineFlags) -> i32 { pub fn run(global_cli_flags: &GlobalCommandLineFlags) -> i32 {
let store = Store::new(global_cli_flags.base_path.as_str(), &global_cli_flags.auth_token_path_override, &global_cli_flags.auth_token_override); let store = Store::new(global_cli_flags.base_path.as_str(), &global_cli_flags.auth_token_path_override, &global_cli_flags.auth_token_override);
if store.is_err() { if store.is_err() {}
}
let si = ServiceInterface { let si = ServiceInterface {
store: store.unwrap(), store: store.unwrap(),

View file

@ -6,13 +6,13 @@
* https://www.zerotier.com/ * https://www.zerotier.com/
*/ */
use std::ffi::CString;
use std::io::{Read, Write}; use std::io::{Read, Write};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::str::FromStr; use std::str::FromStr;
use std::ffi::CString; use std::sync::Mutex;
use zerotier_core::{StateObjectType, NetworkId}; use zerotier_core::{NetworkId, StateObjectType};
use crate::localconfig::LocalConfig; use crate::localconfig::LocalConfig;
@ -27,7 +27,7 @@ pub enum StateObjectType {
IdentityPublic, IdentityPublic,
IdentitySecret, IdentitySecret,
NetworkConfig, NetworkConfig,
Peer Peer,
} }
#[cfg(any(target_os = "macos", target_os = "ios"))] #[cfg(any(target_os = "macos", target_os = "ios"))]
@ -70,16 +70,8 @@ impl Store {
peers_path: bp.join("peers.d").into_boxed_path(), peers_path: bp.join("peers.d").into_boxed_path(),
controller_path: bp.join("controller.d").into_boxed_path(), controller_path: bp.join("controller.d").into_boxed_path(),
networks_path: bp.join("networks.d").into_boxed_path(), networks_path: bp.join("networks.d").into_boxed_path(),
auth_token_path: Mutex::new(auth_token_path_override.map_or_else(|| { auth_token_path: Mutex::new(auth_token_path_override.map_or_else(|| bp.join(AUTHTOKEN_SECRET).into_boxed_path(), |auth_token_path_override| PathBuf::from(auth_token_path_override).into_boxed_path())),
bp.join(AUTHTOKEN_SECRET).into_boxed_path() auth_token: Mutex::new(auth_token_override.map_or_else(|| String::new(), |auth_token_override| auth_token_override)),
}, |auth_token_path_override| {
PathBuf::from(auth_token_path_override).into_boxed_path()
})),
auth_token: Mutex::new(auth_token_override.map_or_else(|| {
String::new()
}, |auth_token_override| {
auth_token_override
})),
}; };
let _ = std::fs::create_dir_all(&s.peers_path); let _ = std::fs::create_dir_all(&s.peers_path);
@ -99,7 +91,7 @@ impl Store {
} else { } else {
Some(self.networks_path.join(format!("{:0>16x}.conf", obj_id[0]))) Some(self.networks_path.join(format!("{:0>16x}.conf", obj_id[0])))
} }
}, }
StateObjectType::Peer => { StateObjectType::Peer => {
if obj_id.len() < 1 { if obj_id.len() < 1 {
None None
@ -132,7 +124,7 @@ impl Store {
let p = self.auth_token_path.lock().unwrap(); let p = self.auth_token_path.lock().unwrap();
let ps = p.to_str().unwrap(); let ps = p.to_str().unwrap();
let token2 = self.read_file(ps).map_or(String::new(), |sb| { String::from_utf8(sb).unwrap_or(String::new()).trim().to_string() }); let token2 = self.read_file(ps).map_or(String::new(), |sb| String::from_utf8(sb).unwrap_or(String::new()).trim().to_string());
if token2.is_empty() { if token2.is_empty() {
if generate_if_missing { if generate_if_missing {
let mut rb = [0_u8; 32]; let mut rb = [0_u8; 32];
@ -173,7 +165,8 @@ impl Store {
if de.is_ok() { if de.is_ok() {
let nn = de.unwrap().file_name(); let nn = de.unwrap().file_name();
let n = nn.to_str().unwrap_or(""); let n = nn.to_str().unwrap_or("");
if n.len() == 21 && n.ends_with(".conf") { // ################.conf if n.len() == 21 && n.ends_with(".conf") {
// ################.conf
let nwid = u64::from_str_radix(&n[0..16], 16); let nwid = u64::from_str_radix(&n[0..16], 16);
if nwid.is_ok() { if nwid.is_ok() {
list.push(NetworkId(nwid.unwrap())); list.push(NetworkId(nwid.unwrap()));

View file

@ -15,8 +15,8 @@ use std::str::FromStr;
use serde::de::DeserializeOwned; use serde::de::DeserializeOwned;
use serde::Serialize; use serde::Serialize;
use zerotier_network_hypervisor::vl1::Identity;
use zerotier_core_crypto::hex; use zerotier_core_crypto::hex;
use zerotier_network_hypervisor::vl1::Identity;
use crate::osdep; use crate::osdep;
@ -30,7 +30,8 @@ pub fn ms_monotonic() -> i64 {
let mut tb: mach::mach_time::mach_timebase_info_data_t = std::mem::zeroed(); let mut tb: mach::mach_time::mach_timebase_info_data_t = std::mem::zeroed();
if mach::mach_time::mach_timebase_info(&mut tb) == 0 { if mach::mach_time::mach_timebase_info(&mut tb) == 0 {
let mt = mach::mach_time::mach_continuous_approximate_time(); // ZT doesn't need it to be *that* exact, and this is faster let mt = mach::mach_time::mach_continuous_approximate_time(); // ZT doesn't need it to be *that* exact, and this is faster
(((mt as u128) * tb.numer as u128 * 1000000_u128) / (tb.denom as u128)) as i64 // milliseconds since X (((mt as u128) * tb.numer as u128 * 1000000_u128) / (tb.denom as u128)) as i64
// milliseconds since X
} else { } else {
panic!("FATAL: mach_timebase_info() failed"); panic!("FATAL: mach_timebase_info() failed");
} }
@ -38,21 +39,26 @@ pub fn ms_monotonic() -> i64 {
} }
#[cfg(not(any(target_os = "macos", target_os = "ios")))] #[cfg(not(any(target_os = "macos", target_os = "ios")))]
pub fn ms_monotonic() -> i64 { pub fn ms_monotonic() -> i64 {}
}
pub fn parse_bool(v: &str) -> Result<bool, String> { pub fn parse_bool(v: &str) -> Result<bool, String> {
if !v.is_empty() { if !v.is_empty() {
match v.chars().next().unwrap() { match v.chars().next().unwrap() {
'y' | 'Y' | '1' | 't' | 'T' => { return Ok(true); } 'y' | 'Y' | '1' | 't' | 'T' => {
'n' | 'N' | '0' | 'f' | 'F' => { return Ok(false); } return Ok(true);
}
'n' | 'N' | '0' | 'f' | 'F' => {
return Ok(false);
}
_ => {} _ => {}
} }
} }
Err(format!("invalid boolean value: '{}'", v)) Err(format!("invalid boolean value: '{}'", v))
} }
pub fn is_valid_bool(v: String) -> Result<(), String> { parse_bool(v.as_str()).map(|_| ()) } pub fn is_valid_bool(v: String) -> Result<(), String> {
parse_bool(v.as_str()).map(|_| ())
}
pub fn is_valid_port(v: String) -> Result<(), String> { pub fn is_valid_port(v: String) -> Result<(), String> {
let i = u16::from_str(v.as_str()).unwrap_or(0); let i = u16::from_str(v.as_str()).unwrap_or(0);
@ -73,26 +79,19 @@ pub fn read_limit<P: AsRef<Path>>(path: P, limit: usize) -> std::io::Result<Vec<
/// Read an identity as either a literal or from a file. /// Read an identity as either a literal or from a file.
pub fn parse_cli_identity(input: &str, validate: bool) -> Result<Identity, String> { pub fn parse_cli_identity(input: &str, validate: bool) -> Result<Identity, String> {
let parse_func = |s: &str| { let parse_func = |s: &str| {
Identity::new_from_string(s).map_or_else(|e| { Identity::new_from_string(s).map_or_else(
Err(format!("invalid identity: {}", e.to_str())) |e| Err(format!("invalid identity: {}", e.to_str())),
}, |id| { |id| {
if !validate || id.validate() { if !validate || id.validate() {
Ok(id) Ok(id)
} else { } else {
Err(String::from("invalid identity: local validation failed")) Err(String::from("invalid identity: local validation failed"))
} }
}) },
)
}; };
if Path::new(input).exists() { if Path::new(input).exists() {
read_limit(input, 16384).map_or_else(|e| { read_limit(input, 16384).map_or_else(|e| Err(e.to_string()), |v| String::from_utf8(v).map_or_else(|e| Err(e.to_string()), |s| parse_func(s.as_str())))
Err(e.to_string())
}, |v| {
String::from_utf8(v).map_or_else(|e| {
Err(e.to_string())
}, |s| {
parse_func(s.as_str())
})
})
} else { } else {
parse_func(input) parse_func(input)
} }
@ -172,24 +171,33 @@ pub fn json_patch(target: &mut serde_json::value::Value, source: &serde_json::va
/// If there are no changes, None is returned. The depth limit is passed through to json_patch and /// If there are no changes, None is returned. The depth limit is passed through to json_patch and
/// should be set to a sanity check value to prevent overflows. /// should be set to a sanity check value to prevent overflows.
pub fn json_patch_object<O: Serialize + DeserializeOwned + Eq>(obj: O, patch: &str, depth_limit: usize) -> Result<Option<O>, serde_json::Error> { pub fn json_patch_object<O: Serialize + DeserializeOwned + Eq>(obj: O, patch: &str, depth_limit: usize) -> Result<Option<O>, serde_json::Error> {
serde_json::from_str::<serde_json::value::Value>(patch).map_or_else(|e| Err(e), |patch| { serde_json::from_str::<serde_json::value::Value>(patch).map_or_else(
serde_json::value::to_value(obj.borrow()).map_or_else(|e| Err(e), |mut obj_value| { |e| Err(e),
|patch| {
serde_json::value::to_value(obj.borrow()).map_or_else(
|e| Err(e),
|mut obj_value| {
json_patch(&mut obj_value, &patch, depth_limit); json_patch(&mut obj_value, &patch, depth_limit);
serde_json::value::from_value::<O>(obj_value).map_or_else(|e| Err(e), |obj_merged| { serde_json::value::from_value::<O>(obj_value).map_or_else(
|e| Err(e),
|obj_merged| {
if obj == obj_merged { if obj == obj_merged {
Ok(None) Ok(None)
} else { } else {
Ok(Some(obj_merged)) Ok(Some(obj_merged))
} }
}) },
}) )
}) },
)
},
)
} }
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use std::time::Duration;
use crate::utils::ms_monotonic; use crate::utils::ms_monotonic;
use std::time::Duration;
#[test] #[test]
fn monotonic_clock_sanity_check() { fn monotonic_clock_sanity_check() {

View file

@ -57,7 +57,7 @@ const SYSCTL: &'static str = "/usr/sbin/sysctl";
// Holds names of feth devices and destroys them on Drop. // Holds names of feth devices and destroys them on Drop.
struct MacFethDevice { struct MacFethDevice {
pub name: String, pub name: String,
pub peer_name: String pub peer_name: String,
} }
impl Drop for MacFethDevice { impl Drop for MacFethDevice {
@ -268,7 +268,7 @@ union u_ifr_ifru {
ifru_lifetime: in6_addrlifetime, ifru_lifetime: in6_addrlifetime,
ifru_stat: in6_ifstat, ifru_stat: in6_ifstat,
ifru_icmp6stat: icmp6_ifstat, ifru_icmp6stat: icmp6_ifstat,
ifru_scope_id: [u32; 16 /* SCOPE6_ID_MAX */], ifru_scope_id: [u32; 16],
} }
#[allow(non_camel_case_types)] #[allow(non_camel_case_types)]
@ -328,7 +328,16 @@ fn device_ipv6_set_params(device: &String, perform_nud: bool, accept_ra: bool) -
let mut ifr: in6_ifreq = zeroed(); let mut ifr: in6_ifreq = zeroed();
copy_nonoverlapping(dev.as_ptr(), ifr.ifr_name.as_mut_ptr().cast::<u8>(), if dev.len() > (ifr.ifr_name.len() - 1) { ifr.ifr_name.len() - 1 } else { dev.len() }); copy_nonoverlapping(dev.as_ptr(), ifr.ifr_name.as_mut_ptr().cast::<u8>(), if dev.len() > (ifr.ifr_name.len() - 1) { ifr.ifr_name.len() - 1 } else { dev.len() });
if libc::ioctl(s, if accept_ra { 132 /* SIOCAUTOCONF_START */ } else { 133 /* SIOCAUTOCONF_STOP */ }, (&mut ifr as *mut in6_ifreq).cast::<c_void>()) != 0 { if libc::ioctl(
s,
if accept_ra {
132 /* SIOCAUTOCONF_START */
} else {
133 /* SIOCAUTOCONF_STOP */
},
(&mut ifr as *mut in6_ifreq).cast::<c_void>(),
) != 0
{
ok = false; ok = false;
} }
@ -510,7 +519,9 @@ impl MacFethTap {
// Set sysctl for max if_fake MTU. This is allowed to fail since this sysctl doesn't // Set sysctl for max if_fake MTU. This is allowed to fail since this sysctl doesn't
// exist on older versions of MacOS (and isn't required there). 16000 is larger than // exist on older versions of MacOS (and isn't required there). 16000 is larger than
// anything ZeroTier supports. OS max is 16384 - some overhead. // anything ZeroTier supports. OS max is 16384 - some overhead.
let _ = Command::new(SYSCTL).arg("net.link.fake.max_mtu").arg("10000").spawn().map(|mut c| { let _ = c.wait(); }); let _ = Command::new(SYSCTL).arg("net.link.fake.max_mtu").arg("10000").spawn().map(|mut c| {
let _ = c.wait();
});
// Create pair of feth interfaces and create MacFethDevice struct. // Create pair of feth interfaces and create MacFethDevice struct.
let cmd = Command::new(IFCONFIG).arg(&device_name).arg("create").spawn(); let cmd = Command::new(IFCONFIG).arg(&device_name).arg("create").spawn();
@ -523,10 +534,7 @@ impl MacFethTap {
return Err(format!("unable to create device '{}': {}", peer_device_name.as_str(), cmd.err().unwrap().to_string())); return Err(format!("unable to create device '{}': {}", peer_device_name.as_str(), cmd.err().unwrap().to_string()));
} }
let _ = cmd.unwrap().wait(); let _ = cmd.unwrap().wait();
let device = MacFethDevice { let device = MacFethDevice { name: device_name, peer_name: peer_device_name };
name: device_name,
peer_name: peer_device_name,
};
// Set link-layer (MAC) address of primary interface. // Set link-layer (MAC) address of primary interface.
let cmd = Command::new(IFCONFIG).arg(&device.name).arg("lladdr").arg(mac.to_string()).spawn(); let cmd = Command::new(IFCONFIG).arg(&device.name).arg("lladdr").arg(mac.to_string()).spawn();
@ -584,46 +592,78 @@ impl MacFethTap {
// Set/get buffer length to use with reads from BPF device, trying to // Set/get buffer length to use with reads from BPF device, trying to
// use up to BPF_BUFFER_SIZE bytes. // use up to BPF_BUFFER_SIZE bytes.
let mut fl: c_int = BPF_BUFFER_SIZE as c_int; let mut fl: c_int = BPF_BUFFER_SIZE as c_int;
if unsafe { libc::ioctl(bpf_fd as c_int, 102 /* BIOCSBLEN */, (&mut fl as *mut c_int).cast::<c_void>()) } != 0 { if unsafe {
unsafe { libc::close(bpf_fd); } libc::ioctl(bpf_fd as c_int, 102 /* BIOCSBLEN */, (&mut fl as *mut c_int).cast::<c_void>())
} != 0
{
unsafe {
libc::close(bpf_fd);
}
return Err(String::from("unable to configure BPF device")); return Err(String::from("unable to configure BPF device"));
} }
let bpf_read_size = fl as libc::size_t; let bpf_read_size = fl as libc::size_t;
// Set immediate mode for "live" capture. // Set immediate mode for "live" capture.
fl = 1; fl = 1;
if unsafe { libc::ioctl(bpf_fd as c_int, 112 /* BIOCIMMEDIATE */, (&mut fl as *mut c_int).cast::<c_void>()) } != 0 { if unsafe {
unsafe { libc::close(bpf_fd); } libc::ioctl(bpf_fd as c_int, 112 /* BIOCIMMEDIATE */, (&mut fl as *mut c_int).cast::<c_void>())
} != 0
{
unsafe {
libc::close(bpf_fd);
}
return Err(String::from("unable to configure BPF device")); return Err(String::from("unable to configure BPF device"));
} }
// Do not send us back packets we inject or send. // Do not send us back packets we inject or send.
fl = 0; fl = 0;
if unsafe { libc::ioctl(bpf_fd as c_int, 119 /* BIOCSSEESENT */, (&mut fl as *mut c_int).cast::<c_void>()) } != 0 { if unsafe {
unsafe { libc::close(bpf_fd); } libc::ioctl(bpf_fd as c_int, 119 /* BIOCSSEESENT */, (&mut fl as *mut c_int).cast::<c_void>())
} != 0
{
unsafe {
libc::close(bpf_fd);
}
return Err(String::from("unable to configure BPF device")); return Err(String::from("unable to configure BPF device"));
} }
// Bind BPF to secondary feth device. // Bind BPF to secondary feth device.
let mut bpf_ifr: ifreq = unsafe { std::mem::zeroed() }; let mut bpf_ifr: ifreq = unsafe { std::mem::zeroed() };
let peer_dev_name_bytes = device.peer_name.as_bytes(); let peer_dev_name_bytes = device.peer_name.as_bytes();
unsafe { copy_nonoverlapping(peer_dev_name_bytes.as_ptr(), bpf_ifr.ifr_name.as_mut_ptr().cast::<u8>(), if peer_dev_name_bytes.len() > (bpf_ifr.ifr_name.len() - 1) { bpf_ifr.ifr_name.len() - 1 } else { peer_dev_name_bytes.len() }); } unsafe {
if unsafe { libc::ioctl(bpf_fd as c_int, 108 /* BIOCSETIF */, (&mut bpf_ifr as *mut ifreq).cast::<c_void>()) } != 0 { copy_nonoverlapping(peer_dev_name_bytes.as_ptr(), bpf_ifr.ifr_name.as_mut_ptr().cast::<u8>(), if peer_dev_name_bytes.len() > (bpf_ifr.ifr_name.len() - 1) { bpf_ifr.ifr_name.len() - 1 } else { peer_dev_name_bytes.len() });
unsafe { libc::close(bpf_fd); } }
if unsafe {
libc::ioctl(bpf_fd as c_int, 108 /* BIOCSETIF */, (&mut bpf_ifr as *mut ifreq).cast::<c_void>())
} != 0
{
unsafe {
libc::close(bpf_fd);
}
return Err(String::from("unable to configure BPF device")); return Err(String::from("unable to configure BPF device"));
} }
// Include Ethernet header in BPF captures. // Include Ethernet header in BPF captures.
fl = 1; fl = 1;
if unsafe { libc::ioctl(bpf_fd as c_int, 117 /* BIOCSHDRCMPLT */, (&mut fl as *mut c_int).cast::<c_void>()) } != 0 { if unsafe {
unsafe { libc::close(bpf_fd); } libc::ioctl(bpf_fd as c_int, 117 /* BIOCSHDRCMPLT */, (&mut fl as *mut c_int).cast::<c_void>())
} != 0
{
unsafe {
libc::close(bpf_fd);
}
return Err(String::from("unable to configure BPF device")); return Err(String::from("unable to configure BPF device"));
} }
// Set promiscuous mode so bridging can work. // Set promiscuous mode so bridging can work.
fl = 1; fl = 1;
if unsafe { libc::ioctl(bpf_fd as c_int, 105 /* BIOCPROMISC */, (&mut fl as *mut c_int).cast::<c_void>()) } != 0 { if unsafe {
unsafe { libc::close(bpf_fd); } libc::ioctl(bpf_fd as c_int, 105 /* BIOCPROMISC */, (&mut fl as *mut c_int).cast::<c_void>())
} != 0
{
unsafe {
libc::close(bpf_fd);
}
return Err(String::from("unable to configure BPF device")); return Err(String::from("unable to configure BPF device"));
} }
@ -653,30 +693,46 @@ impl MacFethTap {
} }
}); });
if t.is_err() { if t.is_err() {
unsafe { libc::close(bpf_fd); } unsafe {
libc::close(bpf_fd);
}
return Err(String::from("unable to start thread")); return Err(String::from("unable to start thread"));
} }
// Create AF_NDRV socket used to inject packets. We could inject with BPF but that has // Create AF_NDRV socket used to inject packets. We could inject with BPF but that has
// a hard MTU limit of 2048 so we have to use AF_NDRV instead. Performance is probably // a hard MTU limit of 2048 so we have to use AF_NDRV instead. Performance is probably
// the same, but it means another socket. // the same, but it means another socket.
let ndrv_fd = unsafe { libc::socket(27 /* AF_NDRV */, libc::SOCK_RAW, 0) }; let ndrv_fd = unsafe {
libc::socket(27 /* AF_NDRV */, libc::SOCK_RAW, 0)
};
if ndrv_fd < 0 { if ndrv_fd < 0 {
unsafe { libc::close(bpf_fd); } unsafe {
libc::close(bpf_fd);
}
return Err(String::from("unable to create AF_NDRV socket")); return Err(String::from("unable to create AF_NDRV socket"));
} }
let mut ndrv_sa: sockaddr_ndrv = unsafe { std::mem::zeroed() }; let mut ndrv_sa: sockaddr_ndrv = unsafe { std::mem::zeroed() };
ndrv_sa.snd_len = std::mem::size_of::<sockaddr_ndrv>() as c_uchar; ndrv_sa.snd_len = std::mem::size_of::<sockaddr_ndrv>() as c_uchar;
ndrv_sa.snd_family = 27 /* AF_NDRV */; ndrv_sa.snd_family = 27 /* AF_NDRV */;
unsafe { copy_nonoverlapping(peer_dev_name_bytes.as_ptr(), ndrv_sa.snd_name.as_mut_ptr().cast::<u8>(), if peer_dev_name_bytes.len() > (bpf_ifr.ifr_name.len() - 1) { bpf_ifr.ifr_name.len() - 1 } else { peer_dev_name_bytes.len() }); } unsafe {
copy_nonoverlapping(peer_dev_name_bytes.as_ptr(), ndrv_sa.snd_name.as_mut_ptr().cast::<u8>(), if peer_dev_name_bytes.len() > (bpf_ifr.ifr_name.len() - 1) { bpf_ifr.ifr_name.len() - 1 } else { peer_dev_name_bytes.len() });
}
if unsafe { libc::bind(ndrv_fd, (&ndrv_sa as *const sockaddr_ndrv).cast(), std::mem::size_of::<sockaddr_ndrv>() as libc::socklen_t) } != 0 { if unsafe { libc::bind(ndrv_fd, (&ndrv_sa as *const sockaddr_ndrv).cast(), std::mem::size_of::<sockaddr_ndrv>() as libc::socklen_t) } != 0 {
unsafe { libc::close(bpf_fd); } unsafe {
unsafe { libc::close(ndrv_fd); } libc::close(bpf_fd);
}
unsafe {
libc::close(ndrv_fd);
}
return Err(String::from("unable to bind AF_NDRV socket")); return Err(String::from("unable to bind AF_NDRV socket"));
} }
if unsafe { libc::connect(ndrv_fd, (&ndrv_sa as *const sockaddr_ndrv).cast(), std::mem::size_of::<sockaddr_ndrv>() as libc::socklen_t) } != 0 { if unsafe { libc::connect(ndrv_fd, (&ndrv_sa as *const sockaddr_ndrv).cast(), std::mem::size_of::<sockaddr_ndrv>() as libc::socklen_t) } != 0 {
unsafe { libc::close(bpf_fd); } unsafe {
unsafe { libc::close(ndrv_fd); } libc::close(bpf_fd);
}
unsafe {
libc::close(ndrv_fd);
}
return Err(String::from("unable to connect AF_NDRV socket")); return Err(String::from("unable to connect AF_NDRV socket"));
} }
@ -688,7 +744,7 @@ impl MacFethTap {
ndrv_fd, ndrv_fd,
bpf_fd, bpf_fd,
bpf_no, bpf_no,
bpf_read_thread: Cell::new(Some(t.unwrap())) bpf_read_thread: Cell::new(Some(t.unwrap())),
}) })
} }
@ -758,10 +814,7 @@ impl VNIC for MacFethTap {
let mut hdr: [u8; 14] = [(dm >> 40) as u8, (dm >> 32) as u8, (dm >> 24) as u8, (dm >> 16) as u8, (dm >> 8) as u8, dm as u8, (sm >> 40) as u8, (sm >> 32) as u8, (sm >> 24) as u8, (sm >> 16) as u8, (sm >> 8) as u8, sm as u8, (ethertype >> 8) as u8, ethertype as u8]; let mut hdr: [u8; 14] = [(dm >> 40) as u8, (dm >> 32) as u8, (dm >> 24) as u8, (dm >> 16) as u8, (dm >> 8) as u8, dm as u8, (sm >> 40) as u8, (sm >> 32) as u8, (sm >> 24) as u8, (sm >> 16) as u8, (sm >> 8) as u8, sm as u8, (ethertype >> 8) as u8, ethertype as u8];
unsafe { unsafe {
let iov: [libc::iovec; 2] = [ let iov: [libc::iovec; 2] = [
libc::iovec { libc::iovec { iov_base: hdr.as_mut_ptr().cast(), iov_len: 14 },
iov_base: hdr.as_mut_ptr().cast(),
iov_len: 14,
},
libc::iovec { libc::iovec {
iov_base: transmute(data), // have to "cast away const" even though data is not modified by writev() iov_base: transmute(data), // have to "cast away const" even though data is not modified by writev()
iov_len: len as libc::size_t, iov_len: len as libc::size_t,

View file

@ -6,8 +6,8 @@
* https://www.zerotier.com/ * https://www.zerotier.com/
*/ */
mod vnic;
mod common; mod common;
mod vnic;
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
mod mac_feth_tap; mod mac_feth_tap;