diff options
author | 2020-02-21 11:52:28 +0100 | |
---|---|---|
committer | 2020-02-26 13:19:16 +0100 | |
commit | f4433f28b509a9f67ca85d79000ccf9c2f4b7a24 (patch) | |
tree | 0f754bc9d8222f3ace11849165753acd85be3b38 /libtransport/src/hicn | |
parent | 0e7669445b6be1163189521eabed7dd0124043c8 (diff) |
[HICN-534] Major rework on libtransport organization
Change-Id: I361b83a18b4fd59be136d5f0817fc28e17e89884
Signed-off-by: Mauro Sardara <msardara@cisco.com>
Diffstat (limited to 'libtransport/src/hicn')
185 files changed, 0 insertions, 28528 deletions
diff --git a/libtransport/src/hicn/transport/CMakeLists.txt b/libtransport/src/hicn/transport/CMakeLists.txt deleted file mode 100644 index 4bdb3c1..0000000 --- a/libtransport/src/hicn/transport/CMakeLists.txt +++ /dev/null @@ -1,92 +0,0 @@ -# Copyright (c) 2017-2019 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. - -cmake_minimum_required(VERSION 3.5 FATAL_ERROR) - -include(GNUInstallDirs) - -set(ASIO_STANDALONE 1) - -add_subdirectory(core) -add_subdirectory(errors) -add_subdirectory(http) -add_subdirectory(interfaces) -add_subdirectory(portability) -add_subdirectory(protocols) -add_subdirectory(utils) - -include(Packager) -extract_version() -configure_file("config.h.in" "config.h" @ONLY) -install( - FILES ${CMAKE_CURRENT_BINARY_DIR}/config.h - DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/hicn/transport - COMPONENT lib${LIBTRANSPORT}-dev -) - -set (COMPILER_DEFINITIONS "-DTRANSPORT_LOG_DEF_LEVEL=TRANSPORT_LOG_${TRANSPORT_LOG_LEVEL}") - -list(INSERT LIBTRANSPORT_INTERNAL_INCLUDE_DIRS 0 - ${CMAKE_CURRENT_SOURCE_DIR}/../.. - ${CMAKE_CURRENT_BINARY_DIR}/../.. -) - -set(LIBTRANSPORT_INCLUDE_DIRS - ${CMAKE_CURRENT_SOURCE_DIR}/../../ - ${CMAKE_CURRENT_BINARY_DIR}/../../ - "" CACHE INTERNAL - "" FORCE -) - -if (NOT WIN32) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pthread") -else () - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /wd4200") - if (CMAKE_BUILD_TYPE EQUAL "RELEASE") - set(CMAKE_SHARED_LINKER_FLAGS "/NODEFAULTLIB:\"MSVCRTD\"" ) - endif () -endif () -if (${CMAKE_SYSTEM_NAME} STREQUAL "Android") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -stdlib=libc++ -isystem -lm") -endif() - -if (DISABLE_SHARED_LIBRARIES) - build_library(${LIBTRANSPORT} - STATIC - SOURCES ${SOURCE_FILES} ${HEADER_FILES} - INSTALL_HEADERS ${HEADER_FILES} - LINK_LIBRARIES ${LIBRARIES} - DEPENDS ${DEPENDENCIES} - COMPONENT lib${LIBTRANSPORT} - INCLUDE_DIRS ${LIBTRANSPORT_INTERNAL_INCLUDE_DIRS} - INSTALL_ROOT_DIR hicn/transport - DEFINITIONS ${COMPILER_DEFINITIONS} - ) -else () - build_library(${LIBTRANSPORT} - STATIC SHARED - SOURCES ${SOURCE_FILES} ${HEADER_FILES} - INSTALL_HEADERS ${HEADER_FILES} - LINK_LIBRARIES ${LIBRARIES} - DEPENDS ${DEPENDENCIES} - COMPONENT lib${LIBTRANSPORT} - INCLUDE_DIRS ${LIBTRANSPORT_INTERNAL_INCLUDE_DIRS} - INSTALL_ROOT_DIR hicn/transport - DEFINITIONS ${COMPILER_DEFINITIONS} - ) -endif () - -if (${COMPILE_TESTS}) - add_subdirectory(core/test) - add_subdirectory(transport/test) -endif() diff --git a/libtransport/src/hicn/transport/config.h.in b/libtransport/src/hicn/transport/config.h.in deleted file mode 100644 index 4e9a0f2..0000000 --- a/libtransport/src/hicn/transport/config.h.in +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2017-2019 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 - -#cmakedefine TRANSPORT_HAVE_PTHREAD 1 - -#define HICNTRANSPORT_VERSION_MAJOR "@VERSION_MAJOR@" -#define HICNTRANSPORT_VERSION_MINOR "@VERSION_MINOR@" -#define HICNTRANSPORT_VERSION_REVISION "@VERSION_REVISION@" - -#ifndef ASIO_STANDALONE -#cmakedefine ASIO_STANDALONE -#endif - -#ifndef SECURE_HICNTRANSPORT -#cmakedefine SECURE_HICNTRANSPORT -#endif - -#define RAAQM_CONFIG_PATH "@raaqm_config_path@" - -#cmakedefine __vpp__ diff --git a/libtransport/src/hicn/transport/core/CMakeLists.txt b/libtransport/src/hicn/transport/core/CMakeLists.txt deleted file mode 100644 index 8439fdf..0000000 --- a/libtransport/src/hicn/transport/core/CMakeLists.txt +++ /dev/null @@ -1,82 +0,0 @@ -# Copyright (c) 2017-2019 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. - -cmake_minimum_required(VERSION 3.5 FATAL_ERROR) - -list(APPEND HEADER_FILES - ${CMAKE_CURRENT_SOURCE_DIR}/content_object.h - ${CMAKE_CURRENT_SOURCE_DIR}/facade.h - ${CMAKE_CURRENT_SOURCE_DIR}/interest.h - ${CMAKE_CURRENT_SOURCE_DIR}/manifest.h - ${CMAKE_CURRENT_SOURCE_DIR}/manifest_inline.h - ${CMAKE_CURRENT_SOURCE_DIR}/manifest_format_fixed.h - ${CMAKE_CURRENT_SOURCE_DIR}/manifest_format.h - ${CMAKE_CURRENT_SOURCE_DIR}/name.h - ${CMAKE_CURRENT_SOURCE_DIR}/packet.h - ${CMAKE_CURRENT_SOURCE_DIR}/payload_type.h - ${CMAKE_CURRENT_SOURCE_DIR}/pending_interest.h - ${CMAKE_CURRENT_SOURCE_DIR}/portal.h - ${CMAKE_CURRENT_SOURCE_DIR}/prefix.h - ${CMAKE_CURRENT_SOURCE_DIR}/connector.h - ${CMAKE_CURRENT_SOURCE_DIR}/tcp_socket_connector.h - ${CMAKE_CURRENT_SOURCE_DIR}/udp_socket_connector.h - ${CMAKE_CURRENT_SOURCE_DIR}/forwarder_interface.h - ${CMAKE_CURRENT_SOURCE_DIR}/hicn_forwarder_interface.h - ${CMAKE_CURRENT_SOURCE_DIR}/vpp_forwarder_interface.h - ${CMAKE_CURRENT_SOURCE_DIR}/memif_connector.h -) - -list(APPEND SOURCE_FILES - ${CMAKE_CURRENT_SOURCE_DIR}/content_object.cc - ${CMAKE_CURRENT_SOURCE_DIR}/interest.cc - ${CMAKE_CURRENT_SOURCE_DIR}/pending_interest.cc - ${CMAKE_CURRENT_SOURCE_DIR}/packet.cc - ${CMAKE_CURRENT_SOURCE_DIR}/name.cc - ${CMAKE_CURRENT_SOURCE_DIR}/prefix.cc - ${CMAKE_CURRENT_SOURCE_DIR}/tcp_socket_connector.cc - ${CMAKE_CURRENT_SOURCE_DIR}/udp_socket_connector.cc - ${CMAKE_CURRENT_SOURCE_DIR}/hicn_forwarder_interface.cc - ${CMAKE_CURRENT_SOURCE_DIR}/manifest_format_fixed.cc - ${CMAKE_CURRENT_SOURCE_DIR}/connector.cc -) - -if ("${CMAKE_SYSTEM_NAME}" STREQUAL "Linux") - if (BUILD_WITH_VPP OR BUILD_HICNPLUGIN) - list(APPEND HEADER_FILES - ${CMAKE_CURRENT_SOURCE_DIR}/vpp_forwarder_interface.h - ${CMAKE_CURRENT_SOURCE_DIR}/memif_connector.h - ${CMAKE_CURRENT_SOURCE_DIR}/hicn_vapi.h - ${CMAKE_CURRENT_SOURCE_DIR}/memif_vapi.h - ) - - list(APPEND SOURCE_FILES - ${CMAKE_CURRENT_SOURCE_DIR}/vpp_forwarder_interface.cc - ${CMAKE_CURRENT_SOURCE_DIR}/memif_connector.cc - ${CMAKE_CURRENT_SOURCE_DIR}/hicn_vapi.c - ${CMAKE_CURRENT_SOURCE_DIR}/memif_vapi.c - ) - endif() - - list(APPEND HEADER_FILES - ${CMAKE_CURRENT_SOURCE_DIR}/raw_socket_connector.h - ${CMAKE_CURRENT_SOURCE_DIR}/raw_socket_interface.h - ) - - list(APPEND SOURCE_FILES - ${CMAKE_CURRENT_SOURCE_DIR}/raw_socket_connector.cc - ${CMAKE_CURRENT_SOURCE_DIR}/raw_socket_interface.cc - ) -endif() - -set(SOURCE_FILES ${SOURCE_FILES} PARENT_SCOPE) -set(HEADER_FILES ${HEADER_FILES} PARENT_SCOPE)
\ No newline at end of file diff --git a/libtransport/src/hicn/transport/core/connector.cc b/libtransport/src/hicn/transport/core/connector.cc deleted file mode 100644 index fc27157..0000000 --- a/libtransport/src/hicn/transport/core/connector.cc +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2017-2019 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. - */ - -#include <hicn/transport/core/connector.h> - -namespace transport { - -namespace core { - -std::once_flag Connector::init_flag_; - -Connector::Connector(PacketReceivedCallback &&receive_callback, - OnReconnect &&reconnect_callback) - : packet_pool_(), - receive_callback_(std::move(receive_callback)), - on_reconnect_callback_(std::move(reconnect_callback)), - state_(ConnectorState::CLOSED) { - init(); -} - -void Connector::init() { increasePoolSize(); } - -void Connector::increasePoolSize(std::size_t size) { - // Allocate space for receiving packets - const auto capacity = packet_size * size; - uint8_t *buffer = static_cast<uint8_t *>(malloc(capacity)); - std::unique_ptr<utils::MemBuf> buffer0 = - utils::MemBuf::takeOwnership(buffer, capacity, 0, nullptr, nullptr, true); - - for (std::size_t i = 1; i < size; i++) { - auto b = buffer0->cloneOne(); - b->advance(i * packet_size); - packet_pool_.add(b.release()); - } -} - -} // end namespace core - -} // end namespace transport diff --git a/libtransport/src/hicn/transport/core/connector.h b/libtransport/src/hicn/transport/core/connector.h deleted file mode 100644 index f2bbe5d..0000000 --- a/libtransport/src/hicn/transport/core/connector.h +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright (c) 2017-2019 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/core/packet.h> -#include <hicn/transport/utils/membuf.h> -#include <hicn/transport/utils/object_pool.h> -#include <hicn/transport/utils/ring_buffer.h> - -#include <deque> -#include <functional> - -namespace transport { - -namespace core { - -enum class ConnectorType : uint8_t { - SOCKET_CONNECTOR, - RAW_SOCKET_CONNECTOR, - VPP_CONNECTOR, -}; - -class Connector { - protected: - enum class ConnectorState { - CLOSED, - CONNECTING, - CONNECTED, - }; - - public: - static constexpr std::size_t packet_size = 2048; - static constexpr std::size_t queue_size = 4096; - static constexpr std::size_t packet_pool_size = 4096; - - using PacketRing = utils::CircularFifo<Packet::MemBufPtr, queue_size>; - using PacketQueue = std::deque<Packet::MemBufPtr>; - using PacketReceivedCallback = std::function<void(Packet::MemBufPtr &&)>; - using OnReconnect = std::function<void()>; - using PacketSentCallback = std::function<void()>; - - Connector(PacketReceivedCallback &&receive_callback, - OnReconnect &&reconnect_callback); - - virtual ~Connector(){}; - - virtual void send(const Packet::MemBufPtr &packet) = 0; - - virtual void send(const uint8_t *packet, std::size_t len, - const PacketSentCallback &packet_sent = 0) = 0; - - virtual void close() = 0; - - virtual ConnectorState state() { return state_; }; - - virtual bool isConnected() { return state_ == ConnectorState::CONNECTED; } - - protected: - void increasePoolSize(std::size_t size = packet_pool_size); - - TRANSPORT_ALWAYS_INLINE utils::ObjectPool<utils::MemBuf>::Ptr getPacket() { - auto result = packet_pool_.get(); - - while (TRANSPORT_EXPECT_FALSE(!result.first)) { - // Add packets to the pool - increasePoolSize(); - result = packet_pool_.get(); - } - - if (result.second->isChained()) { - result.second->separateChain(result.second->next(), - result.second->prev()); - } - - result.second->trimEnd(result.second->length()); - return std::move(result.second); - } - - private: - void init(); - - protected: - static std::once_flag init_flag_; - utils::ObjectPool<utils::MemBuf> packet_pool_; - PacketQueue output_buffer_; - - // Connector events - PacketReceivedCallback receive_callback_; - OnReconnect on_reconnect_callback_; - - // Connector state - ConnectorState state_; -}; -} // end namespace core - -} // end namespace transport diff --git a/libtransport/src/hicn/transport/core/content_object.cc b/libtransport/src/hicn/transport/core/content_object.cc deleted file mode 100644 index 6cbcdb2..0000000 --- a/libtransport/src/hicn/transport/core/content_object.cc +++ /dev/null @@ -1,201 +0,0 @@ -/* - * Copyright (c) 2017-2019 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. - */ - -#include <hicn/transport/core/content_object.h> -#include <hicn/transport/errors/errors.h> -#include <hicn/transport/utils/branch_prediction.h> - -extern "C" { -#ifndef _WIN32 -TRANSPORT_CLANG_DISABLE_WARNING("-Wextern-c-compat") -#endif -#include <hicn/hicn.h> -#include <hicn/util/ip_address.h> -} - -#include <cstring> -#include <memory> - -namespace transport { - -namespace core { - -ContentObject::ContentObject(const Name &name, Packet::Format format) - : Packet(format) { - if (TRANSPORT_EXPECT_FALSE( - hicn_data_set_name(format, packet_start_, &name.name_) < 0)) { - throw errors::RuntimeException("Error filling the packet name."); - } - - if (TRANSPORT_EXPECT_FALSE(hicn_data_get_name(format_, packet_start_, - name_.getStructReference()) < - 0)) { - throw errors::MalformedPacketException(); - } -} - -#ifdef __ANDROID__ -ContentObject::ContentObject(hicn_format_t format) - : ContentObject(Name("0::0|0"), format) {} -#else -ContentObject::ContentObject(hicn_format_t format) - : ContentObject(Packet::base_name, format) {} -#endif - -ContentObject::ContentObject(const Name &name, hicn_format_t format, - const uint8_t *payload, std::size_t size) - : ContentObject(name, format) { - appendPayload(payload, size); -} - -ContentObject::ContentObject(const uint8_t *buffer, std::size_t size) - : Packet(buffer, size) { - if (hicn_data_get_name(format_, packet_start_, name_.getStructReference()) < - 0) { - throw errors::RuntimeException("Error getting name from content object."); - } -} - -ContentObject::ContentObject(MemBufPtr &&buffer) : Packet(std::move(buffer)) { - if (hicn_data_get_name(format_, packet_start_, name_.getStructReference()) < - 0) { - throw errors::RuntimeException("Error getting name from content object."); - } -} - -ContentObject::ContentObject(ContentObject &&other) : Packet(std::move(other)) { - name_ = std::move(other.name_); - - if (hicn_data_get_name(format_, packet_start_, name_.getStructReference()) < - 0) { - throw errors::MalformedPacketException(); - } -} - -ContentObject::~ContentObject() {} - -void ContentObject::replace(MemBufPtr &&buffer) { - Packet::replace(std::move(buffer)); - - if (hicn_data_get_name(format_, packet_start_, name_.getStructReference()) < - 0) { - throw errors::RuntimeException("Error getting name from content object."); - } -} - -const Name &ContentObject::getName() const { - if (!name_) { - if (hicn_data_get_name(format_, packet_start_, - (hicn_name_t *)name_.getConstStructReference()) < - 0) { - throw errors::MalformedPacketException(); - } - } - - return name_; -} - -Name &ContentObject::getWritableName() { return const_cast<Name &>(getName()); } - -void ContentObject::setName(const Name &name) { - if (hicn_data_set_name(format_, packet_start_, - name.getConstStructReference()) < 0) { - throw errors::RuntimeException("Error setting content object name."); - } - - if (hicn_data_get_name(format_, packet_start_, name_.getStructReference()) < - 0) { - throw errors::MalformedPacketException(); - } -} - -void ContentObject::setName(Name &&name) { - if (hicn_data_set_name(format_, packet_start_, name.getStructReference()) < - 0) { - throw errors::RuntimeException( - "Error getting the payload length from content object."); - } - - if (hicn_data_get_name(format_, packet_start_, name_.getStructReference()) < - 0) { - throw errors::MalformedPacketException(); - } -} - -uint32_t ContentObject::getPathLabel() const { - uint32_t path_label; - if (hicn_data_get_path_label(packet_start_, &path_label) < 0) { - throw errors::RuntimeException( - "Error retrieving the path label from content object"); - } - - return path_label; -} - -ContentObject &ContentObject::setPathLabel(uint32_t path_label) { - if (hicn_data_set_path_label((hicn_header_t *)packet_start_, path_label) < - 0) { - throw errors::RuntimeException( - "Error setting the path label from content object"); - } - - return *this; -} - -void ContentObject::setLocator(const ip_address_t &ip_address) { - if (hicn_data_set_locator(format_, packet_start_, &ip_address) < 0) { - throw errors::RuntimeException("Error setting content object locator"); - } - - return; -} - -ip_address_t ContentObject::getLocator() const { - ip_address_t ip; - - if (hicn_data_get_locator(format_, packet_start_, &ip) < 0) { - throw errors::RuntimeException("Error getting content object locator."); - } - - return ip; -} - -void ContentObject::setLifetime(uint32_t lifetime) { - if (hicn_data_set_expiry_time(packet_start_, lifetime) < 0) { - throw errors::MalformedPacketException(); - } -} - -uint32_t ContentObject::getLifetime() const { - uint32_t lifetime = 0; - - if (hicn_data_get_expiry_time(packet_start_, &lifetime) < 0) { - throw errors::MalformedPacketException(); - } - - return lifetime; -} - -void ContentObject::resetForHash() { - if (hicn_data_reset_for_hash( - format_, reinterpret_cast<hicn_header_t *>(packet_start_)) < 0) { - throw errors::RuntimeException( - "Error resetting content object fields for hash computation."); - } -} - -} // end namespace core - -} // end namespace transport diff --git a/libtransport/src/hicn/transport/core/content_object.h b/libtransport/src/hicn/transport/core/content_object.h deleted file mode 100644 index 5af548f..0000000 --- a/libtransport/src/hicn/transport/core/content_object.h +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (c) 2017-2019 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/core/name.h> -#include <hicn/transport/core/packet.h> - -namespace transport { - -namespace core { - -// This class is used just to transfer buffer pointers -// without making a copy, as std::vector<> would do - -class ContentObject : public Packet { - public: - using Ptr = utils::ObjectPool<ContentObject>::Ptr; - using HICNContentObject = hicn_header_t; - - ContentObject(Packet::Format format = HF_INET6_TCP); - - ContentObject(const Name &name, Packet::Format format = HF_INET6_TCP); - - ContentObject(const Name &name, hicn_format_t format, const uint8_t *payload, - std::size_t payload_size); - - ContentObject(const uint8_t *buffer, std::size_t size); - ContentObject(MemBufPtr &&buffer); - - ContentObject(const ContentObject &content_object) = delete; - - ContentObject(ContentObject &&content_object); - - ~ContentObject() override; - - void replace(MemBufPtr &&buffer) override; - - const Name &getName() const override; - - Name &getWritableName() override; - - void setName(const Name &name) override; - - void setName(Name &&name) override; - - uint32_t getPathLabel() const; - - ContentObject &setPathLabel(uint32_t path_label); - - void setLocator(const ip_address_t &ip_address) override; - - ip_address_t getLocator() const override; - - void setLifetime(uint32_t lifetime) override; - - uint32_t getLifetime() const override; - - private: - void resetForHash() override; -}; - -} // end namespace core - -} // end namespace transport diff --git a/libtransport/src/hicn/transport/core/facade.h b/libtransport/src/hicn/transport/core/facade.h deleted file mode 100644 index 27e738e..0000000 --- a/libtransport/src/hicn/transport/core/facade.h +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2017-2019 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/core/forwarder_interface.h> -#include <hicn/transport/core/hicn_forwarder_interface.h> -#include <hicn/transport/core/manifest_format_fixed.h> -#include <hicn/transport/core/manifest_inline.h> -#include <hicn/transport/core/portal.h> - -#ifdef __linux__ -#ifndef __ANDROID__ -#include <hicn/transport/core/raw_socket_interface.h> -#ifdef __vpp__ -#include <hicn/transport/core/vpp_forwarder_interface.h> -#endif -#endif -#endif - -namespace transport { - -namespace core { - -using HicnForwarderPortal = Portal<HicnForwarderInterface>; - -#ifdef __linux__ -#ifndef __ANDROID__ -using RawSocketPortal = Portal<RawSocketInterface>; -#endif -#ifdef __vpp__ -using VPPForwarderPortal = Portal<VPPForwarderInterface>; -#endif -#endif - -using ContentObjectManifest = core::ManifestInline<ContentObject, Fixed>; -using InterestManifest = core::ManifestInline<Interest, Fixed>; - -} // namespace core - -} // namespace transport diff --git a/libtransport/src/hicn/transport/core/forwarder_interface.h b/libtransport/src/hicn/transport/core/forwarder_interface.h deleted file mode 100644 index 63b4a2e..0000000 --- a/libtransport/src/hicn/transport/core/forwarder_interface.h +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Copyright (c) 2017-2019 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/core/prefix.h> -#include <hicn/transport/core/udp_socket_connector.h> -#include <hicn/transport/portability/portability.h> -#include <hicn/transport/utils/chrono_typedefs.h> -#include <hicn/transport/utils/log.h> - -#include <deque> - -namespace transport { - -namespace core { - -typedef struct { - uint64_t rx_packets; - uint64_t tx_packets; - uint64_t rx_bytes; - uint64_t tx_bytes; - uint64_t rx_errors; - uint64_t tx_errors; -} Counters; - -template <typename Implementation, typename ConnectorType> -class ForwarderInterface { - static_assert(std::is_base_of<Connector, ConnectorType>::value, - "T must inherit from connector!"); - - static constexpr uint32_t standard_cs_reserved = 5000; - - protected: - ForwarderInterface(ConnectorType &c) - : connector_(c), - inet_address_({}), - inet6_address_({}), - mtu_(1500), - output_interface_(""), - content_store_reserved_(standard_cs_reserved) { - } - - public: - virtual ~ForwarderInterface() {} - - TRANSPORT_ALWAYS_INLINE void connect(bool is_consumer = true) { - static_cast<Implementation &>(*this).connect(is_consumer); - } - - TRANSPORT_ALWAYS_INLINE void registerRoute(Prefix &prefix) { - static_cast<Implementation &>(*this).registerRoute(); - } - - TRANSPORT_ALWAYS_INLINE std::uint32_t getMtu() { - return static_cast<Implementation &>(*this).getMtu(); - } - - TRANSPORT_ALWAYS_INLINE static bool isControlMessage(const uint8_t *message) { - return Implementation::isControlMessageImpl(message); - } - - template <typename R> - TRANSPORT_ALWAYS_INLINE void processControlMessageReply(R &&packet_buffer) { - return static_cast<Implementation &>(*this).processControlMessageReplyImpl( - std::forward<R &&>(packet_buffer)); - } - - TRANSPORT_ALWAYS_INLINE void closeConnection() { - return static_cast<Implementation &>(*this).closeConnection(); - } - - template < - typename R, - typename = std::enable_if_t< - std::is_base_of<Packet, typename std::remove_reference_t<R>>::value, - R>> - TRANSPORT_ALWAYS_INLINE void send(R &&packet) { - counters_.tx_packets++; - counters_.tx_bytes += packet.payloadSize() + packet.headerSize(); - - if (_is_ipv4(packet.getFormat())) { - packet.setLocator(inet_address_); - } else { - packet.setLocator(inet6_address_); - } - - // TRANSPORT_LOGI("Sending packet %s at %lu", - // packet.getName().toString().c_str(), - // utils::SteadyClock::now().time_since_epoch().count()); - packet.setChecksum(); - connector_.send(packet.acquireMemBufReference()); - } - - TRANSPORT_ALWAYS_INLINE void send(const uint8_t *packet, std::size_t len) { - // ASIO_COMPLETION_HANDLER_CHECK(Handler, packet_sent) type_check; - counters_.tx_packets++; - counters_.tx_bytes += len; - - // Perfect forwarding - connector_.send(packet, len); - } - - TRANSPORT_ALWAYS_INLINE void shutdown() { connector_.close(); } - - TRANSPORT_ALWAYS_INLINE Connector &getConnector() { return connector_; } - - TRANSPORT_ALWAYS_INLINE void setContentStoreSize(uint32_t cs_size) { - content_store_reserved_ = cs_size; - } - - TRANSPORT_ALWAYS_INLINE uint32_t getContentStoreSize() const { - return content_store_reserved_; - } - - TRANSPORT_ALWAYS_INLINE void setOutputInterface( - const std::string &interface) { - output_interface_ = interface; - } - - TRANSPORT_ALWAYS_INLINE std::string &getOutputInterface() { - return output_interface_; - } - - protected: - ConnectorType &connector_; - ip_address_t inet_address_; - ip_address_t inet6_address_; - uint16_t mtu_; - std::string output_interface_; - uint32_t content_store_reserved_; - Counters counters_; -}; - -} // namespace core - -} // namespace transport diff --git a/libtransport/src/hicn/transport/core/hicn_forwarder_interface.cc b/libtransport/src/hicn/transport/core/hicn_forwarder_interface.cc deleted file mode 100644 index 2a02a2b..0000000 --- a/libtransport/src/hicn/transport/core/hicn_forwarder_interface.cc +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright (c) 2017-2019 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. - */ - -#include <hicn/transport/core/hicn_forwarder_interface.h> - -union AddressLight { - uint32_t ipv4; - struct in6_addr ipv6; -}; - -typedef struct { - uint8_t message_type; - uint8_t command_id; - uint16_t length; - uint32_t seq_num; -} CommandHeader; - -typedef struct { - uint8_t message_type; - uint8_t command_id; - uint16_t length; - uint32_t seq_num; - char symbolic_or_connid[16]; - union AddressLight address; - uint16_t cost; - uint8_t address_type; - uint8_t len; -} RouteToSelfCommand; - -typedef struct { - uint8_t message_type; - uint8_t command_id; - uint16_t length; - uint32_t seq_num; - char symbolic_or_connid[16]; -} DeleteSelfConnectionCommand; - -namespace { -static constexpr uint8_t addr_inet = 1; -static constexpr uint8_t addr_inet6 = 2; -static constexpr uint8_t add_route_command = 3; -static constexpr uint8_t delete_connection_command = 5; -static constexpr uint8_t request_light = 0xc0; -static constexpr char identifier[] = "SELF"; - -void fillCommandHeader(CommandHeader *header) { - // Allocate and fill the header - header->message_type = request_light; - header->length = 1; -} - -RouteToSelfCommand createCommandRoute(std::unique_ptr<sockaddr> &&addr, - uint8_t prefix_length) { - RouteToSelfCommand command = {0}; - - // check and set IP address - if (addr->sa_family == AF_INET) { - command.address_type = addr_inet; - command.address.ipv4 = ((sockaddr_in *)addr.get())->sin_addr.s_addr; - } else if (addr->sa_family == AF_INET6) { - command.address_type = addr_inet6; - command.address.ipv6 = ((sockaddr_in6 *)addr.get())->sin6_addr; - } - - // Fill remaining payload fields -#ifndef _WIN32 - strcpy(command.symbolic_or_connid, identifier); -#else - strcpy_s(command.symbolic_or_connid, 16, identifier); -#endif - command.cost = 1; - command.len = (uint8_t)prefix_length; - - // Allocate and fill the header - command.command_id = add_route_command; - fillCommandHeader((CommandHeader *)&command); - - return command; -} - -DeleteSelfConnectionCommand createCommandDeleteConnection() { - DeleteSelfConnectionCommand command = {0}; - fillCommandHeader((CommandHeader *)&command); - command.command_id = delete_connection_command; - -#ifndef _WIN32 - strcpy(command.symbolic_or_connid, identifier); -#else - strcpy_s(command.symbolic_or_connid, 16, identifier); -#endif - - return command; -} - -} // namespace - -namespace transport { - -namespace core { - -HicnForwarderInterface::HicnForwarderInterface(UdpSocketConnector &connector) - : ForwarderInterface<HicnForwarderInterface, UdpSocketConnector>( - connector) {} - -HicnForwarderInterface::~HicnForwarderInterface() {} - -void HicnForwarderInterface::connect(bool is_consumer) { connector_.connect(); } - -void HicnForwarderInterface::registerRoute(Prefix &prefix) { - auto command = createCommandRoute(prefix.toSockaddr(), - (uint8_t)prefix.getPrefixLength()); - send((uint8_t *)&command, sizeof(RouteToSelfCommand)); -} - -void HicnForwarderInterface::closeConnection() { - auto command = createCommandDeleteConnection(); - send((uint8_t *)&command, sizeof(DeleteSelfConnectionCommand)); - connector_.close(); -} - -} // namespace core - -} // namespace transport diff --git a/libtransport/src/hicn/transport/core/hicn_forwarder_interface.h b/libtransport/src/hicn/transport/core/hicn_forwarder_interface.h deleted file mode 100644 index b11841b..0000000 --- a/libtransport/src/hicn/transport/core/hicn_forwarder_interface.h +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (c) 2017-2019 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/core/forwarder_interface.h> -#include <hicn/transport/core/prefix.h> -#include <hicn/transport/core/udp_socket_connector.h> - -#include <deque> - -namespace transport { - -namespace core { - -class HicnForwarderInterface - : public ForwarderInterface<HicnForwarderInterface, UdpSocketConnector> { - static constexpr uint8_t ack_code = 0xc2; - static constexpr uint8_t nack_code = 0xc3; - - public: - union addressLight { - uint32_t ipv4; - struct in6_addr ipv6; - }; - - struct route_to_self_command { - uint8_t messageType; - uint8_t commandID; - uint16_t length; - uint32_t seqNum; - char symbolicOrConnid[16]; - union addressLight address; - uint16_t cost; - uint8_t addressType; - uint8_t len; - }; - - using route_to_self_command = struct route_to_self_command; - using ConnectorType = UdpSocketConnector; - - HicnForwarderInterface(UdpSocketConnector &connector); - - ~HicnForwarderInterface(); - - void connect(bool is_consumer); - - void registerRoute(Prefix &prefix); - - std::uint16_t getMtu() { return interface_mtu; } - - TRANSPORT_ALWAYS_INLINE static bool isControlMessageImpl( - const uint8_t *message) { - return message[0] == ack_code || message[0] == nack_code; - } - - TRANSPORT_ALWAYS_INLINE void processControlMessageReplyImpl( - Packet::MemBufPtr &&packet_buffer) { - if (packet_buffer->data()[0] == nack_code) { - throw errors::RuntimeException( - "Received Nack message from hicn light forwarder."); - } - } - - void closeConnection(); - - private: - static constexpr std::uint16_t interface_mtu = 1500; -}; - -} // namespace core - -} // namespace transport diff --git a/libtransport/src/hicn/transport/core/hicn_vapi.c b/libtransport/src/hicn/transport/core/hicn_vapi.c deleted file mode 100644 index aea08f3..0000000 --- a/libtransport/src/hicn/transport/core/hicn_vapi.c +++ /dev/null @@ -1,224 +0,0 @@ -/* - * Copyright (c) 2017-2019 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. - */ - -#include <hicn/transport/config.h> - -#ifdef __vpp__ - -#include <hicn/transport/core/hicn_vapi.h> -#include <hicn/transport/utils/log.h> - -#define HICN_VPP_PLUGIN -#include <hicn/name.h> -#undef HICN_VPP_PLUGIN - -#include <vapi/vapi_safe.h> -#include <vlib/vlib.h> -#include <vlibapi/api.h> -#include <vlibmemory/api.h> -#include <vppinfra/error.h> - -#include <vnet/ip/format.h> -#include <vnet/ip/ip4_packet.h> -#include <vnet/ip/ip6_packet.h> -#include <vnet/fib/fib_types.h> - -#include <vpp_plugins/hicn/error.h> -#include <vapi/hicn.api.vapi.h> - -///////////////////////////////////////////////////// -const char *HICN_ERROR_STRING[] = { -#define _(a, b, c) c, - foreach_hicn_error -#undef _ -}; -///////////////////////////////////////////////////// - -/*********************** Missing Symbol in vpp libraries *************************/ -u8 * -format_vl_api_address_union (u8 * s, va_list * args) -{ - return NULL; -} - -/*********************************************************************************/ - -DEFINE_VAPI_MSG_IDS_HICN_API_JSON - -static vapi_error_e register_prod_app_cb(vapi_ctx_t ctx, - void *callback_ctx, - vapi_error_e rv, - bool is_last, - vapi_payload_hicn_api_register_prod_app_reply *reply) { - hicn_producer_output_params * output_params = (hicn_producer_output_params *)callback_ctx; - - if(reply == NULL) - return rv; - - output_params->cs_reserved = reply->cs_reserved; - output_params->prod_addr = (ip_address_t *)malloc(sizeof(ip_address_t)); - memset(output_params->prod_addr, 0, sizeof(ip_address_t)); - if(reply->prod_addr.af == ADDRESS_IP6) - memcpy(&output_params->prod_addr->v6, reply->prod_addr.un.ip6, sizeof(ip6_address_t)); - else - memcpy(&output_params->prod_addr->v4, reply->prod_addr.un.ip4, sizeof(ip4_address_t)); - output_params->face_id = reply->faceid; - - return reply->retval; -} - -int hicn_vapi_register_prod_app( - vapi_ctx_t ctx, hicn_producer_input_params *input_params, - hicn_producer_output_params *output_params) { - - vapi_lock(); - vapi_msg_hicn_api_register_prod_app * msg = vapi_alloc_hicn_api_register_prod_app(ctx); - - if(ip46_address_is_ip4((ip46_address_t *)&input_params->prefix->address)) { - memcpy(&msg->payload.prefix.address.un.ip4, &input_params->prefix->address, sizeof(ip4_address_t)); - msg->payload.prefix.address.af = ADDRESS_IP4; - } else { - memcpy(&msg->payload.prefix.address.un.ip6, &input_params->prefix->address, sizeof(ip6_address_t)); - msg->payload.prefix.address.af = ADDRESS_IP6; - } - msg->payload.prefix.len = input_params->prefix->len; - - msg->payload.swif = input_params->swif; - msg->payload.cs_reserved = input_params->cs_reserved; - - int ret = vapi_hicn_api_register_prod_app(ctx, msg, register_prod_app_cb, output_params); - vapi_unlock(); - return ret; -} - -static vapi_error_e face_prod_del_cb(vapi_ctx_t ctx, - void *callback_ctx, - vapi_error_e rv, - bool is_last, - vapi_payload_hicn_api_face_prod_del_reply *reply) { - if(reply == NULL) - return rv; - - return reply->retval; -} - -int hicn_vapi_face_prod_del( - vapi_ctx_t ctx, hicn_del_face_app_input_params *input_params) { - vapi_lock(); - vapi_msg_hicn_api_face_prod_del * msg = vapi_alloc_hicn_api_face_prod_del(ctx); - - msg->payload.faceid = input_params->face_id; - - int ret = vapi_hicn_api_face_prod_del(ctx, msg, face_prod_del_cb, NULL); - vapi_unlock(); - return ret; -} - -static vapi_error_e register_cons_app_cb(vapi_ctx_t ctx, - void *callback_ctx, - vapi_error_e rv, - bool is_last, - vapi_payload_hicn_api_register_cons_app_reply *reply) { - hicn_consumer_output_params * output_params = (hicn_consumer_output_params *)callback_ctx; - - if(reply == NULL) - return rv; - - output_params->src6 = (ip_address_t *)malloc(sizeof(ip_address_t)); - output_params->src4 = (ip_address_t *)malloc(sizeof(ip_address_t)); - memset(output_params->src6, 0, sizeof(ip_address_t)); - memset(output_params->src4, 0, sizeof(ip_address_t)); - memcpy(&output_params->src6->v6, &reply->src_addr6.un.ip6, sizeof(ip6_address_t)); - memcpy(&output_params->src4->v4, &reply->src_addr4.un.ip4, sizeof(ip4_address_t)); - - output_params->face_id1 = reply->faceid1; - output_params->face_id2 = reply->faceid2; - - return reply->retval; -} - -int hicn_vapi_register_cons_app( - vapi_ctx_t ctx, hicn_consumer_input_params *input_params, - hicn_consumer_output_params *output_params) { - - vapi_lock(); - vapi_msg_hicn_api_register_cons_app * msg = vapi_alloc_hicn_api_register_cons_app(ctx); - - msg->payload.swif = input_params->swif; - - int ret = vapi_hicn_api_register_cons_app(ctx, msg, register_cons_app_cb, output_params); - vapi_unlock(); - return ret; -} - -static vapi_error_e face_cons_del_cb(vapi_ctx_t ctx, - void *callback_ctx, - vapi_error_e rv, - bool is_last, - vapi_payload_hicn_api_face_cons_del_reply *reply) { - if(reply == NULL) - return rv; - - return reply->retval; -} - -int hicn_vapi_face_cons_del( - vapi_ctx_t ctx, hicn_del_face_app_input_params *input_params) { - - vapi_lock(); - vapi_msg_hicn_api_face_cons_del * msg = vapi_alloc_hicn_api_face_cons_del(ctx); - - msg->payload.faceid = input_params->face_id; - - int ret = vapi_hicn_api_face_cons_del(ctx, msg, face_cons_del_cb, NULL); - vapi_unlock(); - return ret; -} - -static vapi_error_e reigster_route_cb(vapi_ctx_t ctx, - void *callback_ctx, - vapi_error_e rv, - bool is_last, - vapi_payload_hicn_api_route_nhops_add_reply *reply) { - if(reply == NULL) - return rv; - - return reply->retval; -} - -int hicn_vapi_register_route( - vapi_ctx_t ctx, - hicn_producer_set_route_params *input_params) { - - vapi_lock(); - vapi_msg_hicn_api_route_nhops_add * msg = vapi_alloc_hicn_api_route_nhops_add(ctx); - - fib_prefix_t prefix; - memcpy(&prefix.fp_addr, &input_params->prefix->address, sizeof(ip46_address_t)); - prefix.fp_len = input_params->prefix->len; - msg->payload.face_ids[0] = input_params->face_id; - msg->payload.n_faces = 1; - - int ret = vapi_hicn_api_route_nhops_add(ctx, msg, reigster_route_cb, NULL); - - vapi_unlock(); - return ret; -} - -char *hicn_vapi_get_error_string(int ret_val) { - return get_error_string(ret_val); -} - -#endif // __vpp__ diff --git a/libtransport/src/hicn/transport/core/hicn_vapi.h b/libtransport/src/hicn/transport/core/hicn_vapi.h deleted file mode 100644 index f2718e6..0000000 --- a/libtransport/src/hicn/transport/core/hicn_vapi.h +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (c) 2017-2019 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/config.h> -#include <hicn/util/ip_address.h> - -#ifdef __vpp__ - -#ifdef __cplusplus -extern "C" { -#endif - -#include <vapi/vapi.h> - -#include "stdint.h" - -typedef struct { - ip_prefix_t* prefix; - uint32_t swif; - uint32_t cs_reserved; -} hicn_producer_input_params; - -typedef struct { - uint32_t swif; -} hicn_consumer_input_params; - -typedef struct { - uint32_t face_id; -} hicn_del_face_app_input_params; - -typedef struct { - uint32_t cs_reserved; - ip_address_t* prod_addr; - uint32_t face_id; -} hicn_producer_output_params; - -typedef struct { - ip_address_t* src4; - ip_address_t* src6; - uint32_t face_id1; - uint32_t face_id2; -} hicn_consumer_output_params; - -typedef struct { - ip_prefix_t* prefix; - uint32_t face_id; -} hicn_producer_set_route_params; - -int hicn_vapi_register_prod_app( - vapi_ctx_t ctx, hicn_producer_input_params* input_params, - hicn_producer_output_params* output_params); - -int hicn_vapi_register_cons_app( - vapi_ctx_t ctx, hicn_consumer_input_params* input_params, - hicn_consumer_output_params* output_params); - -int hicn_vapi_register_route( - vapi_ctx_t ctx, hicn_producer_set_route_params* input_params); - -int hicn_vapi_face_cons_del( - vapi_ctx_t ctx, hicn_del_face_app_input_params *input_params); - -int hicn_vapi_face_prod_del( - vapi_ctx_t ctx, hicn_del_face_app_input_params *input_params); - -char* hicn_vapi_get_error_string(int ret_val); - -#ifdef __cplusplus -} -#endif - -#endif // __vpp__ diff --git a/libtransport/src/hicn/transport/core/interest.cc b/libtransport/src/hicn/transport/core/interest.cc deleted file mode 100644 index 166632f..0000000 --- a/libtransport/src/hicn/transport/core/interest.cc +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Copyright (c) 2017-2019 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. - */ - -#include <hicn/transport/core/interest.h> -#include <hicn/transport/errors/errors.h> -#include <hicn/transport/utils/hash.h> - -extern "C" { -#ifndef _WIN32 -TRANSPORT_CLANG_DISABLE_WARNING("-Wextern-c-compat") -#endif -#include <hicn/hicn.h> -} - -#include <cstring> -#include <memory> - -namespace transport { - -namespace core { - -Interest::Interest(const Name &interest_name, Packet::Format format) - : Packet(format) { - if (hicn_interest_set_name(format_, packet_start_, - interest_name.getConstStructReference()) < 0) { - throw errors::MalformedPacketException(); - } - - if (hicn_interest_get_name(format_, packet_start_, - name_.getStructReference()) < 0) { - throw errors::MalformedPacketException(); - } -} - -#ifdef __ANDROID__ -Interest::Interest(hicn_format_t format) : Interest(Name("0::0|0"), format) {} -#else -Interest::Interest(hicn_format_t format) : Interest(base_name, format) {} -#endif - -Interest::Interest(const uint8_t *buffer, std::size_t size) - : Packet(buffer, size) { - if (hicn_interest_get_name(format_, packet_start_, - name_.getStructReference()) < 0) { - throw errors::MalformedPacketException(); - } -} - -Interest::Interest(MemBufPtr &&buffer) : Packet(std::move(buffer)) { - if (hicn_interest_get_name(format_, packet_start_, - name_.getStructReference()) < 0) { - throw errors::MalformedPacketException(); - } -} - -Interest::Interest(Interest &&other_interest) - : Packet(std::move(other_interest)) { - name_ = std::move(other_interest.name_); -} - -Interest::~Interest() {} - -void Interest::replace(MemBufPtr &&buffer) { - Packet::replace(std::move(buffer)); - - if (hicn_interest_get_name(format_, packet_start_, - name_.getStructReference()) < 0) { - throw errors::MalformedPacketException(); - } -} - -const Name &Interest::getName() const { - if (!name_) { - if (hicn_interest_get_name(format_, packet_start_, - (hicn_name_t *)name_.getConstStructReference()) < - 0) { - throw errors::MalformedPacketException(); - } - } - - return name_; -} - -Name &Interest::getWritableName() { return const_cast<Name &>(getName()); } - -void Interest::setName(const Name &name) { - if (hicn_interest_set_name(format_, packet_start_, - name.getConstStructReference()) < 0) { - throw errors::RuntimeException("Error setting interest name."); - } - - if (hicn_interest_get_name(format_, packet_start_, - name_.getStructReference()) < 0) { - throw errors::MalformedPacketException(); - } -} - -void Interest::setName(Name &&name) { - if (hicn_interest_set_name(format_, packet_start_, - name.getStructReference()) < 0) { - throw errors::RuntimeException("Error setting interest name."); - } - - if (hicn_interest_get_name(format_, packet_start_, - name_.getStructReference()) < 0) { - throw errors::MalformedPacketException(); - } -} - -void Interest::setLocator(const ip_address_t &ip_address) { - if (hicn_interest_set_locator(format_, packet_start_, &ip_address) < 0) { - throw errors::RuntimeException("Error setting interest locator."); - } - - return; -} - -ip_address_t Interest::getLocator() const { - ip_address_t ip; - - if (hicn_interest_get_locator(format_, packet_start_, &ip) < 0) { - throw errors::RuntimeException("Error getting interest locator."); - } - - return ip; -} - -void Interest::setLifetime(uint32_t lifetime) { - if (hicn_interest_set_lifetime(packet_start_, lifetime) < 0) { - throw errors::MalformedPacketException(); - } -} - -uint32_t Interest::getLifetime() const { - uint32_t lifetime = 0; - - if (hicn_interest_get_lifetime(packet_start_, &lifetime) < 0) { - throw errors::MalformedPacketException(); - } - - return lifetime; -} - -void Interest::resetForHash() { - if (hicn_interest_reset_for_hash( - format_, reinterpret_cast<hicn_header_t *>(packet_start_)) < 0) { - throw errors::RuntimeException( - "Error resetting interest fields for hash computation."); - } -} - -} // end namespace core - -} // end namespace transport diff --git a/libtransport/src/hicn/transport/core/interest.h b/libtransport/src/hicn/transport/core/interest.h deleted file mode 100644 index 48c833a..0000000 --- a/libtransport/src/hicn/transport/core/interest.h +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (c) 2017-2019 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/core/name.h> -#include <hicn/transport/core/packet.h> -#include <hicn/transport/utils/object_pool.h> - -namespace transport { - -namespace core { - -class Interest - : public Packet /*, public std::enable_shared_from_this<Interest>*/ { - public: - using Ptr = utils::ObjectPool<Interest>::Ptr; - - Interest(Packet::Format format = HF_INET6_TCP); - - Interest(const Name &interest_name, Packet::Format format = HF_INET6_TCP); - - Interest(const uint8_t *buffer, std::size_t size); - Interest(MemBufPtr &&buffer); - - /* - * Enforce zero-copy. - */ - Interest(const Interest &other_interest) = delete; - Interest &operator=(const Interest &other_interest) = delete; - - Interest(Interest &&other_interest); - - ~Interest() override; - - void replace(MemBufPtr &&buffer) override; - - const Name &getName() const override; - - Name &getWritableName() override; - - void setName(const Name &name) override; - - void setName(Name &&name) override; - - void setLocator(const ip_address_t &ip_address) override; - - ip_address_t getLocator() const override; - - void setLifetime(uint32_t lifetime) override; - - uint32_t getLifetime() const override; - - private: - void resetForHash() override; -}; - -} // end namespace core - -} // end namespace transport diff --git a/libtransport/src/hicn/transport/core/manifest.cc b/libtransport/src/hicn/transport/core/manifest.cc deleted file mode 100644 index 3f890f3..0000000 --- a/libtransport/src/hicn/transport/core/manifest.cc +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2017-2019 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. - */ - -#include <hicn/transport/core/manifest.h> - -namespace transport { - -namespace core { - -std::string ManifestEncoding::manifest_type = std::string("manifest_type"); - -std::map<ManifestType, std::string> ManifestEncoding::manifest_types = { - {FINAL_CHUNK_NUMBER, "FinalChunkNumber"}, {NAME_LIST, "NameList"}}; - -std::string ManifestEncoding::final_chunk_number = - std::string("final_chunk_number"); -std::string ManifestEncoding::content_name = std::string("content_name"); - -} // end namespace core - -} // end namespace transport
\ No newline at end of file diff --git a/libtransport/src/hicn/transport/core/manifest.h b/libtransport/src/hicn/transport/core/manifest.h deleted file mode 100644 index 9650de9..0000000 --- a/libtransport/src/hicn/transport/core/manifest.h +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Copyright (c) 2017-2019 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/core/content_object.h> -#include <hicn/transport/core/manifest_format.h> -#include <hicn/transport/core/name.h> - -#include <set> - -namespace transport { - -namespace core { - -using typename core::Name; -using typename core::Packet; -using typename core::PayloadType; - -template <typename Base, typename FormatTraits, typename ManifestImpl> -class Manifest : public Base { - static_assert(std::is_base_of<Packet, Base>::value, - "Base must inherit from packet!"); - - public: - using Encoder = typename FormatTraits::Encoder; - using Decoder = typename FormatTraits::Decoder; - - Manifest(std::size_t signature_size = 0) - : Base(HF_INET6_TCP_AH), - encoder_(*this, signature_size), - decoder_(*this) { - Base::setPayloadType(PayloadType::MANIFEST); - } - - Manifest(const core::Name &name, std::size_t signature_size = 0) - : Base(name, HF_INET6_TCP_AH), - encoder_(*this, signature_size), - decoder_(*this) { - Base::setPayloadType(PayloadType::MANIFEST); - } - - template <typename T> - Manifest(T &&base) - : Base(std::forward<T &&>(base)), encoder_(*this), decoder_(*this) { - Base::setPayloadType(PayloadType::MANIFEST); - } - - virtual ~Manifest() = default; - - std::size_t estimateManifestSize(std::size_t additional_entries = 0) { - return static_cast<ManifestImpl &>(*this).estimateManifestSizeImpl( - additional_entries); - } - - /* - * After the call to encode, users MUST call clear before adding data - * to the manifest. - */ - Manifest &encode() { return static_cast<ManifestImpl &>(*this).encodeImpl(); } - - Manifest &decode() { - Manifest::decoder_.decode(); - - manifest_type_ = decoder_.getManifestType(); - hash_algorithm_ = decoder_.getHashAlgorithm(); - is_last_ = decoder_.getIsFinalManifest(); - - return static_cast<ManifestImpl &>(*this).decodeImpl(); - } - - static std::size_t getManifestHeaderSize() { - return Encoder::getManifestHeaderSize(); - } - - static std::size_t getManifestEntrySize() { - return Encoder::getManifestEntrySize(); - } - - Manifest &setManifestType(ManifestType type) { - manifest_type_ = type; - encoder_.setManifestType(manifest_type_); - return *this; - } - - Manifest &setHashAlgorithm(HashAlgorithm hash_algorithm) { - hash_algorithm_ = hash_algorithm; - encoder_.setHashAlgorithm(hash_algorithm_); - return *this; - } - - HashAlgorithm getHashAlgorithm() { return hash_algorithm_; } - - ManifestType getManifestType() const { return manifest_type_; } - - bool isFinalManifest() const { return is_last_; } - - Manifest &setVersion(ManifestVersion version) { - encoder_.setVersion(version); - return *this; - } - - Manifest &setFinalBlockNumber(std::uint32_t final_block_number) { - encoder_.setFinalBlockNumber(final_block_number); - return *this; - } - - uint32_t getFinalBlockNumber() const { - return decoder_.getFinalBlockNumber(); - } - - ManifestVersion getVersion() const { return decoder_.getVersion(); } - - Manifest &setFinalManifest(bool is_final_manifest) { - encoder_.setIsFinalManifest(is_final_manifest); - is_last_ = is_final_manifest; - return *this; - } - - Manifest &clear() { - encoder_.clear(); - decoder_.clear(); - return *this; - } - - protected: - ManifestType manifest_type_; - HashAlgorithm hash_algorithm_; - bool is_last_; - - Encoder encoder_; - Decoder decoder_; -}; - -} // end namespace core - -} // end namespace transport diff --git a/libtransport/src/hicn/transport/core/manifest_format.h b/libtransport/src/hicn/transport/core/manifest_format.h deleted file mode 100644 index 9b67772..0000000 --- a/libtransport/src/hicn/transport/core/manifest_format.h +++ /dev/null @@ -1,210 +0,0 @@ -/* - * Copyright (c) 2017-2019 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/core/name.h> -#include <hicn/transport/utils/crypto_hasher.h> - -#include <cinttypes> -#include <type_traits> -#include <unordered_map> - -namespace transport { - -namespace core { - -enum class ManifestFields : uint8_t { - VERSION, - HASH_ALGORITHM, - SEGMENT_CALCULATION_STRATEGY, - FINAL_MANIFEST, - NAME_HASH_LIST, - BASE_NAME -}; - -enum class ManifestVersion : uint8_t { - VERSION_1 = 1, -}; - -enum class ManifestType : uint8_t { - INLINE_MANIFEST = 1, - FINAL_CHUNK_NUMBER = 2, - FLIC_MANIFEST = 3, -}; - -enum class HashAlgorithm : uint8_t { - SHA_256 = static_cast<uint8_t>(utils::CryptoHashType::SHA_256), - SHA_512 = static_cast<uint8_t>(utils::CryptoHashType::SHA_512), - CRC32C = static_cast<uint8_t>(utils::CryptoHashType::CRC32C), -}; - -/** - * INCREMENTAL: Manifests will be received inline with the data with no specific - * assumption regarding the manifest capacity. Consumers can send interests - * using a +1 heuristic. - * - * MANIFEST_CAPACITY_BASED: manifests with capacity N have a suffix multiple of - * N+1: 0, N+1, 2(N+1) etc. Contents have a suffix incremented by 1 except when - * it conflicts with a manifest: 1, 2, ..., N, N+2, N+3, ..., 2N+1, 2N+3 - */ -enum class NextSegmentCalculationStrategy : uint8_t { - INCREMENTAL = 1, - MANIFEST_CAPACITY_BASED = 2, -}; - -template <typename T> -struct format_traits { - using Encoder = typename T::Encoder; - using Decoder = typename T::Decoder; - using HashType = typename T::HashType; - using HashList = typename T::HashList; -}; - -class Packet; - -template <typename Implementation> -class ManifestEncoder { - public: - virtual ~ManifestEncoder() = default; - - ManifestEncoder encode() { - return static_cast<Implementation &>(*this).encodeImpl(); - } - - ManifestEncoder &clear() { - return static_cast<Implementation &>(*this).clearImpl(); - } - - ManifestEncoder &setManifestType(ManifestType type) { - return static_cast<Implementation &>(*this).setManifestTypeImpl(type); - } - - ManifestEncoder &setHashAlgorithm(HashAlgorithm hash) { - return static_cast<Implementation &>(*this).setHashAlgorithmImpl(hash); - } - - ManifestEncoder &setFinalChunkNumber(uint32_t final_chunk) { - return static_cast<Implementation &>(*this).setFinalChunkImpl(final_chunk); - } - - ManifestEncoder &setNextSegmentCalculationStrategy( - NextSegmentCalculationStrategy strategy) { - return static_cast<Implementation &>(*this) - .setNextSegmentCalculationStrategyImpl(strategy); - } - - template < - typename T, - typename = std::enable_if_t<std::is_same< - std::remove_const_t<std::remove_reference_t<T>>, core::Name>::value>> - ManifestEncoder &setBaseName(T &&name) { - return static_cast<Implementation &>(*this).setBaseNameImpl(name); - } - - template <typename Hash> - ManifestEncoder &addSuffixAndHash(uint32_t suffix, Hash &&hash) { - return static_cast<Implementation &>(*this).addSuffixAndHashImpl( - suffix, std::forward<Hash &&>(hash)); - } - - ManifestEncoder &setIsFinalManifest(bool is_last) { - return static_cast<Implementation &>(*this).setIsFinalManifestImpl(is_last); - } - - ManifestEncoder &setVersion(ManifestVersion version) { - return static_cast<Implementation &>(*this).setVersionImpl(version); - } - - std::size_t estimateSerializedLength(std::size_t number_of_entries) { - return static_cast<Implementation &>(*this).estimateSerializedLengthImpl( - number_of_entries); - } - - ManifestEncoder &update() { - return static_cast<Implementation &>(*this).updateImpl(); - } - - ManifestEncoder &setFinalBlockNumber(std::uint32_t final_block_number) { - return static_cast<Implementation &>(*this).setFinalBlockNumberImpl( - final_block_number); - } - - static std::size_t getManifestHeaderSize() { - return Implementation::getManifestHeaderSizeImpl(); - } - - static std::size_t getManifestEntrySize() { - return Implementation::getManifestEntrySizeImpl(); - } -}; - -template <typename Implementation> -class ManifestDecoder { - public: - virtual ~ManifestDecoder() = default; - - ManifestDecoder &clear() { - return static_cast<Implementation &>(*this).clearImpl(); - } - - void decode() { static_cast<Implementation &>(*this).decodeImpl(); } - - ManifestType getManifestType() const { - return static_cast<const Implementation &>(*this).getManifestTypeImpl(); - } - - HashAlgorithm getHashAlgorithm() const { - return static_cast<const Implementation &>(*this).getHashAlgorithmImpl(); - } - - uint32_t getFinalChunkNumber() const { - return static_cast<const Implementation &>(*this).getFinalChunkImpl(); - } - - NextSegmentCalculationStrategy getNextSegmentCalculationStrategy() const { - return static_cast<const Implementation &>(*this) - .getNextSegmentCalculationStrategyImpl(); - } - - core::Name getBaseName() const { - return static_cast<const Implementation &>(*this).getBaseNameImpl(); - } - - auto getSuffixHashList() { - return static_cast<Implementation &>(*this).getSuffixHashListImpl(); - } - - bool getIsFinalManifest() const { - return static_cast<const Implementation &>(*this).getIsFinalManifestImpl(); - } - - ManifestVersion getVersion() const { - return static_cast<const Implementation &>(*this).getVersionImpl(); - } - - std::size_t estimateSerializedLength(std::size_t number_of_entries) const { - return static_cast<const Implementation &>(*this) - .estimateSerializedLengthImpl(number_of_entries); - } - - uint32_t getFinalBlockNumber() const { - return static_cast<const Implementation &>(*this).getFinalBlockNumberImpl(); - } -}; - -} // namespace core - -} // namespace transport diff --git a/libtransport/src/hicn/transport/core/manifest_format_fixed.cc b/libtransport/src/hicn/transport/core/manifest_format_fixed.cc deleted file mode 100644 index f5e31d7..0000000 --- a/libtransport/src/hicn/transport/core/manifest_format_fixed.cc +++ /dev/null @@ -1,226 +0,0 @@ -/* - * Copyright (c) 2017-2019 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. - */ - -#include <hicn/transport/core/manifest_format_fixed.h> -#include <hicn/transport/core/packet.h> -#include <hicn/transport/utils/literals.h> - -namespace transport { - -namespace core { - -// TODO use preallocated pool of membufs -FixedManifestEncoder::FixedManifestEncoder(Packet &packet, - std::size_t signature_size) - : packet_(packet), - max_size_(Packet::default_mtu - packet_.headerSize() - signature_size), - manifest_( - utils::MemBuf::create(Packet::default_mtu - packet_.headerSize())), - manifest_header_( - reinterpret_cast<ManifestHeader *>(manifest_->writableData())), - manifest_entries_(reinterpret_cast<ManifestEntry *>( - manifest_->writableData() + sizeof(ManifestHeader))), - current_entry_(0), - signature_size_(signature_size) { - *manifest_header_ = {0}; -} - -FixedManifestEncoder::~FixedManifestEncoder() {} - -FixedManifestEncoder &FixedManifestEncoder::encodeImpl() { - manifest_->append(sizeof(ManifestHeader) + - manifest_header_->number_of_entries * - sizeof(ManifestEntry)); - packet_.appendPayload(std::move(manifest_)); - return *this; -} - -FixedManifestEncoder &FixedManifestEncoder::clearImpl() { - manifest_ = utils::MemBuf::create(Packet::default_mtu - packet_.headerSize() - - signature_size_); - return *this; -} - -FixedManifestEncoder &FixedManifestEncoder::setHashAlgorithmImpl( - HashAlgorithm algorithm) { - manifest_header_->hash_algorithm = static_cast<uint8_t>(algorithm); - return *this; -} - -FixedManifestEncoder &FixedManifestEncoder::setManifestTypeImpl( - ManifestType manifest_type) { - manifest_header_->manifest_type = static_cast<uint8_t>(manifest_type); - return *this; -} - -FixedManifestEncoder & -FixedManifestEncoder::setNextSegmentCalculationStrategyImpl( - NextSegmentCalculationStrategy strategy) { - manifest_header_->next_segment_strategy = static_cast<uint8_t>(strategy); - return *this; -} - -FixedManifestEncoder &FixedManifestEncoder::setBaseNameImpl( - const core::Name &base_name) { - base_name.copyToDestination( - reinterpret_cast<uint8_t *>(&manifest_header_->prefix[0]), false); - manifest_header_->flags.ipv6 = - base_name.getAddressFamily() == AF_INET6 ? 1_U8 : 0_U8; - return *this; -} - -FixedManifestEncoder &FixedManifestEncoder::addSuffixAndHashImpl( - uint32_t suffix, const utils::CryptoHash &hash) { - auto _hash = hash.getDigest<std::uint8_t>(); - addSuffixHashBytes(suffix, _hash.data(), _hash.length()); - return *this; -} - -void FixedManifestEncoder::addSuffixHashBytes(uint32_t suffix, - const uint8_t *hash, - std::size_t length) { - manifest_entries_[current_entry_].suffix = htonl(suffix); - // std::copy(hash, hash + length, - // manifest_entries_[current_entry_].hash); - std::memcpy( - reinterpret_cast<uint8_t *>(manifest_entries_[current_entry_].hash), hash, - length); - - manifest_header_->number_of_entries++; - current_entry_++; - - if (TRANSPORT_EXPECT_FALSE(estimateSerializedLengthImpl() > max_size_)) { - throw errors::RuntimeException("Manifest size exceeded the packet MTU!"); - } -} - -FixedManifestEncoder &FixedManifestEncoder::setIsFinalManifestImpl( - bool is_last) { - manifest_header_->flags.is_last = static_cast<uint8_t>(is_last); - return *this; -} - -FixedManifestEncoder &FixedManifestEncoder::setVersionImpl( - ManifestVersion version) { - manifest_header_->version = static_cast<uint8_t>(version); - return *this; -} - -std::size_t FixedManifestEncoder::estimateSerializedLengthImpl( - std::size_t additional_entries) { - return sizeof(ManifestHeader) + - (manifest_header_->number_of_entries + additional_entries) * - sizeof(ManifestEntry); -} - -FixedManifestEncoder &FixedManifestEncoder::updateImpl() { - max_size_ = Packet::default_mtu - packet_.headerSize() - signature_size_; - return *this; -} - -FixedManifestEncoder &FixedManifestEncoder::setFinalBlockNumberImpl( - std::uint32_t final_block_number) { - manifest_header_->final_block_number = htonl(final_block_number); - return *this; -} - -std::size_t FixedManifestEncoder::getManifestHeaderSizeImpl() { - return sizeof(ManifestHeader); -} - -std::size_t FixedManifestEncoder::getManifestEntrySizeImpl() { - return sizeof(ManifestEntry); -} - -FixedManifestDecoder::FixedManifestDecoder(Packet &packet) - : packet_(packet), - manifest_header_(reinterpret_cast<ManifestHeader *>( - packet_.getPayload()->writableData())), - manifest_entries_(reinterpret_cast<ManifestEntry *>( - packet_.getPayload()->writableData() + sizeof(ManifestHeader))) {} - -FixedManifestDecoder::~FixedManifestDecoder() {} - -void FixedManifestDecoder::decodeImpl() { - std::size_t packet_size = packet_.payloadSize(); - - if (packet_size < sizeof(ManifestHeader) || - packet_size < estimateSerializedLengthImpl()) { - throw errors::RuntimeException( - "The packet does not match expected manifest size."); - } -} - -FixedManifestDecoder &FixedManifestDecoder::clearImpl() { return *this; } - -ManifestType FixedManifestDecoder::getManifestTypeImpl() const { - return static_cast<ManifestType>(manifest_header_->manifest_type); -} - -HashAlgorithm FixedManifestDecoder::getHashAlgorithmImpl() const { - return static_cast<HashAlgorithm>(manifest_header_->hash_algorithm); -} - -NextSegmentCalculationStrategy -FixedManifestDecoder::getNextSegmentCalculationStrategyImpl() const { - return static_cast<NextSegmentCalculationStrategy>( - manifest_header_->next_segment_strategy); -} - -typename Fixed::SuffixList FixedManifestDecoder::getSuffixHashListImpl() { - typename Fixed::SuffixList hash_list; - - for (int i = 0; i < manifest_header_->number_of_entries; i++) { - hash_list.insert(hash_list.end(), - std::make_pair(ntohl(manifest_entries_[i].suffix), - reinterpret_cast<uint8_t *>( - &manifest_entries_[i].hash[0]))); - } - - return hash_list; -} - -core::Name FixedManifestDecoder::getBaseNameImpl() const { - if (static_cast<bool>(manifest_header_->flags.ipv6)) { - return core::Name(AF_INET6, - reinterpret_cast<uint8_t *>(&manifest_header_->prefix)); - } else { - return core::Name(AF_INET, - reinterpret_cast<uint8_t *>(&manifest_header_->prefix)); - } -} - -bool FixedManifestDecoder::getIsFinalManifestImpl() const { - return static_cast<bool>(manifest_header_->flags.is_last); -} - -ManifestVersion FixedManifestDecoder::getVersionImpl() const { - return static_cast<ManifestVersion>(manifest_header_->version); -} - -std::size_t FixedManifestDecoder::estimateSerializedLengthImpl( - std::size_t additional_entries) const { - return sizeof(ManifestHeader) + - (additional_entries + manifest_header_->number_of_entries) * - sizeof(ManifestEntry); -} - -uint32_t FixedManifestDecoder::getFinalBlockNumberImpl() const { - return ntohl(manifest_header_->final_block_number); -} - -} // end namespace core - -} // end namespace transport diff --git a/libtransport/src/hicn/transport/core/manifest_format_fixed.h b/libtransport/src/hicn/transport/core/manifest_format_fixed.h deleted file mode 100644 index 2c6e2bc..0000000 --- a/libtransport/src/hicn/transport/core/manifest_format_fixed.h +++ /dev/null @@ -1,171 +0,0 @@ -/* - * Copyright (c) 2017-2019 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/core/manifest_format.h> -#include <hicn/transport/core/packet.h> - -#include <string> - -namespace transport { - -namespace core { - -// 0 1 2 3 -// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// |Version| MType |HashAlg|NextStr| Flags |NumberOfEntries| -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// | Final Block Number | -// +---------------------------------------------------------------| -// | | -// + + -// | | -// + Prefix + -// | | -// + + -// | | -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// | Suffix | -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// | Hash Value | -// | | -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - -class FixedManifestEncoder; -class FixedManifestDecoder; -class Packet; - -struct Fixed { - using Encoder = FixedManifestEncoder; - using Decoder = FixedManifestDecoder; - using HashType = utils::CryptoHash; - using SuffixList = std::list<std::pair<std::uint32_t, std::uint8_t *>>; -}; - -struct Flags { - std::uint8_t ipv6 : 1; - std::uint8_t is_last : 1; - std::uint8_t unused : 6; -}; - -struct ManifestEntry { - std::uint32_t suffix; - std::uint32_t hash[8]; -}; - -struct ManifestHeader { - std::uint8_t version : 4; - std::uint8_t manifest_type : 4; - std::uint8_t hash_algorithm : 4; - std::uint8_t next_segment_strategy : 4; - Flags flags; - std::uint8_t number_of_entries; - std::uint32_t final_block_number; - std::uint32_t prefix[4]; - ManifestEntry entries[0]; -}; - -static const constexpr std::uint8_t manifest_version = 1; - -class FixedManifestEncoder : public ManifestEncoder<FixedManifestEncoder> { - public: - FixedManifestEncoder(Packet &packet, std::size_t signature_size = 0); - - ~FixedManifestEncoder(); - - FixedManifestEncoder &encodeImpl(); - - FixedManifestEncoder &clearImpl(); - - FixedManifestEncoder &setManifestTypeImpl(ManifestType manifest_type); - - FixedManifestEncoder &setHashAlgorithmImpl(HashAlgorithm algorithm); - - FixedManifestEncoder &setNextSegmentCalculationStrategyImpl( - NextSegmentCalculationStrategy strategy); - - FixedManifestEncoder &setBaseNameImpl(const core::Name &base_name); - - FixedManifestEncoder &addSuffixAndHashImpl(uint32_t suffix, - const utils::CryptoHash &hash); - - FixedManifestEncoder &setIsFinalManifestImpl(bool is_last); - - FixedManifestEncoder &setVersionImpl(ManifestVersion version); - - std::size_t estimateSerializedLengthImpl(std::size_t additional_entries = 0); - - FixedManifestEncoder &updateImpl(); - - FixedManifestEncoder &setFinalBlockNumberImpl( - std::uint32_t final_block_number); - - static std::size_t getManifestHeaderSizeImpl(); - - static std::size_t getManifestEntrySizeImpl(); - - private: - void addSuffixHashBytes(uint32_t suffix, const uint8_t *hash, - std::size_t length); - - Packet &packet_; - std::size_t max_size_; - std::unique_ptr<utils::MemBuf> manifest_; - ManifestHeader *manifest_header_; - ManifestEntry *manifest_entries_; - std::size_t current_entry_; - std::size_t signature_size_; -}; - -class FixedManifestDecoder : public ManifestDecoder<FixedManifestDecoder> { - public: - FixedManifestDecoder(Packet &packet); - - ~FixedManifestDecoder(); - - void decodeImpl(); - - FixedManifestDecoder &clearImpl(); - - ManifestType getManifestTypeImpl() const; - - HashAlgorithm getHashAlgorithmImpl() const; - - NextSegmentCalculationStrategy getNextSegmentCalculationStrategyImpl() const; - - typename Fixed::SuffixList getSuffixHashListImpl(); - - core::Name getBaseNameImpl() const; - - bool getIsFinalManifestImpl() const; - - std::size_t estimateSerializedLengthImpl( - std::size_t additional_entries = 0) const; - - ManifestVersion getVersionImpl() const; - - uint32_t getFinalBlockNumberImpl() const; - - private: - Packet &packet_; - ManifestHeader *manifest_header_; - ManifestEntry *manifest_entries_; -}; - -} // namespace core - -} // namespace transport diff --git a/libtransport/src/hicn/transport/core/manifest_inline.h b/libtransport/src/hicn/transport/core/manifest_inline.h deleted file mode 100644 index 385e43a..0000000 --- a/libtransport/src/hicn/transport/core/manifest_inline.h +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright (c) 2017-2019 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/core/manifest.h> -#include <hicn/transport/core/manifest_format.h> -#include <hicn/transport/portability/portability.h> -#include <set> - -namespace transport { - -namespace core { - -template <typename Base, typename FormatTraits> -class ManifestInline - : public Manifest<Base, FormatTraits, ManifestInline<Base, FormatTraits>> { - using ManifestBase = - Manifest<Base, FormatTraits, ManifestInline<Base, FormatTraits>>; - using HashType = typename FormatTraits::HashType; - using SuffixList = typename FormatTraits::SuffixList; - - public: - ManifestInline() : ManifestBase() {} - - ManifestInline(const core::Name &name, std::size_t signature_size = 0) - : ManifestBase(name, signature_size) {} - - template <typename T> - ManifestInline(T &&base) : ManifestBase(std::forward<T &&>(base)) {} - - static TRANSPORT_ALWAYS_INLINE ManifestInline *createManifest( - const core::Name &manifest_name, ManifestVersion version, - ManifestType type, HashAlgorithm algorithm, bool is_last, - const Name &base_name, NextSegmentCalculationStrategy strategy, - std::size_t signature_size) { - auto manifest = new ManifestInline(manifest_name, signature_size); - manifest->setVersion(version); - manifest->setManifestType(type); - manifest->setHashAlgorithm(algorithm); - manifest->setFinalManifest(is_last); - manifest->setBaseName(base_name); - manifest->setNextSegmentCalculationStrategy(strategy); - - return manifest; - } - - ManifestInline &encodeImpl() { - ManifestBase::encoder_.encode(); - return *this; - } - - ManifestInline &decodeImpl() { - base_name_ = ManifestBase::decoder_.getBaseName(); - next_segment_strategy_ = - ManifestBase::decoder_.getNextSegmentCalculationStrategy(); - suffix_hash_map_ = ManifestBase::decoder_.getSuffixHashList(); - - return *this; - } - - std::size_t estimateManifestSizeImpl(std::size_t additional_entries = 0) { - return ManifestBase::encoder_.estimateSerializedLength(additional_entries); - } - - ManifestInline &setBaseName(const Name &name) { - base_name_ = name; - ManifestBase::encoder_.setBaseName(base_name_); - return *this; - } - - const Name &getBaseName() { return base_name_; } - - ManifestInline &addSuffixHash(uint32_t suffix, const HashType &hash) { - ManifestBase::encoder_.addSuffixAndHash(suffix, hash); - return *this; - } - - // Call this function only after the decode function! - const SuffixList &getSuffixList() { return suffix_hash_map_; } - - ManifestInline &setNextSegmentCalculationStrategy( - NextSegmentCalculationStrategy strategy) { - next_segment_strategy_ = strategy; - ManifestBase::encoder_.setNextSegmentCalculationStrategy( - next_segment_strategy_); - return *this; - } - - NextSegmentCalculationStrategy getNextSegmentCalculationStrategy() { - return next_segment_strategy_; - } - - private: - core::Name base_name_; - NextSegmentCalculationStrategy next_segment_strategy_; - SuffixList suffix_hash_map_; -}; - -} // end namespace core - -} // end namespace transport
\ No newline at end of file diff --git a/libtransport/src/hicn/transport/core/memif_connector.cc b/libtransport/src/hicn/transport/core/memif_connector.cc deleted file mode 100644 index 5e37c88..0000000 --- a/libtransport/src/hicn/transport/core/memif_connector.cc +++ /dev/null @@ -1,493 +0,0 @@ -/* - * Copyright (c) 2017-2019 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. - */ - -#include <hicn/transport/core/memif_connector.h> -#include <hicn/transport/errors/not_implemented_exception.h> - -#ifdef __vpp__ - -#include <sys/epoll.h> -#include <cstdlib> - -extern "C" { -#include <memif/libmemif.h> -}; - -#define CANCEL_TIMER 1 - -namespace transport { - -namespace core { - -struct memif_connection { - uint16_t index; - /* memif conenction handle */ - memif_conn_handle_t conn; - /* transmit queue id */ - uint16_t tx_qid; - /* tx buffers */ - memif_buffer_t *tx_bufs; - /* allocated tx buffers counter */ - /* number of tx buffers pointing to shared memory */ - uint16_t tx_buf_num; - /* rx buffers */ - memif_buffer_t *rx_bufs; - /* allcoated rx buffers counter */ - /* number of rx buffers pointing to shared memory */ - uint16_t rx_buf_num; - /* interface ip address */ - uint8_t ip_addr[4]; -}; - -std::once_flag MemifConnector::flag_; -utils::EpollEventReactor MemifConnector::main_event_reactor_; - -MemifConnector::MemifConnector(PacketReceivedCallback &&receive_callback, - OnReconnect &&on_reconnect_callback, - asio::io_service &io_service, - std::string app_name) - : Connector(std::move(receive_callback), std::move(on_reconnect_callback)), - memif_worker_(nullptr), - timer_set_(false), - send_timer_(std::make_unique<utils::FdDeadlineTimer>(event_reactor_)), - disconnect_timer_( - std::make_unique<utils::FdDeadlineTimer>(event_reactor_)), - io_service_(io_service), - packet_counter_(0), - memif_connection_(std::make_unique<memif_connection_t>()), - tx_buf_counter_(0), - is_reconnection_(false), - data_available_(false), - app_name_(app_name), - socket_filename_("") { - std::call_once(MemifConnector::flag_, &MemifConnector::init, this); -} - -MemifConnector::~MemifConnector() { close(); } - -void MemifConnector::init() { - /* initialize memory interface */ - int err = memif_init(controlFdUpdate, const_cast<char *>(app_name_.c_str()), - nullptr, nullptr, nullptr); - - if (TRANSPORT_EXPECT_FALSE(err != MEMIF_ERR_SUCCESS)) { - TRANSPORT_LOGE("memif_init: %s", memif_strerror(err)); - } -} - -void MemifConnector::connect(uint32_t memif_id, long memif_mode) { - state_ = ConnectorState::CONNECTING; - - memif_id_ = memif_id; - socket_filename_ = "/run/vpp/memif.sock"; - - createMemif(memif_id, memif_mode, nullptr); - - work_ = std::make_unique<asio::io_service::work>(io_service_); - - while (state_ != ConnectorState::CONNECTED) { - MemifConnector::main_event_reactor_.runOneEvent(); - } - - int err; - - /* get interrupt queue id */ - int fd = -1; - err = memif_get_queue_efd(memif_connection_->conn, 0, &fd); - if (TRANSPORT_EXPECT_FALSE(err != MEMIF_ERR_SUCCESS)) { - TRANSPORT_LOGE("memif_get_queue_efd: %s", memif_strerror(err)); - return; - } - - // Remove fd from main epoll - main_event_reactor_.delFileDescriptor(fd); - - // Add fd to epoll of instance - event_reactor_.addFileDescriptor( - fd, EPOLLIN, [this](const utils::Event &evt) -> int { - return onInterrupt(memif_connection_->conn, this, 0); - }); - - memif_worker_ = std::make_unique<std::thread>( - std::bind(&MemifConnector::threadMain, this)); -} - -int MemifConnector::createMemif(uint32_t index, uint8_t mode, char *s) { - memif_connection_t *c = memif_connection_.get(); - - /* setting memif connection arguments */ - memif_conn_args_t args; - memset(&args, 0, sizeof(args)); - - args.is_master = mode; - args.log2_ring_size = MEMIF_LOG2_RING_SIZE; - args.buffer_size = MEMIF_BUF_SIZE; - args.num_s2m_rings = 1; - args.num_m2s_rings = 1; - strncpy((char *)args.interface_name, IF_NAME, strlen(IF_NAME) + 1); - args.mode = memif_interface_mode_t::MEMIF_INTERFACE_MODE_IP; - - int err; - - err = memif_create_socket(&args.socket, socket_filename_.c_str(), nullptr); - - if (TRANSPORT_EXPECT_FALSE(err != MEMIF_ERR_SUCCESS)) { - throw errors::RuntimeException(memif_strerror(err)); - } - - args.interface_id = index; - /* last argument for memif_create (void * private_ctx) is used by user - to identify connection. this context is returned with callbacks */ - - /* default interrupt */ - if (s == nullptr) { - err = memif_create(&c->conn, &args, onConnect, onDisconnect, onInterrupt, - this); - - if (TRANSPORT_EXPECT_FALSE(err != MEMIF_ERR_SUCCESS)) { - throw errors::RuntimeException(memif_strerror(err)); - } - } - - c->index = (uint16_t)index; - c->tx_qid = 0; - /* alloc memif buffers */ - c->rx_buf_num = 0; - c->rx_bufs = static_cast<memif_buffer_t *>( - malloc(sizeof(memif_buffer_t) * MAX_MEMIF_BUFS)); - c->tx_buf_num = 0; - c->tx_bufs = static_cast<memif_buffer_t *>( - malloc(sizeof(memif_buffer_t) * MAX_MEMIF_BUFS)); - - // memif_set_rx_mode (c->conn, MEMIF_RX_MODE_POLLING, 0); - - return 0; -} - -int MemifConnector::deleteMemif() { - memif_connection_t *c = memif_connection_.get(); - - if (c->rx_bufs) { - free(c->rx_bufs); - } - - c->rx_bufs = nullptr; - c->rx_buf_num = 0; - - if (c->tx_bufs) { - free(c->tx_bufs); - } - - c->tx_bufs = nullptr; - c->tx_buf_num = 0; - - int err; - /* disconenct then delete memif connection */ - err = memif_delete(&c->conn); - - if (TRANSPORT_EXPECT_FALSE(err != MEMIF_ERR_SUCCESS)) { - TRANSPORT_LOGE("memif_delete: %s", memif_strerror(err)); - } - - if (TRANSPORT_EXPECT_FALSE(c->conn != nullptr)) { - TRANSPORT_LOGE("memif delete fail"); - } - - return 0; -} - -int MemifConnector::controlFdUpdate(int fd, uint8_t events, void *private_ctx) { - /* convert memif event definitions to epoll events */ - if (events & MEMIF_FD_EVENT_DEL) { - return MemifConnector::main_event_reactor_.delFileDescriptor(fd); - } - - uint32_t evt = 0; - - if (events & MEMIF_FD_EVENT_READ) { - evt |= EPOLLIN; - } - - if (events & MEMIF_FD_EVENT_WRITE) { - evt |= EPOLLOUT; - } - - if (events & MEMIF_FD_EVENT_MOD) { - return MemifConnector::main_event_reactor_.modFileDescriptor(fd, evt); - } - - return MemifConnector::main_event_reactor_.addFileDescriptor( - fd, evt, [](const utils::Event &evt) -> int { - uint32_t event = 0; - int memif_err = 0; - - if (evt.events & EPOLLIN) { - event |= MEMIF_FD_EVENT_READ; - } - - if (evt.events & EPOLLOUT) { - event |= MEMIF_FD_EVENT_WRITE; - } - - if (evt.events & EPOLLERR) { - event |= MEMIF_FD_EVENT_ERROR; - } - - memif_err = memif_control_fd_handler(evt.data.fd, event); - - if (TRANSPORT_EXPECT_FALSE(memif_err != MEMIF_ERR_SUCCESS)) { - TRANSPORT_LOGE("memif_control_fd_handler: %s", - memif_strerror(memif_err)); - } - - return 0; - }); -} - -int MemifConnector::bufferAlloc(long n, uint16_t qid) { - memif_connection_t *c = memif_connection_.get(); - int err; - uint16_t r; - /* set data pointer to shared memory and set buffer_len to shared mmeory - * buffer len */ - err = memif_buffer_alloc(c->conn, qid, c->tx_bufs, n, &r, 2000); - - if (TRANSPORT_EXPECT_FALSE(err != MEMIF_ERR_SUCCESS)) { - TRANSPORT_LOGE("memif_buffer_alloc: %s", memif_strerror(err)); - } - - c->tx_buf_num += r; - return r; -} - -int MemifConnector::txBurst(uint16_t qid) { - memif_connection_t *c = memif_connection_.get(); - int err; - uint16_t r; - /* inform peer memif interface about data in shared memory buffers */ - /* mark memif buffers as free */ - err = memif_tx_burst(c->conn, qid, c->tx_bufs, c->tx_buf_num, &r); - - if (TRANSPORT_EXPECT_FALSE(err != MEMIF_ERR_SUCCESS)) { - TRANSPORT_LOGE("memif_tx_burst: %s", memif_strerror(err)); - } - - // err = memif_refill_queue(c->conn, qid, r, 0); - - if (TRANSPORT_EXPECT_FALSE(err != MEMIF_ERR_SUCCESS)) { - TRANSPORT_LOGE("memif_tx_burst: %s", memif_strerror(err)); - c->tx_buf_num -= r; - return -1; - } - - c->tx_buf_num -= r; - return 0; -} - -void MemifConnector::sendCallback(const std::error_code &ec) { - timer_set_ = false; - - if (TRANSPORT_EXPECT_TRUE(!ec && state_ == ConnectorState::CONNECTED)) { - doSend(); - } -} - -void MemifConnector::processInputBuffer() { - Packet::MemBufPtr ptr; - - while (input_buffer_.pop(ptr)) { - receive_callback_(std::move(ptr)); - } -} - -/* informs user about connected status. private_ctx is used by user to identify - connection (multiple connections WIP) */ -int MemifConnector::onConnect(memif_conn_handle_t conn, void *private_ctx) { - MemifConnector *connector = (MemifConnector *)private_ctx; - connector->state_ = ConnectorState::CONNECTED; - memif_refill_queue(conn, 0, -1, 0); - - return 0; -} - -/* informs user about disconnected status. private_ctx is used by user to - identify connection (multiple connections WIP) */ -int MemifConnector::onDisconnect(memif_conn_handle_t conn, void *private_ctx) { - MemifConnector *connector = (MemifConnector *)private_ctx; - connector->state_ = ConnectorState::CLOSED; - return 0; -} - -void MemifConnector::threadMain() { event_reactor_.runEventLoop(1000); } - -int MemifConnector::onInterrupt(memif_conn_handle_t conn, void *private_ctx, - uint16_t qid) { - MemifConnector *connector = (MemifConnector *)private_ctx; - - memif_connection_t *c = connector->memif_connection_.get(); - int err = MEMIF_ERR_SUCCESS, ret_val; - uint16_t rx; - - do { - err = memif_rx_burst(conn, qid, c->rx_bufs, MAX_MEMIF_BUFS, &rx); - ret_val = err; - - if (TRANSPORT_EXPECT_FALSE(err != MEMIF_ERR_SUCCESS && - err != MEMIF_ERR_NOBUF)) { - TRANSPORT_LOGE("memif_rx_burst: %s", memif_strerror(err)); - goto error; - } - - c->rx_buf_num += rx; - - if (TRANSPORT_EXPECT_TRUE(connector->io_service_.stopped())) { - TRANSPORT_LOGE("socket stopped: ignoring %u packets", rx); - goto error; - } - - std::size_t packet_length; - for (int i = 0; i < rx; i++) { - auto packet = connector->getPacket(); - packet_length = (c->rx_bufs + i)->len; - std::memcpy(packet->writableData(), - reinterpret_cast<const uint8_t *>((c->rx_bufs + i)->data), - packet_length); - packet->append(packet_length); - - if (!connector->input_buffer_.push(std::move(packet))) { - TRANSPORT_LOGE("Error pushing packet. Ring buffer full."); - - // TODO Here we should consider the possibility to signal the congestion - // to the application, that would react properly (e.g. slow down - // message) - } - } - - /* mark memif buffers and shared memory buffers as free */ - /* free processed buffers */ - - err = memif_refill_queue(conn, qid, rx, 0); - - if (TRANSPORT_EXPECT_FALSE(err != MEMIF_ERR_SUCCESS)) { - TRANSPORT_LOGE("memif_buffer_free: %s", memif_strerror(err)); - } - - c->rx_buf_num -= rx; - - } while (ret_val == MEMIF_ERR_NOBUF); - - connector->io_service_.post( - std::bind(&MemifConnector::processInputBuffer, connector)); - - return 0; - -error: - err = memif_refill_queue(c->conn, qid, rx, 0); - - if (TRANSPORT_EXPECT_FALSE(err != MEMIF_ERR_SUCCESS)) { - TRANSPORT_LOGE("memif_buffer_free: %s", memif_strerror(err)); - } - c->rx_buf_num -= rx; - - return 0; -} - -void MemifConnector::close() { - if (state_ != ConnectorState::CLOSED) { - disconnect_timer_->expiresFromNow(std::chrono::microseconds(50)); - disconnect_timer_->asyncWait([this](const std::error_code &ec) { - deleteMemif(); - event_reactor_.stop(); - work_.reset(); - }); - - if (memif_worker_ && memif_worker_->joinable()) { - memif_worker_->join(); - } - } -} - -void MemifConnector::send(const Packet::MemBufPtr &packet) { - { - utils::SpinLock::Acquire locked(write_msgs_lock_); - output_buffer_.push_back(packet); - } -#if CANCEL_TIMER - if (!timer_set_) { - timer_set_ = true; - send_timer_->expiresFromNow(std::chrono::microseconds(50)); - send_timer_->asyncWait( - std::bind(&MemifConnector::sendCallback, this, std::placeholders::_1)); - } -#endif -} - -int MemifConnector::doSend() { - std::size_t max = 0; - uint16_t n = 0; - std::size_t size = 0; - - { - utils::SpinLock::Acquire locked(write_msgs_lock_); - size = output_buffer_.size(); - } - - do { - max = size < MAX_MEMIF_BUFS ? size : MAX_MEMIF_BUFS; - - if (TRANSPORT_EXPECT_FALSE( - (n = bufferAlloc(max, memif_connection_->tx_qid)) < 0)) { - TRANSPORT_LOGE("Error allocating buffers."); - return -1; - } - - for (uint16_t i = 0; i < n; i++) { - utils::SpinLock::Acquire locked(write_msgs_lock_); - - auto packet = output_buffer_.front().get(); - const utils::MemBuf *current = packet; - std::size_t offset = 0; - uint8_t *shared_buffer = - reinterpret_cast<uint8_t *>(memif_connection_->tx_bufs[i].data); - do { - std::memcpy(shared_buffer + offset, current->data(), current->length()); - offset += current->length(); - current = current->next(); - } while (current != packet); - - memif_connection_->tx_bufs[i].len = uint32_t(offset); - - output_buffer_.pop_front(); - } - - txBurst(memif_connection_->tx_qid); - - utils::SpinLock::Acquire locked(write_msgs_lock_); - size = output_buffer_.size(); - } while (size > 0); - - return 0; -} - -void MemifConnector::send(const uint8_t *packet, std::size_t len, - const PacketSentCallback &packet_sent) { - throw errors::NotImplementedException(); -} - -} // end namespace core - -} // end namespace transport - -#endif // __vpp__ diff --git a/libtransport/src/hicn/transport/core/memif_connector.h b/libtransport/src/hicn/transport/core/memif_connector.h deleted file mode 100644 index bf4e2d5..0000000 --- a/libtransport/src/hicn/transport/core/memif_connector.h +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Copyright (c) 2017-2019 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/config.h> -#include <hicn/transport/core/connector.h> -//#include <hicn/transport/core/hicn_vapi.h> -#include <hicn/transport/portability/portability.h> -#include <hicn/transport/utils/epoll_event_reactor.h> -#include <hicn/transport/utils/fd_deadline_timer.h> -#include <hicn/transport/utils/ring_buffer.h> - -#include <asio.hpp> -#include <deque> -#include <mutex> -#include <thread> - -#ifdef __vpp__ - -#define _Static_assert static_assert - -namespace transport { - -namespace core { - -typedef struct memif_connection memif_connection_t; - -#define APP_NAME "libtransport" -#define IF_NAME "vpp_connection" - -#define MEMIF_BUF_SIZE 2048 -#define MEMIF_LOG2_RING_SIZE 11 -#define MAX_MEMIF_BUFS (1 << MEMIF_LOG2_RING_SIZE) - -class MemifConnector : public Connector { - typedef void *memif_conn_handle_t; - - public: - MemifConnector(PacketReceivedCallback &&receive_callback, - OnReconnect &&on_reconnect_callback, - asio::io_service &io_service, - std::string app_name = "Libtransport"); - - ~MemifConnector() override; - - void send(const Packet::MemBufPtr &packet) override; - - void send(const uint8_t *packet, std::size_t len, - const PacketSentCallback &packet_sent = 0) override; - - void close() override; - - void connect(uint32_t memif_id, long memif_mode); - - TRANSPORT_ALWAYS_INLINE uint32_t getMemifId() { return memif_id_; }; - - private: - void init(); - - int doSend(); - - int createMemif(uint32_t index, uint8_t mode, char *s); - - uint32_t getMemifConfiguration(); - - int deleteMemif(); - - static int controlFdUpdate(int fd, uint8_t events, void *private_ctx); - - static int onConnect(memif_conn_handle_t conn, void *private_ctx); - - static int onDisconnect(memif_conn_handle_t conn, void *private_ctx); - - static int onInterrupt(memif_conn_handle_t conn, void *private_ctx, - uint16_t qid); - - void threadMain(); - - int txBurst(uint16_t qid); - - int bufferAlloc(long n, uint16_t qid); - - void sendCallback(const std::error_code &ec); - - void processInputBuffer(); - - private: - static utils::EpollEventReactor main_event_reactor_; - static std::unique_ptr<std::thread> main_worker_; - - int epfd; - std::unique_ptr<std::thread> memif_worker_; - utils::EpollEventReactor event_reactor_; - std::atomic_bool timer_set_; - std::unique_ptr<utils::FdDeadlineTimer> send_timer_; - std::unique_ptr<utils::FdDeadlineTimer> disconnect_timer_; - asio::io_service &io_service_; - std::unique_ptr<asio::io_service::work> work_; - uint32_t packet_counter_; - std::unique_ptr<memif_connection_t> memif_connection_; - uint16_t tx_buf_counter_; - - PacketRing input_buffer_; - bool is_reconnection_; - bool data_available_; - uint32_t memif_id_; - uint8_t memif_mode_; - std::string app_name_; - uint16_t transmission_index_; - utils::SpinLock write_msgs_lock_; - std::string socket_filename_; - - static std::once_flag flag_; -}; - -} // end namespace core - -} // end namespace transport - -#endif // __vpp__
\ No newline at end of file diff --git a/libtransport/src/hicn/transport/core/memif_vapi.c b/libtransport/src/hicn/transport/core/memif_vapi.c deleted file mode 100644 index 11cf424..0000000 --- a/libtransport/src/hicn/transport/core/memif_vapi.c +++ /dev/null @@ -1,144 +0,0 @@ -/* - * Copyright (c) 2017-2019 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. - */ -#include <hicn/transport/config.h> - -#ifdef __vpp__ - -#include <vapi/vapi_safe.h> -#include <vppinfra/clib.h> -#include <hicn/transport/core/memif_vapi.h> -#include <fcntl.h> -#include <inttypes.h> -#include <semaphore.h> -#include <string.h> -#include <sys/stat.h> - -DEFINE_VAPI_MSG_IDS_MEMIF_API_JSON - -static vapi_error_e memif_details_cb(vapi_ctx_t ctx, - void *callback_ctx, - vapi_error_e rv, - bool is_last, - vapi_payload_memif_details *reply) { - uint32_t *last_memif_id = (uint32_t *)callback_ctx; - uint32_t current_memif_id = 0; - if (reply != NULL) { - current_memif_id = reply->id; - } - else { - return rv; - } - - if (current_memif_id >= *last_memif_id) { - *last_memif_id = current_memif_id + 1; - } - - return rv; -} - -int memif_vapi_get_next_memif_id(vapi_ctx_t ctx, - uint32_t *memif_id) { - vapi_lock(); - vapi_msg_memif_dump * msg = vapi_alloc_memif_dump(ctx); - int ret = vapi_memif_dump(ctx, msg, memif_details_cb, memif_id); - vapi_unlock(); - return ret; -} - -static vapi_error_e memif_create_cb(vapi_ctx_t ctx, - void *callback_ctx, - vapi_error_e rv, - bool is_last, - vapi_payload_memif_create_reply *reply) { - memif_output_params_t *output_params = (memif_output_params_t *)callback_ctx; - - if (reply == NULL) - return rv; - - output_params->sw_if_index = reply->sw_if_index; - - return rv; -} - -int memif_vapi_create_memif(vapi_ctx_t ctx, - memif_create_params_t *input_params, - memif_output_params_t *output_params) { - vapi_lock(); - vapi_msg_memif_create * msg = vapi_alloc_memif_create(ctx); - - int ret = 0; - if (input_params->socket_id == ~0) { - // invalid socket-id - ret = -1; - goto END; - } - - if (!is_pow2(input_params->ring_size)) { - // ring size must be power of 2 - ret = -1; - goto END; - } - - if (input_params->rx_queues > 255 || input_params->rx_queues < 1) { - // rx queue must be between 1 - 255 - ret = -1; - goto END; - } - - if (input_params->tx_queues > 255 || input_params->tx_queues < 1) { - // tx queue must be between 1 - 255 - ret = -1; - goto END; - } - - msg->payload.role = input_params->role; - msg->payload.mode = input_params->mode; - msg->payload.rx_queues = input_params->rx_queues; - msg->payload.tx_queues = input_params->tx_queues; - msg->payload.id = input_params->id; - msg->payload.socket_id = input_params->socket_id; - msg->payload.ring_size = input_params->ring_size; - msg->payload.buffer_size = input_params->buffer_size; - - ret = vapi_memif_create(ctx, msg, memif_create_cb, output_params); - END: - vapi_unlock(); - return ret; -} - -static vapi_error_e memif_delete_cb(vapi_ctx_t ctx, - void *callback_ctx, - vapi_error_e rv, - bool is_last, - vapi_payload_memif_delete_reply *reply) { - if(reply == NULL) - return rv; - - return reply->retval; -} - -int memif_vapi_delete_memif(vapi_ctx_t ctx, - uint32_t sw_if_index) { - vapi_lock(); - vapi_msg_memif_delete * msg = vapi_alloc_memif_delete(ctx); - - msg->payload.sw_if_index = sw_if_index; - - int ret = vapi_memif_delete(ctx, msg, memif_delete_cb, NULL); - vapi_unlock(); - return ret; -} - -#endif // __vpp__ diff --git a/libtransport/src/hicn/transport/core/memif_vapi.h b/libtransport/src/hicn/transport/core/memif_vapi.h deleted file mode 100644 index c045cf0..0000000 --- a/libtransport/src/hicn/transport/core/memif_vapi.h +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2017-2019 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/config.h> - -#ifdef __vpp__ - -#ifdef __cplusplus -extern "C" { -#endif - -#include <vapi/memif.api.vapi.h> -#include "stdint.h" - -typedef struct memif_create_params_s { - uint8_t role; - uint8_t mode; - uint8_t rx_queues; - uint8_t tx_queues; - uint32_t id; - uint32_t socket_id; - uint8_t secret[24]; - uint32_t ring_size; - uint16_t buffer_size; - uint8_t hw_addr[6]; -} memif_create_params_t; - -typedef struct memif_output_params_s { - uint32_t sw_if_index; -} memif_output_params_t; - -int memif_vapi_get_next_memif_id(vapi_ctx_t ctx, - uint32_t *memif_id); - -int memif_vapi_create_memif(vapi_ctx_t ctx, - memif_create_params_t *input_params, - memif_output_params_t *output_params); - -int memif_vapi_delete_memif(vapi_ctx_t ctx, - uint32_t sw_if_index); - -#ifdef __cplusplus -} -#endif - -#endif // __vpp__
\ No newline at end of file diff --git a/libtransport/src/hicn/transport/core/name.cc b/libtransport/src/hicn/transport/core/name.cc deleted file mode 100644 index 85e2b85..0000000 --- a/libtransport/src/hicn/transport/core/name.cc +++ /dev/null @@ -1,230 +0,0 @@ -/* - * Copyright (c) 2017-2019 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. - */ - -#include <hicn/transport/core/manifest_format.h> -#include <hicn/transport/core/name.h> -#include <hicn/transport/errors/errors.h> -#include <hicn/transport/errors/tokenizer_exception.h> -#include <hicn/transport/utils/hash.h> -#include <hicn/transport/utils/string_tokenizer.h> - -namespace transport { - -namespace core { - -Name::Name() { name_ = {}; } - -Name::Name(int family, const uint8_t *ip_address, std::uint32_t suffix) - : name_({}) { - name_.type = HNT_UNSPEC; - std::size_t length; - uint8_t *dst = NULL; - - if (family == AF_INET) { - dst = name_.ip4.prefix_as_u8; - length = IPV4_ADDR_LEN; - name_.type = HNT_CONTIGUOUS_V4; - } else if (family == AF_INET6) { - dst = name_.ip6.prefix_as_u8; - length = IPV6_ADDR_LEN; - name_.type = HNT_CONTIGUOUS_V6; - } else { - throw errors::RuntimeException("Specified name family does not exist."); - } - - std::memcpy(dst, ip_address, length); - *reinterpret_cast<std::uint32_t *>(dst + length) = suffix; -} - -Name::Name(const char *name, uint32_t segment) { - name_.type = HNT_UNSPEC; - if (hicn_name_create(name, segment, &name_) < 0) { - throw errors::InvalidIpAddressException(); - } -} - -Name::Name(const std::string &uri, uint32_t segment) - : Name(uri.c_str(), segment) {} - -Name::Name(const std::string &uri) { - name_.type = HNT_UNSPEC; - utils::StringTokenizer tokenizer(uri, "|"); - std::string ip_address; - std::string seq_number; - - ip_address = tokenizer.nextToken(); - - try { - seq_number = tokenizer.nextToken(); - } catch (errors::TokenizerException &) { - seq_number = "0"; - } - - if (hicn_name_create(ip_address.c_str(), (uint32_t)atoi(seq_number.c_str()), - &name_) < 0) { - throw errors::InvalidIpAddressException(); - } -} - -Name::Name(const Name &name) { this->name_ = name.name_; } - -Name &Name::operator=(const Name &name) { - if (hicn_name_copy(&this->name_, &name.name_) < 0) { - throw errors::MalformedNameException(); - } - - return *this; -} - -bool Name::operator==(const Name &name) const { - return this->equals(name, true); -} - -bool Name::operator!=(const Name &name) const { - return !this->operator==(name); -} - -Name::operator bool() const { - return bool(hicn_name_empty((hicn_name_t *)&name_)); -} - -bool Name::equals(const Name &name, bool consider_segment) const { - return !hicn_name_compare(&name_, &name.name_, consider_segment); -} - -std::string Name::toString() const { - char *name = new char[100]; - int ret = hicn_name_ntop(&name_, name, standard_name_string_length); - if (ret < 0) { - throw errors::MalformedNameException(); - } - std::string name_string(name); - delete[] name; - - return name_string; -} - -uint32_t Name::getHash32(bool consider_suffix) const { - uint32_t hash; - if (hicn_name_hash(&name_, &hash, consider_suffix) < 0) { - throw errors::RuntimeException("Error computing the hash of the name!"); - } - return hash; -} - -void Name::clear() { name_.type = HNT_UNSPEC; }; - -Name::Type Name::getType() const { return name_.type; } - -uint32_t Name::getSuffix() const { - uint32_t ret = 0; - if (hicn_name_get_seq_number((hicn_name_t *)&name_, &ret) < 0) { - throw errors::RuntimeException( - "Impossible to retrieve the sequence number from the name."); - } - return ret; -} - -Name &Name::setSuffix(uint32_t seq_number) { - if (hicn_name_set_seq_number(&name_, seq_number) < 0) { - throw errors::RuntimeException( - "Impossible to set the sequence number to the name."); - } - - return *this; -} - -std::shared_ptr<Sockaddr> Name::getAddress() const { - Sockaddr *ret = nullptr; - - switch (name_.type) { - case HNT_CONTIGUOUS_V4: - case HNT_IOV_V4: - ret = (Sockaddr *)new Sockaddr4; - break; - case HNT_CONTIGUOUS_V6: - case HNT_IOV_V6: - ret = (Sockaddr *)new Sockaddr6; - break; - default: - throw errors::MalformedNameException(); - } - - if (hicn_name_to_sockaddr_address((hicn_name_t *)&name_, ret) < 0) { - throw errors::MalformedNameException(); - } - - return std::shared_ptr<Sockaddr>(ret); -} - -ip_prefix_t Name::toIpAddress() const { - ip_prefix_t ret; - std::memset(&ret, 0, sizeof(ret)); - - if (hicn_name_to_ip_prefix(&name_, &ret) < 0) { - throw errors::InvalidIpAddressException(); - } - - return ret; -} - -int Name::getAddressFamily() const { - int ret = 0; - - if (hicn_name_get_family(&name_, &ret) < 0) { - throw errors::InvalidIpAddressException(); - } - - return ret; -} - -void Name::copyToDestination(uint8_t *destination, bool include_suffix) const { - if (hicn_name_copy_to_destination(destination, &name_, include_suffix) < 0) { - throw errors::RuntimeException( - "Impossibe to copy the name into the " - "provided destination"); - } -} - -std::ostream &operator<<(std::ostream &os, const Name &name) { - const std::string &str = name.toString(); - // os << "core:/"; - os << str; - - return os; -} - -size_t hash<transport::core::Name>::operator()( - const transport::core::Name &name) const { - return name.getHash32(false); -} - -size_t compare2<transport::core::Name>::operator()( - const transport::core::Name &name1, - const transport::core::Name &name2) const { - return name1.equals(name2, false); -} - -} // end namespace core - -} // end namespace transport - -namespace std { -size_t hash<transport::core::Name>::operator()( - const transport::core::Name &name) const { - return name.getHash32(); -} - -} // end namespace std diff --git a/libtransport/src/hicn/transport/core/name.h b/libtransport/src/hicn/transport/core/name.h deleted file mode 100644 index ea72797..0000000 --- a/libtransport/src/hicn/transport/core/name.h +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright (c) 2017-2019 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/portability.h> -#include <hicn/transport/utils/branch_prediction.h> - -#include <list> -#include <memory> -#include <string> -#include <unordered_map> - -extern "C" { -#ifndef _WIN32 -TRANSPORT_CLANG_DISABLE_WARNING("-Wextern-c-compat") -#endif -#include <hicn/hicn.h> -}; - -#include <vector> - -namespace transport { - -namespace core { - -typedef struct sockaddr_in6 Sockaddr6; -typedef struct sockaddr_in Sockaddr4; -typedef struct sockaddr Sockaddr; - -enum class HashAlgorithm : uint8_t; - -class Name { - friend class Packet; - friend class ContentObject; - friend class Interest; - - static const uint32_t standard_name_string_length = 100; - - public: - using NameStruct = hicn_name_t; - using Type = hicn_name_type_t; - - Name(); - - /** - * @brief Create name - * @param name The null-terminated URI string - */ - Name(const char *name, uint32_t segment); - - Name(int family, const uint8_t *ip_address, std::uint32_t suffix = 0); - - Name(const std::string &uri, uint32_t segment); - - Name(const std::string &uri); - - Name(const Name &name); - - Name &operator=(const Name &name); - - bool operator==(const Name &name) const; - - bool operator!=(const Name &name) const; - - operator bool() const; - - std::string toString() const; - - bool equals(const Name &name, bool consider_segment = true) const; - - uint32_t getHash32(bool consider_suffix = true) const; - - void clear(); - - Type getType() const; - - uint32_t getSuffix() const; - - std::shared_ptr<Sockaddr> getAddress() const; - - Name &setSuffix(uint32_t seq_number); - - ip_prefix_t toIpAddress() const; - - void copyToDestination(uint8_t *destination, - bool include_suffix = false) const; - - int getAddressFamily() const; - - private: - TRANSPORT_ALWAYS_INLINE const NameStruct *getConstStructReference() const { - return &name_; - } - - TRANSPORT_ALWAYS_INLINE NameStruct *getStructReference() { return &name_; } - - NameStruct name_; -}; - -std::ostream &operator<<(std::ostream &os, const Name &name); - -template <typename T> -struct hash {}; - -template <> -struct hash<transport::core::Name> { - size_t operator()(const transport::core::Name &name) const; -}; - -template <typename T> -struct compare2 {}; - -template <> -struct compare2<transport::core::Name> { - size_t operator()(const transport::core::Name &name1, const transport::core::Name &name2) const; -}; - -} // end namespace core - -} // end namespace transport - - -namespace std { -template <> -struct hash<transport::core::Name> { - size_t operator()(const transport::core::Name &name) const; -}; - -} // end namespace std diff --git a/libtransport/src/hicn/transport/core/packet.cc b/libtransport/src/hicn/transport/core/packet.cc deleted file mode 100644 index 817f8de..0000000 --- a/libtransport/src/hicn/transport/core/packet.cc +++ /dev/null @@ -1,607 +0,0 @@ -/* - * Copyright (c) 2017-2019 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. - */ - -#include <hicn/transport/core/packet.h> -#include <hicn/transport/errors/malformed_packet_exception.h> -#include <hicn/transport/utils/hash.h> -#include <hicn/transport/utils/log.h> - -extern "C" { -#ifndef _WIN32 -TRANSPORT_CLANG_DISABLE_WARNING("-Wextern-c-compat") -#endif -#include <hicn/error.h> -} - -namespace transport { - -namespace core { - -const core::Name Packet::base_name("0::0|0"); - -Packet::Packet(Format format) - : packet_(utils::MemBuf::create(getHeaderSizeFromFormat(format, 256)) - .release()), - packet_start_(reinterpret_cast<hicn_header_t *>(packet_->writableData())), - header_head_(packet_.get()), - payload_head_(nullptr), - format_(format) { - if (hicn_packet_init_header(format, packet_start_) < 0) { - throw errors::RuntimeException("Unexpected error initializing the packet."); - } - - packet_->append(getHeaderSizeFromFormat(format_)); -} - -Packet::Packet(MemBufPtr &&buffer) - : packet_(std::move(buffer)), - packet_start_(reinterpret_cast<hicn_header_t *>(packet_->writableData())), - header_head_(packet_.get()), - payload_head_(nullptr), - format_(getFormatFromBuffer(packet_->writableData())) {} - -Packet::Packet(const uint8_t *buffer, std::size_t size) - : Packet(MemBufPtr(utils::MemBuf::copyBuffer(buffer, size).release())) {} - -Packet::Packet(Packet &&other) - : packet_(std::move(other.packet_)), - packet_start_(other.packet_start_), - header_head_(other.header_head_), - payload_head_(other.payload_head_), - format_(other.format_) { - other.packet_start_ = nullptr; - other.header_head_ = nullptr; - other.payload_head_ = nullptr; - other.format_ = HF_UNSPEC; -} - -Packet::~Packet() {} - -std::size_t Packet::getHeaderSizeFromFormat(Format format, - size_t signature_size) { - 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; -} - -std::size_t Packet::getHeaderSizeFromBuffer(Format format, - const uint8_t *buffer) { - size_t header_length; - if (hicn_packet_get_header_length(format, (hicn_header_t *)buffer, - &header_length) < 0) { - throw errors::MalformedPacketException(); - } - return header_length; -} - -bool Packet::isInterest(const uint8_t *buffer) { - bool is_interest = false; - - if (TRANSPORT_EXPECT_FALSE(hicn_packet_test_ece((const hicn_header_t *)buffer, - &is_interest) < 0)) { - throw errors::RuntimeException( - "Impossible to retrieve ece flag from packet"); - } - - return !is_interest; -} - -Packet::Format Packet::getFormatFromBuffer(const uint8_t *buffer) { - Format format = HF_UNSPEC; - - if (TRANSPORT_EXPECT_FALSE( - hicn_packet_get_format((const hicn_header_t *)buffer, &format) < 0)) { - throw errors::MalformedPacketException(); - } - - return format; -} - -std::size_t Packet::getPayloadSizeFromBuffer(Format format, - const uint8_t *buffer) { - std::size_t payload_length; - if (TRANSPORT_EXPECT_FALSE( - hicn_packet_get_payload_length(format, (hicn_header_t *)buffer, - &payload_length) < 0)) { - throw errors::MalformedPacketException(); - } - - return payload_length; -} - -void Packet::replace(MemBufPtr &&buffer) { - packet_ = std::move(buffer); - packet_start_ = reinterpret_cast<hicn_header_t *>(packet_->writableData()); - header_head_ = packet_.get(); - payload_head_ = nullptr; - format_ = getFormatFromBuffer(reinterpret_cast<uint8_t *>(packet_start_)); -} - -std::size_t Packet::payloadSize() const { - return getPayloadSizeFromBuffer(format_, - reinterpret_cast<uint8_t *>(packet_start_)); -} - -std::size_t Packet::headerSize() const { - return getHeaderSizeFromBuffer(format_, - reinterpret_cast<uint8_t *>(packet_start_)); -} - -Packet &Packet::appendPayload(std::unique_ptr<utils::MemBuf> &&payload) { - separateHeaderPayload(); - - if (!payload_head_) { - payload_head_ = payload.get(); - } - - header_head_->prependChain(std::move(payload)); - updateLength(); - return *this; -} - -Packet &Packet::appendPayload(const uint8_t *buffer, std::size_t length) { - return appendPayload(utils::MemBuf::copyBuffer(buffer, length)); -} - -Packet &Packet::appendHeader(std::unique_ptr<utils::MemBuf> &&header) { - separateHeaderPayload(); - - if (!payload_head_) { - header_head_->prependChain(std::move(header)); - } else { - payload_head_->prependChain(std::move(header)); - } - - updateLength(); - return *this; -} - -Packet &Packet::appendHeader(const uint8_t *buffer, std::size_t length) { - return appendHeader(utils::MemBuf::copyBuffer(buffer, length)); -} - -std::unique_ptr<utils::MemBuf> Packet::getPayload() const { - const_cast<Packet *>(this)->separateHeaderPayload(); - - // Hopefully the payload is contiguous - if (TRANSPORT_EXPECT_FALSE(payload_head_ && - payload_head_->next() != header_head_)) { - payload_head_->gather(payloadSize()); - } - - return payload_head_->cloneOne(); -} - -Packet &Packet::updateLength(std::size_t length) { - std::size_t total_length = length; - - for (utils::MemBuf *current = payload_head_; - current && current != header_head_; current = current->next()) { - total_length += current->length(); - } - - if (hicn_packet_set_payload_length(format_, packet_start_, total_length) < - 0) { - throw errors::RuntimeException("Error setting the packet payload."); - } - - return *this; -} - -PayloadType Packet::getPayloadType() const { - hicn_payload_type_t ret = HPT_UNSPEC; - - if (hicn_packet_get_payload_type(packet_start_, &ret) < 0) { - throw errors::RuntimeException("Impossible to retrieve payload type."); - } - - return PayloadType(ret); -} - -Packet &Packet::setPayloadType(PayloadType payload_type) { - if (hicn_packet_set_payload_type(packet_start_, - hicn_payload_type_t(payload_type)) < 0) { - throw errors::RuntimeException("Error setting payload type of the packet."); - } - - return *this; -} - -Packet::Format Packet::getFormat() const { - if (format_ == HF_UNSPEC) { - if (hicn_packet_get_format(packet_start_, &format_) < 0) { - throw errors::MalformedPacketException(); - } - } - - return format_; -} - -const std::shared_ptr<utils::MemBuf> Packet::acquireMemBufReference() const { - return packet_; -} - -void Packet::dump() const { - const_cast<Packet *>(this)->separateHeaderPayload(); - - std::cout << "HEADER -- Length: " << headerSize() << std::endl; - hicn_packet_dump((uint8_t *)header_head_->data(), headerSize()); - - std::cout << std::endl << "PAYLOAD -- Length: " << payloadSize() << std::endl; - for (utils::MemBuf *current = payload_head_; - current && current != header_head_; current = current->next()) { - std::cout << "MemBuf Length: " << current->length() << std::endl; - hicn_packet_dump((uint8_t *)current->data(), current->length()); - } -} - -void Packet::setSignatureSize(std::size_t size_bytes) { - int ret = hicn_packet_set_signature_size(format_, packet_start_, size_bytes); - - if (ret < 0) { - throw errors::RuntimeException("Packet without Authentication Header."); - } - - packet_->append(size_bytes); - updateLength(); -} - -uint8_t *Packet::getSignature() const { - uint8_t *signature; - int ret = hicn_packet_get_signature(format_, packet_start_, &signature); - - if (ret < 0) { - throw errors::RuntimeException("Packet without Authentication Header."); - } - - return signature; -} - -std::size_t Packet::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; -} - -void Packet::setSignatureTimestamp(const uint64_t ×tamp) { - int ret = - hicn_packet_set_signature_timestamp(format_, packet_start_, timestamp); - - if (ret < 0) { - throw errors::RuntimeException("Error setting the signature timestamp."); - } -} - -uint64_t Packet::getSignatureTimestamp() const { - uint64_t return_value; - int ret = hicn_packet_get_signature_timestamp(format_, packet_start_, - &return_value); - - if (ret < 0) { - throw errors::RuntimeException("Error getting the signature timestamp."); - } - - return return_value; -} - -void Packet::setValidationAlgorithm( - const utils::CryptoSuite &validation_algorithm) { - int ret = hicn_packet_set_validation_algorithm(format_, packet_start_, - uint8_t(validation_algorithm)); - - if (ret < 0) { - throw errors::RuntimeException("Error setting the validation algorithm."); - } -} - -utils::CryptoSuite Packet::getValidationAlgorithm() const { - uint8_t return_value; - int ret = hicn_packet_get_validation_algorithm(format_, packet_start_, - &return_value); - - if (ret < 0) { - throw errors::RuntimeException("Error getting the validation algorithm."); - } - - return utils::CryptoSuite(return_value); -} - -void Packet::setKeyId(const utils::KeyId &key_id) { - int ret = hicn_packet_set_key_id(format_, packet_start_, key_id.first); - - if (ret < 0) { - throw errors::RuntimeException("Error setting the key id."); - } -} - -utils::KeyId Packet::getKeyId() const { - utils::KeyId return_value; - int ret = hicn_packet_get_key_id(format_, packet_start_, &return_value.first, - &return_value.second); - - if (ret < 0) { - throw errors::RuntimeException("Error getting the validation algorithm."); - } - - return return_value; -} - -utils::CryptoHash Packet::computeDigest(HashAlgorithm algorithm) const { - utils::CryptoHasher hasher(static_cast<utils::CryptoHashType>(algorithm)); - hasher.init(); - - // Copy IP+TCP/ICMP header before zeroing them - hicn_header_t header_copy; - - hicn_packet_copy_header(format_, packet_start_, &header_copy, false); - - const_cast<Packet *>(this)->resetForHash(); - - auto current = header_head_; - do { - hasher.updateBytes(current->data(), current->length()); - current = current->next(); - } while (current != header_head_); - - hicn_packet_copy_header(format_, &header_copy, packet_start_, false); - - return hasher.finalize(); -} - -void Packet::setChecksum() { - uint16_t partial_csum = 0; - - for (utils::MemBuf *current = header_head_->next(); - current && current != header_head_; current = current->next()) { - if (partial_csum != 0) { - partial_csum = ~partial_csum; - } - partial_csum = csum(current->data(), current->length(), partial_csum); - } - if (hicn_packet_compute_header_checksum(format_, packet_start_, - partial_csum) < 0) { - throw errors::MalformedPacketException(); - } -} - -bool Packet::checkIntegrity() const { - if (hicn_packet_check_integrity(format_, packet_start_) < 0) { - return false; - } - - return true; -} - -Packet &Packet::setSyn() { - if (hicn_packet_set_syn(packet_start_) < 0) { - throw errors::RuntimeException("Error setting syn bit in the packet."); - } - - return *this; -} - -Packet &Packet::resetSyn() { - if (hicn_packet_reset_syn(packet_start_) < 0) { - throw errors::RuntimeException("Error resetting syn bit in the packet."); - } - - return *this; -} - -bool Packet::testSyn() const { - bool res = false; - if (hicn_packet_test_syn(packet_start_, &res) < 0) { - throw errors::RuntimeException("Error testing syn bit in the packet."); - } - - return res; -} - -Packet &Packet::setAck() { - if (hicn_packet_set_ack(packet_start_) < 0) { - throw errors::RuntimeException("Error setting ack bit in the packet."); - } - - return *this; -} - -Packet &Packet::resetAck() { - if (hicn_packet_reset_ack(packet_start_) < 0) { - throw errors::RuntimeException("Error resetting ack bit in the packet."); - } - - return *this; -} - -bool Packet::testAck() const { - bool res = false; - if (hicn_packet_test_ack(packet_start_, &res) < 0) { - throw errors::RuntimeException("Error testing ack bit in the packet."); - } - - return res; -} - -Packet &Packet::setRst() { - if (hicn_packet_set_rst(packet_start_) < 0) { - throw errors::RuntimeException("Error setting rst bit in the packet."); - } - - return *this; -} - -Packet &Packet::resetRst() { - if (hicn_packet_reset_rst(packet_start_) < 0) { - throw errors::RuntimeException("Error resetting rst bit in the packet."); - } - - return *this; -} - -bool Packet::testRst() const { - bool res = false; - if (hicn_packet_test_rst(packet_start_, &res) < 0) { - throw errors::RuntimeException("Error testing rst bit in the packet."); - } - - return res; -} - -Packet &Packet::setFin() { - if (hicn_packet_set_fin(packet_start_) < 0) { - throw errors::RuntimeException("Error setting fin bit in the packet."); - } - - return *this; -} - -Packet &Packet::resetFin() { - if (hicn_packet_reset_fin(packet_start_) < 0) { - throw errors::RuntimeException("Error resetting fin bit in the packet."); - } - - return *this; -} - -bool Packet::testFin() const { - bool res = false; - if (hicn_packet_test_fin(packet_start_, &res) < 0) { - throw errors::RuntimeException("Error testing fin bit in the packet."); - } - - return res; -} - -Packet &Packet::resetFlags() { - resetSyn(); - resetAck(); - resetRst(); - resetFin(); - - return *this; -} - -std::string Packet::printFlags() const { - std::string flags = ""; - if (testSyn()) { - flags += "S"; - } - if (testAck()) { - flags += "A"; - } - if (testRst()) { - flags += "R"; - } - if (testFin()) { - flags += "F"; - } - return flags; -} - -Packet &Packet::setSrcPort(uint16_t srcPort) { - if (hicn_packet_set_src_port(packet_start_, srcPort) < 0) { - throw errors::RuntimeException("Error setting source port in the packet."); - } - - return *this; -} - -Packet &Packet::setDstPort(uint16_t dstPort) { - if (hicn_packet_set_dst_port(packet_start_, dstPort) < 0) { - throw errors::RuntimeException( - "Error setting destination port in the packet."); - } - - return *this; -} - -uint16_t Packet::getSrcPort() const { - uint16_t port = 0; - - if (hicn_packet_get_src_port(packet_start_, &port) < 0) { - throw errors::RuntimeException("Error reading source port in the packet."); - } - - return port; -} - -uint16_t Packet::getDstPort() const { - uint16_t port = 0; - - if (hicn_packet_get_dst_port(packet_start_, &port) < 0) { - throw errors::RuntimeException( - "Error reading destination port in the packet."); - } - - return port; -} - -Packet &Packet::setTTL(uint8_t hops) { - if (hicn_packet_set_hoplimit(packet_start_, hops) < 0) { - throw errors::RuntimeException("Error setting TTL."); - } - - return *this; -} - -uint8_t Packet::getTTL() const { - uint8_t hops = 0; - if (hicn_packet_get_hoplimit(packet_start_, &hops) < 0) { - throw errors::RuntimeException("Error reading TTL."); - } - - return hops; -} - -void Packet::separateHeaderPayload() { - if (payload_head_) { - return; - } - - int signature_size = 0; - if (_is_ah(format_)) { - signature_size = (uint32_t)getSignatureSize(); - } - - auto header_size = getHeaderSizeFromFormat(format_, signature_size); - auto payload_length = packet_->length() - header_size; - - packet_->trimEnd(packet_->length()); - - auto payload = packet_->cloneOne(); - payload_head_ = payload.get(); - payload_head_->advance(header_size); - payload_head_->append(payload_length); - packet_->prependChain(std::move(payload)); - packet_->append(header_size); -} - -void Packet::resetPayload() { - if (packet_->isChained()) { - packet_->separateChain(packet_->next(), packet_->prev()); - payload_head_ = nullptr; - updateLength(); - } -} - -} // end namespace core - -} // end namespace transport diff --git a/libtransport/src/hicn/transport/core/packet.h b/libtransport/src/hicn/transport/core/packet.h deleted file mode 100644 index 35c8606..0000000 --- a/libtransport/src/hicn/transport/core/packet.h +++ /dev/null @@ -1,203 +0,0 @@ -/* - * Copyright (c) 2017-2019 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/core/name.h> -#include <hicn/transport/core/payload_type.h> -#include <hicn/transport/portability/portability.h> -#include <hicn/transport/utils/branch_prediction.h> -#include <hicn/transport/utils/crypto_hasher.h> -#include <hicn/transport/utils/crypto_suite.h> -#include <hicn/transport/utils/key_id.h> -#include <hicn/transport/utils/membuf.h> -#include <hicn/transport/utils/object_pool.h> - -namespace utils { -class Signer; -class Verifier; -} // namespace utils - -namespace transport { - -namespace core { - -/* - * Basic IP packet, modelled as circular chain of buffers: - * Header = H - * Payload = P - * - * H_0 --> H_1 --> H_2 --> P_0 --> P_1 --> P_2 - * \_______________________________________| - */ - -class Packet : public std::enable_shared_from_this<Packet> { - friend class utils::Signer; - friend class utils::Verifier; - - public: - using MemBufPtr = std::shared_ptr<utils::MemBuf>; - using Format = hicn_format_t; - static constexpr size_t default_mtu = 1500; - - /** - * Create new IP packet. Here we allocate just the header, - * 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_UNSPEC); - - /** - * Create new IP packet using raw buffer. - */ - Packet(const uint8_t *buffer, std::size_t size); - Packet(MemBufPtr &&buffer); - - /* - * Enforce zero-copy lifestyle. - */ - Packet(const Packet &other) = delete; - Packet &operator=(const Packet &other) = delete; - - /* - * Move constructor. - */ - Packet(Packet &&other); - - friend bool operator==(const Packet &l_packet, const Packet &r_packet); - - virtual ~Packet(); - - static std::size_t getHeaderSizeFromFormat(Format format, - std::size_t signature_size = 0); - - 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); - - static Format getFormatFromBuffer(const uint8_t *buffer); - - virtual void replace(MemBufPtr &&buffer); - - std::size_t payloadSize() const; - - std::size_t headerSize() const; - - const std::shared_ptr<utils::MemBuf> acquireMemBufReference() const; - - virtual const Name &getName() const = 0; - - virtual Name &getWritableName() = 0; - - virtual void setName(const Name &name) = 0; - - virtual void setName(Name &&name) = 0; - - virtual void setLifetime(uint32_t lifetime) = 0; - - virtual uint32_t getLifetime() const = 0; - - Packet &appendPayload(const uint8_t *buffer, std::size_t length); - - Packet &appendPayload(std::unique_ptr<utils::MemBuf> &&payload); - - Packet &appendHeader(std::unique_ptr<utils::MemBuf> &&header); - - Packet &appendHeader(const uint8_t *buffer, std::size_t length); - - std::unique_ptr<utils::MemBuf> getPayload() const; - - Packet &updateLength(std::size_t length = 0); - - PayloadType getPayloadType() const; - - Packet &setPayloadType(PayloadType payload_type); - - Format getFormat() const; - - void dump() const; - - virtual void setLocator(const ip_address_t &locator) = 0; - - virtual ip_address_t getLocator() const = 0; - - void setSignatureTimestamp(const uint64_t ×tamp); - - uint64_t getSignatureTimestamp() const; - - void setValidationAlgorithm(const utils::CryptoSuite &validation_algorithm); - - utils::CryptoSuite getValidationAlgorithm() const; - - void setKeyId(const utils::KeyId &key_id); - - utils::KeyId getKeyId() const; - - virtual utils::CryptoHash computeDigest(HashAlgorithm algorithm) const; - - void setChecksum(); - - 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; - - void resetPayload(); - - private: - virtual void resetForHash() = 0; - void setSignatureSize(std::size_t size_bytes); - std::size_t getSignatureSize() const; - uint8_t *getSignature() const; - void separateHeaderPayload(); - - protected: - Name name_; - MemBufPtr packet_; - hicn_header_t *packet_start_; - utils::MemBuf *header_head_; - utils::MemBuf *payload_head_; - mutable Format format_; - - static const core::Name base_name; -}; - -} // end namespace core - -} // end namespace transport diff --git a/libtransport/src/hicn/transport/core/payload_type.h b/libtransport/src/hicn/transport/core/payload_type.h deleted file mode 100644 index fa79db3..0000000 --- a/libtransport/src/hicn/transport/core/payload_type.h +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (c) 2017-2019 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 core { - -enum class PayloadType : uint16_t { - CONTENT_OBJECT = HPT_DATA, - MANIFEST = HPT_MANIFEST, -}; - -} // end namespace core - -} // end namespace transport
\ No newline at end of file diff --git a/libtransport/src/hicn/transport/core/pending_interest.cc b/libtransport/src/hicn/transport/core/pending_interest.cc deleted file mode 100644 index dbbd2c8..0000000 --- a/libtransport/src/hicn/transport/core/pending_interest.cc +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2017-2019 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. - */ - -#include <hicn/transport/core/pending_interest.h> - -namespace transport { - -namespace core { - -PendingInterest::PendingInterest() - : interest_(nullptr, nullptr), - timer_(), - on_content_object_callback_(), - on_interest_timeout_callback_() {} - -PendingInterest::PendingInterest(Interest::Ptr &&interest, - std::unique_ptr<asio::steady_timer> &&timer) - : interest_(std::move(interest)), - timer_(std::move(timer)), - on_content_object_callback_(), - on_interest_timeout_callback_() {} - -PendingInterest::PendingInterest( - Interest::Ptr &&interest, OnContentObjectCallback &&on_content_object, - OnInterestTimeoutCallback &&on_interest_timeout, - std::unique_ptr<asio::steady_timer> &&timer) - : interest_(std::move(interest)), - timer_(std::move(timer)), - on_content_object_callback_(std::move(on_content_object)), - on_interest_timeout_callback_(std::move(on_interest_timeout)) {} - -PendingInterest::~PendingInterest() {} - -void PendingInterest::cancelTimer() { timer_->cancel(); } - -void PendingInterest::setInterest(Interest::Ptr &&interest) { - interest_ = std::move(interest); -} - -Interest::Ptr &&PendingInterest::getInterest() { return std::move(interest_); } - -const OnContentObjectCallback &PendingInterest::getOnDataCallback() const { - return on_content_object_callback_; -} - -void PendingInterest::setOnContentObjectCallback( - OnContentObjectCallback &&on_content_object) { - PendingInterest::on_content_object_callback_ = on_content_object; -} - -const OnInterestTimeoutCallback &PendingInterest::getOnTimeoutCallback() const { - return on_interest_timeout_callback_; -} - -void PendingInterest::setOnTimeoutCallback( - OnInterestTimeoutCallback &&on_interest_timeout) { - PendingInterest::on_interest_timeout_callback_ = on_interest_timeout; -} - -} // end namespace core - -} // end namespace transport diff --git a/libtransport/src/hicn/transport/core/pending_interest.h b/libtransport/src/hicn/transport/core/pending_interest.h deleted file mode 100644 index c481cc2..0000000 --- a/libtransport/src/hicn/transport/core/pending_interest.h +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (c) 2017-2019 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/config.h> -#include <hicn/transport/core/content_object.h> -#include <hicn/transport/core/interest.h> -#include <hicn/transport/core/name.h> -#include <hicn/transport/portability/portability.h> -#include <hicn/transport/utils/deadline_timer.h> - -#include <asio/steady_timer.hpp> - -namespace transport { - -namespace core { - -class HicnForwarderInterface; -class VPPForwarderInterface; -class RawSocketInterface; - -template <typename ForwarderInt> -class Portal; - -typedef std::function<void(Interest::Ptr &&, ContentObject::Ptr &&)> - OnContentObjectCallback; -typedef std::function<void(Interest::Ptr &&)> OnInterestTimeoutCallback; -typedef std::function<void(const std::error_code &)> TimerCallback; - -class PendingInterest { - friend class Portal<HicnForwarderInterface>; - friend class Portal<VPPForwarderInterface>; - friend class Portal<RawSocketInterface>; - - public: - using Ptr = utils::ObjectPool<PendingInterest>::Ptr; - PendingInterest(); - - PendingInterest(Interest::Ptr &&interest, - std::unique_ptr<asio::steady_timer> &&timer); - - PendingInterest(Interest::Ptr &&interest, - OnContentObjectCallback &&on_content_object, - OnInterestTimeoutCallback &&on_interest_timeout, - std::unique_ptr<asio::steady_timer> &&timer); - - ~PendingInterest(); - - template <typename Handler> - TRANSPORT_ALWAYS_INLINE void startCountdown(Handler &&cb) { - timer_->expires_from_now( - std::chrono::milliseconds(interest_->getLifetime())); - timer_->async_wait(std::forward<Handler &&>(cb)); - } - - void cancelTimer(); - - Interest::Ptr &&getInterest(); - - void setInterest(Interest::Ptr &&interest); - - const OnContentObjectCallback &getOnDataCallback() const; - - void setOnContentObjectCallback(OnContentObjectCallback &&on_content_object); - - const OnInterestTimeoutCallback &getOnTimeoutCallback() const; - - void setOnTimeoutCallback(OnInterestTimeoutCallback &&on_interest_timeout); - - private: - Interest::Ptr interest_; - std::unique_ptr<asio::steady_timer> timer_; - OnContentObjectCallback on_content_object_callback_; - OnInterestTimeoutCallback on_interest_timeout_callback_; -}; - -} // end namespace core - -} // end namespace transport diff --git a/libtransport/src/hicn/transport/core/portal.h b/libtransport/src/hicn/transport/core/portal.h deleted file mode 100644 index c6e11ad..0000000 --- a/libtransport/src/hicn/transport/core/portal.h +++ /dev/null @@ -1,695 +0,0 @@ -/* - * Copyright (c) 2017-2019 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/config.h> -#include <hicn/transport/core/content_object.h> -#include <hicn/transport/core/forwarder_interface.h> -#include <hicn/transport/core/interest.h> -#include <hicn/transport/core/name.h> -#include <hicn/transport/core/pending_interest.h> -#include <hicn/transport/core/prefix.h> -#include <hicn/transport/core/udp_socket_connector.h> -#include <hicn/transport/errors/errors.h> -#include <hicn/transport/portability/portability.h> -#include <hicn/transport/utils/log.h> - -#ifdef __vpp__ -#include <hicn/transport/core/memif_connector.h> -#endif - -#include <asio.hpp> -#include <asio/steady_timer.hpp> -#include <future> -#include <memory> -#include <queue> -#include <unordered_map> - -#define UNSET_CALLBACK 0 - -namespace transport { -namespace core { - -namespace portal_details { - -static constexpr uint32_t pool_size = 2048; - -class HandlerMemory { -#ifdef __vpp__ - static constexpr std::size_t memory_size = 1024 * 1024; - - public: - HandlerMemory() : index_(0) {} - - HandlerMemory(const HandlerMemory &) = delete; - HandlerMemory &operator=(const HandlerMemory &) = delete; - - TRANSPORT_ALWAYS_INLINE void *allocate(std::size_t size) { - return &storage_[index_++ % memory_size]; - } - - TRANSPORT_ALWAYS_INLINE void deallocate(void *pointer) {} - - private: - // Storage space used for handler-based custom memory allocation. - typename std::aligned_storage<128>::type storage_[memory_size]; - uint32_t index_; -#else - public: - HandlerMemory() {} - - HandlerMemory(const HandlerMemory &) = delete; - HandlerMemory &operator=(const HandlerMemory &) = delete; - - TRANSPORT_ALWAYS_INLINE void *allocate(std::size_t size) { - return ::operator new(size); - } - - TRANSPORT_ALWAYS_INLINE void deallocate(void *pointer) { - ::operator delete(pointer); - } -#endif -}; - -// The allocator to be associated with the handler objects. This allocator only -// needs to satisfy the C++11 minimal allocator requirements. -template <typename T> -class HandlerAllocator { - public: - using value_type = T; - - explicit HandlerAllocator(HandlerMemory &mem) : memory_(mem) {} - - template <typename U> - HandlerAllocator(const HandlerAllocator<U> &other) noexcept - : memory_(other.memory_) {} - - TRANSPORT_ALWAYS_INLINE bool operator==(const HandlerAllocator &other) const - noexcept { - return &memory_ == &other.memory_; - } - - TRANSPORT_ALWAYS_INLINE bool operator!=(const HandlerAllocator &other) const - noexcept { - return &memory_ != &other.memory_; - } - - TRANSPORT_ALWAYS_INLINE T *allocate(std::size_t n) const { - return static_cast<T *>(memory_.allocate(sizeof(T) * n)); - } - - TRANSPORT_ALWAYS_INLINE void deallocate(T *p, std::size_t /*n*/) const { - return memory_.deallocate(p); - } - - private: - template <typename> - friend class HandlerAllocator; - - // The underlying memory. - HandlerMemory &memory_; -}; - -// Wrapper class template for handler objects to allow handler memory -// allocation to be customised. The allocator_type type and get_allocator() -// member function are used by the asynchronous operations to obtain the -// allocator. Calls to operator() are forwarded to the encapsulated handler. -template <typename Handler> -class CustomAllocatorHandler { - public: - using allocator_type = HandlerAllocator<Handler>; - - CustomAllocatorHandler(HandlerMemory &m, Handler h) - : memory_(m), handler_(h) {} - - allocator_type get_allocator() const noexcept { - return allocator_type(memory_); - } - - template <typename... Args> - void operator()(Args &&... args) { - handler_(std::forward<Args>(args)...); - } - - private: - HandlerMemory &memory_; - Handler handler_; -}; - -// Helper function to wrap a handler object to add custom allocation. -template <typename Handler> -inline CustomAllocatorHandler<Handler> makeCustomAllocatorHandler( - HandlerMemory &m, Handler h) { - return CustomAllocatorHandler<Handler>(m, h); -} - -class Pool { - public: - Pool(asio::io_service &io_service) : io_service_(io_service) { - increasePendingInterestPool(); - increaseInterestPool(); - increaseContentObjectPool(); - } - - TRANSPORT_ALWAYS_INLINE void increasePendingInterestPool() { - // Create pool of pending interests to reuse - for (uint32_t i = 0; i < pool_size; i++) { - pending_interests_pool_.add(new PendingInterest( - Interest::Ptr(nullptr), - std::make_unique<asio::steady_timer>(io_service_))); - } - } - - TRANSPORT_ALWAYS_INLINE void increaseInterestPool() { - // Create pool of interests to reuse - for (uint32_t i = 0; i < pool_size; i++) { - interest_pool_.add(new Interest()); - } - } - - TRANSPORT_ALWAYS_INLINE void increaseContentObjectPool() { - // Create pool of content object to reuse - for (uint32_t i = 0; i < pool_size; i++) { - content_object_pool_.add(new ContentObject()); - } - } - - PendingInterest::Ptr getPendingInterest() { - auto res = pending_interests_pool_.get(); - while (TRANSPORT_EXPECT_FALSE(!res.first)) { - increasePendingInterestPool(); - res = pending_interests_pool_.get(); - } - - return std::move(res.second); - } - - TRANSPORT_ALWAYS_INLINE ContentObject::Ptr getContentObject() { - auto res = content_object_pool_.get(); - while (TRANSPORT_EXPECT_FALSE(!res.first)) { - increaseContentObjectPool(); - res = content_object_pool_.get(); - } - - return std::move(res.second); - } - - TRANSPORT_ALWAYS_INLINE Interest::Ptr getInterest() { - auto res = interest_pool_.get(); - while (TRANSPORT_EXPECT_FALSE(!res.first)) { - increaseInterestPool(); - res = interest_pool_.get(); - } - - return std::move(res.second); - } - - private: - utils::ObjectPool<PendingInterest> pending_interests_pool_; - utils::ObjectPool<ContentObject> content_object_pool_; - utils::ObjectPool<Interest> interest_pool_; - asio::io_service &io_service_; -}; - -} // namespace portal_details - -using PendingInterestHashTable = - std::unordered_map<uint32_t, PendingInterest::Ptr>; - -template <typename PrefixType> -class BasicBindConfig { - static_assert(std::is_same<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<Prefix>; - -/** - * Portal is a opaque class which is used for sending/receiving interest/data - * packets over multiple kind of connector. The connector itself is defined by - * the template ForwarderInt, which is resolved at compile time. It is then not - * possible to decide at runtime what the connector will be. - * - * The tasks performed by portal are the following: - * - Sending/Receiving Interest packets - * - Sending/Receiving Data packets - * - Set timers (one per interest), in order to trigger events if an interest is - * not satisfied - * - Register a producer prefix to the local forwarder - * - * The way of working of portal is event-based, which means that data and - * interests are sent/received in a asynchronous manner, and the notifications - * are performed through callbacks. - * - * The portal class is not thread safe, appropriate locking is required by the - * users of this class. - */ -template <typename ForwarderInt> -class Portal { - static_assert( - std::is_base_of<ForwarderInterface<ForwarderInt, - typename ForwarderInt::ConnectorType>, - ForwarderInt>::value, - "ForwarderInt must inherit from ForwarderInterface!"); - - public: - /** - * Consumer callback is an abstract class containing two methods to be - * implemented by a consumer application. - */ - class ConsumerCallback { - public: - virtual void onContentObject(Interest::Ptr &&i, ContentObject::Ptr &&c) = 0; - virtual void onTimeout(Interest::Ptr &&i) = 0; - }; - - /** - * Producer callback is an abstract class containing two methods to be - * implemented by a producer application. - */ - class ProducerCallback { - public: - virtual void onInterest(Interest::Ptr &&i) = 0; - }; - - Portal() : Portal(internal_io_service_) {} - - Portal(asio::io_service &io_service) - : io_service_(io_service), - packet_pool_(io_service), - app_name_("libtransport_application"), - consumer_callback_(nullptr), - producer_callback_(nullptr), - connector_(std::bind(&Portal::processIncomingMessages, this, - std::placeholders::_1), - std::bind(&Portal::setLocalRoutes, this), io_service_, - app_name_), - forwarder_interface_(connector_) {} - - /** - * Set the consumer callback. - * - * @param consumer_callback - The pointer to the ConsumerCallback object. - */ - void setConsumerCallback(ConsumerCallback *consumer_callback) { - consumer_callback_ = consumer_callback; - } - - /** - * Set the producer callback. - * - * @param producer_callback - The pointer to the ProducerCallback object. - */ - void setProducerCallback(ProducerCallback *producer_callback) { - producer_callback_ = producer_callback; - } - - /** - * Specify the output interface to use. This method will be useful in a future - * scenario where the library will be able to forward packets without - * connecting to a local forwarder. Now it is not used. - * - * @param output_interface - The output interface to use for - * forwarding/receiving packets. - */ - TRANSPORT_ALWAYS_INLINE void setOutputInterface( - const std::string &output_interface) { - forwarder_interface_.setOutputInterface(output_interface); - } - - /** - * Connect the transport to the local hicn forwarder. - * - * @param is_consumer - Boolean specifying if the application on top of portal - * is a consumer or a producer. - */ - TRANSPORT_ALWAYS_INLINE void connect(bool is_consumer = true) { - pending_interest_hash_table_.reserve(portal_details::pool_size); - forwarder_interface_.connect(is_consumer); - } - - /** - * Destructor. - */ - ~Portal() { killConnection(); } - - /** - * Check if there is already a pending interest for a given name. - * - * @param name - The interest name. - */ - TRANSPORT_ALWAYS_INLINE bool interestIsPending(const Name &name) { - auto it = - pending_interest_hash_table_.find(name.getHash32() + name.getSuffix()); - if (it != pending_interest_hash_table_.end()) { - return true; - } - - return false; - } - - /** - * Send an interest through to the local forwarder. - * - * @param interest - The pointer to the interest. The ownership of the - * interest is transferred by the caller to portal. - * - * @param on_content_object_callback - If the caller wishes to use a different - * callback to be called for this interest, it can set this parameter. - * Otherwise ConsumerCallback::onContentObject will be used. - * - * @param on_interest_timeout_callback - If the caller wishes to use a - * different callback to be called for this interest, it can set this - * parameter. Otherwise ConsumerCallback::onTimeout will be used. - */ - TRANSPORT_ALWAYS_INLINE void sendInterest( - Interest::Ptr &&interest, - OnContentObjectCallback &&on_content_object_callback = UNSET_CALLBACK, - OnInterestTimeoutCallback &&on_interest_timeout_callback = - UNSET_CALLBACK) { - uint32_t hash = - interest->getName().getHash32() + interest->getName().getSuffix(); - // Send it - forwarder_interface_.send(*interest); - - auto pending_interest = packet_pool_.getPendingInterest(); - pending_interest->setInterest(std::move(interest)); - pending_interest->setOnContentObjectCallback( - std::move(on_content_object_callback)); - pending_interest->setOnTimeoutCallback( - std::move(on_interest_timeout_callback)); - pending_interest->startCountdown(portal_details::makeCustomAllocatorHandler( - async_callback_memory_, std::bind(&Portal<ForwarderInt>::timerHandler, - this, std::placeholders::_1, hash))); - - auto it = pending_interest_hash_table_.find(hash); - if (it != pending_interest_hash_table_.end()) { - it->second->cancelTimer(); - - // Get reference to interest packet in order to have it destroyed. - auto _int = it->second->getInterest(); - it->second = std::move(pending_interest); - } else { - pending_interest_hash_table_[hash] = std::move(pending_interest); - } - } - - /** - * Handler fot the timer set when the interest is sent. - * - * @param ec - Error code which says whether the timer expired or has been - * canceled upon data packet reception. - * - * @param hash - The index of the interest in the pending interest hash table. - */ - TRANSPORT_ALWAYS_INLINE void timerHandler(const std::error_code &ec, - uint32_t hash) { - bool is_stopped = io_service_.stopped(); - if (TRANSPORT_EXPECT_FALSE(is_stopped)) { - return; - } - - if (TRANSPORT_EXPECT_TRUE(!ec)) { - PendingInterestHashTable::iterator it = - pending_interest_hash_table_.find(hash); - if (it != pending_interest_hash_table_.end()) { - PendingInterest::Ptr ptr = std::move(it->second); - pending_interest_hash_table_.erase(it); - auto _int = ptr->getInterest(); - - if (ptr->getOnTimeoutCallback() != UNSET_CALLBACK) { - ptr->on_interest_timeout_callback_(std::move(_int)); - } else if (consumer_callback_) { - consumer_callback_->onTimeout(std::move(_int)); - } - } - } - } - - /** - * 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. - */ - TRANSPORT_ALWAYS_INLINE void bind(const BindConfig &config) { - forwarder_interface_.setContentStoreSize(config.csReserved()); - served_namespaces_.push_back(config.prefix()); - - setLocalRoutes(); - } - - /** - * Start the event loop. This function blocks here and calls the callback set - * by the application upon interest/data received or timeout. - */ - TRANSPORT_ALWAYS_INLINE void runEventsLoop() { - if (io_service_.stopped()) { - io_service_.reset(); // ensure that run()/poll() will do some work - } - - io_service_.run(); - } - - /** - * Run one event and return. - */ - TRANSPORT_ALWAYS_INLINE void runOneEvent() { - if (io_service_.stopped()) { - io_service_.reset(); // ensure that run()/poll() will do some work - } - - io_service_.run_one(); - } - - /** - * 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. - */ - TRANSPORT_ALWAYS_INLINE void sendContentObject( - ContentObject &content_object) { - forwarder_interface_.send(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. - */ - TRANSPORT_ALWAYS_INLINE void stopEventsLoop() { - if (!io_service_.stopped()) { - io_service_.dispatch([this]() { - clear(); - io_service_.stop(); - }); - } - } - - /** - * Disconnect the transport from the local forwarder. - */ - TRANSPORT_ALWAYS_INLINE void killConnection() { - forwarder_interface_.closeConnection(); - } - - /** - * Clear the pending interest hash table. - */ - TRANSPORT_ALWAYS_INLINE void clear() { - if (!io_service_.stopped()) { - io_service_.dispatch(std::bind(&Portal::doClear, this)); - } else { - doClear(); - } - } - - /** - * Get a reference to the io_service object. - */ - TRANSPORT_ALWAYS_INLINE asio::io_service &getIoService() { - return io_service_; - } - - /** - * Register a route to the local forwarder. - */ - TRANSPORT_ALWAYS_INLINE void registerRoute(Prefix &prefix) { - served_namespaces_.push_back(prefix); - if (connector_.isConnected()) { - forwarder_interface_.registerRoute(prefix); - } - } - - private: - /** - * Clear the pending interest hash table. - */ - TRANSPORT_ALWAYS_INLINE void doClear() { - for (auto &pend_interest : pending_interest_hash_table_) { - pend_interest.second->cancelTimer(); - - // Get interest packet from pending interest and do nothing with it. It - // will get destroyed as it goes out of scope. - auto _int = pend_interest.second->getInterest(); - } - - pending_interest_hash_table_.clear(); - } - - /** - * Callback called by the underlying connector upon reception of a packet from - * the local forwarder. - * - * @param packet_buffer - The bytes of the packet. - */ - TRANSPORT_ALWAYS_INLINE void processIncomingMessages( - Packet::MemBufPtr &&packet_buffer) { - bool is_stopped = io_service_.stopped(); - if (TRANSPORT_EXPECT_FALSE(is_stopped)) { - return; - } - - if (TRANSPORT_EXPECT_FALSE( - ForwarderInt::isControlMessage(packet_buffer->data()))) { - processControlMessage(std::move(packet_buffer)); - return; - } - - Packet::Format format = Packet::getFormatFromBuffer(packet_buffer->data()); - - if (TRANSPORT_EXPECT_TRUE(_is_tcp(format))) { - if (!Packet::isInterest(packet_buffer->data())) { - auto content_object = packet_pool_.getContentObject(); - content_object->replace(std::move(packet_buffer)); - processContentObject(std::move(content_object)); - } else { - auto interest = packet_pool_.getInterest(); - interest->replace(std::move(packet_buffer)); - processInterest(std::move(interest)); - } - } else { - TRANSPORT_LOGE("Received not supported packet. Ignoring it."); - } - } - - /** - * Callback called by the transport upon connection to the local forwarder. - * It register the prefixes in the served_namespaces_ list to the local - * forwarder. - */ - TRANSPORT_ALWAYS_INLINE void setLocalRoutes() { - for (auto &prefix : served_namespaces_) { - if (connector_.isConnected()) { - forwarder_interface_.registerRoute(prefix); - } - } - } - - TRANSPORT_ALWAYS_INLINE void processInterest(Interest::Ptr &&interest) { - // Interest for a producer - if (TRANSPORT_EXPECT_TRUE(producer_callback_ != nullptr)) { - producer_callback_->onInterest(std::move(interest)); - } - } - - /** - * Process a content object: - * - Check if the data packet was effectively requested by portal - * - Delete its timer - * - Pass packet to application - * - * @param content_object - The data packet - */ - TRANSPORT_ALWAYS_INLINE void processContentObject( - ContentObject::Ptr &&content_object) { - uint32_t hash = content_object->getName().getHash32() + - content_object->getName().getSuffix(); - - auto it = pending_interest_hash_table_.find(hash); - if (it != pending_interest_hash_table_.end()) { - PendingInterest::Ptr interest_ptr = std::move(it->second); - pending_interest_hash_table_.erase(it); - interest_ptr->cancelTimer(); - auto _int = interest_ptr->getInterest(); - - if (interest_ptr->getOnDataCallback() != UNSET_CALLBACK) { - interest_ptr->on_content_object_callback_(std::move(_int), - std::move(content_object)); - } else if (consumer_callback_) { - consumer_callback_->onContentObject(std::move(_int), - std::move(content_object)); - } - } - } - - /** - * Process a control message. Control messages are different depending on the - * connector, then the forwarder_interface will do the job of understanding - * them. - */ - TRANSPORT_ALWAYS_INLINE void processControlMessage( - Packet::MemBufPtr &&packet_buffer) { - forwarder_interface_.processControlMessageReply(std::move(packet_buffer)); - } - - private: - asio::io_service &io_service_; - asio::io_service internal_io_service_; - portal_details::Pool packet_pool_; - - std::string app_name_; - - PendingInterestHashTable pending_interest_hash_table_; - std::list<Prefix> served_namespaces_; - - ConsumerCallback *consumer_callback_; - ProducerCallback *producer_callback_; - - portal_details::HandlerMemory async_callback_memory_; - - typename ForwarderInt::ConnectorType connector_; - ForwarderInt forwarder_interface_; -}; - -} // namespace core - -} // end namespace transport diff --git a/libtransport/src/hicn/transport/core/prefix.cc b/libtransport/src/hicn/transport/core/prefix.cc deleted file mode 100644 index 59898ab..0000000 --- a/libtransport/src/hicn/transport/core/prefix.cc +++ /dev/null @@ -1,338 +0,0 @@ -/* - * Copyright (c) 2017-2019 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. - */ - -#include <hicn/transport/core/prefix.h> -#include <hicn/transport/errors/errors.h> -#include <hicn/transport/utils/string_tokenizer.h> - -#ifndef _WIN32 -extern "C" { -#include <arpa/inet.h> -} -#else -#include <hicn/transport/portability/win_portability.h> -#endif - -#include <cstring> -#include <memory> -#include <random> - -#include <openssl/rand.h> - -namespace transport { - -namespace core { - -Prefix::Prefix() { std::memset(&ip_prefix_, 0, sizeof(ip_prefix_t)); } - -Prefix::Prefix(const char *prefix) : Prefix(std::string(prefix)) {} - -Prefix::Prefix(std::string &&prefix) : Prefix(prefix) {} - -Prefix::Prefix(const std::string &prefix) { - utils::StringTokenizer st(prefix, "/"); - - std::string ip_address = st.nextToken(); - int family = get_addr_family(ip_address.c_str()); - - std::string prefix_length = family == AF_INET6 ? "128" : "32"; - - if (st.hasMoreTokens()) { - prefix_length = st.nextToken(); - } - - buildPrefix(ip_address, uint16_t(atoi(prefix_length.c_str())), family); -} - -Prefix::Prefix(std::string &prefix, uint16_t prefix_length) { - int family = get_addr_family(prefix.c_str()); - buildPrefix(prefix, prefix_length, family); -} - -Prefix::Prefix(const core::Name &content_name, uint16_t prefix_length) { - int family = content_name.getAddressFamily(); - - if (!checkPrefixLengthAndAddressFamily(prefix_length, family)) { - throw errors::InvalidIpAddressException(); - } - - ip_prefix_ = content_name.toIpAddress(); - ip_prefix_.len = prefix_length; - ip_prefix_.family = family; -} - -void Prefix::buildPrefix(std::string &prefix, uint16_t prefix_length, - int family) { - if (!checkPrefixLengthAndAddressFamily(prefix_length, family)) { - throw errors::InvalidIpAddressException(); - } - - int ret; - switch (family) { - case AF_INET: - ret = inet_pton(AF_INET, prefix.c_str(), ip_prefix_.address.v4.buffer); - break; - case AF_INET6: - ret = inet_pton(AF_INET6, prefix.c_str(), ip_prefix_.address.v6.buffer); - break; - default: - throw errors::InvalidIpAddressException(); - } - - if (ret != 1) { - throw errors::InvalidIpAddressException(); - } - - ip_prefix_.len = prefix_length; - ip_prefix_.family = family; -} - -std::unique_ptr<Sockaddr> Prefix::toSockaddr() { - Sockaddr *ret = nullptr; - - switch (ip_prefix_.family) { - case AF_INET6: - ret = (Sockaddr *)new Sockaddr6; - break; - case AF_INET: - ret = (Sockaddr *)new Sockaddr4; - break; - default: - throw errors::InvalidIpAddressException(); - } - - if (ip_prefix_to_sockaddr(&ip_prefix_, ret) < 0) { - throw errors::InvalidIpAddressException(); - } - - return std::unique_ptr<Sockaddr>(ret); -} - -uint16_t Prefix::getPrefixLength() { return ip_prefix_.len; } - -Prefix &Prefix::setPrefixLength(uint16_t prefix_length) { - ip_prefix_.len = prefix_length; - return *this; -} - -int Prefix::getAddressFamily() { return ip_prefix_.family; } - -Prefix &Prefix::setAddressFamily(int address_family) { - ip_prefix_.family = address_family; - return *this; -} - -std::string Prefix::getNetwork() const { - if (!checkPrefixLengthAndAddressFamily(ip_prefix_.len, ip_prefix_.family)) { - throw errors::InvalidIpAddressException(); - } - - std::size_t size = - ip_prefix_.family == 4 + AF_INET ? INET_ADDRSTRLEN : INET6_ADDRSTRLEN; - - std::string network(size, 0); - - if (ip_prefix_ntop_short(&ip_prefix_, (char *)network.c_str(), size) < 0) { - throw errors::RuntimeException( - "Impossible to retrieve network from ip address."); - } - - return network; -} - -int Prefix::contains(const ip_address_t &content_name) const { - int res = - ip_address_cmp(&content_name, &(ip_prefix_.address), ip_prefix_.family); - - if (ip_prefix_.len != (ip_prefix_.family == AF_INET6 ? IPV6_ADDR_LEN_BITS - : IPV4_ADDR_LEN_BITS)) { - const u8 *ip_prefix_buffer = - ip_address_get_buffer(&(ip_prefix_.address), ip_prefix_.family); - const u8 *content_name_buffer = - ip_address_get_buffer(&content_name, ip_prefix_.family); - uint8_t mask = 0xFF >> (ip_prefix_.len % 8); - mask = ~mask; - - res += (ip_prefix_buffer[ip_prefix_.len] & mask) == - (content_name_buffer[ip_prefix_.len] & mask); - } - - return res; -} - -int Prefix::contains(const core::Name &content_name) const { - return contains(content_name.toIpAddress().address); -} - -Name Prefix::getName() const { - std::string s(getNetwork()); - return Name(s); -} - -/* - * Mask is used to apply the components to a content name that belong to this - * prefix - */ -Name Prefix::getName(const core::Name &mask, const core::Name &components, - const core::Name &content_name) const { - if (ip_prefix_.family != mask.getAddressFamily() || - ip_prefix_.family != components.getAddressFamily() || - ip_prefix_.family != content_name.getAddressFamily()) - throw errors::RuntimeException( - "Prefix, mask, components and content name are not of the same address " - "family"); - - ip_address_t mask_ip = mask.toIpAddress().address; - ip_address_t component_ip = components.toIpAddress().address; - ip_address_t name_ip = content_name.toIpAddress().address; - const u8 *mask_ip_buffer = ip_address_get_buffer(&mask_ip, ip_prefix_.family); - const u8 *component_ip_buffer = - ip_address_get_buffer(&component_ip, ip_prefix_.family); - u8 *name_ip_buffer = - const_cast<u8 *>(ip_address_get_buffer(&name_ip, ip_prefix_.family)); - - int addr_len = ip_prefix_.family == AF_INET6 ? IPV6_ADDR_LEN : IPV4_ADDR_LEN; - - for (int i = 0; i < addr_len; i++) { - if (mask_ip_buffer[i]) { - name_ip_buffer[i] = component_ip_buffer[i] & mask_ip_buffer[i]; - } - } - - if (this->contains(name_ip)) - throw errors::RuntimeException("Mask overrides the prefix"); - return Name(ip_prefix_.family, (uint8_t *)&name_ip); -} - -Name Prefix::getRandomName() const { - ip_address_t name_ip = ip_prefix_.address; - u8 *name_ip_buffer = - const_cast<u8 *>(ip_address_get_buffer(&name_ip, ip_prefix_.family)); - - int addr_len = - (ip_prefix_.family == AF_INET6 ? IPV6_ADDR_LEN * 8 : IPV4_ADDR_LEN * 8) - - ip_prefix_.len; - - size_t size = (size_t)ceil((float)addr_len / 8.0); - uint8_t buffer[size]; - - RAND_bytes(buffer, size); - - int j = 0; - for (uint8_t i = (uint8_t)ceil((float)ip_prefix_.len / 8.0); - i < (ip_prefix_.family == AF_INET6 ? IPV6_ADDR_LEN : IPV4_ADDR_LEN); - i++) { - name_ip_buffer[i] = buffer[j]; - j++; - } - - return Name(ip_prefix_.family, (uint8_t *)&name_ip); -} - -/* - * Map a name in a different name prefix to this name prefix - */ -Name Prefix::mapName(const core::Name &content_name) const { - if (ip_prefix_.family != content_name.getAddressFamily()) - throw errors::RuntimeException( - "Prefix content name are not of the same address " - "family"); - - ip_address_t name_ip = content_name.toIpAddress().address; - const u8 *ip_prefix_buffer = - ip_address_get_buffer(&(ip_prefix_.address), ip_prefix_.family); - u8 *name_ip_buffer = - const_cast<u8 *>(ip_address_get_buffer(&name_ip, ip_prefix_.family)); - - memcpy(name_ip_buffer, ip_prefix_buffer, ip_prefix_.len / 8); - - if (ip_prefix_.len != (ip_prefix_.family == AF_INET6 ? IPV6_ADDR_LEN_BITS - : IPV4_ADDR_LEN_BITS)) { - uint8_t mask = 0xFF >> (ip_prefix_.len % 8); - name_ip_buffer[ip_prefix_.len / 8 + 1] = - (name_ip_buffer[ip_prefix_.len / 8 + 1] & mask) | - (ip_prefix_buffer[ip_prefix_.len / 8 + 1] & ~mask); - } - - return Name(ip_prefix_.family, (uint8_t *)&name_ip); -} - -Prefix &Prefix::setNetwork(std::string &network) { - if (!inet_pton(AF_INET6, network.c_str(), ip_prefix_.address.v6.buffer)) { - throw errors::RuntimeException("The network name is not valid."); - } - - return *this; -} - -Name Prefix::makeRandomName() const { - srand((unsigned int)time(nullptr)); - - if (ip_prefix_.family == AF_INET6) { - std::default_random_engine eng((std::random_device())()); - std::uniform_int_distribution<uint32_t> idis( - 0, std::numeric_limits<uint32_t>::max()); - uint64_t random_number = idis(eng); - - uint32_t hash_size_bits = IPV6_ADDR_LEN_BITS - ip_prefix_.len; - uint64_t ip_address[2]; - memcpy(ip_address, ip_prefix_.address.v6.buffer, sizeof(uint64_t)); - memcpy(ip_address + 1, ip_prefix_.address.v6.buffer + 8, sizeof(uint64_t)); - std::string network(IPV6_ADDR_LEN * 3, 0); - - // Let's do the magic ;) - int shift_size = hash_size_bits > sizeof(random_number) * 8 - ? sizeof(random_number) * 8 - : hash_size_bits; - - ip_address[1] >>= shift_size; - ip_address[1] <<= shift_size; - - ip_address[1] |= random_number >> (sizeof(uint64_t) * 8 - shift_size); - - if (!inet_ntop(ip_prefix_.family, ip_address, (char *)network.c_str(), - IPV6_ADDR_LEN * 3)) { - throw errors::RuntimeException( - "Impossible to retrieve network from ip address."); - } - - return Name(network); - } - - return Name(); -} - -bool Prefix::checkPrefixLengthAndAddressFamily(uint16_t prefix_length, - int family) { - // First check the family - if (family != AF_INET6 && family != AF_INET) { - return false; - } - - int max_addr_len_bits = - family == AF_INET6 ? IPV6_ADDR_LEN_BITS : IPV4_ADDR_LEN_BITS; - - if (prefix_length > max_addr_len_bits) { - return false; - } - - return true; -} - -ip_prefix_t &Prefix::toIpPrefixStruct() { return ip_prefix_; } - -} // namespace core - -} // namespace transport diff --git a/libtransport/src/hicn/transport/core/prefix.h b/libtransport/src/hicn/transport/core/prefix.h deleted file mode 100644 index 47971ac..0000000 --- a/libtransport/src/hicn/transport/core/prefix.h +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (c) 2017-2019 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/core/name.h> -namespace transport { - -namespace core { - -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 core::Name &content_name, uint16_t prefix_length); - - std::unique_ptr<Sockaddr> toSockaddr(); - - uint16_t getPrefixLength(); - - Prefix &setPrefixLength(uint16_t prefix_length); - - std::string getNetwork() const; - - int contains(const ip_address_t &content_name) const; - - int contains(const core::Name &content_name) const; - - Name getName() const; - - Name getRandomName() 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(); - - Prefix &setAddressFamily(int address_family); - - Name makeRandomName() const; - - ip_prefix_t &toIpPrefixStruct(); - - private: - static bool checkPrefixLengthAndAddressFamily(uint16_t prefix_length, - int family); - - void buildPrefix(std::string &prefix, uint16_t prefix_length, int family); - - ip_prefix_t ip_prefix_; -}; - -} // end namespace core - -} // end namespace transport diff --git a/libtransport/src/hicn/transport/core/raw_socket_connector.cc b/libtransport/src/hicn/transport/core/raw_socket_connector.cc deleted file mode 100644 index 0e17436..0000000 --- a/libtransport/src/hicn/transport/core/raw_socket_connector.cc +++ /dev/null @@ -1,202 +0,0 @@ -/* - * Copyright (c) 2017-2019 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. - */ - -#include <hicn/transport/core/raw_socket_connector.h> -#include <hicn/transport/utils/conversions.h> -#include <hicn/transport/utils/log.h> - -#include <net/if.h> -#include <netdb.h> -#include <stdio.h> -#include <string.h> -#include <sys/ioctl.h> -#include <sys/socket.h> - -#define MY_DEST_MAC0 0x0a -#define MY_DEST_MAC1 0x7b -#define MY_DEST_MAC2 0x7c -#define MY_DEST_MAC3 0x1c -#define MY_DEST_MAC4 0x4a -#define MY_DEST_MAC5 0x14 - -namespace transport { - -namespace core { - -RawSocketConnector::RawSocketConnector( - PacketReceivedCallback &&receive_callback, - OnReconnect &&on_reconnect_callback, asio::io_service &io_service, - std::string app_name) - : Connector(std::move(receive_callback), std::move(on_reconnect_callback)), - io_service_(io_service), - socket_(io_service_, raw_protocol(PF_PACKET, SOCK_RAW)), - // resolver_(io_service_), - timer_(io_service_), - read_msg_(packet_pool_.makePtr(nullptr)), - data_available_(false), - app_name_(app_name) { - memset(&link_layer_address_, 0, sizeof(link_layer_address_)); -} - -RawSocketConnector::~RawSocketConnector() {} - -void RawSocketConnector::connect(const std::string &interface_name, - const std::string &mac_address_str) { - state_ = ConnectorState::CONNECTING; - memset(ðernet_header_, 0, sizeof(ethernet_header_)); - struct ifreq ifr; - struct ifreq if_mac; - uint8_t mac_address[6]; - - utils::convertStringToMacAddress(mac_address_str, mac_address); - - // Get interface mac address - int fd = static_cast<int>(socket_.native_handle()); - - /* Get the index of the interface to send on */ - memset(&ifr, 0, sizeof(struct ifreq)); - strncpy(ifr.ifr_name, interface_name.c_str(), interface_name.size()); - - // if (ioctl(fd, SIOCGIFINDEX, &if_idx) < 0) { - // perror("SIOCGIFINDEX"); - // } - - /* Get the MAC address of the interface to send on */ - memset(&if_mac, 0, sizeof(struct ifreq)); - strncpy(if_mac.ifr_name, interface_name.c_str(), interface_name.size()); - if (ioctl(fd, SIOCGIFHWADDR, &if_mac) < 0) { - perror("SIOCGIFHWADDR"); - throw errors::RuntimeException("Interface does not exist"); - } - - /* Ethernet header */ - for (int i = 0; i < 6; i++) { - ethernet_header_.ether_shost[i] = - ((uint8_t *)&if_mac.ifr_hwaddr.sa_data)[i]; - ethernet_header_.ether_dhost[i] = mac_address[i]; - } - - /* Ethertype field */ - ethernet_header_.ether_type = htons(ETH_P_IPV6); - - strcpy(ifr.ifr_name, interface_name.c_str()); - - if (0 == ioctl(fd, SIOCGIFHWADDR, &ifr)) { - memcpy(link_layer_address_.sll_addr, ifr.ifr_hwaddr.sa_data, 6); - } - - // memset(&ifr, 0, sizeof(ifr)); - // ioctl(fd, SIOCGIFFLAGS, &ifr); - // ifr.ifr_flags |= IFF_PROMISC; - // ioctl(fd, SIOCSIFFLAGS, &ifr); - - link_layer_address_.sll_family = AF_PACKET; - link_layer_address_.sll_protocol = htons(ETH_P_ALL); - link_layer_address_.sll_ifindex = if_nametoindex(interface_name.c_str()); - link_layer_address_.sll_hatype = 1; - link_layer_address_.sll_halen = 6; - - // startConnectionTimer(); - doConnect(); - doRecvPacket(); -} - -void RawSocketConnector::send(const uint8_t *packet, std::size_t len, - const PacketSentCallback &packet_sent) { - if (packet_sent != 0) { - socket_.async_send( - asio::buffer(packet, len), - [packet_sent](std::error_code ec, std::size_t /*length*/) { - packet_sent(); - }); - } else { - if (state_ == ConnectorState::CONNECTED) { - socket_.send(asio::buffer(packet, len)); - } - } -} - -void RawSocketConnector::send(const Packet::MemBufPtr &packet) { - io_service_.post([this, packet]() { - bool write_in_progress = !output_buffer_.empty(); - output_buffer_.push_back(std::move(packet)); - if (TRANSPORT_EXPECT_TRUE(state_ == ConnectorState::CONNECTED)) { - if (!write_in_progress) { - doSendPacket(); - } else { - // Tell the handle connect it has data to write - data_available_ = true; - } - } - }); -} - -void RawSocketConnector::close() { - io_service_.post([this]() { socket_.close(); }); -} - -void RawSocketConnector::doSendPacket() { - auto packet = output_buffer_.front().get(); - auto array = std::vector<asio::const_buffer>(); - - const utils::MemBuf *current = packet; - do { - array.push_back(asio::const_buffer(current->data(), current->length())); - current = current->next(); - } while (current != packet); - - socket_.async_send( - std::move(array), - [this /*, packet*/](std::error_code ec, std::size_t bytes_transferred) { - if (TRANSPORT_EXPECT_TRUE(!ec)) { - output_buffer_.pop_front(); - if (!output_buffer_.empty()) { - doSendPacket(); - } - } else { - TRANSPORT_LOGE("%d %s", ec.value(), ec.message().c_str()); - } - }); -} - -void RawSocketConnector::doRecvPacket() { - read_msg_ = getPacket(); - socket_.async_receive( - asio::buffer(read_msg_->writableData(), packet_size), - [this](std::error_code ec, std::size_t bytes_transferred) mutable { - if (!ec) { - // Ignore packets that are not for us - uint8_t *dst_mac_address = const_cast<uint8_t *>(read_msg_->data()); - if (!std::memcmp(dst_mac_address, ethernet_header_.ether_shost, - ETHER_ADDR_LEN)) { - read_msg_->append(bytes_transferred); - read_msg_->trimStart(sizeof(struct ether_header)); - receive_callback_(std::move(read_msg_)); - } - } else { - TRANSPORT_LOGE("%d %s", ec.value(), ec.message().c_str()); - } - doRecvPacket(); - }); -} - -void RawSocketConnector::doConnect() { - state_ = ConnectorState::CONNECTED; - socket_.bind(raw_endpoint(&link_layer_address_, sizeof(link_layer_address_))); -} - -} // end namespace core - -} // end namespace transport diff --git a/libtransport/src/hicn/transport/core/raw_socket_connector.h b/libtransport/src/hicn/transport/core/raw_socket_connector.h deleted file mode 100644 index fe9ceb2..0000000 --- a/libtransport/src/hicn/transport/core/raw_socket_connector.h +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (c) 2017-2019 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/config.h> -#include <hicn/transport/core/connector.h> -#include <hicn/transport/core/name.h> - -#include <linux/if_packet.h> -#include <net/ethernet.h> -#include <sys/socket.h> -#include <asio.hpp> -#include <asio/steady_timer.hpp> -#include <deque> - -namespace transport { - -namespace core { - -using asio::generic::raw_protocol; -using raw_endpoint = asio::generic::basic_endpoint<raw_protocol>; - -class RawSocketConnector : public Connector { - public: - RawSocketConnector(PacketReceivedCallback &&receive_callback, - OnReconnect &&reconnect_callback, - asio::io_service &io_service, - std::string app_name = "Libtransport"); - - ~RawSocketConnector() override; - - void send(const Packet::MemBufPtr &packet) override; - - void send(const uint8_t *packet, std::size_t len, - const PacketSentCallback &packet_sent = 0) override; - - void close() override; - - void connect(const std::string &interface_name, - const std::string &mac_address_str); - - private: - void doConnect(); - - void doRecvPacket(); - - void doSendPacket(); - - private: - asio::io_service &io_service_; - raw_protocol::socket socket_; - - struct ether_header ethernet_header_; - - struct sockaddr_ll link_layer_address_; - - asio::steady_timer timer_; - - utils::ObjectPool<utils::MemBuf>::Ptr read_msg_; - - bool data_available_; - std::string app_name_; -}; - -} // end namespace core - -} // end namespace transport diff --git a/libtransport/src/hicn/transport/core/raw_socket_interface.cc b/libtransport/src/hicn/transport/core/raw_socket_interface.cc deleted file mode 100644 index bb4e083..0000000 --- a/libtransport/src/hicn/transport/core/raw_socket_interface.cc +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2017-2019 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. - */ - -#include <hicn/transport/core/raw_socket_interface.h> -#include <hicn/transport/utils/linux.h> - -#include <fstream> - -namespace transport { - -namespace core { - -static std::string config_folder_path = "/etc/transport/interface.conf.d"; - -RawSocketInterface::RawSocketInterface(RawSocketConnector &connector) - : ForwarderInterface<RawSocketInterface, RawSocketConnector>(connector) {} - -RawSocketInterface::~RawSocketInterface() {} - -void RawSocketInterface::connect(bool is_consumer) { - std::string complete_filename = - config_folder_path + std::string("/") + output_interface_; - - std::ifstream is(complete_filename); - std::string interface; - - if (is) { - is >> remote_mac_address_; - } - - // Get interface ip address - struct sockaddr_in6 address = {0}; - utils::retrieveInterfaceAddress(output_interface_, &address); - - std::memcpy(&inet6_address_.v6.as_u8, &address.sin6_addr, - sizeof(address.sin6_addr)); - connector_.connect(output_interface_, remote_mac_address_); -} - -void RawSocketInterface::registerRoute(Prefix &prefix) { return; } - -} // namespace core - -} // namespace transport diff --git a/libtransport/src/hicn/transport/core/raw_socket_interface.h b/libtransport/src/hicn/transport/core/raw_socket_interface.h deleted file mode 100644 index ac48e58..0000000 --- a/libtransport/src/hicn/transport/core/raw_socket_interface.h +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) 2017-2019 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/core/forwarder_interface.h> -#include <hicn/transport/core/prefix.h> -#include <hicn/transport/core/raw_socket_connector.h> - -#include <atomic> -#include <deque> - -namespace transport { - -namespace core { - -class RawSocketInterface - : public ForwarderInterface<RawSocketInterface, RawSocketConnector> { - public: - typedef RawSocketConnector ConnectorType; - - RawSocketInterface(RawSocketConnector &connector); - - ~RawSocketInterface(); - - void connect(bool is_consumer); - - void registerRoute(Prefix &prefix); - - std::uint16_t getMtu() { return interface_mtu; } - - TRANSPORT_ALWAYS_INLINE static bool isControlMessageImpl( - const uint8_t *message) { - return false; - } - - TRANSPORT_ALWAYS_INLINE void processControlMessageReplyImpl( - Packet::MemBufPtr &&packet_buffer) {} - - TRANSPORT_ALWAYS_INLINE void closeConnection(){}; - - private: - static constexpr std::uint16_t interface_mtu = 1500; - std::string remote_mac_address_; -}; - -} // namespace core - -} // namespace transport diff --git a/libtransport/src/hicn/transport/core/tcp_socket_connector.cc b/libtransport/src/hicn/transport/core/tcp_socket_connector.cc deleted file mode 100644 index c82373a..0000000 --- a/libtransport/src/hicn/transport/core/tcp_socket_connector.cc +++ /dev/null @@ -1,281 +0,0 @@ -/* - * Copyright (c) 2017-2019 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. - */ - -#ifdef _WIN32 -#include <hicn/transport/portability/win_portability.h> -#endif -#include <hicn/transport/core/tcp_socket_connector.h> -#include <hicn/transport/errors/errors.h> -#include <hicn/transport/utils/log.h> -#include <hicn/transport/utils/object_pool.h> - -#include <thread> -#include <vector> - -namespace transport { - -namespace core { - -namespace { -class NetworkMessage { - public: - static constexpr std::size_t fixed_header_length = 10; - - static std::size_t decodeHeader(const uint8_t *packet) { - // General checks - // CCNX Control packet format - uint8_t first_byte = packet[0]; - uint8_t ip_format = (packet[0] & 0xf0) >> 4; - - if (TRANSPORT_EXPECT_FALSE(first_byte == 102)) { - // Get packet length - return 44; - } else if (TRANSPORT_EXPECT_TRUE(ip_format == 6 || ip_format == 4)) { - Packet::Format format = Packet::getFormatFromBuffer(packet); - return Packet::getHeaderSizeFromBuffer(format, packet) + - Packet::getPayloadSizeFromBuffer(format, packet); - } - - return 0; - } -}; -} // namespace - -TcpSocketConnector::TcpSocketConnector( - PacketReceivedCallback &&receive_callback, - OnReconnect &&on_reconnect_callback, asio::io_service &io_service, - std::string app_name) - : Connector(std::move(receive_callback), std::move(on_reconnect_callback)), - io_service_(io_service), - socket_(io_service_), - resolver_(io_service_), - timer_(io_service_), - read_msg_(packet_pool_.makePtr(nullptr)), - is_reconnection_(false), - data_available_(false), - app_name_(app_name) {} - -TcpSocketConnector::~TcpSocketConnector() {} - -void TcpSocketConnector::connect(std::string ip_address, std::string port) { - endpoint_iterator_ = resolver_.resolve( - {ip_address, port, asio::ip::resolver_query_base::numeric_service}); - - state_ = ConnectorState::CONNECTING; - doConnect(); -} - -void TcpSocketConnector::send(const uint8_t *packet, std::size_t len, - const PacketSentCallback &packet_sent) { - if (packet_sent != 0) { - asio::async_write(socket_, asio::buffer(packet, len), - [packet_sent](std::error_code ec, - std::size_t /*length*/) { packet_sent(); }); - } else { - if (state_ == ConnectorState::CONNECTED) { - asio::write(socket_, asio::buffer(packet, len)); - } - } -} - -void TcpSocketConnector::send(const Packet::MemBufPtr &packet) { - io_service_.post([this, packet]() { - bool write_in_progress = !output_buffer_.empty(); - output_buffer_.push_back(std::move(packet)); - if (TRANSPORT_EXPECT_TRUE(state_ == ConnectorState::CONNECTED)) { - if (!write_in_progress) { - doWrite(); - } - } else { - // Tell the handle connect it has data to write - data_available_ = true; - } - }); -} - -void TcpSocketConnector::close() { - if (state_ != ConnectorState::CLOSED) { - state_ = ConnectorState::CLOSED; - if (socket_.is_open()) { - socket_.shutdown(asio::ip::tcp::socket::shutdown_type::shutdown_both); - socket_.close(); - } - } -} - -void TcpSocketConnector::doWrite() { -#if 1 - auto array = std::vector<asio::const_buffer>(); - std::vector<Packet::MemBufPtr> packet_store(packet_store_size); - uint8_t i = 0; - - utils::MemBuf *packet = nullptr; - const utils::MemBuf *current = nullptr; - // Send vectors of 32 packets - while (!output_buffer_.empty() && i++ < packet_store_size) { - packet_store[i] = output_buffer_.front(); - output_buffer_.pop_front(); - packet = packet_store[i].get(); - current = packet; - do { - array.push_back(asio::const_buffer(current->data(), current->length())); - current = current->next(); - } while (current != packet); - } -#else - auto packet = output_buffer_.front().get(); - auto array = std::vector<asio::const_buffer>(); - - const utils::MemBuf *current = packet; - do { - array.push_back(asio::const_buffer(current->data(), current->length())); - current = current->next(); - } while (current != packet); -#endif - - asio::async_write( - socket_, std::move(array), - [this, packet_store = std::move(packet_store)](std::error_code ec, - std::size_t length) { - if (TRANSPORT_EXPECT_TRUE(!ec)) { - if (!output_buffer_.empty()) { - doWrite(); - } - } else if (ec.value() == - static_cast<int>(std::errc::operation_canceled)) { - // The connection has been closed by the application. - return; - } else { - TRANSPORT_LOGE("%d %s", ec.value(), ec.message().c_str()); - tryReconnect(); - } - }); -} - -void TcpSocketConnector::doReadBody(std::size_t body_length) { - asio::async_read( - socket_, asio::buffer(read_msg_->writableTail(), body_length), - asio::transfer_exactly(body_length), - [this](std::error_code ec, std::size_t length) { - read_msg_->append(length); - if (TRANSPORT_EXPECT_TRUE(!ec)) { - receive_callback_(std::move(read_msg_)); - doReadHeader(); - } else if (ec.value() == - static_cast<int>(std::errc::operation_canceled)) { - // The connection has been closed by the application. - return; - } else { - TRANSPORT_LOGE("%d %s", ec.value(), ec.message().c_str()); - tryReconnect(); - } - }); -} - -void TcpSocketConnector::doReadHeader() { - read_msg_ = getPacket(); - asio::async_read( - socket_, - asio::buffer(read_msg_->writableData(), - NetworkMessage::fixed_header_length), - asio::transfer_exactly(NetworkMessage::fixed_header_length), - [this](std::error_code ec, std::size_t length) { - if (TRANSPORT_EXPECT_TRUE(!ec)) { - read_msg_->append(NetworkMessage::fixed_header_length); - std::size_t body_length = 0; - if ((body_length = NetworkMessage::decodeHeader(read_msg_->data())) > - 0) { - doReadBody(body_length - length); - } else { - TRANSPORT_LOGE("Decoding error. Ignoring packet."); - } - } else if (ec.value() == - static_cast<int>(std::errc::operation_canceled)) { - // The connection has been closed by the application. - return; - } else { - TRANSPORT_LOGE("%d %s", ec.value(), ec.message().c_str()); - tryReconnect(); - } - }); -} - -void TcpSocketConnector::tryReconnect() { - if (state_ == ConnectorState::CONNECTED) { - TRANSPORT_LOGE("Connection lost. Trying to reconnect...\n"); - state_ = ConnectorState::CONNECTING; - is_reconnection_ = true; - io_service_.post([this]() { - if (socket_.is_open()) { - socket_.shutdown(asio::ip::tcp::socket::shutdown_type::shutdown_both); - socket_.close(); - } - startConnectionTimer(); - doConnect(); - }); - } -} - -void TcpSocketConnector::doConnect() { - asio::async_connect( - socket_, endpoint_iterator_, - [this](std::error_code ec, tcp::resolver::iterator) { - if (!ec) { - timer_.cancel(); - state_ = ConnectorState::CONNECTED; - asio::ip::tcp::no_delay noDelayOption(true); - socket_.set_option(noDelayOption); - doReadHeader(); - - if (data_available_) { - data_available_ = false; - doWrite(); - } - - if (is_reconnection_) { - is_reconnection_ = false; - TRANSPORT_LOGI("Connection recovered!\n"); - on_reconnect_callback_(); - } - } else { - doConnect(); - std::this_thread::sleep_for(std::chrono::milliseconds(500)); - } - }); -} - -bool TcpSocketConnector::checkConnected() { - return state_ == ConnectorState::CONNECTED; -} - -void TcpSocketConnector::startConnectionTimer() { - timer_.expires_from_now(std::chrono::seconds(60)); - timer_.async_wait(std::bind(&TcpSocketConnector::handleDeadline, this, - std::placeholders::_1)); -} - -void TcpSocketConnector::handleDeadline(const std::error_code &ec) { - if (!ec) { - io_service_.post([this]() { - socket_.close(); - TRANSPORT_LOGE("Error connecting. Is the forwarder running?\n"); - io_service_.stop(); - }); - } -} - -} // end namespace core - -} // end namespace transport diff --git a/libtransport/src/hicn/transport/core/tcp_socket_connector.h b/libtransport/src/hicn/transport/core/tcp_socket_connector.h deleted file mode 100644 index d755b5e..0000000 --- a/libtransport/src/hicn/transport/core/tcp_socket_connector.h +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (c) 2017-2019 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/config.h> -#include <hicn/transport/core/connector.h> -#include <hicn/transport/core/name.h> -#include <hicn/transport/utils/branch_prediction.h> - -#include <asio.hpp> -#include <asio/steady_timer.hpp> -#include <deque> - -namespace transport { -namespace core { - -using asio::ip::tcp; - -class TcpSocketConnector : public Connector { - static constexpr uint16_t packet_store_size = 32; - - public: - TcpSocketConnector(PacketReceivedCallback &&receive_callback, - OnReconnect &&reconnect_callback, - asio::io_service &io_service, - std::string app_name = "Libtransport"); - - ~TcpSocketConnector() override; - - void send(const Packet::MemBufPtr &packet) override; - - void send(const uint8_t *packet, std::size_t len, - const PacketSentCallback &packet_sent = 0) override; - - void close() override; - - void connect(std::string ip_address = "127.0.0.1", std::string port = "9695"); - - private: - void doConnect(); - - void doReadHeader(); - - void doReadBody(std::size_t body_length); - - void doWrite(); - - bool checkConnected(); - - private: - void handleDeadline(const std::error_code &ec); - - void startConnectionTimer(); - - void tryReconnect(); - - asio::io_service &io_service_; - asio::ip::tcp::socket socket_; - asio::ip::tcp::resolver resolver_; - asio::ip::tcp::resolver::iterator endpoint_iterator_; - asio::steady_timer timer_; - - utils::ObjectPool<utils::MemBuf>::Ptr read_msg_; - - bool is_reconnection_; - bool data_available_; - - std::string app_name_; -}; - -} // end namespace core - -} // end namespace transport diff --git a/libtransport/src/hicn/transport/core/test/CMakeLists.txt b/libtransport/src/hicn/transport/core/test/CMakeLists.txt deleted file mode 100644 index 48c50e9..0000000 --- a/libtransport/src/hicn/transport/core/test/CMakeLists.txt +++ /dev/null @@ -1,10 +0,0 @@ -# Enable gcov output for the tests -add_definitions(--coverage) -set(CMAKE_EXE_LINKER_FLAGS ${CMAKE_EXE_LINKER_FLAGS} " --coverage") - -set(TestsExpectedToPass - test_core_manifest) - -foreach(test ${TestsExpectedToPass}) - AddTest(${test}) -endforeach()
\ No newline at end of file diff --git a/libtransport/src/hicn/transport/core/test/test_core_manifest.cc b/libtransport/src/hicn/transport/core/test/test_core_manifest.cc deleted file mode 100644 index 58563d8..0000000 --- a/libtransport/src/hicn/transport/core/test/test_core_manifest.cc +++ /dev/null @@ -1,296 +0,0 @@ -/* - * Copyright (c) 2017-2019 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. - */ - -#include <gtest/gtest.h> - -#include "../manifest_format_fixed.h" -#include "../manifest_inline.h" - -#include <test.h> -#include <random> -#include <vector> - -namespace transport { - -namespace core { - -namespace { -// The fixture for testing class Foo. -class ManifestTest : public ::testing::Test { - protected: - using ContentObjectManifest = ManifestInline<ContentObject, Fixed>; - - ManifestTest() : name_("b001::123|321"), manifest1_(name_) { - // You can do set-up work for each test here. - } - - virtual ~ManifestTest() { - // You can do clean-up work that doesn't throw exceptions here. - } - - // If the constructor and destructor are not enough for setting up - // and cleaning up each test, you can define the following methods: - - virtual void SetUp() { - // Code here will be called immediately after the constructor (right - // before each test). - } - - virtual void TearDown() { - // Code here will be called immediately after each test (right - // before the destructor). - } - - Name name_; - ContentObjectManifest manifest1_; - - std::vector<uint8_t> manifest_payload = { - 0x11, 0x11, 0x01, 0x00, 0xb0, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xde, 0xad // , 0x00, 0x00, - // 0x00, 0x45, 0xa3, - // 0xd1, 0xf2, 0x2b, - // 0x94, 0x41, 0x22, - // 0xc9, 0x00, 0x00, - // 0x00, 0x44, 0xa3, - // 0xd1, 0xf2, 0x2b, - // 0x94, 0x41, 0x22, - // 0xc8 - }; -}; - -} // namespace - -TEST_F(ManifestTest, ManifestCreate) { - ContentObjectManifest manifest2(name_); - ContentObjectManifest manifest3 = manifest2; - - EXPECT_EQ(manifest1_, manifest2); - EXPECT_EQ(manifest1_, manifest3); -} - -TEST_F(ManifestTest, ManifestCreateFromBase) { - ContentObject content_object(name_); - content_object.setPayload(manifest_payload.data(), manifest_payload.size()); - ContentObjectManifest manifest(std::move(content_object)); - - auto manifest4 = ContentObjectManifest::createManifest( - name_, core::ManifestVersion::VERSION_1, - core::ManifestType::INLINE_MANIFEST, HashAlgorithm::SHA_256, true, - core::Name("b001::dead"), - core::NextSegmentCalculationStrategy::INCREMENTAL, 128); - - manifest4->encode(); - manifest4->dump(); - manifest.dump(); - - EXPECT_EQ(manifest1_, manifest); - // EXPECT_EQ(manifest1_, manifest3); -} - -TEST_F(ManifestTest, SetLastManifest) { - manifest1_.clear(); - - manifest1_.setFinalManifest(true); - manifest1_.encode(); - manifest1_.decode(); - bool fcn = manifest1_.isFinalManifest(); - - ASSERT_TRUE(fcn); -} - -TEST_F(ManifestTest, SetManifestType) { - manifest1_.clear(); - - ManifestType type1 = ManifestType::INLINE_MANIFEST; - ManifestType type2 = ManifestType::FLIC_MANIFEST; - - manifest1_.setManifestType(type1); - manifest1_.encode(); - manifest1_.decode(); - ManifestType type_returned1 = manifest1_.getManifestType(); - - manifest1_.clear(); - - manifest1_.setManifestType(type2); - manifest1_.encode(); - manifest1_.decode(); - ManifestType type_returned2 = manifest1_.getManifestType(); - - ASSERT_EQ(type1, type_returned1); - ASSERT_EQ(type2, type_returned2); -} - -TEST_F(ManifestTest, SetHashAlgorithm) { - manifest1_.clear(); - - HashAlgorithm hash1 = HashAlgorithm::SHA_512; - HashAlgorithm hash2 = HashAlgorithm::CRC32C; - HashAlgorithm hash3 = HashAlgorithm::SHA_256; - - manifest1_.setHashAlgorithm(hash1); - manifest1_.encode(); - manifest1_.decode(); - HashAlgorithm type_returned1 = manifest1_.getHashAlgorithm(); - - manifest1_.clear(); - - manifest1_.setHashAlgorithm(hash2); - manifest1_.encode(); - manifest1_.decode(); - HashAlgorithm type_returned2 = manifest1_.getHashAlgorithm(); - - manifest1_.clear(); - - manifest1_.setHashAlgorithm(hash3); - manifest1_.encode(); - manifest1_.decode(); - HashAlgorithm type_returned3 = manifest1_.getHashAlgorithm(); - - ASSERT_EQ(hash1, type_returned1); - ASSERT_EQ(hash2, type_returned2); - ASSERT_EQ(hash3, type_returned3); -} - -TEST_F(ManifestTest, SetNextSegmentCalculationStrategy) { - manifest1_.clear(); - - NextSegmentCalculationStrategy strategy1 = - NextSegmentCalculationStrategy::INCREMENTAL; - - manifest1_.setNextSegmentCalculationStrategy(strategy1); - manifest1_.encode(); - manifest1_.decode(); - NextSegmentCalculationStrategy type_returned1 = - manifest1_.getNextSegmentCalculationStrategy(); - - ASSERT_EQ(strategy1, type_returned1); -} - -TEST_F(ManifestTest, SetBaseName) { - manifest1_.clear(); - - core::Name base_name("b001::dead"); - manifest1_.setBaseName(base_name); - manifest1_.encode(); - manifest1_.decode(); - core::Name ret_name = manifest1_.getBaseName(); - - ASSERT_EQ(base_name, ret_name); -} - -TEST_F(ManifestTest, SetSuffixList) { - manifest1_.clear(); - - core::Name base_name("b001::dead"); - - using random_bytes_engine = - std::independent_bits_engine<std::default_random_engine, CHAR_BIT, - unsigned char>; - random_bytes_engine rbe; - - std::default_random_engine eng((std::random_device())()); - std::uniform_int_distribution<uint64_t> idis( - 0, std::numeric_limits<uint32_t>::max()); - - auto entries = new std::pair<uint32_t, utils::CryptoHash>[3]; - uint32_t suffixes[3]; - std::vector<unsigned char> data[3]; - - for (int i = 0; i < 3; i++) { - data[i].resize(32); - std::generate(std::begin(data[i]), std::end(data[i]), std::ref(rbe)); - suffixes[i] = idis(eng); - entries[i] = std::make_pair( - suffixes[i], utils::CryptoHash(data[i].data(), data[i].size(), - utils::CryptoHashType::SHA_256)); - manifest1_.addSuffixHash(entries[i].first, entries[i].second); - } - - manifest1_.setBaseName(base_name); - - manifest1_.encode(); - manifest1_.decode(); - - core::Name ret_name = manifest1_.getBaseName(); - - // auto & hash_list = manifest1_.getSuffixHashList(); - - bool cond; - int i = 0; - - // for (auto & item : manifest1_.getSuffixList()) { - // auto hash = manifest1_.getHash(suffixes[i]); - // cond = utils::CryptoHash::compareBinaryDigest(hash, - // entries[i].second.getDigest<uint8_t>().data(), - // entries[i].second.getType()); - // ASSERT_TRUE(cond); - // i++; - // } - - ASSERT_EQ(base_name, ret_name); - - delete[] entries; -} - -TEST_F(ManifestTest, EstimateSize) { - manifest1_.clear(); - - HashAlgorithm hash1 = HashAlgorithm::SHA_256; - NextSegmentCalculationStrategy strategy1 = - NextSegmentCalculationStrategy::INCREMENTAL; - ManifestType type1 = ManifestType::INLINE_MANIFEST; - core::Name base_name1("b001:abcd:fede:baba:cece:d0d0:face:dead"); - - manifest1_.setFinalManifest(true); - manifest1_.setBaseName(base_name1); - manifest1_.setNextSegmentCalculationStrategy(strategy1); - manifest1_.setHashAlgorithm(hash1); - manifest1_.setManifestType(type1); - - std::default_random_engine eng((std::random_device())()); - std::uniform_int_distribution<uint64_t> idis( - 0, std::numeric_limits<uint64_t>::max()); - - using random_bytes_engine = - std::independent_bits_engine<std::default_random_engine, CHAR_BIT, - unsigned char>; - random_bytes_engine rbe; - - while (manifest1_.estimateManifestSize(1) < 1440) { - uint32_t suffix = static_cast<std::uint32_t>(idis(eng)); - std::vector<unsigned char> data(32); - std::generate(std::begin(data), std::end(data), std::ref(rbe)); - auto hash = utils::CryptoHash(data.data(), data.size(), - utils::CryptoHashType::SHA_256); - manifest1_.addSuffixHash(suffix, hash); - } - - manifest1_.encode(); - manifest1_.decode(); - - manifest1_.dump(); - - ASSERT_GT(manifest1_.estimateManifestSize(), 0); - ASSERT_LT(manifest1_.estimateManifestSize(), 1500); -} - -} // namespace core - -} // namespace transport - -int main(int argc, char **argv) { - ::testing::InitGoogleTest(&argc, argv); - return RUN_ALL_TESTS(); -}
\ No newline at end of file diff --git a/libtransport/src/hicn/transport/core/udp_socket_connector.cc b/libtransport/src/hicn/transport/core/udp_socket_connector.cc deleted file mode 100644 index 99f47fe..0000000 --- a/libtransport/src/hicn/transport/core/udp_socket_connector.cc +++ /dev/null @@ -1,222 +0,0 @@ -/* - * Copyright (c) 2017-2019 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. - */ - -#ifdef _WIN32 -#include <hicn/transport/portability/win_portability.h> -#endif -#include <hicn/transport/core/udp_socket_connector.h> -#include <hicn/transport/errors/errors.h> -#include <hicn/transport/utils/log.h> -#include <hicn/transport/utils/object_pool.h> - -#include <thread> -#include <vector> - -namespace transport { - -namespace core { - -UdpSocketConnector::UdpSocketConnector( - PacketReceivedCallback &&receive_callback, - OnReconnect &&on_reconnect_callback, asio::io_service &io_service, - std::string app_name) - : Connector(std::move(receive_callback), std::move(on_reconnect_callback)), - io_service_(io_service), - socket_(io_service_), - resolver_(io_service_), - connection_timer_(io_service_), - read_msg_(packet_pool_.makePtr(nullptr)), - is_reconnection_(false), - data_available_(false), - app_name_(app_name) {} - -UdpSocketConnector::~UdpSocketConnector() {} - -void UdpSocketConnector::connect(std::string ip_address, std::string port) { - endpoint_iterator_ = resolver_.resolve( - {ip_address, port, asio::ip::resolver_query_base::numeric_service}); - - state_ = ConnectorState::CONNECTING; - doConnect(); -} - -void UdpSocketConnector::send(const uint8_t *packet, std::size_t len, - const PacketSentCallback &packet_sent) { - if (packet_sent != 0) { - socket_.async_send( - asio::buffer(packet, len), - [packet_sent](std::error_code ec, std::size_t /*length*/) { - packet_sent(); - }); - } else { - if (state_ == ConnectorState::CONNECTED) { - try { - socket_.send(asio::buffer(packet, len)); - } catch (std::system_error &err) { - TRANSPORT_LOGE( - "Sending of disconnect message to forwarder failed. Reason: %s", - err.what()); - } - } - } -} - -void UdpSocketConnector::send(const Packet::MemBufPtr &packet) { - io_service_.post([this, packet]() { - bool write_in_progress = !output_buffer_.empty(); - output_buffer_.push_back(std::move(packet)); - if (TRANSPORT_EXPECT_TRUE(state_ == ConnectorState::CONNECTED)) { - if (!write_in_progress) { - doWrite(); - } - } else { - // Tell the handle connect it has data to write - data_available_ = true; - } - }); -} - -void UdpSocketConnector::close() { - if (io_service_.stopped()) { - doClose(); - } else { - io_service_.dispatch(std::bind(&UdpSocketConnector::doClose, this)); - } -} - -void UdpSocketConnector::doClose() { - if (state_ != ConnectorState::CLOSED) { - state_ = ConnectorState::CLOSED; - if (socket_.is_open()) { - socket_.shutdown(asio::ip::tcp::socket::shutdown_type::shutdown_both); - socket_.close(); - } - } -} - -void UdpSocketConnector::doWrite() { - auto packet = output_buffer_.front().get(); - auto array = std::vector<asio::const_buffer>(); - - const utils::MemBuf *current = packet; - do { - array.push_back(asio::const_buffer(current->data(), current->length())); - current = current->next(); - } while (current != packet); - - socket_.async_send(std::move(array), [this](std::error_code ec, - std::size_t length) { - if (TRANSPORT_EXPECT_TRUE(!ec)) { - output_buffer_.pop_front(); - if (!output_buffer_.empty()) { - doWrite(); - } - } else if (ec.value() == static_cast<int>(std::errc::operation_canceled)) { - // The connection has been closed by the application. - return; - } else { - TRANSPORT_LOGE("%d %s", ec.value(), ec.message().c_str()); - tryReconnect(); - } - }); -} - -void UdpSocketConnector::doRead() { - read_msg_ = getPacket(); - socket_.async_receive( - asio::buffer(read_msg_->writableData(), Connector::packet_size), - [this](std::error_code ec, std::size_t length) { - if (TRANSPORT_EXPECT_TRUE(!ec)) { - read_msg_->append(length); - receive_callback_(std::move(read_msg_)); - doRead(); - } else if (ec.value() == - static_cast<int>(std::errc::operation_canceled)) { - // The connection has been closed by the application. - return; - } else { - TRANSPORT_LOGE("%d %s", ec.value(), ec.message().c_str()); - tryReconnect(); - } - }); -} - -void UdpSocketConnector::tryReconnect() { - if (state_ == ConnectorState::CONNECTED) { - TRANSPORT_LOGE("Connection lost. Trying to reconnect...\n"); - state_ = ConnectorState::CONNECTING; - is_reconnection_ = true; - io_service_.post([this]() { - if (socket_.is_open()) { - socket_.shutdown(asio::ip::tcp::socket::shutdown_type::shutdown_both); - socket_.close(); - } - - doConnect(); - startConnectionTimer(); - std::this_thread::sleep_for(std::chrono::milliseconds(500)); - }); - } -} - -void UdpSocketConnector::doConnect() { - asio::async_connect( - socket_, endpoint_iterator_, - [this](std::error_code ec, udp::resolver::iterator) { - if (!ec) { - connection_timer_.cancel(); - state_ = ConnectorState::CONNECTED; - doRead(); - - if (data_available_) { - data_available_ = false; - doWrite(); - } - - if (is_reconnection_) { - is_reconnection_ = false; - } - - on_reconnect_callback_(); - } else { - doConnect(); - std::this_thread::sleep_for(std::chrono::milliseconds(500)); - } - }); -} - -bool UdpSocketConnector::checkConnected() { - return state_ == ConnectorState::CONNECTED; -} - -void UdpSocketConnector::startConnectionTimer() { - connection_timer_.expires_from_now(std::chrono::seconds(60)); - connection_timer_.async_wait(std::bind(&UdpSocketConnector::handleDeadline, - this, std::placeholders::_1)); -} - -void UdpSocketConnector::handleDeadline(const std::error_code &ec) { - if (!ec) { - io_service_.post([this]() { - socket_.close(); - TRANSPORT_LOGE("Error connecting. Is the forwarder running?\n"); - io_service_.stop(); - }); - } -} - -} // end namespace core - -} // end namespace transport diff --git a/libtransport/src/hicn/transport/core/udp_socket_connector.h b/libtransport/src/hicn/transport/core/udp_socket_connector.h deleted file mode 100644 index 7c5dbaf..0000000 --- a/libtransport/src/hicn/transport/core/udp_socket_connector.h +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (c) 2017-2019 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/config.h> -#include <hicn/transport/core/connector.h> -#include <hicn/transport/core/name.h> -#include <hicn/transport/utils/branch_prediction.h> - -#include <asio.hpp> -#include <asio/steady_timer.hpp> -#include <deque> - -namespace transport { -namespace core { - -using asio::ip::udp; - -class UdpSocketConnector : public Connector { - public: - UdpSocketConnector(PacketReceivedCallback &&receive_callback, - OnReconnect &&reconnect_callback, - asio::io_service &io_service, - std::string app_name = "Libtransport"); - - ~UdpSocketConnector() override; - - void send(const Packet::MemBufPtr &packet) override; - - void send(const uint8_t *packet, std::size_t len, - const PacketSentCallback &packet_sent = 0) override; - - void close() override; - - void connect(std::string ip_address = "127.0.0.1", std::string port = "9695"); - - private: - void doConnect(); - - void doRead(); - - void doWrite(); - - void doClose(); - - bool checkConnected(); - - private: - void handleDeadline(const std::error_code &ec); - - void startConnectionTimer(); - - void tryReconnect(); - - asio::io_service &io_service_; - asio::ip::udp::socket socket_; - asio::ip::udp::resolver resolver_; - asio::ip::udp::resolver::iterator endpoint_iterator_; - asio::steady_timer connection_timer_; - - utils::ObjectPool<utils::MemBuf>::Ptr read_msg_; - - bool is_reconnection_; - bool data_available_; - - std::string app_name_; -}; - -} // end namespace core - -} // end namespace transport diff --git a/libtransport/src/hicn/transport/core/vpp_forwarder_interface.cc b/libtransport/src/hicn/transport/core/vpp_forwarder_interface.cc deleted file mode 100644 index 9e701bf..0000000 --- a/libtransport/src/hicn/transport/core/vpp_forwarder_interface.cc +++ /dev/null @@ -1,220 +0,0 @@ -/* - * Copyright (c) 2017-2019 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. - */ - -#include <hicn/transport/config.h> - -#ifdef __vpp__ - -#include <hicn/transport/core/hicn_vapi.h> -#include <hicn/transport/core/memif_vapi.h> -#include <hicn/transport/core/prefix.h> -#include <hicn/transport/core/vpp_forwarder_interface.h> - -extern "C" { -#include <memif/libmemif.h> -}; - -typedef enum { MASTER = 0, SLAVE = 1 } memif_role_t; - -#define MEMIF_DEFAULT_RING_SIZE 2048 -#define MEMIF_DEFAULT_RX_QUEUES 1 -#define MEMIF_DEFAULT_TX_QUEUES 1 -#define MEMIF_DEFAULT_BUFFER_SIZE 2048 - -namespace transport { - -namespace core { - -std::mutex VPPForwarderInterface::global_lock_; - -VPPForwarderInterface::VPPForwarderInterface(MemifConnector &connector) - : ForwarderInterface<VPPForwarderInterface, MemifConnector>(connector), - sw_if_index_(~0), - face_id1_(~0), - face_id2_(~0), - is_consumer_(false){ - } - -VPPForwarderInterface::~VPPForwarderInterface() {} - -/** - * @brief Create a memif interface in the local VPP forwarder. - */ -uint32_t VPPForwarderInterface::getMemifConfiguration() { - memif_create_params_t input_params = {0}; - - int ret = memif_vapi_get_next_memif_id( - VPPForwarderInterface::sock_, &memif_id_); - - if (ret < 0) { - throw errors::RuntimeException( - "Error getting next memif id. Could not create memif interface."); - } - - input_params.id = memif_id_; - input_params.role = memif_role_t::MASTER; - input_params.mode = memif_interface_mode_t::MEMIF_INTERFACE_MODE_IP; - input_params.rx_queues = MEMIF_DEFAULT_RX_QUEUES; - input_params.tx_queues = MEMIF_DEFAULT_TX_QUEUES; - input_params.ring_size = MEMIF_DEFAULT_RING_SIZE; - input_params.buffer_size = MEMIF_DEFAULT_BUFFER_SIZE; - - memif_output_params_t output_params = {0}; - - ret = memif_vapi_create_memif(VPPForwarderInterface::sock_, - &input_params, &output_params); - - if (ret < 0) { - throw errors::RuntimeException( - "Error creating memif interface in the local VPP forwarder."); - } - - return output_params.sw_if_index; -} - -void VPPForwarderInterface::consumerConnection() { - hicn_consumer_input_params input = {0}; - hicn_consumer_output_params output = {0}; - ip_address_t ip4_address; - ip_address_t ip6_address; - - output.src4 = &ip4_address; - output.src6 = &ip6_address; - input.swif = sw_if_index_; - - - - int ret = hicn_vapi_register_cons_app(VPPForwarderInterface::sock_, - &input, &output); - - if (ret < 0) { - throw errors::RuntimeException(hicn_vapi_get_error_string(ret)); - } - - face_id1_ = output.face_id1; - face_id2_ = output.face_id2; - - - std::memcpy(inet_address_.v4.as_u8, output.src4->v4.as_u8, IPV4_ADDR_LEN); - - std::memcpy(inet6_address_.v6.as_u8, output.src6->v6.as_u8, IPV6_ADDR_LEN); -} - -void VPPForwarderInterface::producerConnection() { - // Producer connection will be set when we set the first route. -} - -void VPPForwarderInterface::connect(bool is_consumer) { - std::lock_guard<std::mutex> connection_lock(global_lock_); - - vapi_connect_safe(&sock_, 0); - - sw_if_index_ = getMemifConfiguration(); - - is_consumer_ = is_consumer; - if (is_consumer_) { - consumerConnection(); - } - - connector_.connect(memif_id_, 0); -} - -void VPPForwarderInterface::registerRoute(Prefix &prefix) { - ip_prefix_t &addr = prefix.toIpPrefixStruct(); - - ip_prefix_t producer_prefix; - ip_address_t producer_locator; - - if (face_id1_ == uint32_t(~0)) { - hicn_producer_input_params input; - std::memset(&input, 0, sizeof(input)); - - hicn_producer_output_params output; - std::memset(&output, 0, sizeof(output)); - - input.prefix = &producer_prefix; - output.prod_addr = &producer_locator; - - // Here we have to ask to the actual connector what is the - // memif_id, since this function should be called after the - // memif creation. - input.swif = sw_if_index_; - input.prefix->address = addr.address; - input.prefix->family = addr.family; - input.prefix->len = addr.len; - input.cs_reserved = content_store_reserved_; - - int ret = hicn_vapi_register_prod_app( - VPPForwarderInterface::sock_, &input, &output); - - if (ret < 0) { - throw errors::RuntimeException(hicn_vapi_get_error_string(ret)); - } - - inet6_address_ = *output.prod_addr; - - face_id1_ = output.face_id; - } else { - hicn_producer_set_route_params params; - params.prefix = &producer_prefix; - params.prefix->address = addr.address; - params.prefix->family = addr.family; - params.prefix->len = addr.len; - params.face_id = face_id1_; - - int ret = hicn_vapi_register_route(VPPForwarderInterface::sock_, - ¶ms); - - if (ret < 0) { - throw errors::RuntimeException(hicn_vapi_get_error_string(ret)); - } - } -} - -void VPPForwarderInterface::closeConnection() { - if (VPPForwarderInterface::sock_) { - connector_.close(); - - if (is_consumer_) { - hicn_del_face_app_input_params params; - params.face_id = face_id1_; - hicn_vapi_face_cons_del(VPPForwarderInterface::sock_, ¶ms); - params.face_id = face_id2_; - hicn_vapi_face_cons_del(VPPForwarderInterface::sock_, ¶ms); - } - else { - hicn_del_face_app_input_params params; - params.face_id = face_id1_; - hicn_vapi_face_prod_del(VPPForwarderInterface::sock_, ¶ms); - } - - if (sw_if_index_ != uint32_t(~0)) { - int ret = memif_vapi_delete_memif(VPPForwarderInterface::sock_, - sw_if_index_); - if (ret < 0) { - TRANSPORT_LOGE("Error deleting memif with sw idx %u.", sw_if_index_); - } - } - - vapi_disconnect_safe(); - VPPForwarderInterface::sock_ = nullptr; - } -} - -} // namespace core - -} // namespace transport - -#endif diff --git a/libtransport/src/hicn/transport/core/vpp_forwarder_interface.h b/libtransport/src/hicn/transport/core/vpp_forwarder_interface.h deleted file mode 100644 index 9f80008..0000000 --- a/libtransport/src/hicn/transport/core/vpp_forwarder_interface.h +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (c) 2017-2019 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/config.h> - -#ifdef __vpp__ - -#ifdef always_inline -#undef always_inline -#endif -extern "C" { -#include <vapi/vapi_safe.h> -}; - -#include <hicn/transport/core/forwarder_interface.h> -#include <hicn/transport/core/memif_connector.h> -#include <hicn/transport/core/prefix.h> - -#include <deque> - -namespace transport { - -namespace core { - -class VPPForwarderInterface - : public ForwarderInterface<VPPForwarderInterface, MemifConnector> { - static constexpr std::uint16_t interface_mtu = 1500; - - public: - VPPForwarderInterface(MemifConnector &connector); - - typedef MemifConnector ConnectorType; - - ~VPPForwarderInterface(); - - void connect(bool is_consumer); - - void registerRoute(Prefix &prefix); - - TRANSPORT_ALWAYS_INLINE std::uint16_t getMtu() { return interface_mtu; } - - TRANSPORT_ALWAYS_INLINE static bool isControlMessageImpl( - const uint8_t *message) { - return false; - } - - TRANSPORT_ALWAYS_INLINE void processControlMessageReplyImpl( - Packet::MemBufPtr &&packet_buffer) {} - - void closeConnection(); - - private: - uint32_t getMemifConfiguration(); - - void consumerConnection(); - - void producerConnection(); - - uint32_t memif_id_; - uint32_t sw_if_index_; - //A consumer socket in vpp has two faces (ipv4 and ipv6) - uint32_t face_id1_; - uint32_t face_id2_; - bool is_consumer_; - vapi_ctx_t sock_; - static std::mutex global_lock_; -}; - -} // namespace core - -} // namespace transport - -#endif diff --git a/libtransport/src/hicn/transport/errors/CMakeLists.txt b/libtransport/src/hicn/transport/errors/CMakeLists.txt deleted file mode 100644 index 7b0d133..0000000 --- a/libtransport/src/hicn/transport/errors/CMakeLists.txt +++ /dev/null @@ -1,31 +0,0 @@ -# Copyright (c) 2017-2019 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. - -cmake_minimum_required(VERSION 3.5 FATAL_ERROR) - -list(APPEND HEADER_FILES - ${CMAKE_CURRENT_SOURCE_DIR}/not_implemented_exception.h - ${CMAKE_CURRENT_SOURCE_DIR}/invalid_ip_address_exception.h - ${CMAKE_CURRENT_SOURCE_DIR}/malformed_name_exception.h - ${CMAKE_CURRENT_SOURCE_DIR}/errors.h - ${CMAKE_CURRENT_SOURCE_DIR}/malformed_packet_exception.h - ${CMAKE_CURRENT_SOURCE_DIR}/runtime_exception.h - ${CMAKE_CURRENT_SOURCE_DIR}/tokenizer_exception.h - ${CMAKE_CURRENT_SOURCE_DIR}/null_pointer_exception.h - ${CMAKE_CURRENT_SOURCE_DIR}/malformed_ahpacket_exception.h - ${CMAKE_CURRENT_SOURCE_DIR}/unexpected_manifest_exception.h - ${CMAKE_CURRENT_SOURCE_DIR}/indexing_exception.h -) - -set(SOURCE_FILES ${SOURCE_FILES} PARENT_SCOPE) -set(HEADER_FILES ${HEADER_FILES} PARENT_SCOPE)
\ No newline at end of file diff --git a/libtransport/src/hicn/transport/errors/errors.h b/libtransport/src/hicn/transport/errors/errors.h deleted file mode 100644 index 512e357..0000000 --- a/libtransport/src/hicn/transport/errors/errors.h +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (c) 2017-2019 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/invalid_ip_address_exception.h> -#include <hicn/transport/errors/malformed_name_exception.h> -#include <hicn/transport/errors/malformed_packet_exception.h> -#include <hicn/transport/errors/not_implemented_exception.h> -#include <hicn/transport/errors/null_pointer_exception.h> -#include <hicn/transport/errors/runtime_exception.h> -#include <hicn/transport/errors/tokenizer_exception.h>
\ No newline at end of file diff --git a/libtransport/src/hicn/transport/errors/indexing_exception.h b/libtransport/src/hicn/transport/errors/indexing_exception.h deleted file mode 100644 index 731314f..0000000 --- a/libtransport/src/hicn/transport/errors/indexing_exception.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2017-2019 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 <stdexcept> - -namespace errors { - -class IndexingException : public std::logic_error { - public: - IndexingException() : std::logic_error("") {} - - virtual char const *what() const noexcept override { - return "Impossible to retrieve next index to download."; - } -}; - -} // end namespace errors diff --git a/libtransport/src/hicn/transport/errors/invalid_ip_address_exception.h b/libtransport/src/hicn/transport/errors/invalid_ip_address_exception.h deleted file mode 100644 index 60226f5..0000000 --- a/libtransport/src/hicn/transport/errors/invalid_ip_address_exception.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2017-2019 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 <stdexcept> - -namespace errors { - -class InvalidIpAddressException : public std::runtime_error { - public: - InvalidIpAddressException() : std::runtime_error("") {} - - virtual char const *what() const noexcept override { - return "Malformed IP address."; - } -}; - -} // end namespace errors
\ No newline at end of file diff --git a/libtransport/src/hicn/transport/errors/malformed_ahpacket_exception.h b/libtransport/src/hicn/transport/errors/malformed_ahpacket_exception.h deleted file mode 100644 index f0cfe0b..0000000 --- a/libtransport/src/hicn/transport/errors/malformed_ahpacket_exception.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2017-2019 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 <stdexcept> - -namespace errors { - -class MalformedAHPacketException : public std::runtime_error { - public: - MalformedAHPacketException() : std::runtime_error("") {} - - virtual char const *what() const noexcept override { - return "Malformed AH packet."; - } -}; - -} // end namespace errors diff --git a/libtransport/src/hicn/transport/errors/malformed_name_exception.h b/libtransport/src/hicn/transport/errors/malformed_name_exception.h deleted file mode 100644 index 4ef45d2..0000000 --- a/libtransport/src/hicn/transport/errors/malformed_name_exception.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2017-2019 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 <stdexcept> - -namespace errors { - -class MalformedNameException : public std::runtime_error { - public: - MalformedNameException() : std::runtime_error("") {} - - virtual char const *what() const noexcept override { - return "Malformed IP address."; - } -}; - -} // end namespace errors diff --git a/libtransport/src/hicn/transport/errors/malformed_packet_exception.h b/libtransport/src/hicn/transport/errors/malformed_packet_exception.h deleted file mode 100644 index ec5c97e..0000000 --- a/libtransport/src/hicn/transport/errors/malformed_packet_exception.h +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (c) 2017-2019 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 <stdexcept> - -namespace errors { - -class MalformedPacketException : public std::runtime_error { - public: - MalformedPacketException() : std::runtime_error("") {} - - char const *what() const noexcept override { return "Malformed IP packet."; } -}; - -} // end namespace errors diff --git a/libtransport/src/hicn/transport/errors/not_implemented_exception.h b/libtransport/src/hicn/transport/errors/not_implemented_exception.h deleted file mode 100644 index e986916..0000000 --- a/libtransport/src/hicn/transport/errors/not_implemented_exception.h +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2017-2019 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 <stdexcept> - -namespace errors { - -class NotImplementedException : public std::logic_error { - public: - NotImplementedException() : std::logic_error("") {} - virtual char const *what() const noexcept override { - return "Function not yet implemented."; - } -}; - -} // end namespace errors diff --git a/libtransport/src/hicn/transport/errors/null_pointer_exception.h b/libtransport/src/hicn/transport/errors/null_pointer_exception.h deleted file mode 100644 index bd06485..0000000 --- a/libtransport/src/hicn/transport/errors/null_pointer_exception.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2017-2019 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 <stdexcept> - -namespace errors { - -class NullPointerException : public std::runtime_error { - public: - NullPointerException() : std::runtime_error("") {} - - char const *what() const noexcept override { - return "Null pointer exception."; - } -}; - -} // end namespace errors diff --git a/libtransport/src/hicn/transport/errors/runtime_exception.h b/libtransport/src/hicn/transport/errors/runtime_exception.h deleted file mode 100644 index ba5128a..0000000 --- a/libtransport/src/hicn/transport/errors/runtime_exception.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2017-2019 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 <iostream> -#include <sstream> -#include <stdexcept> -#include <string> - -namespace errors { - -class RuntimeException : public std::runtime_error { - public: - RuntimeException() : std::runtime_error("") {} - - RuntimeException(std::string what) : runtime_error(what){}; -}; - -} // end namespace errors
\ No newline at end of file diff --git a/libtransport/src/hicn/transport/errors/tokenizer_exception.h b/libtransport/src/hicn/transport/errors/tokenizer_exception.h deleted file mode 100644 index 76eda83..0000000 --- a/libtransport/src/hicn/transport/errors/tokenizer_exception.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2017-2019 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 <stdexcept> - -namespace errors { - -class TokenizerException : public std::logic_error { - public: - TokenizerException() : std::logic_error("") {} - - virtual char const *what() const noexcept override { - return "No more tokens available."; - } -}; - -} // end namespace errors diff --git a/libtransport/src/hicn/transport/errors/unexpected_manifest_exception.h b/libtransport/src/hicn/transport/errors/unexpected_manifest_exception.h deleted file mode 100644 index 6f71471..0000000 --- a/libtransport/src/hicn/transport/errors/unexpected_manifest_exception.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2017-2019 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 <stdexcept> - -namespace errors { - -class UnexpectedManifestException : public std::logic_error { - public: - UnexpectedManifestException() : std::logic_error("") {} - - virtual char const *what() const noexcept override { - return "Received unexpected manifest."; - } -}; - -} // end namespace errors diff --git a/libtransport/src/hicn/transport/http/CMakeLists.txt b/libtransport/src/hicn/transport/http/CMakeLists.txt deleted file mode 100644 index b24c801..0000000 --- a/libtransport/src/hicn/transport/http/CMakeLists.txt +++ /dev/null @@ -1,35 +0,0 @@ -# Copyright (c) 2017-2019 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. - -cmake_minimum_required(VERSION 3.5 FATAL_ERROR) - -list(APPEND SOURCE_FILES - ${CMAKE_CURRENT_SOURCE_DIR}/client_connection.cc - ${CMAKE_CURRENT_SOURCE_DIR}/request.cc - ${CMAKE_CURRENT_SOURCE_DIR}/server_publisher.cc - ${CMAKE_CURRENT_SOURCE_DIR}/server_acceptor.cc - ${CMAKE_CURRENT_SOURCE_DIR}/response.cc) - -list(APPEND HEADER_FILES - ${CMAKE_CURRENT_SOURCE_DIR}/client_connection.h - ${CMAKE_CURRENT_SOURCE_DIR}/request.h - ${CMAKE_CURRENT_SOURCE_DIR}/server_publisher.h - ${CMAKE_CURRENT_SOURCE_DIR}/server_acceptor.h - ${CMAKE_CURRENT_SOURCE_DIR}/default_values.h - ${CMAKE_CURRENT_SOURCE_DIR}/facade.h - ${CMAKE_CURRENT_SOURCE_DIR}/response.h - ${CMAKE_CURRENT_SOURCE_DIR}/message.h -) - -set(SOURCE_FILES ${SOURCE_FILES} PARENT_SCOPE) -set(HEADER_FILES ${HEADER_FILES} PARENT_SCOPE)
\ No newline at end of file diff --git a/libtransport/src/hicn/transport/http/client_connection.cc b/libtransport/src/hicn/transport/http/client_connection.cc deleted file mode 100644 index bd21bc4..0000000 --- a/libtransport/src/hicn/transport/http/client_connection.cc +++ /dev/null @@ -1,220 +0,0 @@ -/* - * Copyright (c) 2017-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. - */ - -#include <hicn/transport/http/client_connection.h> -#include <hicn/transport/utils/hash.h> - -#define DEFAULT_BETA 0.99 -#define DEFAULT_GAMMA 0.07 - -namespace transport { - -namespace http { - -using namespace transport; - -HTTPClientConnection::HTTPClientConnection() - : consumer_(TransportProtocolAlgorithms::RAAQM), - read_bytes_callback_(nullptr), - read_buffer_(nullptr), - response_(std::make_shared<HTTPResponse>()), - timer_(nullptr) { - consumer_.setSocketOption( - ConsumerCallbacksOptions::CONTENT_OBJECT_TO_VERIFY, - (ConsumerContentObjectVerificationCallback)std::bind( - &HTTPClientConnection::verifyData, this, std::placeholders::_1, - std::placeholders::_2)); - - consumer_.setSocketOption(ConsumerCallbacksOptions::READ_CALLBACK, this); - - consumer_.connect(); - std::shared_ptr<typename ConsumerSocket::Portal> portal; - consumer_.getSocketOption(GeneralTransportOptions::PORTAL, portal); - timer_ = std::make_unique<asio::steady_timer>(portal->getIoService()); -} - -HTTPClientConnection::RC HTTPClientConnection::get( - const std::string &url, HTTPHeaders headers, HTTPPayload &&payload, - std::shared_ptr<HTTPResponse> response, ReadBytesCallback *callback, - std::string ipv6_first_word) { - return sendRequest(url, HTTPMethod::GET, headers, std::move(payload), - response, callback, ipv6_first_word); -} - -HTTPClientConnection::RC HTTPClientConnection::sendRequest( - const std::string &url, HTTPMethod method, HTTPHeaders headers, - HTTPPayload &&payload, std::shared_ptr<HTTPResponse> response, - ReadBytesCallback *callback, std::string ipv6_first_word) { - current_url_ = url; - read_bytes_callback_ = callback; - if (!response) { - response_ = std::make_shared<HTTPResponse>(); - } else { - response_ = response; - } - - auto start = std::chrono::steady_clock::now(); - request_.init(method, url, headers, std::move(payload)); - - success_callback_ = [this, method = std::move(method), url = std::move(url), - start = std::move(start)](std::size_t size) -> void { - auto end = std::chrono::steady_clock::now(); - TRANSPORT_LOGI( - "%s %s [%s] duration: %llu [usec] %zu [bytes]\n", - method_map[method].c_str(), url.c_str(), name_.str().c_str(), - (unsigned long long) - std::chrono::duration_cast<std::chrono::microseconds>(end - start) - .count(), - size); - }; - - sendRequestGetReply(ipv6_first_word); - return return_code_; -} - -void HTTPClientConnection::sendRequestGetReply(std::string &ipv6_first_word) { - const std::string &request_string = request_.getRequestString(); - const std::string &locator = request_.getLocator(); - - // Hash it - - uint32_t locator_hash = - utils::hash::fnv32_buf(locator.c_str(), locator.size()); - uint64_t request_hash = - utils::hash::fnv64_buf(request_string.c_str(), request_string.size()); - - consumer_.setSocketOption( - ConsumerCallbacksOptions::INTEREST_OUTPUT, - (ConsumerInterestCallback)std::bind( - &HTTPClientConnection::processLeavingInterest, this, - std::placeholders::_1, std::placeholders::_2)); - - // Factor hicn name using hash - name_.str(""); - - name_ << ipv6_first_word << ":"; - - for (uint16_t *word = (uint16_t *)&locator_hash; - std::size_t(word) < (std::size_t(&locator_hash) + sizeof(locator_hash)); - word++) { - name_ << ":" << std::hex << *word; - } - - for (uint16_t *word = (uint16_t *)&request_hash; - std::size_t(word) < (std::size_t(&request_hash) + sizeof(request_hash)); - word++) { - name_ << ":" << std::hex << *word; - } - - name_ << "|0"; - - consumer_.consume(Name(name_.str())); - - consumer_.stop(); -} - -std::shared_ptr<HTTPResponse> HTTPClientConnection::response() { - response_->coalescePayloadBuffer(); - return response_; -} - -bool HTTPClientConnection::verifyData( - ConsumerSocket &c, const core::ContentObject &contentObject) { - if (contentObject.getPayloadType() == PayloadType::CONTENT_OBJECT) { - TRANSPORT_LOGI("VERIFY CONTENT\n"); - } else if (contentObject.getPayloadType() == PayloadType::MANIFEST) { - TRANSPORT_LOGI("VERIFY MANIFEST\n"); - } - - return true; -} - -void HTTPClientConnection::processLeavingInterest( - ConsumerSocket &c, const core::Interest &interest) { - if (interest.payloadSize() == 0) { - Interest &int2 = const_cast<Interest &>(interest); - auto payload = request_.getRequestString(); - auto payload2 = request_.getPayload(); - int2.appendPayload((uint8_t *)payload.data(), payload.size()); - if (payload2) - int2.appendPayload((uint8_t *)payload2->data(), payload2->length()); - } -} - -ConsumerSocket &HTTPClientConnection::getConsumer() { return consumer_; } - -HTTPClientConnection &HTTPClientConnection::stop() { - // This is thread safe and can be called from another thread - consumer_.stop(); - - return *this; -} - -HTTPClientConnection &HTTPClientConnection::setTimeout( - const std::chrono::seconds &timeout) { - timer_->cancel(); - timer_->expires_from_now(timeout); - timer_->async_wait([this](std::error_code ec) { - if (!ec) { - consumer_.stop(); - } - }); - - return *this; -} - -HTTPClientConnection &HTTPClientConnection::setCertificate( - const std::string &cert_path) { - if (consumer_.setSocketOption(GeneralTransportOptions::CERTIFICATE, - cert_path) == SOCKET_OPTION_NOT_SET) { - throw errors::RuntimeException("Error setting the certificate."); - } - - return *this; -} - -// Read buffer management -void HTTPClientConnection::readBufferAvailable( - std::unique_ptr<utils::MemBuf> &&buffer) noexcept { - if (!read_bytes_callback_) { - response_->appendResponseChunk(std::move(buffer)); - } else { - read_bytes_callback_->onBytesReceived(std::move(buffer)); - } -} - -// Read buffer management -void HTTPClientConnection::readError(const std::error_code ec) noexcept { - TRANSPORT_LOGE("Error %s during download of %s", ec.message().c_str(), - current_url_.c_str()); - if (read_bytes_callback_) { - read_bytes_callback_->onError(ec); - } - - return_code_ = HTTPClientConnection::RC::DOWNLOAD_FAILED; -} - -void HTTPClientConnection::readSuccess(std::size_t total_size) noexcept { - success_callback_(total_size); - if (read_bytes_callback_) { - read_bytes_callback_->onSuccess(total_size); - } - - return_code_ = HTTPClientConnection::RC::DOWNLOAD_SUCCESS; -} - -} // namespace http - -} // namespace transport diff --git a/libtransport/src/hicn/transport/http/client_connection.h b/libtransport/src/hicn/transport/http/client_connection.h deleted file mode 100644 index e93a371..0000000 --- a/libtransport/src/hicn/transport/http/client_connection.h +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright (c) 2017-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/http/default_values.h> -#include <hicn/transport/http/request.h> -#include <hicn/transport/http/response.h> -#include <hicn/transport/interfaces/socket_consumer.h> -#include <hicn/transport/interfaces/socket_producer.h> -#include <hicn/transport/utils/uri.h> - -#include <vector> - -namespace transport { - -namespace http { - -using namespace interface; -using namespace core; - -class HTTPClientConnection : public ConsumerSocket::ReadCallback { - static constexpr uint32_t max_buffer_capacity = 64 * 1024; - - public: - class ReadBytesCallback { - 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; - }; - - enum class RC : uint32_t { DOWNLOAD_FAILED, DOWNLOAD_SUCCESS }; - - HTTPClientConnection(); - - RC get(const std::string &url, HTTPHeaders headers = {}, - HTTPPayload &&payload = nullptr, - std::shared_ptr<HTTPResponse> response = nullptr, - ReadBytesCallback *callback = nullptr, - std::string ipv6_first_word = "b001"); - - RC sendRequest(const std::string &url, HTTPMethod method, - HTTPHeaders headers = {}, HTTPPayload &&payload = nullptr, - std::shared_ptr<HTTPResponse> response = nullptr, - ReadBytesCallback *callback = nullptr, - std::string ipv6_first_word = "b001"); - - std::shared_ptr<HTTPResponse> response(); - - HTTPClientConnection &stop(); - - interface::ConsumerSocket &getConsumer(); - - HTTPClientConnection &setTimeout(const std::chrono::seconds &timeout); - - HTTPClientConnection &setCertificate(const std::string &cert_path); - - private: - void sendRequestGetReply(std::string &ipv6_first_word); - - bool verifyData(interface::ConsumerSocket &c, - const core::ContentObject &contentObject); - - void processLeavingInterest(interface::ConsumerSocket &c, - const core::Interest &interest); - - // Read callback - bool isBufferMovable() noexcept override { return true; } - void getReadBuffer(uint8_t **application_buffer, - size_t *max_length) override {} - void readDataAvailable(size_t length) noexcept override {} - size_t maxBufferSize() const override { return max_buffer_capacity; } - void readBufferAvailable( - std::unique_ptr<utils::MemBuf> &&buffer) noexcept override; - void readError(const std::error_code ec) noexcept override; - void readSuccess(std::size_t total_size) noexcept override; - - // The consumer socket - ConsumerSocket consumer_; - - // The current url provided by the application - std::string current_url_; - // The current hICN name used for downloading - std::stringstream name_; - // Function to be called when the read is successful - std::function<void(std::size_t)> success_callback_; - // Return code for current download - RC return_code_; - - // Application provided callback for saving the received content during - // the download. If this callback is used, the HTTPClient will NOT save - // any byte internally. - ReadBytesCallback *read_bytes_callback_; - - HTTPRequest request_; - - // Internal read buffer and HTTP response, to be used if the application does - // not provide any read_bytes_callback - std::unique_ptr<utils::MemBuf> read_buffer_; - std::shared_ptr<HTTPResponse> response_; - - // Timer - std::unique_ptr<asio::steady_timer> timer_; -}; - -} // end namespace http - -} // end namespace transport
\ No newline at end of file diff --git a/libtransport/src/hicn/transport/http/default_values.h b/libtransport/src/hicn/transport/http/default_values.h deleted file mode 100644 index 2d5a6b8..0000000 --- a/libtransport/src/hicn/transport/http/default_values.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2017-2019 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 <cstdint> - -namespace transport { - -namespace http { - -namespace default_values { - -const uint16_t ipv6_first_word = 0xb001; // Network byte order - -} // namespace default_values - -} // namespace http - -} // end namespace transport diff --git a/libtransport/src/hicn/transport/http/facade.h b/libtransport/src/hicn/transport/http/facade.h deleted file mode 100644 index 1551ede..0000000 --- a/libtransport/src/hicn/transport/http/facade.h +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (c) 2017-2019 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/http/client_connection.h> -#include <hicn/transport/http/server_acceptor.h> -#include <hicn/transport/http/server_publisher.h> - -namespace libl4 = transport;
\ No newline at end of file diff --git a/libtransport/src/hicn/transport/http/message.h b/libtransport/src/hicn/transport/http/message.h deleted file mode 100644 index b875622..0000000 --- a/libtransport/src/hicn/transport/http/message.h +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) 2017-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 - -#ifdef _WIN32 -#include <hicn/transport/portability/win_portability.h> -#endif - -#include <hicn/transport/utils/membuf.h> - -#include <map> -#include <sstream> -#include <vector> - -#define HTTP_VERSION "1.1" - -namespace transport { - -namespace http { - -typedef enum { GET, POST, PUT, PATCH, DELETE } HTTPMethod; - -static std::map<HTTPMethod, std::string> method_map = { - {GET, "GET"}, {POST, "POST"}, {PUT, "PUT"}, - {PATCH, "PATCH"}, {DELETE, "DELETE"}, -}; - -typedef std::map<std::string, std::string> HTTPHeaders; -typedef std::unique_ptr<utils::MemBuf> HTTPPayload; - -class HTTPMessage { - public: - virtual ~HTTPMessage() = default; - - const HTTPHeaders getHeaders() { return headers_; }; - - void coalescePayloadBuffer() { - auto it = headers_.find("Content-Length"); - if (it != headers_.end()) { - auto content_length = std::stoul(it->second); - payload_->gather(content_length); - } - } - - HTTPPayload &&getPayload() { return std::move(payload_); } - - std::string getHttpVersion() const { return http_version_; }; - - protected: - HTTPHeaders headers_; - HTTPPayload payload_; - std::string http_version_; -}; - -} // end namespace http - -} // end namespace transport
\ No newline at end of file diff --git a/libtransport/src/hicn/transport/http/request.cc b/libtransport/src/hicn/transport/http/request.cc deleted file mode 100644 index 09f7096..0000000 --- a/libtransport/src/hicn/transport/http/request.cc +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2017-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. - */ - -#include <hicn/transport/http/request.h> -#include <hicn/transport/utils/uri.h> - -namespace transport { - -namespace http { - -HTTPRequest::HTTPRequest() {} - -HTTPRequest::HTTPRequest(HTTPMethod method, const std::string &url, - const HTTPHeaders &headers, HTTPPayload &&payload) { - init(method, url, headers, std::move(payload)); -} - -void HTTPRequest::init(HTTPMethod method, const std::string &url, - const HTTPHeaders &headers, HTTPPayload &&payload) { - utils::Uri uri; - uri.parse(url); - - path_ = uri.getPath(); - query_string_ = uri.getQueryString(); - protocol_ = uri.getProtocol(); - locator_ = uri.getLocator(); - port_ = uri.getPort(); - http_version_ = HTTP_VERSION; - - headers_ = headers; - payload_ = std::move(payload); - - std::transform(locator_.begin(), locator_.end(), locator_.begin(), ::tolower); - - std::transform(protocol_.begin(), protocol_.end(), protocol_.begin(), - ::tolower); - - std::stringstream stream; - stream << method_map[method] << " " << uri.getPath() << " HTTP/" - << HTTP_VERSION << "\r\n"; - for (auto &item : headers) { - stream << item.first << ": " << item.second << "\r\n"; - } - stream << "\r\n"; - request_string_ = stream.str(); -} - -std::string HTTPRequest::getPort() const { return port_; } - -std::string HTTPRequest::getLocator() const { return locator_; } - -std::string HTTPRequest::getProtocol() const { return protocol_; } - -std::string HTTPRequest::getPath() const { return path_; } - -std::string HTTPRequest::getQueryString() const { return query_string_; } - -std::string HTTPRequest::getRequestString() const { return request_string_; } - -} // namespace http - -} // namespace transport
\ No newline at end of file diff --git a/libtransport/src/hicn/transport/http/request.h b/libtransport/src/hicn/transport/http/request.h deleted file mode 100644 index 54904d6..0000000 --- a/libtransport/src/hicn/transport/http/request.h +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2017-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/http/message.h> - -#include <map> -#include <sstream> -#include <vector> - -namespace transport { - -namespace http { - -class HTTPRequest : public HTTPMessage { - public: - HTTPRequest(); - HTTPRequest(HTTPMethod method, const std::string &url, - const HTTPHeaders &headers, HTTPPayload &&payload); - - void init(HTTPMethod method, const std::string &url, - const HTTPHeaders &headers, HTTPPayload &&payload); - - std::string getQueryString() const; - - std::string getPath() const; - - std::string getProtocol() const; - - std::string getLocator() const; - - std::string getPort() const; - - std::string getRequestString() const; - - private: - std::string query_string_, path_, protocol_, locator_, port_; - std::string request_string_; -}; - -} // end namespace http - -} // end namespace transport
\ No newline at end of file diff --git a/libtransport/src/hicn/transport/http/response.cc b/libtransport/src/hicn/transport/http/response.cc deleted file mode 100644 index ba0acd1..0000000 --- a/libtransport/src/hicn/transport/http/response.cc +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Copyright (c) 2017-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. - */ - -#include <hicn/transport/errors/errors.h> -#include <hicn/transport/http/response.h> - -#include <experimental/algorithm> -#include <experimental/functional> - -#include <cstring> - -namespace transport { - -namespace http { - -HTTPResponse::HTTPResponse() {} - -HTTPResponse::HTTPResponse(std::unique_ptr<utils::MemBuf> &&response) { - parse(std::move(response)); -} - -void HTTPResponse::appendResponseChunk( - std::unique_ptr<utils::MemBuf> &&response_chunk) { - if (headers_.empty()) { - parse(std::move(response_chunk)); - } else { - payload_->prependChain(std::move(response_chunk)); - } -} - -bool HTTPResponse::parseHeaders(std::unique_ptr<utils::MemBuf> &&buffer) { - auto ret = - HTTPResponse::parseHeaders(buffer->data(), buffer->length(), headers_, - http_version_, status_code_, status_string_); - - if (ret) { - buffer->trimStart(ret); - payload_ = std::move(buffer); - return true; - } - - return false; -} - -std::size_t HTTPResponse::parseHeaders(const uint8_t *buffer, std::size_t size, - HTTPHeaders &headers, - std::string &http_version, - std::string &status_code, - std::string &status_string) { - const char *crlf2 = "\r\n\r\n"; - const char *begin = (const char *)buffer; - const char *end = begin + size; - auto it = - std::experimental::search(begin, end, - std::experimental::make_boyer_moore_searcher( - crlf2, crlf2 + strlen(crlf2))); - - if (it != end) { - std::stringstream ss; - ss.str(std::string(begin, it)); - - std::string line; - getline(ss, line); - std::istringstream line_s(line); - std::string _http_version; - - line_s >> _http_version; - std::size_t separator; - if ((separator = _http_version.find('/')) != std::string::npos) { - if (_http_version.substr(0, separator) != "HTTP") { - return 0; - } - http_version = - line.substr(separator + 1, _http_version.length() - separator - 1); - } else { - return 0; - } - - std::string _status_string; - - line_s >> status_code; - line_s >> _status_string; - - auto _it = std::search(line.begin(), line.end(), status_string.begin(), - status_string.end()); - - status_string = std::string(_it, line.end() - 1); - - std::size_t param_end; - std::size_t value_start; - while (getline(ss, line)) { - if ((param_end = line.find(':')) != std::string::npos) { - value_start = param_end + 1; - if ((value_start) < line.size()) { - if (line[value_start] == ' ') { - value_start++; - } - if (value_start < line.size()) { - headers[line.substr(0, param_end)] = - line.substr(value_start, line.size() - value_start - 1); - } - } - } else { - return 0; - } - } - } - - return it + strlen(crlf2) - begin; -} - -void HTTPResponse::parse(std::unique_ptr<utils::MemBuf> &&response) { - if (!parseHeaders(std::move(response))) { - throw errors::RuntimeException("Malformed HTTP response"); - } -} - -const std::string &HTTPResponse::getStatusCode() const { return status_code_; } - -const std::string &HTTPResponse::getStatusString() const { - return status_string_; -} - -} // namespace http - -} // namespace transport
\ No newline at end of file diff --git a/libtransport/src/hicn/transport/http/response.h b/libtransport/src/hicn/transport/http/response.h deleted file mode 100644 index bab41ac..0000000 --- a/libtransport/src/hicn/transport/http/response.h +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2017-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/http/message.h> -#include <hicn/transport/utils/array.h> - -#include <map> -#include <sstream> -#include <vector> - -namespace transport { - -namespace http { - -class HTTPResponse : public HTTPMessage { - public: - HTTPResponse(); - - HTTPResponse(std::unique_ptr<utils::MemBuf> &&response); - - void appendResponseChunk(std::unique_ptr<utils::MemBuf> &&response_chunk); - - const std::string &getStatusCode() const; - - const std::string &getStatusString() const; - - void parse(std::unique_ptr<utils::MemBuf> &&response); - - bool parseHeaders(std::unique_ptr<utils::MemBuf> &&buffer); - - static std::size_t parseHeaders(const uint8_t *buffer, std::size_t size, - HTTPHeaders &headers, - std::string &http_version, - std::string &status_code, - std::string &status_string); - - private: - std::string status_code_; - std::string status_string_; -}; - -} // end namespace http - -} // end namespace transport
\ No newline at end of file diff --git a/libtransport/src/hicn/transport/http/server_acceptor.cc b/libtransport/src/hicn/transport/http/server_acceptor.cc deleted file mode 100644 index e478dfc..0000000 --- a/libtransport/src/hicn/transport/http/server_acceptor.cc +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (c) 2017-2019 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. - */ - -#include <hicn/transport/http/server_acceptor.h> -#include <hicn/transport/utils/hash.h> -#include <hicn/transport/utils/uri.h> - -namespace transport { - -namespace http { - -HTTPServerAcceptor::HTTPServerAcceptor(std::string &&server_locator, - OnHttpRequest callback) - : HTTPServerAcceptor(server_locator, callback) {} - -HTTPServerAcceptor::HTTPServerAcceptor(std::string &server_locator, - OnHttpRequest callback) - : callback_(callback) { - utils::Uri uri; - - uri.parseProtocolAndLocator(server_locator); - std::string protocol = uri.getProtocol(); - std::string locator = uri.getLocator(); - - std::transform(locator.begin(), locator.end(), locator.begin(), ::tolower); - - std::transform(protocol.begin(), protocol.end(), protocol.begin(), ::tolower); - - if (protocol != "http") { - throw errors::RuntimeException( - "Malformed server_locator. The locator format should be in the form " - "http://locator"); - } - - uint32_t locator_hash = - utils::hash::fnv32_buf(locator.c_str(), locator.size()); - - std::stringstream stream; - stream << std::hex << http::default_values::ipv6_first_word << ":0000"; - - for (uint16_t *word = (uint16_t *)&locator_hash; - std::size_t(word) < (std::size_t(&locator_hash) + sizeof(locator_hash)); - word++) { - stream << ":" << std::hex << *word; - } - - stream << "::0"; - - std::string network = stream.str(); - - core::Prefix acceptor_namespace(network, 64); - - std::string producer_identity = "acceptor_producer"; - acceptor_producer_ = std::make_shared<ProducerSocket>(); - acceptor_producer_->registerPrefix(acceptor_namespace); -} - -void HTTPServerAcceptor::listen(bool async) { - acceptor_producer_->setSocketOption( - ProducerCallbacksOptions::INTEREST_INPUT, - (ProducerInterestCallback)bind( - &HTTPServerAcceptor::processIncomingInterest, this, - std::placeholders::_1, std::placeholders::_2)); - acceptor_producer_->connect(); - - if (!async) { - acceptor_producer_->serveForever(); - } -} - -void HTTPServerAcceptor::processIncomingInterest(ProducerSocket &p, - Interest &interest) { - // Temporary solution. With - auto payload = interest.getPayload(); - - int request_id = utils::hash::fnv32_buf(payload->data(), payload->length()); - - if (publishers_.find(request_id) != publishers_.end()) { - if (publishers_[request_id]) { - publishers_[request_id]->getProducer().onInterest(interest); - return; - } - } - - publishers_[request_id] = - std::make_shared<HTTPServerPublisher>(interest.getName()); - callback_(publishers_[request_id], (uint8_t *)payload->data(), - payload->length(), request_id); -} - -std::map<int, std::shared_ptr<HTTPServerPublisher>> - &HTTPServerAcceptor::getPublishers() { - return publishers_; -} - -} // namespace http - -} // namespace transport diff --git a/libtransport/src/hicn/transport/http/server_acceptor.h b/libtransport/src/hicn/transport/http/server_acceptor.h deleted file mode 100644 index 6ed58f7..0000000 --- a/libtransport/src/hicn/transport/http/server_acceptor.h +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (c) 2017-2019 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/http/default_values.h> -#include <hicn/transport/http/request.h> -#include <hicn/transport/http/server_publisher.h> -#include <hicn/transport/interfaces/socket_consumer.h> -#include <hicn/transport/interfaces/socket_producer.h> - -#include <functional> -#include <vector> - -namespace transport { - -namespace http { - -class HTTPServerAcceptor { - friend class HTTPServerPublisher; - using OnHttpRequest = - std::function<void(std::shared_ptr<HTTPServerPublisher> &, - const uint8_t *, std::size_t, int request_id)>; - - public: - HTTPServerAcceptor(std::string &&server_locator, OnHttpRequest callback); - HTTPServerAcceptor(std::string &server_locator, OnHttpRequest callback); - - void listen(bool async); - - std::map<int, std::shared_ptr<HTTPServerPublisher>> &getPublishers(); - - // void asyncSendResponse(); - - // HTTPClientConnection& get(std::string &url, HTTPHeaders headers = {}, - // HTTPPayload payload = {}); - // - // HTTPResponse&& response(); - - private: - void processIncomingInterest(ProducerSocket &p, Interest &interest); - - OnHttpRequest callback_; - std::shared_ptr<ProducerSocket> acceptor_producer_; - - std::map<int, std::shared_ptr<HTTPServerPublisher>> publishers_; -}; - -} // end namespace http - -} // end namespace transport diff --git a/libtransport/src/hicn/transport/http/server_publisher.cc b/libtransport/src/hicn/transport/http/server_publisher.cc deleted file mode 100644 index b4deb53..0000000 --- a/libtransport/src/hicn/transport/http/server_publisher.cc +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Copyright (c) 2017-2019 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. - */ - -#include <hicn/transport/http/server_publisher.h> -#include <hicn/transport/utils/literals.h> - -namespace transport { - -namespace http { - -HTTPServerPublisher::HTTPServerPublisher(const core::Name &content_name) - : content_name_(content_name) { - std::string identity = "acceptor_producer"; - producer_ = std::make_unique<ProducerSocket>(); - // utils::Identity::generateIdentity(identity)); - core::Prefix publisher_prefix(content_name_, 128); - producer_->registerPrefix(publisher_prefix); -} - -HTTPServerPublisher::~HTTPServerPublisher() { - if (timer_) { - this->timer_->cancel(); - } -} - -HTTPServerPublisher &HTTPServerPublisher::attachPublisher() { - // Create a new publisher - producer_->setSocketOption(GeneralTransportOptions::DATA_PACKET_SIZE, - 1410_U32); - producer_->connect(); - return *this; -} - -HTTPServerPublisher &HTTPServerPublisher::setTimeout( - const std::chrono::milliseconds &timeout, bool timeout_renewal) { - std::shared_ptr<typename ProducerSocket::Portal> portal; - producer_->getSocketOption(GeneralTransportOptions::PORTAL, portal); - timer_ = - std::make_unique<asio::steady_timer>(portal->getIoService(), timeout); - - wait_callback_ = [this](const std::error_code &e) { - if (!e) { - producer_->stop(); - } - }; - - if (timeout_renewal) { - interest_enter_callback_ = [this, timeout](ProducerSocket &p, - const Interest &interest) { - this->timer_->cancel(); - this->timer_->expires_from_now(timeout); - this->timer_->async_wait(wait_callback_); - }; - - producer_->setSocketOption( - ProducerCallbacksOptions::CACHE_HIT, - (ProducerInterestCallback)interest_enter_callback_); - } - - timer_->async_wait(wait_callback_); - - return *this; -} - -void HTTPServerPublisher::publishContent( - const uint8_t *buf, size_t buffer_size, - std::chrono::milliseconds content_lifetime, bool is_last) { - if (producer_) { - producer_->setSocketOption( - GeneralTransportOptions::CONTENT_OBJECT_EXPIRY_TIME, - static_cast<uint32_t>(content_lifetime.count())); - producer_->produce(content_name_, buf, buffer_size, is_last); - // producer_->setSocketOption(ProducerCallbacksOptions::CACHE_MISS, - // [this](ProducerSocket &p, const - // core::Interest &interest){ - // producer_->stop(); - // }); - } -} - -template <typename Handler> -void HTTPServerPublisher::asyncPublishContent( - const uint8_t *buf, size_t buffer_size, - std::chrono::milliseconds content_lifetime, Handler &&handler, - bool is_last) { - if (producer_) { - producer_->setSocketOption( - GeneralTransportOptions::CONTENT_OBJECT_EXPIRY_TIME, - static_cast<uint32_t>(content_lifetime.count())); - producer_->asyncProduce(content_name_, buf, buffer_size, - std::forward<Handler>(handler), is_last); - } -} - -void HTTPServerPublisher::serveClients() { producer_->serveForever(); } - -void HTTPServerPublisher::stop() { - std::shared_ptr<typename ProducerSocket::Portal> portal_ptr; - producer_->getSocketOption(GeneralTransportOptions::PORTAL, portal_ptr); - portal_ptr->getIoService().stop(); -} - -ProducerSocket &HTTPServerPublisher::getProducer() { return *producer_; } - -void HTTPServerPublisher::setPublisherName(std::string &name, - std::string &mask) { - // Name represents the last 64 bits of the ipv6 address. - // It is an ipv6 address with the first 64 bits set to 0 - uint16_t i; - std::string s = content_name_.toString(); - std::shared_ptr<core::Sockaddr> sockaddr = content_name_.getAddress(); - in6_addr name_ipv6 = ((core::Sockaddr6 *)sockaddr.get())->sin6_addr; - - in6_addr bitmask, new_address, _name; - - if (inet_pton(AF_INET6, mask.c_str(), &bitmask) != 1) { - throw errors::RuntimeException("Error during conversion to ipv6 address."); - } - - if (inet_pton(AF_INET6, name.c_str(), &_name) != 1) { - throw errors::RuntimeException("Error during conversion to ipv6 address."); - } - - for (i = 0; i < sizeof(new_address.s6_addr); i++) { - new_address.s6_addr[i] = name_ipv6.s6_addr[i] & bitmask.s6_addr[i]; - } - - for (i = 0; i < sizeof(new_address.s6_addr); i++) { - new_address.s6_addr[i] |= _name.s6_addr[i] & ~bitmask.s6_addr[i]; - } - - // Effectively change the name - char str[INET6_ADDRSTRLEN]; - inet_ntop(AF_INET6, &new_address, str, INET6_ADDRSTRLEN); - std::string str2(str); - - core::Name new_name(str2, 0); - - // If the new name differs from the one required by the consumer part, send a - // manifest - if (!new_name.equals(content_name_, false)) { - // Publish manifest pointing to the new name - - auto manifest = - std::make_shared<ContentObjectManifest>(content_name_.setSuffix(0)); - - content_name_ = core::Name(str2, 0); - - // manifest->setNameList(content_name_); - manifest->setLifetime(4000 * 1000); - manifest->encode(); - producer_->produce(*manifest); - - core::Prefix ns(content_name_, 128); - producer_->registerPrefix(ns); - } -} - -} // namespace http - -} // namespace transport diff --git a/libtransport/src/hicn/transport/http/server_publisher.h b/libtransport/src/hicn/transport/http/server_publisher.h deleted file mode 100644 index 33d596f..0000000 --- a/libtransport/src/hicn/transport/http/server_publisher.h +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (c) 2017-2019 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/http/default_values.h> -#include <hicn/transport/interfaces/socket_consumer.h> -#include <hicn/transport/interfaces/socket_producer.h> - -#include <functional> -#include <vector> - -namespace transport { - -namespace http { - -using namespace interface; -using namespace core; - -class HTTPServerPublisher { - public: - HTTPServerPublisher(const core::Name &content_name); - - ~HTTPServerPublisher(); - - void publishContent(const uint8_t *buf, size_t buffer_size, - std::chrono::milliseconds content_lifetime, bool is_last); - - template <typename Handler> - void asyncPublishContent(const uint8_t *buf, size_t buffer_size, - std::chrono::milliseconds content_lifetime, - Handler &&handler, bool is_last); - - void serveClients(); - - void stop(); - - ProducerSocket &getProducer(); - - HTTPServerPublisher &setTimeout(const std::chrono::milliseconds &timeout, - bool timeout_renewal); - - HTTPServerPublisher &attachPublisher(); - - void setPublisherName(std::string &name, std::string &mask); - - private: - Name content_name_; - std::unique_ptr<asio::steady_timer> timer_; - std::unique_ptr<ProducerSocket> producer_; - ProducerInterestCallback interest_enter_callback_; - utils::UserCallback wait_callback_; -}; - -} // end namespace http - -} // end namespace transport diff --git a/libtransport/src/hicn/transport/interfaces/CMakeLists.txt b/libtransport/src/hicn/transport/interfaces/CMakeLists.txt deleted file mode 100644 index 88b83e9..0000000 --- a/libtransport/src/hicn/transport/interfaces/CMakeLists.txt +++ /dev/null @@ -1,59 +0,0 @@ -# Copyright (c) 2017-2019 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. - -cmake_minimum_required(VERSION 3.5 FATAL_ERROR) - -list(APPEND HEADER_FILES - ${CMAKE_CURRENT_SOURCE_DIR}/socket.h - ${CMAKE_CURRENT_SOURCE_DIR}/socket_consumer.h - ${CMAKE_CURRENT_SOURCE_DIR}/socket_producer.h - ${CMAKE_CURRENT_SOURCE_DIR}/tls_socket_producer.h - ${CMAKE_CURRENT_SOURCE_DIR}/tls_rtc_socket_producer.h - ${CMAKE_CURRENT_SOURCE_DIR}/p2psecure_socket_producer.h - ${CMAKE_CURRENT_SOURCE_DIR}/tls_socket_consumer.h - ${CMAKE_CURRENT_SOURCE_DIR}/p2psecure_socket_consumer.h - ${CMAKE_CURRENT_SOURCE_DIR}/rtc_socket_producer.h - ${CMAKE_CURRENT_SOURCE_DIR}/publication_options.h - ${CMAKE_CURRENT_SOURCE_DIR}/socket_options_default_values.h - ${CMAKE_CURRENT_SOURCE_DIR}/socket_options_keys.h - ${CMAKE_CURRENT_SOURCE_DIR}/callbacks.h - ${CMAKE_CURRENT_SOURCE_DIR}/verification_policy.h -) - -list(APPEND SOURCE_FILES - ${CMAKE_CURRENT_SOURCE_DIR}/socket_producer.cc - ${CMAKE_CURRENT_SOURCE_DIR}/rtc_socket_producer.cc - ${CMAKE_CURRENT_SOURCE_DIR}/socket_consumer.cc - ${CMAKE_CURRENT_SOURCE_DIR}/callbacks.cc -) - -if (${OPENSSL_VERSION} VERSION_EQUAL "1.1.1a" OR ${OPENSSL_VERSION} VERSION_GREATER "1.1.1a") - list(APPEND SOURCE_FILES - ${CMAKE_CURRENT_SOURCE_DIR}/tls_socket_producer.cc - ${CMAKE_CURRENT_SOURCE_DIR}/tls_rtc_socket_producer.cc - ${CMAKE_CURRENT_SOURCE_DIR}/p2psecure_socket_producer.cc - ${CMAKE_CURRENT_SOURCE_DIR}/tls_socket_consumer.cc - ${CMAKE_CURRENT_SOURCE_DIR}/p2psecure_socket_consumer.cc - ) - - list(APPEND HEADER_FILES - ${CMAKE_CURRENT_SOURCE_DIR}/tls_socket_producer.h - ${CMAKE_CURRENT_SOURCE_DIR}/tls_rtc_socket_producer.h - ${CMAKE_CURRENT_SOURCE_DIR}/p2psecure_socket_producer.h - ${CMAKE_CURRENT_SOURCE_DIR}/tls_socket_consumer.h - ${CMAKE_CURRENT_SOURCE_DIR}/p2psecure_socket_consumer.h - ) -endif() - -set(SOURCE_FILES ${SOURCE_FILES} PARENT_SCOPE) -set(HEADER_FILES ${HEADER_FILES} PARENT_SCOPE) diff --git a/libtransport/src/hicn/transport/interfaces/callbacks.cc b/libtransport/src/hicn/transport/interfaces/callbacks.cc deleted file mode 100644 index 2574e77..0000000 --- a/libtransport/src/hicn/transport/interfaces/callbacks.cc +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (c) 2017-2019 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. - */ - -#include "callbacks.h" - -namespace transport { - -namespace interface { - -std::nullptr_t VOID_HANDLER = nullptr; - -} // namespace interface - -} // namespace transport
\ No newline at end of file diff --git a/libtransport/src/hicn/transport/interfaces/callbacks.h b/libtransport/src/hicn/transport/interfaces/callbacks.h deleted file mode 100644 index 9d3d579..0000000 --- a/libtransport/src/hicn/transport/interfaces/callbacks.h +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (c) 2017-2019 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/core/facade.h> -#include <hicn/transport/interfaces/verification_policy.h> - -#include <functional> -#include <system_error> - -namespace utils { -class MemBuf; -} - -namespace transport { - -namespace protocol { - -class IcnObserver; -class TransportStatistics; - -} // namespace protocol - -namespace core { - -class ContentObject; -class Interest; -} // namespace core - -namespace interface { - -// Forward declarations -class ConsumerSocket; -class ProducerSocket; - -/** - * The ConsumerInterestCallback will be called in different parts of the - * consumer socket processing pipeline, with a ConsumerSocket and an Interest as - * parameters. - */ -using ConsumerInterestCallback = - std::function<void(ConsumerSocket &, const core::Interest &)>; - -/** - * The ConsumerTimerCallback is called periodically for exposing to applications - * a summary of the statistics of the transport protocol in use. - */ -using ConsumerTimerCallback = std::function<void( - ConsumerSocket &, const protocol::TransportStatistics &stats)>; - -/** - * The ProducerContentCallback will be called by the producer socket right after - * a content has been segmented and published. - */ -using ProducerContentCallback = std::function<void( - ProducerSocket &, const std::error_code &, uint64_t bytes_written)>; - -/** - * The ConsumerContentObjectCallback will be called in different parts of the - * consumer socket processing pipeline, with a ConsumerSocket and an - * ContentObject as parameters. - */ -using ConsumerContentObjectCallback = - std::function<void(ConsumerSocket &, const core::ContentObject &)>; - -/** - * The ConsumerContentObjectVerificationCallback will be called by the transport - * if an application is willing to verify each content object. Note that a - * better alternative is to instrument the transport to perform the verification - * autonomously, without requiring the intervention of the application. - */ -using ConsumerContentObjectVerificationCallback = - std::function<bool(ConsumerSocket &, const core::ContentObject &)>; - -/** - * The ConsumerContentObjectVerificationFailedCallback will be caled by the - * transport if a data packet (either manifest or content object) cannot be - * verified. The application here decides what to do by returning a - * VerificationFailedPolicy object. - */ -using ConsumerContentObjectVerificationFailedCallback = - std::function<VerificationPolicy( - ConsumerSocket &, const core::ContentObject &, std::error_code ec)>; - -/** - * The ConsumerManifestCallback will be called by the consumer socket when a - * manifest is received. - */ -using ConsumerManifestCallback = - std::function<void(ConsumerSocket &, const core::ContentObjectManifest &)>; - -/** - * The ProducerContentObjectCallback will be called in different parts of the - * consumer socket processing pipeline, with a ProducerSocket and an - * ContentObject as parameters. - */ -using ProducerContentObjectCallback = - std::function<void(ProducerSocket &, core::ContentObject &)>; - -/** - * The ProducerContentObjectCallback will be called in different parts of the - * consumer socket processing pipeline, with a ProducerSocket and an - * Interest as parameters. - */ -using ProducerInterestCallback = - std::function<void(ProducerSocket &, core::Interest &)>; - -extern std::nullptr_t VOID_HANDLER; - -} // namespace interface - -} // namespace transport diff --git a/libtransport/src/hicn/transport/interfaces/p2psecure_socket_consumer.cc b/libtransport/src/hicn/transport/interfaces/p2psecure_socket_consumer.cc deleted file mode 100644 index ec966e5..0000000 --- a/libtransport/src/hicn/transport/interfaces/p2psecure_socket_consumer.cc +++ /dev/null @@ -1,382 +0,0 @@ -#include <hicn/transport/interfaces/p2psecure_socket_consumer.h> -#include <openssl/bio.h> -#include <openssl/ssl.h> -#include <openssl/tls1.h> - -#include <random> - -namespace transport { - -namespace interface { - -void P2PSecureConsumerSocket::setInterestPayload( - ConsumerSocket &c, const core::Interest &interest) { - Interest &int2 = const_cast<Interest &>(interest); - random_suffix_ = int2.getName().getSuffix(); - - if (payload_ != NULL) int2.appendPayload(std::move(payload_)); -} - -// implement void readBufferAvailable(), size_t maxBufferSize() const override, -// void readError(), void readSuccess(). getReadBuffer() and readDataAvailable() -// must be implemented even if empty. - -/* Return the number of read bytes in the return param */ -int readOld(BIO *b, char *buf, int size) { - if (size < 0) return size; - - P2PSecureConsumerSocket *socket; - socket = (P2PSecureConsumerSocket *)BIO_get_data(b); - - std::unique_lock<std::mutex> lck(socket->mtx_); - - if (!socket->something_to_read_) { - if (!socket->transport_protocol_->isRunning()) { - socket->network_name_.setSuffix(socket->random_suffix_); - socket->ConsumerSocket::asyncConsume(socket->network_name_); - } - if (!socket->something_to_read_) socket->cv_.wait(lck); - } - - size_t size_to_read, read; - size_t chain_size = socket->head_->length(); - if (socket->head_->isChained()) - chain_size = socket->head_->computeChainDataLength(); - - if (chain_size > (size_t)size) { - read = size_to_read = (size_t)size; - } else { - read = size_to_read = chain_size; - socket->something_to_read_ = false; - } - - while (size_to_read) { - if (socket->head_->length() < size_to_read) { - std::memcpy(buf, socket->head_->data(), socket->head_->length()); - size_to_read -= socket->head_->length(); - buf += socket->head_->length(); - socket->head_ = socket->head_->pop(); - } else { - std::memcpy(buf, socket->head_->data(), size_to_read); - socket->head_->trimStart(size_to_read); - size_to_read = 0; - } - } - - return read; -} - -/* Return the number of read bytes in readbytes */ -int read(BIO *b, char *buf, size_t size, size_t *readbytes) { - int ret; - - if (size > INT_MAX) size = INT_MAX; - - ret = transport::interface::readOld(b, buf, (int)size); - - if (ret <= 0) { - *readbytes = 0; - return ret; - } - - *readbytes = (size_t)ret; - - return 1; -} - -/* Return the number of written bytes in the return param */ -int writeOld(BIO *b, const char *buf, int num) { - P2PSecureConsumerSocket *socket; - socket = (P2PSecureConsumerSocket *)BIO_get_data(b); - - socket->payload_ = utils::MemBuf::copyBuffer(buf, num); - socket->ConsumerSocket::setSocketOption( - ConsumerCallbacksOptions::INTEREST_OUTPUT, - (ConsumerInterestCallback)std::bind( - &P2PSecureConsumerSocket::setInterestPayload, socket, - std::placeholders::_1, std::placeholders::_2)); - - return num; -} - -/* Return the number of written bytes in written */ -int write(BIO *b, const char *buf, size_t size, size_t *written) { - int ret; - - if (size > INT_MAX) size = INT_MAX; - - ret = transport::interface::writeOld(b, buf, (int)size); - - if (ret <= 0) { - *written = 0; - return ret; - } - - *written = (size_t)ret; - - return 1; -} - -long ctrl(BIO *b, int cmd, long num, void *ptr) { return 1; } - -int P2PSecureConsumerSocket::addHicnKeyIdCb(SSL *s, unsigned int ext_type, - unsigned int context, - const unsigned char **out, - size_t *outlen, X509 *x, - size_t chainidx, int *al, - void *add_arg) { - if (ext_type == 100) { - *out = (unsigned char *)malloc(4); - *(uint32_t *)*out = 10; - *outlen = 4; - } - return 1; -} - -void P2PSecureConsumerSocket::freeHicnKeyIdCb(SSL *s, unsigned int ext_type, - unsigned int context, - const unsigned char *out, - void *add_arg) { - free(const_cast<unsigned char *>(out)); -} - -int P2PSecureConsumerSocket::parseHicnKeyIdCb(SSL *s, unsigned int ext_type, - unsigned int context, - const unsigned char *in, - size_t inlen, X509 *x, - size_t chainidx, int *al, - void *add_arg) { - P2PSecureConsumerSocket *socket = - reinterpret_cast<P2PSecureConsumerSocket *>(add_arg); - if (ext_type == 100) { - memcpy(&socket->secure_prefix_, in, sizeof(ip_prefix_t)); - } - return 1; -} - -P2PSecureConsumerSocket::P2PSecureConsumerSocket(int handshake_protocol, int transport_protocol) - : ConsumerSocket(handshake_protocol), - name_(), - tls_consumer_(), - buf_pool_(), - decrypted_content_(), - payload_(), - head_(), - something_to_read_(false), - content_downloaded_(false), - random_suffix_(), - secure_prefix_(), - producer_namespace_(), - read_callback_decrypted_(), - mtx_(), - cv_(), - protocol_(transport_protocol) { - /* Create the (d)TLS state */ - const SSL_METHOD *meth = TLS_client_method(); - ctx_ = SSL_CTX_new(meth); - - int result = - SSL_CTX_set_ciphersuites(ctx_, - "TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_" - "SHA256:TLS_AES_128_GCM_SHA256"); - if (result != 1) { - throw errors::RuntimeException( - "Unable to set cipher list on TLS subsystem. Aborting."); - } - - SSL_CTX_set_min_proto_version(ctx_, TLS1_3_VERSION); - SSL_CTX_set_max_proto_version(ctx_, TLS1_3_VERSION); - SSL_CTX_set_verify(ctx_, SSL_VERIFY_NONE, NULL); - SSL_CTX_set_ssl_version(ctx_, meth); - - result = SSL_CTX_add_custom_ext( - ctx_, 100, SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS, - P2PSecureConsumerSocket::addHicnKeyIdCb, - P2PSecureConsumerSocket::freeHicnKeyIdCb, NULL, - P2PSecureConsumerSocket::parseHicnKeyIdCb, this); - - ssl_ = SSL_new(ctx_); - - bio_meth_ = BIO_meth_new(BIO_TYPE_CONNECT, "secure consumer socket"); - BIO_meth_set_read(bio_meth_, transport::interface::readOld); - BIO_meth_set_write(bio_meth_, transport::interface::writeOld); - BIO_meth_set_ctrl(bio_meth_, transport::interface::ctrl); - BIO *bio = BIO_new(bio_meth_); - BIO_set_init(bio, 1); - BIO_set_data(bio, this); - SSL_set_bio(ssl_, bio, bio); - - ConsumerSocket::getSocketOption(MAX_WINDOW_SIZE, old_max_win_); - ConsumerSocket::setSocketOption(MAX_WINDOW_SIZE, (double)1.0); - - ConsumerSocket::getSocketOption(CURRENT_WINDOW_SIZE, old_current_win_); - ConsumerSocket::setSocketOption(CURRENT_WINDOW_SIZE, (double)1.0); - - std::default_random_engine generator; - std::uniform_int_distribution<int> distribution( - 1, std::numeric_limits<uint32_t>::max()); - random_suffix_ = 0; - - this->ConsumerSocket::setSocketOption(ConsumerCallbacksOptions::READ_CALLBACK, - this); -}; - -P2PSecureConsumerSocket::~P2PSecureConsumerSocket() { - BIO_meth_free(bio_meth_); - SSL_shutdown(ssl_); -} - -int P2PSecureConsumerSocket::consume(const Name &name) { - if (transport_protocol_->isRunning()) { - return CONSUMER_BUSY; - } - - if ((SSL_in_before(this->ssl_) || SSL_in_init(this->ssl_))) { - ConsumerSocket::setSocketOption(MAX_WINDOW_SIZE, (double)1.0); - network_name_ = producer_namespace_.getRandomName(); - network_name_.setSuffix(0); - int result = SSL_connect(this->ssl_); - ConsumerSocket::setSocketOption(MAX_WINDOW_SIZE, old_max_win_); - ConsumerSocket::setSocketOption(CURRENT_WINDOW_SIZE, old_current_win_); - if (result != 1) - throw errors::RuntimeException("Unable to perform client handshake"); - } - std::shared_ptr<Name> prefix_name = std::make_shared<Name>( - secure_prefix_.family, - ip_address_get_buffer(&(secure_prefix_.address), secure_prefix_.family)); - std::shared_ptr<Prefix> prefix = - std::make_shared<Prefix>(*prefix_name, secure_prefix_.len); - TLSConsumerSocket tls_consumer(this->protocol_, this->ssl_); - - ConsumerTimerCallback *stats_summary_callback = nullptr; - this->getSocketOption(ConsumerCallbacksOptions::STATS_SUMMARY, - &stats_summary_callback); - - uint32_t lifetime; - this->getSocketOption(GeneralTransportOptions::INTEREST_LIFETIME, lifetime); - tls_consumer.setSocketOption(GeneralTransportOptions::INTEREST_LIFETIME, - lifetime); - tls_consumer.setSocketOption(ConsumerCallbacksOptions::READ_CALLBACK, - read_callback_decrypted_); - tls_consumer.setSocketOption(ConsumerCallbacksOptions::STATS_SUMMARY, - *stats_summary_callback); - tls_consumer.setSocketOption(GeneralTransportOptions::STATS_INTERVAL, - this->timer_interval_milliseconds_); - tls_consumer.setSocketOption(MAX_WINDOW_SIZE, old_max_win_); - tls_consumer.setSocketOption(CURRENT_WINDOW_SIZE, old_current_win_); - tls_consumer.connect(); - - if (payload_ != NULL) - return tls_consumer.consume((prefix->mapName(name)), std::move(payload_)); - else - return tls_consumer.consume((prefix->mapName(name))); -} - -int P2PSecureConsumerSocket::asyncConsume(const Name &name) { - if ((SSL_in_before(this->ssl_) || SSL_in_init(this->ssl_))) { - ConsumerSocket::setSocketOption(CURRENT_WINDOW_SIZE, (double)1.0); - ConsumerSocket::setSocketOption(MAX_WINDOW_SIZE, (double)1.0); - network_name_ = producer_namespace_.getRandomName(); - network_name_.setSuffix(0); - TRANSPORT_LOGD("Start handshake at %s", network_name_.toString().c_str()); - interface::ConsumerSocket::ReadCallback *on_payload = VOID_HANDLER; - this->getSocketOption(ConsumerCallbacksOptions::READ_CALLBACK, &on_payload); - int result = SSL_connect(this->ssl_); - ConsumerSocket::setSocketOption(MAX_WINDOW_SIZE, old_max_win_); - ConsumerSocket::setSocketOption(CURRENT_WINDOW_SIZE, old_current_win_); - if (result != 1) - throw errors::RuntimeException("Unable to perform client handshake"); - TRANSPORT_LOGD("Handshake performed!"); - } - - std::shared_ptr<Name> prefix_name = std::make_shared<Name>( - secure_prefix_.family, - ip_address_get_buffer(&(secure_prefix_.address), secure_prefix_.family)); - std::shared_ptr<Prefix> prefix = - std::make_shared<Prefix>(*prefix_name, secure_prefix_.len); - tls_consumer_ = - std::make_shared<TLSConsumerSocket>(this->protocol_, this->ssl_); - - ConsumerTimerCallback *stats_summary_callback = nullptr; - this->getSocketOption(ConsumerCallbacksOptions::STATS_SUMMARY, - &stats_summary_callback); - - uint32_t lifetime; - this->getSocketOption(GeneralTransportOptions::INTEREST_LIFETIME, lifetime); - tls_consumer_->setSocketOption(GeneralTransportOptions::INTEREST_LIFETIME, - lifetime); - tls_consumer_->setSocketOption(ConsumerCallbacksOptions::READ_CALLBACK, - read_callback_decrypted_); - tls_consumer_->setSocketOption(ConsumerCallbacksOptions::STATS_SUMMARY, - *stats_summary_callback); - tls_consumer_->setSocketOption(GeneralTransportOptions::STATS_INTERVAL, - this->timer_interval_milliseconds_); - tls_consumer_->setSocketOption(MAX_WINDOW_SIZE, old_max_win_); - tls_consumer_->setSocketOption(CURRENT_WINDOW_SIZE, old_current_win_); - tls_consumer_->connect(); - - if (payload_ != NULL) - return tls_consumer_->asyncConsume((prefix->mapName(name)), - std::move(payload_)); - else - return tls_consumer_->asyncConsume((prefix->mapName(name))); -} - -void P2PSecureConsumerSocket::registerPrefix(const Prefix &producer_namespace) { - producer_namespace_ = producer_namespace; -} - -int P2PSecureConsumerSocket::setSocketOption( - int socket_option_key, ConsumerSocket::ReadCallback *socket_option_value) { - return rescheduleOnIOService( - socket_option_key, socket_option_value, - [this](int socket_option_key, - ConsumerSocket::ReadCallback *socket_option_value) -> int { - switch (socket_option_key) { - case ConsumerCallbacksOptions::READ_CALLBACK: - read_callback_decrypted_ = socket_option_value; - break; - default: - return SOCKET_OPTION_NOT_SET; - } - - return SOCKET_OPTION_SET; - }); -} - -void P2PSecureConsumerSocket::getReadBuffer(uint8_t **application_buffer, - size_t *max_length){}; - -void P2PSecureConsumerSocket::readDataAvailable(size_t length) noexcept {}; - -size_t P2PSecureConsumerSocket::maxBufferSize() const { - return SSL3_RT_MAX_PLAIN_LENGTH; -} - -void P2PSecureConsumerSocket::readBufferAvailable( - std::unique_ptr<utils::MemBuf> &&buffer) noexcept { - std::unique_lock<std::mutex> lck(this->mtx_); - if (head_) { - head_->prependChain(std::move(buffer)); - } else { - head_ = std::move(buffer); - } - - something_to_read_ = true; - cv_.notify_one(); -} - -void P2PSecureConsumerSocket::readError(const std::error_code ec) noexcept {}; - -void P2PSecureConsumerSocket::readSuccess(std::size_t total_size) noexcept { - std::unique_lock<std::mutex> lck(this->mtx_); - content_downloaded_ = true; - something_to_read_ = true; - cv_.notify_one(); -} - -bool P2PSecureConsumerSocket::isBufferMovable() noexcept { return true; } - -} // namespace interface - -} // namespace transport diff --git a/libtransport/src/hicn/transport/interfaces/p2psecure_socket_consumer.h b/libtransport/src/hicn/transport/interfaces/p2psecure_socket_consumer.h deleted file mode 100644 index ff867f0..0000000 --- a/libtransport/src/hicn/transport/interfaces/p2psecure_socket_consumer.h +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright (c) 2017-2019 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/interfaces/socket_consumer.h> -#include <hicn/transport/interfaces/tls_socket_consumer.h> -#include <openssl/bio.h> -#include <openssl/ssl.h> - -namespace transport { - -namespace interface { - -class P2PSecureConsumerSocket : public ConsumerSocket, - public ConsumerSocket::ReadCallback { - /* Return the number of read bytes in readbytes */ - friend int read(BIO *b, char *buf, size_t size, size_t *readbytes); - - /* Return the number of read bytes in the return param */ - friend int readOld(BIO *h, char *buf, int size); - - /* Return the number of written bytes in written */ - friend int write(BIO *b, const char *buf, size_t size, size_t *written); - - /* Return the number of written bytes in the return param */ - friend int writeOld(BIO *h, const char *buf, int num); - - friend long ctrl(BIO *b, int cmd, long num, void *ptr); - - public: - explicit P2PSecureConsumerSocket(int handshake_protocol, int transport_protocol); - - ~P2PSecureConsumerSocket(); - - int consume(const Name &name) override; - - int asyncConsume(const Name &name) override; - - void registerPrefix(const Prefix &producer_namespace); - - int setSocketOption( - int socket_option_key, - ConsumerSocket::ReadCallback *socket_option_value) override; - - using ConsumerSocket::getSocketOption; - using ConsumerSocket::setSocketOption; - - protected: - /* Callback invoked once an interest has been received and its payload - * decrypted */ - ConsumerInterestCallback on_interest_input_decrypted_; - ConsumerInterestCallback on_interest_process_decrypted_; - - private: - Name name_; - std::shared_ptr<TLSConsumerSocket> tls_consumer_; - - /* SSL handle */ - SSL *ssl_; - SSL_CTX *ctx_; - BIO_METHOD *bio_meth_; - - /* Chain of MemBuf to be used as a temporary buffer to pass descypted data - * from the underlying layer to the application */ - utils::ObjectPool<utils::MemBuf> buf_pool_; - std::unique_ptr<utils::MemBuf> decrypted_content_; - - /* Chain of MemBuf holding the payload to be written into interest or data */ - std::unique_ptr<utils::MemBuf> payload_; - - /* Chain of MemBuf holding the data retrieved from the underlying layer */ - std::unique_ptr<utils::MemBuf> head_; - - bool something_to_read_; - - bool content_downloaded_; - - double old_max_win_; - - double old_current_win_; - - uint32_t random_suffix_; - - ip_prefix_t secure_prefix_; - - Prefix producer_namespace_; - - ConsumerSocket::ReadCallback *read_callback_decrypted_; - - std::mutex mtx_; - - /* Condition variable for the wait */ - std::condition_variable cv_; - - int protocol_; - - void setInterestPayload(ConsumerSocket &c, const core::Interest &interest); - void processPayload(ConsumerSocket &c, std::size_t bytes_transferred, - const std::error_code &ec); - - static int addHicnKeyIdCb(SSL *s, unsigned int ext_type, unsigned int context, - const unsigned char **out, size_t *outlen, X509 *x, - size_t chainidx, int *al, void *add_arg); - - static void freeHicnKeyIdCb(SSL *s, unsigned int ext_type, - unsigned int context, const unsigned char *out, - void *add_arg); - - static int parseHicnKeyIdCb(SSL *s, unsigned int ext_type, - unsigned int context, const unsigned char *in, - size_t inlen, X509 *x, size_t chainidx, int *al, - void *add_arg); - - virtual void getReadBuffer(uint8_t **application_buffer, - size_t *max_length) override; - - virtual void readDataAvailable(size_t length) noexcept override; - - virtual size_t maxBufferSize() const override; - - virtual void readBufferAvailable( - std::unique_ptr<utils::MemBuf> &&buffer) noexcept override; - - virtual void readError(const std::error_code ec) noexcept override; - - virtual void readSuccess(std::size_t total_size) noexcept override; - virtual bool isBufferMovable() noexcept override; - - int download_content(const Name &name); -}; - -} // namespace interface - -} // end namespace transport diff --git a/libtransport/src/hicn/transport/interfaces/p2psecure_socket_producer.cc b/libtransport/src/hicn/transport/interfaces/p2psecure_socket_producer.cc deleted file mode 100644 index 8850bde..0000000 --- a/libtransport/src/hicn/transport/interfaces/p2psecure_socket_producer.cc +++ /dev/null @@ -1,380 +0,0 @@ -#include <hicn/transport/core/interest.h> -#include <hicn/transport/interfaces/p2psecure_socket_producer.h> -#include <hicn/transport/interfaces/tls_rtc_socket_producer.h> -#include <hicn/transport/interfaces/tls_socket_producer.h> - -#include <openssl/bio.h> -#include <openssl/rand.h> -#include <openssl/ssl.h> - -namespace transport { - -namespace interface { - -/* Workaround to prevent content with expiry time equal to 0 to be lost when - * pushed in the forwarder */ -#define HICN_HANDSHAKE_CONTENT_EXPIRY_TIME 100; - -P2PSecureProducerSocket::P2PSecureProducerSocket() - : ProducerSocket(), - mtx_(), - cv_(), - map_secure_producers(), - map_secure_rtc_producers(), - list_secure_producers() {} - -P2PSecureProducerSocket::P2PSecureProducerSocket( - bool rtc, const std::shared_ptr<utils::Identity> &identity) - : ProducerSocket(), - rtc_(rtc), - mtx_(), - cv_(), - map_secure_producers(), - map_secure_rtc_producers(), - list_secure_producers() { - /* - * Setup SSL context (identity and parameter to use TLS 1.3) - */ - der_cert_ = parcKeyStore_GetDEREncodedCertificate( - (identity->getSigner()->getKeyStore())); - der_prk_ = parcKeyStore_GetDEREncodedPrivateKey( - (identity->getSigner()->getKeyStore())); - - int cert_size = parcBuffer_Limit(der_cert_); - int prk_size = parcBuffer_Limit(der_prk_); - const uint8_t *cert = - reinterpret_cast<uint8_t *>(parcBuffer_Overlay(der_cert_, cert_size)); - const uint8_t *prk = - reinterpret_cast<uint8_t *>(parcBuffer_Overlay(der_prk_, prk_size)); - cert_509_ = d2i_X509(NULL, &cert, cert_size); - pkey_rsa_ = d2i_AutoPrivateKey(NULL, &prk, prk_size); - - /* - * Set the callback so that when an interest is received we catch it and we - * decrypt the payload before passing it to the application. - */ - ProducerSocket::setSocketOption( - ProducerCallbacksOptions::INTEREST_INPUT, - (ProducerInterestCallback)std::bind( - &P2PSecureProducerSocket::onInterestCallback, this, - std::placeholders::_1, std::placeholders::_2)); -} - -P2PSecureProducerSocket::~P2PSecureProducerSocket() { - if (der_cert_) parcBuffer_Release(&der_cert_); - if (der_prk_) parcBuffer_Release(&der_prk_); -} - -void P2PSecureProducerSocket::onInterestCallback(ProducerSocket &p, - Interest &interest) { - std::unique_lock<std::mutex> lck(mtx_); - - TRANSPORT_LOGD("Start handshake at %s", interest.getName().toString().c_str()); - if (!rtc_) { - auto it = map_secure_producers.find(interest.getName()); - if (it != map_secure_producers.end()) return; - TLSProducerSocket *tls_producer = - new TLSProducerSocket(this, interest.getName()); - tls_producer->on_content_produced_application_ = - this->on_content_produced_application_; - tls_producer->setSocketOption(CONTENT_OBJECT_EXPIRY_TIME, - this->content_object_expiry_time_); - tls_producer->setSocketOption(SIGNER, this->signer_); - tls_producer->setSocketOption(MAKE_MANIFEST, this->making_manifest_); - tls_producer->setSocketOption(DATA_PACKET_SIZE, - (uint32_t)(this->data_packet_size_)); - tls_producer->output_buffer_.setLimit(this->output_buffer_.getLimit()); - map_secure_producers.insert( - {interest.getName(), std::unique_ptr<TLSProducerSocket>(tls_producer)}); - tls_producer->onInterest(*tls_producer, interest); - tls_producer->async_accept(); - } else { - auto it = map_secure_rtc_producers.find(interest.getName()); - if (it != map_secure_rtc_producers.end()) return; - TLSRTCProducerSocket *tls_producer = - new TLSRTCProducerSocket(this, interest.getName()); - tls_producer->on_content_produced_application_ = - this->on_content_produced_application_; - tls_producer->setSocketOption(CONTENT_OBJECT_EXPIRY_TIME, - this->content_object_expiry_time_); - tls_producer->setSocketOption(SIGNER, this->signer_); - tls_producer->setSocketOption(MAKE_MANIFEST, this->making_manifest_); - tls_producer->setSocketOption(DATA_PACKET_SIZE, - (uint32_t)(this->data_packet_size_)); - tls_producer->output_buffer_.setLimit(this->output_buffer_.getLimit()); - map_secure_rtc_producers.insert( - {interest.getName(), - std::unique_ptr<TLSRTCProducerSocket>(tls_producer)}); - tls_producer->onInterest(*tls_producer, interest); - tls_producer->async_accept(); - } -} - -void P2PSecureProducerSocket::produce(const uint8_t *buffer, - size_t buffer_size) { - if (!rtc_) { - throw errors::RuntimeException( - "RTC must be the transport protocol to start the production of current " - "data. Aborting."); - } - - std::unique_lock<std::mutex> lck(mtx_); - if (list_secure_rtc_producers.empty()) cv_.wait(lck); - - for (auto it = list_secure_rtc_producers.cbegin(); - it != list_secure_rtc_producers.cend(); it++) { - (*it)->produce(utils::MemBuf::copyBuffer(buffer, buffer_size)); - } -} - -uint32_t P2PSecureProducerSocket::produce( - Name content_name, std::unique_ptr<utils::MemBuf> &&buffer, bool is_last, - uint32_t start_offset) { - if (rtc_) { - throw errors::RuntimeException( - "RTC transport protocol is not compatible with the production of " - "current data. Aborting."); - } - - std::unique_lock<std::mutex> lck(mtx_); - uint32_t segments = 0; - if (list_secure_producers.empty()) cv_.wait(lck); - - for (auto it = list_secure_producers.cbegin(); - it != list_secure_producers.cend(); it++) - segments += - (*it)->produce(content_name, buffer->clone(), is_last, start_offset); - return segments; -} - -uint32_t P2PSecureProducerSocket::produce(Name content_name, - const uint8_t *buffer, - size_t buffer_size, bool is_last, - uint32_t start_offset) { - if (rtc_) { - throw errors::RuntimeException( - "RTC transport protocol is not compatible with the production of " - "current data. Aborting."); - } - - std::unique_lock<std::mutex> lck(mtx_); - uint32_t segments = 0; - if (list_secure_producers.empty()) cv_.wait(lck); - - for (auto it = list_secure_producers.cbegin(); - it != list_secure_producers.cend(); it++) - segments += (*it)->produce(content_name, buffer, buffer_size, is_last, - start_offset); - return segments; -} - -void P2PSecureProducerSocket::asyncProduce(const Name &content_name, - const uint8_t *buf, - size_t buffer_size, bool is_last, - uint32_t *start_offset) { - if (rtc_) { - throw errors::RuntimeException( - "RTC transport protocol is not compatible with the production of " - "current data. Aborting."); - } - - std::unique_lock<std::mutex> lck(mtx_); - if (list_secure_producers.empty()) cv_.wait(lck); - - for (auto it = list_secure_producers.cbegin(); - it != list_secure_producers.cend(); it++) { - (*it)->asyncProduce(content_name, buf, buffer_size, is_last, start_offset); - } -} - -void P2PSecureProducerSocket::asyncProduce( - Name content_name, std::unique_ptr<utils::MemBuf> &&buffer, bool is_last, - uint32_t offset, uint32_t **last_segment) { - if (rtc_) { - throw errors::RuntimeException( - "RTC transport protocol is not compatible with the production of " - "current data. Aborting."); - } - - std::unique_lock<std::mutex> lck(mtx_); - if (list_secure_producers.empty()) cv_.wait(lck); - - for (auto it = list_secure_producers.cbegin(); - it != list_secure_producers.cend(); it++) { - (*it)->asyncProduce(content_name, buffer->clone(), is_last, offset, - last_segment); - } -} - -// Socket Option Redefinition to avoid name hiding - -int P2PSecureProducerSocket::setSocketOption( - int socket_option_key, ProducerInterestCallback socket_option_value) { - if (!list_secure_producers.empty()) { - for (auto it = list_secure_producers.cbegin(); - it != list_secure_producers.cend(); it++) - (*it)->setSocketOption(socket_option_key, socket_option_value); - } - - switch (socket_option_key) { - case ProducerCallbacksOptions::INTEREST_INPUT: - on_interest_input_decrypted_ = socket_option_value; - return SOCKET_OPTION_SET; - - case ProducerCallbacksOptions::INTEREST_DROP: - on_interest_dropped_input_buffer_ = socket_option_value; - return SOCKET_OPTION_SET; - - case ProducerCallbacksOptions::INTEREST_PASS: - on_interest_inserted_input_buffer_ = socket_option_value; - return SOCKET_OPTION_SET; - - case ProducerCallbacksOptions::CACHE_HIT: - on_interest_satisfied_output_buffer_ = socket_option_value; - return SOCKET_OPTION_SET; - - case ProducerCallbacksOptions::CACHE_MISS: - on_interest_process_decrypted_ = socket_option_value; - return SOCKET_OPTION_SET; - - default: - return SOCKET_OPTION_NOT_SET; - } -} - -int P2PSecureProducerSocket::setSocketOption( - int socket_option_key, - const std::shared_ptr<utils::Signer> &socket_option_value) { - if (!list_secure_producers.empty()) - for (auto it = list_secure_producers.cbegin(); - it != list_secure_producers.cend(); it++) - (*it)->setSocketOption(socket_option_key, socket_option_value); - - switch (socket_option_key) { - case GeneralTransportOptions::SIGNER: { - signer_.reset(); - signer_ = socket_option_value; - - return SOCKET_OPTION_SET; - } - default: - return SOCKET_OPTION_NOT_SET; - } -} - -int P2PSecureProducerSocket::setSocketOption(int socket_option_key, - uint32_t socket_option_value) { - if (!list_secure_producers.empty()) { - for (auto it = list_secure_producers.cbegin(); - it != list_secure_producers.cend(); it++) - (*it)->setSocketOption(socket_option_key, socket_option_value); - } - switch (socket_option_key) { - case GeneralTransportOptions::CONTENT_OBJECT_EXPIRY_TIME: - content_object_expiry_time_ = - socket_option_value; // HICN_HANDSHAKE_CONTENT_EXPIRY_TIME; - return SOCKET_OPTION_SET; - } - return ProducerSocket::setSocketOption(socket_option_key, - socket_option_value); -} - -int P2PSecureProducerSocket::setSocketOption(int socket_option_key, - bool socket_option_value) { - if (!list_secure_producers.empty()) - for (auto it = list_secure_producers.cbegin(); - it != list_secure_producers.cend(); it++) - (*it)->setSocketOption(socket_option_key, socket_option_value); - - return ProducerSocket::setSocketOption(socket_option_key, - socket_option_value); -} - -int P2PSecureProducerSocket::setSocketOption(int socket_option_key, - Name *socket_option_value) { - if (!list_secure_producers.empty()) - for (auto it = list_secure_producers.cbegin(); - it != list_secure_producers.cend(); it++) - (*it)->setSocketOption(socket_option_key, socket_option_value); - - return ProducerSocket::setSocketOption(socket_option_key, - socket_option_value); -} - -int P2PSecureProducerSocket::setSocketOption( - int socket_option_key, std::list<Prefix> socket_option_value) { - if (!list_secure_producers.empty()) - for (auto it = list_secure_producers.cbegin(); - it != list_secure_producers.cend(); it++) - (*it)->setSocketOption(socket_option_key, socket_option_value); - - return ProducerSocket::setSocketOption(socket_option_key, - socket_option_value); -} - -int P2PSecureProducerSocket::setSocketOption( - int socket_option_key, ProducerContentObjectCallback socket_option_value) { - if (!list_secure_producers.empty()) - for (auto it = list_secure_producers.cbegin(); - it != list_secure_producers.cend(); it++) - (*it)->setSocketOption(socket_option_key, socket_option_value); - - return ProducerSocket::setSocketOption(socket_option_key, - socket_option_value); -} - -int P2PSecureProducerSocket::setSocketOption( - int socket_option_key, ProducerContentCallback socket_option_value) { - if (!list_secure_producers.empty()) - for (auto it = list_secure_producers.cbegin(); - it != list_secure_producers.cend(); it++) - (*it)->setSocketOption(socket_option_key, socket_option_value); - - switch (socket_option_key) { - case ProducerCallbacksOptions::CONTENT_PRODUCED: - on_content_produced_application_ = socket_option_value; - break; - - default: - return SOCKET_OPTION_NOT_SET; - } - - return SOCKET_OPTION_SET; -} - -int P2PSecureProducerSocket::setSocketOption( - int socket_option_key, HashAlgorithm socket_option_value) { - if (!list_secure_producers.empty()) - for (auto it = list_secure_producers.cbegin(); - it != list_secure_producers.cend(); it++) - (*it)->setSocketOption(socket_option_key, socket_option_value); - - return ProducerSocket::setSocketOption(socket_option_key, - socket_option_value); -} - -int P2PSecureProducerSocket::setSocketOption( - int socket_option_key, utils::CryptoSuite socket_option_value) { - if (!list_secure_producers.empty()) - for (auto it = list_secure_producers.cbegin(); - it != list_secure_producers.cend(); it++) - (*it)->setSocketOption(socket_option_key, socket_option_value); - - return ProducerSocket::setSocketOption(socket_option_key, - socket_option_value); -} - -int P2PSecureProducerSocket::setSocketOption( - int socket_option_key, const std::string &socket_option_value) { - if (!list_secure_producers.empty()) - for (auto it = list_secure_producers.cbegin(); - it != list_secure_producers.cend(); it++) - (*it)->setSocketOption(socket_option_key, socket_option_value); - - return ProducerSocket::setSocketOption(socket_option_key, - socket_option_value); -} - -} // namespace interface - -} // namespace transport diff --git a/libtransport/src/hicn/transport/interfaces/p2psecure_socket_producer.h b/libtransport/src/hicn/transport/interfaces/p2psecure_socket_producer.h deleted file mode 100644 index ba3fa01..0000000 --- a/libtransport/src/hicn/transport/interfaces/p2psecure_socket_producer.h +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright (c) 2017-2019 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/interfaces/socket_producer.h> -#include <hicn/transport/interfaces/tls_socket_producer.h> -#include <hicn/transport/interfaces/tls_rtc_socket_producer.h> -#include <hicn/transport/utils/content_store.h> -#include <hicn/transport/utils/identity.h> -#include <hicn/transport/utils/signer.h> - -#include <openssl/ssl.h> -#include <condition_variable> -#include <forward_list> -#include <mutex> - -namespace transport { - -namespace interface { - -class P2PSecureProducerSocket : public ProducerSocket { - friend class TLSProducerSocket; - friend class TLSRTCProducerSocket; - - public: - explicit P2PSecureProducerSocket(); - explicit P2PSecureProducerSocket( - bool rtc, const std::shared_ptr<utils::Identity> &identity); - ~P2PSecureProducerSocket(); - - void produce(const uint8_t *buffer, size_t buffer_size) override; - - uint32_t produce(Name content_name, const uint8_t *buffer, size_t buffer_size, - bool is_last = true, uint32_t start_offset = 0) override; - - uint32_t produce(Name content_name, std::unique_ptr<utils::MemBuf> &&buffer, - bool is_last = true, uint32_t start_offset = 0) override; - - void asyncProduce(const Name &suffix, const uint8_t *buf, size_t buffer_size, - bool is_last = true, - uint32_t *start_offset = nullptr) override; - - void asyncProduce(Name content_name, std::unique_ptr<utils::MemBuf> &&buffer, - bool is_last, uint32_t offset, - uint32_t **last_segment = nullptr) override; - - int setSocketOption(int socket_option_key, - ProducerInterestCallback socket_option_value) override; - - int setSocketOption( - int socket_option_key, - const std::shared_ptr<utils::Signer> &socket_option_value) override; - - int setSocketOption(int socket_option_key, - uint32_t socket_option_value) override; - - int setSocketOption(int socket_option_key, bool socket_option_value) override; - - int setSocketOption(int socket_option_key, - Name *socket_option_value) override; - - int setSocketOption(int socket_option_key, - std::list<Prefix> socket_option_value) override; - - int setSocketOption( - int socket_option_key, - ProducerContentObjectCallback socket_option_value) override; - - int setSocketOption(int socket_option_key, - ProducerContentCallback socket_option_value) override; - - int setSocketOption(int socket_option_key, - HashAlgorithm socket_option_value) override; - - int setSocketOption(int socket_option_key, - utils::CryptoSuite socket_option_value) override; - - int setSocketOption(int socket_option_key, - const std::string &socket_option_value) override; - - using ProducerSocket::getSocketOption; - using ProducerSocket::onInterest; - - protected: - bool rtc_; - /* Callback invoked once an interest has been received and its payload - * decrypted */ - ProducerInterestCallback on_interest_input_decrypted_; - ProducerInterestCallback on_interest_process_decrypted_; - ProducerContentCallback on_content_produced_application_; - - private: - std::mutex mtx_; - - /* Condition variable for the wait */ - std::condition_variable cv_; - - PARCBuffer *der_cert_; - PARCBuffer *der_prk_; - X509 *cert_509_; - EVP_PKEY *pkey_rsa_; - std::unordered_map<core::Name, std::unique_ptr<TLSProducerSocket>, - core::hash<core::Name>, core::compare2<core::Name>> - map_secure_producers; - std::unordered_map<core::Name, std::unique_ptr<TLSRTCProducerSocket>, - core::hash<core::Name>, core::compare2<core::Name>> - map_secure_rtc_producers; - std::list<std::unique_ptr<TLSProducerSocket>> list_secure_producers; - std::list<std::unique_ptr<TLSRTCProducerSocket>> list_secure_rtc_producers; - - void onInterestCallback(ProducerSocket &p, Interest &interest); -}; - -} // namespace interface - -} // namespace transport diff --git a/libtransport/src/hicn/transport/interfaces/publication_options.h b/libtransport/src/hicn/transport/interfaces/publication_options.h deleted file mode 100644 index 6910e53..0000000 --- a/libtransport/src/hicn/transport/interfaces/publication_options.h +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2017-2019 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/core/name.h> - -namespace transport { - -namespace interface { - -class PublicationOptions { - public: - template <typename T> - PublicationOptions(T&& name, uint32_t lifetime) - : name_(std::forward<T&&>(name)), - content_lifetime_milliseconds_(lifetime) {} - - TRANSPORT_ALWAYS_INLINE const core::Name& getName() const { return name_; } - TRANSPORT_ALWAYS_INLINE uint32_t getLifetime() const { - return content_lifetime_milliseconds_; - } - - private: - core::Name name_; - uint32_t content_lifetime_milliseconds_; - // TODO Signature -}; -} // namespace interface - -} // namespace transport
\ No newline at end of file diff --git a/libtransport/src/hicn/transport/interfaces/rtc_socket_producer.cc b/libtransport/src/hicn/transport/interfaces/rtc_socket_producer.cc deleted file mode 100644 index fefa419..0000000 --- a/libtransport/src/hicn/transport/interfaces/rtc_socket_producer.cc +++ /dev/null @@ -1,368 +0,0 @@ -/* - * Copyright (c) 2017-2019 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. - */ - -#include <hicn/transport/interfaces/callbacks.h> -#include <hicn/transport/interfaces/rtc_socket_producer.h> -#include <stdlib.h> -#include <time.h> - -#define NACK_HEADER_SIZE 8 // bytes -#define TIMESTAMP_LEN 8 // bytes -#define TCP_HEADER_SIZE 20 -#define IP6_HEADER_SIZE 40 -#define INIT_PACKET_PRODUCTION_RATE 100 // pps random value (almost 1Mbps) -#define STATS_INTERVAL_DURATION 500 // ms -#define INTEREST_LIFETIME_REDUCTION_FACTOR 0.8 -#define INACTIVE_TIME \ - 500 // ms without producing before the socket - // is considered inactive -#define MILLI_IN_A_SEC 1000 // ms in a second - -#define HICN_MAX_DATA_SEQ 0xefffffff - -// slow production rate param -#define MIN_PRODUCTION_RATE \ - 10 // in pacekts per sec. this value is computed - // through experiments -#define LIFETIME_FRACTION 0.5 - -// NACK HEADER -// +-----------------------------------------+ -// | 4 bytes: current segment in production | -// +-----------------------------------------+ -// | 4 bytes: production rate (bytes x sec) | -// +-----------------------------------------+ -// - -// PACKET HEADER -// +-----------------------------------------+ -// | 8 bytes: TIMESTAMP | -// +-----------------------------------------+ -// | packet | -// +-----------------------------------------+ - -namespace transport { - -namespace interface { - -RTCProducerSocket::RTCProducerSocket(asio::io_service &io_service) - : ProducerSocket(io_service), - currentSeg_(1), - producedBytes_(0), - producedPackets_(0), - bytesProductionRate_(INIT_PACKET_PRODUCTION_RATE * 1400), - packetsProductionRate_(INIT_PACKET_PRODUCTION_RATE), - perSecondFactor_(MILLI_IN_A_SEC / STATS_INTERVAL_DURATION), - timer_on_(false) { - srand((unsigned int)time(NULL)); - prodLabel_ = ((rand() % 255) << 24UL); - interests_cache_timer_ = - std::make_unique<asio::steady_timer>(this->getIoService()); - round_timer_ = std::make_unique<asio::steady_timer>(this->getIoService()); - setSocketOption(GeneralTransportOptions::OUTPUT_BUFFER_SIZE, 10000U); - scheduleRoundTimer(); -} - -RTCProducerSocket::RTCProducerSocket() - : ProducerSocket(), - currentSeg_(1), - producedBytes_(0), - producedPackets_(0), - bytesProductionRate_(INIT_PACKET_PRODUCTION_RATE * 1400), - packetsProductionRate_(INIT_PACKET_PRODUCTION_RATE), - perSecondFactor_(MILLI_IN_A_SEC / STATS_INTERVAL_DURATION), - timer_on_(false) { - srand((unsigned int)time(NULL)); - prodLabel_ = ((rand() % 255) << 24UL); - interests_cache_timer_ = - std::make_unique<asio::steady_timer>(this->getIoService()); - round_timer_ = std::make_unique<asio::steady_timer>(this->getIoService()); - setSocketOption(GeneralTransportOptions::OUTPUT_BUFFER_SIZE, 10000U); - scheduleRoundTimer(); -} - -RTCProducerSocket::~RTCProducerSocket() {} - -void RTCProducerSocket::registerPrefix(const Prefix &producer_namespace) { - ProducerSocket::registerPrefix(producer_namespace); - - flowName_ = producer_namespace.getName(); - auto family = flowName_.getAddressFamily(); - - switch (family) { - case AF_INET6: - headerSize_ = (uint32_t)Packet::getHeaderSizeFromFormat(HF_INET6_TCP); - break; - case AF_INET: - headerSize_ = (uint32_t)Packet::getHeaderSizeFromFormat(HF_INET_TCP); - break; - default: - throw errors::RuntimeException("Unknown name format."); - } -} - -void RTCProducerSocket::scheduleRoundTimer() { - round_timer_->expires_from_now( - std::chrono::milliseconds(STATS_INTERVAL_DURATION)); - round_timer_->async_wait([this](std::error_code ec) { - if (ec) return; - updateStats(); - }); -} - -void RTCProducerSocket::updateStats() { - bytesProductionRate_ = producedBytes_.load() * perSecondFactor_; - packetsProductionRate_ = producedPackets_.load() * perSecondFactor_; - if (packetsProductionRate_.load() == 0) packetsProductionRate_ = 1; - producedBytes_ = 0; - producedPackets_ = 0; - scheduleRoundTimer(); -} - -void RTCProducerSocket::produce(std::unique_ptr<utils::MemBuf> &&buffer) { - auto buffer_size = buffer->length(); - - if (TRANSPORT_EXPECT_FALSE(buffer_size == 0)) { - return; - } - - if (TRANSPORT_EXPECT_FALSE((buffer_size + headerSize_ + TIMESTAMP_LEN) > - data_packet_size_)) { - return; - } - - uint64_t now = std::chrono::duration_cast<std::chrono::milliseconds>( - std::chrono::steady_clock::now().time_since_epoch()) - .count(); - - producedBytes_ += (uint32_t)(buffer_size + headerSize_ + TIMESTAMP_LEN); - producedPackets_++; - - Name n(flowName_); - auto content_object = - std::make_shared<ContentObject>(n.setSuffix(currentSeg_.load())); - auto payload = utils::MemBuf::create(TIMESTAMP_LEN); - - memcpy(payload->writableData(), &now, TIMESTAMP_LEN); - payload->append(TIMESTAMP_LEN); - payload->prependChain(std::move(buffer)); - content_object->appendPayload(std::move(payload)); - - content_object->setLifetime(500); // XXX this should be set by the APP - - content_object->setPathLabel(prodLabel_); - - output_buffer_.insert(std::static_pointer_cast<ContentObject>( - content_object->shared_from_this())); - - if (on_content_object_in_output_buffer_) { - on_content_object_in_output_buffer_(*this, *content_object); - } - - TRANSPORT_LOGD("Send content %u (produce)", content_object->getName().getSuffix()); - portal_->sendContentObject(*content_object); - - if (on_content_object_output_) { - on_content_object_output_(*this, *content_object); - } - - uint32_t old_curr = currentSeg_.load(); - currentSeg_ = (currentSeg_.load() + 1) % HICN_MAX_DATA_SEQ; - - // remove interests from the interest cache if it exists - // this generates nacks that will tell to the consumer - // that a new data packet was produced - utils::SpinLock::Acquire locked(interests_cache_lock_); - if (!seqs_map_.empty()) { - for (auto it = seqs_map_.begin(); it != seqs_map_.end(); it++) { - if (it->first != old_curr) sendNack(it->first); - } - seqs_map_.clear(); - timers_map_.clear(); - } -} - -void RTCProducerSocket::onInterest(Interest::Ptr &&interest) { - uint32_t interestSeg = interest->getName().getSuffix(); - uint32_t lifetime = interest->getLifetime(); - - if (on_interest_input_) { - on_interest_input_(*this, *interest); - } - - uint64_t now = std::chrono::duration_cast<std::chrono::milliseconds>( - std::chrono::steady_clock::now().time_since_epoch()) - .count(); - - if (interestSeg > HICN_MAX_DATA_SEQ) { - sendNack(interestSeg); - return; - } - - const std::shared_ptr<ContentObject> content_object = - output_buffer_.find(*interest); - - if (content_object) { - if (on_interest_satisfied_output_buffer_) { - on_interest_satisfied_output_buffer_(*this, *interest); - } - - if (on_content_object_output_) { - on_content_object_output_(*this, *content_object); - } - - TRANSPORT_LOGD("Send content %u (onInterest)", content_object->getName().getSuffix()); - portal_->sendContentObject(*content_object); - return; - } else { - if (on_interest_process_) { - on_interest_process_(*this, *interest); - } - } - - // if the production rate is less than MIN_PRODUCTION_RATE we put the - // interest in a queue, otherwise we handle it in the usual way - if (packetsProductionRate_.load() < MIN_PRODUCTION_RATE && - interestSeg >= currentSeg_.load()) { - utils::SpinLock::Acquire locked(interests_cache_lock_); - - uint64_t next_timer = ~0; - if (!timers_map_.empty()) { - next_timer = timers_map_.begin()->first; - } - - uint64_t expiration = now + (lifetime * LIFETIME_FRACTION); - // check if the seq number exists already - auto it_seqs = seqs_map_.find(interestSeg); - if (it_seqs != seqs_map_.end()) { - // the seq already exists - if (expiration < it_seqs->second) { - // we need to update the timer becasue we got a smaller one - // 1) remove the entry from the multimap - // 2) update this entry - auto range = timers_map_.equal_range(it_seqs->second); - for (auto it_timers = range.first; it_timers != range.second; - it_timers++) { - if (it_timers->second == it_seqs->first) { - timers_map_.erase(it_timers); - break; - } - } - timers_map_.insert( - std::pair<uint64_t, uint32_t>(expiration, interestSeg)); - it_seqs->second = expiration; - } else { - // nothing to do here - return; - } - } else { - // add the new seq - timers_map_.insert( - std::pair<uint64_t, uint32_t>(expiration, interestSeg)); - seqs_map_.insert(std::pair<uint32_t, uint64_t>(interestSeg, expiration)); - } - - // here we have at least one interest in the queue, we need to start or - // update the timer - if (!timer_on_) { - // set timeout - timer_on_ = true; - scheduleCacheTimer(timers_map_.begin()->first - now); - } else { - // re-schedule the timer because a new interest will expires sooner - if (next_timer > timers_map_.begin()->first) { - interests_cache_timer_->cancel(); - scheduleCacheTimer(timers_map_.begin()->first - now); - } - } - return; - } - - uint32_t max_gap = (uint32_t)floor( - (double)((double)((double)lifetime * INTEREST_LIFETIME_REDUCTION_FACTOR / - 1000.0) * - (double)packetsProductionRate_.load())); - - if (interestSeg < currentSeg_.load() || - interestSeg > (max_gap + currentSeg_.load())) { - sendNack(interestSeg); - } - // else drop packet -} - -void RTCProducerSocket::scheduleCacheTimer(uint64_t wait) { - interests_cache_timer_->expires_from_now(std::chrono::milliseconds(wait)); - interests_cache_timer_->async_wait([this](std::error_code ec) { - if (ec) return; - interestCacheTimer(); - }); -} - -void RTCProducerSocket::interestCacheTimer() { - uint64_t now = std::chrono::duration_cast<std::chrono::milliseconds>( - std::chrono::steady_clock::now().time_since_epoch()) - .count(); - - utils::SpinLock::Acquire locked(interests_cache_lock_); - - for (auto it_timers = timers_map_.begin(); it_timers != timers_map_.end();) { - uint64_t expire = it_timers->first; - if (expire <= now) { - uint32_t seq = it_timers->second; - sendNack(seq); - // remove the interest from the other map - seqs_map_.erase(seq); - it_timers = timers_map_.erase(it_timers); - } else { - // stop, we are done! - break; - } - } - if (timers_map_.empty()) { - timer_on_ = false; - } else { - timer_on_ = true; - scheduleCacheTimer(timers_map_.begin()->first - now); - } -} - -void RTCProducerSocket::sendNack(uint32_t sequence) { - auto nack_payload = utils::MemBuf::create(NACK_HEADER_SIZE); - nack_payload->append(NACK_HEADER_SIZE); - ContentObject nack; - - Name n(flowName_); - nack.appendPayload(std::move(nack_payload)); - nack.setName(n.setSuffix(sequence)); - - uint32_t *payload_ptr = (uint32_t *)nack.getPayload()->data(); - *payload_ptr = currentSeg_.load(); - - *(++payload_ptr) = bytesProductionRate_.load(); - - nack.setLifetime(0); - nack.setPathLabel(prodLabel_); - - if (on_content_object_output_) { - on_content_object_output_(*this, nack); - } - - TRANSPORT_LOGD("Send nack %u", sequence); - portal_->sendContentObject(nack); -} - -} // namespace interface - -} // end namespace transport diff --git a/libtransport/src/hicn/transport/interfaces/rtc_socket_producer.h b/libtransport/src/hicn/transport/interfaces/rtc_socket_producer.h deleted file mode 100644 index d7917a8..0000000 --- a/libtransport/src/hicn/transport/interfaces/rtc_socket_producer.h +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (c) 2017-2019 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/interfaces/socket_producer.h> -#include <hicn/transport/utils/content_store.h> - -#include <atomic> -#include <map> -#include <mutex> - -namespace transport { - -namespace interface { - -class RTCProducerSocket : virtual public ProducerSocket { - public: - RTCProducerSocket(asio::io_service &io_service); - - RTCProducerSocket(); - - ~RTCProducerSocket(); - - void registerPrefix(const Prefix &producer_namespace) override; - - virtual void produce(std::unique_ptr<utils::MemBuf> &&buffer) override; - - void onInterest(Interest::Ptr &&interest) override; - - private: - void sendNack(uint32_t sequence); - void updateStats(); - void scheduleCacheTimer(uint64_t wait); - void scheduleRoundTimer(); - void interestCacheTimer(); - - std::atomic<uint32_t> currentSeg_; - uint32_t prodLabel_; - uint16_t headerSize_; - Name flowName_; - std::atomic<uint32_t> producedBytes_; - std::atomic<uint32_t> producedPackets_; - std::atomic<uint32_t> bytesProductionRate_; - std::atomic<uint32_t> packetsProductionRate_; - uint32_t perSecondFactor_; - - std::unique_ptr<asio::steady_timer> round_timer_; - - // cache for the received interests - // this map maps the expiration time of an interest to - // its sequence number. the map is sorted by timeouts - // the same timeout may be used for multiple sequence numbers - // but for each sequence number we store only the smallest - // expiry time. In this way the mapping from seqs_map_ to - // timers_map_ is unique - std::multimap<uint64_t,uint32_t> timers_map_; - // this map does the opposite, this map is not ordered - std::unordered_map<uint32_t,uint64_t> seqs_map_; - bool timer_on_; - std::unique_ptr<asio::steady_timer> interests_cache_timer_; - utils::SpinLock interests_cache_lock_; -}; - -} // namespace interface - -} // end namespace transport diff --git a/libtransport/src/hicn/transport/interfaces/socket.h b/libtransport/src/hicn/transport/interfaces/socket.h deleted file mode 100644 index 4c9bda7..0000000 --- a/libtransport/src/hicn/transport/interfaces/socket.h +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (c) 2017-2019 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/config.h> -#include <hicn/transport/core/facade.h> -#include <hicn/transport/interfaces/callbacks.h> -#include <hicn/transport/interfaces/socket_options_default_values.h> -#include <hicn/transport/interfaces/socket_options_keys.h> - -#define SOCKET_OPTION_GET 0 -#define SOCKET_OPTION_NOT_GET 1 -#define SOCKET_OPTION_SET 2 -#define SOCKET_OPTION_NOT_SET 3 -#define SOCKET_OPTION_DEFAULT 12345 - -namespace transport { - -namespace interface { - -// Forward Declarations -template <typename PortalType> -class Socket; - -// Define the portal and its connector, depending on the compilation options -// passed by the build tool. -using HicnForwarderPortal = core::HicnForwarderPortal; - -#ifdef __linux__ -#ifndef __ANDROID__ -using RawSocketPortal = core::RawSocketPortal; -#endif -#endif - -#ifdef __vpp__ -using VPPForwarderPortal = core::VPPForwarderPortal; -using BaseSocket = Socket<VPPForwarderPortal>; -using BasePortal = VPPForwarderPortal; -#else -using BaseSocket = Socket<HicnForwarderPortal>; -using BasePortal = HicnForwarderPortal; -#endif - -template <typename PortalType> -class Socket { - static_assert(std::is_same<PortalType, HicnForwarderPortal>::value -#ifdef __linux__ -#ifndef __ANDROID__ - || std::is_same<PortalType, RawSocketPortal>::value -#ifdef __vpp__ - || std::is_same<PortalType, VPPForwarderPortal>::value -#endif -#endif - , -#else - , - -#endif - "This class is not allowed as Portal"); - - public: - using Portal = PortalType; - - virtual asio::io_service &getIoService() = 0; - - virtual void connect() = 0; - - virtual bool isRunning() = 0; - - protected: - virtual ~Socket(){}; - - protected: - std::string output_interface_; -}; - -} // namespace interface - -} // namespace transport diff --git a/libtransport/src/hicn/transport/interfaces/socket_consumer.cc b/libtransport/src/hicn/transport/interfaces/socket_consumer.cc deleted file mode 100644 index b2c0549..0000000 --- a/libtransport/src/hicn/transport/interfaces/socket_consumer.cc +++ /dev/null @@ -1,862 +0,0 @@ -/* - * Copyright (c) 2017-2019 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. - */ - -#include <hicn/transport/interfaces/socket_consumer.h> -#include <hicn/transport/protocols/cbr.h> -#include <hicn/transport/protocols/raaqm.h> -#include <hicn/transport/protocols/rtc.h> - -namespace transport { - -namespace interface { - -ConsumerSocket::ConsumerSocket(int protocol) - : ConsumerSocket(protocol, internal_io_service_) {} - -ConsumerSocket::ConsumerSocket(int protocol, asio::io_service &io_service) - : io_service_(io_service), - portal_(std::make_shared<Portal>(io_service_)), - async_downloader_(), - interest_lifetime_(default_values::interest_lifetime), - min_window_size_(default_values::min_window_size), - max_window_size_(default_values::max_window_size), - current_window_size_(-1), - max_retransmissions_( - default_values::transport_protocol_max_retransmissions), - /****** RAAQM Parameters ******/ - minimum_drop_probability_(default_values::minimum_drop_probability), - sample_number_(default_values::sample_number), - gamma_(default_values::gamma_value), - beta_(default_values::beta_value), - drop_factor_(default_values::drop_factor), - /****** END RAAQM Parameters ******/ - rate_estimation_alpha_(default_values::rate_alpha), - rate_estimation_observer_(nullptr), - rate_estimation_batching_parameter_(default_values::batch), - rate_estimation_choice_(0), - verifier_(std::make_shared<utils::Verifier>()), - verify_signature_(false), - key_content_(false), - on_interest_output_(VOID_HANDLER), - on_interest_timeout_(VOID_HANDLER), - on_interest_satisfied_(VOID_HANDLER), - on_content_object_input_(VOID_HANDLER), - on_content_object_verification_(VOID_HANDLER), - on_content_object_(VOID_HANDLER), - on_manifest_(VOID_HANDLER), - stats_summary_(VOID_HANDLER), - read_callback_(nullptr), - virtual_download_(false), - timer_interval_milliseconds_(0), - guard_raaqm_params_() { - switch (protocol) { - case TransportProtocolAlgorithms::CBR: - transport_protocol_ = std::make_unique<CbrTransportProtocol>(this); - break; - case TransportProtocolAlgorithms::RTC: - transport_protocol_ = std::make_unique<RTCTransportProtocol>(this); - break; - case TransportProtocolAlgorithms::RAAQM: - default: - transport_protocol_ = std::make_unique<RaaqmTransportProtocol>(this); - break; - } -} - -ConsumerSocket::~ConsumerSocket() { - stop(); - async_downloader_.stop(); -} - -void ConsumerSocket::connect() { portal_->connect(); } - -int ConsumerSocket::consume(const Name &name) { - if (transport_protocol_->isRunning()) { - return CONSUMER_BUSY; - } - - network_name_ = name; - network_name_.setSuffix(0); - - transport_protocol_->start(); - - return CONSUMER_FINISHED; -} - -int ConsumerSocket::asyncConsume(const Name &name) { - if (!async_downloader_.stopped()) { - async_downloader_.add([this, name]() { - network_name_ = std::move(name); - network_name_.setSuffix(0); - transport_protocol_->start(); - }); - } - - return CONSUMER_RUNNING; -} - -bool ConsumerSocket::verifyKeyPackets() { - return transport_protocol_->verifyKeyPackets(); -} - -void ConsumerSocket::stop() { - if (transport_protocol_) { - if (transport_protocol_->isRunning()) transport_protocol_->stop(); - } -} - -void ConsumerSocket::resume() { - if (!transport_protocol_->isRunning()) { - transport_protocol_->resume(); - } -} - -asio::io_service &ConsumerSocket::getIoService() { - return portal_->getIoService(); -} - -int ConsumerSocket::setSocketOption(int socket_option_key, - ReadCallback *socket_option_value) { - // Reschedule the function on the io_service to avoid race condition in case - // setSocketOption is called while the io_service is running. - return rescheduleOnIOService( - socket_option_key, socket_option_value, - [this](int socket_option_key, ReadCallback *socket_option_value) -> int { - switch (socket_option_key) { - case ConsumerCallbacksOptions::READ_CALLBACK: - read_callback_ = socket_option_value; - break; - default: - return SOCKET_OPTION_NOT_SET; - } - - return SOCKET_OPTION_SET; - }); -} - -int ConsumerSocket::getSocketOption(int socket_option_key, - ReadCallback **socket_option_value) { - // Reschedule the function on the io_service to avoid race condition in case - // setSocketOption is called while the io_service is running. - return rescheduleOnIOService( - socket_option_key, socket_option_value, - [this](int socket_option_key, ReadCallback **socket_option_value) -> int { - switch (socket_option_key) { - case ConsumerCallbacksOptions::READ_CALLBACK: - *socket_option_value = read_callback_; - break; - default: - return SOCKET_OPTION_NOT_GET; - } - - return SOCKET_OPTION_GET; - }); -} - -int ConsumerSocket::setSocketOption(int socket_option_key, - double socket_option_value) { - utils::SpinLock::Acquire locked(guard_raaqm_params_); - switch (socket_option_key) { - case MIN_WINDOW_SIZE: - min_window_size_ = socket_option_value; - break; - - case MAX_WINDOW_SIZE: - max_window_size_ = socket_option_value; - break; - - case CURRENT_WINDOW_SIZE: - current_window_size_ = socket_option_value; - break; - - case GAMMA_VALUE: - gamma_ = socket_option_value; - break; - - case BETA_VALUE: - beta_ = socket_option_value; - break; - - case DROP_FACTOR: - drop_factor_ = socket_option_value; - break; - - case MINIMUM_DROP_PROBABILITY: - minimum_drop_probability_ = socket_option_value; - break; - - case RATE_ESTIMATION_ALPHA: - if (socket_option_value >= 0 && socket_option_value < 1) { - rate_estimation_alpha_ = socket_option_value; - } else { - rate_estimation_alpha_ = default_values::alpha; - } - break; - default: - return SOCKET_OPTION_NOT_SET; - } - - return SOCKET_OPTION_SET; -} - -int ConsumerSocket::setSocketOption(int socket_option_key, - uint32_t socket_option_value) { - utils::SpinLock::Acquire locked(guard_raaqm_params_); - switch (socket_option_key) { - case GeneralTransportOptions::MAX_INTEREST_RETX: - max_retransmissions_ = socket_option_value; - break; - - case GeneralTransportOptions::INTEREST_LIFETIME: - interest_lifetime_ = socket_option_value; - break; - - case RateEstimationOptions::RATE_ESTIMATION_BATCH_PARAMETER: - if (socket_option_value > 0) { - rate_estimation_batching_parameter_ = socket_option_value; - } else { - rate_estimation_batching_parameter_ = default_values::batch; - } - break; - - case RateEstimationOptions::RATE_ESTIMATION_CHOICE: - if (socket_option_value > 0) { - rate_estimation_choice_ = socket_option_value; - } else { - rate_estimation_choice_ = default_values::rate_choice; - } - break; - - case GeneralTransportOptions::STATS_INTERVAL: - timer_interval_milliseconds_ = socket_option_value; - break; - - default: - return SOCKET_OPTION_NOT_SET; - } - - return SOCKET_OPTION_SET; -} - -int ConsumerSocket::setSocketOption(int socket_option_key, - std::nullptr_t socket_option_value) { - // Reschedule the function on the io_service to avoid race condition in case - // setSocketOption is called while the io_service is running. - return rescheduleOnIOService( - socket_option_key, socket_option_value, - [this](int socket_option_key, std::nullptr_t socket_option_value) -> int { - switch (socket_option_key) { - case ConsumerCallbacksOptions::INTEREST_RETRANSMISSION: - if (socket_option_value == VOID_HANDLER) { - on_interest_retransmission_ = VOID_HANDLER; - break; - } - - case ConsumerCallbacksOptions::INTEREST_EXPIRED: - if (socket_option_value == VOID_HANDLER) { - on_interest_timeout_ = VOID_HANDLER; - break; - } - - case ConsumerCallbacksOptions::INTEREST_SATISFIED: - if (socket_option_value == VOID_HANDLER) { - on_interest_satisfied_ = VOID_HANDLER; - break; - } - - case ConsumerCallbacksOptions::INTEREST_OUTPUT: - if (socket_option_value == VOID_HANDLER) { - on_interest_output_ = VOID_HANDLER; - break; - } - - case ConsumerCallbacksOptions::CONTENT_OBJECT_INPUT: - if (socket_option_value == VOID_HANDLER) { - on_content_object_input_ = VOID_HANDLER; - break; - } - - case ConsumerCallbacksOptions::CONTENT_OBJECT_TO_VERIFY: - if (socket_option_value == VOID_HANDLER) { - on_content_object_verification_ = VOID_HANDLER; - break; - } - - default: - return SOCKET_OPTION_NOT_SET; - } - - return SOCKET_OPTION_SET; - }); -} - -int ConsumerSocket::setSocketOption(int socket_option_key, - bool socket_option_value) { - int result = SOCKET_OPTION_NOT_SET; - if (!transport_protocol_->isRunning()) { - switch (socket_option_key) { - case OtherOptions::VIRTUAL_DOWNLOAD: - virtual_download_ = socket_option_value; - result = SOCKET_OPTION_SET; - break; - - case GeneralTransportOptions::VERIFY_SIGNATURE: - verify_signature_ = socket_option_value; - result = SOCKET_OPTION_SET; - break; - - case GeneralTransportOptions::KEY_CONTENT: - key_content_ = socket_option_value; - result = SOCKET_OPTION_SET; - break; - - default: - return result; - } - } - return result; -} - -int ConsumerSocket::setSocketOption( - int socket_option_key, ConsumerContentObjectCallback socket_option_value) { - // Reschedule the function on the io_service to avoid race condition in case - // setSocketOption is called while the io_service is running. - return rescheduleOnIOService( - socket_option_key, socket_option_value, - [this](int socket_option_key, - ConsumerContentObjectCallback socket_option_value) -> int { - switch (socket_option_key) { - case ConsumerCallbacksOptions::CONTENT_OBJECT_INPUT: - on_content_object_input_ = socket_option_value; - break; - - default: - return SOCKET_OPTION_NOT_SET; - } - - return SOCKET_OPTION_SET; - }); -} - -int ConsumerSocket::setSocketOption( - int socket_option_key, - ConsumerContentObjectVerificationCallback socket_option_value) { - // Reschedule the function on the io_service to avoid race condition in case - // setSocketOption is called while the io_service is running. - return rescheduleOnIOService( - socket_option_key, socket_option_value, - [this](int socket_option_key, - ConsumerContentObjectVerificationCallback socket_option_value) - -> int { - switch (socket_option_key) { - case ConsumerCallbacksOptions::CONTENT_OBJECT_TO_VERIFY: - on_content_object_verification_ = socket_option_value; - break; - - default: - return SOCKET_OPTION_NOT_SET; - } - - return SOCKET_OPTION_SET; - }); -} - -int ConsumerSocket::setSocketOption( - int socket_option_key, ConsumerInterestCallback socket_option_value) { - // Reschedule the function on the io_service to avoid race condition in case - // setSocketOption is called while the io_service is running. - return rescheduleOnIOService( - socket_option_key, socket_option_value, - [this](int socket_option_key, - ConsumerInterestCallback socket_option_value) -> int { - switch (socket_option_key) { - case ConsumerCallbacksOptions::INTEREST_RETRANSMISSION: - on_interest_retransmission_ = socket_option_value; - break; - - case ConsumerCallbacksOptions::INTEREST_OUTPUT: - on_interest_output_ = socket_option_value; - break; - - case ConsumerCallbacksOptions::INTEREST_EXPIRED: - on_interest_timeout_ = socket_option_value; - break; - - case ConsumerCallbacksOptions::INTEREST_SATISFIED: - on_interest_satisfied_ = socket_option_value; - break; - - default: - return SOCKET_OPTION_NOT_SET; - } - - return SOCKET_OPTION_SET; - }); -} - -int ConsumerSocket::setSocketOption( - int socket_option_key, ConsumerManifestCallback socket_option_value) { - // Reschedule the function on the io_service to avoid race condition in case - // setSocketOption is called while the io_service is running. - return rescheduleOnIOService( - socket_option_key, socket_option_value, - [this](int socket_option_key, - ConsumerManifestCallback socket_option_value) -> int { - switch (socket_option_key) { - case ConsumerCallbacksOptions::MANIFEST_INPUT: - on_manifest_ = socket_option_value; - break; - - default: - return SOCKET_OPTION_NOT_SET; - } - - return SOCKET_OPTION_SET; - }); -} - -int ConsumerSocket::setSocketOption( - int socket_option_key, - ConsumerContentObjectVerificationFailedCallback socket_option_value) { - return rescheduleOnIOService( - socket_option_key, socket_option_value, - [this]( - int socket_option_key, - ConsumerContentObjectVerificationFailedCallback socket_option_value) - -> int { - switch (socket_option_key) { - case ConsumerCallbacksOptions::VERIFICATION_FAILED: - verification_failed_callback_ = socket_option_value; - break; - - default: - return SOCKET_OPTION_NOT_SET; - } - - return SOCKET_OPTION_SET; - }); -} - -int ConsumerSocket::setSocketOption(int socket_option_key, - IcnObserver *socket_option_value) { - utils::SpinLock::Acquire locked(guard_raaqm_params_); - switch (socket_option_key) { - case RateEstimationOptions::RATE_ESTIMATION_OBSERVER: - rate_estimation_observer_ = socket_option_value; - break; - - default: - return SOCKET_OPTION_NOT_SET; - } - - return SOCKET_OPTION_SET; -} - -int ConsumerSocket::setSocketOption( - int socket_option_key, - const std::shared_ptr<utils::Verifier> &socket_option_value) { - int result = SOCKET_OPTION_NOT_SET; - if (!transport_protocol_->isRunning()) { - switch (socket_option_key) { - case GeneralTransportOptions::VERIFIER: - verifier_.reset(); - verifier_ = socket_option_value; - result = SOCKET_OPTION_SET; - break; - default: - return result; - } - } - - return result; -} - -int ConsumerSocket::setSocketOption(int socket_option_key, - const std::string &socket_option_value) { - int result = SOCKET_OPTION_NOT_SET; - if (!transport_protocol_->isRunning()) { - switch (socket_option_key) { - case GeneralTransportOptions::CERTIFICATE: - key_id_ = verifier_->addKeyFromCertificate(socket_option_value); - if (key_id_ != nullptr) result = SOCKET_OPTION_SET; - break; - - case DataLinkOptions::OUTPUT_INTERFACE: - output_interface_ = socket_option_value; - portal_->setOutputInterface(output_interface_); - result = SOCKET_OPTION_SET; - break; - - default: - return result; - } - } - return result; -} - -int ConsumerSocket::setSocketOption(int socket_option_key, - ConsumerTimerCallback socket_option_value) { - // Reschedule the function on the io_service to avoid race condition in case - // setSocketOption is called while the io_service is running. - return rescheduleOnIOService( - socket_option_key, socket_option_value, - [this](int socket_option_key, - ConsumerTimerCallback socket_option_value) -> int { - switch (socket_option_key) { - case ConsumerCallbacksOptions::STATS_SUMMARY: - stats_summary_ = socket_option_value; - break; - - default: - return SOCKET_OPTION_NOT_SET; - } - - return SOCKET_OPTION_SET; - }); -} - -int ConsumerSocket::getSocketOption(int socket_option_key, - double &socket_option_value) { - utils::SpinLock::Acquire locked(guard_raaqm_params_); - switch (socket_option_key) { - case GeneralTransportOptions::MIN_WINDOW_SIZE: - socket_option_value = min_window_size_; - break; - - case GeneralTransportOptions::MAX_WINDOW_SIZE: - socket_option_value = max_window_size_; - break; - - case GeneralTransportOptions::CURRENT_WINDOW_SIZE: - socket_option_value = current_window_size_; - break; - - // RAAQM parameters - - case RaaqmTransportOptions::GAMMA_VALUE: - socket_option_value = gamma_; - break; - - case RaaqmTransportOptions::BETA_VALUE: - socket_option_value = beta_; - break; - - case RaaqmTransportOptions::DROP_FACTOR: - socket_option_value = drop_factor_; - break; - - case RaaqmTransportOptions::MINIMUM_DROP_PROBABILITY: - socket_option_value = minimum_drop_probability_; - break; - - case RateEstimationOptions::RATE_ESTIMATION_ALPHA: - socket_option_value = rate_estimation_alpha_; - break; - - default: - return SOCKET_OPTION_NOT_GET; - } - - return SOCKET_OPTION_GET; -} - -int ConsumerSocket::getSocketOption(int socket_option_key, - uint32_t &socket_option_value) { - utils::SpinLock::Acquire locked(guard_raaqm_params_); - switch (socket_option_key) { - case GeneralTransportOptions::MAX_INTEREST_RETX: - socket_option_value = max_retransmissions_; - break; - - case GeneralTransportOptions::INTEREST_LIFETIME: - socket_option_value = interest_lifetime_; - break; - - case RaaqmTransportOptions::SAMPLE_NUMBER: - socket_option_value = sample_number_; - break; - - case RateEstimationOptions::RATE_ESTIMATION_BATCH_PARAMETER: - socket_option_value = rate_estimation_batching_parameter_; - break; - - case RateEstimationOptions::RATE_ESTIMATION_CHOICE: - socket_option_value = rate_estimation_choice_; - break; - - case GeneralTransportOptions::STATS_INTERVAL: - socket_option_value = timer_interval_milliseconds_; - break; - - default: - return SOCKET_OPTION_NOT_GET; - } - - return SOCKET_OPTION_GET; -} - -int ConsumerSocket::getSocketOption(int socket_option_key, - bool &socket_option_value) { - switch (socket_option_key) { - case GeneralTransportOptions::RUNNING: - socket_option_value = transport_protocol_->isRunning(); - break; - - case OtherOptions::VIRTUAL_DOWNLOAD: - socket_option_value = virtual_download_; - break; - - case GeneralTransportOptions::VERIFY_SIGNATURE: - socket_option_value = verify_signature_; - break; - - case GeneralTransportOptions::KEY_CONTENT: - socket_option_value = key_content_; - break; - - default: - return SOCKET_OPTION_NOT_GET; - } - - return SOCKET_OPTION_GET; -} - -int ConsumerSocket::getSocketOption(int socket_option_key, - Name **socket_option_value) { - switch (socket_option_key) { - case GeneralTransportOptions::NETWORK_NAME: - *socket_option_value = &network_name_; - break; - - default: - return SOCKET_OPTION_NOT_GET; - } - - return SOCKET_OPTION_GET; -} - -int ConsumerSocket::getSocketOption( - int socket_option_key, - ConsumerContentObjectCallback **socket_option_value) { - // Reschedule the function on the io_service to avoid race condition in case - // setSocketOption is called while the io_service is running. - return rescheduleOnIOService( - socket_option_key, socket_option_value, - [this](int socket_option_key, - ConsumerContentObjectCallback **socket_option_value) -> int { - switch (socket_option_key) { - case ConsumerCallbacksOptions::CONTENT_OBJECT_INPUT: - *socket_option_value = &on_content_object_input_; - break; - - default: - return SOCKET_OPTION_NOT_GET; - } - - return SOCKET_OPTION_GET; - }); -} - -int ConsumerSocket::getSocketOption( - int socket_option_key, - ConsumerContentObjectVerificationCallback **socket_option_value) { - // Reschedule the function on the io_service to avoid race condition in case - // setSocketOption is called while the io_service is running. - return rescheduleOnIOService( - socket_option_key, socket_option_value, - [this](int socket_option_key, - ConsumerContentObjectVerificationCallback **socket_option_value) - -> int { - switch (socket_option_key) { - case ConsumerCallbacksOptions::CONTENT_OBJECT_TO_VERIFY: - *socket_option_value = &on_content_object_verification_; - break; - - default: - return SOCKET_OPTION_NOT_GET; - } - - return SOCKET_OPTION_GET; - }); -} - -int ConsumerSocket::getSocketOption( - int socket_option_key, ConsumerInterestCallback **socket_option_value) { - // Reschedule the function on the io_service to avoid race condition in case - // setSocketOption is called while the io_service is running. - return rescheduleOnIOService( - socket_option_key, socket_option_value, - [this](int socket_option_key, - ConsumerInterestCallback **socket_option_value) -> int { - switch (socket_option_key) { - case ConsumerCallbacksOptions::INTEREST_RETRANSMISSION: - *socket_option_value = &on_interest_retransmission_; - break; - - case ConsumerCallbacksOptions::INTEREST_OUTPUT: - *socket_option_value = &on_interest_output_; - break; - - case ConsumerCallbacksOptions::INTEREST_EXPIRED: - *socket_option_value = &on_interest_timeout_; - break; - - case ConsumerCallbacksOptions::INTEREST_SATISFIED: - *socket_option_value = &on_interest_satisfied_; - break; - - default: - return SOCKET_OPTION_NOT_GET; - } - - return SOCKET_OPTION_GET; - }); -} - -int ConsumerSocket::getSocketOption( - int socket_option_key, ConsumerManifestCallback **socket_option_value) { - // Reschedule the function on the io_service to avoid race condition in case - // setSocketOption is called while the io_service is running. - return rescheduleOnIOService( - socket_option_key, socket_option_value, - [this](int socket_option_key, - ConsumerManifestCallback **socket_option_value) -> int { - switch (socket_option_key) { - case ConsumerCallbacksOptions::MANIFEST_INPUT: - *socket_option_value = &on_manifest_; - break; - default: - return SOCKET_OPTION_NOT_GET; - } - - return SOCKET_OPTION_GET; - }); -} - -int ConsumerSocket::getSocketOption( - int socket_option_key, - ConsumerContentObjectVerificationFailedCallback **socket_option_value) { - // Reschedule the function on the io_service to avoid race condition in case - // setSocketOption is called while the io_service is running. - return rescheduleOnIOService( - socket_option_key, socket_option_value, - [this]( - int socket_option_key, - ConsumerContentObjectVerificationFailedCallback **socket_option_value) - -> int { - switch (socket_option_key) { - case ConsumerCallbacksOptions::VERIFICATION_FAILED: - *socket_option_value = &verification_failed_callback_; - break; - default: - return SOCKET_OPTION_NOT_GET; - } - - return SOCKET_OPTION_GET; - }); -} - -int ConsumerSocket::getSocketOption( - int socket_option_key, std::shared_ptr<Portal> &socket_option_value) { - switch (socket_option_key) { - case PORTAL: - socket_option_value = portal_; - break; - - default: - return SOCKET_OPTION_NOT_GET; - } - - return SOCKET_OPTION_GET; -} - -int ConsumerSocket::getSocketOption(int socket_option_key, - IcnObserver **socket_option_value) { - utils::SpinLock::Acquire locked(guard_raaqm_params_); - switch (socket_option_key) { - case RateEstimationOptions::RATE_ESTIMATION_OBSERVER: - *socket_option_value = (rate_estimation_observer_); - break; - - default: - return SOCKET_OPTION_NOT_GET; - } - - return SOCKET_OPTION_GET; -} - -int ConsumerSocket::getSocketOption( - int socket_option_key, - std::shared_ptr<utils::Verifier> &socket_option_value) { - switch (socket_option_key) { - case GeneralTransportOptions::VERIFIER: - socket_option_value = verifier_; - break; - default: - return SOCKET_OPTION_NOT_GET; - } - - return SOCKET_OPTION_GET; -} - -int ConsumerSocket::getSocketOption(int socket_option_key, - std::string &socket_option_value) { - switch (socket_option_key) { - case DataLinkOptions::OUTPUT_INTERFACE: - socket_option_value = output_interface_; - break; - default: - return SOCKET_OPTION_NOT_GET; - } - - return SOCKET_OPTION_GET; -} - -int ConsumerSocket::getSocketOption(int socket_option_key, - TransportStatistics **socket_option_value) { - switch (socket_option_key) { - case OtherOptions::STATISTICS: - *socket_option_value = &stats_; - break; - default: - return SOCKET_OPTION_NOT_GET; - } - - return SOCKET_OPTION_GET; -} - -int ConsumerSocket::getSocketOption( - int socket_option_key, ConsumerTimerCallback **socket_option_value) { - // Reschedule the function on the io_service to avoid race condition in case - // setSocketOption is called while the io_service is running. - return rescheduleOnIOService( - socket_option_key, socket_option_value, - [this](int socket_option_key, - ConsumerTimerCallback **socket_option_value) -> int { - switch (socket_option_key) { - case ConsumerCallbacksOptions::STATS_SUMMARY: - *socket_option_value = &stats_summary_; - break; - default: - return SOCKET_OPTION_NOT_GET; - } - - return SOCKET_OPTION_GET; - }); -} - -} // namespace interface - -} // namespace transport diff --git a/libtransport/src/hicn/transport/interfaces/socket_consumer.h b/libtransport/src/hicn/transport/interfaces/socket_consumer.h deleted file mode 100644 index 48a594a..0000000 --- a/libtransport/src/hicn/transport/interfaces/socket_consumer.h +++ /dev/null @@ -1,412 +0,0 @@ -/* - * Copyright (c) 2017-2019 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/interfaces/socket.h> -#include <hicn/transport/interfaces/socket_options_default_values.h> -#include <hicn/transport/protocols/protocol.h> -#include <hicn/transport/protocols/statistics.h> -#include <hicn/transport/utils/event_thread.h> -#include <hicn/transport/utils/verifier.h> - -extern "C" { -#include <parc/security/parc_KeyId.h> -} - -#define CONSUMER_FINISHED 0 -#define CONSUMER_BUSY 1 -#define CONSUMER_RUNNING 2 - -namespace transport { - -namespace interface { - -using namespace core; -using namespace protocol; - -/** - * @brief Main interface for consumer applications. - * - * The consumer socket is the main interface for a consumer application. - * It allows to retrieve an application data from one/many producers, by - * hiding all the complexity of the transport protocol used underneath. - */ -class ConsumerSocket : public BaseSocket { - public: - /** - * The ReadCallback is a class which can be used by the transport for both - * querying the application needs and notifying events. - * - * Beware that the methods of this class will be called synchronously while - * the transport is working, so the operations the application is performing - * on the data retrieved should be executed in another thread in an - * asynchronous manner. Blocking one of these callbacks means blocking the - * transport. - */ - class ReadCallback { - public: - virtual ~ReadCallback() = default; - - /** - * This API will specify to the transport whether the buffer should be - * allocated by the application (and then the retrieved content will be - * copied there) or the transport should allocate the buffer and "move" it - * to the application. In other words, if isBufferMovable return true, the - * transport will transfer the ownership of the read buffer to the - * application, without performing an additional copy, while if it returns - * false the transport will use the getReadBuffer API. - * - * By default this method returns true. - * - */ - virtual bool isBufferMovable() noexcept { return true; } - - /** - * This method will be called by the transport when the content is - * available. The application can then allocate its own buffer and provide - * the address to the transport, which will use it for writing the data. - * Note that if the application won't allocate enough memory this method - * will be called several times, until the internal read buffer will be - * emptied. For ensuring this method will be called once, applications - * should allocate at least maxBufferSize() bytes. - * - * @param application_buffer - Pointer to the application's buffer. - * @param max_length - The length of the application buffer. - */ - virtual void getReadBuffer(uint8_t **application_buffer, - size_t *max_length) = 0; - - /** - * This method will be called by the transport after calling getReadBuffer, - * in order to notify the application that length bytes are available in the - * buffer. The max_length size of the buffer could be larger than the actual - * amount of bytes written. - * - * @param length - The number of bytes placed in the buffer. - */ - virtual void readDataAvailable(size_t length) noexcept = 0; - - /** - * This method will be called by the transport for understanding how many - * bytes it should read (at most) before notifying the application. - * - * By default it reads 64 KB. - */ - virtual size_t maxBufferSize() const { return 64 * 1024; } - - /** - * This method will be called by the transport iff (isBufferMovable == - * true). The unique_ptr underlines the fact that the ownership of the - * buffer is being transferred to the application. - * - * @param buffer - The buffer - */ - virtual void readBufferAvailable( - std::unique_ptr<utils::MemBuf> &&buffer) noexcept {} - - /** - * readError() will be invoked if an error occurs reading from the - * transport. - * - * @param ec - An error code describing the error. - */ - virtual void readError(const std::error_code ec) noexcept = 0; - - /** - * This callback will be invoked when the whole content is retrieved. The - * transport itself knows when a content is retrieved (since it is not an - * opaque bytestream like TCP), and the transport itself is able to tell - * the application when the transfer is done. - */ - virtual void readSuccess(std::size_t total_size) noexcept = 0; - - virtual void afterRead() {} - }; - - /** - * @brief Create a new consumer socket. - * - * @param protocol - The transport protocol to use. So far the following - * transport are supported: - * - CBR: Constant bitrate - * - Raaqm: Based on paper: Optimal multipath congestion control and request - * forwarding in information-centric networks: Protocol design and - * experimentation. G Carofiglio, M Gallo, L Muscariello. Computer Networks - * 110, 104-117 - * - RTC: Real time communication - */ - explicit ConsumerSocket(int protocol); - explicit ConsumerSocket(int protocol, asio::io_service &io_service); - - /** - * @brief Destroy the consumer socket. - */ - ~ConsumerSocket(); - - /** - * @brief Connect the consumer socket to the underlying hICN forwarder. - */ - void connect() override; - - /** - * @brief Check whether consumer socket is active or not. - */ - bool isRunning() override { return transport_protocol_->isRunning(); } - - /** - * Retrieve a content using the protocol specified in the constructor. - * This function blocks until the whole content is downloaded. - * For monitoring the status of the download, the application MUST set the - * ConsumerRead callback. This callback will be called periodically (depending - * on the needs of the application), allowing the application to save the - * retrieved data. - * - * @param name - The name of the content to retrieve. - * - * @return CONSUMER_BUSY if a pending download exists - * @return CONSUMER_FINISHED when the download finishes - * - * Notice that the fact consume() returns CONSUMER_FINISHED does not imply the - * content retrieval succeeded. This information can be obtained from the - * error code in CONTENT_RETRIEVED callback. - */ - virtual int consume(const Name &name); - virtual int asyncConsume(const Name &name); - - /** - * Verify the packets containing a key after the origin of the key has been - * validated by the client. - * - * @return true if all packets are valid, false otherwise - */ - virtual bool verifyKeyPackets(); - - /** - * Stops the consumer socket. If several downloads are queued (using - * asyncConsume), this call stops just the current one. - */ - void stop(); - - /** - * Resume the download from the same exact point it stopped. - */ - void resume(); - - /** - * Get the io_service which is running the transport protocol event loop. - * - * @return A reference to the internal io_service where the transport protocol - * is running. - */ - asio::io_service &getIoService() override; - - virtual int setSocketOption(int socket_option_key, - ReadCallback *socket_option_value); - - virtual int getSocketOption(int socket_option_key, - ReadCallback **socket_option_value); - - virtual int setSocketOption(int socket_option_key, - double socket_option_value); - - virtual int setSocketOption(int socket_option_key, - uint32_t socket_option_value); - - virtual int setSocketOption(int socket_option_key, - std::nullptr_t socket_option_value); - - virtual int setSocketOption(int socket_option_key, bool socket_option_value); - - virtual int setSocketOption( - int socket_option_key, ConsumerContentObjectCallback socket_option_value); - - virtual int setSocketOption( - int socket_option_key, - ConsumerContentObjectVerificationFailedCallback socket_option_value); - - virtual int setSocketOption( - int socket_option_key, - ConsumerContentObjectVerificationCallback socket_option_value); - - virtual int setSocketOption(int socket_option_key, - ConsumerInterestCallback socket_option_value); - - virtual int setSocketOption(int socket_option_key, - ConsumerManifestCallback socket_option_value); - - virtual int setSocketOption(int socket_option_key, - IcnObserver *socket_option_value); - - virtual int setSocketOption( - int socket_option_key, - const std::shared_ptr<utils::Verifier> &socket_option_value); - - virtual int setSocketOption(int socket_option_key, - const std::string &socket_option_value); - - virtual int setSocketOption(int socket_option_key, - ConsumerTimerCallback socket_option_value); - - virtual int getSocketOption(int socket_option_key, - double &socket_option_value); - - virtual int getSocketOption(int socket_option_key, - uint32_t &socket_option_value); - - virtual int getSocketOption(int socket_option_key, bool &socket_option_value); - - virtual int getSocketOption(int socket_option_key, - Name **socket_option_value); - - virtual int getSocketOption( - int socket_option_key, - ConsumerContentObjectCallback **socket_option_value); - - virtual int getSocketOption( - int socket_option_key, - ConsumerContentObjectVerificationFailedCallback **socket_option_value); - - virtual int getSocketOption( - int socket_option_key, - ConsumerContentObjectVerificationCallback **socket_option_value); - - virtual int getSocketOption(int socket_option_key, - ConsumerInterestCallback **socket_option_value); - - virtual int getSocketOption(int socket_option_key, - ConsumerManifestCallback **socket_option_value); - - virtual int getSocketOption(int socket_option_key, - std::shared_ptr<Portal> &socket_option_value); - - virtual int getSocketOption(int socket_option_key, - IcnObserver **socket_option_value); - - virtual int getSocketOption( - int socket_option_key, - std::shared_ptr<utils::Verifier> &socket_option_value); - - virtual int getSocketOption(int socket_option_key, - std::string &socket_option_value); - - virtual int getSocketOption(int socket_option_key, - ConsumerTimerCallback **socket_option_value); - - virtual int getSocketOption(int socket_option_key, - TransportStatistics **socket_option_value); - - protected: - // If the thread calling lambda_func is not the same of io_service, this - // function reschedule the function on it - template <typename Lambda, typename arg2> - int rescheduleOnIOService(int socket_option_key, arg2 socket_option_value, - Lambda lambda_func) { - // To enforce type check - std::function<int(int, arg2)> func = lambda_func; - int result = SOCKET_OPTION_SET; - if (transport_protocol_->isRunning()) { - std::mutex mtx; - /* Condition variable for the wait */ - std::condition_variable cv; - bool done = false; - io_service_.dispatch([&socket_option_key, &socket_option_value, &mtx, &cv, - &result, &done, &func]() { - std::unique_lock<std::mutex> lck(mtx); - done = true; - result = func(socket_option_key, socket_option_value); - cv.notify_all(); - }); - std::unique_lock<std::mutex> lck(mtx); - if (!done) { - cv.wait(lck); - } - } else { - result = func(socket_option_key, socket_option_value); - } - - return result; - } - - // context inner state variables - asio::io_service internal_io_service_; - asio::io_service &io_service_; - - std::shared_ptr<Portal> portal_; - - utils::EventThread async_downloader_; - - Name network_name_; - - int interest_lifetime_; - - double min_window_size_; - double max_window_size_; - double current_window_size_; - uint32_t max_retransmissions_; - - // RAAQM Parameters - double minimum_drop_probability_; - unsigned int sample_number_; - double gamma_; - double beta_; - double drop_factor_; - - // Rate estimation parameters - double rate_estimation_alpha_; - IcnObserver *rate_estimation_observer_; - int rate_estimation_batching_parameter_; - int rate_estimation_choice_; - - bool is_async_; - - // Verification parameters - std::shared_ptr<utils::Verifier> verifier_; - PARCKeyId *key_id_; - std::atomic_bool verify_signature_; - std::atomic_bool key_content_; - - ConsumerInterestCallback on_interest_retransmission_; - ConsumerInterestCallback on_interest_output_; - ConsumerInterestCallback on_interest_timeout_; - ConsumerInterestCallback on_interest_satisfied_; - - ConsumerContentObjectCallback on_content_object_input_; - ConsumerContentObjectVerificationCallback on_content_object_verification_; - - ConsumerContentObjectCallback on_content_object_; - ConsumerManifestCallback on_manifest_; - ConsumerTimerCallback stats_summary_; - ConsumerContentObjectVerificationFailedCallback verification_failed_callback_; - - ReadCallback *read_callback_; - - // Virtual download for traffic generator - bool virtual_download_; - - uint32_t timer_interval_milliseconds_; - - // Transport protocol - std::unique_ptr<TransportProtocol> transport_protocol_; - - // Statistic - TransportStatistics stats_; - - utils::SpinLock guard_raaqm_params_; -}; - -} // namespace interface - -} // end namespace transport diff --git a/libtransport/src/hicn/transport/interfaces/socket_options_default_values.h b/libtransport/src/hicn/transport/interfaces/socket_options_default_values.h deleted file mode 100644 index bcf103b..0000000 --- a/libtransport/src/hicn/transport/interfaces/socket_options_default_values.h +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (c) 2017-2019 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/base.h> -#include <chrono> -#include <cstdint> - -namespace transport { - -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 = - 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 = - 150000; // Content Object -static constexpr uint32_t log_2_default_buffer_size = 12; -static constexpr uint32_t signature_size = 260; // bytes -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 - -// 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; - -// 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; - -// 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 - -} // namespace default_values - -} // namespace interface - -} // end namespace transport diff --git a/libtransport/src/hicn/transport/interfaces/socket_options_keys.h b/libtransport/src/hicn/transport/interfaces/socket_options_keys.h deleted file mode 100644 index a381312..0000000 --- a/libtransport/src/hicn/transport/interfaces/socket_options_keys.h +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (c) 2017-2019 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 interface { - -typedef enum { - RAAQM = 0, - CBR = 1, - RTC = 2, -} TransportProtocolAlgorithms; - -typedef enum { - INPUT_BUFFER_SIZE = 101, - OUTPUT_BUFFER_SIZE = 102, - NETWORK_NAME = 103, - NAME_SUFFIX = 104, - MAX_INTEREST_RETX = 105, - DATA_PACKET_SIZE = 106, - INTEREST_LIFETIME = 107, - CONTENT_OBJECT_EXPIRY_TIME = 108, - KEY_CONTENT = 110, - 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, - CRYPTO_SUITE = 120, - SIGNER = 121, - VERIFIER = 122, - CERTIFICATE = 123, - VERIFY_SIGNATURE = 124, - STATS_INTERVAL = 125, -} GeneralTransportOptions; - -typedef enum { - SAMPLE_NUMBER = 201, - GAMMA_VALUE = 202, - BETA_VALUE = 203, - DROP_FACTOR = 204, - MINIMUM_DROP_PROBABILITY = 205, - PATH_ID = 206, - RTT_STATS = 207, -} RaaqmTransportOptions; - -typedef enum { - RATE_ESTIMATION_ALPHA = 301, - RATE_ESTIMATION_OBSERVER = 302, - RATE_ESTIMATION_BATCH_PARAMETER = 303, - RATE_ESTIMATION_CHOICE = 304, -} RateEstimationOptions; - -typedef enum { - INTEREST_OUTPUT = 401, - INTEREST_RETRANSMISSION = 402, - INTEREST_EXPIRED = 403, - INTEREST_SATISFIED = 404, - CONTENT_OBJECT_INPUT = 411, - MANIFEST_INPUT = 412, - CONTENT_OBJECT_TO_VERIFY = 413, - VERIFICATION_FAILED = 414, - READ_CALLBACK = 415, - STATS_SUMMARY = 416 -} ConsumerCallbacksOptions; - -typedef enum { - INTEREST_INPUT = 501, - INTEREST_DROP = 502, - INTEREST_PASS = 503, - CACHE_HIT = 506, - CACHE_MISS = 508, - NEW_CONTENT_OBJECT = 509, - CONTENT_OBJECT_SIGN = 513, - CONTENT_OBJECT_READY = 510, - CONTENT_OBJECT_OUTPUT = 511, - CONTENT_PRODUCED = 512, -} ProducerCallbacksOptions; - -typedef enum { OUTPUT_INTERFACE = 601 } DataLinkOptions; - -typedef enum { - VIRTUAL_DOWNLOAD = 701, - USE_CFG_FILE = 702, - STATISTICS -} OtherOptions; - -typedef enum { - SHA_256 = 801, - RSA_256 = 802, -} SignatureType; - -} // namespace interface - -} // end namespace transport diff --git a/libtransport/src/hicn/transport/interfaces/socket_producer.cc b/libtransport/src/hicn/transport/interfaces/socket_producer.cc deleted file mode 100644 index 26a7208..0000000 --- a/libtransport/src/hicn/transport/interfaces/socket_producer.cc +++ /dev/null @@ -1,909 +0,0 @@ -/* - * Copyright (c) 2017-2019 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. - */ - -#include <hicn/transport/interfaces/socket_producer.h> -#include <hicn/transport/utils/signer.h> - -#include <functional> - -namespace transport { - -namespace interface { - -namespace details {} - -typedef std::chrono::time_point<std::chrono::steady_clock> Time; -typedef std::chrono::microseconds TimeDuration; - -ProducerSocket::ProducerSocket() : ProducerSocket(internal_io_service_) {} - -ProducerSocket::ProducerSocket(asio::io_service &io_service) - : io_service_(io_service), - portal_(std::make_shared<Portal>(io_service_)), - data_packet_size_(default_values::content_object_packet_size), - content_object_expiry_time_(default_values::content_object_expiry_time), - output_buffer_(default_values::producer_socket_output_buffer_size), - async_thread_(), - registration_status_(REGISTRATION_NOT_ATTEMPTED), - making_manifest_(false), - hash_algorithm_(HashAlgorithm::SHA_256), - suffix_strategy_(core::NextSegmentCalculationStrategy::INCREMENTAL), - on_interest_input_(VOID_HANDLER), - on_interest_dropped_input_buffer_(VOID_HANDLER), - on_interest_inserted_input_buffer_(VOID_HANDLER), - on_interest_satisfied_output_buffer_(VOID_HANDLER), - on_interest_process_(VOID_HANDLER), - on_new_segment_(VOID_HANDLER), - on_content_object_to_sign_(VOID_HANDLER), - on_content_object_in_output_buffer_(VOID_HANDLER), - on_content_object_output_(VOID_HANDLER), - on_content_object_evicted_from_output_buffer_(VOID_HANDLER), - on_content_produced_(VOID_HANDLER) {} - -ProducerSocket::~ProducerSocket() { - stop(); - if (listening_thread_.joinable()) { - listening_thread_.join(); - } -} - -void ProducerSocket::connect() { - portal_->connect(false); - listening_thread_ = std::thread(std::bind(&ProducerSocket::listen, this)); -} - -void ProducerSocket::serveForever() { - if (listening_thread_.joinable()) { - listening_thread_.join(); - } -} - -void ProducerSocket::stop() { portal_->stopEventsLoop(); } - -void ProducerSocket::registerPrefix(const Prefix &producer_namespace) { - served_namespaces_.push_back(producer_namespace); -} - -void ProducerSocket::listen() { - registration_status_ = REGISTRATION_IN_PROGRESS; - bool first = true; - - for (core::Prefix &producer_namespace : served_namespaces_) { - if (first) { - core::BindConfig bind_config(producer_namespace, 1000); - portal_->bind(bind_config); - portal_->setProducerCallback(this); - first = !first; - } else { - portal_->registerRoute(producer_namespace); - } - } - - portal_->runEventsLoop(); -} - -void ProducerSocket::passContentObjectToCallbacks( - const std::shared_ptr<ContentObject> &content_object) { - if (content_object) { - io_service_.dispatch([this, content_object]() { - if (on_new_segment_) { - on_new_segment_(*this, *content_object); - } - - if (on_content_object_to_sign_) { - on_content_object_to_sign_(*this, *content_object); - } - - if (on_content_object_in_output_buffer_) { - on_content_object_in_output_buffer_(*this, *content_object); - } - }); - - output_buffer_.insert(content_object); - - io_service_.dispatch([this, content_object]() { - if (on_content_object_output_) { - on_content_object_output_(*this, *content_object); - } - }); - - portal_->sendContentObject(*content_object); - } -} - -void ProducerSocket::produce(ContentObject &content_object) { - io_service_.dispatch([this, &content_object]() { - if (on_content_object_in_output_buffer_) { - on_content_object_in_output_buffer_(*this, content_object); - } - }); - - output_buffer_.insert(std::static_pointer_cast<ContentObject>( - content_object.shared_from_this())); - - io_service_.dispatch([this, &content_object]() { - if (on_content_object_output_) { - on_content_object_output_(*this, content_object); - } - }); - - portal_->sendContentObject(content_object); -} - -uint32_t ProducerSocket::produce(Name content_name, - std::unique_ptr<utils::MemBuf> &&buffer, - bool is_last, uint32_t start_offset) { - if (TRANSPORT_EXPECT_FALSE(buffer->length() == 0)) { - return 0; - } - - // Copy the atomic variables to ensure they keep the same value - // during the production - std::size_t data_packet_size = data_packet_size_; - uint32_t content_object_expiry_time = content_object_expiry_time_; - HashAlgorithm hash_algo = hash_algorithm_; - bool making_manifest = making_manifest_; - auto suffix_strategy = utils::SuffixStrategyFactory::getSuffixStrategy( - suffix_strategy_, start_offset); - std::shared_ptr<utils::Signer> signer; - getSocketOption(GeneralTransportOptions::SIGNER, signer); - - auto buffer_size = buffer->length(); - int bytes_segmented = 0; - std::size_t header_size; - std::size_t manifest_header_size = 0; - std::size_t signature_length = 0; - std::uint32_t final_block_number = start_offset; - uint64_t free_space_for_content = 0; - - core::Packet::Format format; - std::shared_ptr<ContentObjectManifest> manifest; - bool is_last_manifest = false; - - // TODO Manifest may still be used for indexing - if (making_manifest && !signer) { - TRANSPORT_LOGD("Making manifests without setting producer identity."); - } - - core::Packet::Format hf_format = core::Packet::Format::HF_UNSPEC; - core::Packet::Format hf_format_ah = core::Packet::Format::HF_UNSPEC; - if (content_name.getType() == HNT_CONTIGUOUS_V4 || - content_name.getType() == HNT_IOV_V4) { - hf_format = core::Packet::Format::HF_INET_TCP; - hf_format_ah = core::Packet::Format::HF_INET_TCP_AH; - } else if (content_name.getType() == HNT_CONTIGUOUS_V6 || - content_name.getType() == HNT_IOV_V6) { - hf_format = core::Packet::Format::HF_INET6_TCP; - hf_format_ah = core::Packet::Format::HF_INET6_TCP_AH; - } else { - throw errors::RuntimeException("Unknown name format."); - } - - format = hf_format; - if (making_manifest) { - manifest_header_size = core::Packet::getHeaderSizeFromFormat( - signer ? hf_format_ah : hf_format, - signer ? signer->getSignatureLength() : 0); - } else if (signer) { - format = hf_format_ah; - signature_length = signer->getSignatureLength(); - } - - header_size = core::Packet::getHeaderSizeFromFormat(format, signature_length); - free_space_for_content = data_packet_size - header_size; - uint32_t number_of_segments = - uint32_t(std::ceil(double(buffer_size) / double(free_space_for_content))); - if (free_space_for_content * number_of_segments < buffer_size) { - number_of_segments++; - } - - // TODO allocate space for all the headers - if (making_manifest) { - uint32_t segment_in_manifest = static_cast<uint32_t>( - std::floor(double(data_packet_size - manifest_header_size - - ContentObjectManifest::getManifestHeaderSize()) / - ContentObjectManifest::getManifestEntrySize()) - - 1.0); - uint32_t number_of_manifests = static_cast<uint32_t>( - std::ceil(float(number_of_segments) / segment_in_manifest)); - final_block_number += number_of_segments + number_of_manifests - 1; - - manifest.reset(ContentObjectManifest::createManifest( - content_name.setSuffix(suffix_strategy->getNextManifestSuffix()), - core::ManifestVersion::VERSION_1, core::ManifestType::INLINE_MANIFEST, - hash_algo, is_last_manifest, content_name, suffix_strategy_, - signer ? signer->getSignatureLength() : 0)); - manifest->setLifetime(content_object_expiry_time); - - if (is_last) { - manifest->setFinalBlockNumber(final_block_number); - } else { - manifest->setFinalBlockNumber(utils::SuffixStrategy::INVALID_SUFFIX); - } - } - - TRANSPORT_LOGD("--------- START PRODUCE ----------"); - for (unsigned int packaged_segments = 0; - packaged_segments < number_of_segments; packaged_segments++) { - if (making_manifest) { - if (manifest->estimateManifestSize(2) > - data_packet_size - manifest_header_size) { - // Send the current manifest - manifest->encode(); - - // If identity set, sign manifest - if (signer) { - signer->sign(*manifest); - } - - passContentObjectToCallbacks(manifest); - TRANSPORT_LOGD("Send manifest %u", manifest->getName().getSuffix()); - - // Send content objects stored in the queue - while (!content_queue_.empty()) { - passContentObjectToCallbacks(content_queue_.front()); - TRANSPORT_LOGD("Send content %u", - content_queue_.front()->getName().getSuffix()); - content_queue_.pop(); - } - - // Create new manifest. The reference to the last manifest has been - // acquired in the passContentObjectToCallbacks function, so we can - // safely release this reference - manifest.reset(ContentObjectManifest::createManifest( - content_name.setSuffix(suffix_strategy->getNextManifestSuffix()), - core::ManifestVersion::VERSION_1, - core::ManifestType::INLINE_MANIFEST, hash_algo, is_last_manifest, - content_name, suffix_strategy_, - signer ? signer->getSignatureLength() : 0)); - - manifest->setLifetime(content_object_expiry_time); - manifest->setFinalBlockNumber( - is_last ? final_block_number - : utils::SuffixStrategy::INVALID_SUFFIX); - } - } - - auto content_suffix = suffix_strategy->getNextContentSuffix(); - auto content_object = std::make_shared<ContentObject>( - content_name.setSuffix(content_suffix), format); - content_object->setLifetime(content_object_expiry_time); - - auto b = buffer->cloneOne(); - b->trimStart(free_space_for_content * packaged_segments); - b->trimEnd(b->length()); - - if (TRANSPORT_EXPECT_FALSE(packaged_segments == number_of_segments - 1)) { - b->append(buffer_size - bytes_segmented); - bytes_segmented += (int)(buffer_size - bytes_segmented); - - if (is_last && making_manifest) { - is_last_manifest = true; - } else if (is_last) { - content_object->setRst(); - } - - } else { - b->append(free_space_for_content); - bytes_segmented += (int)(free_space_for_content); - } - - content_object->appendPayload(std::move(b)); - - if (making_manifest) { - using namespace std::chrono_literals; - utils::CryptoHash hash = content_object->computeDigest(hash_algo); - manifest->addSuffixHash(content_suffix, hash); - content_queue_.push(content_object); - } else { - if (signer) { - signer->sign(*content_object); - } - passContentObjectToCallbacks(content_object); - TRANSPORT_LOGD("Send content %u", content_object->getName().getSuffix()); - } - } - - if (making_manifest) { - if (is_last_manifest) { - manifest->setFinalManifest(is_last_manifest); - } - - manifest->encode(); - if (signer) { - signer->sign(*manifest); - } - - passContentObjectToCallbacks(manifest); - TRANSPORT_LOGD("Send manifest %u", manifest->getName().getSuffix()); - while (!content_queue_.empty()) { - passContentObjectToCallbacks(content_queue_.front()); - TRANSPORT_LOGD("Send content %u", - content_queue_.front()->getName().getSuffix()); - content_queue_.pop(); - } - } - - io_service_.dispatch([this, buffer_size]() { - if (on_content_produced_) { - on_content_produced_(*this, std::make_error_code(std::errc(0)), - buffer_size); - } - }); - - TRANSPORT_LOGD("--------- END PRODUCE ------------"); - return suffix_strategy->getTotalCount(); -} - -void ProducerSocket::asyncProduce(ContentObject &content_object) { - if (!async_thread_.stopped()) { - auto co_ptr = std::static_pointer_cast<ContentObject>( - content_object.shared_from_this()); - async_thread_.add([this, content_object = std::move(co_ptr)]() { - ProducerSocket::produce(*content_object); - }); - } -} - -void ProducerSocket::asyncProduce(const Name &suffix, const uint8_t *buf, - size_t buffer_size, bool is_last, - uint32_t *start_offset) { - if (!async_thread_.stopped()) { - async_thread_.add([this, suffix, buffer = buf, size = buffer_size, is_last, - start_offset]() { - if (start_offset != NULL) { - *start_offset = ProducerSocket::produce(suffix, buffer, size, is_last, - *start_offset); - } else { - ProducerSocket::produce(suffix, buffer, size, is_last, 0); - } - }); - } -} - -void ProducerSocket::asyncProduce(Name content_name, - std::unique_ptr<utils::MemBuf> &&buffer, - bool is_last, uint32_t offset, - uint32_t **last_segment) { - if (!async_thread_.stopped()) { - auto a = buffer.release(); - async_thread_.add([this, content_name, a, is_last, offset, last_segment]() { - auto buf = std::unique_ptr<utils::MemBuf>(a); - if (last_segment != NULL) { - **last_segment = - offset + ProducerSocket::produce(content_name, std::move(buf), - is_last, offset); - } else { - ProducerSocket::produce(content_name, std::move(buf), is_last, offset); - } - }); - } -} - -void ProducerSocket::onInterest(Interest &interest) { - if (on_interest_input_) { - on_interest_input_(*this, interest); - } - - const std::shared_ptr<ContentObject> content_object = - output_buffer_.find(interest); - - if (content_object) { - if (on_interest_satisfied_output_buffer_) { - on_interest_satisfied_output_buffer_(*this, interest); - } - - if (on_content_object_output_) { - on_content_object_output_(*this, *content_object); - } - - portal_->sendContentObject(*content_object); - } else { - if (on_interest_process_) { - on_interest_process_(*this, interest); - } - } -} - -int ProducerSocket::setSocketOption(int socket_option_key, - uint32_t socket_option_value) { - switch (socket_option_key) { - case GeneralTransportOptions::DATA_PACKET_SIZE: - if (socket_option_value < default_values::max_content_object_size && - socket_option_value > 0) { - data_packet_size_ = socket_option_value; - } - break; - - case GeneralTransportOptions::OUTPUT_BUFFER_SIZE: - output_buffer_.setLimit(socket_option_value); - break; - - case GeneralTransportOptions::CONTENT_OBJECT_EXPIRY_TIME: - content_object_expiry_time_ = socket_option_value; - break; - - default: - return SOCKET_OPTION_NOT_SET; - } - - return SOCKET_OPTION_SET; -} - -int ProducerSocket::setSocketOption(int socket_option_key, - std::nullptr_t socket_option_value) { - // Reschedule the function on the io_service to avoid race condition in case - // setSocketOption is called while the io_service is running. - return rescheduleOnIOService( - socket_option_key, socket_option_value, - [this](int socket_option_key, - ProducerContentObjectCallback socket_option_value) -> int { - switch (socket_option_key) { - case ProducerCallbacksOptions::INTEREST_INPUT: - if (socket_option_value == VOID_HANDLER) { - on_interest_input_ = VOID_HANDLER; - break; - } - - case ProducerCallbacksOptions::INTEREST_DROP: - if (socket_option_value == VOID_HANDLER) { - on_interest_dropped_input_buffer_ = VOID_HANDLER; - break; - } - - case ProducerCallbacksOptions::INTEREST_PASS: - if (socket_option_value == VOID_HANDLER) { - on_interest_inserted_input_buffer_ = VOID_HANDLER; - break; - } - - case ProducerCallbacksOptions::CACHE_HIT: - if (socket_option_value == VOID_HANDLER) { - on_interest_satisfied_output_buffer_ = VOID_HANDLER; - break; - } - - case ProducerCallbacksOptions::CACHE_MISS: - if (socket_option_value == VOID_HANDLER) { - on_interest_process_ = VOID_HANDLER; - break; - } - - case ProducerCallbacksOptions::NEW_CONTENT_OBJECT: - if (socket_option_value == VOID_HANDLER) { - on_new_segment_ = VOID_HANDLER; - break; - } - - case ProducerCallbacksOptions::CONTENT_OBJECT_SIGN: - if (socket_option_value == VOID_HANDLER) { - on_content_object_to_sign_ = VOID_HANDLER; - break; - } - - case ProducerCallbacksOptions::CONTENT_OBJECT_READY: - if (socket_option_value == VOID_HANDLER) { - on_content_object_in_output_buffer_ = VOID_HANDLER; - break; - } - - case ProducerCallbacksOptions::CONTENT_OBJECT_OUTPUT: - if (socket_option_value == VOID_HANDLER) { - on_content_object_output_ = VOID_HANDLER; - break; - } - - default: - return SOCKET_OPTION_NOT_SET; - } - - return SOCKET_OPTION_SET; - }); -} - -int ProducerSocket::setSocketOption(int socket_option_key, - bool socket_option_value) { - switch (socket_option_key) { - case GeneralTransportOptions::MAKE_MANIFEST: - making_manifest_ = socket_option_value; - break; - - default: - return SOCKET_OPTION_NOT_SET; - } - - return SOCKET_OPTION_SET; -} - -int ProducerSocket::setSocketOption(int socket_option_key, - Name *socket_option_value) { - return SOCKET_OPTION_NOT_SET; -} - -int ProducerSocket::setSocketOption(int socket_option_key, - std::list<Prefix> socket_option_value) { - switch (socket_option_key) { - case GeneralTransportOptions::NETWORK_NAME: - served_namespaces_ = socket_option_value; - break; - default: - return SOCKET_OPTION_NOT_SET; - } - - return SOCKET_OPTION_SET; -} - -int ProducerSocket::setSocketOption( - int socket_option_key, ProducerContentObjectCallback socket_option_value) { - // Reschedule the function on the io_service to avoid race condition in case - // setSocketOption is called while the io_service is running. - return rescheduleOnIOService( - socket_option_key, socket_option_value, - [this](int socket_option_key, - ProducerContentObjectCallback socket_option_value) -> int { - switch (socket_option_key) { - case ProducerCallbacksOptions::NEW_CONTENT_OBJECT: - on_new_segment_ = socket_option_value; - break; - - case ProducerCallbacksOptions::CONTENT_OBJECT_SIGN: - on_content_object_to_sign_ = socket_option_value; - break; - - case ProducerCallbacksOptions::CONTENT_OBJECT_READY: - on_content_object_in_output_buffer_ = socket_option_value; - break; - - case ProducerCallbacksOptions::CONTENT_OBJECT_OUTPUT: - on_content_object_output_ = socket_option_value; - break; - - default: - return SOCKET_OPTION_NOT_SET; - } - - return SOCKET_OPTION_SET; - }); -} - -int ProducerSocket::setSocketOption( - int socket_option_key, ProducerInterestCallback socket_option_value) { - // Reschedule the function on the io_service to avoid race condition in case - // setSocketOption is called while the io_service is running. - return rescheduleOnIOService( - socket_option_key, socket_option_value, - [this](int socket_option_key, - ProducerInterestCallback socket_option_value) -> int { - switch (socket_option_key) { - case ProducerCallbacksOptions::INTEREST_INPUT: - on_interest_input_ = socket_option_value; - break; - - case ProducerCallbacksOptions::INTEREST_DROP: - on_interest_dropped_input_buffer_ = socket_option_value; - break; - - case ProducerCallbacksOptions::INTEREST_PASS: - on_interest_inserted_input_buffer_ = socket_option_value; - break; - - case ProducerCallbacksOptions::CACHE_HIT: - on_interest_satisfied_output_buffer_ = socket_option_value; - break; - - case ProducerCallbacksOptions::CACHE_MISS: - on_interest_process_ = socket_option_value; - break; - - default: - return SOCKET_OPTION_NOT_SET; - } - - return SOCKET_OPTION_SET; - }); -} - -int ProducerSocket::setSocketOption( - int socket_option_key, ProducerContentCallback socket_option_value) { - // Reschedule the function on the io_service to avoid race condition in case - // setSocketOption is called while the io_service is running. - return rescheduleOnIOService( - socket_option_key, socket_option_value, - [this](int socket_option_key, - ProducerContentCallback socket_option_value) -> int { - switch (socket_option_key) { - case ProducerCallbacksOptions::CONTENT_PRODUCED: - on_content_produced_ = socket_option_value; - break; - - default: - return SOCKET_OPTION_NOT_SET; - } - - return SOCKET_OPTION_SET; - }); -} - -int ProducerSocket::setSocketOption(int socket_option_key, - HashAlgorithm socket_option_value) { - switch (socket_option_key) { - case GeneralTransportOptions::HASH_ALGORITHM: - hash_algorithm_ = socket_option_value; - break; - default: - return SOCKET_OPTION_NOT_SET; - } - - return SOCKET_OPTION_SET; -} - -int ProducerSocket::setSocketOption(int socket_option_key, - utils::CryptoSuite socket_option_value) { - switch (socket_option_key) { - case GeneralTransportOptions::CRYPTO_SUITE: - crypto_suite_ = socket_option_value; - break; - default: - return SOCKET_OPTION_NOT_SET; - } - - return SOCKET_OPTION_SET; -} - -int ProducerSocket::setSocketOption( - int socket_option_key, - const std::shared_ptr<utils::Signer> &socket_option_value) { - switch (socket_option_key) { - case GeneralTransportOptions::SIGNER: { - utils::SpinLock::Acquire locked(signer_lock_); - signer_.reset(); - signer_ = socket_option_value; - } break; - default: - return SOCKET_OPTION_NOT_SET; - } - - return SOCKET_OPTION_SET; -} - -int ProducerSocket::setSocketOption(int socket_option_key, - const std::string &socket_option_value) { - switch (socket_option_key) { - case DataLinkOptions::OUTPUT_INTERFACE: - output_interface_ = socket_option_value; - portal_->setOutputInterface(output_interface_); - break; - default: - return SOCKET_OPTION_NOT_SET; - } - - return SOCKET_OPTION_SET; -} - -int ProducerSocket::getSocketOption(int socket_option_key, - uint32_t &socket_option_value) { - switch (socket_option_key) { - case GeneralTransportOptions::OUTPUT_BUFFER_SIZE: - socket_option_value = (uint32_t)output_buffer_.getLimit(); - break; - - case GeneralTransportOptions::DATA_PACKET_SIZE: - socket_option_value = (uint32_t)data_packet_size_; - break; - - case GeneralTransportOptions::CONTENT_OBJECT_EXPIRY_TIME: - socket_option_value = content_object_expiry_time_; - break; - - default: - return SOCKET_OPTION_NOT_SET; - } - - return SOCKET_OPTION_GET; -} - -int ProducerSocket::getSocketOption(int socket_option_key, - bool &socket_option_value) { - switch (socket_option_key) { - case GeneralTransportOptions::MAKE_MANIFEST: - socket_option_value = making_manifest_; - break; - - default: - return SOCKET_OPTION_NOT_GET; - } - - return SOCKET_OPTION_GET; -} - -int ProducerSocket::getSocketOption(int socket_option_key, - std::list<Prefix> &socket_option_value) { - switch (socket_option_key) { - case GeneralTransportOptions::NETWORK_NAME: - socket_option_value = served_namespaces_; - break; - - default: - return SOCKET_OPTION_NOT_GET; - } - - return SOCKET_OPTION_GET; -} - -int ProducerSocket::getSocketOption( - int socket_option_key, - ProducerContentObjectCallback **socket_option_value) { - // Reschedule the function on the io_service to avoid race condition in case - // setSocketOption is called while the io_service is running. - return rescheduleOnIOService( - socket_option_key, socket_option_value, - [this](int socket_option_key, - ProducerContentObjectCallback **socket_option_value) -> int { - switch (socket_option_key) { - case ProducerCallbacksOptions::NEW_CONTENT_OBJECT: - *socket_option_value = &on_new_segment_; - break; - - case ProducerCallbacksOptions::CONTENT_OBJECT_SIGN: - *socket_option_value = &on_content_object_to_sign_; - break; - - case ProducerCallbacksOptions::CONTENT_OBJECT_READY: - *socket_option_value = &on_content_object_in_output_buffer_; - break; - - case ProducerCallbacksOptions::CONTENT_OBJECT_OUTPUT: - *socket_option_value = &on_content_object_output_; - break; - - default: - return SOCKET_OPTION_NOT_GET; - } - - return SOCKET_OPTION_GET; - }); -} - -int ProducerSocket::getSocketOption( - int socket_option_key, ProducerContentCallback **socket_option_value) { - // Reschedule the function on the io_service to avoid race condition in case - // setSocketOption is called while the io_service is running. - return rescheduleOnIOService( - socket_option_key, socket_option_value, - [this](int socket_option_key, - ProducerContentCallback **socket_option_value) -> int { - switch (socket_option_key) { - case ProducerCallbacksOptions::CONTENT_PRODUCED: - *socket_option_value = &on_content_produced_; - break; - - default: - return SOCKET_OPTION_NOT_GET; - } - - return SOCKET_OPTION_GET; - }); -} - -int ProducerSocket::getSocketOption( - int socket_option_key, ProducerInterestCallback **socket_option_value) { - // Reschedule the function on the io_service to avoid race condition in case - // setSocketOption is called while the io_service is running. - return rescheduleOnIOService( - socket_option_key, socket_option_value, - [this](int socket_option_key, - ProducerInterestCallback **socket_option_value) -> int { - switch (socket_option_key) { - case ProducerCallbacksOptions::INTEREST_INPUT: - *socket_option_value = &on_interest_input_; - break; - - case ProducerCallbacksOptions::INTEREST_DROP: - *socket_option_value = &on_interest_dropped_input_buffer_; - break; - - case ProducerCallbacksOptions::INTEREST_PASS: - *socket_option_value = &on_interest_inserted_input_buffer_; - break; - - case CACHE_HIT: - *socket_option_value = &on_interest_satisfied_output_buffer_; - break; - - case CACHE_MISS: - *socket_option_value = &on_interest_process_; - break; - - default: - return SOCKET_OPTION_NOT_GET; - } - - return SOCKET_OPTION_GET; - }); -} - -int ProducerSocket::getSocketOption( - int socket_option_key, std::shared_ptr<Portal> &socket_option_value) { - switch (socket_option_key) { - case PORTAL: - socket_option_value = portal_; - break; - default: - return SOCKET_OPTION_NOT_GET; - ; - } - - return SOCKET_OPTION_GET; -} - -int ProducerSocket::getSocketOption(int socket_option_key, - HashAlgorithm &socket_option_value) { - switch (socket_option_key) { - case GeneralTransportOptions::HASH_ALGORITHM: - socket_option_value = hash_algorithm_; - break; - default: - return SOCKET_OPTION_NOT_GET; - } - - return SOCKET_OPTION_GET; -} - -int ProducerSocket::getSocketOption(int socket_option_key, - utils::CryptoSuite &socket_option_value) { - switch (socket_option_key) { - case GeneralTransportOptions::HASH_ALGORITHM: - socket_option_value = crypto_suite_; - break; - default: - return SOCKET_OPTION_NOT_GET; - } - - return SOCKET_OPTION_GET; -} - -int ProducerSocket::getSocketOption( - int socket_option_key, - std::shared_ptr<utils::Signer> &socket_option_value) { - switch (socket_option_key) { - case GeneralTransportOptions::SIGNER: { - utils::SpinLock::Acquire locked(signer_lock_); - socket_option_value = signer_; - } break; - default: - return SOCKET_OPTION_NOT_GET; - } - - return SOCKET_OPTION_GET; -} - -int ProducerSocket::getSocketOption(int socket_option_key, - std::string &socket_option_value) { - switch (socket_option_key) { - case DataLinkOptions::OUTPUT_INTERFACE: - socket_option_value = output_interface_; - break; - default: - return SOCKET_OPTION_NOT_GET; - } - - return SOCKET_OPTION_GET; -} - -asio::io_service &ProducerSocket::getIoService() { return io_service_; } - -} // namespace interface - -} // end namespace transport diff --git a/libtransport/src/hicn/transport/interfaces/socket_producer.h b/libtransport/src/hicn/transport/interfaces/socket_producer.h deleted file mode 100644 index 5f360f2..0000000 --- a/libtransport/src/hicn/transport/interfaces/socket_producer.h +++ /dev/null @@ -1,295 +0,0 @@ -/* - * Copyright (c) 2017-2019 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/interfaces/socket.h> -#include <hicn/transport/utils/content_store.h> -#include <hicn/transport/utils/event_thread.h> -#include <hicn/transport/utils/signer.h> -#include <hicn/transport/utils/suffix_strategy.h> - -#include <atomic> -#include <cmath> -#include <condition_variable> -#include <mutex> -#include <queue> -#include <thread> - -#define REGISTRATION_NOT_ATTEMPTED 0 -#define REGISTRATION_SUCCESS 1 -#define REGISTRATION_FAILURE 2 -#define REGISTRATION_IN_PROGRESS 3 - -namespace transport { - -namespace interface { - -using namespace core; - -class ProducerSocket : public Socket<BasePortal>, - public BasePortal::ProducerCallback { - public: - explicit ProducerSocket(); - explicit ProducerSocket(asio::io_service &io_service); - - ~ProducerSocket(); - - void connect() override; - - bool isRunning() override { return !io_service_.stopped(); }; - - virtual uint32_t produce(Name content_name, const uint8_t *buffer, - size_t buffer_size, bool is_last = true, - uint32_t start_offset = 0) { - return ProducerSocket::produce( - content_name, utils::MemBuf::copyBuffer(buffer, buffer_size), is_last, - start_offset); - } - - virtual uint32_t produce(Name content_name, - std::unique_ptr<utils::MemBuf> &&buffer, - bool is_last = true, uint32_t start_offset = 0); - - virtual void produce(ContentObject &content_object); - - virtual void produce(const uint8_t *buffer, size_t buffer_size) { - produce(utils::MemBuf::copyBuffer(buffer, buffer_size)); - } - - virtual void produce(std::unique_ptr<utils::MemBuf> &&buffer) { - // This API is meant to be used just with the RTC producer. - // Here it cannot be used since no name for the content is specified. - throw errors::NotImplementedException(); - } - - virtual void asyncProduce(const Name &suffix, const uint8_t *buf, - size_t buffer_size, bool is_last = true, - uint32_t *start_offset = nullptr); - - void asyncProduce(const Name &suffix); - - virtual void asyncProduce(Name content_name, - std::unique_ptr<utils::MemBuf> &&buffer, - bool is_last, uint32_t offset, - uint32_t **last_segment = nullptr); - - virtual void asyncProduce(ContentObject &content_object); - - virtual void registerPrefix(const Prefix &producer_namespace); - - void serveForever(); - - void stop(); - - asio::io_service &getIoService() override; - - virtual void onInterest(Interest &interest); - - virtual void onInterest(Interest::Ptr &&interest) override { - onInterest(*interest); - }; - - virtual int setSocketOption(int socket_option_key, - uint32_t socket_option_value); - - virtual int setSocketOption(int socket_option_key, - std::nullptr_t socket_option_value); - - virtual int setSocketOption(int socket_option_key, bool socket_option_value); - - virtual int setSocketOption(int socket_option_key, Name *socket_option_value); - - virtual int setSocketOption(int socket_option_key, - std::list<Prefix> socket_option_value); - - virtual int setSocketOption( - int socket_option_key, ProducerContentObjectCallback socket_option_value); - - virtual int setSocketOption(int socket_option_key, - ProducerInterestCallback socket_option_value); - - virtual int setSocketOption(int socket_option_key, - ProducerContentCallback socket_option_value); - - virtual int setSocketOption(int socket_option_key, - HashAlgorithm socket_option_value); - - virtual int setSocketOption(int socket_option_key, - utils::CryptoSuite socket_option_value); - - virtual int setSocketOption( - int socket_option_key, - const std::shared_ptr<utils::Signer> &socket_option_value); - - virtual int setSocketOption(int socket_option_key, - const std::string &socket_option_value); - - virtual int getSocketOption(int socket_option_key, - uint32_t &socket_option_value); - - virtual int getSocketOption(int socket_option_key, bool &socket_option_value); - - virtual int getSocketOption(int socket_option_key, - std::list<Prefix> &socket_option_value); - - virtual int getSocketOption( - int socket_option_key, - ProducerContentObjectCallback **socket_option_value); - - virtual int getSocketOption(int socket_option_key, - ProducerContentCallback **socket_option_value); - - virtual int getSocketOption(int socket_option_key, - ProducerInterestCallback **socket_option_value); - - virtual int getSocketOption(int socket_option_key, - std::shared_ptr<Portal> &socket_option_value); - - virtual int getSocketOption(int socket_option_key, - HashAlgorithm &socket_option_value); - - virtual int getSocketOption(int socket_option_key, - utils::CryptoSuite &socket_option_value); - - virtual int getSocketOption( - int socket_option_key, - std::shared_ptr<utils::Signer> &socket_option_value); - - virtual int getSocketOption(int socket_option_key, - std::string &socket_option_value); - - // If the thread calling lambda_func is not the same of io_service, this - // function reschedule the function on it - template <typename Lambda, typename arg2> - int rescheduleOnIOService(int socket_option_key, arg2 socket_option_value, - Lambda lambda_func) { - // To enforce type check - std::function<int(int, arg2)> func = lambda_func; - int result = SOCKET_OPTION_SET; - if (listening_thread_.joinable() && - std::this_thread::get_id() != listening_thread_.get_id()) { - std::mutex mtx; - /* Condition variable for the wait */ - std::condition_variable cv; - bool done = false; - io_service_.dispatch([&socket_option_key, &socket_option_value, &mtx, &cv, - &result, &done, &func]() { - std::unique_lock<std::mutex> lck(mtx); - done = true; - result = func(socket_option_key, socket_option_value); - cv.notify_all(); - }); - std::unique_lock<std::mutex> lck(mtx); - if (!done) { - cv.wait(lck); - } - } else { - result = func(socket_option_key, socket_option_value); - } - - return result; - } - - template <typename Lambda, typename arg2> - int rescheduleOnIOServiceWithReference(int socket_option_key, - arg2 &socket_option_value, - Lambda lambda_func) { - // To enforce type check - std::function<int(int, arg2 &)> func = lambda_func; - int result = SOCKET_OPTION_SET; - if (listening_thread_.joinable() && - std::this_thread::get_id() != this->listening_thread_.get_id()) { - std::mutex mtx; - /* Condition variable for the wait */ - std::condition_variable cv; - - bool done = false; - io_service_.dispatch([&socket_option_key, &socket_option_value, &mtx, &cv, - &result, &done, &func]() { - std::unique_lock<std::mutex> lck(mtx); - done = true; - result = func(socket_option_key, socket_option_value); - cv.notify_all(); - }); - std::unique_lock<std::mutex> lck(mtx); - if (!done) { - cv.wait(lck); - } - } else { - result = func(socket_option_key, socket_option_value); - } - - return result; - } - // Threads - protected: - std::thread listening_thread_; - asio::io_service internal_io_service_; - asio::io_service &io_service_; - std::shared_ptr<Portal> portal_; - std::atomic<size_t> data_packet_size_; - std::list<Prefix> - served_namespaces_; // No need to be threadsafe, this is always modified - // by the application thread - std::atomic<uint32_t> content_object_expiry_time_; - - // buffers - // ContentStore is thread-safe - utils::ContentStore output_buffer_; - - utils::EventThread async_thread_; - int registration_status_; - - std::atomic<bool> making_manifest_; - - // map for storing sequence numbers for several calls of the publish - // function - std::unordered_map<Name, std::unordered_map<int, uint32_t>> seq_number_map_; - - std::atomic<HashAlgorithm> hash_algorithm_; - std::atomic<utils::CryptoSuite> crypto_suite_; - utils::SpinLock signer_lock_; - std::shared_ptr<utils::Signer> signer_; - core::NextSegmentCalculationStrategy suffix_strategy_; - - // While manifests are being built, contents are stored in a queue - std::queue<std::shared_ptr<ContentObject>> content_queue_; - - // callbacks - ProducerInterestCallback on_interest_input_; - ProducerInterestCallback on_interest_dropped_input_buffer_; - ProducerInterestCallback on_interest_inserted_input_buffer_; - ProducerInterestCallback on_interest_satisfied_output_buffer_; - ProducerInterestCallback on_interest_process_; - - ProducerContentObjectCallback on_new_segment_; - ProducerContentObjectCallback on_content_object_to_sign_; - ProducerContentObjectCallback on_content_object_in_output_buffer_; - ProducerContentObjectCallback on_content_object_output_; - ProducerContentObjectCallback on_content_object_evicted_from_output_buffer_; - - ProducerContentCallback on_content_produced_; - - private: - void listen(); - - void passContentObjectToCallbacks( - const std::shared_ptr<ContentObject> &content_object); -}; - -} // namespace interface - -} // namespace transport diff --git a/libtransport/src/hicn/transport/interfaces/tls_rtc_socket_producer.cc b/libtransport/src/hicn/transport/interfaces/tls_rtc_socket_producer.cc deleted file mode 100644 index 27c1e54..0000000 --- a/libtransport/src/hicn/transport/interfaces/tls_rtc_socket_producer.cc +++ /dev/null @@ -1,178 +0,0 @@ -#include <hicn/transport/core/interest.h> -#include <hicn/transport/interfaces/p2psecure_socket_producer.h> -#include <hicn/transport/interfaces/tls_rtc_socket_producer.h> - -#include <openssl/bio.h> -#include <openssl/rand.h> -#include <openssl/ssl.h> - -namespace transport { - -namespace interface { -int TLSRTCProducerSocket::read(BIO *b, char *buf, size_t size, - size_t *readbytes) { - int ret; - - if (size > INT_MAX) size = INT_MAX; - - ret = TLSRTCProducerSocket::readOld(b, buf, (int)size); - - if (ret <= 0) { - *readbytes = 0; - return ret; - } - - *readbytes = (size_t)ret; - - return 1; -} - -int TLSRTCProducerSocket::readOld(BIO *b, char *buf, int size) { - TLSRTCProducerSocket *socket; - socket = (TLSRTCProducerSocket *)BIO_get_data(b); - - std::unique_lock<std::mutex> lck(socket->mtx_); - if (!socket->something_to_read_) { - (socket->cv_).wait(lck); - } - - utils::MemBuf *membuf = socket->packet_->next(); - int size_to_read; - - if ((int)membuf->length() > size) { - size_to_read = size; - } else { - size_to_read = membuf->length(); - socket->something_to_read_ = false; - } - - std::memcpy(buf, membuf->data(), size_to_read); - membuf->trimStart(size_to_read); - - return size_to_read; -} - -int TLSRTCProducerSocket::write(BIO *b, const char *buf, size_t size, - size_t *written) { - int ret; - - if (size > INT_MAX) size = INT_MAX; - - ret = TLSRTCProducerSocket::writeOld(b, buf, (int)size); - - if (ret <= 0) { - *written = 0; - return ret; - } - - *written = (size_t)ret; - - return 1; -} - -int TLSRTCProducerSocket::writeOld(BIO *b, const char *buf, int num) { - TLSRTCProducerSocket *socket; - socket = (TLSRTCProducerSocket *)BIO_get_data(b); - - if ((SSL_in_before(socket->ssl_) || SSL_in_init(socket->ssl_)) && - socket->first_) { - socket->tls_chunks_--; - bool making_manifest = socket->parent_->making_manifest_; - socket->parent_->setSocketOption(GeneralTransportOptions::MAKE_MANIFEST, - false); - socket->parent_->ProducerSocket::produce( - socket->name_, (const uint8_t *)buf, num, socket->tls_chunks_ == 0, 0); - socket->parent_->setSocketOption(GeneralTransportOptions::MAKE_MANIFEST, - making_manifest); - socket->first_ = false; - - } else { - std::unique_ptr<utils::MemBuf> mbuf = - utils::MemBuf::copyBuffer(buf, (std::size_t)num, 0, 0); - auto a = mbuf.release(); - socket->async_thread_.add([socket = socket, a]() { - socket->to_call_oncontentproduced_--; - auto mbuf = std::unique_ptr<utils::MemBuf>(a); - socket->RTCProducerSocket::produce(std::move(mbuf)); - ProducerContentCallback on_content_produced_application; - socket->getSocketOption(ProducerCallbacksOptions::CONTENT_PRODUCED, - on_content_produced_application); - if (socket->to_call_oncontentproduced_ == 0 && - on_content_produced_application) { - on_content_produced_application(*socket, std::error_code(), 0); - } - }); - } - - return num; -} - -TLSRTCProducerSocket::TLSRTCProducerSocket(P2PSecureProducerSocket *parent, - const Name &handshake_name) - : RTCProducerSocket(), TLSProducerSocket(parent, handshake_name) { - BIO_METHOD *bio_meth = - BIO_meth_new(BIO_TYPE_ACCEPT, "secure rtc producer socket"); - BIO_meth_set_read(bio_meth, TLSRTCProducerSocket::readOld); - BIO_meth_set_write(bio_meth, TLSRTCProducerSocket::writeOld); - BIO_meth_set_ctrl(bio_meth, TLSProducerSocket::ctrl); - BIO *bio = BIO_new(bio_meth); - BIO_set_init(bio, 1); - BIO_set_data(bio, this); - SSL_set_bio(ssl_, bio, bio); -} - -void TLSRTCProducerSocket::accept() { - if (SSL_in_before(ssl_) || SSL_in_init(ssl_)) { - tls_chunks_ = 1; - int result = SSL_accept(ssl_); - if (result != 1) - throw errors::RuntimeException("Unable to perform client handshake"); - } - - TRANSPORT_LOGD("Handshake performed!"); - parent_->list_secure_rtc_producers.push_front( - std::move(parent_->map_secure_rtc_producers[handshake_name_])); - parent_->map_secure_rtc_producers.erase(handshake_name_); - - ProducerInterestCallback on_interest_process_decrypted; - getSocketOption(ProducerCallbacksOptions::CACHE_MISS, - on_interest_process_decrypted); - - if (on_interest_process_decrypted) { - Interest inter(std::move(packet_)); - on_interest_process_decrypted(*this, inter); - } - - parent_->cv_.notify_one(); -} - -int TLSRTCProducerSocket::async_accept() { - if (!async_thread_.stopped()) { - async_thread_.add([this]() { this->TLSRTCProducerSocket::accept(); }); - } else { - throw errors::RuntimeException( - "Async thread not running, impossible to perform handshake"); - } - - return 1; -} - -void TLSRTCProducerSocket::produce(std::unique_ptr<utils::MemBuf> &&buffer) { - if (SSL_in_before(ssl_) || SSL_in_init(ssl_)) { - throw errors::RuntimeException( - "New handshake on the same P2P secure producer socket not supported"); - } - - size_t buf_size = buffer->length(); - tls_chunks_ = ceil((float)buf_size / (float)SSL3_RT_MAX_PLAIN_LENGTH); - to_call_oncontentproduced_ = tls_chunks_; - - SSL_write(ssl_, buffer->data(), buf_size); - BIO *wbio = SSL_get_wbio(ssl_); - int i = BIO_flush(wbio); - (void)i; // To shut up gcc 5 -} - -} // namespace interface - -} // namespace transport diff --git a/libtransport/src/hicn/transport/interfaces/tls_rtc_socket_producer.h b/libtransport/src/hicn/transport/interfaces/tls_rtc_socket_producer.h deleted file mode 100644 index 16125f8..0000000 --- a/libtransport/src/hicn/transport/interfaces/tls_rtc_socket_producer.h +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2017-2019 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/interfaces/rtc_socket_producer.h> -#include <hicn/transport/interfaces/tls_socket_producer.h> - -namespace transport { - -namespace interface { - -class P2PSecureProducerSocket; - -class TLSRTCProducerSocket : public RTCProducerSocket, - public TLSProducerSocket { - friend class P2PSecureProducerSocket; - - public: - explicit TLSRTCProducerSocket(P2PSecureProducerSocket *parent, - const Name &handshake_name); - - ~TLSRTCProducerSocket() = default; - - void produce(std::unique_ptr<utils::MemBuf> &&buffer) override; - - void accept() override; - - int async_accept() override; - - using TLSProducerSocket::produce; - using TLSProducerSocket::onInterest; - - protected: - static int read(BIO *b, char *buf, size_t size, size_t *readbytes); - - static int readOld(BIO *h, char *buf, int size); - - static int write(BIO *b, const char *buf, size_t size, size_t *written); - - static int writeOld(BIO *h, const char *buf, int num); -}; - -} // namespace interface - -} // end namespace transport diff --git a/libtransport/src/hicn/transport/interfaces/tls_socket_consumer.cc b/libtransport/src/hicn/transport/interfaces/tls_socket_consumer.cc deleted file mode 100644 index 58b3c1d..0000000 --- a/libtransport/src/hicn/transport/interfaces/tls_socket_consumer.cc +++ /dev/null @@ -1,364 +0,0 @@ -#include <hicn/transport/interfaces/tls_socket_consumer.h> -#include <openssl/bio.h> -#include <openssl/ssl.h> -#include <openssl/tls1.h> - -#include <random> - -namespace transport { - -namespace interface { - -void TLSConsumerSocket::setInterestPayload(ConsumerSocket &c, - const core::Interest &interest) { - Interest &int2 = const_cast<Interest &>(interest); - random_suffix_ = int2.getName().getSuffix(); - - if (payload_ != NULL) int2.appendPayload(std::move(payload_)); -} - -/* Return the number of read bytes in the return param */ -int readOldTLS(BIO *b, char *buf, int size) { - if (size < 0) return size; - - TLSConsumerSocket *socket; - socket = (TLSConsumerSocket *)BIO_get_data(b); - - std::unique_lock<std::mutex> lck(socket->mtx_); - - if (!socket->something_to_read_) { - if (!socket->transport_protocol_->isRunning()) { - socket->network_name_.setSuffix(socket->random_suffix_); - socket->ConsumerSocket::asyncConsume(socket->network_name_); - } - if (!socket->something_to_read_) socket->cv_.wait(lck); - } - - size_t size_to_read, read; - size_t chain_size = socket->head_->length(); - if (socket->head_->isChained()) - chain_size = socket->head_->computeChainDataLength(); - - if (chain_size > (size_t)size) { - read = size_to_read = (size_t)size; - } else { - read = size_to_read = chain_size; - socket->something_to_read_ = false; - } - - while (size_to_read) { - if (socket->head_->length() < size_to_read) { - std::memcpy(buf, socket->head_->data(), socket->head_->length()); - size_to_read -= socket->head_->length(); - buf += socket->head_->length(); - socket->head_ = socket->head_->pop(); - } else { - std::memcpy(buf, socket->head_->data(), size_to_read); - socket->head_->trimStart(size_to_read); - size_to_read = 0; - } - } - - return read; -} - -/* Return the number of read bytes in readbytes */ -int readTLS(BIO *b, char *buf, size_t size, size_t *readbytes) { - int ret; - - if (size > INT_MAX) size = INT_MAX; - - ret = transport::interface::readOldTLS(b, buf, (int)size); - - if (ret <= 0) { - *readbytes = 0; - return ret; - } - - *readbytes = (size_t)ret; - - return 1; -} - -/* Return the number of written bytes in the return param */ -int writeOldTLS(BIO *b, const char *buf, int num) { - TLSConsumerSocket *socket; - socket = (TLSConsumerSocket *)BIO_get_data(b); - - socket->payload_ = utils::MemBuf::copyBuffer(buf, num); - socket->ConsumerSocket::setSocketOption( - ConsumerCallbacksOptions::INTEREST_OUTPUT, - (ConsumerInterestCallback)std::bind( - &TLSConsumerSocket::setInterestPayload, socket, std::placeholders::_1, - std::placeholders::_2)); - - return num; -} - -/* Return the number of written bytes in written */ -int writeTLS(BIO *b, const char *buf, size_t size, size_t *written) { - int ret; - - if (size > INT_MAX) size = INT_MAX; - - ret = transport::interface::writeOldTLS(b, buf, (int)size); - - if (ret <= 0) { - *written = 0; - return ret; - } - - *written = (size_t)ret; - - return 1; -} - -long ctrlTLS(BIO *b, int cmd, long num, void *ptr) { return 1; } - -TLSConsumerSocket::TLSConsumerSocket(int protocol, SSL *ssl) - : ConsumerSocket(protocol), - name_(), - buf_pool_(), - decrypted_content_(), - payload_(), - head_(), - something_to_read_(false), - content_downloaded_(false), - random_suffix_(), - secure_prefix_(), - producer_namespace_(), - read_callback_decrypted_(), - mtx_(), - cv_(), - async_downloader_tls_() { - /* Create the (d)TLS state */ - const SSL_METHOD *meth = TLS_client_method(); - ctx_ = SSL_CTX_new(meth); - - int result = - SSL_CTX_set_ciphersuites(ctx_, - "TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_" - "SHA256:TLS_AES_128_GCM_SHA256"); - if (result != 1) { - throw errors::RuntimeException( - "Unable to set cipher list on TLS subsystem. Aborting."); - } - - SSL_CTX_set_min_proto_version(ctx_, TLS1_3_VERSION); - SSL_CTX_set_max_proto_version(ctx_, TLS1_3_VERSION); - SSL_CTX_set_verify(ctx_, SSL_VERIFY_NONE, NULL); - SSL_CTX_set_ssl_version(ctx_, meth); - - ssl_ = ssl; - - BIO_METHOD *bio_meth = - BIO_meth_new(BIO_TYPE_CONNECT, "secure consumer socket"); - BIO_meth_set_read(bio_meth, transport::interface::readOldTLS); - BIO_meth_set_write(bio_meth, transport::interface::writeOldTLS); - BIO_meth_set_ctrl(bio_meth, transport::interface::ctrlTLS); - BIO *bio = BIO_new(bio_meth); - BIO_set_init(bio, 1); - BIO_set_data(bio, this); - SSL_set_bio(ssl_, bio, bio); - - ConsumerSocket::getSocketOption(MAX_WINDOW_SIZE, old_max_win_); - ConsumerSocket::setSocketOption(MAX_WINDOW_SIZE, (double)1.0); - - ConsumerSocket::getSocketOption(CURRENT_WINDOW_SIZE, old_current_win_); - ConsumerSocket::setSocketOption(CURRENT_WINDOW_SIZE, (double)1.0); - - std::default_random_engine generator; - std::uniform_int_distribution<int> distribution( - 1, std::numeric_limits<uint32_t>::max()); - random_suffix_ = 0; - - this->ConsumerSocket::setSocketOption(ConsumerCallbacksOptions::READ_CALLBACK, - this); -}; - -int TLSConsumerSocket::consume(const Name &name, - std::unique_ptr<utils::MemBuf> &&buffer) { - this->payload_ = std::move(buffer); - - this->ConsumerSocket::setSocketOption( - ConsumerCallbacksOptions::INTEREST_OUTPUT, - (ConsumerInterestCallback)std::bind( - &TLSConsumerSocket::setInterestPayload, this, std::placeholders::_1, - std::placeholders::_2)); - - return consume(name); -} - -int TLSConsumerSocket::consume(const Name &name) { - if (transport_protocol_->isRunning()) { - return CONSUMER_BUSY; - } - - if ((SSL_in_before(this->ssl_) || SSL_in_init(this->ssl_))) { - throw errors::RuntimeException("Handshake not performed"); - } - - return download_content(name); -} - -int TLSConsumerSocket::download_content(const Name &name) { - network_name_ = name; - network_name_.setSuffix(0); - something_to_read_ = false; - content_downloaded_ = false; - - decrypted_content_ = utils::MemBuf::createCombined(SSL3_RT_MAX_PLAIN_LENGTH); - uint8_t *buf = decrypted_content_->writableData(); - size_t size = 0; - int result = -1; - - while (!content_downloaded_ || something_to_read_) { - if (decrypted_content_->tailroom() < SSL3_RT_MAX_PLAIN_LENGTH) { - decrypted_content_->appendChain( - utils::MemBuf::createCombined(SSL3_RT_MAX_PLAIN_LENGTH)); - // decrypted_content_->computeChainDataLength(); - buf = decrypted_content_->prev()->writableData(); - } else { - buf = decrypted_content_->writableTail(); - } - - result = SSL_read(this->ssl_, buf, SSL3_RT_MAX_PLAIN_LENGTH); - - /* SSL_read returns the data only if there were SSL3_RT_MAX_PLAIN_LENGTH of - * the data has been fully downloaded */ - - /* ASSERT((result < SSL3_RT_MAX_PLAIN_LENGTH && content_downloaded_) || */ - /* result == SSL3_RT_MAX_PLAIN_LENGTH); */ - - if (result >= 0) { - size += result; - decrypted_content_->prepend(result); - } else - throw errors::RuntimeException("Unable to download content"); - - if (size >= read_callback_decrypted_->maxBufferSize()) { - if (read_callback_decrypted_->isBufferMovable()) { - // No need to perform an additional copy. The whole buffer will be - // tranferred to the application. - - read_callback_decrypted_->readBufferAvailable( - std::move(decrypted_content_)); - decrypted_content_ = utils::MemBuf::create(SSL3_RT_MAX_PLAIN_LENGTH); - } else { - // The buffer will be copied into the application-provided buffer - uint8_t *buffer; - std::size_t length; - std::size_t total_length = decrypted_content_->length(); - - while (decrypted_content_->length()) { - buffer = nullptr; - length = 0; - read_callback_decrypted_->getReadBuffer(&buffer, &length); - - if (!buffer || !length) { - throw errors::RuntimeException( - "Invalid buffer provided by the application."); - } - - auto to_copy = std::min(decrypted_content_->length(), length); - std::memcpy(buffer, decrypted_content_->data(), to_copy); - decrypted_content_->trimStart(to_copy); - } - - read_callback_decrypted_->readDataAvailable(total_length); - decrypted_content_->clear(); - } - } - } - - read_callback_decrypted_->readSuccess(size); - - return CONSUMER_FINISHED; -} - -int TLSConsumerSocket::asyncConsume(const Name &name, - std::unique_ptr<utils::MemBuf> &&buffer) { - this->payload_ = std::move(buffer); - - this->ConsumerSocket::setSocketOption( - ConsumerCallbacksOptions::INTEREST_OUTPUT, - (ConsumerInterestCallback)std::bind( - &TLSConsumerSocket::setInterestPayload, this, std::placeholders::_1, - std::placeholders::_2)); - - return asyncConsume(name); -} - -int TLSConsumerSocket::asyncConsume(const Name &name) { - if ((SSL_in_before(this->ssl_) || SSL_in_init(this->ssl_))) { - throw errors::RuntimeException("Handshake not performed"); - } - - if (!async_downloader_tls_.stopped()) { - async_downloader_tls_.add([this, name]() { - is_async_ = true; - download_content(name); - }); - } - - return CONSUMER_RUNNING; -} - -void TLSConsumerSocket::registerPrefix(const Prefix &producer_namespace) { - producer_namespace_ = producer_namespace; -} - -int TLSConsumerSocket::setSocketOption( - int socket_option_key, ConsumerSocket::ReadCallback *socket_option_value) { - return rescheduleOnIOService( - socket_option_key, socket_option_value, - [this](int socket_option_key, - ConsumerSocket::ReadCallback *socket_option_value) -> int { - switch (socket_option_key) { - case ConsumerCallbacksOptions::READ_CALLBACK: - read_callback_decrypted_ = socket_option_value; - break; - default: - return SOCKET_OPTION_NOT_SET; - } - - return SOCKET_OPTION_SET; - }); -} - -void TLSConsumerSocket::getReadBuffer(uint8_t **application_buffer, - size_t *max_length) {} - -void TLSConsumerSocket::readDataAvailable(size_t length) noexcept {} - -size_t TLSConsumerSocket::maxBufferSize() const { - return SSL3_RT_MAX_PLAIN_LENGTH; -} - -void TLSConsumerSocket::readBufferAvailable( - std::unique_ptr<utils::MemBuf> &&buffer) noexcept { - std::unique_lock<std::mutex> lck(this->mtx_); - if (head_) { - head_->prependChain(std::move(buffer)); - } else { - head_ = std::move(buffer); - } - - something_to_read_ = true; - cv_.notify_one(); -} - -void TLSConsumerSocket::readError(const std::error_code ec) noexcept {} - -void TLSConsumerSocket::readSuccess(std::size_t total_size) noexcept { - std::unique_lock<std::mutex> lck(this->mtx_); - content_downloaded_ = true; - something_to_read_ = true; - cv_.notify_one(); -} - -bool TLSConsumerSocket::isBufferMovable() noexcept { return true; } - -} // namespace interface - -} // namespace transport diff --git a/libtransport/src/hicn/transport/interfaces/tls_socket_consumer.h b/libtransport/src/hicn/transport/interfaces/tls_socket_consumer.h deleted file mode 100644 index 05f7fe6..0000000 --- a/libtransport/src/hicn/transport/interfaces/tls_socket_consumer.h +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright (c) 2017-2019 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/interfaces/socket_consumer.h> -#include <openssl/ssl.h> - -namespace transport { - -namespace interface { - -class TLSConsumerSocket : public ConsumerSocket, - public ConsumerSocket::ReadCallback { - /* Return the number of read bytes in readbytes */ - friend int readTLS(BIO *b, char *buf, size_t size, size_t *readbytes); - - /* Return the number of read bytes in the return param */ - friend int readOldTLS(BIO *h, char *buf, int size); - - /* Return the number of written bytes in written */ - friend int writeTLS(BIO *b, const char *buf, size_t size, size_t *written); - - /* Return the number of written bytes in the return param */ - friend int writeOldTLS(BIO *h, const char *buf, int num); - - friend long ctrlTLS(BIO *b, int cmd, long num, void *ptr); - - public: - explicit TLSConsumerSocket(int protocol, SSL *ssl_); - - ~TLSConsumerSocket() = default; - - int consume(const Name &name, std::unique_ptr<utils::MemBuf> &&buffer); - int consume(const Name &name) override; - - int asyncConsume(const Name &name, std::unique_ptr<utils::MemBuf> &&buffer); - int asyncConsume(const Name &name) override; - - void registerPrefix(const Prefix &producer_namespace); - - int setSocketOption( - int socket_option_key, - ConsumerSocket::ReadCallback *socket_option_value) override; - - using ConsumerSocket::getSocketOption; - using ConsumerSocket::setSocketOption; - - protected: - /* Callback invoked once an interest has been received and its payload - * decrypted */ - ConsumerInterestCallback on_interest_input_decrypted_; - ConsumerInterestCallback on_interest_process_decrypted_; - - private: - Name name_; - - /* SSL handle */ - SSL *ssl_; - SSL_CTX *ctx_; - - /* Chain of MemBuf to be used as a temporary buffer to pass descypted data - * from the underlying layer to the application */ - utils::ObjectPool<utils::MemBuf> buf_pool_; - std::unique_ptr<utils::MemBuf> decrypted_content_; - - /* Chain of MemBuf holding the payload to be written into interest or data */ - std::unique_ptr<utils::MemBuf> payload_; - - /* Chain of MemBuf holding the data retrieved from the underlying layer */ - std::unique_ptr<utils::MemBuf> head_; - - bool something_to_read_; - - bool content_downloaded_; - - double old_max_win_; - - double old_current_win_; - - uint32_t random_suffix_; - - ip_address_t secure_prefix_; - - Prefix producer_namespace_; - - ConsumerSocket::ReadCallback *read_callback_decrypted_; - - std::mutex mtx_; - - /* Condition variable for the wait */ - std::condition_variable cv_; - - utils::EventThread async_downloader_tls_; - - void setInterestPayload(ConsumerSocket &c, const core::Interest &interest); - void processPayload(ConsumerSocket &c, std::size_t bytes_transferred, - const std::error_code &ec); - - virtual void getReadBuffer(uint8_t **application_buffer, - size_t *max_length) override; - - virtual void readDataAvailable(size_t length) noexcept override; - - virtual size_t maxBufferSize() const override; - - virtual void readBufferAvailable( - std::unique_ptr<utils::MemBuf> &&buffer) noexcept override; - - virtual void readError(const std::error_code ec) noexcept override; - - virtual void readSuccess(std::size_t total_size) noexcept override; - virtual bool isBufferMovable() noexcept override; - - int download_content(const Name &name); -}; - -} // namespace interface - -} // end namespace transport
\ No newline at end of file diff --git a/libtransport/src/hicn/transport/interfaces/tls_socket_producer.cc b/libtransport/src/hicn/transport/interfaces/tls_socket_producer.cc deleted file mode 100644 index ad85ec6..0000000 --- a/libtransport/src/hicn/transport/interfaces/tls_socket_producer.cc +++ /dev/null @@ -1,587 +0,0 @@ -#include <hicn/transport/core/interest.h> -#include <hicn/transport/interfaces/p2psecure_socket_producer.h> -#include <hicn/transport/interfaces/tls_socket_producer.h> - -#include <openssl/bio.h> -#include <openssl/rand.h> -#include <openssl/ssl.h> - -namespace transport { - -namespace interface { - -/* Return the number of read bytes in readbytes */ -int TLSProducerSocket::read(BIO *b, char *buf, size_t size, size_t *readbytes) { - int ret; - - if (size > INT_MAX) size = INT_MAX; - - ret = TLSProducerSocket::readOld(b, buf, (int)size); - - if (ret <= 0) { - *readbytes = 0; - return ret; - } - - *readbytes = (size_t)ret; - - return 1; -} - -/* Return the number of read bytes in the return param */ -int TLSProducerSocket::readOld(BIO *b, char *buf, int size) { - TLSProducerSocket *socket; - socket = (TLSProducerSocket *)BIO_get_data(b); - - /* take a lock on the mutex. It will be unlocked by */ - std::unique_lock<std::mutex> lck(socket->mtx_); - if (!socket->something_to_read_) { - (socket->cv_).wait(lck); - } - - /* Either there already is something to read, or the thread has been waken up - */ - /* must return the payload in the interest */ - - utils::MemBuf *membuf = socket->packet_->next(); - int size_to_read; - if ((int)membuf->length() > size) { - size_to_read = size; - } else { - size_to_read = membuf->length(); - socket->something_to_read_ = false; - } - - std::memcpy(buf, membuf->data(), size_to_read); - membuf->trimStart(size_to_read); - - return size_to_read; -} - -/* Return the number of written bytes in written */ -int TLSProducerSocket::write(BIO *b, const char *buf, size_t size, - size_t *written) { - int ret; - - if (size > INT_MAX) size = INT_MAX; - - ret = TLSProducerSocket::writeOld(b, buf, (int)size); - - if (ret <= 0) { - *written = 0; - return ret; - } - - *written = (size_t)ret; - - return 1; -} - -/* Return the number of written bytes in the return param */ -int TLSProducerSocket::writeOld(BIO *b, const char *buf, int num) { - TLSProducerSocket *socket; - socket = (TLSProducerSocket *)BIO_get_data(b); - - if ((SSL_in_before(socket->ssl_) || SSL_in_init(socket->ssl_)) && - socket->first_) { - //! socket->tls_chunks_ corresponds to is_last - socket->tls_chunks_--; - bool making_manifest = socket->parent_->making_manifest_; - socket->parent_->setSocketOption(GeneralTransportOptions::MAKE_MANIFEST, - false); - socket->parent_->ProducerSocket::produce( - socket->name_, (const uint8_t *)buf, num, socket->tls_chunks_ == 0, - socket->last_segment_); - socket->parent_->setSocketOption(GeneralTransportOptions::MAKE_MANIFEST, - making_manifest); - socket->first_ = false; - } else { - socket->still_writing_ = true; - - std::unique_ptr<utils::MemBuf> mbuf = - utils::MemBuf::copyBuffer(buf, (std::size_t)num, 0, 0); - auto a = mbuf.release(); - socket->async_thread_.add([socket = socket, a]() { - socket->tls_chunks_--; - socket->to_call_oncontentproduced_--; - auto mbuf = std::unique_ptr<utils::MemBuf>(a); - socket->last_segment_ += socket->ProducerSocket::produce( - socket->name_, std::move(mbuf), socket->tls_chunks_ == 0, - socket->last_segment_); - ProducerContentCallback on_content_produced_application; - socket->getSocketOption(ProducerCallbacksOptions::CONTENT_PRODUCED, - on_content_produced_application); - if (socket->to_call_oncontentproduced_ == 0 && - on_content_produced_application) { - on_content_produced_application(*socket, std::error_code(), 0); - } - }); - } - - return num; -} - -TLSProducerSocket::TLSProducerSocket(P2PSecureProducerSocket *parent, - const Name &handshake_name) - : ProducerSocket(), - on_content_produced_application_(), - mtx_(), - cv_(), - something_to_read_(), - name_(), - last_segment_(0), - parent_(parent), - first_(true), - handshake_name_(handshake_name), - tls_chunks_(0), - to_call_oncontentproduced_(0), - still_writing_(false), - encryption_thread_() { - const SSL_METHOD *meth = TLS_server_method(); - ctx_ = SSL_CTX_new(meth); - - /* - * Setup SSL context (identity and parameter to use TLS 1.3) - */ - SSL_CTX_use_certificate(ctx_, parent->cert_509_); - SSL_CTX_use_PrivateKey(ctx_, parent->pkey_rsa_); - - int result = - SSL_CTX_set_ciphersuites(ctx_, - "TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_" - "SHA256:TLS_AES_128_GCM_SHA256"); - if (result != 1) { - throw errors::RuntimeException( - "Unable to set cipher list on TLS subsystem. Aborting."); - } - - // We force it to be TLS 1.3 - SSL_CTX_set_min_proto_version(ctx_, TLS1_3_VERSION); - SSL_CTX_set_max_proto_version(ctx_, TLS1_3_VERSION); - SSL_CTX_set_verify(ctx_, SSL_VERIFY_NONE, NULL); - SSL_CTX_set_num_tickets(ctx_, 0); - - result = SSL_CTX_add_custom_ext( - ctx_, 100, SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS, - TLSProducerSocket::addHicnKeyIdCb, TLSProducerSocket::freeHicnKeyIdCb, - this, TLSProducerSocket::parseHicnKeyIdCb, NULL); - - ssl_ = SSL_new(ctx_); - /* - * Setup this producer socker as the bio that TLS will use to write and read - * data (in stream mode) - */ - BIO_METHOD *bio_meth = - BIO_meth_new(BIO_TYPE_ACCEPT, "secure producer socket"); - BIO_meth_set_read(bio_meth, TLSProducerSocket::readOld); - BIO_meth_set_write(bio_meth, TLSProducerSocket::writeOld); - BIO_meth_set_ctrl(bio_meth, TLSProducerSocket::ctrl); - BIO *bio = BIO_new(bio_meth); - BIO_set_init(bio, 1); - BIO_set_data(bio, this); - SSL_set_bio(ssl_, bio, bio); - /* - * Set the callback so that when an interest is received we catch it and we - * decrypt the payload before passing it to the application. - */ - this->ProducerSocket::setSocketOption( - ProducerCallbacksOptions::CACHE_MISS, - (ProducerInterestCallback)std::bind(&TLSProducerSocket::cacheMiss, this, - std::placeholders::_1, - std::placeholders::_2)); - this->ProducerSocket::setSocketOption( - ProducerCallbacksOptions::CONTENT_PRODUCED, - (ProducerContentCallback)bind( - &TLSProducerSocket::onContentProduced, this, std::placeholders::_1, - std::placeholders::_2, std::placeholders::_3)); -} - -void TLSProducerSocket::accept() { - if (SSL_in_before(ssl_) || SSL_in_init(ssl_)) { - tls_chunks_ = 1; - int result = SSL_accept(ssl_); - if (result != 1) - throw errors::RuntimeException("Unable to perform client handshake"); - } - TRANSPORT_LOGD("Handshake performed!"); - parent_->list_secure_producers.push_front( - std::move(parent_->map_secure_producers[handshake_name_])); - parent_->map_secure_producers.erase(handshake_name_); - - ProducerInterestCallback on_interest_process_decrypted; - getSocketOption(ProducerCallbacksOptions::CACHE_MISS, - on_interest_process_decrypted); - - if (on_interest_process_decrypted) { - Interest inter(std::move(packet_)); - on_interest_process_decrypted(*this, inter); - } else { - throw errors::RuntimeException( - "On interest process unset. Unable to perform handshake"); - } -} - -int TLSProducerSocket::async_accept() { - if (!async_thread_.stopped()) { - async_thread_.add([this]() { this->accept(); }); - } else { - throw errors::RuntimeException( - "Async thread not running, impossible to perform handshake"); - } - - return 1; -} - -void TLSProducerSocket::onInterest(ProducerSocket &p, Interest &interest) { - /* Based on the state machine of (D)TLS, we know what action to do */ - if (SSL_in_before(ssl_) || SSL_in_init(ssl_)) { - std::unique_lock<std::mutex> lck(mtx_); - name_ = interest.getName(); - something_to_read_ = true; - packet_ = interest.acquireMemBufReference(); - if (head_) { - payload_->prependChain(interest.getPayload()); - } else { - payload_ = interest.getPayload(); // std::move(interest.getPayload()); - } - cv_.notify_one(); - } else { - name_ = interest.getName(); - packet_ = interest.acquireMemBufReference(); - payload_ = interest.getPayload(); - something_to_read_ = true; - - if (interest.getPayload()->length() > 0) - SSL_read( - ssl_, - const_cast<unsigned char *>(interest.getPayload()->writableData()), - interest.getPayload()->length()); - } - - ProducerInterestCallback on_interest_input_decrypted; - getSocketOption(ProducerCallbacksOptions::INTEREST_INPUT, - on_interest_input_decrypted); - if (on_interest_input_decrypted) - (on_interest_input_decrypted)(*this, interest); -} - -void TLSProducerSocket::cacheMiss(ProducerSocket &p, Interest &interest) { - if (SSL_in_before(ssl_) || SSL_in_init(ssl_)) { - std::unique_lock<std::mutex> lck(mtx_); - name_ = interest.getName(); - something_to_read_ = true; - packet_ = interest.acquireMemBufReference(); - payload_ = interest.getPayload(); - cv_.notify_one(); - } else { - name_ = interest.getName(); - packet_ = interest.acquireMemBufReference(); - payload_ = interest.getPayload(); - something_to_read_ = true; - - if (interest.getPayload()->length() > 0) - SSL_read( - ssl_, - const_cast<unsigned char *>(interest.getPayload()->writableData()), - interest.getPayload()->length()); - - if (on_interest_process_decrypted_ != VOID_HANDLER) - on_interest_process_decrypted_(*this, interest); - } -} - -void TLSProducerSocket::onContentProduced(ProducerSocket &p, - const std::error_code &err, - uint64_t bytes_written) {} - -uint32_t TLSProducerSocket::produce(Name content_name, - std::unique_ptr<utils::MemBuf> &&buffer, - bool is_last, uint32_t start_offset) { - if (SSL_in_before(ssl_) || SSL_in_init(ssl_)) { - throw errors::RuntimeException( - "New handshake on the same P2P secure producer socket not supported"); - } - size_t buf_size = buffer->length(); - name_ = served_namespaces_.front().mapName(content_name); - - tls_chunks_ = to_call_oncontentproduced_ = - ceil((float)buf_size / (float)SSL3_RT_MAX_PLAIN_LENGTH); - - if (!is_last) { - tls_chunks_++; - } - - last_segment_ = start_offset; - - SSL_write(ssl_, buffer->data(), buf_size); - BIO *wbio = SSL_get_wbio(ssl_); - int i = BIO_flush(wbio); - (void)i; // To shut up gcc 5 - - return 0; -} - -void TLSProducerSocket::asyncProduce(const Name &content_name, - const uint8_t *buf, size_t buffer_size, - bool is_last, uint32_t *start_offset) { - if (!encryption_thread_.stopped()) { - encryption_thread_.add([this, content_name, buffer = buf, - size = buffer_size, is_last, start_offset]() { - if (start_offset != NULL) { - produce(content_name, buffer, size, is_last, *start_offset); - } else { - produce(content_name, buffer, size, is_last, 0); - } - }); - } -} - -void TLSProducerSocket::asyncProduce(Name content_name, - std::unique_ptr<utils::MemBuf> &&buffer, - bool is_last, uint32_t offset, - uint32_t **last_segment) { - if (!encryption_thread_.stopped()) { - auto a = buffer.release(); - encryption_thread_.add( - [this, content_name, a, is_last, offset, last_segment]() { - auto buf = std::unique_ptr<utils::MemBuf>(a); - if (last_segment != NULL) { - *last_segment = &last_segment_; - } - produce(content_name, std::move(buf), is_last, offset); - }); - } -} - -void TLSProducerSocket::asyncProduce(ContentObject &content_object) { - throw errors::RuntimeException("API not supported"); -} - -void TLSProducerSocket::produce(ContentObject &content_object) { - throw errors::RuntimeException("API not supported"); -} - -long TLSProducerSocket::ctrl(BIO *b, int cmd, long num, void *ptr) { - if (cmd == BIO_CTRL_FLUSH) { - } - return 1; -} - -int TLSProducerSocket::addHicnKeyIdCb(SSL *s, unsigned int ext_type, - unsigned int context, - const unsigned char **out, size_t *outlen, - X509 *x, size_t chainidx, int *al, - void *add_arg) { - TLSProducerSocket *socket = reinterpret_cast<TLSProducerSocket *>(add_arg); - if (ext_type == 100) { - ip_prefix_t ip_prefix = - socket->parent_->served_namespaces_.front().toIpPrefixStruct(); - int inet_family = - socket->parent_->served_namespaces_.front().getAddressFamily(); - uint16_t prefix_len_bits = - socket->parent_->served_namespaces_.front().getPrefixLength(); - uint8_t prefix_len_bytes = prefix_len_bits / 8; - uint8_t prefix_len_u32 = prefix_len_bits / 32; - - ip_prefix_t *out_ip = (ip_prefix_t *)malloc(sizeof(ip_prefix_t)); - out_ip->family = inet_family; - out_ip->len = prefix_len_bits + 32; - u8 *out_ip_buf = const_cast<u8 *>( - ip_address_get_buffer(&(out_ip->address), inet_family)); - *out = reinterpret_cast<unsigned char *>(out_ip); - - RAND_bytes((unsigned char *)&socket->key_id_, 4); - - memcpy(out_ip_buf, ip_address_get_buffer(&(ip_prefix.address), inet_family), - prefix_len_bytes); - memcpy((out_ip_buf + prefix_len_bytes), &socket->key_id_, 4); - *outlen = sizeof(ip_prefix_t); - - ip_address_t mask = {}; - ip_address_t keyId_component = {}; - u32 *mask_buf; - u32 *keyId_component_buf; - switch (inet_family) { - case AF_INET: - mask_buf = &(mask.v4.as_u32); - keyId_component_buf = &(keyId_component.v4.as_u32); - break; - case AF_INET6: - mask_buf = mask.v6.as_u32; - keyId_component_buf = keyId_component.v6.as_u32; - break; - default: - throw errors::RuntimeException("Unknown protocol"); - } - - if (prefix_len_bits > (inet_family == AF_INET6 ? IPV6_ADDR_LEN_BITS - 32 - : IPV4_ADDR_LEN_BITS - 32)) - throw errors::RuntimeException( - "Not enough space in the content name to add key_id"); - - mask_buf[prefix_len_u32] = 0xffffffff; - keyId_component_buf[prefix_len_u32] = socket->key_id_; - socket->last_segment_ = 0; - - socket->on_interest_process_decrypted_ = - socket->parent_->on_interest_process_decrypted_; - - socket->registerPrefix( - Prefix(socket->parent_->served_namespaces_.front().getName( - Name(inet_family, (uint8_t *)&mask), - Name(inet_family, (uint8_t *)&keyId_component), - socket->parent_->served_namespaces_.front().getName()), - out_ip->len)); - socket->connect(); - } - return 1; -} - -void TLSProducerSocket::freeHicnKeyIdCb(SSL *s, unsigned int ext_type, - unsigned int context, - const unsigned char *out, - void *add_arg) { - free(const_cast<unsigned char *>(out)); -} - -int TLSProducerSocket::parseHicnKeyIdCb(SSL *s, unsigned int ext_type, - unsigned int context, - const unsigned char *in, size_t inlen, - X509 *x, size_t chainidx, int *al, - void *add_arg) { - return 1; -} - -int TLSProducerSocket::setSocketOption( - int socket_option_key, ProducerInterestCallback socket_option_value) { - return rescheduleOnIOService( - socket_option_key, socket_option_value, - [this](int socket_option_key, - ProducerInterestCallback socket_option_value) -> int { - int result = SOCKET_OPTION_SET; - switch (socket_option_key) { - case ProducerCallbacksOptions::INTEREST_INPUT: - on_interest_input_decrypted_ = socket_option_value; - break; - - case ProducerCallbacksOptions::INTEREST_DROP: - on_interest_dropped_input_buffer_ = socket_option_value; - break; - - case ProducerCallbacksOptions::INTEREST_PASS: - on_interest_inserted_input_buffer_ = socket_option_value; - break; - - case ProducerCallbacksOptions::CACHE_HIT: - on_interest_satisfied_output_buffer_ = socket_option_value; - break; - - case ProducerCallbacksOptions::CACHE_MISS: - on_interest_process_decrypted_ = socket_option_value; - break; - - default: - result = SOCKET_OPTION_NOT_SET; - break; - } - return result; - }); -} - -int TLSProducerSocket::setSocketOption( - int socket_option_key, ProducerContentCallback socket_option_value) { - return rescheduleOnIOService( - socket_option_key, socket_option_value, - [this](int socket_option_key, - ProducerContentCallback socket_option_value) -> int { - switch (socket_option_key) { - case ProducerCallbacksOptions::CONTENT_PRODUCED: - on_content_produced_application_ = socket_option_value; - break; - - default: - return SOCKET_OPTION_NOT_SET; - } - - return SOCKET_OPTION_SET; - }); -} - -int TLSProducerSocket::getSocketOption( - int socket_option_key, ProducerContentCallback **socket_option_value) { - return rescheduleOnIOService( - socket_option_key, socket_option_value, - [this](int socket_option_key, - ProducerContentCallback **socket_option_value) -> int { - switch (socket_option_key) { - case ProducerCallbacksOptions::CONTENT_PRODUCED: - *socket_option_value = &on_content_produced_application_; - break; - - default: - return SOCKET_OPTION_NOT_GET; - } - - return SOCKET_OPTION_GET; - }); -} - -int TLSProducerSocket::getSocketOption( - int socket_option_key, ProducerContentCallback &socket_option_value) { - return rescheduleOnIOServiceWithReference( - socket_option_key, socket_option_value, - [this](int socket_option_key, - ProducerContentCallback &socket_option_value) -> int { - switch (socket_option_key) { - case ProducerCallbacksOptions::CONTENT_PRODUCED: - socket_option_value = on_content_produced_application_; - break; - - default: - return SOCKET_OPTION_NOT_GET; - } - - return SOCKET_OPTION_GET; - }); -} - -int TLSProducerSocket::getSocketOption( - int socket_option_key, ProducerInterestCallback &socket_option_value) { - // Reschedule the function on the io_service to avoid race condition in case - // setSocketOption is called while the io_service is running. - return rescheduleOnIOServiceWithReference( - socket_option_key, socket_option_value, - [this](int socket_option_key, - ProducerInterestCallback &socket_option_value) -> int { - switch (socket_option_key) { - case ProducerCallbacksOptions::INTEREST_INPUT: - socket_option_value = on_interest_input_decrypted_; - break; - - case ProducerCallbacksOptions::INTEREST_DROP: - socket_option_value = on_interest_dropped_input_buffer_; - break; - - case ProducerCallbacksOptions::INTEREST_PASS: - socket_option_value = on_interest_inserted_input_buffer_; - break; - - case ProducerCallbacksOptions::CACHE_HIT: - socket_option_value = on_interest_satisfied_output_buffer_; - break; - - case ProducerCallbacksOptions::CACHE_MISS: - socket_option_value = on_interest_process_decrypted_; - break; - - default: - return SOCKET_OPTION_NOT_GET; - } - - return SOCKET_OPTION_GET; - }); -} - -} // namespace interface - -} // namespace transport diff --git a/libtransport/src/hicn/transport/interfaces/tls_socket_producer.h b/libtransport/src/hicn/transport/interfaces/tls_socket_producer.h deleted file mode 100644 index 4c09dda..0000000 --- a/libtransport/src/hicn/transport/interfaces/tls_socket_producer.h +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Copyright (c) 2017-2019 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/interfaces/socket_producer.h> -#include <hicn/transport/utils/content_store.h> - -#include <openssl/ssl.h> -#include <condition_variable> -#include <mutex> - -namespace transport { - -namespace interface { - -class P2PSecureProducerSocket; - -class TLSProducerSocket : virtual public ProducerSocket { - friend class P2PSecureProducerSocket; - - public: - explicit TLSProducerSocket(P2PSecureProducerSocket *parent, - const Name &handshake_name); - ~TLSProducerSocket() = default; - - uint32_t produce(Name content_name, const uint8_t *buffer, size_t buffer_size, - bool is_last = true, uint32_t start_offset = 0) override { - return produce(content_name, utils::MemBuf::copyBuffer(buffer, buffer_size), - is_last, start_offset); - } - - uint32_t produce(Name content_name, std::unique_ptr<utils::MemBuf> &&buffer, - bool is_last = true, uint32_t start_offset = 0) override; - - void produce(ContentObject &content_object) override; - - void asyncProduce(const Name &suffix, const uint8_t *buf, size_t buffer_size, - bool is_last = true, - uint32_t *start_offset = nullptr) override; - - void asyncProduce(Name content_name, std::unique_ptr<utils::MemBuf> &&buffer, - bool is_last, uint32_t offset, - uint32_t **last_segment = nullptr) override; - - void asyncProduce(ContentObject &content_object) override; - - virtual void accept(); - - virtual int async_accept(); - - virtual int setSocketOption( - int socket_option_key, - ProducerInterestCallback socket_option_value) override; - - virtual int setSocketOption( - int socket_option_key, - ProducerContentCallback socket_option_value) override; - - virtual int getSocketOption( - int socket_option_key, - ProducerContentCallback **socket_option_value) override; - - int getSocketOption(int socket_option_key, - ProducerContentCallback &socket_option_value); - - int getSocketOption(int socket_option_key, - ProducerInterestCallback &socket_option_value); - - using ProducerSocket::getSocketOption; - using ProducerSocket::onInterest; - using ProducerSocket::setSocketOption; - - protected: - /* Callback invoked once an interest has been received and its payload - * decrypted */ - ProducerInterestCallback on_interest_input_decrypted_; - ProducerInterestCallback on_interest_process_decrypted_; - ProducerContentCallback on_content_produced_application_; - - std::mutex mtx_; - - /* Condition variable for the wait */ - std::condition_variable cv_; - - /* Bool variable, true if there is something to read (an interest arrived) */ - bool something_to_read_; - - /* First interest that open a secure connection */ - transport::core::Name name_; - - /* SSL handle */ - SSL *ssl_; - SSL_CTX *ctx_; - - Packet::MemBufPtr packet_; - - std::unique_ptr<utils::MemBuf> head_; - std::uint32_t last_segment_; - std::shared_ptr<utils::MemBuf> payload_; - std::uint32_t key_id_; - - std::thread *handshake; - P2PSecureProducerSocket *parent_; - - bool first_; - Name handshake_name_; - int tls_chunks_; - int to_call_oncontentproduced_; - - bool still_writing_; - - utils::EventThread encryption_thread_; - - void onInterest(ProducerSocket &p, Interest &interest); - void cacheMiss(ProducerSocket &p, Interest &interest); - - /* Return the number of read bytes in readbytes */ - static int read(BIO *b, char *buf, size_t size, size_t *readbytes); - - /* Return the number of read bytes in the return param */ - static int readOld(BIO *h, char *buf, int size); - - /* Return the number of written bytes in written */ - static int write(BIO *b, const char *buf, size_t size, size_t *written); - - /* Return the number of written bytes in the return param */ - static int writeOld(BIO *h, const char *buf, int num); - - static long ctrl(BIO *b, int cmd, long num, void *ptr); - - static int addHicnKeyIdCb(SSL *s, unsigned int ext_type, unsigned int context, - const unsigned char **out, size_t *outlen, X509 *x, - size_t chainidx, int *al, void *add_arg); - - static void freeHicnKeyIdCb(SSL *s, unsigned int ext_type, - unsigned int context, const unsigned char *out, - void *add_arg); - - static int parseHicnKeyIdCb(SSL *s, unsigned int ext_type, - unsigned int context, const unsigned char *in, - size_t inlen, X509 *x, size_t chainidx, int *al, - void *add_arg); - - void onContentProduced(ProducerSocket &p, const std::error_code &err, - uint64_t bytes_written); -}; - -} // namespace interface - -} // end namespace transport diff --git a/libtransport/src/hicn/transport/interfaces/verification_policy.h b/libtransport/src/hicn/transport/interfaces/verification_policy.h deleted file mode 100644 index cb5140a..0000000 --- a/libtransport/src/hicn/transport/interfaces/verification_policy.h +++ /dev/null @@ -1,33 +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 <cstdint> - -namespace transport { -namespace interface { - -/** - * This policy allows the application to tell the transport what to do in case - * the verification of a content object fails. - */ -enum class VerificationPolicy : std::uint8_t { - DROP_PACKET, - ACCEPT_PACKET, - ABORT_SESSION -}; -} // namespace interface -} // namespace transport
\ No newline at end of file diff --git a/libtransport/src/hicn/transport/portability/CMakeLists.txt b/libtransport/src/hicn/transport/portability/CMakeLists.txt deleted file mode 100644 index 5ad3c82..0000000 --- a/libtransport/src/hicn/transport/portability/CMakeLists.txt +++ /dev/null @@ -1,32 +0,0 @@ -# Copyright (c) 2017-2019 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. - -cmake_minimum_required(VERSION 3.5 FATAL_ERROR) - -list(APPEND HEADER_FILES - ${CMAKE_CURRENT_SOURCE_DIR}/c_portability.h - ${CMAKE_CURRENT_SOURCE_DIR}/portability.h -) - -list(APPEND SOURCE_FILES - "" -) - -if(WIN32) - list(APPEND HEADER_FILES - ${CMAKE_CURRENT_SOURCE_DIR}/win_portability.h - ) -endif() - -set(SOURCE_FILES ${SOURCE_FILES} PARENT_SCOPE) -set(HEADER_FILES ${HEADER_FILES} PARENT_SCOPE)
\ No newline at end of file diff --git a/libtransport/src/hicn/transport/portability/c_portability.h b/libtransport/src/hicn/transport/portability/c_portability.h deleted file mode 100644 index 71e976a..0000000 --- a/libtransport/src/hicn/transport/portability/c_portability.h +++ /dev/null @@ -1,36 +0,0 @@ -/* - * 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 - -// noinline -#ifdef _MSC_VER -#define TRANSPORT_NOINLINE __declspec(noinline) -#elif defined(__clang__) || defined(__GNUC__) -#define TRANSPORT_NOINLINE __attribute__((__noinline__)) -#else -#define TRANSPORT_NOINLINE -#endif - -// always inline -#ifdef _MSC_VER -#define TRANSPORT_ALWAYS_INLINE __forceinline -#elif defined(__clang__) || defined(__GNUC__) -#define TRANSPORT_ALWAYS_INLINE inline __attribute__((__always_inline__)) -#else -#define TRANSPORT_ALWAYS_INLINE inline -#endif
\ No newline at end of file diff --git a/libtransport/src/hicn/transport/portability/portability.h b/libtransport/src/hicn/transport/portability/portability.h deleted file mode 100644 index 1d97a34..0000000 --- a/libtransport/src/hicn/transport/portability/portability.h +++ /dev/null @@ -1,50 +0,0 @@ -/* - * 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 - -#ifdef _WIN32 -#include <hicn/transport/portability/win_portability.h> -#endif - -#include <hicn/transport/portability/c_portability.h> - -#include <string.h> -#include <cstddef> - -namespace portability { - -constexpr bool little_endian_arch = __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__; -constexpr bool big_endian_arch = !little_endian_arch; - -#if defined(__GNUC__) -#define _TRANSPORT_GNU_DISABLE_WARNING(warning) #warning -#define TRANSPORT_GNU_DISABLE_WARNING(warning) \ - _Pragma(_TRANSPORT_GNU_DISABLE_WARNING(GCC diagnostic ignored warning)) - -#ifdef __clang__ -#define TRANSPORT_CLANG_DISABLE_WARNING(warning) \ - TRANSPORT_GNU_DISABLE_WARNING(warning) -#define TRANSPORT_GCC_DISABLE_WARNING(warning) -#else -#define TRANSPORT_CLANG_DISABLE_WARNING(warning) -#define TRANSPORT_GCC_DISABLE_WARNING(warning) \ - TRANSPORT_GNU_DISABLE_WARNING(warning) -#endif -#endif - -} // namespace portability diff --git a/libtransport/src/hicn/transport/portability/win_portability.h b/libtransport/src/hicn/transport/portability/win_portability.h deleted file mode 100644 index 65d9492..0000000 --- a/libtransport/src/hicn/transport/portability/win_portability.h +++ /dev/null @@ -1,42 +0,0 @@ -/*
- * 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
-#define NOMINMAX
-#include <fcntl.h>
-#include <io.h>
-#include <parc/windows/parc_Utils.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/src/hicn/transport/protocols/CMakeLists.txt b/libtransport/src/hicn/transport/protocols/CMakeLists.txt deleted file mode 100644 index 06515e0..0000000 --- a/libtransport/src/hicn/transport/protocols/CMakeLists.txt +++ /dev/null @@ -1,77 +0,0 @@ -# Copyright (c) 2017-2019 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. - -cmake_minimum_required(VERSION 3.5 FATAL_ERROR) - -list(APPEND HEADER_FILES - ${CMAKE_CURRENT_SOURCE_DIR}/indexer.h - ${CMAKE_CURRENT_SOURCE_DIR}/incremental_indexer.h - ${CMAKE_CURRENT_SOURCE_DIR}/manifest_incremental_indexer.h - ${CMAKE_CURRENT_SOURCE_DIR}/reassembly.h - ${CMAKE_CURRENT_SOURCE_DIR}/datagram_reassembly.h - ${CMAKE_CURRENT_SOURCE_DIR}/byte_stream_reassembly.h - ${CMAKE_CURRENT_SOURCE_DIR}/congestion_window_protocol.h - ${CMAKE_CURRENT_SOURCE_DIR}/packet_manager.h - ${CMAKE_CURRENT_SOURCE_DIR}/statistics.h - ${CMAKE_CURRENT_SOURCE_DIR}/rate_estimation.h - ${CMAKE_CURRENT_SOURCE_DIR}/download_observer.h - ${CMAKE_CURRENT_SOURCE_DIR}/protocol.h - ${CMAKE_CURRENT_SOURCE_DIR}/raaqm.h - ${CMAKE_CURRENT_SOURCE_DIR}/raaqm_data_path.h - ${CMAKE_CURRENT_SOURCE_DIR}/cbr.h - ${CMAKE_CURRENT_SOURCE_DIR}/rtc.h - ${CMAKE_CURRENT_SOURCE_DIR}/rtc_data_path.h - ${CMAKE_CURRENT_SOURCE_DIR}/errors.h - ${CMAKE_CURRENT_SOURCE_DIR}/verification_manager.h - ${CMAKE_CURRENT_SOURCE_DIR}/data_processing_events.h -) - -list(APPEND SOURCE_FILES - ${CMAKE_CURRENT_SOURCE_DIR}/indexer.cc - ${CMAKE_CURRENT_SOURCE_DIR}/incremental_indexer.cc - ${CMAKE_CURRENT_SOURCE_DIR}/manifest_incremental_indexer.cc - ${CMAKE_CURRENT_SOURCE_DIR}/reassembly.cc - ${CMAKE_CURRENT_SOURCE_DIR}/datagram_reassembly.cc - ${CMAKE_CURRENT_SOURCE_DIR}/byte_stream_reassembly.cc - ${CMAKE_CURRENT_SOURCE_DIR}/protocol.cc - ${CMAKE_CURRENT_SOURCE_DIR}/raaqm.cc - ${CMAKE_CURRENT_SOURCE_DIR}/rate_estimation.cc - ${CMAKE_CURRENT_SOURCE_DIR}/raaqm_data_path.cc - ${CMAKE_CURRENT_SOURCE_DIR}/cbr.cc - ${CMAKE_CURRENT_SOURCE_DIR}/rtc.cc - ${CMAKE_CURRENT_SOURCE_DIR}/rtc_data_path.cc - ${CMAKE_CURRENT_SOURCE_DIR}/errors.cc - ${CMAKE_CURRENT_SOURCE_DIR}/verification_manager.cc -) - -set(RAAQM_CONFIG_INSTALL_PREFIX -${CMAKE_INSTALL_PREFIX}/etc/hicn -) - -set(raaqm_config_path - ${RAAQM_CONFIG_INSTALL_PREFIX}/consumer.conf - PARENT_SCOPE -) - -set(TRANSPORT_CONFIG - ${CMAKE_CURRENT_SOURCE_DIR}/consumer.conf -) - -install( - FILES ${TRANSPORT_CONFIG} - DESTINATION ${CMAKE_INSTALL_FULL_SYSCONFDIR}/hicn - COMPONENT lib${LIBTRANSPORT} -) - -set(SOURCE_FILES ${SOURCE_FILES} PARENT_SCOPE) -set(HEADER_FILES ${HEADER_FILES} PARENT_SCOPE)
\ No newline at end of file diff --git a/libtransport/src/hicn/transport/protocols/byte_stream_reassembly.cc b/libtransport/src/hicn/transport/protocols/byte_stream_reassembly.cc deleted file mode 100644 index 2f1e5d8..0000000 --- a/libtransport/src/hicn/transport/protocols/byte_stream_reassembly.cc +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright (c) 2017-2019 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. - */ - -#include <hicn/transport/protocols/byte_stream_reassembly.h> - -#include <hicn/transport/interfaces/socket_consumer.h> -#include <hicn/transport/protocols/errors.h> -#include <hicn/transport/protocols/indexer.h> -#include <hicn/transport/utils/array.h> -#include <hicn/transport/utils/membuf.h> - -namespace transport { - -namespace protocol { - -ByteStreamReassembly::ByteStreamReassembly( - interface::ConsumerSocket *icn_socket, - TransportProtocol *transport_protocol) - : Reassembly(icn_socket, transport_protocol), - index_(IndexManager::invalid_index), - download_complete_(false) {} - -void ByteStreamReassembly::reassemble( - std::unique_ptr<ContentObjectManifest> &&manifest) { - if (TRANSPORT_EXPECT_TRUE(manifest != nullptr)) { - received_packets_.emplace( - std::make_pair(manifest->getName().getSuffix(), nullptr)); - assembleContent(); - } -} - -void ByteStreamReassembly::reassemble(ContentObject::Ptr &&content_object) { - if (TRANSPORT_EXPECT_TRUE(content_object != nullptr)) { - received_packets_.emplace(std::make_pair( - content_object->getName().getSuffix(), std::move(content_object))); - assembleContent(); - } -} - -void ByteStreamReassembly::assembleContent() { - if (TRANSPORT_EXPECT_FALSE(index_ == IndexManager::invalid_index)) { - index_ = index_manager_->getNextReassemblySegment(); - if (index_ == IndexManager::invalid_index) { - return; - } - } - - auto it = received_packets_.find((const unsigned int)index_); - while (it != received_packets_.end()) { - // Check if valid packet - if (it->second) { - copyContent(*it->second); - } - - received_packets_.erase(it); - index_ = index_manager_->getNextReassemblySegment(); - it = received_packets_.find((const unsigned int)index_); - } - - if (!download_complete_ && index_ != IndexManager::invalid_index) { - transport_protocol_->onReassemblyFailed(index_); - } -} - -void ByteStreamReassembly::copyContent(const ContentObject &content_object) { - auto a = content_object.getPayload(); - auto payload_length = a->length(); - auto write_size = std::min(payload_length, read_buffer_->tailroom()); - auto additional_bytes = payload_length > read_buffer_->tailroom() - ? payload_length - read_buffer_->tailroom() - : 0; - - std::memcpy(read_buffer_->writableTail(), a->data(), write_size); - read_buffer_->append(write_size); - - if (!read_buffer_->tailroom()) { - notifyApplication(); - std::memcpy(read_buffer_->writableTail(), a->data() + write_size, - additional_bytes); - read_buffer_->append(additional_bytes); - } - - download_complete_ = - index_manager_->getFinalSuffix() == content_object.getName().getSuffix(); - - if (TRANSPORT_EXPECT_FALSE(download_complete_)) { - notifyApplication(); - transport_protocol_->onContentReassembled( - make_error_code(protocol_error::success)); - } -} - -void ByteStreamReassembly::reInitialize() { - index_ = IndexManager::invalid_index; - download_complete_ = false; - - received_packets_.clear(); - - // reset read buffer - interface::ConsumerSocket::ReadCallback *read_callback; - reassembly_consumer_socket_->getSocketOption( - interface::ConsumerCallbacksOptions::READ_CALLBACK, &read_callback); - - read_buffer_ = utils::MemBuf::create(read_callback->maxBufferSize()); -} - -} // namespace protocol - -} // namespace transport diff --git a/libtransport/src/hicn/transport/protocols/byte_stream_reassembly.h b/libtransport/src/hicn/transport/protocols/byte_stream_reassembly.h deleted file mode 100644 index 7c77d48..0000000 --- a/libtransport/src/hicn/transport/protocols/byte_stream_reassembly.h +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2017-2019 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/protocols/reassembly.h> - -namespace transport { - -namespace protocol { - -class ByteStreamReassembly : public Reassembly { - public: - ByteStreamReassembly(interface::ConsumerSocket *icn_socket, - TransportProtocol *transport_protocol); - - protected: - virtual void reassemble(core::ContentObject::Ptr &&content_object) override; - - virtual void reassemble( - std::unique_ptr<core::ContentObjectManifest> &&manifest) override; - - virtual void copyContent(const core::ContentObject &content_object); - - virtual void reInitialize() override; - - private: - void assembleContent(); - - protected: - // The consumer socket - // std::unique_ptr<IncrementalIndexManager> incremental_index_manager_; - // std::unique_ptr<ManifestIndexManager> manifest_index_manager_; - // IndexVerificationManager *index_manager_; - std::unordered_map<std::uint32_t, core::ContentObject::Ptr> received_packets_; - uint32_t index_; - bool download_complete_; -}; - -} // namespace protocol - -} // end namespace transport diff --git a/libtransport/src/hicn/transport/protocols/cbr.cc b/libtransport/src/hicn/transport/protocols/cbr.cc deleted file mode 100644 index 02bc7b5..0000000 --- a/libtransport/src/hicn/transport/protocols/cbr.cc +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2017-2019 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. - */ - -#include <hicn/transport/interfaces/socket_consumer.h> -#include <hicn/transport/protocols/cbr.h> - -namespace transport { - -namespace protocol { - -using namespace interface; - -CbrTransportProtocol::CbrTransportProtocol( - interface::ConsumerSocket *icnet_socket) - : RaaqmTransportProtocol(icnet_socket) {} - -int CbrTransportProtocol::start() { return RaaqmTransportProtocol::start(); } - -void CbrTransportProtocol::reset() { - RaaqmTransportProtocol::reset(); - socket_->getSocketOption(GeneralTransportOptions::CURRENT_WINDOW_SIZE, - current_window_size_); -} - -void CbrTransportProtocol::afterDataUnsatisfied(uint64_t segment) {} - -void CbrTransportProtocol::afterContentReception( - const Interest &interest, const ContentObject &content_object) { - auto segment = content_object.getName().getSuffix(); - auto now = utils::SteadyClock::now(); - auto rtt = std::chrono::duration_cast<utils::Microseconds>( - now - interest_timepoints_[segment & mask]); - // Update stats - updateStats(segment, rtt.count(), now); -} - -} // end namespace protocol - -} // end namespace transport diff --git a/libtransport/src/hicn/transport/protocols/cbr.h b/libtransport/src/hicn/transport/protocols/cbr.h deleted file mode 100644 index e80da14..0000000 --- a/libtransport/src/hicn/transport/protocols/cbr.h +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2017-2019 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/protocols/raaqm.h> - -namespace transport { - -namespace protocol { - -class CbrTransportProtocol : public RaaqmTransportProtocol { - public: - CbrTransportProtocol(interface::ConsumerSocket *icnet_socket); - - int start() override; - - void reset() override; - - private: - void afterContentReception(const Interest &interest, - const ContentObject &content_object) override; - void afterDataUnsatisfied(uint64_t segment) override; -}; - -} // end namespace protocol - -} // end namespace transport
\ No newline at end of file diff --git a/libtransport/src/hicn/transport/protocols/congestion_window_protocol.h b/libtransport/src/hicn/transport/protocols/congestion_window_protocol.h deleted file mode 100644 index 36ac6eb..0000000 --- a/libtransport/src/hicn/transport/protocols/congestion_window_protocol.h +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2017-2019 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 { - -class CWindowProtocol { - protected: - virtual void increaseWindow() = 0; - virtual void decreaseWindow() = 0; -}; - -} // end namespace protocol - -} // end namespace transport diff --git a/libtransport/src/hicn/transport/protocols/consumer.conf b/libtransport/src/hicn/transport/protocols/consumer.conf deleted file mode 100644 index 1a366f3..0000000 --- a/libtransport/src/hicn/transport/protocols/consumer.conf +++ /dev/null @@ -1,21 +0,0 @@ -; this file contais the parameters for RAAQM -autotune = no -lifetime = 500 -retransmissions = 128 -beta = 0.99 -drop = 0.003 -beta_wifi_ = 0.99 -drop_wifi_ = 0.6 -beta_lte_ = 0.99 -drop_lte_ = 0.003 -wifi_delay_ = 200 -lte_delay_ = 9000 - -alpha = 0.95 -batching_parameter = 200 - -;Choice of rate estimator: -;0 --> an estimation each $(batching_parameter) packets -;1 --> an estimation "a la TCP", estimation at the end of the download of the segment - -rate_estimator = 0 diff --git a/libtransport/src/hicn/transport/protocols/data_processing_events.h b/libtransport/src/hicn/transport/protocols/data_processing_events.h deleted file mode 100644 index 8975c2b..0000000 --- a/libtransport/src/hicn/transport/protocols/data_processing_events.h +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2017-2019 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/core/content_object.h> -#include <hicn/transport/core/interest.h> - -namespace transport { -namespace protocol { - -class ContentObjectProcessingEventCallback { - public: - virtual ~ContentObjectProcessingEventCallback() = default; - virtual void onPacketDropped(core::Interest::Ptr &&i, - core::ContentObject::Ptr &&c) = 0; - virtual void onReassemblyFailed(std::uint32_t missing_segment) = 0; -}; - -} // namespace protocol -} // namespace transport diff --git a/libtransport/src/hicn/transport/protocols/datagram_reassembly.cc b/libtransport/src/hicn/transport/protocols/datagram_reassembly.cc deleted file mode 100644 index 7b01ad4..0000000 --- a/libtransport/src/hicn/transport/protocols/datagram_reassembly.cc +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2017-2019 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. - */ - -#include <hicn/transport/protocols/datagram_reassembly.h> - -namespace transport { - -namespace protocol { - -DatagramReassembly::DatagramReassembly(interface::ConsumerSocket* icn_socket, - TransportProtocol* transport_protocol) - : Reassembly(icn_socket, transport_protocol) {} - -void DatagramReassembly::reassemble(core::ContentObject::Ptr&& content_object) { - read_buffer_ = content_object->getPayload(); - Reassembly::notifyApplication(); -} - -void DatagramReassembly::reInitialize() {} - -} // namespace protocol - -} // namespace transport diff --git a/libtransport/src/hicn/transport/protocols/datagram_reassembly.h b/libtransport/src/hicn/transport/protocols/datagram_reassembly.h deleted file mode 100644 index 923b6f2..0000000 --- a/libtransport/src/hicn/transport/protocols/datagram_reassembly.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2017-2019 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/protocols/reassembly.h> - -namespace transport { - -namespace protocol { - -class DatagramReassembly : public Reassembly { - public: - DatagramReassembly(interface::ConsumerSocket *icn_socket, - TransportProtocol *transport_protocol); - - virtual void reassemble(core::ContentObject::Ptr &&content_object) override; - virtual void reInitialize() override; - virtual void reassemble( - std::unique_ptr<core::ContentObjectManifest> &&manifest) override { - return; - } -}; - -} // namespace protocol - -} // end namespace transport diff --git a/libtransport/src/hicn/transport/protocols/download_observer.h b/libtransport/src/hicn/transport/protocols/download_observer.h deleted file mode 100644 index 6d24fe6..0000000 --- a/libtransport/src/hicn/transport/protocols/download_observer.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2017-2019 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 { - -class IcnObserver { - public: - virtual ~IcnObserver(){}; - - virtual void notifyStats(double throughput) = 0; - virtual void notifyDownloadTime(double downloadTime) = 0; -}; - -} // end namespace protocol - -} // end namespace transport diff --git a/libtransport/src/hicn/transport/protocols/errors.cc b/libtransport/src/hicn/transport/protocols/errors.cc deleted file mode 100644 index c2249ed..0000000 --- a/libtransport/src/hicn/transport/protocols/errors.cc +++ /dev/null @@ -1,60 +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. - */ - -#include <hicn/transport/protocols/errors.h> - -namespace transport { -namespace protocol { - -const std::error_category& protocol_category() { - static protocol_category_impl instance; - - return instance; -} - -const char* protocol_category_impl::name() const throw() { - return "transport::protocol::error"; -} - -std::string protocol_category_impl::message(int ev) const { - switch (static_cast<protocol_error>(ev)) { - case protocol_error::success: { - return "Success"; - } - case protocol_error::signature_verification_failed: { - return "Signature verification failed."; - } - case protocol_error::integrity_verification_failed: { - return "Integrity verification failed"; - } - case protocol_error::no_verifier_provided: { - return "Transport cannot get any verifier for the given data."; - } - case protocol_error::io_error: { - return "Conectivity error between transport and local forwarder"; - } - case protocol_error::max_retransmissions_error: { - return "Transport protocol reached max number of retransmissions allowed " - "for the same interest."; - } - case protocol_error::session_aborted: { - return "The session has been aborted by the application."; - } - default: { return "Unknown protocol error"; } - } -} - -} // namespace protocol -} // namespace transport
\ No newline at end of file diff --git a/libtransport/src/hicn/transport/protocols/errors.h b/libtransport/src/hicn/transport/protocols/errors.h deleted file mode 100644 index cb3d347..0000000 --- a/libtransport/src/hicn/transport/protocols/errors.h +++ /dev/null @@ -1,91 +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 <string> -#include <system_error> - -namespace transport { -namespace protocol { - -/** - * @brief Get the default server error category. - * @return The default server error category instance. - * - * @warning The first call to this function is thread-safe only starting with - * C++11. - */ -const std::error_category& protocol_category(); - -/** - * The list of errors. - */ -enum class protocol_error { - success = 0, - signature_verification_failed, - integrity_verification_failed, - no_verifier_provided, - io_error, - max_retransmissions_error, - session_aborted, -}; - -/** - * @brief Create an error_code instance for the given error. - * @param error The error. - * @return The error_code instance. - */ -inline std::error_code make_error_code(protocol_error error) { - return std::error_code(static_cast<int>(error), protocol_category()); -} - -/** - * @brief Create an error_condition instance for the given error. - * @param error The error. - * @return The error_condition instance. - */ -inline std::error_condition make_error_condition(protocol_error error) { - return std::error_condition(static_cast<int>(error), protocol_category()); -} - -/** - * @brief A server error category. - */ -class protocol_category_impl : public std::error_category { - public: - /** - * @brief Get the name of the category. - * @return The name of the category. - */ - virtual const char* name() const throw(); - - /** - * @brief Get the error message for a given error. - * @param ev The error numeric value. - * @return The message associated to the error. - */ - virtual std::string message(int ev) const; -}; -} // namespace protocol -} // namespace transport - -namespace std { -// namespace system { -template <> -struct is_error_code_enum<::transport::protocol::protocol_error> - : public std::true_type {}; -// } // namespace system -} // namespace std
\ No newline at end of file diff --git a/libtransport/src/hicn/transport/protocols/incremental_indexer.cc b/libtransport/src/hicn/transport/protocols/incremental_indexer.cc deleted file mode 100644 index 5a8046d..0000000 --- a/libtransport/src/hicn/transport/protocols/incremental_indexer.cc +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2017-2019 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. - */ - -#include <hicn/transport/protocols/incremental_indexer.h> - -#include <hicn/transport/interfaces/socket_consumer.h> - -namespace transport { -namespace protocol { - -void IncrementalIndexer::onContentObject( - core::Interest::Ptr &&interest, core::ContentObject::Ptr &&content_object) { - using namespace interface; - - if (TRANSPORT_EXPECT_FALSE(content_object->testRst())) { - final_suffix_ = content_object->getName().getSuffix(); - } - - auto ret = verification_manager_->onPacketToVerify(*content_object); - - switch (ret) { - case VerificationPolicy::ACCEPT_PACKET: { - reassembly_->reassemble(std::move(content_object)); - break; - } - case VerificationPolicy::DROP_PACKET: { - transport_protocol_->onPacketDropped(std::move(interest), - std::move(content_object)); - break; - } - case VerificationPolicy::ABORT_SESSION: { - transport_protocol_->onContentReassembled( - make_error_code(protocol_error::session_aborted)); - break; - } - } -} - -} // namespace protocol -} // namespace transport
\ No newline at end of file diff --git a/libtransport/src/hicn/transport/protocols/incremental_indexer.h b/libtransport/src/hicn/transport/protocols/incremental_indexer.h deleted file mode 100644 index b587a83..0000000 --- a/libtransport/src/hicn/transport/protocols/incremental_indexer.h +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright (c) 2017-2019 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/protocols/indexer.h> - -#include <hicn/transport/errors/runtime_exception.h> -#include <hicn/transport/errors/unexpected_manifest_exception.h> -#include <hicn/transport/protocols/reassembly.h> -#include <hicn/transport/protocols/verification_manager.h> -#include <hicn/transport/utils/literals.h> - -#include <deque> - -namespace transport { - -namespace interface { -class ConsumerSocket; -} - -namespace protocol { - -class Reassembly; -class TransportProtocol; - -class IncrementalIndexer : public Indexer { - public: - IncrementalIndexer(interface::ConsumerSocket *icn_socket, - TransportProtocol *transport, Reassembly *reassembly) - : socket_(icn_socket), - reassembly_(reassembly), - transport_protocol_(transport), - final_suffix_(std::numeric_limits<uint32_t>::max()), - first_suffix_(0), - next_download_suffix_(0), - next_reassembly_suffix_(0), - verification_manager_( - std::make_unique<SignatureVerificationManager>(icn_socket)) { - if (reassembly_) { - reassembly_->setIndexer(this); - } - } - - IncrementalIndexer(const IncrementalIndexer &) = delete; - - IncrementalIndexer(IncrementalIndexer &&other) - : socket_(other.socket_), - reassembly_(other.reassembly_), - transport_protocol_(other.transport_protocol_), - final_suffix_(other.final_suffix_), - first_suffix_(other.first_suffix_), - next_download_suffix_(other.next_download_suffix_), - next_reassembly_suffix_(other.next_reassembly_suffix_), - verification_manager_(std::move(other.verification_manager_)) { - if (reassembly_) { - reassembly_->setIndexer(this); - } - } - - /** - * - */ - virtual ~IncrementalIndexer() {} - - TRANSPORT_ALWAYS_INLINE virtual void reset( - std::uint32_t offset = 0) override { - final_suffix_ = std::numeric_limits<uint32_t>::max(); - next_download_suffix_ = offset; - next_reassembly_suffix_ = offset; - } - - /** - * Retrieve from the manifest the next suffix to retrieve. - */ - TRANSPORT_ALWAYS_INLINE virtual uint32_t getNextSuffix() override { - return next_download_suffix_ <= final_suffix_ ? next_download_suffix_++ - : IndexManager::invalid_index; - } - - TRANSPORT_ALWAYS_INLINE virtual void setFirstSuffix( - uint32_t suffix) override { - first_suffix_ = suffix; - } - - /** - * Retrive the next segment to be reassembled. - */ - TRANSPORT_ALWAYS_INLINE virtual uint32_t getNextReassemblySegment() override { - return next_reassembly_suffix_ <= final_suffix_ - ? next_reassembly_suffix_++ - : IndexManager::invalid_index; - } - - TRANSPORT_ALWAYS_INLINE virtual bool isFinalSuffixDiscovered() override { - return final_suffix_ != std::numeric_limits<uint32_t>::max(); - } - - TRANSPORT_ALWAYS_INLINE virtual uint32_t getFinalSuffix() override { - return final_suffix_; - } - - void onContentObject(core::Interest::Ptr &&interest, - core::ContentObject::Ptr &&content_object) override; - - TRANSPORT_ALWAYS_INLINE void setReassembly(Reassembly *reassembly) { - reassembly_ = reassembly; - - if (reassembly_) { - reassembly_->setIndexer(this); - } - } - - TRANSPORT_ALWAYS_INLINE bool onKeyToVerify() override { - return verification_manager_->onKeyToVerify(); - } - - protected: - interface::ConsumerSocket *socket_; - Reassembly *reassembly_; - TransportProtocol *transport_protocol_; - uint32_t final_suffix_; - uint32_t first_suffix_; - uint32_t next_download_suffix_; - uint32_t next_reassembly_suffix_; - std::unique_ptr<VerificationManager> verification_manager_; -}; - -} // end namespace protocol - -} // end namespace transport diff --git a/libtransport/src/hicn/transport/protocols/indexer.cc b/libtransport/src/hicn/transport/protocols/indexer.cc deleted file mode 100644 index d95c10f..0000000 --- a/libtransport/src/hicn/transport/protocols/indexer.cc +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) 2017-2019 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. - */ - -#include <hicn/transport/protocols/indexer.h> - -#include <hicn/transport/protocols/incremental_indexer.h> -#include <hicn/transport/protocols/manifest_incremental_indexer.h> -#include <hicn/transport/protocols/protocol.h> -#include <hicn/transport/utils/branch_prediction.h> - -namespace transport { -namespace protocol { - -IndexManager::IndexManager(interface::ConsumerSocket *icn_socket, - TransportProtocol *transport, Reassembly *reassembly) - : indexer_(std::make_unique<IncrementalIndexer>(icn_socket, transport, - reassembly)), - first_segment_received_(false), - icn_socket_(icn_socket), - transport_(transport), - reassembly_(reassembly) {} - -void IndexManager::onContentObject(core::Interest::Ptr &&interest, - core::ContentObject::Ptr &&content_object) { - if (first_segment_received_) { - indexer_->onContentObject(std::move(interest), std::move(content_object)); - } else { - std::uint32_t segment_number = interest->getName().getSuffix(); - - if (segment_number == 0) { - // Check if manifest - if (content_object->getPayloadType() == PayloadType::MANIFEST) { - IncrementalIndexer *indexer = - static_cast<IncrementalIndexer *>(indexer_.release()); - indexer_ = - std::make_unique<ManifestIncrementalIndexer>(std::move(*indexer)); - delete indexer; - } - - indexer_->onContentObject(std::move(interest), std::move(content_object)); - auto it = interest_data_set_.begin(); - while (it != interest_data_set_.end()) { - indexer_->onContentObject(std::move(const_cast<core::Interest::Ptr &&>(it->first)), std::move(const_cast<core::ContentObject::Ptr &&>(it->second))); - it = interest_data_set_.erase(it); - } - - first_segment_received_ = true; - } else { - interest_data_set_.emplace(std::move(interest), std::move(content_object)); - } - } -} - -bool IndexManager::onKeyToVerify() { - return indexer_->onKeyToVerify(); -} - -void IndexManager::reset(std::uint32_t offset) { - indexer_ = std::make_unique<IncrementalIndexer>(icn_socket_, transport_, - reassembly_); - first_segment_received_ = false; - interest_data_set_.clear(); -} - -} // namespace protocol -} // namespace transport diff --git a/libtransport/src/hicn/transport/protocols/indexer.h b/libtransport/src/hicn/transport/protocols/indexer.h deleted file mode 100644 index 87cf9b3..0000000 --- a/libtransport/src/hicn/transport/protocols/indexer.h +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (c) 2017-2019 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/core/content_object.h> -#include <hicn/transport/core/interest.h> - -#include <set> - -namespace transport { - -namespace interface { -class ConsumerSocket; -} - -namespace protocol { - -class Reassembly; -class TransportProtocol; - -class Indexer { - public: - /** - * - */ - virtual ~Indexer() = default; - /** - * Retrieve from the manifest the next suffix to retrieve. - */ - virtual uint32_t getNextSuffix() = 0; - - virtual void setFirstSuffix(uint32_t suffix) = 0; - - /** - * Retrive the next segment to be reassembled. - */ - virtual uint32_t getNextReassemblySegment() = 0; - - virtual bool isFinalSuffixDiscovered() = 0; - - virtual uint32_t getFinalSuffix() = 0; - - virtual void reset(std::uint32_t offset = 0) = 0; - - virtual void onContentObject(core::Interest::Ptr &&interest, - core::ContentObject::Ptr &&content_object) = 0; - - virtual bool onKeyToVerify() = 0; -}; - -class IndexManager : Indexer { - public: - static constexpr uint32_t invalid_index = ~0; - - IndexManager(interface::ConsumerSocket *icn_socket, - TransportProtocol *transport, Reassembly *reassembly); - - uint32_t getNextSuffix() override { return indexer_->getNextSuffix(); } - - void setFirstSuffix(uint32_t suffix) override { - indexer_->setFirstSuffix(suffix); - } - - uint32_t getNextReassemblySegment() override { - return indexer_->getNextReassemblySegment(); - } - - bool isFinalSuffixDiscovered() override { - return indexer_->isFinalSuffixDiscovered(); - } - - uint32_t getFinalSuffix() override { return indexer_->getFinalSuffix(); } - - void reset(std::uint32_t offset = 0) override; - - void onContentObject(core::Interest::Ptr &&interest, - core::ContentObject::Ptr &&content_object) override; - - bool onKeyToVerify() override; - - private: - std::unique_ptr<Indexer> indexer_; - bool first_segment_received_; - std::set<std::pair<core::Interest::Ptr, core::ContentObject::Ptr>> - interest_data_set_; - interface::ConsumerSocket *icn_socket_; - TransportProtocol *transport_; - Reassembly *reassembly_; -}; - -} // end namespace protocol - -} // end namespace transport diff --git a/libtransport/src/hicn/transport/protocols/manifest_incremental_indexer.cc b/libtransport/src/hicn/transport/protocols/manifest_incremental_indexer.cc deleted file mode 100644 index 592daa4..0000000 --- a/libtransport/src/hicn/transport/protocols/manifest_incremental_indexer.cc +++ /dev/null @@ -1,232 +0,0 @@ -/* - * Copyright (c) 2017-2019 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. - */ - -#include <hicn/transport/interfaces/socket_consumer.h> -#include <hicn/transport/protocols/manifest_incremental_indexer.h> - -#include <cmath> -#include <deque> - -namespace transport { - -namespace protocol { - -using namespace interface; - -ManifestIncrementalIndexer::ManifestIncrementalIndexer( - interface::ConsumerSocket *icn_socket, TransportProtocol *transport, - Reassembly *reassembly) - : IncrementalIndexer(icn_socket, transport, reassembly), - suffix_strategy_(utils::SuffixStrategyFactory::getSuffixStrategy( - NextSegmentCalculationStrategy::INCREMENTAL, - next_download_suffix_, 0)) {} - -void ManifestIncrementalIndexer::onContentObject( - core::Interest::Ptr &&interest, core::ContentObject::Ptr &&content_object) { - // Check if mainfiest or not - if (content_object->getPayloadType() == PayloadType::MANIFEST) { - onUntrustedManifest(std::move(interest), std::move(content_object)); - } else if (content_object->getPayloadType() == PayloadType::CONTENT_OBJECT) { - onUntrustedContentObject(std::move(interest), std::move(content_object)); - } -} - -void ManifestIncrementalIndexer::onUntrustedManifest( - core::Interest::Ptr &&interest, core::ContentObject::Ptr &&content_object) { - auto ret = verification_manager_->onPacketToVerify(*content_object); - - switch (ret) { - cas |