Format tweak.

This commit is contained in:
Adam Ierymenko 2023-03-03 09:49:25 -05:00
parent bbeff32bce
commit 781b5eb270
25 changed files with 129 additions and 373 deletions

View file

@ -67,9 +67,7 @@ impl Controller {
recently_authorized: RwLock::new(HashMap::new()), recently_authorized: RwLock::new(HashMap::new()),
})) }))
} else { } else {
Err(Box::new(InvalidParameterError( Err(Box::new(InvalidParameterError("local controller's identity not readable by database")))
"local controller's identity not readable by database",
)))
} }
} }
@ -238,8 +236,7 @@ impl Controller {
if member.node_id != *m { if member.node_id != *m {
if let Some(peer) = self.service.read().unwrap().upgrade().and_then(|s| s.node().peer(*m)) { if let Some(peer) = self.service.read().unwrap().upgrade().and_then(|s| s.node().peer(*m)) {
revocations.clear(); revocations.clear();
Revocation::new(member.network_id, time_clock, member.node_id, *m, &self.local_identity, false) Revocation::new(member.network_id, time_clock, member.node_id, *m, &self.local_identity, false).map(|r| revocations.push(r));
.map(|r| revocations.push(r));
self.send_revocations(&peer, &mut revocations); self.send_revocations(&peer, &mut revocations);
} }
} }
@ -565,8 +562,7 @@ impl InnerProtocolLayer for Controller {
}; };
// Launch handler as an async background task. // Launch handler as an async background task.
let (self2, source, source_remote_endpoint) = let (self2, source, source_remote_endpoint) = (self.self_ref.upgrade().unwrap(), source.clone(), source_path.endpoint.clone());
(self.self_ref.upgrade().unwrap(), source.clone(), source_path.endpoint.clone());
self.reaper.add( self.reaper.add(
self.runtime.spawn(async move { self.runtime.spawn(async move {
let node_id = source.identity.address; let node_id = source.identity.address;

View file

@ -50,8 +50,8 @@ impl FileDatabase {
let db_weak = db_weak_tmp.clone(); let db_weak = db_weak_tmp.clone();
let runtime2 = runtime.clone(); let runtime2 = runtime.clone();
let local_identity = load_node_identity(base_path.as_path()) let local_identity =
.ok_or(std::io::Error::new(std::io::ErrorKind::NotFound, "identity.secret not found"))?; load_node_identity(base_path.as_path()).ok_or(std::io::Error::new(std::io::ErrorKind::NotFound, "identity.secret not found"))?;
let controller_address = local_identity.address; let controller_address = local_identity.address;
let db = Arc::new(Self { let db = Arc::new(Self {
@ -144,8 +144,7 @@ impl FileDatabase {
.send(Change::NetworkChanged(old_network, new_network)); .send(Change::NetworkChanged(old_network, new_network));
} }
(true, None) => { (true, None) => {
let _ = let _ = db.change_sender.send(Change::NetworkCreated(new_network));
db.change_sender.send(Change::NetworkCreated(new_network));
} }
_ => {} _ => {}
} }
@ -155,13 +154,11 @@ impl FileDatabase {
if let Ok(Some(new_member)) = Self::load_object::<Member>(changed).await { if let Ok(Some(new_member)) = Self::load_object::<Member>(changed).await {
match db.cache.on_member_updated(new_member.clone()) { match db.cache.on_member_updated(new_member.clone()) {
(true, Some(old_member)) => { (true, Some(old_member)) => {
let _ = db let _ =
.change_sender db.change_sender.send(Change::MemberChanged(old_member, new_member));
.send(Change::MemberChanged(old_member, new_member));
} }
(true, None) => { (true, None) => {
let _ = let _ = db.change_sender.send(Change::MemberCreated(new_member));
db.change_sender.send(Change::MemberCreated(new_member));
} }
_ => {} _ => {}
} }
@ -315,9 +312,7 @@ impl Database for FileDatabase {
if ent.file_type().await.map_or(false, |t| t.is_file() || t.is_symlink()) { if ent.file_type().await.map_or(false, |t| t.is_file() || t.is_symlink()) {
let osname = ent.file_name(); let osname = ent.file_name();
let name = osname.to_string_lossy(); let name = osname.to_string_lossy();
if name.len() == (zerotier_network_hypervisor::protocol::ADDRESS_SIZE_STRING + 6) if name.len() == (zerotier_network_hypervisor::protocol::ADDRESS_SIZE_STRING + 6) && name.starts_with("M") && name.ends_with(".yaml")
&& name.starts_with("M")
&& name.ends_with(".yaml")
{ {
if let Ok(member_address) = u64::from_str_radix(&name[1..11], 16) { if let Ok(member_address) = u64::from_str_radix(&name[1..11], 16) {
if let Some(member_address) = Address::from_u64(member_address) { if let Some(member_address) = Address::from_u64(member_address) {

View file

@ -88,18 +88,13 @@ impl PostgresConnection {
let (client, connection) = tokio_postgres::connect(postgres_path, tokio_postgres::NoTls).await?; let (client, connection) = tokio_postgres::connect(postgres_path, tokio_postgres::NoTls).await?;
Ok(Box::new(Self { Ok(Box::new(Self {
s_list_networks: client s_list_networks: client
.prepare_typed( .prepare_typed("SELECT id FROM ztc_network WHERE controller_id = $1 AND deleted = false", &[Type::TEXT])
"SELECT id FROM ztc_network WHERE controller_id = $1 AND deleted = false",
&[Type::TEXT],
)
.await?, .await?,
s_list_members: client s_list_members: client
.prepare_typed("SELECT id FROM ztc_member WHERE network_id = $1 AND deleted = false", &[Type::TEXT]) .prepare_typed("SELECT id FROM ztc_member WHERE network_id = $1 AND deleted = false", &[Type::TEXT])
.await?, .await?,
s_get_network: client.prepare_typed(GET_NETWORK_SQL, &[Type::TEXT]).await?, s_get_network: client.prepare_typed(GET_NETWORK_SQL, &[Type::TEXT]).await?,
s_get_network_members_with_capabilities: client s_get_network_members_with_capabilities: client.prepare_typed(GET_NETWORK_MEMBERS_WITH_CAPABILITIES_SQL, &[Type::TEXT]).await?,
.prepare_typed(GET_NETWORK_MEMBERS_WITH_CAPABILITIES_SQL, &[Type::TEXT])
.await?,
client, client,
connection_task: runtime.spawn(async move { connection_task: runtime.spawn(async move {
if let Err(e) = connection.await { if let Err(e) = connection.await {
@ -144,12 +139,7 @@ pub struct PostgresDatabase {
} }
impl PostgresDatabase { impl PostgresDatabase {
pub async fn new( pub async fn new(runtime: Handle, postgres_path: String, num_connections: usize, local_identity: Valid<Identity>) -> Result<Arc<Self>, Error> {
runtime: Handle,
postgres_path: String,
num_connections: usize,
local_identity: Valid<Identity>,
) -> Result<Arc<Self>, Error> {
assert!(num_connections > 0); assert!(num_connections > 0);
let (sender, _) = channel(4096); let (sender, _) = channel(4096);
let mut connections = Vec::with_capacity(num_connections); let mut connections = Vec::with_capacity(num_connections);
@ -217,11 +207,7 @@ impl Database for PostgresDatabase {
let c = self.get_connection().await?; let c = self.get_connection().await?;
let network_id_string = id.to_string(); let network_id_string = id.to_string();
if let Some(r) = c.client.query_opt(&c.s_get_network, &[&network_id_string]).await? { if let Some(r) = c.client.query_opt(&c.s_get_network, &[&network_id_string]).await? {
if let Ok(with_caps) = c if let Ok(with_caps) = c.client.query(&c.s_get_network_members_with_capabilities, &[&network_id_string]).await {
.client
.query(&c.s_get_network_members_with_capabilities, &[&network_id_string])
.await
{
(r, with_caps) (r, with_caps)
} else { } else {
(r, Vec::new()) (r, Vec::new())
@ -341,10 +327,7 @@ impl Database for PostgresDatabase {
if let Ok(member_id) = Address::from_str(wc.get(0)) { if let Ok(member_id) = Address::from_str(wc.get(0)) {
if let Ok(cap_ids) = serde_json::from_str::<Vec<u32>>(wc.get(1)) { if let Ok(cap_ids) = serde_json::from_str::<Vec<u32>>(wc.get(1)) {
for cap_id in cap_ids.iter() { for cap_id in cap_ids.iter() {
members_by_cap members_by_cap.entry(*cap_id).or_insert_with(|| Vec::with_capacity(4)).push(member_id);
.entry(*cap_id)
.or_insert_with(|| Vec::with_capacity(4))
.push(member_id);
} }
} }
} }

View file

@ -31,9 +31,7 @@ pub fn criterion_benchmark(c: &mut Criterion) {
group.measurement_time(Duration::new(10, 0)); group.measurement_time(Duration::new(10, 0));
group.bench_function("ecdhp384", |b| { group.bench_function("ecdhp384", |b| b.iter(|| p384_a.agree(p384_b.public_key()).expect("ecdhp384 failed")));
b.iter(|| p384_a.agree(p384_b.public_key()).expect("ecdhp384 failed"))
});
group.bench_function("ecdhx25519", |b| b.iter(|| x25519_a.agree(&x25519_b_pub))); group.bench_function("ecdhx25519", |b| b.iter(|| x25519_a.agree(&x25519_b_pub)));
group.finish(); group.finish();

View file

@ -135,14 +135,7 @@ mod fruit_flavored {
assert_eq!(data.len(), 16); assert_eq!(data.len(), 16);
unsafe { unsafe {
let mut data_out_written = 0; let mut data_out_written = 0;
CCCryptorUpdate( CCCryptorUpdate(self.0, data.as_ptr().cast(), 16, data.as_mut_ptr().cast(), 16, &mut data_out_written);
self.0,
data.as_ptr().cast(),
16,
data.as_mut_ptr().cast(),
16,
&mut data_out_written,
);
} }
} }
@ -168,14 +161,7 @@ mod fruit_flavored {
assert_eq!(data.len(), 16); assert_eq!(data.len(), 16);
unsafe { unsafe {
let mut data_out_written = 0; let mut data_out_written = 0;
CCCryptorUpdate( CCCryptorUpdate(self.1, data.as_ptr().cast(), 16, data.as_mut_ptr().cast(), 16, &mut data_out_written);
self.1,
data.as_ptr().cast(),
16,
data.as_mut_ptr().cast(),
16,
&mut data_out_written,
);
} }
} }
} }
@ -357,15 +343,9 @@ mod fruit_flavored {
pub fn crypt_in_place(&mut self, data: &mut [u8]) { pub fn crypt_in_place(&mut self, data: &mut [u8]) {
unsafe { unsafe {
if self.1 { if self.1 {
assert_eq!( assert_eq!(CCCryptorGCMEncrypt(self.0, data.as_ptr().cast(), data.len(), data.as_mut_ptr().cast()), 0);
CCCryptorGCMEncrypt(self.0, data.as_ptr().cast(), data.len(), data.as_mut_ptr().cast()),
0
);
} else { } else {
assert_eq!( assert_eq!(CCCryptorGCMDecrypt(self.0, data.as_ptr().cast(), data.len(), data.as_mut_ptr().cast()), 0);
CCCryptorGCMDecrypt(self.0, data.as_ptr().cast(), data.len(), data.as_mut_ptr().cast()),
0
);
} }
} }
} }

View file

@ -178,15 +178,9 @@ impl AesGmacSiv {
self.tmp.copy_from_slice(&tag_tmp[0..16]); self.tmp.copy_from_slice(&tag_tmp[0..16]);
self.tmp[12] &= 0x7f; self.tmp[12] &= 0x7f;
let _ = self.ctr.replace( let _ = self
Crypter::new( .ctr
aes_ctr_by_key_size(self.k1.len()), .replace(Crypter::new(aes_ctr_by_key_size(self.k1.len()), Mode::Encrypt, self.k1.as_slice(), Some(&self.tmp)).unwrap());
Mode::Encrypt,
self.k1.as_slice(),
Some(&self.tmp),
)
.unwrap(),
);
} }
/// Feed plaintext for second pass and write ciphertext to supplied buffer. /// Feed plaintext for second pass and write ciphertext to supplied buffer.
@ -219,15 +213,9 @@ impl AesGmacSiv {
pub fn decrypt_init(&mut self, tag: &[u8]) { pub fn decrypt_init(&mut self, tag: &[u8]) {
self.tmp.copy_from_slice(tag); self.tmp.copy_from_slice(tag);
self.tmp[12] &= 0x7f; self.tmp[12] &= 0x7f;
let _ = self.ctr.replace( let _ = self
Crypter::new( .ctr
aes_ctr_by_key_size(self.k1.len()), .replace(Crypter::new(aes_ctr_by_key_size(self.k1.len()), Mode::Decrypt, self.k1.as_slice(), Some(&self.tmp)).unwrap());
Mode::Decrypt,
self.k1.as_slice(),
Some(&self.tmp),
)
.unwrap(),
);
let mut tag_tmp = [0_u8; 32]; let mut tag_tmp = [0_u8; 32];
let mut ecb = Crypter::new(aes_ecb_by_key_size(self.k1.len()), Mode::Decrypt, self.k1.as_slice(), None).unwrap(); let mut ecb = Crypter::new(aes_ecb_by_key_size(self.k1.len()), Mode::Decrypt, self.k1.as_slice(), None).unwrap();

View file

@ -55,9 +55,7 @@ mod openssl_based {
impl P384PublicKey { impl P384PublicKey {
fn new_from_point(key: &EcPointRef) -> Self { fn new_from_point(key: &EcPointRef) -> Self {
let mut bnc = BigNumContext::new().unwrap(); let mut bnc = BigNumContext::new().unwrap();
let kb = key let kb = key.to_bytes(GROUP_P384.as_ref(), PointConversionForm::COMPRESSED, &mut bnc).unwrap();
.to_bytes(GROUP_P384.as_ref(), PointConversionForm::COMPRESSED, &mut bnc)
.unwrap();
let mut bytes = [0_u8; 49]; let mut bytes = [0_u8; 49];
bytes[(49 - kb.len())..].copy_from_slice(kb.as_slice()); bytes[(49 - kb.len())..].copy_from_slice(kb.as_slice());
Self { Self {
@ -599,17 +597,12 @@ mod builtin {
let mut i: uint = 0; /* p = c0 */ let mut i: uint = 0; /* p = c0 */
vli_clear(l_tmp.as_mut_ptr()); vli_clear(l_tmp.as_mut_ptr());
vli_clear(l_tmp.as_mut_ptr().offset((48 as libc::c_int / 8 as libc::c_int) as isize)); vli_clear(l_tmp.as_mut_ptr().offset((48 as libc::c_int / 8 as libc::c_int) as isize));
omega_mult( omega_mult(l_tmp.as_mut_ptr(), p_product.offset((48 as libc::c_int / 8 as libc::c_int) as isize));
l_tmp.as_mut_ptr(),
p_product.offset((48 as libc::c_int / 8 as libc::c_int) as isize),
);
vli_clear(p_product.offset((48 as libc::c_int / 8 as libc::c_int) as isize)); vli_clear(p_product.offset((48 as libc::c_int / 8 as libc::c_int) as isize));
/* (c1, c0) = c0 + w * c1 */ /* (c1, c0) = c0 + w * c1 */
i = 0 as libc::c_int as uint; i = 0 as libc::c_int as uint;
while i < (48 as libc::c_int / 8 as libc::c_int + 3 as libc::c_int) as libc::c_uint { while i < (48 as libc::c_int / 8 as libc::c_int + 3 as libc::c_int) as libc::c_uint {
let mut l_sum: uint64_t = (*p_product.offset(i as isize)) let mut l_sum: uint64_t = (*p_product.offset(i as isize)).wrapping_add(l_tmp[i as usize]).wrapping_add(l_carry);
.wrapping_add(l_tmp[i as usize])
.wrapping_add(l_carry);
if l_sum != *p_product.offset(i as isize) { if l_sum != *p_product.offset(i as isize) {
l_carry = (l_sum < *p_product.offset(i as isize)) as libc::c_int as uint64_t l_carry = (l_sum < *p_product.offset(i as isize)) as libc::c_int as uint64_t
} }
@ -855,12 +848,7 @@ mod builtin {
vli_set(X1, t7.as_mut_ptr()); vli_set(X1, t7.as_mut_ptr());
} }
unsafe fn EccPoint_mult( unsafe fn EccPoint_mult(mut p_result: *mut EccPoint, mut p_point: *mut EccPoint, mut p_scalar: *mut uint64_t, mut p_initialZ: *mut uint64_t) {
mut p_result: *mut EccPoint,
mut p_point: *mut EccPoint,
mut p_scalar: *mut uint64_t,
mut p_initialZ: *mut uint64_t,
) {
/* R0 and R1 */ /* R0 and R1 */
let mut Rx: [[uint64_t; 6]; 2] = std::mem::MaybeUninit::uninit().assume_init(); let mut Rx: [[uint64_t; 6]; 2] = std::mem::MaybeUninit::uninit().assume_init();
let mut Ry: [[uint64_t; 6]; 2] = std::mem::MaybeUninit::uninit().assume_init(); let mut Ry: [[uint64_t; 6]; 2] = std::mem::MaybeUninit::uninit().assume_init();
@ -1039,20 +1027,12 @@ mod builtin {
} }
} }
ecc_native2bytes(p_privateKey, l_private.as_mut_ptr() as *const uint64_t); ecc_native2bytes(p_privateKey, l_private.as_mut_ptr() as *const uint64_t);
ecc_native2bytes( ecc_native2bytes(p_publicKey.offset(1 as libc::c_int as isize), l_public.x.as_mut_ptr() as *const uint64_t);
p_publicKey.offset(1 as libc::c_int as isize), *p_publicKey.offset(0 as libc::c_int as isize) =
l_public.x.as_mut_ptr() as *const uint64_t, (2 as libc::c_int as libc::c_ulong).wrapping_add(l_public.y[0 as libc::c_int as usize] & 0x1 as libc::c_int as libc::c_ulong) as uint8_t;
);
*p_publicKey.offset(0 as libc::c_int as isize) = (2 as libc::c_int as libc::c_ulong)
.wrapping_add(l_public.y[0 as libc::c_int as usize] & 0x1 as libc::c_int as libc::c_ulong)
as uint8_t;
return 1 as libc::c_int; return 1 as libc::c_int;
} }
pub unsafe fn ecdh_shared_secret( pub unsafe fn ecdh_shared_secret(mut p_publicKey: *const uint8_t, mut p_privateKey: *const uint8_t, mut p_secret: *mut uint8_t) -> libc::c_int {
mut p_publicKey: *const uint8_t,
mut p_privateKey: *const uint8_t,
mut p_secret: *mut uint8_t,
) -> libc::c_int {
let mut l_public: EccPoint = std::mem::MaybeUninit::uninit().assume_init(); let mut l_public: EccPoint = std::mem::MaybeUninit::uninit().assume_init();
let mut l_private: [uint64_t; 6] = std::mem::MaybeUninit::uninit().assume_init(); let mut l_private: [uint64_t; 6] = std::mem::MaybeUninit::uninit().assume_init();
let mut l_random: [uint64_t; 6] = std::mem::MaybeUninit::uninit().assume_init(); let mut l_random: [uint64_t; 6] = std::mem::MaybeUninit::uninit().assume_init();
@ -1079,8 +1059,7 @@ mod builtin {
vli_mult(l_product.as_mut_ptr(), p_left, p_right); vli_mult(l_product.as_mut_ptr(), p_left, p_right);
l_productBits = vli_numBits(l_product.as_mut_ptr().offset((48 as libc::c_int / 8 as libc::c_int) as isize)); l_productBits = vli_numBits(l_product.as_mut_ptr().offset((48 as libc::c_int / 8 as libc::c_int) as isize));
if l_productBits != 0 { if l_productBits != 0 {
l_productBits = (l_productBits as libc::c_uint) l_productBits = (l_productBits as libc::c_uint).wrapping_add((48 as libc::c_int / 8 as libc::c_int * 64 as libc::c_int) as libc::c_uint)
.wrapping_add((48 as libc::c_int / 8 as libc::c_int * 64 as libc::c_int) as libc::c_uint)
as uint as uint as uint as uint
} else { } else {
l_productBits = vli_numBits(l_product.as_mut_ptr()) l_productBits = vli_numBits(l_product.as_mut_ptr())
@ -1094,12 +1073,8 @@ mod builtin {
power of two possible while still resulting in a number less than p_left. */ power of two possible while still resulting in a number less than p_left. */
vli_clear(l_modMultiple.as_mut_ptr()); vli_clear(l_modMultiple.as_mut_ptr());
vli_clear(l_modMultiple.as_mut_ptr().offset((48 as libc::c_int / 8 as libc::c_int) as isize)); vli_clear(l_modMultiple.as_mut_ptr().offset((48 as libc::c_int / 8 as libc::c_int) as isize));
l_digitShift = l_productBits l_digitShift = l_productBits.wrapping_sub(l_modBits).wrapping_div(64 as libc::c_int as libc::c_uint);
.wrapping_sub(l_modBits) l_bitShift = l_productBits.wrapping_sub(l_modBits).wrapping_rem(64 as libc::c_int as libc::c_uint);
.wrapping_div(64 as libc::c_int as libc::c_uint);
l_bitShift = l_productBits
.wrapping_sub(l_modBits)
.wrapping_rem(64 as libc::c_int as libc::c_uint);
if l_bitShift != 0 { if l_bitShift != 0 {
l_modMultiple[l_digitShift.wrapping_add((48 as libc::c_int / 8 as libc::c_int) as libc::c_uint) as usize] = l_modMultiple[l_digitShift.wrapping_add((48 as libc::c_int / 8 as libc::c_int) as libc::c_uint) as usize] =
vli_lshift(l_modMultiple.as_mut_ptr().offset(l_digitShift as isize), p_mod, l_bitShift) vli_lshift(l_modMultiple.as_mut_ptr().offset(l_digitShift as isize), p_mod, l_bitShift)
@ -1186,11 +1161,7 @@ mod builtin {
ecc_native2bytes(p_signature.offset(48 as libc::c_int as isize), l_s.as_mut_ptr() as *const uint64_t); ecc_native2bytes(p_signature.offset(48 as libc::c_int as isize), l_s.as_mut_ptr() as *const uint64_t);
return 1 as libc::c_int; return 1 as libc::c_int;
} }
pub unsafe fn ecdsa_verify( pub unsafe fn ecdsa_verify(mut p_publicKey: *const uint8_t, mut p_hash: *const uint8_t, mut p_signature: *const uint8_t) -> libc::c_int {
mut p_publicKey: *const uint8_t,
mut p_hash: *const uint8_t,
mut p_signature: *const uint8_t,
) -> libc::c_int {
let mut u1: [uint64_t; 6] = std::mem::MaybeUninit::uninit().assume_init(); let mut u1: [uint64_t; 6] = std::mem::MaybeUninit::uninit().assume_init();
let mut u2: [uint64_t; 6] = std::mem::MaybeUninit::uninit().assume_init(); let mut u2: [uint64_t; 6] = std::mem::MaybeUninit::uninit().assume_init();
let mut z: [uint64_t; 6] = std::mem::MaybeUninit::uninit().assume_init(); let mut z: [uint64_t; 6] = std::mem::MaybeUninit::uninit().assume_init();
@ -1210,8 +1181,7 @@ mod builtin {
/* r, s must not be 0. */ /* r, s must not be 0. */
return 0 as libc::c_int; return 0 as libc::c_int;
} }
if vli_cmp(curve_n.as_mut_ptr(), l_r.as_mut_ptr()) != 1 as libc::c_int if vli_cmp(curve_n.as_mut_ptr(), l_r.as_mut_ptr()) != 1 as libc::c_int || vli_cmp(curve_n.as_mut_ptr(), l_s.as_mut_ptr()) != 1 as libc::c_int
|| vli_cmp(curve_n.as_mut_ptr(), l_s.as_mut_ptr()) != 1 as libc::c_int
{ {
/* r, s must be < n. */ /* r, s must be < n. */
return 0 as libc::c_int; return 0 as libc::c_int;
@ -1233,10 +1203,10 @@ mod builtin {
/* Use Shamir's trick to calculate u1*G + u2*Q */ /* Use Shamir's trick to calculate u1*G + u2*Q */
let mut l_points: [*mut EccPoint; 4] = [0 as *mut EccPoint, &mut curve_G, &mut l_public, &mut l_sum]; /* Z = x2 - x1 */ let mut l_points: [*mut EccPoint; 4] = [0 as *mut EccPoint, &mut curve_G, &mut l_public, &mut l_sum]; /* Z = x2 - x1 */
let mut l_numBits: uint = umax(vli_numBits(u1.as_mut_ptr()), vli_numBits(u2.as_mut_ptr())); /* Z = 1/Z */ let mut l_numBits: uint = umax(vli_numBits(u1.as_mut_ptr()), vli_numBits(u2.as_mut_ptr())); /* Z = 1/Z */
let mut l_point: *mut EccPoint = l_points[((vli_testBit(u1.as_mut_ptr(), l_numBits.wrapping_sub(1 as libc::c_int as libc::c_uint)) let mut l_point: *mut EccPoint = l_points[((vli_testBit(u1.as_mut_ptr(), l_numBits.wrapping_sub(1 as libc::c_int as libc::c_uint)) != 0)
!= 0) as libc::c_int as libc::c_int
| ((vli_testBit(u2.as_mut_ptr(), l_numBits.wrapping_sub(1 as libc::c_int as libc::c_uint)) != 0) as libc::c_int) | ((vli_testBit(u2.as_mut_ptr(), l_numBits.wrapping_sub(1 as libc::c_int as libc::c_uint)) != 0) as libc::c_int) << 1 as libc::c_int)
<< 1 as libc::c_int) as usize]; as usize];
vli_set(rx.as_mut_ptr(), (*l_point).x.as_mut_ptr()); vli_set(rx.as_mut_ptr(), (*l_point).x.as_mut_ptr());
vli_set(ry.as_mut_ptr(), (*l_point).y.as_mut_ptr()); vli_set(ry.as_mut_ptr(), (*l_point).y.as_mut_ptr());
vli_clear(z.as_mut_ptr()); vli_clear(z.as_mut_ptr());

View file

@ -20,12 +20,12 @@ mod tests {
use crate::poly1305::*; use crate::poly1305::*;
const TV0_INPUT: [u8; 32] = [ const TV0_INPUT: [u8; 32] = [
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
]; ];
const TV0_KEY: [u8; 32] = [ const TV0_KEY: [u8; 32] = [
0x74, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x33, 0x32, 0x2d, 0x62, 0x79, 0x74, 0x65, 0x20, 0x6b, 0x65, 0x79, 0x20, 0x66, 0x6f, 0x74, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x33, 0x32, 0x2d, 0x62, 0x79, 0x74, 0x65, 0x20, 0x6b, 0x65, 0x79, 0x20, 0x66, 0x6f, 0x72,
0x72, 0x20, 0x50, 0x6f, 0x6c, 0x79, 0x31, 0x33, 0x30, 0x35, 0x20, 0x50, 0x6f, 0x6c, 0x79, 0x31, 0x33, 0x30, 0x35,
]; ];
const TV0_TAG: [u8; 16] = [ const TV0_TAG: [u8; 16] = [
0x49, 0xec, 0x78, 0x09, 0x0e, 0x48, 0x1e, 0xc6, 0xc2, 0x6b, 0x33, 0xb9, 0x1c, 0xcc, 0x03, 0x07, 0x49, 0xec, 0x78, 0x09, 0x0e, 0x48, 0x1e, 0xc6, 0xc2, 0x6b, 0x33, 0xb9, 0x1c, 0xcc, 0x03, 0x07,
@ -33,8 +33,8 @@ mod tests {
const TV1_INPUT: [u8; 12] = [0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x21]; const TV1_INPUT: [u8; 12] = [0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x21];
const TV1_KEY: [u8; 32] = [ const TV1_KEY: [u8; 32] = [
0x74, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x33, 0x32, 0x2d, 0x62, 0x79, 0x74, 0x65, 0x20, 0x6b, 0x65, 0x79, 0x20, 0x66, 0x6f, 0x74, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x33, 0x32, 0x2d, 0x62, 0x79, 0x74, 0x65, 0x20, 0x6b, 0x65, 0x79, 0x20, 0x66, 0x6f, 0x72,
0x72, 0x20, 0x50, 0x6f, 0x6c, 0x79, 0x31, 0x33, 0x30, 0x35, 0x20, 0x50, 0x6f, 0x6c, 0x79, 0x31, 0x33, 0x30, 0x35,
]; ];
const TV1_TAG: [u8; 16] = [ const TV1_TAG: [u8; 16] = [
0xa6, 0xf7, 0x45, 0x00, 0x8f, 0x81, 0xc9, 0x16, 0xa2, 0x0d, 0xcc, 0x74, 0xee, 0xf2, 0xb2, 0xf0, 0xa6, 0xf7, 0x45, 0x00, 0x8f, 0x81, 0xc9, 0x16, 0xa2, 0x0d, 0xcc, 0x74, 0xee, 0xf2, 0xb2, 0xf0,

View file

@ -242,14 +242,14 @@ mod tests {
use crate::salsa::*; use crate::salsa::*;
const SALSA_20_TV0_KEY: [u8; 32] = [ const SALSA_20_TV0_KEY: [u8; 32] = [
0x0f, 0x62, 0xb5, 0x08, 0x5b, 0xae, 0x01, 0x54, 0xa7, 0xfa, 0x4d, 0xa0, 0xf3, 0x46, 0x99, 0xec, 0x3f, 0x92, 0xe5, 0x38, 0x8b, 0xde, 0x0f, 0x62, 0xb5, 0x08, 0x5b, 0xae, 0x01, 0x54, 0xa7, 0xfa, 0x4d, 0xa0, 0xf3, 0x46, 0x99, 0xec, 0x3f, 0x92, 0xe5, 0x38, 0x8b, 0xde, 0x31,
0x31, 0x84, 0xd7, 0x2a, 0x7d, 0xd0, 0x23, 0x76, 0xc9, 0x1c, 0x84, 0xd7, 0x2a, 0x7d, 0xd0, 0x23, 0x76, 0xc9, 0x1c,
]; ];
const SALSA_20_TV0_IV: [u8; 8] = [0x28, 0x8f, 0xf6, 0x5d, 0xc4, 0x2b, 0x92, 0xf9]; const SALSA_20_TV0_IV: [u8; 8] = [0x28, 0x8f, 0xf6, 0x5d, 0xc4, 0x2b, 0x92, 0xf9];
const SALSA_20_TV0_KS: [u8; 64] = [ const SALSA_20_TV0_KS: [u8; 64] = [
0x5e, 0x5e, 0x71, 0xf9, 0x01, 0x99, 0x34, 0x03, 0x04, 0xab, 0xb2, 0x2a, 0x37, 0xb6, 0x62, 0x5b, 0xf8, 0x83, 0xfb, 0x89, 0xce, 0x3b, 0x5e, 0x5e, 0x71, 0xf9, 0x01, 0x99, 0x34, 0x03, 0x04, 0xab, 0xb2, 0x2a, 0x37, 0xb6, 0x62, 0x5b, 0xf8, 0x83, 0xfb, 0x89, 0xce, 0x3b, 0x21,
0x21, 0xf5, 0x4a, 0x10, 0xb8, 0x10, 0x66, 0xef, 0x87, 0xda, 0x30, 0xb7, 0x76, 0x99, 0xaa, 0x73, 0x79, 0xda, 0x59, 0x5c, 0x77, 0xdd, 0xf5, 0x4a, 0x10, 0xb8, 0x10, 0x66, 0xef, 0x87, 0xda, 0x30, 0xb7, 0x76, 0x99, 0xaa, 0x73, 0x79, 0xda, 0x59, 0x5c, 0x77, 0xdd, 0x59, 0x54,
0x59, 0x54, 0x2d, 0xa2, 0x08, 0xe5, 0x95, 0x4f, 0x89, 0xe4, 0x0e, 0xb7, 0xaa, 0x80, 0xa8, 0x4a, 0x61, 0x76, 0x66, 0x3f, 0x2d, 0xa2, 0x08, 0xe5, 0x95, 0x4f, 0x89, 0xe4, 0x0e, 0xb7, 0xaa, 0x80, 0xa8, 0x4a, 0x61, 0x76, 0x66, 0x3f,
]; ];
#[test] #[test]

View file

@ -216,10 +216,7 @@ impl Marshalable for Endpoint {
TYPE_NIL => Ok(Endpoint::Nil), TYPE_NIL => Ok(Endpoint::Nil),
TYPE_ZEROTIER => { TYPE_ZEROTIER => {
let zt = Address::from_bytes_fixed(buf.read_bytes_fixed(cursor)?).ok_or(UnmarshalError::InvalidData)?; let zt = Address::from_bytes_fixed(buf.read_bytes_fixed(cursor)?).ok_or(UnmarshalError::InvalidData)?;
Ok(Endpoint::ZeroTier( Ok(Endpoint::ZeroTier(zt, buf.read_bytes_fixed::<IDENTITY_FINGERPRINT_SIZE>(cursor)?.clone()))
zt,
buf.read_bytes_fixed::<IDENTITY_FINGERPRINT_SIZE>(cursor)?.clone(),
))
} }
TYPE_ETHERNET => Ok(Endpoint::Ethernet(MAC::unmarshal(buf, cursor)?)), TYPE_ETHERNET => Ok(Endpoint::Ethernet(MAC::unmarshal(buf, cursor)?)),
TYPE_WIFIDIRECT => Ok(Endpoint::WifiDirect(MAC::unmarshal(buf, cursor)?)), TYPE_WIFIDIRECT => Ok(Endpoint::WifiDirect(MAC::unmarshal(buf, cursor)?)),
@ -230,9 +227,7 @@ impl Marshalable for Endpoint {
TYPE_HTTP => Ok(Endpoint::Http( TYPE_HTTP => Ok(Endpoint::Http(
String::from_utf8_lossy(buf.read_bytes(buf.read_varint(cursor)? as usize, cursor)?).to_string(), String::from_utf8_lossy(buf.read_bytes(buf.read_varint(cursor)? as usize, cursor)?).to_string(),
)), )),
TYPE_WEBRTC => Ok(Endpoint::WebRTC( TYPE_WEBRTC => Ok(Endpoint::WebRTC(buf.read_bytes(buf.read_varint(cursor)? as usize, cursor)?.to_vec())),
buf.read_bytes(buf.read_varint(cursor)? as usize, cursor)?.to_vec(),
)),
TYPE_ZEROTIER_ENCAP => { TYPE_ZEROTIER_ENCAP => {
let zt = Address::from_bytes_fixed(buf.read_bytes_fixed(cursor)?).ok_or(UnmarshalError::InvalidData)?; let zt = Address::from_bytes_fixed(buf.read_bytes_fixed(cursor)?).ok_or(UnmarshalError::InvalidData)?;
Ok(Endpoint::ZeroTierEncap(zt, buf.read_bytes_fixed(cursor)?.clone())) Ok(Endpoint::ZeroTierEncap(zt, buf.read_bytes_fixed(cursor)?.clone()))
@ -361,10 +356,7 @@ impl FromStr for Endpoint {
if endpoint_type == "zt" { if endpoint_type == "zt" {
return Ok(Endpoint::ZeroTier(Address::from_str(address)?, hash.as_slice().try_into().unwrap())); return Ok(Endpoint::ZeroTier(Address::from_str(address)?, hash.as_slice().try_into().unwrap()));
} else { } else {
return Ok(Endpoint::ZeroTierEncap( return Ok(Endpoint::ZeroTierEncap(Address::from_str(address)?, hash.as_slice().try_into().unwrap()));
Address::from_str(address)?,
hash.as_slice().try_into().unwrap(),
));
} }
} }
} }
@ -587,11 +579,7 @@ mod tests {
let inet = crate::vl1::InetAddress::from_ip_port(&v, 1234); let inet = crate::vl1::InetAddress::from_ip_port(&v, 1234);
for e in [ for e in [Endpoint::Icmp(inet.clone()), Endpoint::IpTcp(inet.clone()), Endpoint::IpUdp(inet.clone())] {
Endpoint::Icmp(inet.clone()),
Endpoint::IpTcp(inet.clone()),
Endpoint::IpUdp(inet.clone()),
] {
let mut buf = Buffer::<20>::new(); let mut buf = Buffer::<20>::new();
let res = e.marshal(&mut buf); let res = e.marshal(&mut buf);

View file

@ -222,9 +222,7 @@ impl Identity {
/// It would be possible to change this in the future, with care. /// It would be possible to change this in the future, with care.
pub fn upgrade(&mut self) -> Result<bool, InvalidParameterError> { pub fn upgrade(&mut self) -> Result<bool, InvalidParameterError> {
if self.secret.is_none() { if self.secret.is_none() {
return Err(InvalidParameterError( return Err(InvalidParameterError("an identity can only be upgraded if it includes its private key"));
"an identity can only be upgraded if it includes its private key",
));
} }
if self.p384.is_none() { if self.p384.is_none() {
let p384_ecdh = P384KeyPair::generate(); let p384_ecdh = P384KeyPair::generate();
@ -292,9 +290,8 @@ impl Identity {
/// This is somewhat time consuming due to the memory-intensive work algorithm. /// This is somewhat time consuming due to the memory-intensive work algorithm.
pub fn validate(self) -> Option<Valid<Self>> { pub fn validate(self) -> Option<Valid<Self>> {
if let Some(p384) = self.p384.as_ref() { if let Some(p384) = self.p384.as_ref() {
let mut self_sign_buf: Vec<u8> = Vec::with_capacity( let mut self_sign_buf: Vec<u8> =
ADDRESS_SIZE + 4 + C25519_PUBLIC_KEY_SIZE + ED25519_PUBLIC_KEY_SIZE + P384_PUBLIC_KEY_SIZE + P384_PUBLIC_KEY_SIZE, Vec::with_capacity(ADDRESS_SIZE + 4 + C25519_PUBLIC_KEY_SIZE + ED25519_PUBLIC_KEY_SIZE + P384_PUBLIC_KEY_SIZE + P384_PUBLIC_KEY_SIZE);
);
let _ = self_sign_buf.write_all(&self.address.to_bytes()); let _ = self_sign_buf.write_all(&self.address.to_bytes());
let _ = self_sign_buf.write_all(&self.x25519); let _ = self_sign_buf.write_all(&self.x25519);
let _ = self_sign_buf.write_all(&self.ed25519); let _ = self_sign_buf.write_all(&self.ed25519);
@ -331,11 +328,7 @@ impl Identity {
/// ///
/// This does NOT validate either identity. Ensure that validation has been performed. /// This does NOT validate either identity. Ensure that validation has been performed.
pub fn is_upgraded_from(&self, other: &Identity) -> bool { pub fn is_upgraded_from(&self, other: &Identity) -> bool {
self.address == other.address self.address == other.address && self.x25519 == other.x25519 && self.ed25519 == other.ed25519 && self.p384.is_some() && other.p384.is_none()
&& self.x25519 == other.x25519
&& self.ed25519 == other.ed25519
&& self.p384.is_some()
&& other.p384.is_none()
} }
/// Perform ECDH key agreement, returning a shared secret or None on error. /// Perform ECDH key agreement, returning a shared secret or None on error.
@ -493,13 +486,12 @@ impl Identity {
s.push(':'); s.push(':');
} }
s.push_str(":2:"); // 2 == IDENTITY_ALGORITHM_EC_NIST_P384 s.push_str(":2:"); // 2 == IDENTITY_ALGORITHM_EC_NIST_P384
let p384_joined: [u8; P384_PUBLIC_KEY_SIZE + P384_PUBLIC_KEY_SIZE + P384_ECDSA_SIGNATURE_SIZE + ED25519_SIGNATURE_SIZE] = let p384_joined: [u8; P384_PUBLIC_KEY_SIZE + P384_PUBLIC_KEY_SIZE + P384_ECDSA_SIGNATURE_SIZE + ED25519_SIGNATURE_SIZE] = concat_arrays_4(
concat_arrays_4( p384.ecdh.as_bytes(),
p384.ecdh.as_bytes(), p384.ecdsa.as_bytes(),
p384.ecdsa.as_bytes(), &p384.ecdsa_self_signature,
&p384.ecdsa_self_signature, &p384.ed25519_self_signature,
&p384.ed25519_self_signature, );
);
s.push_str(base64_encode_url_nopad(&p384_joined).as_str()); s.push_str(base64_encode_url_nopad(&p384_joined).as_str());
if self.secret.is_some() && include_private { if self.secret.is_some() && include_private {
let secret = self.secret.as_ref().unwrap(); let secret = self.secret.as_ref().unwrap();
@ -600,9 +592,7 @@ impl FromStr for Identity {
if keys[0].len() != C25519_PUBLIC_KEY_SIZE + ED25519_PUBLIC_KEY_SIZE { if keys[0].len() != C25519_PUBLIC_KEY_SIZE + ED25519_PUBLIC_KEY_SIZE {
return Err(InvalidFormatError); return Err(InvalidFormatError);
} }
if !keys[2].is_empty() if !keys[2].is_empty() && keys[2].len() != P384_PUBLIC_KEY_SIZE + P384_PUBLIC_KEY_SIZE + P384_ECDSA_SIGNATURE_SIZE + ED25519_SIGNATURE_SIZE {
&& keys[2].len() != P384_PUBLIC_KEY_SIZE + P384_PUBLIC_KEY_SIZE + P384_ECDSA_SIGNATURE_SIZE + ED25519_SIGNATURE_SIZE
{
return Err(InvalidFormatError); return Err(InvalidFormatError);
} }
if !keys[3].is_empty() && keys[3].len() != P384_SECRET_KEY_SIZE + P384_SECRET_KEY_SIZE { if !keys[3].is_empty() && keys[3].len() != P384_SECRET_KEY_SIZE + P384_SECRET_KEY_SIZE {
@ -632,8 +622,7 @@ impl FromStr for Identity {
Some(IdentityP384Public { Some(IdentityP384Public {
ecdh: ecdh.unwrap(), ecdh: ecdh.unwrap(),
ecdsa: ecdsa.unwrap(), ecdsa: ecdsa.unwrap(),
ecdsa_self_signature: keys[2].as_slice() ecdsa_self_signature: keys[2].as_slice()[(P384_PUBLIC_KEY_SIZE * 2)..((P384_PUBLIC_KEY_SIZE * 2) + P384_ECDSA_SIGNATURE_SIZE)]
[(P384_PUBLIC_KEY_SIZE * 2)..((P384_PUBLIC_KEY_SIZE * 2) + P384_ECDSA_SIGNATURE_SIZE)]
.try_into() .try_into()
.unwrap(), .unwrap(),
ed25519_self_signature: keys[2].as_slice()[((P384_PUBLIC_KEY_SIZE * 2) + P384_ECDSA_SIGNATURE_SIZE)..] ed25519_self_signature: keys[2].as_slice()[((P384_PUBLIC_KEY_SIZE * 2) + P384_ECDSA_SIGNATURE_SIZE)..]
@ -667,10 +656,8 @@ impl FromStr for Identity {
} else { } else {
Some(IdentityP384Secret { Some(IdentityP384Secret {
ecdh: { ecdh: {
let tmp = P384KeyPair::from_bytes( let tmp =
&keys[2].as_slice()[..P384_PUBLIC_KEY_SIZE], P384KeyPair::from_bytes(&keys[2].as_slice()[..P384_PUBLIC_KEY_SIZE], &keys[3].as_slice()[..P384_SECRET_KEY_SIZE]);
&keys[3].as_slice()[..P384_SECRET_KEY_SIZE],
);
if tmp.is_none() { if tmp.is_none() {
return Err(InvalidFormatError); return Err(InvalidFormatError);
} }
@ -711,16 +698,8 @@ impl Marshalable for Identity {
let x25519 = buf.read_bytes_fixed::<C25519_PUBLIC_KEY_SIZE>(cursor)?; let x25519 = buf.read_bytes_fixed::<C25519_PUBLIC_KEY_SIZE>(cursor)?;
let ed25519 = buf.read_bytes_fixed::<ED25519_PUBLIC_KEY_SIZE>(cursor)?; let ed25519 = buf.read_bytes_fixed::<ED25519_PUBLIC_KEY_SIZE>(cursor)?;
let ( let (mut ecdh, mut ecdsa, mut ecdsa_self_signature, mut ed25519_self_signature, mut x25519_s, mut ed25519_s, mut ecdh_s, mut ecdsa_s) =
mut ecdh, (None, None, None, None, None, None, None, None);
mut ecdsa,
mut ecdsa_self_signature,
mut ed25519_self_signature,
mut x25519_s,
mut ed25519_s,
mut ecdh_s,
mut ecdsa_s,
) = (None, None, None, None, None, None, None, None);
if type_flags == 0 { if type_flags == 0 {
const C25519_SECRETS_SIZE: u8 = (C25519_SECRET_KEY_SIZE + ED25519_SECRET_KEY_SIZE) as u8; const C25519_SECRETS_SIZE: u8 = (C25519_SECRET_KEY_SIZE + ED25519_SECRET_KEY_SIZE) as u8;
@ -736,9 +715,7 @@ impl Marshalable for Identity {
_ => return Err(UnmarshalError::InvalidData), _ => return Err(UnmarshalError::InvalidData),
} }
} else { } else {
if (type_flags & (Self::ALGORITHM_X25519 | Self::FLAG_INCLUDES_SECRETS)) if (type_flags & (Self::ALGORITHM_X25519 | Self::FLAG_INCLUDES_SECRETS)) == (Self::ALGORITHM_X25519 | Self::FLAG_INCLUDES_SECRETS) {
== (Self::ALGORITHM_X25519 | Self::FLAG_INCLUDES_SECRETS)
{
x25519_s = Some(buf.read_bytes_fixed::<C25519_SECRET_KEY_SIZE>(cursor)?); x25519_s = Some(buf.read_bytes_fixed::<C25519_SECRET_KEY_SIZE>(cursor)?);
ed25519_s = Some(buf.read_bytes_fixed::<ED25519_SECRET_KEY_SIZE>(cursor)?); ed25519_s = Some(buf.read_bytes_fixed::<ED25519_SECRET_KEY_SIZE>(cursor)?);
} }
@ -772,17 +749,12 @@ impl Marshalable for Identity {
secret: if let Some(x25519_s) = x25519_s { secret: if let Some(x25519_s) = x25519_s {
Some(IdentitySecret { Some(IdentitySecret {
x25519: X25519KeyPair::from_bytes(x25519, x25519_s).ok_or(UnmarshalError::InvalidData)?, x25519: X25519KeyPair::from_bytes(x25519, x25519_s).ok_or(UnmarshalError::InvalidData)?,
ed25519: Ed25519KeyPair::from_bytes(ed25519, ed25519_s.ok_or(UnmarshalError::InvalidData)?) ed25519: Ed25519KeyPair::from_bytes(ed25519, ed25519_s.ok_or(UnmarshalError::InvalidData)?).ok_or(UnmarshalError::InvalidData)?,
.ok_or(UnmarshalError::InvalidData)?,
p384: if let Some(ecdh_s) = ecdh_s { p384: if let Some(ecdh_s) = ecdh_s {
Some(IdentityP384Secret { Some(IdentityP384Secret {
ecdh: P384KeyPair::from_bytes(ecdh.ok_or(UnmarshalError::InvalidData)?, ecdh_s) ecdh: P384KeyPair::from_bytes(ecdh.ok_or(UnmarshalError::InvalidData)?, ecdh_s).ok_or(UnmarshalError::InvalidData)?,
ecdsa: P384KeyPair::from_bytes(ecdsa.ok_or(UnmarshalError::InvalidData)?, ecdsa_s.ok_or(UnmarshalError::InvalidData)?)
.ok_or(UnmarshalError::InvalidData)?, .ok_or(UnmarshalError::InvalidData)?,
ecdsa: P384KeyPair::from_bytes(
ecdsa.ok_or(UnmarshalError::InvalidData)?,
ecdsa_s.ok_or(UnmarshalError::InvalidData)?,
)
.ok_or(UnmarshalError::InvalidData)?,
}) })
} else { } else {
None None
@ -810,9 +782,7 @@ impl Eq for Identity {}
impl Ord for Identity { impl Ord for Identity {
#[inline(always)] #[inline(always)]
fn cmp(&self, other: &Self) -> Ordering { fn cmp(&self, other: &Self) -> Ordering {
self.address self.address.cmp(&other.address).then_with(|| self.fingerprint.cmp(&other.fingerprint))
.cmp(&other.address)
.then_with(|| self.fingerprint.cmp(&other.fingerprint))
} }
} }
@ -941,11 +911,7 @@ mod tests {
let gen_unmarshaled = Identity::from_bytes(bytes.as_bytes()).unwrap(); let gen_unmarshaled = Identity::from_bytes(bytes.as_bytes()).unwrap();
assert!(gen_unmarshaled.secret.is_some()); assert!(gen_unmarshaled.secret.is_some());
if !gen_unmarshaled.eq(&gen) { if !gen_unmarshaled.eq(&gen) {
println!( println!("{} != {}", hex::to_string(&gen_unmarshaled.fingerprint), hex::to_string(&gen.fingerprint));
"{} != {}",
hex::to_string(&gen_unmarshaled.fingerprint),
hex::to_string(&gen.fingerprint)
);
} }
assert!(Identity::from_str(string.as_str()).unwrap().secret.is_some()); assert!(Identity::from_str(string.as_str()).unwrap().secret.is_some());

View file

@ -892,11 +892,7 @@ impl Marshalable for InetAddress {
AF_INET6 => { AF_INET6 => {
let b = buf.append_bytes_fixed_get_mut::<19>()?; let b = buf.append_bytes_fixed_get_mut::<19>()?;
b[0] = 6; b[0] = 6;
copy_nonoverlapping( copy_nonoverlapping((&(self.sin6.sin6_addr) as *const in6_addr).cast::<u8>(), b.as_mut_ptr().offset(1), 16);
(&(self.sin6.sin6_addr) as *const in6_addr).cast::<u8>(),
b.as_mut_ptr().offset(1),
16,
);
b[17] = *(&self.sin6.sin6_port as *const u16).cast::<u8>(); b[17] = *(&self.sin6.sin6_port as *const u16).cast::<u8>();
b[18] = *(&self.sin6.sin6_port as *const u16).cast::<u8>().offset(1); b[18] = *(&self.sin6.sin6_port as *const u16).cast::<u8>().offset(1);
} }
@ -913,10 +909,7 @@ impl Marshalable for InetAddress {
Ok(InetAddress::from_ip_port(&b[0..4], u16::from_be_bytes(b[4..6].try_into().unwrap()))) Ok(InetAddress::from_ip_port(&b[0..4], u16::from_be_bytes(b[4..6].try_into().unwrap())))
} else if t == 6 { } else if t == 6 {
let b: &[u8; 18] = buf.read_bytes_fixed(cursor)?; let b: &[u8; 18] = buf.read_bytes_fixed(cursor)?;
Ok(InetAddress::from_ip_port( Ok(InetAddress::from_ip_port(&b[0..16], u16::from_be_bytes(b[16..18].try_into().unwrap())))
&b[0..16],
u16::from_be_bytes(b[16..18].try_into().unwrap()),
))
} else { } else {
Ok(InetAddress::new()) Ok(InetAddress::new())
} }

View file

@ -27,12 +27,7 @@ impl MAC {
pub fn from_bytes(b: &[u8]) -> Option<MAC> { pub fn from_bytes(b: &[u8]) -> Option<MAC> {
if b.len() >= 6 { if b.len() >= 6 {
NonZeroU64::new( NonZeroU64::new(
(b[0] as u64) << 40 (b[0] as u64) << 40 | (b[1] as u64) << 32 | (b[2] as u64) << 24 | (b[3] as u64) << 16 as u64 | (b[4] as u64) << 8 | b[5] as u64,
| (b[1] as u64) << 32
| (b[2] as u64) << 24
| (b[3] as u64) << 16 as u64
| (b[4] as u64) << 8
| b[5] as u64,
) )
.map(|i| MAC(i)) .map(|i| MAC(i))
} else { } else {
@ -94,10 +89,7 @@ impl Marshalable for MAC {
impl ToString for MAC { impl ToString for MAC {
fn to_string(&self) -> String { fn to_string(&self) -> String {
let b: [u8; 6] = self.to_bytes(); let b: [u8; 6] = self.to_bytes();
format!( format!("{:0>2x}:{:0>2x}:{:0>2x}:{:0>2x}:{:0>2x}:{:0>2x}", b[0], b[1], b[2], b[3], b[4], b[5])
"{:0>2x}:{:0>2x}:{:0>2x}:{:0>2x}:{:0>2x}:{:0>2x}",
b[0], b[1], b[2], b[3], b[4], b[5]
)
} }
} }

View file

@ -388,14 +388,7 @@ impl Node {
/// Get the root sets that this node trusts. /// Get the root sets that this node trusts.
#[inline] #[inline]
pub fn root_sets(&self) -> Vec<RootSet> { pub fn root_sets(&self) -> Vec<RootSet> {
self.roots self.roots.read().unwrap().sets.values().cloned().map(|s| s.remove_typestate()).collect()
.read()
.unwrap()
.sets
.values()
.cloned()
.map(|s| s.remove_typestate())
.collect()
} }
pub fn do_background_tasks<Application: ApplicationLayer + ?Sized>(&self, app: &Application) -> Duration { pub fn do_background_tasks<Application: ApplicationLayer + ?Sized>(&self, app: &Application) -> Duration {
@ -463,8 +456,7 @@ impl Node {
for (_, rs) in roots.sets.iter() { for (_, rs) in roots.sets.iter() {
for m in rs.members.iter() { for m in rs.members.iter() {
if m.endpoints.is_some() && !address_collisions.contains(&m.identity.address) && !m.identity.eq(&self.identity) if m.endpoints.is_some() && !address_collisions.contains(&m.identity.address) && !m.identity.eq(&self.identity) {
{
debug_event!( debug_event!(
app, app,
"[vl1] examining root {} with {} endpoints", "[vl1] examining root {} with {} endpoints",
@ -551,11 +543,7 @@ impl Node {
); );
*best_root = best.clone(); *best_root = best.clone();
} else { } else {
debug_event!( debug_event!(app, "[vl1] selected new best root: {} (was empty)", best.identity.address.to_string());
app,
"[vl1] selected new best root: {} (was empty)",
best.identity.address.to_string()
);
let _ = best_root.insert(best.clone()); let _ = best_root.insert(best.clone());
} }
} }
@ -648,11 +636,7 @@ impl Node {
// Lock in write mode and remove dead paths, doing so piecemeal to again avoid blocking. // Lock in write mode and remove dead paths, doing so piecemeal to again avoid blocking.
for dp in dead_paths.iter() { for dp in dead_paths.iter() {
self.paths self.paths.write().unwrap().get_mut::<PathMap<Application::LocalSocket>>().remove(dp);
.write()
.unwrap()
.get_mut::<PathMap<Application::LocalSocket>>()
.remove(dp);
} }
// Finally run keepalive sends as a batch. // Finally run keepalive sends as a batch.
@ -704,15 +688,9 @@ impl Node {
app, app,
"[vl1] {} -> #{} {}->{} length {} (on socket {}@{})", "[vl1] {} -> #{} {}->{} length {} (on socket {}@{})",
source_endpoint.to_string(), source_endpoint.to_string(),
packet packet.bytes_fixed_at::<8>(0).map_or("????????????????".into(), |pid| hex::to_string(pid)),
.bytes_fixed_at::<8>(0) packet.bytes_fixed_at::<5>(13).map_or("??????????".into(), |src| hex::to_string(src)),
.map_or("????????????????".into(), |pid| hex::to_string(pid)), packet.bytes_fixed_at::<5>(8).map_or("??????????".into(), |dest| hex::to_string(dest)),
packet
.bytes_fixed_at::<5>(13)
.map_or("??????????".into(), |src| hex::to_string(src)),
packet
.bytes_fixed_at::<5>(8)
.map_or("??????????".into(), |dest| hex::to_string(dest)),
packet.len(), packet.len(),
source_local_socket.to_string(), source_local_socket.to_string(),
source_local_interface.to_string() source_local_interface.to_string()
@ -780,8 +758,7 @@ impl Node {
for i in 1..assembled_packet.have { for i in 1..assembled_packet.have {
if let Some(f) = assembled_packet.frags[i as usize].as_ref() { if let Some(f) = assembled_packet.frags[i as usize].as_ref() {
if f.len() > v1::FRAGMENT_HEADER_SIZE { if f.len() > v1::FRAGMENT_HEADER_SIZE {
ok |= ok |= combined_packet.append_bytes(&f.as_bytes()[v1::FRAGMENT_HEADER_SIZE..]).is_ok();
combined_packet.append_bytes(&f.as_bytes()[v1::FRAGMENT_HEADER_SIZE..]).is_ok();
} }
} }
} }
@ -831,12 +808,7 @@ impl Node {
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
{ {
debug_packet_id = u64::from_be_bytes(packet_header.id); debug_packet_id = u64::from_be_bytes(packet_header.id);
debug_event!( debug_event!(app, "[vl1] [v1] #{:0>16x} forwarding packet to {}", debug_packet_id, dest.to_string());
app,
"[vl1] [v1] #{:0>16x} forwarding packet to {}",
debug_packet_id,
dest.to_string()
);
} }
if packet_header.increment_hops() > v1::FORWARD_MAX_HOPS { if packet_header.increment_hops() > v1::FORWARD_MAX_HOPS {
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
@ -993,10 +965,7 @@ impl Node {
time_ticks: i64, time_ticks: i64,
) -> Arc<Path> { ) -> Arc<Path> {
let paths = self.paths.read().unwrap(); let paths = self.paths.read().unwrap();
if let Some(path) = paths if let Some(path) = paths.get::<PathMap<Application::LocalSocket>>().get(&PathKey::Ref(ep, local_socket)) {
.get::<PathMap<Application::LocalSocket>>()
.get(&PathKey::Ref(ep, local_socket))
{
path.clone() path.clone()
} else { } else {
drop(paths); drop(paths);

View file

@ -324,11 +324,7 @@ impl Peer {
let mut aes_gmac_siv = self.v1_proto_static_secret.aes_gmac_siv.get(); let mut aes_gmac_siv = self.v1_proto_static_secret.aes_gmac_siv.get();
aes_gmac_siv.encrypt_init(&self.v1_proto_next_message_id().to_be_bytes()); aes_gmac_siv.encrypt_init(&self.v1_proto_next_message_id().to_be_bytes());
aes_gmac_siv.encrypt_set_aad(&v1::get_packet_aad_bytes( aes_gmac_siv.encrypt_set_aad(&v1::get_packet_aad_bytes(self.identity.address, node.identity.address, flags_cipher_hops));
self.identity.address,
node.identity.address,
flags_cipher_hops,
));
let payload = packet.as_bytes_starting_at_mut(v1::HEADER_SIZE).unwrap(); let payload = packet.as_bytes_starting_at_mut(v1::HEADER_SIZE).unwrap();
aes_gmac_siv.encrypt_first_pass(payload); aes_gmac_siv.encrypt_first_pass(payload);
aes_gmac_siv.encrypt_first_pass_finish(); aes_gmac_siv.encrypt_first_pass_finish();
@ -419,8 +415,7 @@ impl Peer {
let message_id = self.v1_proto_next_message_id(); let message_id = self.v1_proto_next_message_id();
{ {
let f: &mut (v1::PacketHeader, v1::message_component_structs::HelloFixedHeaderFields) = let f: &mut (v1::PacketHeader, v1::message_component_structs::HelloFixedHeaderFields) = packet.append_struct_get_mut().unwrap();
packet.append_struct_get_mut().unwrap();
f.0.id = message_id.to_ne_bytes(); f.0.id = message_id.to_ne_bytes();
f.0.dest = self.identity.address.to_bytes(); f.0.dest = self.identity.address.to_bytes();
f.0.src = node.identity.address.to_bytes(); f.0.src = node.identity.address.to_bytes();
@ -545,16 +540,9 @@ impl Peer {
return match verb { return match verb {
message_type::VL1_NOP => PacketHandlerResult::Ok, message_type::VL1_NOP => PacketHandlerResult::Ok,
message_type::VL1_HELLO => self.handle_incoming_hello(app, inner, node, time_ticks, message_id, source_path, &payload), message_type::VL1_HELLO => self.handle_incoming_hello(app, inner, node, time_ticks, message_id, source_path, &payload),
message_type::VL1_ERROR => self.handle_incoming_error( message_type::VL1_ERROR => {
app, self.handle_incoming_error(app, inner, node, time_ticks, source_path, packet_header.hops(), message_id, &payload)
inner, }
node,
time_ticks,
source_path,
packet_header.hops(),
message_id,
&payload,
),
message_type::VL1_OK => self.handle_incoming_ok( message_type::VL1_OK => self.handle_incoming_ok(
app, app,
inner, inner,
@ -567,13 +555,9 @@ impl Peer {
&payload, &payload,
), ),
message_type::VL1_WHOIS => self.handle_incoming_whois(app, inner, node, time_ticks, message_id, &payload), message_type::VL1_WHOIS => self.handle_incoming_whois(app, inner, node, time_ticks, message_id, &payload),
message_type::VL1_RENDEZVOUS => { message_type::VL1_RENDEZVOUS => self.handle_incoming_rendezvous(app, node, time_ticks, message_id, source_path, &payload),
self.handle_incoming_rendezvous(app, node, time_ticks, message_id, source_path, &payload)
}
message_type::VL1_ECHO => self.handle_incoming_echo(app, inner, node, time_ticks, message_id, &payload), message_type::VL1_ECHO => self.handle_incoming_echo(app, inner, node, time_ticks, message_id, &payload),
message_type::VL1_PUSH_DIRECT_PATHS => { message_type::VL1_PUSH_DIRECT_PATHS => self.handle_incoming_push_direct_paths(app, node, time_ticks, source_path, &payload),
self.handle_incoming_push_direct_paths(app, node, time_ticks, source_path, &payload)
}
message_type::VL1_USER_MESSAGE => self.handle_incoming_user_message(app, node, time_ticks, source_path, &payload), message_type::VL1_USER_MESSAGE => self.handle_incoming_user_message(app, node, time_ticks, source_path, &payload),
_ => inner.handle_packet(app, node, self, &source_path, packet_header.hops(), message_id, verb, &payload, 1), _ => inner.handle_packet(app, node, self, &source_path, packet_header.hops(), message_id, verb, &payload, 1),
}; };
@ -617,8 +601,7 @@ impl Peer {
} }
self.send(app, node, Some(source_path), time_ticks, |packet| -> Result<(), Infallible> { self.send(app, node, Some(source_path), time_ticks, |packet| -> Result<(), Infallible> {
let f: &mut (OkHeader, v1::message_component_structs::OkHelloFixedHeaderFields) = let f: &mut (OkHeader, v1::message_component_structs::OkHelloFixedHeaderFields) = packet.append_struct_get_mut().unwrap();
packet.append_struct_get_mut().unwrap();
f.0.verb = message_type::VL1_OK; f.0.verb = message_type::VL1_OK;
f.0.in_re_verb = message_type::VL1_HELLO; f.0.in_re_verb = message_type::VL1_HELLO;
f.0.in_re_message_id = message_id.to_ne_bytes(); f.0.in_re_message_id = message_id.to_ne_bytes();

View file

@ -116,10 +116,7 @@ impl NetworkConfig {
d.set_u64(proto_v1_field_name::network_config::VERSION, 6); d.set_u64(proto_v1_field_name::network_config::VERSION, 6);
d.set_str( d.set_str(proto_v1_field_name::network_config::NETWORK_ID, self.network_id.to_string().as_str());
proto_v1_field_name::network_config::NETWORK_ID,
self.network_id.to_string().as_str(),
);
if !self.name.is_empty() { if !self.name.is_empty() {
d.set_str(proto_v1_field_name::network_config::NAME, self.name.as_str()); d.set_str(proto_v1_field_name::network_config::NAME, self.name.as_str());
} }
@ -253,8 +250,7 @@ impl NetworkConfig {
let mut nc = Self::new(nwid, issued_to_address); let mut nc = Self::new(nwid, issued_to_address);
d.get_str(proto_v1_field_name::network_config::NAME) d.get_str(proto_v1_field_name::network_config::NAME).map(|x| nc.name = x.to_string());
.map(|x| nc.name = x.to_string());
nc.private = d.get_str(proto_v1_field_name::network_config::TYPE).map_or(true, |x| x == "1"); nc.private = d.get_str(proto_v1_field_name::network_config::TYPE).map_or(true, |x| x == "1");
nc.timestamp = d nc.timestamp = d
.get_i64(proto_v1_field_name::network_config::TIMESTAMP) .get_i64(proto_v1_field_name::network_config::TIMESTAMP)
@ -358,16 +354,10 @@ impl NetworkConfig {
authentication_expiry_time: d authentication_expiry_time: d
.get_i64(proto_v1_field_name::network_config::SSO_AUTHENTICATION_EXPIRY_TIME) .get_i64(proto_v1_field_name::network_config::SSO_AUTHENTICATION_EXPIRY_TIME)
.unwrap_or(0), .unwrap_or(0),
issuer_url: d issuer_url: d.get_str(proto_v1_field_name::network_config::SSO_ISSUER_URL).unwrap_or("").to_string(),
.get_str(proto_v1_field_name::network_config::SSO_ISSUER_URL)
.unwrap_or("")
.to_string(),
nonce: d.get_str(proto_v1_field_name::network_config::SSO_NONCE).unwrap_or("").to_string(), nonce: d.get_str(proto_v1_field_name::network_config::SSO_NONCE).unwrap_or("").to_string(),
state: d.get_str(proto_v1_field_name::network_config::SSO_STATE).unwrap_or("").to_string(), state: d.get_str(proto_v1_field_name::network_config::SSO_STATE).unwrap_or("").to_string(),
client_id: d client_id: d.get_str(proto_v1_field_name::network_config::SSO_CLIENT_ID).unwrap_or("").to_string(),
.get_str(proto_v1_field_name::network_config::SSO_CLIENT_ID)
.unwrap_or("")
.to_string(),
}) })
} }
@ -464,10 +454,7 @@ pub struct IpRoute {
impl Marshalable for IpRoute { impl Marshalable for IpRoute {
const MAX_MARSHAL_SIZE: usize = (InetAddress::MAX_MARSHAL_SIZE * 2) + 2 + 2; const MAX_MARSHAL_SIZE: usize = (InetAddress::MAX_MARSHAL_SIZE * 2) + 2 + 2;
fn marshal<const BL: usize>( fn marshal<const BL: usize>(&self, buf: &mut zerotier_utils::buffer::Buffer<BL>) -> Result<(), zerotier_utils::marshalable::UnmarshalError> {
&self,
buf: &mut zerotier_utils::buffer::Buffer<BL>,
) -> Result<(), zerotier_utils::marshalable::UnmarshalError> {
self.target.marshal(buf)?; self.target.marshal(buf)?;
if let Some(via) = self.via.as_ref() { if let Some(via) = self.via.as_ref() {
via.marshal(buf)?; via.marshal(buf)?;

View file

@ -171,10 +171,7 @@ fn main() {
if suggested.is_empty() { if suggested.is_empty() {
eprintln!("Unrecognized option '{}'. Use 'help' for help.", invalid); eprintln!("Unrecognized option '{}'. Use 'help' for help.", invalid);
} else { } else {
eprintln!( eprintln!("Unrecognized option '{}', did you mean {}? Use 'help' for help.", invalid, suggested);
"Unrecognized option '{}', did you mean {}? Use 'help' for help.",
invalid, suggested
);
} }
} }
std::process::exit(exitcode::ERR_USAGE); std::process::exit(exitcode::ERR_USAGE);
@ -184,9 +181,7 @@ fn main() {
let flags = Flags { let flags = Flags {
json_output: global_args.is_present("json"), json_output: global_args.is_present("json"),
base_path: global_args base_path: global_args.value_of("path").map_or_else(platform_default_home_path, |p| p.to_string()),
.value_of("path")
.map_or_else(platform_default_home_path, |p| p.to_string()),
auth_token_path_override: global_args.value_of("token_path").map(|p| p.to_string()), auth_token_path_override: global_args.value_of("token_path").map(|p| p.to_string()),
auth_token_override: global_args.value_of("token").map(|t| t.to_string()), auth_token_override: global_args.value_of("token").map(|t| t.to_string()),
}; };

View file

@ -93,13 +93,11 @@ impl Dictionary {
} }
pub fn get_u64(&self, k: &str) -> Option<u64> { pub fn get_u64(&self, k: &str) -> Option<u64> {
self.get_str(k) self.get_str(k).map_or(None, |s| u64::from_str_radix(s, 16).map_or(None, |i| Some(i)))
.map_or(None, |s| u64::from_str_radix(s, 16).map_or(None, |i| Some(i)))
} }
pub fn get_i64(&self, k: &str) -> Option<i64> { pub fn get_i64(&self, k: &str) -> Option<i64> {
self.get_str(k) self.get_str(k).map_or(None, |s| i64::from_str_radix(s, 16).map_or(None, |i| Some(i)))
.map_or(None, |s| i64::from_str_radix(s, 16).map_or(None, |i| Some(i)))
} }
pub fn get_bool(&self, k: &str) -> Option<bool> { pub fn get_bool(&self, k: &str) -> Option<bool> {

View file

@ -44,11 +44,7 @@ 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>( pub fn json_patch_object<O: Serialize + DeserializeOwned + Eq>(obj: O, patch: &str, depth_limit: usize) -> Result<Option<O>, serde_json::Error> {
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( serde_json::from_str::<serde_json::value::Value>(patch).map_or_else(
|e| Err(e), |e| Err(e),
|patch| { |patch| {

View file

@ -55,10 +55,7 @@ pub fn base64_decode_url_nopad(b64: &str) -> Option<Vec<u8>> {
/// Get milliseconds since unix epoch. /// Get milliseconds since unix epoch.
#[inline] #[inline]
pub fn ms_since_epoch() -> i64 { pub fn ms_since_epoch() -> i64 {
std::time::SystemTime::now() std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_millis() as i64
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_millis() as i64
} }
/// Get milliseconds since an arbitrary time in the past, guaranteed to monotonically increase. /// Get milliseconds since an arbitrary time in the past, guaranteed to monotonically increase.

View file

@ -2,15 +2,15 @@
/// A list of unassigned or obsolete ports under 1024 that could possibly be squatted. /// A list of unassigned or obsolete ports under 1024 that could possibly be squatted.
pub const UNASSIGNED_PRIVILEGED_PORTS: [u16; 299] = [ pub const UNASSIGNED_PRIVILEGED_PORTS: [u16; 299] = [
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, 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,
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, 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,
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, 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,
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, 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,
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, 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,
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, 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,
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, 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,
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, 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,
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, 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,
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, 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,
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, 1005, 1006, 1007, 1008, 1009, 1023,
]; ];

View file

@ -31,11 +31,7 @@ fn socket_read_concurrency() -> usize {
unsafe { unsafe {
let mut t = THREADS_PER_SOCKET; let mut t = THREADS_PER_SOCKET;
if t == 0 { if t == 0 {
t = std::thread::available_parallelism() t = std::thread::available_parallelism().unwrap().get().max(1).min(MAX_PER_SOCKET_CONCURRENCY);
.unwrap()
.get()
.max(1)
.min(MAX_PER_SOCKET_CONCURRENCY);
THREADS_PER_SOCKET = t; THREADS_PER_SOCKET = t;
} }
t t
@ -43,13 +39,7 @@ fn socket_read_concurrency() -> usize {
} }
pub trait UdpPacketHandler: Send + Sync { pub trait UdpPacketHandler: Send + Sync {
fn incoming_udp_packet( fn incoming_udp_packet(self: &Arc<Self>, time_ticks: i64, socket: &Arc<BoundUdpSocket>, source_address: &InetAddress, packet: PooledPacketBuffer);
self: &Arc<Self>,
time_ticks: i64,
socket: &Arc<BoundUdpSocket>,
source_address: &InetAddress,
packet: PooledPacketBuffer,
);
} }
/// A local port to which one or more UDP sockets is bound. /// A local port to which one or more UDP sockets is bound.

View file

@ -113,8 +113,7 @@ impl<Inner: InnerProtocolLayer + ?Sized + 'static> VL1Service<Inner> {
if !state.settings.fixed_ports.contains(p) { if !state.settings.fixed_ports.contains(p) {
let (total_smart_ptr_handles, most_recent_receive) = s.read().unwrap().liveness(); let (total_smart_ptr_handles, most_recent_receive) = s.read().unwrap().liveness();
if total_smart_ptr_handles < most_stale_binding_liveness.0 if total_smart_ptr_handles < most_stale_binding_liveness.0
|| (total_smart_ptr_handles == most_stale_binding_liveness.0 || (total_smart_ptr_handles == most_stale_binding_liveness.0 && most_recent_receive <= most_stale_binding_liveness.1)
&& most_recent_receive <= most_stale_binding_liveness.1)
{ {
most_stale_binding_liveness.0 = total_smart_ptr_handles; most_stale_binding_liveness.0 = total_smart_ptr_handles;
most_stale_binding_liveness.1 = most_recent_receive; most_stale_binding_liveness.1 = most_recent_receive;

View file

@ -27,8 +27,7 @@ pub struct VL1Settings {
impl VL1Settings { impl VL1Settings {
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
pub const DEFAULT_PREFIX_BLACKLIST: [&'static str; 11] = pub const DEFAULT_PREFIX_BLACKLIST: [&'static str; 11] = ["lo", "utun", "gif", "stf", "iptap", "pktap", "feth", "zt", "llw", "anpi", "bridge"];
["lo", "utun", "gif", "stf", "iptap", "pktap", "feth", "zt", "llw", "anpi", "bridge"];
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
pub const DEFAULT_PREFIX_BLACKLIST: [&'static str; 5] = ["lo", "tun", "tap", "ipsec", "zt"]; pub const DEFAULT_PREFIX_BLACKLIST: [&'static str; 5] = ["lo", "tun", "tap", "ipsec", "zt"];

View file

@ -39,13 +39,7 @@ impl<Fragment, const MAX_FRAGMENTS: usize> Fragged<Fragment, MAX_FRAGMENTS> {
unsafe { zeroed() } unsafe { zeroed() }
} }
pub fn assemble( pub fn assemble(&mut self, counter: u64, fragment: Fragment, fragment_no: u8, fragment_count: u8) -> Option<Assembled<Fragment, MAX_FRAGMENTS>> {
&mut self,
counter: u64,
fragment: Fragment,
fragment_no: u8,
fragment_count: u8,
) -> Option<Assembled<Fragment, MAX_FRAGMENTS>> {
if fragment_no < fragment_count && (fragment_count as usize) <= MAX_FRAGMENTS { if fragment_no < fragment_count && (fragment_count as usize) <= MAX_FRAGMENTS {
debug_assert!((fragment_count as usize) <= MAX_FRAGMENTS); debug_assert!((fragment_count as usize) <= MAX_FRAGMENTS);
debug_assert!((fragment_no as usize) < MAX_FRAGMENTS); debug_assert!((fragment_no as usize) < MAX_FRAGMENTS);