Skip to content

Commit

Permalink
Merge pull request #385 from nervosnetwork/impl-clippy-review
Browse files Browse the repository at this point in the history
bump to 0.6.5
driftluo authored Dec 2, 2024
2 parents 16278e5 + 07a0b87 commit bb06c4c
Show file tree
Hide file tree
Showing 14 changed files with 279 additions and 459 deletions.
24 changes: 24 additions & 0 deletions .github/workflows/release.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
name: Release

on:
release:
types: [created]

permissions:
contents: write

jobs:
release:
runs-on: ubuntu-latest
include:
- rust: stable
steps:
- uses: actions/checkout@v4
- run: sudo apt-get update && sudo apt-get install libssl-dev pkg-config libclang-dev -y
- name: Publish
run: |
cargo login ${{ secrets.CARGO_REGISTRY_TOKEN }}
cd multiaddr && cargo publish --dry-run
cd secio && cargo publish --dry-run
cd yamux && cargo publish --dry-run
cd tentacle && cargo publish --dry-run
10 changes: 8 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
## tentacle 0.6.5 yamux 0.3.10 secio 0.6.4

### Features

- enable tcp base protocol listen on same port

## tentacle 0.6.4

## Feature
### Features
- Make `runtime::Interval` behavior same as tokio interval(#379)

## tentacle 0.6.3

## Bug Fix
### Bug Fix
- Fix session open protocol open order(#377)
- Fix interval inconsistent behavior(#378)

Expand Down
2 changes: 1 addition & 1 deletion secio/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "tentacle-secio"
version = "0.6.3"
version = "0.6.4"
license = "MIT"
description = "Secio encryption protocol for p2p"
authors = ["piaoliu <driftluo@foxmail.com>", "Nervos Core Dev <dev@nervos.org>"]
Expand Down
2 changes: 1 addition & 1 deletion secio/src/crypto/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ pub fn new_stream(t: cipher::CipherType, key: &[u8], _mode: CryptoMode) -> BoxSt
/// ...
fn nonce_advance(nonce: &mut [u8]) {
for i in nonce {
if std::u8::MAX == *i {
if u8::MAX == *i {
*i = 0;
} else {
*i += 1;
Expand Down
2 changes: 1 addition & 1 deletion secio/src/crypto/openssl_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ impl OpenSsLCrypt {
let cipher = match cipher_type {
CipherType::Aes128Gcm => symm::Cipher::aes_128_gcm(),
CipherType::Aes256Gcm => symm::Cipher::aes_256_gcm(),
#[cfg(any(ossl110))]
#[cfg(ossl110)]
CipherType::ChaCha20Poly1305 => symm::Cipher::chacha20_poly1305(),
#[cfg(not(ossl110))]
_ => panic!(
Expand Down
3 changes: 1 addition & 2 deletions secio/src/peer_id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,7 @@ impl PeerId {

let header_len = code.len() + 1;

let mut inner = Vec::new();
inner.resize(header_len + SHA256_SIZE as usize, 0);
let mut inner = vec![0; header_len + SHA256_SIZE as usize];
inner[..code.len()].copy_from_slice(code);
inner[code.len()] = SHA256_SIZE;

Expand Down
2 changes: 1 addition & 1 deletion tentacle/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "tentacle"
version = "0.6.4"
version = "0.6.5"
license = "MIT"
description = "Minimal implementation for a multiplexed p2p network framework."
authors = ["piaoliu <driftluo@foxmail.com>", "Nervos Core Dev <dev@nervos.org>"]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use tentacle::{
ProtocolId,
};

#[path = "./test_tls_dial.rs"]
#[path = "./tls_common.rs"]
mod tls;

pub fn create<F>(
Expand Down
221 changes: 6 additions & 215 deletions tentacle/tests/test_tls_dial.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
#![cfg(feature = "tls")]
use futures::channel;
use std::io::BufReader;
use std::str::FromStr;
use std::sync::Arc;
use std::{fs, thread};
use std::{str::FromStr, thread};
use tentacle::{
async_trait,
builder::{MetaBuilder, ServiceBuilder},
Expand All @@ -18,16 +15,11 @@ use tentacle::{
traits::{ServiceHandle, ServiceProtocol},
ProtocolId, SessionId,
};
use tokio_rustls::rustls::server::WebPkiClientVerifier;
use tokio_rustls::rustls::version::{TLS12, TLS13};
use tokio_rustls::rustls::{
crypto::aws_lc_rs::default_provider,
crypto::aws_lc_rs::ALL_CIPHER_SUITES,
pki_types::{
pem::PemObject, CertificateDer, PrivateKeyDer, PrivatePkcs1KeyDer, PrivatePkcs8KeyDer,
},
ClientConfig, RootCertStore, ServerConfig, SupportedCipherSuite, SupportedProtocolVersion,
};

#[path = "./tls_common.rs"]
mod tls;

use tls::{make_client_config, make_server_config, NetConfig};

pub fn create<F>(meta: ProtocolMeta, shandle: F, cert_path: String) -> Service<F, NoopKeyProvider>
where
Expand Down Expand Up @@ -118,30 +110,6 @@ impl ServiceProtocol for PHandle {
}
}

#[derive(Debug, Clone)]
pub struct NetConfig {
server_cert_chain: Option<String>,
server_key: Option<String>,

ca_cert: Option<String>,

protocols: Option<Vec<String>>,
cypher_suits: Option<Vec<String>>,
}

impl NetConfig {
pub fn example(node_dir: String) -> Self {
Self {
server_cert_chain: Some(node_dir.clone() + "server.crt"),
server_key: Some(node_dir.clone() + "server.key"),
ca_cert: Some(node_dir + "ca.crt"),

protocols: None,
cypher_suits: None,
}
}
}

fn create_meta(id: ProtocolId) -> (ProtocolMeta, crossbeam_channel::Receiver<bytes::Bytes>) {
// NOTE: channel size must large, otherwise send will failed.
let (sender, receiver) = crossbeam_channel::unbounded();
Expand Down Expand Up @@ -178,183 +146,6 @@ fn create_shandle() -> (
)
}

fn find_suite(name: &str) -> Option<SupportedCipherSuite> {
for suite in ALL_CIPHER_SUITES {
let cs_name = format!("{:?}", suite.suite()).to_lowercase();

if cs_name == name.to_string().to_lowercase() {
return Some(*suite);
}
}

None
}

fn lookup_suites(suites: &[String]) -> Vec<SupportedCipherSuite> {
let mut out = Vec::new();

for cs_name in suites {
let scs = find_suite(cs_name);
match scs {
Some(s) => out.push(s),
None => panic!("cannot look up cipher suite '{}'", cs_name),
}
}

out
}

/// Make a vector of protocol versions named in `versions`
fn lookup_versions(versions: &[String]) -> Vec<&'static SupportedProtocolVersion> {
let mut out = Vec::new();

for vname in versions {
let version = match vname.as_ref() {
"1.2" => &TLS12,
"1.3" => &TLS13,
_ => panic!(
"cannot look up version '{}', valid are '1.2' and '1.3'",
vname
),
};
out.push(version);
}

out
}

fn load_certs(filename: &str) -> Vec<CertificateDer<'static>> {
let certfile = fs::File::open(filename).expect("cannot open certificate file");
let mut reader = BufReader::new(certfile);
CertificateDer::pem_reader_iter(&mut reader)
.collect::<Result<Vec<_>, _>>()
.unwrap()
}

fn load_private_key(filename: &str) -> PrivateKeyDer<'static> {
let keyfile = fs::File::open(filename).expect("cannot open private key file");
let mut reader = BufReader::new(keyfile);
let mut rsa_keys = PrivatePkcs1KeyDer::pem_reader_iter(&mut reader);

let rsa_keys_peek = rsa_keys.next();

if let Some(rsa_keys_peek) = rsa_keys_peek {
return PrivateKeyDer::Pkcs1(rsa_keys_peek.unwrap().clone_key());
}

let keyfile = fs::File::open(filename).expect("cannot open private key file");
let mut reader = BufReader::new(keyfile);
let mut pkcs8_keys = PrivatePkcs8KeyDer::pem_reader_iter(&mut reader);
let pkcs8_keys_peek = pkcs8_keys.next();

assert!(pkcs8_keys_peek.is_some());
PrivateKeyDer::Pkcs8(pkcs8_keys_peek.unwrap().unwrap().clone_key())
}

/// Build a `ServerConfig` from our NetConfig
pub fn make_server_config(config: &NetConfig) -> ServerConfig {
let mut cryp = default_provider();

if config.cypher_suits.is_some() {
cryp.cipher_suites = lookup_suites(config.cypher_suits.as_ref().unwrap())
};

let server_config = ServerConfig::builder_with_provider(Arc::new(cryp));

let server_config = if config.protocols.is_some() {
server_config
.with_protocol_versions(lookup_versions(config.protocols.as_ref().unwrap()).as_slice())
.unwrap()
} else {
server_config.with_safe_default_protocol_versions().unwrap()
};

let cacerts = load_certs(config.ca_cert.as_ref().unwrap());

let mut client_auth_roots = RootCertStore::empty();
for cacert in &cacerts {
client_auth_roots.add(cacert.clone()).unwrap();
}
let client_auth = WebPkiClientVerifier::builder(client_auth_roots.into())
.build()
.unwrap();

let server_config = server_config.with_client_cert_verifier(client_auth);

let mut certs = load_certs(
config
.server_cert_chain
.as_ref()
.expect("server_cert_chain option missing"),
);
let privkey = load_private_key(
config
.server_key
.as_ref()
.expect("server_key option missing"),
);

// Specially for server.crt not a cert-chain only one server certificate, so manually make
// a cert-chain.
if certs.len() == 1 && !cacerts.is_empty() {
certs.extend(cacerts);
}

server_config.with_single_cert(certs, privkey).unwrap()
}

/// Build a `ClientConfig` from our NetConfig
pub fn make_client_config(config: &NetConfig) -> ClientConfig {
let mut cryp = default_provider();

if config.cypher_suits.is_some() {
cryp.cipher_suites = lookup_suites(config.cypher_suits.as_ref().unwrap());
};

let client_config = ClientConfig::builder_with_provider(Arc::new(cryp));

let client_config = if config.protocols.is_some() {
client_config
.with_protocol_versions(lookup_versions(config.protocols.as_ref().unwrap()).as_slice())
.unwrap()
} else {
client_config.with_safe_default_protocol_versions().unwrap()
};

let cafile = config.ca_cert.as_ref().unwrap();

let mut client_root_cert_store = RootCertStore::empty();
client_root_cert_store.add_parsable_certificates(load_certs(cafile));

let client_config = client_config.with_root_certificates(client_root_cert_store);

if config.server_key.is_some() || config.server_cert_chain.is_some() {
let certsfile = config
.server_cert_chain
.as_ref()
.expect("must provide client_cert with client_key");

let keyfile = config
.server_key
.as_ref()
.expect("must provide client_key with client_cert");

let mut certs = load_certs(certsfile);
let cacerts = load_certs(cafile);
let privkey = load_private_key(keyfile);

// Specially for server.crt not a cert-chain only one server certificate, so manually make
// a cert-chain.
if certs.len() == 1 && !cacerts.is_empty() {
certs.extend(cacerts);
}

client_config.with_client_auth_cert(certs, privkey).unwrap()
} else {
client_config.with_no_client_auth()
}
}

fn test_tls_dial() {
let (meta_1, receiver_1) = create_meta(1.into());
let (meta_2, receiver_2) = create_meta(1.into());
Expand Down
221 changes: 6 additions & 215 deletions tentacle/tests/test_tls_reconnect.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
#![cfg(feature = "tls")]
use crossbeam_channel::Receiver;
use std::io::BufReader;
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;
use std::{fs, thread};
use std::{str::FromStr, thread, time::Duration};
use tentacle::bytes::Bytes;
use tentacle::service::ServiceControl;
use tentacle::{
Expand All @@ -17,16 +13,11 @@ use tentacle::{
traits::{ServiceHandle, ServiceProtocol},
ProtocolId,
};
use tokio_rustls::rustls::server::WebPkiClientVerifier;
use tokio_rustls::rustls::version::{TLS12, TLS13};
use tokio_rustls::rustls::{
crypto::aws_lc_rs::default_provider,
crypto::aws_lc_rs::ALL_CIPHER_SUITES,
pki_types::{
pem::PemObject, CertificateDer, PrivateKeyDer, PrivatePkcs1KeyDer, PrivatePkcs8KeyDer,
},
ClientConfig, RootCertStore, ServerConfig, SupportedCipherSuite, SupportedProtocolVersion,
};

#[path = "./tls_common.rs"]
mod tls;

use tls::{make_client_config, make_server_config, NetConfig};

pub fn create<F>(meta: ProtocolMeta, shandle: F, cert_path: String) -> Service<F, NoopKeyProvider>
where
Expand Down Expand Up @@ -70,30 +61,6 @@ impl ServiceProtocol for PHandle {
}
}

#[derive(Debug, Clone)]
pub struct NetConfig {
server_cert_chain: Option<String>,
server_key: Option<String>,

ca_cert: Option<String>,

protocols: Option<Vec<String>>,
cypher_suits: Option<Vec<String>>,
}

impl NetConfig {
fn example(node_dir: String) -> Self {
Self {
server_cert_chain: Some(node_dir.clone() + "server.crt"),
server_key: Some(node_dir.clone() + "server.key"),
ca_cert: Some(node_dir + "ca.crt"),

protocols: None,
cypher_suits: None,
}
}
}

fn create_meta(
id: ProtocolId,
send: bool,
Expand Down Expand Up @@ -121,182 +88,6 @@ fn create_shandle() -> Box<dyn ServiceHandle + Send> {
Box::new(())
}

fn find_suite(name: &str) -> Option<SupportedCipherSuite> {
for suite in ALL_CIPHER_SUITES {
let cs_name = format!("{:?}", suite.suite()).to_lowercase();

if cs_name == name.to_string().to_lowercase() {
return Some(*suite);
}
}

None
}

fn lookup_suites(suites: &[String]) -> Vec<SupportedCipherSuite> {
let mut out = Vec::new();

for cs_name in suites {
let scs = find_suite(cs_name);
match scs {
Some(s) => out.push(s),
None => panic!("cannot look up cipher suite '{}'", cs_name),
}
}

out
}

/// Make a vector of protocol versions named in `versions`
fn lookup_versions(versions: &[String]) -> Vec<&'static SupportedProtocolVersion> {
let mut out = Vec::new();

for vname in versions {
let version = match vname.as_ref() {
"1.2" => &TLS12,
"1.3" => &TLS13,
_ => panic!(
"cannot look up version '{}', valid are '1.2' and '1.3'",
vname
),
};
out.push(version);
}

out
}

fn load_certs(filename: &str) -> Vec<CertificateDer<'static>> {
let certfile = fs::File::open(filename).expect("cannot open certificate file");
let mut reader = BufReader::new(certfile);
CertificateDer::pem_reader_iter(&mut reader)
.collect::<Result<Vec<_>, _>>()
.unwrap()
}

fn load_private_key(filename: &str) -> PrivateKeyDer<'static> {
let keyfile = fs::File::open(filename).expect("cannot open private key file");
let mut reader = BufReader::new(keyfile);
let mut rsa_keys = PrivatePkcs1KeyDer::pem_reader_iter(&mut reader);

let rsa_keys_peek = rsa_keys.next();

if let Some(rsa_keys_peek) = rsa_keys_peek {
return PrivateKeyDer::Pkcs1(rsa_keys_peek.unwrap().clone_key());
}

let keyfile = fs::File::open(filename).expect("cannot open private key file");
let mut reader = BufReader::new(keyfile);
let mut pkcs8_keys = PrivatePkcs8KeyDer::pem_reader_iter(&mut reader);
let pkcs8_keys_peek = pkcs8_keys.next();

assert!(pkcs8_keys_peek.is_some());
PrivateKeyDer::Pkcs8(pkcs8_keys_peek.unwrap().unwrap().clone_key())
}

/// Build a `ServerConfig` from our NetConfig
pub fn make_server_config(config: &NetConfig) -> ServerConfig {
let mut cryp = default_provider();

if config.cypher_suits.is_some() {
cryp.cipher_suites = lookup_suites(config.cypher_suits.as_ref().unwrap())
};

let server_config = ServerConfig::builder_with_provider(Arc::new(cryp));
let server_config = if config.protocols.is_some() {
server_config
.with_protocol_versions(lookup_versions(config.protocols.as_ref().unwrap()).as_slice())
.unwrap()
} else {
server_config.with_safe_default_protocol_versions().unwrap()
};

let cacerts = load_certs(config.ca_cert.as_ref().unwrap());

let mut client_auth_roots = RootCertStore::empty();
for cacert in &cacerts {
client_auth_roots.add(cacert.clone()).unwrap();
}
let client_auth = WebPkiClientVerifier::builder(client_auth_roots.into())
.build()
.unwrap();

let server_config = server_config.with_client_cert_verifier(client_auth);

let mut certs = load_certs(
config
.server_cert_chain
.as_ref()
.expect("server_cert_chain option missing"),
);
let privkey = load_private_key(
config
.server_key
.as_ref()
.expect("server_key option missing"),
);

// Specially for server.crt not a cert-chain only one server certificate, so manually make
// a cert-chain.
if certs.len() == 1 && !cacerts.is_empty() {
certs.extend(cacerts);
}

server_config.with_single_cert(certs, privkey).unwrap()
}

/// Build a `ClientConfig` from our NetConfig
pub fn make_client_config(config: &NetConfig) -> ClientConfig {
let mut cryp = default_provider();

if config.cypher_suits.is_some() {
cryp.cipher_suites = lookup_suites(config.cypher_suits.as_ref().unwrap());
};

let client_config = ClientConfig::builder_with_provider(Arc::new(cryp));

let client_config = if config.protocols.is_some() {
client_config
.with_protocol_versions(lookup_versions(config.protocols.as_ref().unwrap()).as_slice())
.unwrap()
} else {
client_config.with_safe_default_protocol_versions().unwrap()
};

let cafile = config.ca_cert.as_ref().unwrap();

let mut client_root_cert_store = RootCertStore::empty();
client_root_cert_store.add_parsable_certificates(load_certs(cafile));

let client_config = client_config.with_root_certificates(client_root_cert_store);

if config.server_key.is_some() || config.server_cert_chain.is_some() {
let certsfile = config
.server_cert_chain
.as_ref()
.expect("must provide client_cert with client_key");

let keyfile = config
.server_key
.as_ref()
.expect("must provide client_key with client_cert");

let mut certs = load_certs(certsfile);
let cacerts = load_certs(cafile);
let privkey = load_private_key(keyfile);

// Specially for server.crt not a cert-chain only one server certificate, so manually make
// a cert-chain.
if certs.len() == 1 && !cacerts.is_empty() {
certs.extend(cacerts);
}

client_config.with_client_auth_cert(certs, privkey).unwrap()
} else {
client_config.with_no_client_auth()
}
}

fn server_node(path: String, listen_address: Multiaddr) -> (Receiver<Bytes>, Multiaddr) {
let (meta, receiver) = create_meta(1.into(), true);
let shandle = create_shandle();
Expand Down
215 changes: 215 additions & 0 deletions tentacle/tests/tls_common.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
#![cfg(feature = "tls")]

use std::{fs, io::BufReader, sync::Arc};

use tokio_rustls::rustls::server::WebPkiClientVerifier;
use tokio_rustls::rustls::version::{TLS12, TLS13};
use tokio_rustls::rustls::{
crypto::aws_lc_rs::default_provider,
crypto::aws_lc_rs::ALL_CIPHER_SUITES,
pki_types::{
pem::PemObject, CertificateDer, PrivateKeyDer, PrivatePkcs1KeyDer, PrivatePkcs8KeyDer,
},
ClientConfig, RootCertStore, ServerConfig, SupportedCipherSuite, SupportedProtocolVersion,
};

#[derive(Debug, Clone)]
pub struct NetConfig {
server_cert_chain: Option<String>,
server_key: Option<String>,

ca_cert: Option<String>,

protocols: Option<Vec<String>>,
cypher_suits: Option<Vec<String>>,
}

impl NetConfig {
pub fn example(node_dir: String) -> Self {
Self {
server_cert_chain: Some(node_dir.clone() + "server.crt"),
server_key: Some(node_dir.clone() + "server.key"),
ca_cert: Some(node_dir + "ca.crt"),

protocols: None,
cypher_suits: None,
}
}
}

fn find_suite(name: &str) -> Option<SupportedCipherSuite> {
for suite in ALL_CIPHER_SUITES {
let cs_name = format!("{:?}", suite.suite()).to_lowercase();

if cs_name == name.to_string().to_lowercase() {
return Some(*suite);
}
}

None
}

fn lookup_suites(suites: &[String]) -> Vec<SupportedCipherSuite> {
let mut out = Vec::new();

for cs_name in suites {
let scs = find_suite(cs_name);
match scs {
Some(s) => out.push(s),
None => panic!("cannot look up cipher suite '{}'", cs_name),
}
}

out
}

/// Make a vector of protocol versions named in `versions`
fn lookup_versions(versions: &[String]) -> Vec<&'static SupportedProtocolVersion> {
let mut out = Vec::new();

for vname in versions {
let version = match vname.as_ref() {
"1.2" => &TLS12,
"1.3" => &TLS13,
_ => panic!(
"cannot look up version '{}', valid are '1.2' and '1.3'",
vname
),
};
out.push(version);
}

out
}

fn load_certs(filename: &str) -> Vec<CertificateDer<'static>> {
let certfile = fs::File::open(filename).expect("cannot open certificate file");
let mut reader = BufReader::new(certfile);
CertificateDer::pem_reader_iter(&mut reader)
.collect::<Result<Vec<_>, _>>()
.unwrap()
}

fn load_private_key(filename: &str) -> PrivateKeyDer<'static> {
let keyfile = fs::File::open(filename).expect("cannot open private key file");
let mut reader = BufReader::new(keyfile);
let mut rsa_keys = PrivatePkcs1KeyDer::pem_reader_iter(&mut reader);

let rsa_keys_peek = rsa_keys.next();

if let Some(rsa_keys_peek) = rsa_keys_peek {
return PrivateKeyDer::Pkcs1(rsa_keys_peek.unwrap().clone_key());
}

let keyfile = fs::File::open(filename).expect("cannot open private key file");
let mut reader = BufReader::new(keyfile);
let mut pkcs8_keys = PrivatePkcs8KeyDer::pem_reader_iter(&mut reader);
let pkcs8_keys_peek = pkcs8_keys.next();

assert!(pkcs8_keys_peek.is_some());
PrivateKeyDer::Pkcs8(pkcs8_keys_peek.unwrap().unwrap().clone_key())
}

/// Build a `ServerConfig` from our NetConfig
pub fn make_server_config(config: &NetConfig) -> ServerConfig {
let mut cryp = default_provider();

if config.cypher_suits.is_some() {
cryp.cipher_suites = lookup_suites(config.cypher_suits.as_ref().unwrap())
};

let server_config = ServerConfig::builder_with_provider(Arc::new(cryp));

let server_config = if config.protocols.is_some() {
server_config
.with_protocol_versions(lookup_versions(config.protocols.as_ref().unwrap()).as_slice())
.unwrap()
} else {
server_config.with_safe_default_protocol_versions().unwrap()
};

let cacerts = load_certs(config.ca_cert.as_ref().unwrap());

let mut client_auth_roots = RootCertStore::empty();
for cacert in &cacerts {
client_auth_roots.add(cacert.clone()).unwrap();
}
let client_auth = WebPkiClientVerifier::builder(client_auth_roots.into())
.build()
.unwrap();

let server_config = server_config.with_client_cert_verifier(client_auth);

let mut certs = load_certs(
config
.server_cert_chain
.as_ref()
.expect("server_cert_chain option missing"),
);
let privkey = load_private_key(
config
.server_key
.as_ref()
.expect("server_key option missing"),
);

// Specially for server.crt not a cert-chain only one server certificate, so manually make
// a cert-chain.
if certs.len() == 1 && !cacerts.is_empty() {
certs.extend(cacerts);
}

server_config.with_single_cert(certs, privkey).unwrap()
}

/// Build a `ClientConfig` from our NetConfig
pub fn make_client_config(config: &NetConfig) -> ClientConfig {
let mut cryp = default_provider();

if config.cypher_suits.is_some() {
cryp.cipher_suites = lookup_suites(config.cypher_suits.as_ref().unwrap());
};

let client_config = ClientConfig::builder_with_provider(Arc::new(cryp));

let client_config = if config.protocols.is_some() {
client_config
.with_protocol_versions(lookup_versions(config.protocols.as_ref().unwrap()).as_slice())
.unwrap()
} else {
client_config.with_safe_default_protocol_versions().unwrap()
};

let cafile = config.ca_cert.as_ref().unwrap();

let mut client_root_cert_store = RootCertStore::empty();
client_root_cert_store.add_parsable_certificates(load_certs(cafile));

let client_config = client_config.with_root_certificates(client_root_cert_store);

if config.server_key.is_some() || config.server_cert_chain.is_some() {
let certsfile = config
.server_cert_chain
.as_ref()
.expect("must provide client_cert with client_key");

let keyfile = config
.server_key
.as_ref()
.expect("must provide client_key with client_cert");

let mut certs = load_certs(certsfile);
let cacerts = load_certs(cafile);
let privkey = load_private_key(keyfile);

// Specially for server.crt not a cert-chain only one server certificate, so manually make
// a cert-chain.
if certs.len() == 1 && !cacerts.is_empty() {
certs.extend(cacerts);
}

client_config.with_client_auth_cert(certs, privkey).unwrap()
} else {
client_config.with_no_client_auth()
}
}
2 changes: 1 addition & 1 deletion yamux/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "tokio-yamux"
version = "0.3.9"
version = "0.3.10"
license = "MIT"
repository = "https://github.com/nervosnetwork/tentacle"
description = "Rust implementation of Yamux"
Expand Down
2 changes: 1 addition & 1 deletion yamux/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -741,7 +741,7 @@ mod timer {
}

fn size_hint(&self) -> (usize, Option<usize>) {
(std::usize::MAX, None)
(usize::MAX, None)
}
}

Expand Down
30 changes: 12 additions & 18 deletions yamux/src/stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -334,15 +334,12 @@ impl StreamHandle {
return Poll::Ready(Ok(0));
}

if let Err(e) = self.recv_frames(cx) {
match e {
// read flag error or read data error
Error::UnexpectedFlag | Error::RecvWindowExceeded | Error::InvalidMsgType => {
self.send_go_away();
return Poll::Ready(Err(io::ErrorKind::InvalidData.into()));
}
_ => (),
}
if let Err(Error::UnexpectedFlag | Error::RecvWindowExceeded | Error::InvalidMsgType) =
self.recv_frames(cx)
{
// read flag error or read data error
self.send_go_away();
return Poll::Ready(Err(io::ErrorKind::InvalidData.into()));
}

if self.check_self_state()? {
Expand Down Expand Up @@ -385,15 +382,12 @@ impl AsyncRead for StreamHandle {
return Poll::Ready(Ok(()));
}

if let Err(e) = self.recv_frames(cx) {
match e {
// read flag error or read data error
Error::UnexpectedFlag | Error::RecvWindowExceeded | Error::InvalidMsgType => {
self.send_go_away();
return Poll::Ready(Err(io::ErrorKind::InvalidData.into()));
}
_ => (),
}
if let Err(Error::UnexpectedFlag | Error::RecvWindowExceeded | Error::InvalidMsgType) =
self.recv_frames(cx)
{
// read flag error or read data error
self.send_go_away();
return Poll::Ready(Err(io::ErrorKind::InvalidData.into()));
}

if self.check_self_state()? {
Expand Down

0 comments on commit bb06c4c

Please sign in to comment.