diff options
Diffstat (limited to 'libtransport/includes/hicn/transport')
85 files changed, 1366 insertions, 806 deletions
diff --git a/libtransport/includes/hicn/transport/CMakeLists.txt b/libtransport/includes/hicn/transport/CMakeLists.txt index eb339fb5a..8b9f907b9 100644 --- a/libtransport/includes/hicn/transport/CMakeLists.txt +++ b/libtransport/includes/hicn/transport/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2020 Cisco and/or its affiliates. +# Copyright (c) 2021-2022 Cisco and/or its affiliates. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at: @@ -23,14 +23,21 @@ add_subdirectory(portability) add_subdirectory(auth) add_subdirectory(utils) -set(LIBTRANSPORT_INCLUDE_DIRS - ${CMAKE_CURRENT_SOURCE_DIR}/../.. "" + +############################################################## +# Public headers directory +############################################################## +set(Libhicntransport_INCLUDE_DIRS + ${CMAKE_CURRENT_SOURCE_DIR}/../.. CACHE INTERNAL "" FORCE ) + +############################################################## +# Header files to install +############################################################## set(LIBHICNTRANSPORT_TO_INSTALL_HEADER_FILES - ${HEADER_FILES} "" - CACHE INTERNAL - "" FORCE + ${HEADER_FILES} + PARENT_SCOPE ) diff --git a/libtransport/includes/hicn/transport/auth/CMakeLists.txt b/libtransport/includes/hicn/transport/auth/CMakeLists.txt index 1e9fe4698..0b5ae1836 100644 --- a/libtransport/includes/hicn/transport/auth/CMakeLists.txt +++ b/libtransport/includes/hicn/transport/auth/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2019 Cisco and/or its affiliates. +# Copyright (c) 2021 Cisco and/or its affiliates. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at: @@ -15,7 +15,6 @@ list(APPEND HEADER_FILES ${CMAKE_CURRENT_SOURCE_DIR}/common.h ${CMAKE_CURRENT_SOURCE_DIR}/crypto_hash.h ${CMAKE_CURRENT_SOURCE_DIR}/crypto_suite.h - ${CMAKE_CURRENT_SOURCE_DIR}/identity.h ${CMAKE_CURRENT_SOURCE_DIR}/key_id.h ${CMAKE_CURRENT_SOURCE_DIR}/policies.h ${CMAKE_CURRENT_SOURCE_DIR}/signer.h diff --git a/libtransport/includes/hicn/transport/auth/common.h b/libtransport/includes/hicn/transport/auth/common.h index fb0e82eb7..d2282436e 100644 --- a/libtransport/includes/hicn/transport/auth/common.h +++ b/libtransport/includes/hicn/transport/auth/common.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: diff --git a/libtransport/includes/hicn/transport/auth/crypto_hash.h b/libtransport/includes/hicn/transport/auth/crypto_hash.h index 90f1627e9..9535e07c7 100644 --- a/libtransport/includes/hicn/transport/auth/crypto_hash.h +++ b/libtransport/includes/hicn/transport/auth/crypto_hash.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: @@ -27,8 +27,6 @@ extern "C" { namespace transport { namespace auth { -typedef const EVP_MD *(*CryptoHashEVP)(void); - enum class CryptoHashType : uint8_t { UNKNOWN, SHA256, @@ -42,7 +40,7 @@ class CryptoHash { // Constructors CryptoHash(); CryptoHash(const CryptoHash &other); - CryptoHash(CryptoHash &&other); + CryptoHash(CryptoHash &&other) noexcept; CryptoHash(CryptoHashType hash_type); CryptoHash(const uint8_t *hash, std::size_t size, CryptoHashType hash_type); CryptoHash(const std::vector<uint8_t> &hash, CryptoHashType hash_type); @@ -57,12 +55,10 @@ class CryptoHash { // Compute the hash of given buffer void computeDigest(const uint8_t *buffer, std::size_t len); void computeDigest(const std::vector<uint8_t> &buffer); - - // Compute the hash of given membuf void computeDigest(const utils::MemBuf *buffer); // Return the computed hash - std::vector<uint8_t> getDigest() const; + const utils::MemBuf::Ptr &getDigest() const; // Return the computed hash as a string std::string getStringDigest() const; @@ -82,19 +78,19 @@ class CryptoHash { // Reset hash void reset(); - // Return OpenSSL EVP function associated to a given hash type - static CryptoHashEVP getEVP(CryptoHashType hash_type); + // Return the OpenSSL EVP_MD pointer associated to a given hash type + static const EVP_MD *getMD(CryptoHashType hash_type); // Return hash size static std::size_t getSize(CryptoHashType hash_type); // Compare two raw buffers - static bool compareDigest(const uint8_t *h1, const uint8_t *h2, + static bool compareDigest(const uint8_t *digest1, const uint8_t *digest2, CryptoHashType hash_type); private: CryptoHashType digest_type_; - std::vector<uint8_t> digest_; + utils::MemBuf::Ptr digest_; std::size_t digest_size_; }; diff --git a/libtransport/includes/hicn/transport/auth/crypto_suite.h b/libtransport/includes/hicn/transport/auth/crypto_suite.h index d0f1de395..f3b535264 100644 --- a/libtransport/includes/hicn/transport/auth/crypto_suite.h +++ b/libtransport/includes/hicn/transport/auth/crypto_suite.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: @@ -26,29 +26,36 @@ namespace auth { enum class CryptoSuite : uint8_t { UNKNOWN, + DSA_BLAKE2B512, + DSA_BLAKE2S256, + DSA_SHA256, + DSA_SHA512, ECDSA_BLAKE2B512, ECDSA_BLAKE2S256, ECDSA_SHA256, ECDSA_SHA512, - RSA_BLAKE2B512, - RSA_BLAKE2S256, - RSA_SHA256, - RSA_SHA512, + ED25519, + ED448, HMAC_BLAKE2B512, HMAC_BLAKE2S256, HMAC_SHA256, HMAC_SHA512, - DSA_BLAKE2B512, - DSA_BLAKE2S256, - DSA_SHA256, - DSA_SHA512, + RSA_BLAKE2B512, + RSA_BLAKE2S256, + RSA_SHA256, + RSA_SHA512, }; // Return the suite associated to the given NID CryptoSuite getSuite(int nid); +// Return the string representation of given suite +std::string getStringSuite(CryptoSuite suite); + // Return the hash type associated to the given suite CryptoHashType getHashType(CryptoSuite suite); +// Return the OpenSSL EVP_MD pointer associated to a given suite +const EVP_MD *getMD(CryptoSuite suite); } // namespace auth } // namespace transport diff --git a/libtransport/includes/hicn/transport/auth/identity.h b/libtransport/includes/hicn/transport/auth/identity.h deleted file mode 100644 index be072f5d3..000000000 --- a/libtransport/includes/hicn/transport/auth/identity.h +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (c) 2017-2021 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include <errno.h> -#include <fcntl.h> -#include <hicn/transport/auth/signer.h> -#include <unistd.h> - -extern "C" { -#include <openssl/pkcs12.h> -#include <openssl/rand.h> -#include <openssl/x509.h> -#include <openssl/x509v3.h> -} - -namespace transport { -namespace auth { - -class Identity { - // This class holds several information about a client, including its public - // key. - public: - // Generate a new identity from the given parameters. The identity will be - // saved in 'keystore_path' and encrypted using 'keystore_pwd'. - Identity(const std::string &keystore_path, const std::string &keystore_pwd, - CryptoSuite suite, unsigned int signature_len, - unsigned int validity_days, const std::string &subject_name); - - // Create an identity from an already existing keystore path. - Identity(std::string &keystore_path, std::string &keystore_pwd, - CryptoHashType hash_type); - - Identity(const Identity &other); - Identity(Identity &&other); - ~Identity(); - - // Return the asymmetric signer object created from the public key. - std::shared_ptr<AsymmetricSigner> getSigner() const; - - // Return the key store filename. - std::string getFilename() const; - - // Return the key store password. - std::string getPassword() const; - - std::shared_ptr<X509> getCertificate() const; - - std::shared_ptr<EVP_PKEY> getPrivateKey() const; - - // Generate a new random identity. - static Identity generateIdentity(const std::string &subject_name = ""); - - private: - static void free_key(EVP_PKEY *T) { EVP_PKEY_free(T); } - - std::string pwd_; - std::string filename_; - std::shared_ptr<AsymmetricSigner> signer_; - std::shared_ptr<X509> cert_; -}; - -} // namespace auth -} // namespace transport diff --git a/libtransport/includes/hicn/transport/auth/key_id.h b/libtransport/includes/hicn/transport/auth/key_id.h index 3aa09336f..8723ae698 100644 --- a/libtransport/includes/hicn/transport/auth/key_id.h +++ b/libtransport/includes/hicn/transport/auth/key_id.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: diff --git a/libtransport/includes/hicn/transport/auth/policies.h b/libtransport/includes/hicn/transport/auth/policies.h index 00464d54b..b9755595c 100644 --- a/libtransport/includes/hicn/transport/auth/policies.h +++ b/libtransport/includes/hicn/transport/auth/policies.h @@ -23,10 +23,10 @@ namespace auth { * perform after verification. */ enum class VerificationPolicy { + UNKNOWN, ABORT, - ACCEPT, DROP, - UNKNOWN, + ACCEPT, }; } // namespace auth diff --git a/libtransport/includes/hicn/transport/auth/signer.h b/libtransport/includes/hicn/transport/auth/signer.h index 405dd83cf..f9e07efae 100644 --- a/libtransport/includes/hicn/transport/auth/signer.h +++ b/libtransport/includes/hicn/transport/auth/signer.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2021 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: @@ -21,18 +21,19 @@ #include <hicn/transport/errors/errors.h> #include <hicn/transport/utils/membuf.h> +#include <memory> extern "C" { #include <openssl/evp.h> #include <openssl/hmac.h> +#include <openssl/pkcs12.h> +#include <openssl/x509.h> } namespace transport { namespace auth { -class Identity; class Signer { // The base class from which all signer classes derive. - friend class Identity; public: Signer(); @@ -41,11 +42,15 @@ class Signer { // Sign a packet. virtual void signPacket(PacketPtr packet); + virtual void signBuffer(const uint8_t *buffer, std::size_t len); virtual void signBuffer(const std::vector<uint8_t> &buffer); virtual void signBuffer(const utils::MemBuf *buffer); // Return the signature. - std::vector<uint8_t> getSignature() const; + const utils::MemBuf::Ptr &getSignature() const; + + // Return the signature as a string. + std::string getStringSignature() const; // Return the signature size in bytes. virtual std::size_t getSignatureSize() const; @@ -61,9 +66,12 @@ class Signer { // Return the hash algorithm associated to the signer. CryptoHashType getHashType() const; + // Print signature to stdout. + void display(); + protected: CryptoSuite suite_; - std::vector<uint8_t> signature_; + utils::MemBuf::Ptr signature_; std::size_t signature_len_; std::shared_ptr<EVP_PKEY> key_; CryptoHash key_id_; @@ -75,6 +83,7 @@ class VoidSigner : public Signer { VoidSigner() = default; void signPacket(PacketPtr packet) override; + void signBuffer(const uint8_t *buffer, std::size_t len) override; void signBuffer(const std::vector<uint8_t> &buffer) override; void signBuffer(const utils::MemBuf *buffer) override; }; @@ -84,10 +93,17 @@ class AsymmetricSigner : public Signer { public: AsymmetricSigner() = default; - // Construct an AsymmetricSigner from a key store and a given crypto suite. + // Create an AsymmetricSigner from a keystore file (.p12). + AsymmetricSigner(std::string keystore_path, std::string password); + + // Construct an AsymmetricSigner from a key store and a given crypto + // suite. AsymmetricSigner(CryptoSuite suite, std::shared_ptr<EVP_PKEY> key, std::shared_ptr<EVP_PKEY> pub_key); + void setKey(CryptoSuite suite, std::shared_ptr<EVP_PKEY> key, + std::shared_ptr<EVP_PKEY> pub_key); + std::size_t getSignatureFieldSize() const override; }; diff --git a/libtransport/includes/hicn/transport/auth/verifier.h b/libtransport/includes/hicn/transport/auth/verifier.h index 6321d4ed5..2e086df4f 100644 --- a/libtransport/includes/hicn/transport/auth/verifier.h +++ b/libtransport/includes/hicn/transport/auth/verifier.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2021 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: @@ -40,9 +40,9 @@ class Verifier { // The VerificationFailedCallback will be called by the transport if a // data packet (either a manifest or a content object) was not validated. // The application decides what to do then by returning a - // VerificationPolicy object. + // new VerificationPolicy. using VerificationFailedCallback = std::function<auth::VerificationPolicy( - const core::ContentObject &content_object, std::error_code ec)>; + Suffix suffix, VerificationPolicy policy)>; // The list of VerificationPolicy that will trigger the // VerificationFailedCallback. @@ -54,12 +54,15 @@ class Verifier { // Verify a single packet or buffer. virtual bool verifyPacket(PacketPtr packet); + virtual bool verifyBuffer(const uint8_t *buffer, std::size_t len, + const utils::MemBuf::Ptr &signature, + CryptoSuite suite) = 0; virtual bool verifyBuffer(const std::vector<uint8_t> &buffer, - const std::vector<uint8_t> &signature, - CryptoHashType hash_type) = 0; + const utils::MemBuf::Ptr &signature, + CryptoSuite suite) = 0; virtual bool verifyBuffer(const utils::MemBuf *buffer, - const std::vector<uint8_t> &signature, - CryptoHashType hash_type) = 0; + const utils::MemBuf::Ptr &signature, + CryptoSuite suite) = 0; // Verify a batch of packets. Return a mapping from packet suffixes to their // VerificationPolicy. @@ -96,13 +99,13 @@ class Verifier { void getVerificationFailedCallback( VerificationFailedCallback **verification_failed_cb); + // Call VerificationFailedCallback if it is set and update the packet policy. + void callVerificationFailedCallback(Suffix suffix, + VerificationPolicy &policy); + protected: VerificationFailedCallback verification_failed_cb_; std::vector<VerificationPolicy> failed_policies_; - - // Call VerificationFailedCallback if it is set and update the packet policy. - void callVerificationFailedCallback(PacketPtr packet, - VerificationPolicy &policy); }; class VoidVerifier : public Verifier { @@ -110,12 +113,15 @@ class VoidVerifier : public Verifier { // and always returns true. public: bool verifyPacket(PacketPtr packet) override; + bool verifyBuffer(const uint8_t *buffer, std::size_t len, + const utils::MemBuf::Ptr &signature, + CryptoSuite suite) override; bool verifyBuffer(const std::vector<uint8_t> &buffer, - const std::vector<uint8_t> &signature, - CryptoHashType hash_type) override; + const utils::MemBuf::Ptr &signature, + CryptoSuite suite) override; bool verifyBuffer(const utils::MemBuf *buffer, - const std::vector<uint8_t> &signature, - CryptoHashType hash_type) override; + const utils::MemBuf::Ptr &signature, + CryptoSuite suite) override; PolicyMap verifyPackets(const std::vector<PacketPtr> &packets) override; @@ -143,12 +149,15 @@ class AsymmetricVerifier : public Verifier { void useCertificate(const std::string &cert_path); void useCertificate(std::shared_ptr<X509> cert); + bool verifyBuffer(const uint8_t *buffer, std::size_t len, + const utils::MemBuf::Ptr &signature, + CryptoSuite suite) override; bool verifyBuffer(const std::vector<uint8_t> &buffer, - const std::vector<uint8_t> &signature, - CryptoHashType hash_type) override; + const utils::MemBuf::Ptr &signature, + CryptoSuite suite) override; bool verifyBuffer(const utils::MemBuf *buffer, - const std::vector<uint8_t> &signature, - CryptoHashType hash_type) override; + const utils::MemBuf::Ptr &signature, + CryptoSuite suite) override; private: std::shared_ptr<EVP_PKEY> key_; @@ -166,12 +175,15 @@ class SymmetricVerifier : public Verifier { // Create and set a symmetric key from a passphrase. void setPassphrase(const std::string &passphrase); + bool verifyBuffer(const uint8_t *buffer, std::size_t len, + const utils::MemBuf::Ptr &signature, + CryptoSuite suite) override; bool verifyBuffer(const std::vector<uint8_t> &buffer, - const std::vector<uint8_t> &signature, - CryptoHashType hash_type) override; + const utils::MemBuf::Ptr &signature, + CryptoSuite suite) override; bool verifyBuffer(const utils::MemBuf *buffer, - const std::vector<uint8_t> &signature, - CryptoHashType hash_type) override; + const utils::MemBuf::Ptr &signature, + CryptoSuite suite) override; protected: std::shared_ptr<EVP_PKEY> key_; diff --git a/libtransport/includes/hicn/transport/core/CMakeLists.txt b/libtransport/includes/hicn/transport/core/CMakeLists.txt index 14c795a7a..34048d93a 100644 --- a/libtransport/includes/hicn/transport/core/CMakeLists.txt +++ b/libtransport/includes/hicn/transport/core/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2019 Cisco and/or its affiliates. +# Copyright (c) 2021 Cisco and/or its affiliates. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at: diff --git a/libtransport/includes/hicn/transport/core/asio_wrapper.h b/libtransport/includes/hicn/transport/core/asio_wrapper.h index 78cad35dc..41b660587 100644 --- a/libtransport/includes/hicn/transport/core/asio_wrapper.h +++ b/libtransport/includes/hicn/transport/core/asio_wrapper.h @@ -23,6 +23,9 @@ TRANSPORT_CLANG_DISABLE_WARNING("-Wdeprecated-declarations") #ifndef ASIO_STANDALONE #define ASIO_STANDALONE #endif +#ifdef __APPLE__ +TRANSPORT_CLANG_DISABLE_WARNING("-Wshorten-64-to-32") +#endif #include <asio.hpp> TRANSPORT_POP_WARNING diff --git a/libtransport/includes/hicn/transport/core/connector.h b/libtransport/includes/hicn/transport/core/connector.h index dcf38cdc8..7882b285d 100644 --- a/libtransport/includes/hicn/transport/core/connector.h +++ b/libtransport/includes/hicn/transport/core/connector.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Cisco and/or its affiliates. + * Copyright (c) 2021-2022 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: @@ -15,6 +15,7 @@ #pragma once +#include <glog/logging.h> #include <hicn/transport/core/connector_stats.h> #include <hicn/transport/core/content_object.h> #include <hicn/transport/core/endpoint.h> @@ -29,6 +30,7 @@ #include <deque> #include <functional> +#include <system_error> namespace transport { @@ -50,54 +52,51 @@ class Connector : public std::enable_shared_from_this<Connector> { enum class Role : std::uint8_t { CONSUMER, PRODUCER }; - public: static constexpr std::size_t queue_size = 4096; static constexpr std::uint32_t invalid_connector = ~0; - -#ifdef LINUX + static constexpr std::uint32_t max_reconnection_reattempts = 5; static constexpr std::uint16_t max_burst = 256; -#endif using Ptr = std::shared_ptr<Connector>; - using PacketQueue = std::deque<Packet::Ptr>; + using ReceptionBuffer = std::vector<utils::MemBuf::Ptr>; + using PacketQueue = std::deque<utils::MemBuf::Ptr>; using PacketReceivedCallback = std::function<void( - Connector *, utils::MemBuf &, const std::error_code &)>; + Connector *, const ReceptionBuffer &, const std::error_code &)>; using PacketSentCallback = std::function<void(Connector *, const std::error_code &)>; using OnCloseCallback = std::function<void(Connector *)>; - using OnReconnectCallback = std::function<void(Connector *)>; + using OnReconnectCallback = + std::function<void(Connector *, const std::error_code &)>; using Id = std::uint64_t; template <typename ReceiveCallback, typename SentCallback, typename OnClose, typename OnReconnect> Connector(ReceiveCallback &&receive_callback, SentCallback &&packet_sent, OnClose &&close_callback, OnReconnect &&on_reconnect) - : receive_callback_(std::forward<ReceiveCallback &&>(receive_callback)), - sent_callback_(std::forward<SentCallback &&>(packet_sent)), - on_close_callback_(std::forward<OnClose &&>(close_callback)), - on_reconnect_callback_(std::forward<OnReconnect &&>(on_reconnect)), - state_(State::CLOSED), - connector_id_(invalid_connector) {} + : receive_callback_(std::forward<ReceiveCallback>(receive_callback)), + sent_callback_(std::forward<SentCallback>(packet_sent)), + on_close_callback_(std::forward<OnClose>(close_callback)), + on_reconnect_callback_(std::forward<OnReconnect>(on_reconnect)) {} virtual ~Connector(){}; template <typename ReceiveCallback> void setReceiveCallback(ReceiveCallback &&callback) { - receive_callback_ = std::forward<ReceiveCallback &&>(callback); + receive_callback_ = std::forward<ReceiveCallback>(callback); } template <typename SentCallback> void setSentCallback(SentCallback &&callback) { - sent_callback_ = std::forward<SentCallback &&>(callback); + sent_callback_ = std::forward<SentCallback>(callback); } template <typename OnClose> void setOnCloseCallback(OnClose &&callback) { - on_close_callback_ = std::forward<OnClose &&>(callback); + on_close_callback_ = std::forward<OnClose>(callback); } template <typename OnReconnect> - void setReconnectCallback(const OnReconnect &&callback) { + void setReconnectCallback(OnReconnect &&callback) { on_reconnect_callback_ = std::forward<OnReconnect>(callback); } @@ -115,7 +114,15 @@ class Connector : public std::enable_shared_from_this<Connector> { virtual void send(Packet &packet) = 0; - virtual void send(const uint8_t *packet, std::size_t len) = 0; + virtual void send(const utils::MemBuf::Ptr &buffer) = 0; + + virtual void receive(const std::vector<utils::MemBuf::Ptr> &buffers) { + receive_callback_(this, buffers, std::make_error_code(std::errc())); + } + + virtual void reconnect() { + on_reconnect_callback_(this, std::make_error_code(std::errc())); + } virtual void close() = 0; @@ -127,36 +134,48 @@ class Connector : public std::enable_shared_from_this<Connector> { Id getConnectorId() { return connector_id_; } - void setConnectorName(std::string connector_name) { + void setConnectorName(const std::string &connector_name) { connector_name_ = connector_name; } - std::string getConnectorName() { return connector_name_; } + std::string getConnectorName() const { return connector_name_; } + + template <typename EP> + void setLocalEndpoint(EP &&endpoint) { + local_endpoint_ = std::forward<EP>(endpoint); + } - Endpoint getLocalEndpoint() { return local_endpoint_; } + Endpoint getLocalEndpoint() const { return local_endpoint_; } - Endpoint getRemoteEndpoint() { return remote_endpoint_; } + Endpoint getRemoteEndpoint() const { return remote_endpoint_; } void setRole(Role r) { role_ = r; } - Role getRole() { return role_; } + Role getRole() const { return role_; } static utils::MemBuf::Ptr getPacketFromBuffer(uint8_t *buffer, std::size_t size) { utils::MemBuf::Ptr ret; - auto format = Packet::getFormatFromBuffer(buffer, size); + hicn_packet_buffer_t pkbuf; + hicn_packet_set_buffer(&pkbuf, buffer, size, size); + hicn_packet_analyze(&pkbuf); + hicn_packet_type_t type = hicn_packet_get_type(&pkbuf); - if (TRANSPORT_EXPECT_TRUE(format != HF_UNSPEC && !_is_icmp(format))) { - if (Packet::isInterest(buffer)) { + // XXX reuse pkbuf when creating the packet, to avoid reanalyzing it + + switch (type) { + case HICN_PACKET_TYPE_INTEREST: ret = core::PacketManager<>::getInstance() .getPacketFromExistingBuffer<Interest>(buffer, size); - } else { + break; + case HICN_PACKET_TYPE_DATA: ret = core::PacketManager<>::getInstance() .getPacketFromExistingBuffer<ContentObject>(buffer, size); - } - } else { - ret = core::PacketManager<>::getInstance().getMemBuf(buffer, size); + break; + default: + ret = core::PacketManager<>::getInstance().getMemBuf(buffer, size); + break; } return ret; @@ -191,8 +210,8 @@ class Connector : public std::enable_shared_from_this<Connector> { OnReconnectCallback on_reconnect_callback_; // Connector state - std::atomic<State> state_; - Id connector_id_; + std::atomic<State> state_ = State::CLOSED; + Id connector_id_ = invalid_connector; // Endpoints Endpoint local_endpoint_; @@ -206,6 +225,9 @@ class Connector : public std::enable_shared_from_this<Connector> { // Stats AtomicConnectorStats stats_; + + // Connection attempts + std::uint32_t connection_reattempts_ = 0; }; } // namespace core diff --git a/libtransport/includes/hicn/transport/core/content_object.h b/libtransport/includes/hicn/transport/core/content_object.h index 38baafc69..3d6d98c48 100644 --- a/libtransport/includes/hicn/transport/core/content_object.h +++ b/libtransport/includes/hicn/transport/core/content_object.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021-2022 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: @@ -29,41 +29,37 @@ namespace core { class ContentObject : public Packet { public: using Ptr = std::shared_ptr<ContentObject>; - using HICNContentObject = hicn_header_t; + using HICNContentObject = u8; - ContentObject(Packet::Format format = HF_INET6_TCP, - std::size_t additional_header_size = 0); + ContentObject(Packet::Format format, std::size_t additional_header_size = 0); - ContentObject(const Name &name, Packet::Format format = HF_INET6_TCP, + ContentObject(const Name &name, Packet::Format format, std::size_t additional_header_size = 0); - ContentObject(const Name &name, hicn_format_t format, + ContentObject(const Name &name, hicn_packet_format_t format, std::size_t additional_header_size, const uint8_t *payload, std::size_t payload_size); template <typename... Args> - ContentObject(CopyBufferOp op, Args &&... args) + ContentObject(CopyBufferOp op, Args &&...args) : Packet(op, std::forward<Args>(args)...) { - if (hicn_data_get_name(format_, packet_start_, name_.getStructReference()) < - 0) { + if (hicn_data_get_name(&pkbuf_, &name_.getStructReference()) < 0) { throw errors::MalformedPacketException(); } } template <typename... Args> - ContentObject(WrapBufferOp op, Args &&... args) + ContentObject(WrapBufferOp op, Args &&...args) : Packet(op, std::forward<Args>(args)...) { - if (hicn_data_get_name(format_, packet_start_, name_.getStructReference()) < - 0) { + if (hicn_data_get_name(&pkbuf_, &name_.getStructReference()) < 0) { throw errors::MalformedPacketException(); } } template <typename... Args> - ContentObject(CreateOp op, Args &&... args) - : Packet(op, std::forward<Args>(args)...) { - if (hicn_data_get_name(format_, packet_start_, name_.getStructReference()) < - 0) { + ContentObject(CreateOp op, Args &&...args) + : Packet(op, HICN_PACKET_TYPE_DATA, std::forward<Args>(args)...) { + if (hicn_data_get_name(&pkbuf_, &name_.getStructReference()) < 0) { throw errors::MalformedPacketException(); } } @@ -82,13 +78,13 @@ class ContentObject : public Packet { void setName(const Name &name) override; - uint32_t getPathLabel() const; + hicn_path_label_t getPathLabel() const; - ContentObject &setPathLabel(uint32_t path_label); + ContentObject &setPathLabel(hicn_path_label_t path_label); - void setLocator(const ip_address_t &ip_address) override; + void setLocator(const hicn_ip_address_t &ip_address) override; - ip_address_t getLocator() const override; + hicn_ip_address_t getLocator() const override; void setLifetime(uint32_t lifetime) override; @@ -96,6 +92,10 @@ class ContentObject : public Packet { auto shared_from_this() { return utils::shared_from(this); } + bool isLast() const; + + void setLast(); + private: void resetForHash() override; }; diff --git a/libtransport/includes/hicn/transport/core/endpoint.h b/libtransport/includes/hicn/transport/core/endpoint.h index cb6b0f562..2278a1759 100644 --- a/libtransport/includes/hicn/transport/core/endpoint.h +++ b/libtransport/includes/hicn/transport/core/endpoint.h @@ -42,22 +42,28 @@ class Endpoint { ~Endpoint() = default; Endpoint &operator=(const Endpoint &other) { - address_ = other.address_; - port_ = other.port_; + if (this != &other) { + address_ = other.address_; + port_ = other.port_; + } + return *this; } Endpoint &operator=(Endpoint &&other) { - address_ = std::move(other.address_); - port_ = std::move(other.port_); + if (this != &other) { + address_ = std::move(other.address_); + port_ = std::move(other.port_); + } + return *this; } #if 0 template <typename Ip, typename Port> Endpoint(Ip &&ip_address, Port &&port) - : address_(std::forward<Ip &&>(ip_address)), - port_(std::forward<Port &&>(port)) {} + : address_(std::forward<Ip>(ip_address)), + port_(std::forward<Port>(port)) {} #endif asio::ip::address getAddress() { return address_; } diff --git a/libtransport/includes/hicn/transport/core/global_object_pool.h b/libtransport/includes/hicn/transport/core/global_object_pool.h index d7f3a9e41..f98df521f 100644 --- a/libtransport/includes/hicn/transport/core/global_object_pool.h +++ b/libtransport/includes/hicn/transport/core/global_object_pool.h @@ -27,9 +27,10 @@ namespace transport { namespace core { template <std::size_t packet_pool_size = 1024, std::size_t chunk_size = 2048> -class PacketManager - : public utils::Singleton<PacketManager<packet_pool_size, chunk_size>> { - friend class utils::Singleton<PacketManager<packet_pool_size, chunk_size>>; +class PacketManager : public utils::ThreadLocalSingleton< + PacketManager<packet_pool_size, chunk_size>> { + friend class utils::ThreadLocalSingleton< + PacketManager<packet_pool_size, chunk_size>>; public: using MemoryPool = utils::FixedBlockAllocator<chunk_size, packet_pool_size>; @@ -71,7 +72,10 @@ class PacketManager template < typename PacketType, typename... Args, typename = std::enable_if_t<std::is_base_of<Packet, PacketType>::value>> - typename PacketType::Ptr getPacket(Args &&... args) { + typename PacketType::Ptr getPacket(Args &&...args) { + static_assert(sizeof(PacketType) + sizeof(std::shared_ptr<PacketType>) + + sizeof(std::max_align_t) <= + sizeof(PacketStorage::packet_and_shared_ptr)); PacketType *memory = nullptr; memory = reinterpret_cast<PacketType *>(memory_pool_.allocateBlock()); @@ -98,7 +102,7 @@ class PacketManager template <typename PacketType, typename... Args> typename PacketType::Ptr getPacketFromExistingBuffer(uint8_t *buffer, std::size_t length, - Args &&... args) { + Args &&...args) { auto offset = offsetof(PacketStorage, align); auto memory = reinterpret_cast<PacketType *>(buffer - offset); utils::STLAllocator<PacketType, MemoryPool> allocator(memory, diff --git a/libtransport/includes/hicn/transport/core/interest.h b/libtransport/includes/hicn/transport/core/interest.h index a5b9cf375..270ea7027 100644 --- a/libtransport/includes/hicn/transport/core/interest.h +++ b/libtransport/includes/hicn/transport/core/interest.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021-2022 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: @@ -21,6 +21,10 @@ #include <set> +extern "C" { +#include <hicn/interest_manifest.h> +} + namespace transport { namespace core { @@ -29,46 +33,35 @@ const uint32_t MAX_AGGREGATED_INTEREST = 128; class Interest : public Packet /*, public std::enable_shared_from_this<Interest>*/ { - private: - struct InterestManifestHeader { - /* This can be 16 bits, but we use 32 bits for alignment */ - uint32_t n_suffixes; - /* Followed by the list of prefixes to ask */ - /* ... */ - }; - public: using Ptr = std::shared_ptr<Interest>; - Interest(Packet::Format format = HF_INET6_TCP, - std::size_t additional_header_size = 0); + Interest(Packet::Format format, std::size_t additional_header_size = 0); - Interest(const Name &interest_name, Packet::Format format = HF_INET6_TCP, + Interest(const Name &interest_name, Packet::Format format, std::size_t additional_header_size = 0); Interest(MemBuf &&buffer); template <typename... Args> - Interest(CopyBufferOp op, Args &&... args) + Interest(CopyBufferOp op, Args &&...args) : Packet(op, std::forward<Args>(args)...) { - if (hicn_interest_get_name(format_, packet_start_, - name_.getStructReference()) < 0) { + if (hicn_interest_get_name(&pkbuf_, &name_.getStructReference()) < 0) { throw errors::MalformedPacketException(); } } template <typename... Args> - Interest(WrapBufferOp op, Args &&... args) + Interest(WrapBufferOp op, Args &&...args) : Packet(op, std::forward<Args>(args)...) { - if (hicn_interest_get_name(format_, packet_start_, - name_.getStructReference()) < 0) { + if (hicn_interest_get_name(&pkbuf_, &name_.getStructReference()) < 0) { throw errors::MalformedPacketException(); } } template <typename... Args> - Interest(CreateOp op, Args &&... args) - : Packet(op, std::forward<Args>(args)...) {} + Interest(CreateOp op, Args &&...args) + : Packet(op, HICN_PACKET_TYPE_INTEREST, std::forward<Args>(args)...) {} /* Move constructor */ Interest(Interest &&other_interest); @@ -87,24 +80,36 @@ class Interest void setName(const Name &name) override; - void setLocator(const ip_address_t &ip_address) override; + void setLocator(const hicn_ip_address_t &ip_address) override; - ip_address_t getLocator() const override; + hicn_ip_address_t getLocator() const override; void setLifetime(uint32_t lifetime) override; uint32_t getLifetime() const override; - bool hasManifest(); + bool hasManifest() const; void appendSuffix(std::uint32_t suffix); void encodeSuffixes(); + void serializeSuffixes(); + + void deserializeSuffixes(); + uint32_t *firstSuffix(); uint32_t numberOfSuffixes(); + hicn_uword *getRequestBitmap(); + + interest_manifest_header_t *getIntManifestHeader(); + + void setRequestBitmap(const uint32_t *request_bitmap); + + bool isValid(); + auto shared_from_this() { return utils::shared_from(this); } private: diff --git a/libtransport/includes/hicn/transport/core/io_module.h b/libtransport/includes/hicn/transport/core/io_module.h index ea3cf4e16..cfaa61975 100644 --- a/libtransport/includes/hicn/transport/core/io_module.h +++ b/libtransport/includes/hicn/transport/core/io_module.h @@ -19,6 +19,7 @@ #include <hicn/transport/core/connector.h> #include <hicn/transport/core/packet.h> #include <hicn/transport/core/prefix.h> +#include <hicn/transport/portability/endianess.h> #include <hicn/transport/portability/portability.h> #include <hicn/transport/utils/chrono_typedefs.h> #include <hicn/transport/utils/membuf.h> @@ -40,7 +41,7 @@ typedef struct { class Connector; -class IoModule { +class IoModule : utils::NonCopyable { protected: IoModule() : inet_address_({}), @@ -48,13 +49,12 @@ class IoModule { mtu_(1500), output_interface_(""), content_store_reserved_(5000) { - inet_address_.v4.as_u32 = htonl(0x7f00001); + inet_address_.v4.as_u32 = portability::host_to_net(0x7f00001); inet6_address_.v6.as_u8[15] = 0x01; } public: static IoModule *load(const char *); - static bool unload(IoModule *); public: virtual ~IoModule(); @@ -64,15 +64,21 @@ class IoModule { virtual bool isConnected() = 0; virtual void init(Connector::PacketReceivedCallback &&receive_callback, + Connector::PacketSentCallback &&sent_callback, + Connector::OnCloseCallback &&close_callback, Connector::OnReconnectCallback &&reconnect_callback, asio::io_service &io_service, const std::string &app_name = "Libtransport") = 0; virtual void registerRoute(const Prefix &prefix) = 0; + virtual void sendMapme() {} + + virtual void setForwardingStrategy(const Prefix &prefix, + std::string &strategy){}; virtual std::uint32_t getMtu() = 0; - virtual bool isControlMessage(const uint8_t *message) = 0; + virtual bool isControlMessage(utils::MemBuf &packet_buffer) = 0; virtual void processControlMessageReply(utils::MemBuf &packet_buffer) = 0; @@ -82,14 +88,14 @@ class IoModule { counters_.tx_packets++; counters_.tx_bytes += packet.payloadSize() + packet.headerSize(); - if (_is_ipv4(packet.getFormat())) { + if (HICN_PACKET_FORMAT_IS_IPV4(packet.getFormat())) { packet.setLocator(inet_address_); } else { packet.setLocator(inet6_address_); } } - virtual void send(const uint8_t *packet, std::size_t len) = 0; + virtual void send(const utils::MemBuf::Ptr &buffer) = 0; void setContentStoreSize(uint32_t cs_size) { content_store_reserved_ = cs_size; @@ -103,14 +109,9 @@ class IoModule { const std::string &getOutputInterface() { return output_interface_; } -#ifndef ANDROID - private: - void *handle_; -#endif - protected: - ip_address_t inet_address_; - ip_address_t inet6_address_; + hicn_ip_address_t inet_address_; + hicn_ip_address_t inet6_address_; uint16_t mtu_; std::string output_interface_; uint32_t content_store_reserved_; diff --git a/libtransport/includes/hicn/transport/core/name.h b/libtransport/includes/hicn/transport/core/name.h index 033582289..14ea10898 100644 --- a/libtransport/includes/hicn/transport/core/name.h +++ b/libtransport/includes/hicn/transport/core/name.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: @@ -46,12 +46,13 @@ class Name { friend class Packet; friend class ContentObject; friend class Interest; + friend class Prefix; static const uint32_t standard_name_string_length = 100; public: using NameStruct = hicn_name_t; - using Type = hicn_name_type_t; + enum class Type { UNDEFINED, V4, V6 }; Name(); @@ -69,6 +70,8 @@ class Name { Name(const Name &name); + ~Name(); + Name &operator=(const Name &name); bool operator==(const Name &name) const; @@ -91,23 +94,22 @@ class Name { uint32_t getSuffix() const; - std::shared_ptr<Sockaddr> getAddress() const; - Name &setSuffix(uint32_t seq_number); - ip_prefix_t toIpAddress() const; + hicn_ip_prefix_t toIpAddress() const; + + std::string getPrefix() const; - void copyToDestination(uint8_t *destination, - bool include_suffix = false) const; + void copyPrefixToDestination(uint8_t *destination) const; int getAddressFamily() const; private: - TRANSPORT_ALWAYS_INLINE const NameStruct *getConstStructReference() const { - return &name_; + TRANSPORT_ALWAYS_INLINE const NameStruct &getConstStructReference() const { + return name_; } - TRANSPORT_ALWAYS_INLINE NameStruct *getStructReference() { return &name_; } + TRANSPORT_ALWAYS_INLINE NameStruct &getStructReference() { return name_; } NameStruct name_; }; diff --git a/libtransport/includes/hicn/transport/core/packet.h b/libtransport/includes/hicn/transport/core/packet.h index 269a1571a..31d856cd5 100644 --- a/libtransport/includes/hicn/transport/core/packet.h +++ b/libtransport/includes/hicn/transport/core/packet.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021-2022 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: @@ -26,15 +26,18 @@ #include <hicn/transport/utils/membuf.h> #include <hicn/transport/utils/object_pool.h> +extern "C" { +#ifndef _WIN32 +TRANSPORT_CLANG_DISABLE_WARNING("-Wextern-c-compat") +#endif +#include <hicn/packet.h> +} + namespace transport { namespace auth { class Signer; -class AsymmetricSigner; -class SymmetricSigner; class Verifier; -class AsymmetricVerifier; -class SymmetricVerifier; } // namespace auth namespace core { @@ -51,16 +54,14 @@ namespace core { class Packet : public utils::MemBuf, public std::enable_shared_from_this<Packet> { friend class auth::Signer; - friend class auth::SymmetricSigner; - friend class auth::AsymmetricSigner; friend class auth::Verifier; - friend class auth::AsymmetricVerifier; - friend class auth::SymmetricVerifier; public: using Ptr = std::shared_ptr<Packet>; using MemBufPtr = std::shared_ptr<utils::MemBuf>; - using Format = hicn_format_t; + using Format = hicn_packet_format_t; + using Type = hicn_packet_type_t; + static constexpr size_t default_mtu = 1500; /** @@ -68,211 +69,120 @@ class Packet : public utils::MemBuf, * the eventual payload will be added by prepending the payload buffer * to the buffer chain whose the fist buffer is the header itself. */ - Packet(Format format = HF_INET6_TCP, std::size_t additional_header_size = 0); - - /** - * Create new IP packet using raw buffer. - */ - + Packet(Type type, Format format, std::size_t additional_header_size = 0); /* Copy buffer */ Packet(CopyBufferOp, const uint8_t *buffer, std::size_t size); /* Wrap buffer */ Packet(WrapBufferOp, uint8_t *buffer, std::size_t length, std::size_t size); /* Create new using pre-allocated buffer */ - Packet(CreateOp, uint8_t *buffer, std::size_t length, std::size_t size, - Format format = HF_INET6_TCP, std::size_t additional_header_size = 0); - /* Move MemBuf */ - Packet(MemBuf &&buffer); + Packet(CreateOp, Type type, uint8_t *buffer, std::size_t length, + std::size_t size, Format format, + std::size_t additional_header_size = 0); + Packet(MemBuf &&buffer); Packet(Packet &&other); - - /* - * Copy constructor and assignemnt operators. - */ Packet(const Packet &other); - Packet &operator=(const Packet &other); - - friend bool operator==(const Packet &l_packet, const Packet &r_packet); + // Destructor virtual ~Packet(); - static std::size_t getHeaderSizeFromFormat(Format format, - std::size_t signature_size = 0) { - std::size_t header_length; - hicn_packet_get_header_length_from_format(format, &header_length); - int is_ah = _is_ah(format); - return is_ah * (header_length + signature_size) + (!is_ah) * header_length; - } - - static std::size_t getHeaderSizeFromBuffer(Format format, - const uint8_t *buffer); - - static std::size_t getPayloadSizeFromBuffer(Format format, - const uint8_t *buffer); - - static bool isInterest(const uint8_t *buffer); - - bool isInterest(); - - static Format getFormatFromBuffer(const uint8_t *buffer, std::size_t length) { - Format format = HF_UNSPEC; - hicn_packet_get_format((const hicn_header_t *)buffer, &format); - return format; - } - - void reset() { - clear(); - packet_start_ = reinterpret_cast<hicn_header_t *>(writableData()); - header_offset_ = 0; - format_ = HF_UNSPEC; - payload_type_ = PayloadType::UNSPECIFIED; - name_.clear(); + // Operators + Packet &operator=(const Packet &other); + friend bool operator==(const Packet &l_packet, const Packet &r_packet); - if (isChained()) { - separateChain(next(), prev()); - } - } + // Cast to MemBuf + std::shared_ptr<utils::MemBuf> acquireMemBufReference(); - void setFormat(Packet::Format format = HF_INET6_TCP, - std::size_t additional_header_size = 0); + // Format + Format getFormat() const; + void setFormat(Packet::Format format); - std::size_t payloadSize() const; + void initialize(std::size_t additional_header_size = 0); + void analyze(); - std::size_t headerSize() const; + void initializeType(Packet::Type type); + hicn_packet_type_t getType() const; + void setType(Packet::Type type); - std::shared_ptr<utils::MemBuf> acquireMemBufReference(); + void setBuffer(); + // Name virtual const Name &getName() const = 0; - virtual Name &getWritableName() = 0; - virtual void setName(const Name &name) = 0; + // Lifetime virtual void setLifetime(uint32_t lifetime) = 0; - virtual uint32_t getLifetime() const = 0; - Packet &appendPayload(const uint8_t *buffer, std::size_t length); + // Locator + virtual void setLocator(const hicn_ip_address_t &locator) = 0; + virtual hicn_ip_address_t getLocator() const = 0; - Packet &appendPayload(std::unique_ptr<utils::MemBuf> &&payload); + // Payload type + PayloadType getPayloadType() const; + Packet &setPayloadType(PayloadType payload_type); + // Payload std::unique_ptr<utils::MemBuf> getPayload() const; + Packet &appendPayload(std::unique_ptr<utils::MemBuf> &&payload); + Packet &appendPayload(const uint8_t *buffer, std::size_t length); - Packet &updateLength(std::size_t length = 0); + // Sizes + std::size_t headerSize() const; + std::size_t payloadSize() const; - PayloadType getPayloadType() const; + // Digest + auth::CryptoHash computeDigest(auth::CryptoHashType algorithm) const; - Packet &setPayloadType(PayloadType payload_type); + bool isInterest(); - Format getFormat() const; + // Reset packet + void reset(); + // Utils + Packet &updateLength(std::size_t length = 0); void dump() const; - static void dump(uint8_t *buffer, std::size_t length); - - virtual void setLocator(const ip_address_t &locator) = 0; - - virtual ip_address_t getLocator() const = 0; - - /** - * @brief Set signature timestamp, in milliseconds. - */ - void setSignatureTimestamp(const uint64_t ×tamp_milliseconds); + // TCP methods + void setChecksum(); + bool checkIntegrity() const; + // Authentication Header methods + bool hasAH() const; + utils::MemBuf::Ptr getSignature() const; + std::size_t getSignatureFieldSize() const; + std::size_t getSignatureSize() const; uint64_t getSignatureTimestamp() const; - - void setValidationAlgorithm(const auth::CryptoSuite &validation_algorithm); - + auth::KeyId getKeyId() const; auth::CryptoSuite getValidationAlgorithm() const; - + void setSignature(const utils::MemBuf::Ptr &signature); + void setSignatureFieldSize(std::size_t size); + void setSignatureSize(std::size_t size); + void setSignatureTimestamp(const uint64_t ×tamp_ms); void setKeyId(const auth::KeyId &key_id); + void setValidationAlgorithm(const auth::CryptoSuite &algo); - auth::KeyId getKeyId() const; - - virtual auth::CryptoHash computeDigest(auth::CryptoHashType algorithm) const; - - void setChecksum() { - uint16_t partial_csum = - csum(data() + HICN_V6_TCP_HDRLEN, length() - HICN_V6_TCP_HDRLEN, 0); - - for (utils::MemBuf *current = next(); current != this; - current = current->next()) { - partial_csum = csum(current->data(), current->length(), ~partial_csum); - } - - if (hicn_packet_compute_header_checksum(format_, packet_start_, - partial_csum) < 0) { - throw errors::MalformedPacketException(); - } - } + void saveHeader(u8 *header, size_t *header_len); + void loadHeader(u8 *header, size_t header_len); - bool checkIntegrity() const; - - Packet &setSyn(); - Packet &resetSyn(); - bool testSyn() const; - Packet &setAck(); - Packet &resetAck(); - bool testAck() const; - Packet &setRst(); - Packet &resetRst(); - bool testRst() const; - Packet &setFin(); - Packet &resetFin(); - bool testFin() const; - Packet &resetFlags(); - std::string printFlags() const; - - Packet &setSrcPort(uint16_t srcPort); - Packet &setDstPort(uint16_t dstPort); - uint16_t getSrcPort() const; - uint16_t getDstPort() const; - - Packet &setTTL(uint8_t hops); - uint8_t getTTL() const; + // Static methods + static Format toAHFormat(const Format &format); + static Format getFormatFromBuffer(const uint8_t *buffer, std::size_t length); + static std::size_t getHeaderSizeFromFormat(Format format, + std::size_t signature_size = 0); + static std::size_t getHeaderSizeFromBuffer(const uint8_t *buffer, + size_t length); + static std::size_t getPayloadSizeFromBuffer(const uint8_t *buffer, + size_t length); + static void dump(uint8_t *buffer, std::size_t length); private: virtual void resetForHash() = 0; - void setSignatureSize(std::size_t size_bytes); - void setSignatureSizeGap(std::size_t size_bytes); void prependPayload(const uint8_t **buffer, std::size_t *size); - bool authenticationHeader() const { return _is_ah(format_); } - - std::size_t getSignatureSize() const { - size_t size_bytes; - int ret = - hicn_packet_get_signature_size(format_, packet_start_, &size_bytes); - - if (ret < 0) { - throw errors::RuntimeException("Packet without Authentication Header."); - } - - return size_bytes; - } - - std::size_t getSignatureSizeGap() const { - uint8_t size_bytes; - int ret = - hicn_packet_get_signature_gap(format_, packet_start_, &size_bytes); - - if (ret < 0) { - throw errors::RuntimeException("Packet without Authentication Header."); - } - - return (size_t)size_bytes; - } - - std::size_t getSignatureSizeReal() const { - return getSignatureSize() - getSignatureSizeGap(); - } - - uint8_t *getSignature() const; - protected: - hicn_header_t *packet_start_; - std::size_t header_offset_; - mutable Format format_; + hicn_packet_buffer_t pkbuf_; Name name_; mutable PayloadType payload_type_; static const core::Name base_name; diff --git a/libtransport/includes/hicn/transport/core/payload_type.h b/libtransport/includes/hicn/transport/core/payload_type.h index 8c918f792..a528500ad 100644 --- a/libtransport/includes/hicn/transport/core/payload_type.h +++ b/libtransport/includes/hicn/transport/core/payload_type.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021-2022 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: @@ -15,6 +15,15 @@ #pragma once +#include <hicn/transport/portability/portability.h> + +extern "C" { +#ifndef _WIN32 +TRANSPORT_CLANG_DISABLE_WARNING("-Wextern-c-compat") +#endif +#include <hicn/base.h> +}; + namespace transport { namespace core { @@ -27,4 +36,4 @@ enum class PayloadType : uint16_t { } // end namespace core -} // end namespace transport
\ No newline at end of file +} // end namespace transport diff --git a/libtransport/includes/hicn/transport/core/prefix.h b/libtransport/includes/hicn/transport/core/prefix.h index 7ef667bc8..791fbc770 100644 --- a/libtransport/includes/hicn/transport/core/prefix.h +++ b/libtransport/includes/hicn/transport/core/prefix.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: @@ -25,16 +25,18 @@ class Prefix { public: Prefix(); - Prefix(const char *prefix); - Prefix(const std::string &prefix); - Prefix(std::string &&prefix); - - Prefix(std::string &prefix, uint16_t prefix_length); + Prefix(const std::string &prefix, uint16_t prefix_length); Prefix(const core::Name &content_name, uint16_t prefix_length); + bool operator<(const Prefix &prefix) const; + + bool operator==(const Prefix &prefix) const; + + bool operator!=(const Prefix &prefix) const { return !operator==(prefix); } + std::unique_ptr<Sockaddr> toSockaddr() const; uint16_t getPrefixLength() const; @@ -43,36 +45,34 @@ class Prefix { std::string getNetwork() const; - int contains(const ip_address_t &content_name) const; + Prefix &setNetwork(const std::string &network); - int contains(const core::Name &content_name) const; + int getAddressFamily() const; - Name getName() const; + bool contains(const hicn_ip_address_t &content_name) const; - Name getRandomName() const; + bool contains(const core::Name &content_name) const; Name getName(const core::Name &mask, const core::Name &components, const core::Name &content_name) const; Name mapName(const core::Name &content_name) const; - Prefix &setNetwork(std::string &network); - - int getAddressFamily() const; - - Prefix &setAddressFamily(int address_family); - + Name makeName() const; Name makeRandomName() const; + Name makeNameWithIndex(std::uint64_t index) const; - const ip_prefix_t &toIpPrefixStruct() const; + const hicn_ip_prefix_t &toIpPrefixStruct() const; private: static bool checkPrefixLengthAndAddressFamily(uint16_t prefix_length, int family); - void buildPrefix(std::string &prefix, uint16_t prefix_length, int family); + void buildPrefix(const std::string &prefix, uint16_t prefix_length, + int family); - ip_prefix_t ip_prefix_; + private: + hicn_ip_prefix_t hicn_ip_prefix_; }; } // end namespace core diff --git a/libtransport/includes/hicn/transport/errors/CMakeLists.txt b/libtransport/includes/hicn/transport/errors/CMakeLists.txt index 1d35c5b34..c8642b51b 100644 --- a/libtransport/includes/hicn/transport/errors/CMakeLists.txt +++ b/libtransport/includes/hicn/transport/errors/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2019 Cisco and/or its affiliates. +# Copyright (c) 2021 Cisco and/or its affiliates. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at: diff --git a/libtransport/includes/hicn/transport/errors/errors.h b/libtransport/includes/hicn/transport/errors/errors.h index b659820fa..09ce97221 100644 --- a/libtransport/includes/hicn/transport/errors/errors.h +++ b/libtransport/includes/hicn/transport/errors/errors.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: diff --git a/libtransport/includes/hicn/transport/errors/indexing_exception.h b/libtransport/includes/hicn/transport/errors/indexing_exception.h index 731314f0e..bdcc39aef 100644 --- a/libtransport/includes/hicn/transport/errors/indexing_exception.h +++ b/libtransport/includes/hicn/transport/errors/indexing_exception.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: diff --git a/libtransport/includes/hicn/transport/errors/invalid_ip_address_exception.h b/libtransport/includes/hicn/transport/errors/invalid_ip_address_exception.h index 60226f576..26e0f98af 100644 --- a/libtransport/includes/hicn/transport/errors/invalid_ip_address_exception.h +++ b/libtransport/includes/hicn/transport/errors/invalid_ip_address_exception.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: diff --git a/libtransport/includes/hicn/transport/errors/malformed_ahpacket_exception.h b/libtransport/includes/hicn/transport/errors/malformed_ahpacket_exception.h index f0cfe0b82..9b3ec7466 100644 --- a/libtransport/includes/hicn/transport/errors/malformed_ahpacket_exception.h +++ b/libtransport/includes/hicn/transport/errors/malformed_ahpacket_exception.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: diff --git a/libtransport/includes/hicn/transport/errors/malformed_name_exception.h b/libtransport/includes/hicn/transport/errors/malformed_name_exception.h index 4ef45d2e8..57412cf7f 100644 --- a/libtransport/includes/hicn/transport/errors/malformed_name_exception.h +++ b/libtransport/includes/hicn/transport/errors/malformed_name_exception.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: diff --git a/libtransport/includes/hicn/transport/errors/malformed_packet_exception.h b/libtransport/includes/hicn/transport/errors/malformed_packet_exception.h index ec5c97e6e..996d6a4ab 100644 --- a/libtransport/includes/hicn/transport/errors/malformed_packet_exception.h +++ b/libtransport/includes/hicn/transport/errors/malformed_packet_exception.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: diff --git a/libtransport/includes/hicn/transport/errors/not_implemented_exception.h b/libtransport/includes/hicn/transport/errors/not_implemented_exception.h index e9869163d..3291fa425 100644 --- a/libtransport/includes/hicn/transport/errors/not_implemented_exception.h +++ b/libtransport/includes/hicn/transport/errors/not_implemented_exception.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: diff --git a/libtransport/includes/hicn/transport/errors/null_pointer_exception.h b/libtransport/includes/hicn/transport/errors/null_pointer_exception.h index bd06485ed..7edb619b8 100644 --- a/libtransport/includes/hicn/transport/errors/null_pointer_exception.h +++ b/libtransport/includes/hicn/transport/errors/null_pointer_exception.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: diff --git a/libtransport/includes/hicn/transport/errors/runtime_exception.h b/libtransport/includes/hicn/transport/errors/runtime_exception.h index ba5128a7e..498c41a7c 100644 --- a/libtransport/includes/hicn/transport/errors/runtime_exception.h +++ b/libtransport/includes/hicn/transport/errors/runtime_exception.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: diff --git a/libtransport/includes/hicn/transport/errors/tokenizer_exception.h b/libtransport/includes/hicn/transport/errors/tokenizer_exception.h index 76eda838e..31f79644a 100644 --- a/libtransport/includes/hicn/transport/errors/tokenizer_exception.h +++ b/libtransport/includes/hicn/transport/errors/tokenizer_exception.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: diff --git a/libtransport/includes/hicn/transport/errors/unexpected_manifest_exception.h b/libtransport/includes/hicn/transport/errors/unexpected_manifest_exception.h index 6f71471e4..c8e4eadd4 100644 --- a/libtransport/includes/hicn/transport/errors/unexpected_manifest_exception.h +++ b/libtransport/includes/hicn/transport/errors/unexpected_manifest_exception.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: diff --git a/libtransport/includes/hicn/transport/http/CMakeLists.txt b/libtransport/includes/hicn/transport/http/CMakeLists.txt index 9f4cdaf39..36a2ca5ce 100644 --- a/libtransport/includes/hicn/transport/http/CMakeLists.txt +++ b/libtransport/includes/hicn/transport/http/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2020 Cisco and/or its affiliates. +# Copyright (c) 2021 Cisco and/or its affiliates. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at: diff --git a/libtransport/includes/hicn/transport/http/client_connection.h b/libtransport/includes/hicn/transport/http/client_connection.h index 7e78e9c59..d5edf6cd0 100644 --- a/libtransport/includes/hicn/transport/http/client_connection.h +++ b/libtransport/includes/hicn/transport/http/client_connection.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2020 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: @@ -31,7 +31,7 @@ namespace http { using namespace interface; using namespace core; -class HTTPClientConnection { +class HTTPClientConnection : private utils::NonCopyable { static constexpr uint32_t max_buffer_capacity = 64 * 1024; public: @@ -39,7 +39,7 @@ class HTTPClientConnection { public: virtual void onBytesReceived(std::unique_ptr<utils::MemBuf> &&buffer) = 0; virtual void onSuccess(std::size_t bytes) = 0; - virtual void onError(const std::error_code ec) = 0; + virtual void onError(const std::error_code &ec) = 0; }; enum class RC : uint32_t { DOWNLOAD_FAILED, DOWNLOAD_SUCCESS }; diff --git a/libtransport/includes/hicn/transport/http/default_values.h b/libtransport/includes/hicn/transport/http/default_values.h index 2d5a6b821..8cf247e19 100644 --- a/libtransport/includes/hicn/transport/http/default_values.h +++ b/libtransport/includes/hicn/transport/http/default_values.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: diff --git a/libtransport/includes/hicn/transport/http/facade.h b/libtransport/includes/hicn/transport/http/facade.h index 8a465ce94..c886a7588 100644 --- a/libtransport/includes/hicn/transport/http/facade.h +++ b/libtransport/includes/hicn/transport/http/facade.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: diff --git a/libtransport/includes/hicn/transport/http/message.h b/libtransport/includes/hicn/transport/http/message.h index b8756224f..a07941413 100644 --- a/libtransport/includes/hicn/transport/http/message.h +++ b/libtransport/includes/hicn/transport/http/message.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2020 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: diff --git a/libtransport/includes/hicn/transport/http/request.h b/libtransport/includes/hicn/transport/http/request.h index b62f5b061..9939fbcaf 100644 --- a/libtransport/includes/hicn/transport/http/request.h +++ b/libtransport/includes/hicn/transport/http/request.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2020 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: diff --git a/libtransport/includes/hicn/transport/http/response.h b/libtransport/includes/hicn/transport/http/response.h index bab41acb8..79def27cd 100644 --- a/libtransport/includes/hicn/transport/http/response.h +++ b/libtransport/includes/hicn/transport/http/response.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2020 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: diff --git a/libtransport/includes/hicn/transport/interfaces/CMakeLists.txt b/libtransport/includes/hicn/transport/interfaces/CMakeLists.txt index 40623dfe1..43f95a466 100644 --- a/libtransport/includes/hicn/transport/interfaces/CMakeLists.txt +++ b/libtransport/includes/hicn/transport/interfaces/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2019 Cisco and/or its affiliates. +# Copyright (c) 2021 Cisco and/or its affiliates. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at: @@ -21,13 +21,7 @@ list(APPEND HEADER_FILES ${CMAKE_CURRENT_SOURCE_DIR}/global_conf_interface.h ${CMAKE_CURRENT_SOURCE_DIR}/statistics.h ${CMAKE_CURRENT_SOURCE_DIR}/portal.h + ${CMAKE_CURRENT_SOURCE_DIR}/notification.h ) -if (${OPENSSL_VERSION} VERSION_EQUAL "1.1.1a" OR ${OPENSSL_VERSION} VERSION_GREATER "1.1.1a") - list(APPEND HEADER_FILES - ${CMAKE_CURRENT_SOURCE_DIR}/p2psecure_socket_producer.h - ${CMAKE_CURRENT_SOURCE_DIR}/p2psecure_socket_consumer.h - ) -endif() - set(HEADER_FILES ${HEADER_FILES} PARENT_SCOPE) diff --git a/libtransport/includes/hicn/transport/interfaces/callbacks.h b/libtransport/includes/hicn/transport/interfaces/callbacks.h index 22e111799..41e4fba3b 100644 --- a/libtransport/includes/hicn/transport/interfaces/callbacks.h +++ b/libtransport/includes/hicn/transport/interfaces/callbacks.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: @@ -16,6 +16,7 @@ #pragma once #include <hicn/transport/auth/policies.h> +#include <hicn/transport/interfaces/notification.h> #include <hicn/transport/interfaces/statistics.h> #include <functional> @@ -60,6 +61,12 @@ using ConsumerTimerCallback = std::function<void(ConsumerSocket &, const TransportStatistics &stats)>; /** + * The ConsumerTimerCallback is called when the forwarding/recovery stategy is + * changes. + */ +using StrategyCallback = std::function<void(notification::Strategy strategy)>; + +/** * The ProducerContentCallback will be called by the producer socket right after * a content has been segmented and published. */ diff --git a/libtransport/includes/hicn/transport/interfaces/global_conf_interface.h b/libtransport/includes/hicn/transport/interfaces/global_conf_interface.h index a9fe6fac6..e1465d375 100644 --- a/libtransport/includes/hicn/transport/interfaces/global_conf_interface.h +++ b/libtransport/includes/hicn/transport/interfaces/global_conf_interface.h @@ -26,8 +26,16 @@ namespace transport { namespace interface { namespace global_config { -static const constexpr char io_module_section[] = "io_module"; -void parseConfigurationFile(const std::string& path = ""); +class GlobalConfigInterface { + public: + GlobalConfigInterface(); + ~GlobalConfigInterface(); + void parseConfigurationFile(const std::string& path = "") const; + + private: + void libtransportConfigInit() const; + void libtransportConfigTerminate() const; +}; class ConfigurationObject { public: @@ -49,7 +57,9 @@ class ConfigurationObject { class IoModuleConfiguration : public ConfigurationObject { public: - std::string getKey() const override { return io_module_section; } + static inline char section[] = "io_module"; + + std::string getKey() const override { return section; } std::string name; std::vector<std::string> search_path; diff --git a/libtransport/includes/hicn/transport/interfaces/p2psecure_socket_consumer.h b/libtransport/includes/hicn/transport/interfaces/notification.h index 224493f00..a0945c3f0 100644 --- a/libtransport/includes/hicn/transport/interfaces/p2psecure_socket_consumer.h +++ b/libtransport/includes/hicn/transport/interfaces/notification.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Cisco and/or its affiliates. + * Copyright (c) 2022 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: @@ -15,18 +15,17 @@ #pragma once -#include <hicn/transport/interfaces/socket_consumer.h> +#include <variant> namespace transport { - namespace interface { +namespace notification { + +enum class ForwardingStrategy { BEST_PATH, REPLICATION, BOTH, NONE }; +enum class RecoveryStrategy { RECOVERY_OFF, RTX_ONLY, FEC_ONLY, RTX_AND_FEC }; -class P2PSecureConsumerSocket : public ConsumerSocket { - public: - P2PSecureConsumerSocket(int handshake_protocol, int transport_protocol); - ~P2PSecureConsumerSocket() = default; - void registerPrefix(const Prefix &producer_namespace); -}; +using Strategy = std::variant<ForwardingStrategy, RecoveryStrategy>; +} // namespace notification } // namespace interface -} // end namespace transport +} // namespace transport
\ No newline at end of file diff --git a/libtransport/includes/hicn/transport/interfaces/p2psecure_socket_producer.h b/libtransport/includes/hicn/transport/interfaces/p2psecure_socket_producer.h deleted file mode 100644 index d86744514..000000000 --- a/libtransport/includes/hicn/transport/interfaces/p2psecure_socket_producer.h +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2020 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include <hicn/transport/auth/identity.h> -#include <hicn/transport/interfaces/socket_producer.h> - -namespace transport { - -namespace interface { - -class P2PSecureProducerSocket : public ProducerSocket { - public: - P2PSecureProducerSocket(); - P2PSecureProducerSocket(bool rtc, - const std::shared_ptr<auth::Identity> &identity); - ~P2PSecureProducerSocket() = default; -}; - -} // namespace interface - -} // end namespace transport diff --git a/libtransport/includes/hicn/transport/interfaces/portal.h b/libtransport/includes/hicn/transport/interfaces/portal.h index 66fc84256..bca78cb3b 100644 --- a/libtransport/includes/hicn/transport/interfaces/portal.h +++ b/libtransport/includes/hicn/transport/interfaces/portal.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: @@ -19,6 +19,8 @@ #include <hicn/transport/core/content_object.h> #include <hicn/transport/core/interest.h> #include <hicn/transport/core/prefix.h> +#include <hicn/transport/utils/event_thread.h> +#include <hicn/transport/utils/noncopyable.h> #include <functional> @@ -28,58 +30,18 @@ namespace transport { namespace interface { -template <typename PrefixType> -class BasicBindConfig { - static_assert(std::is_same<core::Prefix, PrefixType>::value, - "Prefix must be a Prefix type."); - - const uint32_t standard_cs_reserved = 5000; - - public: - template <typename T> - BasicBindConfig(T &&prefix) - : prefix_(std::forward<T &&>(prefix)), - content_store_reserved_(standard_cs_reserved) {} - - template <typename T> - BasicBindConfig(T &&prefix, uint32_t cs_reserved) - : prefix_(std::forward<T &&>(prefix)), - content_store_reserved_(cs_reserved) {} - - TRANSPORT_ALWAYS_INLINE const PrefixType &prefix() const { return prefix_; } - - TRANSPORT_ALWAYS_INLINE uint32_t csReserved() const { - return content_store_reserved_; - } - - private: - PrefixType prefix_; - uint32_t content_store_reserved_; -}; - -using BindConfig = BasicBindConfig<core::Prefix>; - -class Portal { +class Portal : private utils::NonCopyable { public: /** - * Consumer callback is an abstract class containing two methods to be - * implemented by a consumer application. + * Transport callback is an abstract class containing two methods to be + * implemented by a consumer/producer application. */ - class ConsumerCallback { + class TransportCallback { public: + virtual void onInterest(core::Interest &i) = 0; virtual void onContentObject(core::Interest &i, core::ContentObject &c) = 0; virtual void onTimeout(core::Interest::Ptr &i, const core::Name &n) = 0; - virtual void onError(std::error_code ec) = 0; - }; - - /** - * Producer callback is an abstract class containing two methods to be - * implemented by a producer application. - */ - class ProducerCallback { - public: - virtual void onInterest(core::Interest &i) = 0; - virtual void onError(std::error_code ec) = 0; + virtual void onError(const std::error_code &ec) = 0; }; using OnContentObjectCallback = @@ -89,21 +51,14 @@ class Portal { Portal(); - Portal(asio::io_service &io_service); + Portal(::utils::EventThread &worker); /** - * Set the consumer callback. - * - * @param consumer_callback - The pointer to the ConsumerCallback object. - */ - void setConsumerCallback(ConsumerCallback *consumer_callback); - - /** - * Set the producer callback. + * Set the transport protocl callback. * * @param producer_callback - The pointer to the ProducerCallback object. */ - void setProducerCallback(ProducerCallback *producer_callback); + void registerTransportCallback(TransportCallback *transport_callback); /** * Connect the transport to the local hicn forwarder. @@ -140,40 +95,18 @@ class Portal { * parameter. Otherwise ConsumerCallback::onTimeout will be used. */ void sendInterest( - core::Interest::Ptr &&interest, + core::Interest::Ptr &interest, uint32_t lifetime, OnContentObjectCallback &&on_content_object_callback = UNSET_CALLBACK, OnInterestTimeoutCallback &&on_interest_timeout_callback = UNSET_CALLBACK); /** - * Register a producer name to the local forwarder and optionally set the - * content store size in a per-face manner. - * - * @param config - The configuration for the local forwarder binding. - */ - void bind(const BindConfig &config); - - void runEventsLoop(); - - /** - * Run one event and return. - */ - void runOneEvent(); - - /** * Send a data packet to the local forwarder. As opposite to sendInterest, the * ownership of the content object is not transferred to the portal. * * @param content_object - The data packet. */ void sendContentObject(core::ContentObject &content_object); - /** - * Stop the event loop, canceling all the pending events in the event queue. - * - * Beware that stopping the event loop DOES NOT disconnect the transport from - * the local forwarder, the connector underneath will stay connected. - */ - void stopEventsLoop(); /** * Disconnect the transport from the local forwarder. @@ -188,15 +121,26 @@ class Portal { /** * Get a reference to the io_service object. */ - asio::io_service &getIoService(); + utils::EventThread &getThread(); /** * Register a route to the local forwarder. */ void registerRoute(core::Prefix &prefix); + /** + * Send a MAP-Me command to traverse NATs. + */ + void sendMapme(); + + /** + * Set forwarding strategy + */ + void setForwardingStrategy(core::Prefix &prefix, std::string &strategy); + private: - void *implementation_; + class Impl; + Impl *implementation_; }; } // namespace interface diff --git a/libtransport/includes/hicn/transport/interfaces/publication_options.h b/libtransport/includes/hicn/transport/interfaces/publication_options.h index 6910e5371..f4f409d00 100644 --- a/libtransport/includes/hicn/transport/interfaces/publication_options.h +++ b/libtransport/includes/hicn/transport/interfaces/publication_options.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: @@ -25,7 +25,7 @@ class PublicationOptions { public: template <typename T> PublicationOptions(T&& name, uint32_t lifetime) - : name_(std::forward<T&&>(name)), + : name_(std::forward<T>(name)), content_lifetime_milliseconds_(lifetime) {} TRANSPORT_ALWAYS_INLINE const core::Name& getName() const { return name_; } diff --git a/libtransport/includes/hicn/transport/interfaces/socket_consumer.h b/libtransport/includes/hicn/transport/interfaces/socket_consumer.h index 5e0e81b9f..1c709eb72 100644 --- a/libtransport/includes/hicn/transport/interfaces/socket_consumer.h +++ b/libtransport/includes/hicn/transport/interfaces/socket_consumer.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: @@ -23,6 +23,8 @@ #include <hicn/transport/interfaces/callbacks.h> #include <hicn/transport/interfaces/socket_options_default_values.h> #include <hicn/transport/interfaces/socket_options_keys.h> +#include <hicn/transport/utils/event_thread.h> +#include <hicn/transport/utils/noncopyable.h> #define CONSUMER_FINISHED 0 #define CONSUMER_BUSY 1 @@ -45,7 +47,7 @@ using namespace core; * It allows to retrieve an application data from one/many producers, by * hiding all the complexity of the transport protocol used underneath. */ -class ConsumerSocket { +class ConsumerSocket : private utils::NonCopyable { public: /** * The ReadCallback is a class which can be used by the transport for both @@ -124,7 +126,7 @@ class ConsumerSocket { * * @param ec - An error code describing the error. */ - virtual void readError(const std::error_code ec) noexcept = 0; + virtual void readError(const std::error_code &ec) noexcept = 0; /** * This callback will be invoked when the whole content is retrieved. The @@ -166,7 +168,12 @@ class ConsumerSocket { * 110, 104-117 * - RTC: Real time communication */ - explicit ConsumerSocket(int protocol, asio::io_service &io_service); + explicit ConsumerSocket(int protocol, ::utils::EventThread &worker); + + /** + * @brief Move contructor + */ + ConsumerSocket(ConsumerSocket &&other) noexcept; /** * @brief Destroy the consumer socket. @@ -200,12 +207,10 @@ class ConsumerSocket { * content retrieval succeeded. This information can be obtained from the * error code in CONTENT_RETRIEVED callback. */ - int consume(const Name &name); - int asyncConsume(const Name &name); + int consume(const Name &name, bool blocking = false); /** - * Stops the consumer socket. If several downloads are queued (using - * asyncConsume), this call stops just the current one. + * Stops the consumer socket. */ void stop(); @@ -245,6 +250,9 @@ class ConsumerSocket { int setSocketOption(int socket_option_key, interface::IcnObserver *socket_option_value); + int setSocketOption(int socket_option_key, + const std::shared_ptr<auth::Signer> &socket_option_value); + int setSocketOption( int socket_option_key, const std::shared_ptr<auth::Verifier> &socket_option_value); @@ -255,6 +263,9 @@ class ConsumerSocket { int setSocketOption(int socket_option_key, ConsumerTimerCallback socket_option_value); + int setSocketOption(int socket_option_key, + StrategyCallback socket_option_value); + int getSocketOption(int socket_option_key, double &socket_option_value); int getSocketOption(int socket_option_key, uint32_t &socket_option_value); @@ -272,6 +283,9 @@ class ConsumerSocket { int getSocketOption(int socket_option_key, IcnObserver **socket_option_value); int getSocketOption(int socket_option_key, + std::shared_ptr<auth::Signer> &socket_option_value); + + int getSocketOption(int socket_option_key, std::shared_ptr<auth::Verifier> &socket_option_value); int getSocketOption(int socket_option_key, std::string &socket_option_value); @@ -280,6 +294,9 @@ class ConsumerSocket { ConsumerTimerCallback **socket_option_value); int getSocketOption(int socket_option_key, + StrategyCallback **socket_option_value); + + int getSocketOption(int socket_option_key, interface::TransportStatistics **socket_option_value); protected: diff --git a/libtransport/includes/hicn/transport/interfaces/socket_options_default_values.h b/libtransport/includes/hicn/transport/interfaces/socket_options_default_values.h index f4945ac8a..5558197f8 100644 --- a/libtransport/includes/hicn/transport/interfaces/socket_options_default_values.h +++ b/libtransport/includes/hicn/transport/interfaces/socket_options_default_values.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021-2022 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: @@ -15,7 +15,14 @@ #pragma once +#include <hicn/transport/portability/portability.h> + +extern "C" { +#ifndef _WIN32 +TRANSPORT_CLANG_DISABLE_WARNING("-Wextern-c-compat") +#endif #include <hicn/base.h> +}; #include <chrono> #include <cstdint> @@ -26,13 +33,17 @@ namespace interface { namespace default_values { -static constexpr uint32_t interest_lifetime = 1001; // milliseconds -static constexpr uint32_t never_expire_time = HICN_MAX_LIFETIME; -static constexpr uint32_t content_object_expiry_time = +// Packet format +static constexpr hicn_packet_format_t packet_format = + HICN_PACKET_FORMAT_DEFAULT; + +// Parameters +static const uint32_t interest_lifetime = 1001; // milliseconds +static const uint32_t never_expire_time = HICN_MAX_LIFETIME; +static const uint32_t content_object_expiry_time = never_expire_time; // milliseconds -> 50 seconds -static constexpr uint32_t content_object_packet_size = - 1500; // The ethernet MTU -static constexpr uint32_t producer_socket_output_buffer_size = +static const uint32_t content_object_packet_size = 1500; // The ethernet MTU +static const uint32_t producer_socket_output_buffer_size = 150000; // Content Object static constexpr uint32_t log_2_default_buffer_size = 12; static constexpr uint32_t signature_size = 260; // bytes @@ -40,28 +51,31 @@ static constexpr uint32_t key_locator_size = 60; // bytes static constexpr uint32_t limit_guard = 80; // bytes static constexpr uint32_t digest_size = 34; // bytes static constexpr uint32_t max_out_of_order_segments = 3; // content object +static constexpr uint32_t manifest_max_capacity = 30; +static constexpr uint32_t manifest_factor_relevant = 100; +static constexpr uint32_t manifest_factor_alert = 20; // RAAQM -static constexpr int sample_number = 30; -static constexpr double gamma_value = 1; -static constexpr double beta_value = 0.8; -static constexpr double drop_factor = 0.2; -static constexpr double minimum_drop_probability = 0.00001; -static constexpr int path_id = 0; -static constexpr double rate_alpha = 0.8; +static const int sample_number = 30; +static const double gamma_value = 1; +static const double beta_value = 0.8; +static const double drop_factor = 0.2; +static const double minimum_drop_probability = 0.00001; +static const int path_id = 0; +static const double rate_alpha = 0.8; // Rate estimation -static constexpr uint32_t batch = 50; -static constexpr uint32_t kv = 20; -static constexpr double alpha = 0.8; -static constexpr uint32_t rate_choice = 0; +static const uint32_t batch = 50; +static const uint32_t kv = 20; +static const double alpha = 0.8; +static const uint32_t rate_choice = 0; // maximum allowed values -static constexpr uint32_t transport_protocol_min_retransmissions = 0; -static constexpr uint32_t transport_protocol_max_retransmissions = 128; -static constexpr uint32_t max_content_object_size = 8096; -static constexpr uint32_t min_window_size = 1; // Interests -static constexpr uint32_t max_window_size = 256 * 2; // Interests +static const uint32_t transport_protocol_min_retransmissions = 0; +static const uint32_t transport_protocol_max_retransmissions = 128; +static const uint32_t max_content_object_size = 8096; +static const uint32_t min_window_size = 1; // Interests +static const uint32_t max_window_size = 256 * 2; // Interests } // namespace default_values diff --git a/libtransport/includes/hicn/transport/interfaces/socket_options_keys.h b/libtransport/includes/hicn/transport/interfaces/socket_options_keys.h index 00cd44075..a14c8414c 100644 --- a/libtransport/includes/hicn/transport/interfaces/socket_options_keys.h +++ b/libtransport/includes/hicn/transport/interfaces/socket_options_keys.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: @@ -26,15 +26,30 @@ namespace transport { namespace interface { typedef enum { - RAAQM = 0, - CBR = 1, - RTC = 2, + UNKNOWN = 0, + BYTE_STREAM = 1, + RTC_PROD = 2, +} ProductionProtocolAlgorithms; + +typedef enum { + RAAQM = 10, + CBR = 11, + RTC = 12, } TransportProtocolAlgorithms; typedef enum { - BYTE_STREAM = 10, - RTC_PROD = 11, -} ProductionProtocolAlgorithms; + RECOVERY_OFF = 20, + RTX_ONLY = 21, + FEC_ONLY = 22, + DELAY_BASED = 23, + LOW_RATE = 24, + LOW_RATE_AND_BESTPATH = 25, + LOW_RATE_AND_REPLICATION = 26, + LOW_RATE_AND_ALL_FWD_STRATEGIES = 27, + FEC_ONLY_LOW_RES_LOSSES = 28, + DELAY_AND_BESTPATH = 29, + DELAY_AND_REPLICATION = 30, +} RtcTransportRecoveryStrategies; typedef enum { INPUT_BUFFER_SIZE = 101, @@ -45,19 +60,24 @@ typedef enum { DATA_PACKET_SIZE = 106, INTEREST_LIFETIME = 107, CONTENT_OBJECT_EXPIRY_TIME = 108, - MIN_WINDOW_SIZE = 111, - MAX_WINDOW_SIZE = 112, - CURRENT_WINDOW_SIZE = 113, - ASYNC_MODE = 114, - MAKE_MANIFEST = 115, - PORTAL = 116, - RUNNING = 117, - APPLICATION_BUFFER = 118, - HASH_ALGORITHM = 119, - SIGNER = 121, - VERIFIER = 122, - STATS_INTERVAL = 125, - SUFFIX_STRATEGY = 126 + MAX_SEGMENT_SIZE = 109, + MIN_WINDOW_SIZE = 110, + MAX_WINDOW_SIZE = 111, + CURRENT_WINDOW_SIZE = 112, + ASYNC_MODE = 113, + PORTAL = 114, + RUNNING = 115, + APPLICATION_BUFFER = 116, + HASH_ALGORITHM = 117, + SIGNER = 118, + VERIFIER = 119, + MANIFEST_MAX_CAPACITY = 120, + MANIFEST_FACTOR_RELEVANT = 121, + MANIFEST_FACTOR_ALERT = 122, + STATS_INTERVAL = 123, + SUFFIX_STRATEGY = 124, + PACKET_FORMAT = 125, + FEC_TYPE = 126, } GeneralTransportOptions; typedef enum { @@ -87,7 +107,9 @@ typedef enum { CONTENT_OBJECT_TO_VERIFY = 413, VERIFICATION_FAILED = 414, READ_CALLBACK = 415, - STATS_SUMMARY = 416 + STATS_SUMMARY = 416, + FWD_STRATEGY_CHANGE = 417, + REC_STRATEGY_CHANGE = 418, } ConsumerCallbacksOptions; typedef enum { @@ -100,7 +122,8 @@ typedef enum { CONTENT_OBJECT_READY = 510, CONTENT_OBJECT_OUTPUT = 511, CONTENT_PRODUCED = 512, - CONTENT_OBJECT_TO_SIGN = 513 + CONTENT_OBJECT_TO_SIGN = 513, + PRODUCER_CALLBACK = 514, } ProducerCallbacksOptions; typedef enum { OUTPUT_INTERFACE = 601 } DataLinkOptions; @@ -116,6 +139,13 @@ typedef enum { RSA_256 = 802, } SignatureType; +typedef enum { + RECOVERY_STRATEGY = 901, + AGGREGATED_DATA = 902, + CONTENT_SHARING_MODE = 903, + AGGREGATED_INTERESTS = 904, +} RtcTransportOptions; + } // namespace interface } // end namespace transport diff --git a/libtransport/includes/hicn/transport/interfaces/socket_producer.h b/libtransport/includes/hicn/transport/interfaces/socket_producer.h index 27b603dfe..2627b3138 100644 --- a/libtransport/includes/hicn/transport/interfaces/socket_producer.h +++ b/libtransport/includes/hicn/transport/interfaces/socket_producer.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: @@ -23,6 +23,8 @@ #include <hicn/transport/interfaces/callbacks.h> #include <hicn/transport/interfaces/socket_options_default_values.h> #include <hicn/transport/interfaces/socket_options_keys.h> +#include <hicn/transport/utils/event_thread.h> +#include <hicn/transport/utils/noncopyable.h> namespace transport { @@ -34,12 +36,28 @@ namespace interface { using namespace core; -class ProducerSocket { +class ProducerSocket : private utils::NonCopyable { public: + /** + * @brief This class is used by the transport to notify events to the + * application. + */ + class Callback { + public: + /** + * @brief This will invoked in an error occurred in the production protocol. + * + * @param ec - An error code describing the error. + */ + virtual void produceError(const std::error_code &ec) noexcept = 0; + }; + explicit ProducerSocket( int protocol = ProductionProtocolAlgorithms::BYTE_STREAM); - explicit ProducerSocket(int protocol, asio::io_service &io_service); + explicit ProducerSocket(int protocol, ::utils::EventThread &worker); + + ProducerSocket(ProducerSocket &&other) noexcept; virtual ~ProducerSocket(); @@ -63,21 +81,18 @@ class ProducerSocket { uint32_t produceDatagram(const Name &content_name, std::unique_ptr<utils::MemBuf> &&buffer); - void asyncProduce(const Name &suffix, const uint8_t *buf, size_t buffer_size, - bool is_last = true, uint32_t *start_offset = nullptr); - - void asyncProduce(Name content_name, std::unique_ptr<utils::MemBuf> &&buffer, - bool is_last, uint32_t offset, - uint32_t **last_segment = nullptr); - void produce(ContentObject &content_object); - void serveForever(); + void sendMapme(); void stop(); + void start(); + asio::io_service &getIoService(); + int setSocketOption(int socket_option_key, Callback *socket_option_value); + int setSocketOption(int socket_option_key, uint32_t socket_option_value); int setSocketOption(int socket_option_key, @@ -108,6 +123,10 @@ class ProducerSocket { int setSocketOption(int socket_option_key, const std::shared_ptr<auth::Signer> &socket_option_value); + int setSocketOption( + int socket_option_key, + const std::shared_ptr<auth::Verifier> &socket_option_value); + int setSocketOption(int socket_option_key, const std::string &socket_option_value); @@ -136,6 +155,9 @@ class ProducerSocket { int getSocketOption(int socket_option_key, std::shared_ptr<auth::Signer> &socket_option_value); + int getSocketOption(int socket_option_key, + std::shared_ptr<auth::Verifier> &socket_option_value); + int getSocketOption(int socket_option_key, std::string &socket_option_value); protected: diff --git a/libtransport/includes/hicn/transport/interfaces/statistics.h b/libtransport/includes/hicn/transport/interfaces/statistics.h index 1ff6f3edd..e83aa9a27 100644 --- a/libtransport/includes/hicn/transport/interfaces/statistics.h +++ b/libtransport/includes/hicn/transport/interfaces/statistics.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: @@ -16,6 +16,7 @@ #pragma once #include <hicn/transport/portability/c_portability.h> +#include <hicn/transport/utils/chrono_typedefs.h> #include <cstdint> @@ -37,6 +38,8 @@ class TransportStatistics { static constexpr double default_alpha = 0.7; public: + enum class statsAlerts : uint8_t { CONGESTION, LATENCY, LOSSES }; + TransportStatistics(double alpha = default_alpha) : retx_count_(0), bytes_received_(0), @@ -51,11 +54,15 @@ class TransportStatistics { lost_data_(0), definitely_lost_data_(0), recovered_data_(0), - status_(-1), + status_(0), // avg_data_rtt_(0), avg_pending_pkt_(0.0), received_nacks_(0), - received_fec_(0) {} + received_fec_(0), + in_congestion_(false), + residual_loss_rate_(0.0), + quality_score_(5), + alerts_(0) {} TRANSPORT_ALWAYS_INLINE void updateRetxCount(uint64_t retx) { retx_count_ += retx; @@ -65,8 +72,11 @@ class TransportStatistics { bytes_received_ += bytes; } - TRANSPORT_ALWAYS_INLINE void updateAverageRtt(uint64_t rtt) { - average_rtt_ = (alpha_ * average_rtt_) + ((1. - alpha_) * double(rtt)); + TRANSPORT_ALWAYS_INLINE void updateAverageRtt( + const utils::SteadyTime::Microseconds &rtt) { + double rtt_milliseconds = double(rtt.count()) / 1000.0; + + average_rtt_ = (alpha_ * average_rtt_) + ((1. - alpha_) * rtt_milliseconds); } TRANSPORT_ALWAYS_INLINE void updateAverageWindowSize(double current_window) { @@ -120,6 +130,26 @@ class TransportStatistics { received_fec_ += pkt; } + TRANSPORT_ALWAYS_INLINE void updateResidualLossRate(double val) { + residual_loss_rate_ = val; + } + + TRANSPORT_ALWAYS_INLINE void updateQualityScore(uint8_t val) { + quality_score_ = val; + } + + TRANSPORT_ALWAYS_INLINE void updateCongestionState(bool state) { + in_congestion_ = state; + } + + TRANSPORT_ALWAYS_INLINE void setAlert(statsAlerts x) { + alerts_ |= 1UL << (uint32_t)x; + } + + TRANSPORT_ALWAYS_INLINE void clearAlert(statsAlerts x) { + alerts_ &= ~(1UL << (uint32_t)x); + } + TRANSPORT_ALWAYS_INLINE uint64_t getRetxCount() const { return retx_count_; } TRANSPORT_ALWAYS_INLINE uint64_t getBytesRecv() const { @@ -174,6 +204,18 @@ class TransportStatistics { return received_fec_; } + TRANSPORT_ALWAYS_INLINE double getResidualLossRate() const { + return residual_loss_rate_; + } + + TRANSPORT_ALWAYS_INLINE uint8_t getQualityScore() const { + return quality_score_; + } + + TRANSPORT_ALWAYS_INLINE bool isCongested() const { return in_congestion_; } + + TRANSPORT_ALWAYS_INLINE uint32_t getAlerts() const { return alerts_; } + TRANSPORT_ALWAYS_INLINE void setAlpha(double val) { alpha_ = val; } TRANSPORT_ALWAYS_INLINE void reset() { @@ -193,6 +235,8 @@ class TransportStatistics { avg_pending_pkt_ = 0; received_nacks_ = 0; received_fec_ = 0; + in_congestion_ = false; + quality_score_ = 5; } private: @@ -213,6 +257,14 @@ class TransportStatistics { double avg_pending_pkt_; uint32_t received_nacks_; uint32_t received_fec_; + bool in_congestion_; + double residual_loss_rate_; + uint8_t quality_score_; + + // alerts is a bit vector used to signal to the upper layer that + // something bad is appening in the network, the encode is done accoding to + // the enum alerts; + uint32_t alerts_; }; } // namespace interface diff --git a/libtransport/includes/hicn/transport/portability/CMakeLists.txt b/libtransport/includes/hicn/transport/portability/CMakeLists.txt index 8094c0661..d29ec737c 100644 --- a/libtransport/includes/hicn/transport/portability/CMakeLists.txt +++ b/libtransport/includes/hicn/transport/portability/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2019 Cisco and/or its affiliates. +# Copyright (c) 2021 Cisco and/or its affiliates. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at: @@ -14,6 +14,9 @@ list(APPEND HEADER_FILES ${CMAKE_CURRENT_SOURCE_DIR}/c_portability.h ${CMAKE_CURRENT_SOURCE_DIR}/portability.h + ${CMAKE_CURRENT_SOURCE_DIR}/cpu.h + ${CMAKE_CURRENT_SOURCE_DIR}/cache.h + ${CMAKE_CURRENT_SOURCE_DIR}/endianess.h ) list(APPEND SOURCE_FILES diff --git a/libtransport/includes/hicn/transport/portability/c_portability.h b/libtransport/includes/hicn/transport/portability/c_portability.h index 2675de000..bc697d8b1 100644 --- a/libtransport/includes/hicn/transport/portability/c_portability.h +++ b/libtransport/includes/hicn/transport/portability/c_portability.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Copyright 2017 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/libtransport/includes/hicn/transport/portability/cache.h b/libtransport/includes/hicn/transport/portability/cache.h new file mode 100644 index 000000000..ae113c7d6 --- /dev/null +++ b/libtransport/includes/hicn/transport/portability/cache.h @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2022 Cisco and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include <hicn/transport/portability/platform.h> + +namespace transport { +namespace portability { +namespace cache { + +/** + * @Prefetch utilities + */ + +/* Default cache line size of 64 bytes. */ +#ifndef LOG2_CACHE_LINE_BYTES +static constexpr const std::size_t klog2_cache_line_bytes = 6; +#else +static constexpr const std::size_t klog2_cache_line_bytes = + LOG2_CACHE_LINE_BYTES; +#endif + +/* How much data prefetch instruction prefetches */ +#ifndef LOG2_CACHE_PREFETCH_BYTES +static constexpr const std::size_t klog2_cache_prefetch_bytes = + klog2_cache_line_bytes; +#else +static constexpr const std::size_t klog2_cache_prefetch_bytes = + LOG2_CACHE_PREFETCH_BYTES; +#endif + +/* Default cache line fill buffers. */ +#ifndef N_PREFETCHES +static constexpr const std::size_t kn_prefetches = 16; +#else +static constexpr const std::size_t kn_prefetches = N_PREFETCHES; +#endif + +static constexpr const std::size_t kcache_line_bytes = + (1 << klog2_cache_line_bytes); +static constexpr const std::size_t kcache_prefetch_bytes = + (1 << klog2_cache_prefetch_bytes); + +static constexpr const int READ = 0; +static constexpr const int LOAD = 0; /* alias for read */ +static constexpr const int WRITE = 1; +static constexpr const int STORE = 1; /* alias for write */ + +#if defined(__GNUC__) || defined(__clang__) +// Clang & GCC + +template <int type> +static inline void _prefetch(uint8_t *addr, std::size_t n, std::size_t size) { + if (size > n * kcache_prefetch_bytes) { + __builtin_prefetch(addr + n * kcache_prefetch_bytes, type, + /* locality */ 3); + } +} + +template <typename T, int type> +static inline void prefetch(T *addr, std::size_t size) { + uint8_t *_addr = reinterpret_cast<uint8_t *>(addr); + + _prefetch<type>(_addr, 0, size); + _prefetch<type>(_addr, 1, size); + _prefetch<type>(_addr, 2, size); + _prefetch<type>(_addr, 3, size); +} +#endif + +} // namespace cache +} // namespace portability +} // namespace transport
\ No newline at end of file diff --git a/libtransport/includes/hicn/transport/portability/cpu.h b/libtransport/includes/hicn/transport/portability/cpu.h new file mode 100644 index 000000000..036bf9cd9 --- /dev/null +++ b/libtransport/includes/hicn/transport/portability/cpu.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2022 Cisco and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#if defined(__aarch64__) && defined(__ARM_NEON) || defined(__i686__) +#define TRANSPORT_HAVE_VEC128 +#endif + +#if defined(__SSE4_2__) && __GNUC__ >= 4 +#define TRANSPORT_HAVE_VEC128 +#endif + +#if defined(__ALTIVEC__) +#define TRANSPORT_HAVE_VEC128 +#endif + +#if defined(__AVX2__) +#define TRANSPORT_HAVE_VEC256 +#if defined(__clang__) && __clang_major__ < 4 +#undef TRANSPORT_HAVE_VEC256 +#endif +#endif + +#if defined(__AVX512BITALG__) +#define TRANSPORT_HAVE_VEC512 +#endif diff --git a/libtransport/includes/hicn/transport/portability/endianess.h b/libtransport/includes/hicn/transport/portability/endianess.h new file mode 100644 index 000000000..c18ac82cf --- /dev/null +++ b/libtransport/includes/hicn/transport/portability/endianess.h @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2022 Cisco and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include <hicn/transport/errors/errors.h> + +namespace transport { +namespace portability { + +#if (__BYTE_ORDER__) == (__ORDER_LITTLE_ENDIAN__) +static constexpr const bool kIsBigEndian = false; +static constexpr const bool kIsLittleEndian = true; +#else +static constexpr const bool kIsBigEndian = true; +static constexpr const bool kIsLittleEndian = false; +#endif + +template <typename T> +inline T bswap(T value) { + throw errors::RuntimeException("Not implemented"); +} + +template <> +inline int16_t bswap(int16_t value) { + return __builtin_bswap16(value); +} + +template <> +inline int32_t bswap(int32_t value) { + return __builtin_bswap32(value); +} + +template <> +inline int64_t bswap(int64_t value) { + return __builtin_bswap64(value); +} + +template <> +inline uint16_t bswap(uint16_t value) { + return __builtin_bswap16(value); +} + +template <> +inline uint32_t bswap(uint32_t value) { + return __builtin_bswap32(value); +} + +template <> +inline uint64_t bswap(uint64_t value) { + return __builtin_bswap64(value); +} + +template <typename T> +inline T host_to_net(T value) { + if constexpr (kIsLittleEndian) { + return bswap(value); + } + + return value; +} + +template <typename T> +inline T net_to_host(T value) { + if constexpr (kIsLittleEndian) { + return bswap(value); + } + + return value; +} + +} // namespace portability +} // namespace transport
\ No newline at end of file diff --git a/libtransport/includes/hicn/transport/portability/portability.h b/libtransport/includes/hicn/transport/portability/portability.h index 24ef012f7..fd6eca4de 100644 --- a/libtransport/includes/hicn/transport/portability/portability.h +++ b/libtransport/includes/hicn/transport/portability/portability.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Copyright 2017 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -26,11 +26,9 @@ #include <cstddef> +namespace transport { namespace portability { -constexpr bool little_endian_arch = __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__; -constexpr bool big_endian_arch = !little_endian_arch; - // Generalize warning push/pop. #if defined(__GNUC__) || defined(__clang__) // Clang & GCC @@ -69,3 +67,4 @@ constexpr bool big_endian_arch = !little_endian_arch; #endif } // namespace portability +} // namespace transport
\ No newline at end of file diff --git a/libtransport/includes/hicn/transport/portability/win_portability.h b/libtransport/includes/hicn/transport/portability/win_portability.h index 24c7a932a..81aa828cd 100644 --- a/libtransport/includes/hicn/transport/portability/win_portability.h +++ b/libtransport/includes/hicn/transport/portability/win_portability.h @@ -1,44 +1,44 @@ -/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
- * Copyright 2017 Facebook, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#pragma once
-#define WIN32_LEAN_AND_MEAN
-#ifndef NOMINMAX
-#define NOMINMAX
-#endif
-#include <fcntl.h>
-#include <io.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <string.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <time.h>
-#include <windows.h>
-#include <winsock2.h>
-#include <ws2ipdef.h>
-#include <ws2tcpip.h>
-
-#include <algorithm>
-
-#define __ORDER_LITTLE_ENDIAN__ 0x41424344UL
-#define __ORDER_BIG_ENDIAN__ 0x44434241UL
-#define __BYTE_ORDER__ ('ABCD')
-#undef DELETE
-
-#define HAVE_STRUCT_TIMESPEC
+/* + * Copyright (c) 2021 Cisco and/or its affiliates. + * Copyright 2017 Facebook, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once +#define WIN32_LEAN_AND_MEAN +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include <fcntl.h> +#include <io.h> +#include <stdint.h> +#include <stdio.h> +#include <string.h> +#include <sys/stat.h> +#include <sys/types.h> +#include <time.h> +#include <windows.h> +#include <winsock2.h> +#include <ws2ipdef.h> +#include <ws2tcpip.h> + +#include <algorithm> + +#define __ORDER_LITTLE_ENDIAN__ 0x41424344UL +#define __ORDER_BIG_ENDIAN__ 0x44434241UL +#define __BYTE_ORDER__ ('ABCD') +#undef DELETE + +#define HAVE_STRUCT_TIMESPEC #include <pthread.h>
\ No newline at end of file diff --git a/libtransport/includes/hicn/transport/utils/CMakeLists.txt b/libtransport/includes/hicn/transport/utils/CMakeLists.txt index 75f727f03..060b83b63 100644 --- a/libtransport/includes/hicn/transport/utils/CMakeLists.txt +++ b/libtransport/includes/hicn/transport/utils/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2019 Cisco and/or its affiliates. +# Copyright (c) 2021 Cisco and/or its affiliates. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at: @@ -19,6 +19,7 @@ list(APPEND HEADER_FILES ${CMAKE_CURRENT_SOURCE_DIR}/chrono_typedefs.h ${CMAKE_CURRENT_SOURCE_DIR}/branch_prediction.h ${CMAKE_CURRENT_SOURCE_DIR}/ring_buffer.h + ${CMAKE_CURRENT_SOURCE_DIR}/rtc_quality_score.h ${CMAKE_CURRENT_SOURCE_DIR}/literals.h ${CMAKE_CURRENT_SOURCE_DIR}/conversions.h ${CMAKE_CURRENT_SOURCE_DIR}/linux.h @@ -31,9 +32,9 @@ list(APPEND HEADER_FILES ${CMAKE_CURRENT_SOURCE_DIR}/string_utils.h ${CMAKE_CURRENT_SOURCE_DIR}/file.h ${CMAKE_CURRENT_SOURCE_DIR}/shared_ptr_utils.h - ${CMAKE_CURRENT_SOURCE_DIR}/move_wrapper.h ${CMAKE_CURRENT_SOURCE_DIR}/noncopyable.h ${CMAKE_CURRENT_SOURCE_DIR}/singleton.h + ${CMAKE_CURRENT_SOURCE_DIR}/traffic_generator.h ) if(NOT WIN32) diff --git a/libtransport/includes/hicn/transport/utils/array.h b/libtransport/includes/hicn/transport/utils/array.h index 7c0ed65d8..d57bfabaf 100644 --- a/libtransport/includes/hicn/transport/utils/array.h +++ b/libtransport/includes/hicn/transport/utils/array.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: diff --git a/libtransport/includes/hicn/transport/utils/branch_prediction.h b/libtransport/includes/hicn/transport/utils/branch_prediction.h index 8cbfaca76..626cb1573 100644 --- a/libtransport/includes/hicn/transport/utils/branch_prediction.h +++ b/libtransport/includes/hicn/transport/utils/branch_prediction.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: diff --git a/libtransport/includes/hicn/transport/utils/chrono_typedefs.h b/libtransport/includes/hicn/transport/utils/chrono_typedefs.h index 8f28e763c..14234eaa1 100644 --- a/libtransport/includes/hicn/transport/utils/chrono_typedefs.h +++ b/libtransport/includes/hicn/transport/utils/chrono_typedefs.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: @@ -17,11 +17,102 @@ #include <chrono> +namespace std { +namespace chrono { +namespace detail { + +template <typename From, typename To> +struct posix_duration_cast; + +// chrono -> timespec caster +template <typename Rep, typename Period> +struct posix_duration_cast<std::chrono::duration<Rep, Period>, + struct timespec> { + static struct timespec cast(std::chrono::duration<Rep, Period> const &d) { + struct timespec tv; + + std::chrono::seconds const sec = + std::chrono::duration_cast<std::chrono::seconds>(d); + + tv.tv_sec = sec.count(); + tv.tv_nsec = + std::chrono::duration_cast<std::chrono::nanoseconds>(d - sec).count(); + + return tv; + } +}; + +// timespec -> chrono caster +template <typename Rep, typename Period> +struct posix_duration_cast<struct timespec, + std::chrono::duration<Rep, Period>> { + static std::chrono::duration<Rep, Period> cast(struct timespec const &tv) { + return std::chrono::duration_cast<std::chrono::duration<Rep, Period>>( + std::chrono::seconds(tv.tv_sec) + std::chrono::nanoseconds(tv.tv_nsec)); + } +}; + +} // namespace detail + +// chrono -> timespec +template <typename T, typename Rep, typename Period> +auto duration_cast(std::chrono::duration<Rep, Period> const &d) -> + typename std::enable_if<std::is_same<T, struct timespec>::value, + struct timespec>::type { + return detail::posix_duration_cast<std::chrono::duration<Rep, Period>, + timespec>::cast(d); +} + +// timespec -> chrono +template <typename Duration> +Duration duration_cast(struct timespec const &tv) { + return detail::posix_duration_cast<struct timespec, Duration>::cast(tv); +} + +} // namespace chrono +} // namespace std + namespace utils { -using SteadyClock = std::chrono::steady_clock; -using TimePoint = SteadyClock::time_point; -using Milliseconds = std::chrono::milliseconds; -using Microseconds = std::chrono::microseconds; +template <typename T> +class Time { + public: + using Clock = T; + using TimePoint = typename Clock::time_point; + using Rep = uint64_t; + using Seconds = std::chrono::duration<Rep>; + using Milliseconds = std::chrono::duration<Rep, std::milli>; + using Microseconds = std::chrono::duration<Rep, std::micro>; + + static auto now() { return Clock::now(); } + + // From epochs + static auto nowMs() { + return std::chrono::duration_cast<Milliseconds>(now().time_since_epoch()); + } + + // From epoch + static auto nowUs() { + return std::chrono::duration_cast<Microseconds>(now().time_since_epoch()); + } + + template <typename D> + static auto getDuration(const TimePoint &start, const TimePoint &end) { + return std::chrono::duration_cast<D>(end - start); + } + + static auto getDurationS(const TimePoint &start, const TimePoint &end) { + return getDuration<Seconds>(start, end); + } + static auto getDurationMs(const TimePoint &start, const TimePoint &end) { + return getDuration<Milliseconds>(start, end); + } + static auto getDurationUs(const TimePoint &start, const TimePoint &end) { + return getDuration<Microseconds>(start, end); + } +}; + +using SteadyTime = Time<std::chrono::steady_clock>; +using SystemTime = Time<std::chrono::system_clock>; } // namespace utils diff --git a/libtransport/includes/hicn/transport/utils/color.h b/libtransport/includes/hicn/transport/utils/color.h new file mode 100644 index 000000000..3e8d93e14 --- /dev/null +++ b/libtransport/includes/hicn/transport/utils/color.h @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2021 Cisco and/or its affiliates. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include <array> +#include <ostream> +#include <random> +#include <sstream> + +namespace utils { + +#define foreach_modifier \ + _(RESET, 0) \ + _(BOLD, 1) \ + _(FG_DEFAULT, 39) \ + _(FG_BLACK, 30) \ + _(FG_RED, 31) \ + _(FG_GREEN, 32) \ + _(FG_YELLOW, 33) \ + _(FG_BLUE, 34) \ + _(FG_MAGENTA, 35) \ + _(FG_CYAN, 36) \ + _(FG_LIGHT_GRAY, 37) \ + _(FG_DARK_GRAY, 90) \ + _(FG_LIGHT_RED, 91) \ + _(FG_LIGHT_GREEN, 92) \ + _(FG_LIGHT_YELLOW, 93) \ + _(FG_LIGHT_BLUE, 94) \ + _(FG_LIGHT_MAGENTA, 95) \ + _(FG_LIGHT_CYAN, 96) \ + _(FG_WHITE, 97) \ + _(BG_RED, 41) \ + _(BG_GREEN, 42) \ + _(BG_BLUE, 44) \ + _(BG_DEFAULT, 49) + +class ColorModifier { + static inline const std::size_t n_modifiers = 23; + static inline const char format_string_start[] = "\033["; + static inline const char format_string_end[] = "m"; + + public: + enum class Code { +#define _(name, value) name = value, + foreach_modifier +#undef _ + }; + + static inline std::array<Code, n_modifiers> code_array = { +#define _(name, value) Code::name, + foreach_modifier +#undef _ + }; + + static Code getRandomModifier() { + static std::random_device rd; + static std::mt19937 gen(rd()); + static std::uniform_int_distribution<> distr(4, 17); + + return code_array[distr(gen)]; + } + + ColorModifier(Code code) : code_(code), color_string_() { + std::stringstream ss; + if (std::getenv("COLORTERM") != nullptr) { + ss << format_string_start << static_cast<int>(code_) << format_string_end; + color_string_ = ss.str(); + } + } + + ColorModifier() : ColorModifier(getRandomModifier()) {} + + friend std::ostream& operator<<(std::ostream& os, const ColorModifier& mod) { + return os << mod.color_string_; + } + + private: + Code code_; + std::string color_string_; +}; + +} // namespace utils
\ No newline at end of file diff --git a/libtransport/includes/hicn/transport/utils/conversions.h b/libtransport/includes/hicn/transport/utils/conversions.h index 52d3e3168..812803175 100644 --- a/libtransport/includes/hicn/transport/utils/conversions.h +++ b/libtransport/includes/hicn/transport/utils/conversions.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: diff --git a/libtransport/includes/hicn/transport/utils/daemonizator.h b/libtransport/includes/hicn/transport/utils/daemonizator.h index 028d74865..1d0a0b309 100644 --- a/libtransport/includes/hicn/transport/utils/daemonizator.h +++ b/libtransport/includes/hicn/transport/utils/daemonizator.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: diff --git a/libtransport/includes/hicn/transport/utils/event_thread.h b/libtransport/includes/hicn/transport/utils/event_thread.h index 15ec1d62c..164c853a5 100644 --- a/libtransport/includes/hicn/transport/utils/event_thread.h +++ b/libtransport/includes/hicn/transport/utils/event_thread.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: @@ -29,16 +29,16 @@ class EventThread { EventThread(asio::io_service& io_service, bool detached = false) : internal_io_service_(nullptr), io_service_(std::ref(io_service)), - work_(std::make_unique<asio::io_service::work>(io_service_)), + work_guard_(asio::make_work_guard(io_service_.get())), thread_(nullptr), detached_(detached) { run(); } - EventThread(bool detached = false) + explicit EventThread(bool detached = false) : internal_io_service_(std::make_unique<asio::io_service>()), io_service_(std::ref(*internal_io_service_)), - work_(std::make_unique<asio::io_service::work>(io_service_)), + work_guard_(asio::make_work_guard(io_service_.get())), thread_(nullptr), detached_(detached) { run(); @@ -47,22 +47,12 @@ class EventThread { EventThread(const EventThread&) = delete; EventThread& operator=(const EventThread&) = delete; - EventThread(EventThread&& other) + EventThread(EventThread&& other) noexcept : internal_io_service_(std::move(other.internal_io_service_)), io_service_(std::move(other.io_service_)), - work_(std::move(other.work_)), + work_guard_(std::move(other.work_guard_)), thread_(std::move(other.thread_)), - detached_(std::move(other.detached_)) {} - - EventThread& operator=(EventThread&& other) { - internal_io_service_ = std::move(other.internal_io_service_); - io_service_ = std::move(other.io_service_); - work_ = std::move(other.work_); - thread_ = std::move(other.thread_); - detached_ = other.detached_; - - return *this; - } + detached_(other.detached_) {} ~EventThread() { stop(); } @@ -89,16 +79,29 @@ class EventThread { template <typename Func> void add(Func&& f) { - io_service_.get().post(std::forward<Func&&>(f)); + io_service_.get().post(std::forward<Func>(f)); } template <typename Func> void tryRunHandlerNow(Func&& f) { - io_service_.get().dispatch(std::forward<Func&&>(f)); + io_service_.get().dispatch(std::forward<Func>(f)); + } + + template <typename Func> + void addAndWaitForExecution(Func&& f) const { + auto promise = std::promise<void>(); + auto future = promise.get_future(); + + asio::dispatch(io_service_.get(), [&promise, f = std::forward<Func>(f)]() { + f(); + promise.set_value(); + }); + + future.wait(); } void stop() { - work_.reset(); + add([this]() { work_guard_.reset(); }); if (thread_ && thread_->joinable()) { thread_->join(); @@ -107,14 +110,14 @@ class EventThread { thread_.reset(); } - bool stopped() { return io_service_.get().stopped(); } + bool stopped() const { return io_service_.get().stopped(); } asio::io_service& getIoService() { return io_service_; } private: std::unique_ptr<asio::io_service> internal_io_service_; std::reference_wrapper<asio::io_service> io_service_; - std::unique_ptr<asio::io_service::work> work_; + asio::executor_work_guard<asio::io_context::executor_type> work_guard_; std::unique_ptr<std::thread> thread_; bool detached_; }; diff --git a/libtransport/includes/hicn/transport/utils/fixed_block_allocator.h b/libtransport/includes/hicn/transport/utils/fixed_block_allocator.h index 298b6f9d1..19b52b37e 100644 --- a/libtransport/includes/hicn/transport/utils/fixed_block_allocator.h +++ b/libtransport/includes/hicn/transport/utils/fixed_block_allocator.h @@ -1,23 +1,28 @@ /* - * Copyright (c) 2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. */ #pragma once #include <hicn/transport/portability/c_portability.h> +#include <hicn/transport/utils/branch_prediction.h> #include <hicn/transport/utils/singleton.h> #include <hicn/transport/utils/spinlock.h> #include <stdint.h> #include <cassert> #include <cstdlib> +#include <list> #include <memory> namespace utils { template <std::size_t SIZE = 512, std::size_t OBJECTS = 4096> class FixedBlockAllocator - : public utils::Singleton<FixedBlockAllocator<SIZE, OBJECTS>> { - friend class utils::Singleton<FixedBlockAllocator<SIZE, OBJECTS>>; + : public utils::ThreadLocalSingleton<FixedBlockAllocator<SIZE, OBJECTS>> { + friend class utils::ThreadLocalSingleton<FixedBlockAllocator<SIZE, OBJECTS>>; + + static inline const std::size_t BLOCK_SIZE = SIZE; + static inline const std::size_t BLOCKS_PER_POOL = OBJECTS; public: ~FixedBlockAllocator() { @@ -26,19 +31,19 @@ class FixedBlockAllocator } } - void* allocateBlock(size_t size = SIZE) { - assert(size <= SIZE); + void* allocateBlock() { uint32_t index; - SpinLock::Acquire locked(lock_); void* p_block = pop(); if (!p_block) { - if (TRANSPORT_EXPECT_FALSE(current_pool_index_ >= max_objects_)) { + if (TRANSPORT_EXPECT_FALSE(current_pool_index_ >= BLOCKS_PER_POOL)) { // Allocate new memory block p_pools_.emplace_front( - new typename std::aligned_storage<SIZE>::type[max_objects_]); + new typename std::aligned_storage<SIZE>::type[BLOCKS_PER_POOL]); // reset current_pool_index_ current_pool_index_ = 0; + // Increase total block count + block_count_ += BLOCKS_PER_POOL; } auto& latest = p_pools_.front(); @@ -59,7 +64,7 @@ class FixedBlockAllocator } public: - std::size_t blockSize() { return block_size_; } + std::size_t blockSize() { return BLOCK_SIZE; } uint32_t blockCount() { return block_count_; } @@ -69,20 +74,32 @@ class FixedBlockAllocator uint32_t deallocations() { return deallocations_; } + void reset() { + p_head_ = nullptr; + blocks_in_use_ = 0; + allocations_ = 0; + deallocations_ = 0; + current_pool_index_ = 0; + block_count_ = BLOCKS_PER_POOL; + + // Delete all memory pools but the first one + for (auto it = std::next(p_pools_.begin()); it != p_pools_.end();) { + delete[] * it; + it = p_pools_.erase(it); + } + } + private: FixedBlockAllocator() - : block_size_(SIZE), - object_size_(SIZE), - max_objects_(OBJECTS), - p_head_(NULL), + : p_head_(NULL), current_pool_index_(0), - block_count_(0), + block_count_(BLOCKS_PER_POOL), blocks_in_use_(0), allocations_(0), deallocations_(0) { static_assert(SIZE >= sizeof(long*), "SIZE must be at least 8 bytes"); p_pools_.emplace_front( - new typename std::aligned_storage<SIZE>::type[max_objects_]); + new typename std::aligned_storage<SIZE>::type[BLOCKS_PER_POOL]); } void push(void* p_memory) { @@ -106,12 +123,6 @@ class FixedBlockAllocator Block* p_next; }; - static std::unique_ptr<FixedBlockAllocator> instance_; - - const std::size_t block_size_; - const std::size_t object_size_; - const std::size_t max_objects_; - Block* p_head_; uint32_t current_pool_index_; std::list<typename std::aligned_storage<SIZE>::type*> p_pools_; @@ -123,10 +134,6 @@ class FixedBlockAllocator SpinLock lock_; }; -template <std::size_t A, std::size_t B> -std::unique_ptr<FixedBlockAllocator<A, B>> - FixedBlockAllocator<A, B>::instance_ = nullptr; - /** * STL Allocator trait to be used with allocate_shared. */ diff --git a/libtransport/includes/hicn/transport/utils/hash.h b/libtransport/includes/hicn/transport/utils/hash.h index 6815ca4bf..7943596e6 100644 --- a/libtransport/includes/hicn/transport/utils/hash.h +++ b/libtransport/includes/hicn/transport/utils/hash.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Copyright 2017 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/libtransport/includes/hicn/transport/utils/linux.h b/libtransport/includes/hicn/transport/utils/linux.h index 4fbf5f01e..14ef179ac 100644 --- a/libtransport/includes/hicn/transport/utils/linux.h +++ b/libtransport/includes/hicn/transport/utils/linux.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: @@ -44,7 +44,7 @@ static TRANSPORT_ALWAYS_INLINE int retrieveInterfaceAddress( uint16_t prefix = 0; memcpy(&prefix, tmp->sin6_addr.s6_addr, sizeof(uint16_t)); - if (htons(LINK_LOCAL_PREFIX) != prefix) { + if (portability::host_to_net(LINK_LOCAL_PREFIX) != prefix) { *address = *(struct sockaddr_in6 *)ifa->ifa_addr; getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in6), addr, sizeof(addr), NULL, 0, NI_NUMERICHOST); diff --git a/libtransport/includes/hicn/transport/utils/literals.h b/libtransport/includes/hicn/transport/utils/literals.h index bd00e0a58..531f67362 100644 --- a/libtransport/includes/hicn/transport/utils/literals.h +++ b/libtransport/includes/hicn/transport/utils/literals.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: diff --git a/libtransport/includes/hicn/transport/utils/log.h b/libtransport/includes/hicn/transport/utils/log.h index 0947b755e..f4d39b6b1 100644 --- a/libtransport/includes/hicn/transport/utils/log.h +++ b/libtransport/includes/hicn/transport/utils/log.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: diff --git a/libtransport/includes/hicn/transport/utils/membuf.h b/libtransport/includes/hicn/transport/utils/membuf.h index 6f92c2208..4b442dda3 100644 --- a/libtransport/includes/hicn/transport/utils/membuf.h +++ b/libtransport/includes/hicn/transport/utils/membuf.h @@ -30,6 +30,7 @@ #include <cinttypes> #include <cstddef> #include <cstring> +#include <iostream> #include <iterator> #include <limits> #include <memory> diff --git a/libtransport/includes/hicn/transport/utils/noncopyable.h b/libtransport/includes/hicn/transport/utils/noncopyable.h index 83923e647..0c54d24a3 100644 --- a/libtransport/includes/hicn/transport/utils/noncopyable.h +++ b/libtransport/includes/hicn/transport/utils/noncopyable.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: diff --git a/libtransport/includes/hicn/transport/utils/object_pool.h b/libtransport/includes/hicn/transport/utils/object_pool.h index d9b28e663..63288c655 100644 --- a/libtransport/includes/hicn/transport/utils/object_pool.h +++ b/libtransport/includes/hicn/transport/utils/object_pool.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: @@ -16,6 +16,7 @@ #pragma once #include <hicn/transport/utils/branch_prediction.h> +#include <hicn/transport/utils/noncopyable.h> #include <hicn/transport/utils/spinlock.h> #include <deque> @@ -25,7 +26,7 @@ namespace utils { template <typename T> -class ObjectPool { +class ObjectPool : private utils::NonCopyable { class ObjectDeleter { public: ObjectDeleter(ObjectPool<T> *pool = nullptr) : pool_(pool) {} @@ -47,8 +48,20 @@ class ObjectPool { ObjectPool() : destructor_(false) {} - // No copies - ObjectPool(const ObjectPool &other) = delete; + ObjectPool(ObjectPool &&other) + : object_pool_lock_(std::move(other.object_pool_lock_)), + object_pool_(std::move(other.object_pool_)), + destructor_(other.destructor_) {} + + ObjectPool &operator=(ObjectPool &&other) { + if (this != &other) { + object_pool_lock_ = std::move(other.object_pool_lock_); + object_pool_ = std::move(other.object_pool_); + destructor_ = other.destructor_; + } + + return *this; + } ~ObjectPool() { destructor_ = true; diff --git a/libtransport/includes/hicn/transport/utils/ring_buffer.h b/libtransport/includes/hicn/transport/utils/ring_buffer.h index 52629b82b..3032032c9 100644 --- a/libtransport/includes/hicn/transport/utils/ring_buffer.h +++ b/libtransport/includes/hicn/transport/utils/ring_buffer.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: diff --git a/libtransport/includes/hicn/transport/utils/rtc_quality_score.h b/libtransport/includes/hicn/transport/utils/rtc_quality_score.h new file mode 100644 index 000000000..2e8ca97d3 --- /dev/null +++ b/libtransport/includes/hicn/transport/utils/rtc_quality_score.h @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2021 Cisco and/or its affiliates. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +namespace transport { + +namespace protocol { + +namespace rtc { + +class RTCQualityScore { + public: + RTCQualityScore(){}; + ~RTCQualityScore(){}; + + uint8_t getQualityScore(uint64_t RTT, uint32_t loss_rate) { + uint32_t delay_index = getDelay(RTT); + uint32_t loss_index = getLossRate(loss_rate); + return quality_score_[loss_index][delay_index]; + } + + private: + // see quality score map + uint8_t quality_score_[7][6]{{5, 5, 5, 4, 3, 1}, {5, 4, 3, 2, 1, 1}, + {5, 3, 2, 1, 1, 1}, {5, 2, 1, 1, 1, 1}, + {4, 1, 1, 1, 1, 1}, {3, 1, 1, 1, 1, 1}, + {1, 1, 1, 1, 1, 1}}; + + uint8_t getDelay(uint64_t RTT) { + uint64_t OWD = RTT / 2; + // we should never get a OWD of 0. so we take the first col if OWD is < 5ms + if (OWD < 5) return 0; + if (OWD < 50) return 1; + if (OWD < 100) return 2; + if (OWD < 200) return 3; + if (OWD < 300) return 4; + return 5; + } + + uint8_t getLossRate(uint32_t loss_rate) { + // we use 3% as mean loss rate + if (loss_rate < 3) return 0; + if (loss_rate < 10) return 1; + if (loss_rate < 20) return 2; + if (loss_rate < 30) return 3; + if (loss_rate < 40) return 4; + if (loss_rate < 50) return 5; + return 6; + } +}; + +} // namespace rtc + +} // namespace protocol + +} // namespace transport diff --git a/libtransport/includes/hicn/transport/utils/singleton.h b/libtransport/includes/hicn/transport/utils/singleton.h index 4b7b19c0a..cdd8b03bf 100644 --- a/libtransport/includes/hicn/transport/utils/singleton.h +++ b/libtransport/includes/hicn/transport/utils/singleton.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: @@ -32,4 +32,17 @@ class Singleton : NonCopyable { ~Singleton() {} }; +template <typename T> +class ThreadLocalSingleton : NonCopyable { + public: + static T& getInstance() { + static thread_local T instance; + return instance; + } + + protected: + ThreadLocalSingleton() {} + ~ThreadLocalSingleton() {} +}; + } // namespace utils
\ No newline at end of file diff --git a/libtransport/includes/hicn/transport/utils/spinlock.h b/libtransport/includes/hicn/transport/utils/spinlock.h index 009a94454..40fc48de3 100644 --- a/libtransport/includes/hicn/transport/utils/spinlock.h +++ b/libtransport/includes/hicn/transport/utils/spinlock.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: diff --git a/libtransport/includes/hicn/transport/utils/string_tokenizer.h b/libtransport/includes/hicn/transport/utils/string_tokenizer.h index 36630eb58..2b2b893a0 100644 --- a/libtransport/includes/hicn/transport/utils/string_tokenizer.h +++ b/libtransport/includes/hicn/transport/utils/string_tokenizer.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: diff --git a/libtransport/includes/hicn/transport/utils/string_utils.h b/libtransport/includes/hicn/transport/utils/string_utils.h index 313c28cc6..5f9cca13b 100644 --- a/libtransport/includes/hicn/transport/utils/string_utils.h +++ b/libtransport/includes/hicn/transport/utils/string_utils.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: diff --git a/libtransport/includes/hicn/transport/utils/move_wrapper.h b/libtransport/includes/hicn/transport/utils/thread_pool.h index 5dc3b461d..76218ff09 100644 --- a/libtransport/includes/hicn/transport/utils/move_wrapper.h +++ b/libtransport/includes/hicn/transport/utils/thread_pool.h @@ -1,6 +1,5 @@ /* * Copyright (c) 2021 Cisco and/or its affiliates. - * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: @@ -16,23 +15,28 @@ #pragma once -#include <type_traits> +#include <hicn/transport/utils/event_thread.h> +#include <hicn/transport/utils/noncopyable.h> + +#include <thread> +#include <vector> namespace utils { -template <typename F> -struct MoveWrapper : F { - MoveWrapper(F&& f) : F(std::move(f)) {} +class ThreadPool : public NonCopyable { + public: + explicit ThreadPool( + std::size_t n_threads = std::thread::hardware_concurrency()) + : workers_(n_threads > 0 ? n_threads : 1) {} + + ~ThreadPool() = default; - MoveWrapper(MoveWrapper&&) = default; - MoveWrapper& operator=(MoveWrapper&&) = default; + std::size_t getNThreads() const { return workers_.size(); } + EventThread &getWorker(std::size_t i) { return workers_.at(i); } + std::vector<EventThread> &getWorkers() { return workers_; } - MoveWrapper(const MoveWrapper&); - MoveWrapper& operator=(const MoveWrapper&); + private: + std::vector<EventThread> workers_; }; -template <typename T> -auto moveHandler(T&& t) -> MoveWrapper<typename std::decay<T>::type> { - return std::move(t); -} } // namespace utils
\ No newline at end of file diff --git a/libtransport/includes/hicn/transport/utils/traffic_generator.h b/libtransport/includes/hicn/transport/utils/traffic_generator.h new file mode 100644 index 000000000..abd84886d --- /dev/null +++ b/libtransport/includes/hicn/transport/utils/traffic_generator.h @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2022 Cisco and/or its affiliates. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include <random> +#include <string> + +namespace transport { + +class TrafficGenerator { + public: + TrafficGenerator(uint32_t count); + virtual ~TrafficGenerator() = default; + bool hasFinished(); + uint32_t getSentCount(); + virtual std::pair<std::string, uint32_t> getPrefixAndSuffix(); + + virtual std::string getPrefix() = 0; + virtual uint32_t getSuffix() = 0; + virtual void reset(); + + protected: + void onSuffixGenerated(); + + uint32_t count_; + uint32_t sent_; +}; + +/* Fixed prefix, incremental suffix */ +class IncrSuffixTrafficGenerator : public TrafficGenerator { + public: + explicit IncrSuffixTrafficGenerator(std::string prefix, uint32_t suffix, + uint32_t count); + std::string getPrefix() override; + uint32_t getSuffix() override; + void reset() override; + + private: + std::string prefix_; + uint32_t suffix_; + uint32_t initial_suffix_; +}; + +/* Random prefix, random suffix */ +class RandomTrafficGenerator : public TrafficGenerator { + public: + static constexpr char NET_PREFIX[] = "2001:db8:1::/64"; + + RandomTrafficGenerator(uint32_t count, std::string net_prefix = NET_PREFIX); + std::string getPrefix() override; + uint32_t getSuffix() override; + + private: + std::string net_prefix_; + std::default_random_engine rand_engine_; + std::uniform_int_distribution<uint32_t> uniform_distribution_; +}; + +} // namespace transport
\ No newline at end of file diff --git a/libtransport/includes/hicn/transport/utils/uri.h b/libtransport/includes/hicn/transport/utils/uri.h index 7c28e8552..30675e880 100644 --- a/libtransport/includes/hicn/transport/utils/uri.h +++ b/libtransport/includes/hicn/transport/utils/uri.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: |