diff options
author | Mauro Sardara <msardara@cisco.com> | 2020-02-21 11:52:28 +0100 |
---|---|---|
committer | Mauro Sardara <msardara@cisco.com> | 2020-02-26 13:19:16 +0100 |
commit | f4433f28b509a9f67ca85d79000ccf9c2f4b7a24 (patch) | |
tree | 0f754bc9d8222f3ace11849165753acd85be3b38 /libtransport/src | |
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')
-rw-r--r-- | libtransport/src/CMakeLists.txt (renamed from libtransport/src/hicn/transport/CMakeLists.txt) | 26 | ||||
-rw-r--r-- | libtransport/src/config.h.in (renamed from libtransport/src/hicn/transport/config.h.in) | 0 | ||||
-rw-r--r-- | libtransport/src/core/CMakeLists.txt (renamed from libtransport/src/hicn/transport/core/CMakeLists.txt) | 6 | ||||
-rw-r--r-- | libtransport/src/core/connector.cc (renamed from libtransport/src/hicn/transport/core/connector.cc) | 2 | ||||
-rw-r--r-- | libtransport/src/core/connector.h (renamed from libtransport/src/hicn/transport/core/connector.h) | 0 | ||||
-rw-r--r-- | libtransport/src/core/content_object.cc (renamed from libtransport/src/hicn/transport/core/content_object.cc) | 0 | ||||
-rw-r--r-- | libtransport/src/core/facade.h (renamed from libtransport/src/hicn/transport/core/facade.h) | 14 | ||||
-rw-r--r-- | libtransport/src/core/forwarder_interface.h (renamed from libtransport/src/hicn/transport/core/forwarder_interface.h) | 6 | ||||
-rw-r--r-- | libtransport/src/core/hicn_forwarder_interface.cc (renamed from libtransport/src/hicn/transport/core/hicn_forwarder_interface.cc) | 2 | ||||
-rw-r--r-- | libtransport/src/core/hicn_forwarder_interface.h (renamed from libtransport/src/hicn/transport/core/hicn_forwarder_interface.h) | 5 | ||||
-rw-r--r-- | libtransport/src/core/hicn_vapi.c (renamed from libtransport/src/hicn/transport/core/hicn_vapi.c) | 150 | ||||
-rw-r--r-- | libtransport/src/core/hicn_vapi.h (renamed from libtransport/src/hicn/transport/core/hicn_vapi.h) | 0 | ||||
-rw-r--r-- | libtransport/src/core/interest.cc (renamed from libtransport/src/hicn/transport/core/interest.cc) | 0 | ||||
-rw-r--r-- | libtransport/src/core/manifest.cc (renamed from libtransport/src/hicn/transport/core/manifest.cc) | 0 | ||||
-rw-r--r-- | libtransport/src/core/manifest.h (renamed from libtransport/src/hicn/transport/core/manifest.h) | 3 | ||||
-rw-r--r-- | libtransport/src/core/manifest_format.h (renamed from libtransport/src/hicn/transport/core/manifest_format.h) | 2 | ||||
-rw-r--r-- | libtransport/src/core/manifest_format_fixed.cc (renamed from libtransport/src/hicn/transport/core/manifest_format_fixed.cc) | 3 | ||||
-rw-r--r-- | libtransport/src/core/manifest_format_fixed.h (renamed from libtransport/src/hicn/transport/core/manifest_format_fixed.h) | 3 | ||||
-rw-r--r-- | libtransport/src/core/manifest_inline.h (renamed from libtransport/src/hicn/transport/core/manifest_inline.h) | 5 | ||||
-rw-r--r-- | libtransport/src/core/memif_connector.cc (renamed from libtransport/src/hicn/transport/core/memif_connector.cc) | 3 | ||||
-rw-r--r-- | libtransport/src/core/memif_connector.h (renamed from libtransport/src/hicn/transport/core/memif_connector.h) | 9 | ||||
-rw-r--r-- | libtransport/src/core/memif_vapi.c (renamed from libtransport/src/hicn/transport/core/memif_vapi.c) | 57 | ||||
-rw-r--r-- | libtransport/src/core/memif_vapi.h (renamed from libtransport/src/hicn/transport/core/memif_vapi.h) | 0 | ||||
-rw-r--r-- | libtransport/src/core/name.cc (renamed from libtransport/src/hicn/transport/core/name.cc) | 3 | ||||
-rw-r--r-- | libtransport/src/core/packet.cc (renamed from libtransport/src/hicn/transport/core/packet.cc) | 0 | ||||
-rw-r--r-- | libtransport/src/core/pending_interest.cc (renamed from libtransport/src/hicn/transport/core/pending_interest.cc) | 2 | ||||
-rw-r--r-- | libtransport/src/core/pending_interest.h (renamed from libtransport/src/hicn/transport/core/pending_interest.h) | 3 | ||||
-rw-r--r-- | libtransport/src/core/portal.h (renamed from libtransport/src/hicn/transport/core/portal.h) | 9 | ||||
-rw-r--r-- | libtransport/src/core/prefix.cc (renamed from libtransport/src/hicn/transport/core/prefix.cc) | 0 | ||||
-rw-r--r-- | libtransport/src/core/raw_socket_connector.cc (renamed from libtransport/src/hicn/transport/core/raw_socket_connector.cc) | 3 | ||||
-rw-r--r-- | libtransport/src/core/raw_socket_connector.h (renamed from libtransport/src/hicn/transport/core/raw_socket_connector.h) | 3 | ||||
-rw-r--r-- | libtransport/src/core/raw_socket_interface.cc (renamed from libtransport/src/hicn/transport/core/raw_socket_interface.cc) | 3 | ||||
-rw-r--r-- | libtransport/src/core/raw_socket_interface.h (renamed from libtransport/src/hicn/transport/core/raw_socket_interface.h) | 5 | ||||
-rw-r--r-- | libtransport/src/core/tcp_socket_connector.cc (renamed from libtransport/src/hicn/transport/core/tcp_socket_connector.cc) | 5 | ||||
-rw-r--r-- | libtransport/src/core/tcp_socket_connector.h (renamed from libtransport/src/hicn/transport/core/tcp_socket_connector.h) | 3 | ||||
-rw-r--r-- | libtransport/src/core/test/CMakeLists.txt (renamed from libtransport/src/hicn/transport/core/test/CMakeLists.txt) | 0 | ||||
-rw-r--r-- | libtransport/src/core/test/test_core_manifest.cc (renamed from libtransport/src/hicn/transport/core/test/test_core_manifest.cc) | 0 | ||||
-rw-r--r-- | libtransport/src/core/udp_socket_connector.cc (renamed from libtransport/src/hicn/transport/core/udp_socket_connector.cc) | 6 | ||||
-rw-r--r-- | libtransport/src/core/udp_socket_connector.h (renamed from libtransport/src/hicn/transport/core/udp_socket_connector.h) | 3 | ||||
-rw-r--r-- | libtransport/src/core/vpp_forwarder_interface.cc (renamed from libtransport/src/hicn/transport/core/vpp_forwarder_interface.cc) | 39 | ||||
-rw-r--r-- | libtransport/src/core/vpp_forwarder_interface.h (renamed from libtransport/src/hicn/transport/core/vpp_forwarder_interface.h) | 9 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/core/content_object.h | 77 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/core/interest.h | 72 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/core/name.h | 142 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/core/packet.h | 203 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/core/prefix.h | 79 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/errors/CMakeLists.txt | 31 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/errors/errors.h | 24 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/errors/indexing_exception.h | 31 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/errors/invalid_ip_address_exception.h | 31 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/errors/malformed_ahpacket_exception.h | 31 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/errors/malformed_name_exception.h | 31 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/errors/malformed_packet_exception.h | 29 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/errors/not_implemented_exception.h | 30 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/errors/null_pointer_exception.h | 31 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/errors/runtime_exception.h | 32 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/errors/tokenizer_exception.h | 31 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/errors/unexpected_manifest_exception.h | 31 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/http/client_connection.cc | 220 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/http/client_connection.h | 121 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/http/facade.h | 22 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/http/message.h | 70 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/http/request.h | 56 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/http/response.h | 58 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/http/server_acceptor.cc | 110 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/http/server_acceptor.h | 63 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/http/server_publisher.cc | 173 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/http/server_publisher.h | 69 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/interfaces/callbacks.h | 125 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/interfaces/socket_consumer.cc | 862 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/interfaces/socket_consumer.h | 412 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/interfaces/socket_options_default_values.h | 69 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/interfaces/socket_options_keys.h | 113 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/interfaces/socket_producer.cc | 909 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/interfaces/socket_producer.h | 295 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/portability/c_portability.h | 36 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/portability/portability.h | 50 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/portability/win_portability.h | 42 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/protocols/manifest_indexing_manager.cc | 297 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/protocols/statistics.h | 113 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/utils/array.h | 62 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/utils/branch_prediction.h | 27 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/utils/chrono_typedefs.h | 27 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/utils/conversions.h | 37 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/utils/crypto_hash.h | 119 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/utils/crypto_hash_type.h | 31 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/utils/crypto_hasher.h | 68 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/utils/crypto_suite.h | 35 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/utils/daemonizator.h | 30 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/utils/hash.h | 101 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/utils/identity.h | 62 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/utils/key_id.h | 25 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/utils/linux.h | 64 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/utils/literals.h | 55 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/utils/log.h | 1057 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/utils/membuf.h | 921 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/utils/object_pool.h | 89 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/utils/ring_buffer.h | 129 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/utils/signer.h | 90 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/utils/spinlock.h | 53 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/utils/string_tokenizer.h | 35 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/utils/uri.h | 47 | ||||
-rw-r--r-- | libtransport/src/hicn/transport/utils/verifier.h | 103 | ||||
-rw-r--r-- | libtransport/src/http/CMakeLists.txt (renamed from libtransport/src/hicn/transport/http/CMakeLists.txt) | 16 | ||||
-rw-r--r-- | libtransport/src/http/client_connection.cc | 317 | ||||
-rw-r--r-- | libtransport/src/http/request.cc (renamed from libtransport/src/hicn/transport/http/request.cc) | 0 | ||||
-rw-r--r-- | libtransport/src/http/response.cc (renamed from libtransport/src/hicn/transport/http/response.cc) | 0 | ||||
-rw-r--r-- | libtransport/src/implementation/CMakeLists.txt (renamed from libtransport/src/hicn/transport/interfaces/CMakeLists.txt) | 27 | ||||
-rw-r--r-- | libtransport/src/implementation/p2psecure_socket_consumer.cc (renamed from libtransport/src/hicn/transport/interfaces/p2psecure_socket_consumer.cc) | 55 | ||||
-rw-r--r-- | libtransport/src/implementation/p2psecure_socket_consumer.h (renamed from libtransport/src/hicn/transport/interfaces/p2psecure_socket_consumer.h) | 25 | ||||
-rw-r--r-- | libtransport/src/implementation/p2psecure_socket_producer.cc (renamed from libtransport/src/hicn/transport/interfaces/p2psecure_socket_producer.cc) | 52 | ||||
-rw-r--r-- | libtransport/src/implementation/p2psecure_socket_producer.h (renamed from libtransport/src/hicn/transport/interfaces/p2psecure_socket_producer.h) | 33 | ||||
-rw-r--r-- | libtransport/src/implementation/rtc_socket_producer.cc (renamed from libtransport/src/hicn/transport/interfaces/rtc_socket_producer.cc) | 50 | ||||
-rw-r--r-- | libtransport/src/implementation/rtc_socket_producer.h (renamed from libtransport/src/hicn/transport/interfaces/rtc_socket_producer.h) | 23 | ||||
-rw-r--r-- | libtransport/src/implementation/socket.h (renamed from libtransport/src/hicn/transport/interfaces/socket.h) | 11 | ||||
-rw-r--r-- | libtransport/src/implementation/socket_consumer.h | 950 | ||||
-rw-r--r-- | libtransport/src/implementation/socket_producer.h | 1061 | ||||
-rw-r--r-- | libtransport/src/implementation/tls_rtc_socket_producer.cc (renamed from libtransport/src/hicn/transport/interfaces/tls_rtc_socket_producer.cc) | 39 | ||||
-rw-r--r-- | libtransport/src/implementation/tls_rtc_socket_producer.h (renamed from libtransport/src/hicn/transport/interfaces/tls_rtc_socket_producer.h) | 14 | ||||
-rw-r--r-- | libtransport/src/implementation/tls_socket_consumer.cc (renamed from libtransport/src/hicn/transport/interfaces/tls_socket_consumer.cc) | 54 | ||||
-rw-r--r-- | libtransport/src/implementation/tls_socket_consumer.h (renamed from libtransport/src/hicn/transport/interfaces/tls_socket_consumer.h) | 29 | ||||
-rw-r--r-- | libtransport/src/implementation/tls_socket_producer.cc (renamed from libtransport/src/hicn/transport/interfaces/tls_socket_producer.cc) | 52 | ||||
-rw-r--r-- | libtransport/src/implementation/tls_socket_producer.h (renamed from libtransport/src/hicn/transport/interfaces/tls_socket_producer.h) | 20 | ||||
-rw-r--r-- | libtransport/src/interfaces/CMakeLists.txt | 39 | ||||
-rw-r--r-- | libtransport/src/interfaces/callbacks.cc (renamed from libtransport/src/hicn/transport/interfaces/callbacks.cc) | 2 | ||||
-rw-r--r-- | libtransport/src/interfaces/p2psecure_socket_consumer.cc | 32 | ||||
-rw-r--r-- | libtransport/src/interfaces/p2psecure_socket_producer.cc (renamed from libtransport/src/hicn/transport/interfaces/publication_options.h) | 31 | ||||
-rw-r--r-- | libtransport/src/interfaces/rtc_socket_producer.cc (renamed from libtransport/src/hicn/transport/http/default_values.h) | 19 | ||||
-rw-r--r-- | libtransport/src/interfaces/socket_consumer.cc | 196 | ||||
-rw-r--r-- | libtransport/src/interfaces/socket_producer.cc | 198 | ||||
-rw-r--r-- | libtransport/src/interfaces/tls_rtc_socket_producer.cc | 32 | ||||
-rw-r--r-- | libtransport/src/interfaces/tls_rtc_socket_producer.h | 36 | ||||
-rw-r--r-- | libtransport/src/interfaces/tls_socket_consumer.cc (renamed from libtransport/src/hicn/transport/core/payload_type.h) | 20 | ||||
-rw-r--r-- | libtransport/src/interfaces/tls_socket_consumer.h (renamed from libtransport/src/hicn/transport/interfaces/verification_policy.h) | 23 | ||||
-rw-r--r-- | libtransport/src/interfaces/tls_socket_producer.cc | 31 | ||||
-rw-r--r-- | libtransport/src/interfaces/tls_socket_producer.h (renamed from libtransport/src/hicn/transport/protocols/download_observer.h) | 20 | ||||
-rw-r--r-- | libtransport/src/protocols/CMakeLists.txt (renamed from libtransport/src/hicn/transport/protocols/CMakeLists.txt) | 2 | ||||
-rw-r--r-- | libtransport/src/protocols/byte_stream_reassembly.cc (renamed from libtransport/src/hicn/transport/protocols/byte_stream_reassembly.cc) | 17 | ||||
-rw-r--r-- | libtransport/src/protocols/byte_stream_reassembly.h (renamed from libtransport/src/hicn/transport/protocols/byte_stream_reassembly.h) | 4 | ||||
-rw-r--r-- | libtransport/src/protocols/cbr.cc (renamed from libtransport/src/hicn/transport/protocols/cbr.cc) | 7 | ||||
-rw-r--r-- | libtransport/src/protocols/cbr.h (renamed from libtransport/src/hicn/transport/protocols/cbr.h) | 4 | ||||
-rw-r--r-- | libtransport/src/protocols/congestion_window_protocol.h (renamed from libtransport/src/hicn/transport/protocols/congestion_window_protocol.h) | 0 | ||||
-rw-r--r-- | libtransport/src/protocols/consumer.conf (renamed from libtransport/src/hicn/transport/protocols/consumer.conf) | 0 | ||||
-rw-r--r-- | libtransport/src/protocols/data_processing_events.h (renamed from libtransport/src/hicn/transport/protocols/data_processing_events.h) | 0 | ||||
-rw-r--r-- | libtransport/src/protocols/datagram_reassembly.cc (renamed from libtransport/src/hicn/transport/protocols/datagram_reassembly.cc) | 7 | ||||
-rw-r--r-- | libtransport/src/protocols/datagram_reassembly.h (renamed from libtransport/src/hicn/transport/protocols/datagram_reassembly.h) | 4 | ||||
-rw-r--r-- | libtransport/src/protocols/errors.cc (renamed from libtransport/src/hicn/transport/protocols/errors.cc) | 2 | ||||
-rw-r--r-- | libtransport/src/protocols/errors.h (renamed from libtransport/src/hicn/transport/protocols/errors.h) | 0 | ||||
-rw-r--r-- | libtransport/src/protocols/incremental_indexer.cc (renamed from libtransport/src/hicn/transport/protocols/incremental_indexer.cc) | 3 | ||||
-rw-r--r-- | libtransport/src/protocols/incremental_indexer.h (renamed from libtransport/src/hicn/transport/protocols/incremental_indexer.h) | 12 | ||||
-rw-r--r-- | libtransport/src/protocols/indexer.cc (renamed from libtransport/src/hicn/transport/protocols/indexer.cc) | 25 | ||||
-rw-r--r-- | libtransport/src/protocols/indexer.h (renamed from libtransport/src/hicn/transport/protocols/indexer.h) | 6 | ||||
-rw-r--r-- | libtransport/src/protocols/manifest_incremental_indexer.cc (renamed from libtransport/src/hicn/transport/protocols/manifest_incremental_indexer.cc) | 14 | ||||
-rw-r--r-- | libtransport/src/protocols/manifest_incremental_indexer.h (renamed from libtransport/src/hicn/transport/protocols/manifest_incremental_indexer.h) | 11 | ||||
-rw-r--r-- | libtransport/src/protocols/packet_manager.h (renamed from libtransport/src/hicn/transport/protocols/packet_manager.h) | 4 | ||||
-rw-r--r-- | libtransport/src/protocols/protocol.cc (renamed from libtransport/src/hicn/transport/protocols/protocol.cc) | 8 | ||||
-rw-r--r-- | libtransport/src/protocols/protocol.h (renamed from libtransport/src/hicn/transport/protocols/protocol.h) | 23 | ||||
-rw-r--r-- | libtransport/src/protocols/raaqm.cc (renamed from libtransport/src/hicn/transport/protocols/raaqm.cc) | 30 | ||||
-rw-r--r-- | libtransport/src/protocols/raaqm.h (renamed from libtransport/src/hicn/transport/protocols/raaqm.h) | 13 | ||||
-rw-r--r-- | libtransport/src/protocols/raaqm_data_path.cc (renamed from libtransport/src/hicn/transport/protocols/raaqm_data_path.cc) | 3 | ||||
-rw-r--r-- | libtransport/src/protocols/raaqm_data_path.h (renamed from libtransport/src/hicn/transport/protocols/raaqm_data_path.h) | 3 | ||||
-rw-r--r-- | libtransport/src/protocols/rate_estimation.cc (renamed from libtransport/src/hicn/transport/protocols/rate_estimation.cc) | 3 | ||||
-rw-r--r-- | libtransport/src/protocols/rate_estimation.h (renamed from libtransport/src/hicn/transport/protocols/rate_estimation.h) | 9 | ||||
-rw-r--r-- | libtransport/src/protocols/reassembly.cc (renamed from libtransport/src/hicn/transport/protocols/reassembly.cc) | 8 | ||||
-rw-r--r-- | libtransport/src/protocols/reassembly.h (renamed from libtransport/src/hicn/transport/protocols/reassembly.h) | 10 | ||||
-rw-r--r-- | libtransport/src/protocols/rtc.cc (renamed from libtransport/src/hicn/transport/protocols/rtc.cc) | 11 | ||||
-rw-r--r-- | libtransport/src/protocols/rtc.h (renamed from libtransport/src/hicn/transport/protocols/rtc.h) | 14 | ||||
-rw-r--r-- | libtransport/src/protocols/rtc_data_path.cc (renamed from libtransport/src/hicn/transport/protocols/rtc_data_path.cc) | 58 | ||||
-rw-r--r-- | libtransport/src/protocols/rtc_data_path.h (renamed from libtransport/src/hicn/transport/protocols/rtc_data_path.h) | 17 | ||||
-rw-r--r-- | libtransport/src/protocols/test/CMakeLists.txt (renamed from libtransport/src/hicn/transport/protocols/test/CMakeLists.txt) | 0 | ||||
-rw-r--r-- | libtransport/src/protocols/test/test_transport_producer.cc (renamed from libtransport/src/hicn/transport/protocols/test/test_transport_producer.cc) | 0 | ||||
-rw-r--r-- | libtransport/src/protocols/verification_manager.cc (renamed from libtransport/src/hicn/transport/protocols/verification_manager.cc) | 11 | ||||
-rw-r--r-- | libtransport/src/protocols/verification_manager.h (renamed from libtransport/src/hicn/transport/protocols/verification_manager.h) | 12 | ||||
-rw-r--r-- | libtransport/src/security/CMakeLists.txt (renamed from libtransport/src/hicn/transport/portability/CMakeLists.txt) | 16 | ||||
-rw-r--r-- | libtransport/src/security/identity.cc (renamed from libtransport/src/hicn/transport/utils/identity.cc) | 2 | ||||
-rw-r--r-- | libtransport/src/security/signer.cc (renamed from libtransport/src/hicn/transport/utils/signer.cc) | 4 | ||||
-rw-r--r-- | libtransport/src/security/verifier.cc (renamed from libtransport/src/hicn/transport/utils/verifier.cc) | 11 | ||||
-rw-r--r-- | libtransport/src/utils/CMakeLists.txt (renamed from libtransport/src/hicn/transport/utils/CMakeLists.txt) | 31 | ||||
-rw-r--r-- | libtransport/src/utils/content_store.cc (renamed from libtransport/src/hicn/transport/utils/content_store.cc) | 8 | ||||
-rw-r--r-- | libtransport/src/utils/content_store.h (renamed from libtransport/src/hicn/transport/utils/content_store.h) | 1 | ||||
-rw-r--r-- | libtransport/src/utils/daemonizator.cc (renamed from libtransport/src/hicn/transport/utils/daemonizator.cc) | 0 | ||||
-rw-r--r-- | libtransport/src/utils/deadline_timer.h (renamed from libtransport/src/hicn/transport/utils/deadline_timer.h) | 2 | ||||
-rw-r--r-- | libtransport/src/utils/epoll_event_reactor.cc (renamed from libtransport/src/hicn/transport/utils/epoll_event_reactor.cc) | 5 | ||||
-rw-r--r-- | libtransport/src/utils/epoll_event_reactor.h (renamed from libtransport/src/hicn/transport/utils/epoll_event_reactor.h) | 2 | ||||
-rw-r--r-- | libtransport/src/utils/event_reactor.h (renamed from libtransport/src/hicn/transport/utils/event_reactor.h) | 0 | ||||
-rw-r--r-- | libtransport/src/utils/event_thread.h (renamed from libtransport/src/hicn/transport/utils/event_thread.h) | 0 | ||||
-rw-r--r-- | libtransport/src/utils/fd_deadline_timer.h (renamed from libtransport/src/hicn/transport/utils/fd_deadline_timer.h) | 5 | ||||
-rw-r--r-- | libtransport/src/utils/log.cc (renamed from libtransport/src/hicn/transport/utils/log.cc) | 0 | ||||
-rw-r--r-- | libtransport/src/utils/membuf.cc (renamed from libtransport/src/hicn/transport/utils/membuf.cc) | 0 | ||||
-rw-r--r-- | libtransport/src/utils/memory_pool_allocator.h | 152 | ||||
-rw-r--r-- | libtransport/src/utils/min_filter.h (renamed from libtransport/src/hicn/transport/utils/min_filter.h) | 0 | ||||
-rw-r--r-- | libtransport/src/utils/stream_buffer.h (renamed from libtransport/src/hicn/transport/utils/stream_buffer.h) | 0 | ||||
-rw-r--r-- | libtransport/src/utils/string_tokenizer.cc (renamed from libtransport/src/hicn/transport/utils/string_tokenizer.cc) | 0 | ||||
-rw-r--r-- | libtransport/src/utils/suffix_strategy.h (renamed from libtransport/src/hicn/transport/utils/suffix_strategy.h) | 3 | ||||
-rw-r--r-- | libtransport/src/utils/test.h (renamed from libtransport/src/hicn/transport/utils/test.h) | 0 | ||||
-rw-r--r-- | libtransport/src/utils/uri.cc (renamed from libtransport/src/hicn/transport/utils/uri.cc) | 0 |
196 files changed, 3790 insertions, 9194 deletions
diff --git a/libtransport/src/hicn/transport/CMakeLists.txt b/libtransport/src/CMakeLists.txt index 4bdb3c1e7..a182998e3 100644 --- a/libtransport/src/hicn/transport/CMakeLists.txt +++ b/libtransport/src/CMakeLists.txt @@ -18,18 +18,18 @@ 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(security) +add_subdirectory(implementation) add_subdirectory(utils) +add_subdirectory(http) include(Packager) extract_version() -configure_file("config.h.in" "config.h" @ONLY) +configure_file("config.h.in" "hicn/transport/config.h" @ONLY) install( - FILES ${CMAKE_CURRENT_BINARY_DIR}/config.h + FILES ${CMAKE_CURRENT_BINARY_DIR}/hicn/transport/config.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/hicn/transport COMPONENT lib${LIBTRANSPORT}-dev ) @@ -37,13 +37,13 @@ install( 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}/../.. + ${CMAKE_CURRENT_SOURCE_DIR}/ + ${CMAKE_CURRENT_BINARY_DIR}/ ) set(LIBTRANSPORT_INCLUDE_DIRS - ${CMAKE_CURRENT_SOURCE_DIR}/../../ - ${CMAKE_CURRENT_BINARY_DIR}/../../ + ${CMAKE_CURRENT_BINARY_DIR} + ${LIBTRANSPORT_INCLUDE_DIRS} "" CACHE INTERNAL "" FORCE ) @@ -64,11 +64,11 @@ if (DISABLE_SHARED_LIBRARIES) build_library(${LIBTRANSPORT} STATIC SOURCES ${SOURCE_FILES} ${HEADER_FILES} - INSTALL_HEADERS ${HEADER_FILES} + INSTALL_HEADERS ${LIBHICNTRANSPORT_TO_INSTALL_HEADER_FILES} LINK_LIBRARIES ${LIBRARIES} DEPENDS ${DEPENDENCIES} COMPONENT lib${LIBTRANSPORT} - INCLUDE_DIRS ${LIBTRANSPORT_INTERNAL_INCLUDE_DIRS} + INCLUDE_DIRS ${LIBTRANSPORT_INTERNAL_INCLUDE_DIRS} ${LIBTRANSPORT_INCLUDE_DIRS} INSTALL_ROOT_DIR hicn/transport DEFINITIONS ${COMPILER_DEFINITIONS} ) @@ -76,11 +76,11 @@ else () build_library(${LIBTRANSPORT} STATIC SHARED SOURCES ${SOURCE_FILES} ${HEADER_FILES} - INSTALL_HEADERS ${HEADER_FILES} + INSTALL_HEADERS ${LIBHICNTRANSPORT_TO_INSTALL_HEADER_FILES} LINK_LIBRARIES ${LIBRARIES} DEPENDS ${DEPENDENCIES} COMPONENT lib${LIBTRANSPORT} - INCLUDE_DIRS ${LIBTRANSPORT_INTERNAL_INCLUDE_DIRS} + INCLUDE_DIRS ${LIBTRANSPORT_INTERNAL_INCLUDE_DIRS} ${LIBTRANSPORT_INCLUDE_DIRS} INSTALL_ROOT_DIR hicn/transport DEFINITIONS ${COMPILER_DEFINITIONS} ) diff --git a/libtransport/src/hicn/transport/config.h.in b/libtransport/src/config.h.in index 4e9a0f262..4e9a0f262 100644 --- a/libtransport/src/hicn/transport/config.h.in +++ b/libtransport/src/config.h.in diff --git a/libtransport/src/hicn/transport/core/CMakeLists.txt b/libtransport/src/core/CMakeLists.txt index 8439fdf45..12ef9cfe4 100644 --- a/libtransport/src/hicn/transport/core/CMakeLists.txt +++ b/libtransport/src/core/CMakeLists.txt @@ -14,19 +14,13 @@ 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 diff --git a/libtransport/src/hicn/transport/core/connector.cc b/libtransport/src/core/connector.cc index fc271574c..63919537d 100644 --- a/libtransport/src/hicn/transport/core/connector.cc +++ b/libtransport/src/core/connector.cc @@ -13,7 +13,7 @@ * limitations under the License. */ -#include <hicn/transport/core/connector.h> +#include <core/connector.h> namespace transport { diff --git a/libtransport/src/hicn/transport/core/connector.h b/libtransport/src/core/connector.h index f2bbe5dcd..f2bbe5dcd 100644 --- a/libtransport/src/hicn/transport/core/connector.h +++ b/libtransport/src/core/connector.h diff --git a/libtransport/src/hicn/transport/core/content_object.cc b/libtransport/src/core/content_object.cc index 6cbcdb29e..6cbcdb29e 100644 --- a/libtransport/src/hicn/transport/core/content_object.cc +++ b/libtransport/src/core/content_object.cc diff --git a/libtransport/src/hicn/transport/core/facade.h b/libtransport/src/core/facade.h index 27e738e62..04f643f63 100644 --- a/libtransport/src/hicn/transport/core/facade.h +++ b/libtransport/src/core/facade.h @@ -15,17 +15,17 @@ #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> +#include <core/forwarder_interface.h> +#include <core/hicn_forwarder_interface.h> +#include <core/manifest_format_fixed.h> +#include <core/manifest_inline.h> +#include <core/portal.h> #ifdef __linux__ #ifndef __ANDROID__ -#include <hicn/transport/core/raw_socket_interface.h> +#include <core/raw_socket_interface.h> #ifdef __vpp__ -#include <hicn/transport/core/vpp_forwarder_interface.h> +#include <core/vpp_forwarder_interface.h> #endif #endif #endif diff --git a/libtransport/src/hicn/transport/core/forwarder_interface.h b/libtransport/src/core/forwarder_interface.h index 63b4a2eda..3e70e221d 100644 --- a/libtransport/src/hicn/transport/core/forwarder_interface.h +++ b/libtransport/src/core/forwarder_interface.h @@ -15,11 +15,10 @@ #pragma once +#include <core/udp_socket_connector.h> #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> @@ -50,8 +49,7 @@ class ForwarderInterface { inet6_address_({}), mtu_(1500), output_interface_(""), - content_store_reserved_(standard_cs_reserved) { - } + content_store_reserved_(standard_cs_reserved) {} public: virtual ~ForwarderInterface() {} diff --git a/libtransport/src/hicn/transport/core/hicn_forwarder_interface.cc b/libtransport/src/core/hicn_forwarder_interface.cc index 2a02a2ba8..810daba3a 100644 --- a/libtransport/src/hicn/transport/core/hicn_forwarder_interface.cc +++ b/libtransport/src/core/hicn_forwarder_interface.cc @@ -13,7 +13,7 @@ * limitations under the License. */ -#include <hicn/transport/core/hicn_forwarder_interface.h> +#include <core/hicn_forwarder_interface.h> union AddressLight { uint32_t ipv4; diff --git a/libtransport/src/hicn/transport/core/hicn_forwarder_interface.h b/libtransport/src/core/hicn_forwarder_interface.h index b11841b69..6969f4a6b 100644 --- a/libtransport/src/hicn/transport/core/hicn_forwarder_interface.h +++ b/libtransport/src/core/hicn_forwarder_interface.h @@ -15,9 +15,10 @@ #pragma once -#include <hicn/transport/core/forwarder_interface.h> #include <hicn/transport/core/prefix.h> -#include <hicn/transport/core/udp_socket_connector.h> + +#include <core/forwarder_interface.h> +#include <core/udp_socket_connector.h> #include <deque> diff --git a/libtransport/src/hicn/transport/core/hicn_vapi.c b/libtransport/src/core/hicn_vapi.c index aea08f31c..d19e36346 100644 --- a/libtransport/src/hicn/transport/core/hicn_vapi.c +++ b/libtransport/src/core/hicn_vapi.c @@ -17,9 +17,10 @@ #ifdef __vpp__ -#include <hicn/transport/core/hicn_vapi.h> #include <hicn/transport/utils/log.h> +#include <core/hicn_vapi.h> + #define HICN_VPP_PLUGIN #include <hicn/name.h> #undef HICN_VPP_PLUGIN @@ -30,13 +31,13 @@ #include <vlibmemory/api.h> #include <vppinfra/error.h> +#include <vnet/fib/fib_types.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> +#include <vpp_plugins/hicn/error.h> ///////////////////////////////////////////////////// const char *HICN_ERROR_STRING[] = { @@ -46,51 +47,50 @@ const char *HICN_ERROR_STRING[] = { }; ///////////////////////////////////////////////////// -/*********************** Missing Symbol in vpp libraries *************************/ -u8 * -format_vl_api_address_union (u8 * s, va_list * args) -{ - return NULL; -} +/*********************** 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; +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; + 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)); + 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)); + 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) { - +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); + 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)); + 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)); + 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; @@ -98,26 +98,24 @@ int hicn_vapi_register_prod_app( 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); + 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; +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) { +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); + vapi_msg_hicn_api_face_prod_del *msg = vapi_alloc_hicn_api_face_prod_del(ctx); msg->payload.faceid = input_params->face_id; @@ -126,22 +124,22 @@ int hicn_vapi_face_prod_del( 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; +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; + 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)); + 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; @@ -149,36 +147,33 @@ static vapi_error_e register_cons_app_cb(vapi_ctx_t ctx, 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) { - +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); + 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); + 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; +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) { - +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); + vapi_msg_hicn_api_face_cons_del *msg = vapi_alloc_hicn_api_face_cons_del(ctx); msg->payload.faceid = input_params->face_id; @@ -187,26 +182,23 @@ int hicn_vapi_face_cons_del( 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; +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) { - +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); + 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)); + 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; diff --git a/libtransport/src/hicn/transport/core/hicn_vapi.h b/libtransport/src/core/hicn_vapi.h index f2718e6f5..f2718e6f5 100644 --- a/libtransport/src/hicn/transport/core/hicn_vapi.h +++ b/libtransport/src/core/hicn_vapi.h diff --git a/libtransport/src/hicn/transport/core/interest.cc b/libtransport/src/core/interest.cc index 166632f0a..166632f0a 100644 --- a/libtransport/src/hicn/transport/core/interest.cc +++ b/libtransport/src/core/interest.cc diff --git a/libtransport/src/hicn/transport/core/manifest.cc b/libtransport/src/core/manifest.cc index 3f890f3d0..3f890f3d0 100644 --- a/libtransport/src/hicn/transport/core/manifest.cc +++ b/libtransport/src/core/manifest.cc diff --git a/libtransport/src/hicn/transport/core/manifest.h b/libtransport/src/core/manifest.h index 9650de94d..b4875bf22 100644 --- a/libtransport/src/hicn/transport/core/manifest.h +++ b/libtransport/src/core/manifest.h @@ -16,9 +16,10 @@ #pragma once #include <hicn/transport/core/content_object.h> -#include <hicn/transport/core/manifest_format.h> #include <hicn/transport/core/name.h> +#include <core/manifest_format.h> + #include <set> namespace transport { diff --git a/libtransport/src/hicn/transport/core/manifest_format.h b/libtransport/src/core/manifest_format.h index 9b6777270..f95d19aa8 100644 --- a/libtransport/src/hicn/transport/core/manifest_format.h +++ b/libtransport/src/core/manifest_format.h @@ -16,7 +16,7 @@ #pragma once #include <hicn/transport/core/name.h> -#include <hicn/transport/utils/crypto_hasher.h> +#include <hicn/transport/security/crypto_hasher.h> #include <cinttypes> #include <type_traits> diff --git a/libtransport/src/hicn/transport/core/manifest_format_fixed.cc b/libtransport/src/core/manifest_format_fixed.cc index f5e31d784..4073a5d26 100644 --- a/libtransport/src/hicn/transport/core/manifest_format_fixed.cc +++ b/libtransport/src/core/manifest_format_fixed.cc @@ -13,10 +13,11 @@ * limitations under the License. */ -#include <hicn/transport/core/manifest_format_fixed.h> #include <hicn/transport/core/packet.h> #include <hicn/transport/utils/literals.h> +#include <core/manifest_format_fixed.h> + namespace transport { namespace core { diff --git a/libtransport/src/hicn/transport/core/manifest_format_fixed.h b/libtransport/src/core/manifest_format_fixed.h index 2c6e2bced..9cacb3bc2 100644 --- a/libtransport/src/hicn/transport/core/manifest_format_fixed.h +++ b/libtransport/src/core/manifest_format_fixed.h @@ -15,9 +15,10 @@ #pragma once -#include <hicn/transport/core/manifest_format.h> #include <hicn/transport/core/packet.h> +#include <core/manifest_format.h> + #include <string> namespace transport { diff --git a/libtransport/src/hicn/transport/core/manifest_inline.h b/libtransport/src/core/manifest_inline.h index 385e43af3..235c6f3a0 100644 --- a/libtransport/src/hicn/transport/core/manifest_inline.h +++ b/libtransport/src/core/manifest_inline.h @@ -15,9 +15,10 @@ #pragma once -#include <hicn/transport/core/manifest.h> -#include <hicn/transport/core/manifest_format.h> #include <hicn/transport/portability/portability.h> + +#include <core/manifest.h> +#include <core/manifest_format.h> #include <set> namespace transport { diff --git a/libtransport/src/hicn/transport/core/memif_connector.cc b/libtransport/src/core/memif_connector.cc index 5e37c882a..2292e9b41 100644 --- a/libtransport/src/hicn/transport/core/memif_connector.cc +++ b/libtransport/src/core/memif_connector.cc @@ -13,9 +13,10 @@ * limitations under the License. */ -#include <hicn/transport/core/memif_connector.h> #include <hicn/transport/errors/not_implemented_exception.h> +#include <core/memif_connector.h> + #ifdef __vpp__ #include <sys/epoll.h> diff --git a/libtransport/src/hicn/transport/core/memif_connector.h b/libtransport/src/core/memif_connector.h index bf4e2d56c..aafef1e56 100644 --- a/libtransport/src/hicn/transport/core/memif_connector.h +++ b/libtransport/src/core/memif_connector.h @@ -16,13 +16,14 @@ #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 <core/connector.h> +//#include <hicn/transport/core/hicn_vapi.h> +#include <utils/epoll_event_reactor.h> +#include <utils/fd_deadline_timer.h> + #include <asio.hpp> #include <deque> #include <mutex> diff --git a/libtransport/src/hicn/transport/core/memif_vapi.c b/libtransport/src/core/memif_vapi.c index 11cf42441..ea3513306 100644 --- a/libtransport/src/hicn/transport/core/memif_vapi.c +++ b/libtransport/src/core/memif_vapi.c @@ -16,28 +16,26 @@ #ifdef __vpp__ -#include <vapi/vapi_safe.h> -#include <vppinfra/clib.h> -#include <hicn/transport/core/memif_vapi.h> +#include <core/memif_vapi.h> + #include <fcntl.h> #include <inttypes.h> #include <semaphore.h> #include <string.h> #include <sys/stat.h> +#include <vapi/vapi_safe.h> +#include <vppinfra/clib.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, +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 { + } else { return rv; } @@ -48,35 +46,30 @@ static vapi_error_e memif_details_cb(vapi_ctx_t ctx, return rv; } -int memif_vapi_get_next_memif_id(vapi_ctx_t ctx, - uint32_t *memif_id) { +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); + 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) { +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; + 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, +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); + vapi_msg_memif_create *msg = vapi_alloc_memif_create(ctx); int ret = 0; if (input_params->socket_id == ~0) { @@ -113,26 +106,22 @@ int memif_vapi_create_memif(vapi_ctx_t ctx, msg->payload.buffer_size = input_params->buffer_size; ret = vapi_memif_create(ctx, msg, memif_create_cb, output_params); - END: +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; - +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) { +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); + vapi_msg_memif_delete *msg = vapi_alloc_memif_delete(ctx); msg->payload.sw_if_index = sw_if_index; diff --git a/libtransport/src/hicn/transport/core/memif_vapi.h b/libtransport/src/core/memif_vapi.h index c045cf093..c045cf093 100644 --- a/libtransport/src/hicn/transport/core/memif_vapi.h +++ b/libtransport/src/core/memif_vapi.h diff --git a/libtransport/src/hicn/transport/core/name.cc b/libtransport/src/core/name.cc index 85e2b8565..811e93b87 100644 --- a/libtransport/src/hicn/transport/core/name.cc +++ b/libtransport/src/core/name.cc @@ -13,13 +13,14 @@ * 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> +#include <core/manifest_format.h> + namespace transport { namespace core { diff --git a/libtransport/src/hicn/transport/core/packet.cc b/libtransport/src/core/packet.cc index 817f8de66..817f8de66 100644 --- a/libtransport/src/hicn/transport/core/packet.cc +++ b/libtransport/src/core/packet.cc diff --git a/libtransport/src/hicn/transport/core/pending_interest.cc b/libtransport/src/core/pending_interest.cc index dbbd2c83e..fbe98cab5 100644 --- a/libtransport/src/hicn/transport/core/pending_interest.cc +++ b/libtransport/src/core/pending_interest.cc @@ -13,7 +13,7 @@ * limitations under the License. */ -#include <hicn/transport/core/pending_interest.h> +#include <core/pending_interest.h> namespace transport { diff --git a/libtransport/src/hicn/transport/core/pending_interest.h b/libtransport/src/core/pending_interest.h index c481cc200..87fed5073 100644 --- a/libtransport/src/hicn/transport/core/pending_interest.h +++ b/libtransport/src/core/pending_interest.h @@ -20,7 +20,8 @@ #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 <utils/deadline_timer.h> #include <asio/steady_timer.hpp> diff --git a/libtransport/src/hicn/transport/core/portal.h b/libtransport/src/core/portal.h index c6e11ada6..d7c463dfd 100644 --- a/libtransport/src/hicn/transport/core/portal.h +++ b/libtransport/src/core/portal.h @@ -17,18 +17,19 @@ #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> +#include <core/forwarder_interface.h> +#include <core/pending_interest.h> +#include <core/udp_socket_connector.h> + #ifdef __vpp__ -#include <hicn/transport/core/memif_connector.h> +#include <core/memif_connector.h> #endif #include <asio.hpp> diff --git a/libtransport/src/hicn/transport/core/prefix.cc b/libtransport/src/core/prefix.cc index 59898ab70..59898ab70 100644 --- a/libtransport/src/hicn/transport/core/prefix.cc +++ b/libtransport/src/core/prefix.cc diff --git a/libtransport/src/hicn/transport/core/raw_socket_connector.cc b/libtransport/src/core/raw_socket_connector.cc index 0e1743671..4d780959b 100644 --- a/libtransport/src/hicn/transport/core/raw_socket_connector.cc +++ b/libtransport/src/core/raw_socket_connector.cc @@ -13,10 +13,11 @@ * 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 <core/raw_socket_connector.h> + #include <net/if.h> #include <netdb.h> #include <stdio.h> diff --git a/libtransport/src/hicn/transport/core/raw_socket_connector.h b/libtransport/src/core/raw_socket_connector.h index fe9ceb227..1d4e9cb39 100644 --- a/libtransport/src/hicn/transport/core/raw_socket_connector.h +++ b/libtransport/src/core/raw_socket_connector.h @@ -16,9 +16,10 @@ #pragma once #include <hicn/transport/config.h> -#include <hicn/transport/core/connector.h> #include <hicn/transport/core/name.h> +#include <core/connector.h> + #include <linux/if_packet.h> #include <net/ethernet.h> #include <sys/socket.h> diff --git a/libtransport/src/hicn/transport/core/raw_socket_interface.cc b/libtransport/src/core/raw_socket_interface.cc index bb4e083e1..7ee2a844d 100644 --- a/libtransport/src/hicn/transport/core/raw_socket_interface.cc +++ b/libtransport/src/core/raw_socket_interface.cc @@ -13,9 +13,10 @@ * limitations under the License. */ -#include <hicn/transport/core/raw_socket_interface.h> #include <hicn/transport/utils/linux.h> +#include <core/raw_socket_interface.h> + #include <fstream> namespace transport { diff --git a/libtransport/src/hicn/transport/core/raw_socket_interface.h b/libtransport/src/core/raw_socket_interface.h index ac48e5874..c06d14637 100644 --- a/libtransport/src/hicn/transport/core/raw_socket_interface.h +++ b/libtransport/src/core/raw_socket_interface.h @@ -15,9 +15,10 @@ #pragma once -#include <hicn/transport/core/forwarder_interface.h> #include <hicn/transport/core/prefix.h> -#include <hicn/transport/core/raw_socket_connector.h> + +#include <core/forwarder_interface.h> +#include <core/raw_socket_connector.h> #include <atomic> #include <deque> diff --git a/libtransport/src/hicn/transport/core/tcp_socket_connector.cc b/libtransport/src/core/tcp_socket_connector.cc index c82373ae1..58df8fb08 100644 --- a/libtransport/src/hicn/transport/core/tcp_socket_connector.cc +++ b/libtransport/src/core/tcp_socket_connector.cc @@ -13,10 +13,11 @@ * limitations under the License. */ +#include <core/tcp_socket_connector.h> #ifdef _WIN32 -#include <hicn/transport/portability/win_portability.h> +#include <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> diff --git a/libtransport/src/hicn/transport/core/tcp_socket_connector.h b/libtransport/src/core/tcp_socket_connector.h index d755b5e86..c57123e9f 100644 --- a/libtransport/src/hicn/transport/core/tcp_socket_connector.h +++ b/libtransport/src/core/tcp_socket_connector.h @@ -16,10 +16,11 @@ #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 <core/connector.h> + #include <asio.hpp> #include <asio/steady_timer.hpp> #include <deque> diff --git a/libtransport/src/hicn/transport/core/test/CMakeLists.txt b/libtransport/src/core/test/CMakeLists.txt index 48c50e9b0..48c50e9b0 100644 --- a/libtransport/src/hicn/transport/core/test/CMakeLists.txt +++ b/libtransport/src/core/test/CMakeLists.txt diff --git a/libtransport/src/hicn/transport/core/test/test_core_manifest.cc b/libtransport/src/core/test/test_core_manifest.cc index 58563d8f9..58563d8f9 100644 --- a/libtransport/src/hicn/transport/core/test/test_core_manifest.cc +++ b/libtransport/src/core/test/test_core_manifest.cc diff --git a/libtransport/src/hicn/transport/core/udp_socket_connector.cc b/libtransport/src/core/udp_socket_connector.cc index 99f47fedf..ec59c2e64 100644 --- a/libtransport/src/hicn/transport/core/udp_socket_connector.cc +++ b/libtransport/src/core/udp_socket_connector.cc @@ -14,13 +14,15 @@ */ #ifdef _WIN32 -#include <hicn/transport/portability/win_portability.h> +#include <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 <core/udp_socket_connector.h> + #include <thread> #include <vector> diff --git a/libtransport/src/hicn/transport/core/udp_socket_connector.h b/libtransport/src/core/udp_socket_connector.h index 7c5dbaf10..5fdb6aeec 100644 --- a/libtransport/src/hicn/transport/core/udp_socket_connector.h +++ b/libtransport/src/core/udp_socket_connector.h @@ -16,10 +16,11 @@ #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 <core/connector.h> + #include <asio.hpp> #include <asio/steady_timer.hpp> #include <deque> diff --git a/libtransport/src/hicn/transport/core/vpp_forwarder_interface.cc b/libtransport/src/core/vpp_forwarder_interface.cc index 9e701bf80..7b4298592 100644 --- a/libtransport/src/hicn/transport/core/vpp_forwarder_interface.cc +++ b/libtransport/src/core/vpp_forwarder_interface.cc @@ -17,10 +17,9 @@ #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> +#include <core/hicn_vapi.h> +#include <core/memif_vapi.h> +#include <core/vpp_forwarder_interface.h> extern "C" { #include <memif/libmemif.h> @@ -44,8 +43,7 @@ VPPForwarderInterface::VPPForwarderInterface(MemifConnector &connector) sw_if_index_(~0), face_id1_(~0), face_id2_(~0), - is_consumer_(false){ - } + is_consumer_(false) {} VPPForwarderInterface::~VPPForwarderInterface() {} @@ -55,8 +53,8 @@ VPPForwarderInterface::~VPPForwarderInterface() {} uint32_t VPPForwarderInterface::getMemifConfiguration() { memif_create_params_t input_params = {0}; - int ret = memif_vapi_get_next_memif_id( - VPPForwarderInterface::sock_, &memif_id_); + int ret = + memif_vapi_get_next_memif_id(VPPForwarderInterface::sock_, &memif_id_); if (ret < 0) { throw errors::RuntimeException( @@ -73,8 +71,8 @@ uint32_t VPPForwarderInterface::getMemifConfiguration() { memif_output_params_t output_params = {0}; - ret = memif_vapi_create_memif(VPPForwarderInterface::sock_, - &input_params, &output_params); + ret = memif_vapi_create_memif(VPPForwarderInterface::sock_, &input_params, + &output_params); if (ret < 0) { throw errors::RuntimeException( @@ -94,10 +92,8 @@ void VPPForwarderInterface::consumerConnection() { output.src6 = &ip6_address; input.swif = sw_if_index_; - - - int ret = hicn_vapi_register_cons_app(VPPForwarderInterface::sock_, - &input, &output); + int ret = hicn_vapi_register_cons_app(VPPForwarderInterface::sock_, &input, + &output); if (ret < 0) { throw errors::RuntimeException(hicn_vapi_get_error_string(ret)); @@ -106,7 +102,6 @@ void VPPForwarderInterface::consumerConnection() { 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); @@ -156,8 +151,8 @@ void VPPForwarderInterface::registerRoute(Prefix &prefix) { input.prefix->len = addr.len; input.cs_reserved = content_store_reserved_; - int ret = hicn_vapi_register_prod_app( - VPPForwarderInterface::sock_, &input, &output); + int ret = hicn_vapi_register_prod_app(VPPForwarderInterface::sock_, &input, + &output); if (ret < 0) { throw errors::RuntimeException(hicn_vapi_get_error_string(ret)); @@ -174,8 +169,7 @@ void VPPForwarderInterface::registerRoute(Prefix &prefix) { params.prefix->len = addr.len; params.face_id = face_id1_; - int ret = hicn_vapi_register_route(VPPForwarderInterface::sock_, - ¶ms); + int ret = hicn_vapi_register_route(VPPForwarderInterface::sock_, ¶ms); if (ret < 0) { throw errors::RuntimeException(hicn_vapi_get_error_string(ret)); @@ -193,16 +187,15 @@ void VPPForwarderInterface::closeConnection() { hicn_vapi_face_cons_del(VPPForwarderInterface::sock_, ¶ms); params.face_id = face_id2_; hicn_vapi_face_cons_del(VPPForwarderInterface::sock_, ¶ms); - } - else { + } 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_); + 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_); } diff --git a/libtransport/src/hicn/transport/core/vpp_forwarder_interface.h b/libtransport/src/core/vpp_forwarder_interface.h index 9f8000828..eb759f8bc 100644 --- a/libtransport/src/hicn/transport/core/vpp_forwarder_interface.h +++ b/libtransport/src/core/vpp_forwarder_interface.h @@ -19,6 +19,8 @@ #ifdef __vpp__ +#include <hicn/transport/core/prefix.h> + #ifdef always_inline #undef always_inline #endif @@ -26,9 +28,8 @@ 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 <core/forwarder_interface.h> +#include <core/memif_connector.h> #include <deque> @@ -72,7 +73,7 @@ class VPPForwarderInterface uint32_t memif_id_; uint32_t sw_if_index_; - //A consumer socket in vpp has two faces (ipv4 and ipv6) + // A consumer socket in vpp has two faces (ipv4 and ipv6) uint32_t face_id1_; uint32_t face_id2_; bool is_consumer_; 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 5af548fe4..000000000 --- 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/interest.h b/libtransport/src/hicn/transport/core/interest.h deleted file mode 100644 index 48c833a73..000000000 --- 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/name.h b/libtransport/src/hicn/transport/core/name.h deleted file mode 100644 index ea72797ad..000000000 --- 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.h b/libtransport/src/hicn/transport/core/packet.h deleted file mode 100644 index 35c8606c9..000000000 --- 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/prefix.h b/libtransport/src/hicn/transport/core/prefix.h deleted file mode 100644 index 47971acaf..000000000 --- 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/errors/CMakeLists.txt b/libtransport/src/hicn/transport/errors/CMakeLists.txt deleted file mode 100644 index 7b0d1332d..000000000 --- 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 512e35736..000000000 --- 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 731314f0e..000000000 --- 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 60226f576..000000000 --- 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 f0cfe0b82..000000000 --- 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 4ef45d2e8..000000000 --- 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 ec5c97e6e..000000000 --- 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 e9869163d..000000000 --- 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 bd06485ed..000000000 --- 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 ba5128a7e..000000000 --- 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 76eda838e..000000000 --- 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 6f71471e4..000000000 --- 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/client_connection.cc b/libtransport/src/hicn/transport/http/client_connection.cc deleted file mode 100644 index bd21bc448..000000000 --- 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 e93a37111..000000000 --- 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/facade.h b/libtransport/src/hicn/transport/http/facade.h deleted file mode 100644 index 1551ede3a..000000000 --- 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 b8756224f..000000000 --- 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.h b/libtransport/src/hicn/transport/http/request.h deleted file mode 100644 index 54904d696..000000000 --- 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.h b/libtransport/src/hicn/transport/http/response.h deleted file mode 100644 index bab41acb8..000000000 --- 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 e478dfcd4..000000000 --- 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 6ed58f70e..000000000 --- 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 b4deb5333..000000000 --- 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 33d596f63..000000000 --- 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/callbacks.h b/libtransport/src/hicn/transport/interfaces/callbacks.h deleted file mode 100644 index 9d3d57992..000000000 --- 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/socket_consumer.cc b/libtransport/src/hicn/transport/interfaces/socket_consumer.cc deleted file mode 100644 index b2c054947..000000000 --- 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 48a594adf..000000000 --- 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 bcf103b8c..000000000 --- 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 a38131271..000000000 --- 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 26a7208b6..000000000 --- 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 5f360f2ce..000000000 --- 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/portability/c_portability.h b/libtransport/src/hicn/transport/portability/c_portability.h deleted file mode 100644 index 71e976a81..000000000 --- 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 1d97a346e..000000000 --- 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 65d949291..000000000 --- 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/manifest_indexing_manager.cc b/libtransport/src/hicn/transport/protocols/manifest_indexing_manager.cc deleted file mode 100644 index 5bf9c89f7..000000000 --- a/libtransport/src/hicn/transport/protocols/manifest_indexing_manager.cc +++ /dev/null @@ -1,297 +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_indexing_manager.h> - -#include <cmath> -#include <deque> - -namespace transport { - -namespace protocol { - -using namespace interface; - -ManifestIndexManager::ManifestIndexManager( - interface::ConsumerSocket *icn_socket, TransportProtocol *next_interest) - : IncrementalIndexManager(icn_socket), - PacketManager<Interest>(1024), - next_to_retrieve_segment_(suffix_queue_.end()), - suffix_manifest_(core::NextSegmentCalculationStrategy::INCREMENTAL, 0), - next_reassembly_segment_( - core::NextSegmentCalculationStrategy::INCREMENTAL, 1, true), - ignored_segments_(), - next_interest_(next_interest) {} - -bool ManifestIndexManager::onManifest( - core::ContentObject::Ptr &&content_object) { - auto manifest = - std::make_unique<ContentObjectManifest>(std::move(*content_object)); - bool manifest_verified = verification_manager_->onPacketToVerify(*manifest); - - if (manifest_verified) { - manifest->decode(); - - if (TRANSPORT_EXPECT_FALSE(manifest->getVersion() != - core::ManifestVersion::VERSION_1)) { - throw errors::RuntimeException("Received manifest with unknown version."); - } - - switch (manifest->getManifestType()) { - case core::ManifestType::INLINE_MANIFEST: { - auto _it = manifest->getSuffixList().begin(); - auto _end = manifest->getSuffixList().end(); - size_t nb_segments = std::distance(_it, _end); - final_suffix_ = manifest->getFinalBlockNumber(); // final block number - - TRANSPORT_LOGD("Received manifest %u", - manifest->getWritableName().getSuffix()); - suffix_hash_map_[_it->first] = - std::make_pair(std::vector<uint8_t>(_it->second, _it->second + 32), - manifest->getHashAlgorithm()); - suffix_queue_.push_back(_it->first); - - // If the transport protocol finished the list of segments to retrieve, - // reset the next_to_retrieve_segment_ iterator to the next segment - // provided by this manifest. - if (TRANSPORT_EXPECT_FALSE(next_to_retrieve_segment_ == - suffix_queue_.end())) { - next_to_retrieve_segment_ = --suffix_queue_.end(); - } - - std::advance(_it, 1); - for (; _it != _end; _it++) { - suffix_hash_map_[_it->first] = std::make_pair( - std::vector<uint8_t>(_it->second, _it->second + 32), - manifest->getHashAlgorithm()); - suffix_queue_.push_back(_it->first); - } - - if (TRANSPORT_EXPECT_FALSE(manifest->getName().getSuffix()) == 0) { - core::NextSegmentCalculationStrategy strategy = - manifest->getNextSegmentCalculationStrategy(); - - suffix_manifest_.reset(0); - suffix_manifest_.setNbSegments(nb_segments); - suffix_manifest_.setSuffixStrategy(strategy); - TRANSPORT_LOGD("Capacity of 1st manifest %zu", - suffix_manifest_.getNbSegments()); - - next_reassembly_segment_.reset(*suffix_queue_.begin()); - next_reassembly_segment_.setNbSegments(nb_segments); - suffix_manifest_.setSuffixStrategy(strategy); - } - - // If the manifest is not full, we add the suffixes of missing segments - // to the list of segments to ignore when computing the next reassembly - // index. - if (TRANSPORT_EXPECT_FALSE( - suffix_manifest_.getNbSegments() - nb_segments > 0)) { - auto start = manifest->getSuffixList().begin(); - auto last = --_end; - for (uint32_t i = last->first + 1; - i < start->first + suffix_manifest_.getNbSegments(); i++) { - ignored_segments_.push_back(i); - } - } - - if (TRANSPORT_EXPECT_FALSE(manifest->isFinalManifest()) == 0) { - fillWindow(manifest->getWritableName(), - manifest->getName().getSuffix()); - } - - break; - } - case core::ManifestType::FLIC_MANIFEST: { - throw errors::NotImplementedException(); - } - case core::ManifestType::FINAL_CHUNK_NUMBER: { - throw errors::NotImplementedException(); - } - } - } - - return manifest_verified; -} - -void ManifestIndexManager::onManifestReceived(Interest::Ptr &&i, - ContentObject::Ptr &&c) { - onManifest(std::move(c)); - if (next_interest_) { - next_interest_->scheduleNextInterests(); - } -} - -void ManifestIndexManager::onManifestTimeout(Interest::Ptr &&i) { - const Name &n = i->getName(); - uint32_t segment = n.getSuffix(); - - if (segment > final_suffix_) { - return; - } - - TRANSPORT_LOGD("Timeout on manifest %u", segment); - // Get portal - std::shared_ptr<interface::BasePortal> portal; - socket_->getSocketOption(GeneralTransportOptions::PORTAL, portal); - - // Send requests for manifest out of the congestion window (no - // in_flight_interests++) - portal->sendInterest( - std::move(i), - std::bind(&ManifestIndexManager::onManifestReceived, this, - std::placeholders::_1, std::placeholders::_2), - std::bind(&ManifestIndexManager::onManifestTimeout, this, - std::placeholders::_1)); -} - -void ManifestIndexManager::fillWindow(Name &name, uint32_t current_manifest) { - /* Send as many manifest as required for filling window. */ - uint32_t interest_lifetime; - double window_size; - std::shared_ptr<interface::BasePortal> portal; - Interest::Ptr interest; - uint32_t current_segment = *next_to_retrieve_segment_; - // suffix_manifest_ now points to the next manifest to request - uint32_t last_requested_manifest = (suffix_manifest_++).getSuffix(); - - socket_->getSocketOption(GeneralTransportOptions::PORTAL, portal); - socket_->getSocketOption(GeneralTransportOptions::INTEREST_LIFETIME, - interest_lifetime); - socket_->getSocketOption(GeneralTransportOptions::CURRENT_WINDOW_SIZE, - window_size); - - if (TRANSPORT_EXPECT_FALSE(suffix_manifest_.getSuffix() >= final_suffix_)) { - suffix_manifest_.updateSuffix(last_requested_manifest); - return; - } - - if (current_segment + window_size < suffix_manifest_.getSuffix() && - current_manifest != last_requested_manifest) { - suffix_manifest_.updateSuffix(last_requested_manifest); - return; - } - - do { - interest = getPacket(); - name.setSuffix(suffix_manifest_.getSuffix()); - interest->setName(name); - interest->setLifetime(interest_lifetime); - - // Send interests for manifest out of the congestion window (no - // in_flight_interests++) - portal->sendInterest( - std::move(interest), - std::bind(&ManifestIndexManager::onManifestReceived, this, - std::placeholders::_1, std::placeholders::_2), - std::bind(&ManifestIndexManager::onManifestTimeout, this, - std::placeholders::_1)); - TRANSPORT_LOGD("Send manifest interest %u", name.getSuffix()); - - last_requested_manifest = (suffix_manifest_++).getSuffix(); - } while (current_segment + window_size >= suffix_manifest_.getSuffix() && - suffix_manifest_.getSuffix() < final_suffix_); - - // suffix_manifest_ now points to the last requested manifest - suffix_manifest_.updateSuffix(last_requested_manifest); -} - -bool ManifestIndexManager::onContentObject( - const core::ContentObject &content_object) { - bool verify_signature; - socket_->getSocketOption(GeneralTransportOptions::VERIFY_SIGNATURE, - verify_signature); - - if (!verify_signature) { - return true; - } - - uint64_t segment = content_object.getName().getSuffix(); - - bool ret = false; - - auto it = suffix_hash_map_.find((const unsigned int)segment); - if (it != suffix_hash_map_.end()) { - auto hash_type = static_cast<utils::CryptoHashType>(it->second.second); - auto data_packet_digest = content_object.computeDigest(it->second.second); - auto data_packet_digest_bytes = - data_packet_digest.getDigest<uint8_t>().data(); - std::vector<uint8_t> &manifest_digest_bytes = it->second.first; - - if (utils::CryptoHash::compareBinaryDigest(data_packet_digest_bytes, - manifest_digest_bytes.data(), - hash_type)) { - suffix_hash_map_.erase(it); - ret = true; - } else { - throw errors::RuntimeException( - "Verification failure policy has to be implemented."); - } - } - - return ret; -} - -uint32_t ManifestIndexManager::getNextSuffix() { - if (TRANSPORT_EXPECT_FALSE(next_to_retrieve_segment_ == - suffix_queue_.end())) { - return invalid_index; - } - - return *next_to_retrieve_segment_++; -} - -uint32_t ManifestIndexManager::getFinalSuffix() { return final_suffix_; } - -bool ManifestIndexManager::isFinalSuffixDiscovered() { - return IncrementalIndexManager::isFinalSuffixDiscovered(); -} - -uint32_t ManifestIndexManager::getNextReassemblySegment() { - uint32_t current_reassembly_segment; - - while (true) { - current_reassembly_segment = next_reassembly_segment_.getSuffix(); - next_reassembly_segment_++; - - if (TRANSPORT_EXPECT_FALSE(current_reassembly_segment > final_suffix_)) { - return invalid_index; - } - - if (ignored_segments_.empty()) break; - - auto is_ignored = - std::find(ignored_segments_.begin(), ignored_segments_.end(), - current_reassembly_segment); - - if (is_ignored == ignored_segments_.end()) break; - - ignored_segments_.erase(is_ignored); - } - - return current_reassembly_segment; -} - -void ManifestIndexManager::reset() { - IncrementalIndexManager::reset(); - suffix_manifest_.reset(0); - suffix_queue_.clear(); - suffix_hash_map_.clear(); -} - -} // end namespace protocol - -} // end namespace transport diff --git a/libtransport/src/hicn/transport/protocols/statistics.h b/libtransport/src/hicn/transport/protocols/statistics.h deleted file mode 100644 index c92940ab4..000000000 --- a/libtransport/src/hicn/transport/protocols/statistics.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 - -#include <hicn/transport/portability/c_portability.h> - -#include <cstdint> - -namespace transport { - -namespace protocol { - -class TransportStatistics { - static constexpr double default_alpha = 0.7; - - public: - TransportStatistics(double alpha = default_alpha) - : retx_count_(0), - bytes_received_(0), - average_rtt_(0), - avg_window_size_(0), - interest_tx_(0), - alpha_(alpha), - loss_ratio_(0.0), - queuing_delay_(0.0) {} - - TRANSPORT_ALWAYS_INLINE void updateRetxCount(uint64_t retx) { - retx_count_ += retx; - } - - TRANSPORT_ALWAYS_INLINE void updateBytesRecv(uint64_t bytes) { - bytes_received_ += bytes; - } - - TRANSPORT_ALWAYS_INLINE void updateAverageRtt(uint64_t rtt) { - average_rtt_ = (alpha_ * average_rtt_) + ((1. - alpha_) * double(rtt)); - } - - TRANSPORT_ALWAYS_INLINE void updateAverageWindowSize(double current_window) { - avg_window_size_ = - (alpha_ * avg_window_size_) + ((1. - alpha_) * current_window); - } - - TRANSPORT_ALWAYS_INLINE void updateInterestTx(uint64_t int_tx) { - interest_tx_ += int_tx; - } - - TRANSPORT_ALWAYS_INLINE void updateLossRatio(double loss_ratio) { - loss_ratio_ = loss_ratio; - } - - TRANSPORT_ALWAYS_INLINE void updateQueuingDelay(double queuing_delay) { - queuing_delay_ = queuing_delay; - } - - TRANSPORT_ALWAYS_INLINE uint64_t getRetxCount() const { return retx_count_; } - - TRANSPORT_ALWAYS_INLINE uint64_t getBytesRecv() const { - return bytes_received_; - } - - TRANSPORT_ALWAYS_INLINE double getAverageRtt() const { return average_rtt_; } - - TRANSPORT_ALWAYS_INLINE double getAverageWindowSize() const { - return avg_window_size_; - } - - TRANSPORT_ALWAYS_INLINE uint64_t getInterestTx() const { - return interest_tx_; - } - - TRANSPORT_ALWAYS_INLINE double getLossRatio() const { return loss_ratio_; } - - TRANSPORT_ALWAYS_INLINE double getQueuingDelay() const { - return queuing_delay_; - } - - TRANSPORT_ALWAYS_INLINE void reset() { - retx_count_ = 0; - bytes_received_ = 0; - average_rtt_ = 0; - avg_window_size_ = 0; - interest_tx_ = 0; - loss_ratio_ = 0; - } - - private: - uint64_t retx_count_; - uint64_t bytes_received_; - double average_rtt_; - double avg_window_size_; - uint64_t interest_tx_; - double alpha_; - double loss_ratio_; - double queuing_delay_; -}; - -} // end namespace protocol - -} // end namespace transport diff --git a/libtransport/src/hicn/transport/utils/array.h b/libtransport/src/hicn/transport/utils/array.h deleted file mode 100644 index 7c0ed65d8..000000000 --- a/libtransport/src/hicn/transport/utils/array.h +++ /dev/null @@ -1,62 +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 <cstddef> - -namespace utils { - -template <typename T = uint8_t> -class Array { - public: - explicit Array(const T *array, size_t size) : array_(array), size_(size) { - this->array_ = array; - this->size_ = size; - } - - Array() : array_(nullptr), size_(0) { - this->array_ = nullptr; - this->size_ = 0; - } - - TRANSPORT_ALWAYS_INLINE const T *data() const { return array_; } - - TRANSPORT_ALWAYS_INLINE T *writableData() const { - return const_cast<T *>(array_); - } - - TRANSPORT_ALWAYS_INLINE std::size_t length() const { return size_; } - - TRANSPORT_ALWAYS_INLINE Array &setData(const T *data) { - array_ = data; - return *this; - } - - TRANSPORT_ALWAYS_INLINE Array &setSize(std::size_t size) { - size_ = size; - return *this; - } - - TRANSPORT_ALWAYS_INLINE bool empty() { return !size_; } - - private: - const T *array_; - std::size_t size_; -}; - -} // namespace utils diff --git a/libtransport/src/hicn/transport/utils/branch_prediction.h b/libtransport/src/hicn/transport/utils/branch_prediction.h deleted file mode 100644 index 8cbfaca76..000000000 --- a/libtransport/src/hicn/transport/utils/branch_prediction.h +++ /dev/null @@ -1,27 +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 - -#undef TRANSPORT_EXPECT_TRUE -#undef TRANSPORT_EXPECT_FALSE - -#ifndef _WIN32 -#define TRANSPORT_EXPECT_TRUE(x) __builtin_expect((x), 1) -#define TRANSPORT_EXPECT_FALSE(x) __builtin_expect((x), 0) -#else -#define TRANSPORT_EXPECT_TRUE(x) (x) -#define TRANSPORT_EXPECT_FALSE(x) (x) -#endif
\ No newline at end of file diff --git a/libtransport/src/hicn/transport/utils/chrono_typedefs.h b/libtransport/src/hicn/transport/utils/chrono_typedefs.h deleted file mode 100644 index 8f28e763c..000000000 --- a/libtransport/src/hicn/transport/utils/chrono_typedefs.h +++ /dev/null @@ -1,27 +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 <chrono> - -namespace utils { - -using SteadyClock = std::chrono::steady_clock; -using TimePoint = SteadyClock::time_point; -using Milliseconds = std::chrono::milliseconds; -using Microseconds = std::chrono::microseconds; - -} // namespace utils diff --git a/libtransport/src/hicn/transport/utils/conversions.h b/libtransport/src/hicn/transport/utils/conversions.h deleted file mode 100644 index 24b529206..000000000 --- a/libtransport/src/hicn/transport/utils/conversions.h +++ /dev/null @@ -1,37 +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 <stdio.h> -#include <cstdint> -#include <string> - -namespace utils { - -static TRANSPORT_ALWAYS_INLINE int convertStringToMacAddress( - const std::string& mac_address, uint8_t* mac_byte_array) { - const char* mac = mac_address.c_str(); - - sscanf(mac, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx", &mac_byte_array[0], - &mac_byte_array[1], &mac_byte_array[2], &mac_byte_array[3], - &mac_byte_array[4], &mac_byte_array[5]); - - return 0; -} - -} // namespace utils
\ No newline at end of file diff --git a/libtransport/src/hicn/transport/utils/crypto_hash.h b/libtransport/src/hicn/transport/utils/crypto_hash.h deleted file mode 100644 index 945909d14..000000000 --- a/libtransport/src/hicn/transport/utils/crypto_hash.h +++ /dev/null @@ -1,119 +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/runtime_exception.h> -#include <hicn/transport/portability/portability.h> -#include <hicn/transport/utils/array.h> -#include <hicn/transport/utils/crypto_hash_type.h> - -extern "C" { -#include <parc/security/parc_CryptoHash.h> -}; - -#include <cstring> -#include <unordered_map> - -namespace utils { - -class CryptoHasher; - -struct EnumClassHash { - template <typename T> - std::size_t operator()(T t) const { - return static_cast<std::size_t>(t); - } -}; - -static std::unordered_map<CryptoHashType, std::size_t, EnumClassHash> - hash_size_map = {{CryptoHashType::SHA_256, 32}, - {CryptoHashType::CRC32C, 4}, - {CryptoHashType::SHA_512, 64}}; - -class Signer; -class Verifier; - -class CryptoHash { - friend class CryptoHasher; - friend class Signer; - friend class Verifier; - - public: - CryptoHash() : hash_(nullptr) {} - - CryptoHash(const CryptoHash& other) { - if (other.hash_) { - hash_ = parcCryptoHash_Acquire(other.hash_); - } - } - - CryptoHash(CryptoHash&& other) { - if (other.hash_) { - hash_ = parcCryptoHash_Acquire(other.hash_); - } - } - - template <typename T> - CryptoHash(const T* buffer, std::size_t length, CryptoHashType hash_type) { - hash_ = parcCryptoHash_CreateFromArray( - static_cast<PARCCryptoHashType>(hash_type), buffer, length); - } - - ~CryptoHash() { - if (hash_) { - parcCryptoHash_Release(&hash_); - } - } - - CryptoHash& operator=(const CryptoHash& other) { - if (other.hash_) { - hash_ = parcCryptoHash_Acquire(other.hash_); - } - - return *this; - } - - template <typename T> - utils::Array<T> getDigest() const { - return utils::Array<T>( - static_cast<T*>(parcBuffer_Overlay(parcCryptoHash_GetDigest(hash_), 0)), - parcBuffer_Remaining(parcCryptoHash_GetDigest(hash_))); - } - - CryptoHashType getType() { - return static_cast<CryptoHashType>(parcCryptoHash_GetDigestType(hash_)); - } - - template <typename T> - static bool compareBinaryDigest(const T* digest1, const T* digest2, - CryptoHashType hash_type) { - if (hash_size_map.find(hash_type) == hash_size_map.end()) { - return false; - } - - return !static_cast<bool>( - std::memcmp(digest1, digest2, hash_size_map[hash_type])); - } - - TRANSPORT_ALWAYS_INLINE void display() { - parcBuffer_Display(parcCryptoHash_GetDigest(hash_), 2); - } - - private: - PARCCryptoHash* hash_; -}; - -} // namespace utils
\ No newline at end of file diff --git a/libtransport/src/hicn/transport/utils/crypto_hash_type.h b/libtransport/src/hicn/transport/utils/crypto_hash_type.h deleted file mode 100644 index b7597e208..000000000 --- a/libtransport/src/hicn/transport/utils/crypto_hash_type.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 - -extern "C" { -#include <parc/security/parc_CryptoHashType.h> -}; - -namespace utils { - -enum class CryptoHashType : uint8_t { - SHA_256 = PARCCryptoHashType_SHA256, - SHA_512 = PARCCryptoHashType_SHA512, - CRC32C = PARCCryptoHashType_CRC32C, - NULL_HASH = PARCCryptoHashType_NULL -}; - -}
\ No newline at end of file diff --git a/libtransport/src/hicn/transport/utils/crypto_hasher.h b/libtransport/src/hicn/transport/utils/crypto_hasher.h deleted file mode 100644 index c34a26fac..000000000 --- a/libtransport/src/hicn/transport/utils/crypto_hasher.h +++ /dev/null @@ -1,68 +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/utils/crypto_hash.h> - -extern "C" { -#include <parc/security/parc_CryptoHasher.h> -}; - -namespace utils { - -class CryptoHasher { - public: - CryptoHasher(CryptoHashType hash_type) - : hasher_(parcCryptoHasher_Create( - static_cast<PARCCryptoHashType>(hash_type))), - managed_(true) {} - - CryptoHasher(PARCCryptoHasher* hasher) : hasher_(hasher), managed_(false) {} - - ~CryptoHasher() { - if (managed_) { - parcCryptoHasher_Release(&hasher_); - } - } - - CryptoHasher& init() { - if (parcCryptoHasher_Init(hasher_) == -1) { - throw errors::RuntimeException("Cryptohash init failed."); - } - - return *this; - } - - template <typename T> - CryptoHasher& updateBytes(const T* buffer, std::size_t length) { - if (parcCryptoHasher_UpdateBytes(hasher_, buffer, length) == -1) { - throw errors::RuntimeException("Cryptohash updateBytes failed."); - } - return *this; - } - - CryptoHash finalize() { - CryptoHash hash; - hash.hash_ = parcCryptoHasher_Finalize(hasher_); - return hash; - } - - private: - PARCCryptoHasher* hasher_; - bool managed_; -}; - -} // namespace utils
\ No newline at end of file diff --git a/libtransport/src/hicn/transport/utils/crypto_suite.h b/libtransport/src/hicn/transport/utils/crypto_suite.h deleted file mode 100644 index 8ae32b846..000000000 --- a/libtransport/src/hicn/transport/utils/crypto_suite.h +++ /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. - */ - -#pragma once - -extern "C" { -#include <parc/security/parc_CryptoSuite.h> -}; - -namespace utils { - -enum class CryptoSuite : uint8_t { - RSA_SHA256 = PARCCryptoSuite_RSA_SHA256, - DSA_SHA256 = PARCCryptoSuite_DSA_SHA256, - RSA_SHA512 = PARCCryptoSuite_RSA_SHA512, - HMAC_SHA256 = PARCCryptoSuite_HMAC_SHA256, - HMAC_SHA512 = PARCCryptoSuite_HMAC_SHA512, - NULL_CRC32C = PARCCryptoSuite_NULL_CRC32C, - ECDSA_256K1 = PARCCryptoSuite_ECDSA_SHA256, - UNKNOWN = PARCCryptoSuite_UNKNOWN -}; - -} diff --git a/libtransport/src/hicn/transport/utils/daemonizator.h b/libtransport/src/hicn/transport/utils/daemonizator.h deleted file mode 100644 index 028d74865..000000000 --- a/libtransport/src/hicn/transport/utils/daemonizator.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 - -#ifndef _WIN32 - -#include <cstdlib> -namespace utils { - -class Daemonizator { - public: - static void daemonize(bool close_fds = true); -}; - -} // namespace utils - -#endif
\ No newline at end of file diff --git a/libtransport/src/hicn/transport/utils/hash.h b/libtransport/src/hicn/transport/utils/hash.h deleted file mode 100644 index 6815ca4bf..000000000 --- a/libtransport/src/hicn/transport/utils/hash.h +++ /dev/null @@ -1,101 +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 - -#include <hicn/transport/portability/portability.h> - -#include <cstddef> -#include <cstdint> -#include <cstring> -#include <string> -#include <tuple> -#include <type_traits> -#include <utility> - -namespace utils { - -namespace hash { - -/* - * Fowler / Noll / Vo (FNV) Hash - * http://www.isthe.com/chongo/tech/comp/fnv/ - */ - -const uint32_t FNV_32_HASH_START = 2166136261UL; -const uint64_t FNV_64_HASH_START = 14695981039346656037ULL; - -TRANSPORT_ALWAYS_INLINE uint32_t fnv32(const char *s, - uint32_t hash = FNV_32_HASH_START) { - for (; *s; ++s) { - hash += - (hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24); - hash ^= *s; - } - return hash; -} - -TRANSPORT_ALWAYS_INLINE uint32_t fnv32_buf(const void *buf, size_t n, - uint32_t hash = FNV_32_HASH_START) { - // forcing signed char, since other platforms can use unsigned - const signed char *char_buf = reinterpret_cast<const signed char *>(buf); - - for (size_t i = 0; i < n; ++i) { - hash += - (hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24); - hash ^= char_buf[i]; - } - - return hash; -} - -TRANSPORT_ALWAYS_INLINE uint32_t fnv32(const std::string &str, - uint32_t hash = FNV_32_HASH_START) { - return fnv32_buf(str.data(), str.size(), hash); -} - -TRANSPORT_ALWAYS_INLINE uint64_t fnv64(const char *s, - uint64_t hash = FNV_64_HASH_START) { - for (; *s; ++s) { - hash += (hash << 1) + (hash << 4) + (hash << 5) + (hash << 7) + - (hash << 8) + (hash << 40); - hash ^= *s; - } - return hash; -} - -TRANSPORT_ALWAYS_INLINE uint64_t fnv64_buf(const void *buf, size_t n, - uint64_t hash = FNV_64_HASH_START) { - // forcing signed char, since other platforms can use unsigned - const signed char *char_buf = reinterpret_cast<const signed char *>(buf); - - for (size_t i = 0; i < n; ++i) { - hash += (hash << 1) + (hash << 4) + (hash << 5) + (hash << 7) + - (hash << 8) + (hash << 40); - hash ^= char_buf[i]; - } - return hash; -} - -TRANSPORT_ALWAYS_INLINE uint64_t fnv64(const std::string &str, - uint64_t hash = FNV_64_HASH_START) { - return fnv64_buf(str.data(), str.size(), hash); -} - -} // namespace hash - -} // namespace utils diff --git a/libtransport/src/hicn/transport/utils/identity.h b/libtransport/src/hicn/transport/utils/identity.h deleted file mode 100644 index e9801a005..000000000 --- a/libtransport/src/hicn/transport/utils/identity.h +++ /dev/null @@ -1,62 +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/utils/crypto_suite.h> -#include <hicn/transport/utils/signer.h> - -extern "C" { -#include <parc/security/parc_Identity.h> -#include <parc/security/parc_IdentityFile.h> -#include <parc/security/parc_Pkcs12KeyStore.h> -}; - -#include <string> - -namespace utils { - -class Identity { - public: - Identity(const std::string &keystore_name, - const std::string &keystore_password, CryptoSuite suite, - unsigned int signature_length, unsigned int validity_days, - const std::string &subject_name); - - Identity(const Identity &other); - - Identity(std::string &file_name, std::string &password, - transport::core::HashAlgorithm hash_algorithm); - - ~Identity(); - - static Identity generateIdentity(const std::string &subject_name); - - std::string getFileName(); - - std::string getPassword(); - - std::shared_ptr<Signer> getSigner(); - - size_t getSignatureLength() const; - - private: - PARCIdentity *identity_; - std::shared_ptr<Signer> signer_; - transport::core::HashAlgorithm hash_algorithm_; -}; - -} // namespace utils diff --git a/libtransport/src/hicn/transport/utils/key_id.h b/libtransport/src/hicn/transport/utils/key_id.h deleted file mode 100644 index d67b73d7a..000000000 --- a/libtransport/src/hicn/transport/utils/key_id.h +++ /dev/null @@ -1,25 +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> -#include <utility> - -namespace utils { - -using KeyId = std::pair<uint8_t*, uint8_t>; - -} diff --git a/libtransport/src/hicn/transport/utils/linux.h b/libtransport/src/hicn/transport/utils/linux.h deleted file mode 100644 index 5820528e1..000000000 --- a/libtransport/src/hicn/transport/utils/linux.h +++ /dev/null @@ -1,64 +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 - -#ifdef __linux__ - -#include <hicn/transport/portability/portability.h> -#include <hicn/transport/utils/log.h> - -#include <arpa/inet.h> -#include <ifaddrs.h> -#include <netdb.h> -#include <stdio.h> -#include <sys/socket.h> -#include <string> - -#define LINK_LOCAL_PREFIX 0xfe80 - -namespace utils { - -static TRANSPORT_ALWAYS_INLINE int retrieveInterfaceAddress( - const std::string &interface_name, struct sockaddr_in6 *address) { - struct ifaddrs *ifap, *ifa; - char addr[INET6_ADDRSTRLEN]; - - getifaddrs(&ifap); - - for (ifa = ifap; ifa; ifa = ifa->ifa_next) { - if (ifa->ifa_addr->sa_family == AF_INET6 && - strcmp(ifa->ifa_name, interface_name.c_str()) == 0) { - struct sockaddr_in6 *tmp = (struct sockaddr_in6 *)ifa->ifa_addr; - uint16_t prefix = 0; - memcpy(&prefix, tmp->sin6_addr.s6_addr, sizeof(uint16_t)); - - if (htons(LINK_LOCAL_PREFIX) != prefix) { - *address = *(struct sockaddr_in6 *)ifa->ifa_addr; - getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in6), addr, - sizeof(addr), NULL, 0, NI_NUMERICHOST); - TRANSPORT_LOGI("Interface: %s\tAddress: %s", ifa->ifa_name, addr); - } - } - } - - freeifaddrs(ifap); - - return 0; -} - -} // namespace utils - -#endif // __linux__
\ No newline at end of file diff --git a/libtransport/src/hicn/transport/utils/literals.h b/libtransport/src/hicn/transport/utils/literals.h deleted file mode 100644 index bd00e0a58..000000000 --- a/libtransport/src/hicn/transport/utils/literals.h +++ /dev/null @@ -1,55 +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 <cstdint> - -TRANSPORT_ALWAYS_INLINE std::uint8_t operator"" _U8(unsigned long long value) { - return static_cast<std::uint8_t>(value); -} - -TRANSPORT_ALWAYS_INLINE std::uint16_t operator"" _U16( - unsigned long long value) { - return static_cast<std::uint16_t>(value); -} - -TRANSPORT_ALWAYS_INLINE std::uint32_t operator"" _U32( - unsigned long long value) { - return static_cast<std::uint32_t>(value); -} - -TRANSPORT_ALWAYS_INLINE std::uint64_t operator"" _U64( - unsigned long long value) { - return static_cast<std::uint64_t>(value); -} - -TRANSPORT_ALWAYS_INLINE std::int8_t operator"" _I8(unsigned long long value) { - return static_cast<std::int8_t>(value); -} - -TRANSPORT_ALWAYS_INLINE std::int16_t operator"" _I16(unsigned long long value) { - return static_cast<std::int16_t>(value); -} - -TRANSPORT_ALWAYS_INLINE std::int32_t operator"" _I32(unsigned long long value) { - return static_cast<std::int32_t>(value); -} - -TRANSPORT_ALWAYS_INLINE std::int64_t operator"" _I64(unsigned long long value) { - return static_cast<std::int64_t>(value); -}
\ No newline at end of file diff --git a/libtransport/src/hicn/transport/utils/log.h b/libtransport/src/hicn/transport/utils/log.h deleted file mode 100644 index 3c4f1277a..000000000 --- a/libtransport/src/hicn/transport/utils/log.h +++ /dev/null @@ -1,1057 +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. - */ - -/* - * The MIT License (MIT) - * - * Copyright (c) 2017 wonder-mice - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -#pragma once - -/* To detect incompatible changes you can define TRANSPORT_LOG_VERSION_REQUIRED - * to be the current value of TRANSPORT_LOG_VERSION before including this file - * (or via compiler command line): - * - * #define TRANSPORT_LOG_VERSION_REQUIRED 4 - * #include <hicn/transport_log.h> - * - * Compilation will fail when included file has different version. - */ -#define TRANSPORT_LOG_VERSION 4 -#if defined(TRANSPORT_LOG_VERSION_REQUIRED) -#if TRANSPORT_LOG_VERSION_REQUIRED != TRANSPORT_LOG_VERSION -#error different transport_log version required -#endif -#endif - -/* Log level guideline: - * - TRANSPORT_LOG_FATAL - happened something impossible and absolutely - * unexpected. Process can't continue and must be terminated. Example: division - * by zero, unexpected modifications from other thread. - * - TRANSPORT_LOG_ERROR - happened something possible, but highly unexpected. - * The process is able to recover and continue execution. Example: out of memory - * (could also be FATAL if not handled properly). - * - TRANSPORT_LOG_WARN - happened something that *usually* should not happen - * and significantly changes application behavior for some period of time. - * Example: configuration file not found, auth error. - * - TRANSPORT_LOG_INFO - happened significant life cycle event or major state - * transition. - * Example: app started, user logged in. - * - TRANSPORT_LOG_DEBUG - minimal set of events that could help to reconstruct - * the execution path. Usually disabled in release builds. - * - TRANSPORT_LOG_VERBOSE - all other events. Usually disabled in release - * builds. - * - * *Ideally*, log file of debugged, well tested, production ready application - * should be empty or very small. Choosing a right log level is as important as - * providing short and self descriptive log message. - */ -#define TRANSPORT_LOG_VERBOSE 1 -#define TRANSPORT_LOG_DEBUG 2 -#define TRANSPORT_LOG_INFO 3 -#define TRANSPORT_LOG_WARN 4 -#define TRANSPORT_LOG_ERROR 5 -#define TRANSPORT_LOG_FATAL 6 -#define TRANSPORT_LOG_NONE 0xFF - -/* "Current" log level is a compile time check and has no runtime overhead. Log - * level that is below current log level it said to be "disabled". Otherwise, - * it's "enabled". Log messages that are disabled has no runtime overhead - they - * are converted to no-op by preprocessor and then eliminated by compiler. - * Current log level is configured per compilation module (.c/.cpp/.m file) by - * defining TRANSPORT_LOG_DEF_LEVEL or TRANSPORT_LOG_LEVEL. TRANSPORT_LOG_LEVEL - * has higer priority and when defined overrides value provided by - * TRANSPORT_LOG_DEF_LEVEL. - * - * Common practice is to define default current log level with - * TRANSPORT_LOG_DEF_LEVEL in build script (e.g. Makefile, CMakeLists.txt, gyp, - * etc.) for the entire project or target: - * - * CC_ARGS := -DTRANSPORT_LOG_DEF_LEVEL=TRANSPORT_LOG_INFO - * - * And when necessary to override it with TRANSPORT_LOG_LEVEL in .c/.cpp/.m - * files before including transport_log.h: - * - * #define TRANSPORT_LOG_LEVEL TRANSPORT_LOG_VERBOSE - * #include <hicn/transport_log.h> - * - * If both TRANSPORT_LOG_DEF_LEVEL and TRANSPORT_LOG_LEVEL are undefined, then - * TRANSPORT_LOG_INFO will be used for release builds (NDEBUG is defined) and - * TRANSPORT_LOG_DEBUG otherwise (NDEBUG is not defined). - */ -#if defined(TRANSPORT_LOG_LEVEL) -#define _TRANSPORT_LOG_LEVEL TRANSPORT_LOG_LEVEL -#elif defined(TRANSPORT_LOG_DEF_LEVEL) -#define _TRANSPORT_LOG_LEVEL TRANSPORT_LOG_DEF_LEVEL -#else -#ifdef NDEBUG -#define _TRANSPORT_LOG_LEVEL TRANSPORT_LOG_INFO -#else -#define _TRANSPORT_LOG_LEVEL TRANSPORT_LOG_DEBUG -#endif -#endif - -/* "Output" log level is a runtime check. When log level is below output log - * level it said to be "turned off" (or just "off" for short). Otherwise it's - * "turned on" (or just "on"). Log levels that were "disabled" (see - * TRANSPORT_LOG_LEVEL and TRANSPORT_LOG_DEF_LEVEL) can't be "turned on", but - * "enabled" log levels could be "turned off". Only messages with log level - * which is "turned on" will reach output facility. All other messages will be - * ignored (and their arguments will not be evaluated). Output log level is a - * global property and configured per process using - * transport_log_set_output_level() function which can be called at any time. - * - * Though in some cases it could be useful to configure output log level per - * compilation module or per library. There are two ways to achieve that: - * - Define TRANSPORT_LOG_OUTPUT_LEVEL to expresion that evaluates to desired - * output log level. - * - Copy transport_log.h and transport_log.c files into your library and build - * it with TRANSPORT_LOG_LIBRARY_PREFIX defined to library specific prefix. See - * TRANSPORT_LOG_LIBRARY_PREFIX for more details. - * - * When defined, TRANSPORT_LOG_OUTPUT_LEVEL must evaluate to integral value that - * corresponds to desired output log level. Use it only when compilation module - * is required to have output log level which is different from global output - * log level set by transport_log_set_output_level() function. For other cases, - * consider defining TRANSPORT_LOG_LEVEL or using - * transport_log_set_output_level() function. - * - * Example: - * - * #define TRANSPORT_LOG_OUTPUT_LEVEL g_module_log_level - * #include <hicn/transport_log.h> - * static int g_module_log_level = TRANSPORT_LOG_INFO; - * static void foo() { - * TRANSPORT_LOGI("Will check g_module_log_level for output log level"); - * } - * void debug_log(bool on) { - * g_module_log_level = on? TRANSPORT_LOG_DEBUG: TRANSPORT_LOG_INFO; - * } - * - * Note on performance. This expression will be evaluated each time message is - * logged (except when message log level is "disabled" - see TRANSPORT_LOG_LEVEL - * for details). Keep this expression as simple as possible, otherwise it will - * not only add runtime overhead, but also will increase size of call site - * (which will result in larger executable). The prefered way is to use integer - * variable (as in example above). If structure must be used, log_level field - * must be the first field in this structure: - * - * #define TRANSPORT_LOG_OUTPUT_LEVEL (g_config.log_level) - * #include <hicn/transport_log.h> - * struct config { - * int log_level; - * unsigned other_field; - * [...] - * }; - * static config g_config = {TRANSPORT_LOG_INFO, 0, ...}; - * - * This allows compiler to generate more compact load instruction (no need to - * specify offset since it's zero). Calling a function to get output log level - * is generaly a bad idea, since it will increase call site size and runtime - * overhead even further. - */ -#if defined(TRANSPORT_LOG_OUTPUT_LEVEL) -#define _TRANSPORT_LOG_OUTPUT_LEVEL TRANSPORT_LOG_OUTPUT_LEVEL -#else -#define _TRANSPORT_LOG_OUTPUT_LEVEL _transport_log_global_output_lvl -#endif - -/* "Tag" is a compound string that could be associated with a log message. It - * consists of tag prefix and tag (both are optional). - * - * Tag prefix is a global property and configured per process using - * transport_log_set_tag_prefix() function. Tag prefix identifies context in - * which component or module is running (e.g. process name). For example, the - * same library could be used in both client and server processes that work on - * the same machine. Tag prefix could be used to easily distinguish between - * them. For more details about tag prefix see transport_log_set_tag_prefix() - * function. Tag prefix - * - * Tag identifies component or module. It is configured per compilation module - * (.c/.cpp/.m file) by defining TRANSPORT_LOG_TAG or TRANSPORT_LOG_DEF_TAG. - * TRANSPORT_LOG_TAG has higer priority and when defined overrides value - * provided by TRANSPORT_LOG_DEF_TAG. When defined, value must evaluate to - * (const char *), so for strings double quotes must be used. - * - * Default tag could be defined with TRANSPORT_LOG_DEF_TAG in build script (e.g. - * Makefile, CMakeLists.txt, gyp, etc.) for the entire project or target: - * - * CC_ARGS := -DTRANSPORT_LOG_DEF_TAG=\"MISC\" - * - * And when necessary could be overriden with TRANSPORT_LOG_TAG in .c/.cpp/.m - * files before including transport_log.h: - * - * #define TRANSPORT_LOG_TAG "MAIN" - * #include <hicn/transport_log.h> - * - * If both TRANSPORT_LOG_DEF_TAG and TRANSPORT_LOG_TAG are undefined no tag will - * be added to the log message (tag prefix still could be added though). - * - * Output example: - * - * 04-29 22:43:20.244 40059 1299 I hello.MAIN Number of arguments: 1 - * | | - * | +- tag (e.g. module) - * +- tag prefix (e.g. process name) - */ -#if defined(TRANSPORT_LOG_TAG) -#define _TRANSPORT_LOG_TAG TRANSPORT_LOG_TAG -#elif defined(TRANSPORT_LOG_DEF_TAG) -#define _TRANSPORT_LOG_TAG TRANSPORT_LOG_DEF_TAG -#else -#define _TRANSPORT_LOG_TAG 0 -#endif - -/* Source location is part of a log line that describes location (function or - * method name, file name and line number, e.g. "runloop@main.cpp:68") of a - * log statement that produced it. - * Source location formats are: - * - TRANSPORT_LOG_SRCLOC_NONE - don't add source location to log line. - * - TRANSPORT_LOG_SRCLOC_SHORT - add source location in short form (file and - * line number, e.g. "@main.cpp:68"). - * - TRANSPORT_LOG_SRCLOC_LONG - add source location in long form (function or - * method name, file and line number, e.g. "runloop@main.cpp:68"). - */ -#define TRANSPORT_LOG_SRCLOC_NONE 0 -#define TRANSPORT_LOG_SRCLOC_SHORT 1 -#define TRANSPORT_LOG_SRCLOC_LONG 2 - -/* Source location format is configured per compilation module (.c/.cpp/.m - * file) by defining TRANSPORT_LOG_DEF_SRCLOC or TRANSPORT_LOG_SRCLOC. - * TRANSPORT_LOG_SRCLOC has higer priority and when defined overrides value - * provided by TRANSPORT_LOG_DEF_SRCLOC. - * - * Common practice is to define default format with TRANSPORT_LOG_DEF_SRCLOC in - * build script (e.g. Makefile, CMakeLists.txt, gyp, etc.) for the entire - * project or target: - * - * CC_ARGS := -DTRANSPORT_LOG_DEF_SRCLOC=TRANSPORT_LOG_SRCLOC_LONG - * - * And when necessary to override it with TRANSPORT_LOG_SRCLOC in .c/.cpp/.m - * files before including transport_log.h: - * - * #define TRANSPORT_LOG_SRCLOC TRANSPORT_LOG_SRCLOC_NONE - * #include <hicn/transport_log.h> - * - * If both TRANSPORT_LOG_DEF_SRCLOC and TRANSPORT_LOG_SRCLOC are undefined, then - * TRANSPORT_LOG_SRCLOC_NONE will be used for release builds (NDEBUG is defined) - * and TRANSPORT_LOG_SRCLOC_LONG otherwise (NDEBUG is not defined). - */ -#if defined(TRANSPORT_LOG_SRCLOC) -#define _TRANSPORT_LOG_SRCLOC TRANSPORT_LOG_SRCLOC -#elif defined(TRANSPORT_LOG_DEF_SRCLOC) -#define _TRANSPORT_LOG_SRCLOC TRANSPORT_LOG_DEF_SRCLOC -#else -#ifdef NDEBUG -#define _TRANSPORT_LOG_SRCLOC TRANSPORT_LOG_SRCLOC_NONE -#else -#define _TRANSPORT_LOG_SRCLOC TRANSPORT_LOG_SRCLOC_LONG -#endif -#endif -#if TRANSPORT_LOG_SRCLOC_LONG == _TRANSPORT_LOG_SRCLOC -#define _TRANSPORT_LOG_SRCLOC_FUNCTION _TRANSPORT_LOG_FUNCTION -#else -#define _TRANSPORT_LOG_SRCLOC_FUNCTION 0 -#endif - -/* Censoring provides conditional logging of secret information, also known as - * Personally Identifiable Information (PII) or Sensitive Personal Information - * (SPI). Censoring can be either enabled (TRANSPORT_LOG_CENSORED) or disabled - * (TRANSPORT_LOG_UNCENSORED). When censoring is enabled, log statements marked - * as "secrets" will be ignored and will have zero overhead (arguments also will - * not be evaluated). - */ -#define TRANSPORT_LOG_CENSORED 1 -#define TRANSPORT_LOG_UNCENSORED 0 - -/* Censoring is configured per compilation module (.c/.cpp/.m file) by defining - * TRANSPORT_LOG_DEF_CENSORING or TRANSPORT_LOG_CENSORING. - * TRANSPORT_LOG_CENSORING has higer priority and when defined overrides value - * provided by TRANSPORT_LOG_DEF_CENSORING. - * - * Common practice is to define default censoring with - * TRANSPORT_LOG_DEF_CENSORING in build script (e.g. Makefile, CMakeLists.txt, - * gyp, etc.) for the entire project or target: - * - * CC_ARGS := -DTRANSPORT_LOG_DEF_CENSORING=TRANSPORT_LOG_CENSORED - * - * And when necessary to override it with TRANSPORT_LOG_CENSORING in .c/.cpp/.m - * files before including transport_log.h (consider doing it only for debug - * purposes and be very careful not to push such temporary changes to source - * control): - * - * #define TRANSPORT_LOG_CENSORING TRANSPORT_LOG_UNCENSORED - * #include <hicn/transport_log.h> - * - * If both TRANSPORT_LOG_DEF_CENSORING and TRANSPORT_LOG_CENSORING are - * undefined, then TRANSPORT_LOG_CENSORED will be used for release builds - * (NDEBUG is defined) and TRANSPORT_LOG_UNCENSORED otherwise (NDEBUG is not - * defined). - */ -#if defined(TRANSPORT_LOG_CENSORING) -#define _TRANSPORT_LOG_CENSORING TRANSPORT_LOG_CENSORING -#elif defined(TRANSPORT_LOG_DEF_CENSORING) -#define _TRANSPORT_LOG_CENSORING TRANSPORT_LOG_DEF_CENSORING -#else -#ifdef NDEBUG -#define _TRANSPORT_LOG_CENSORING TRANSPORT_LOG_CENSORED -#else -#define _TRANSPORT_LOG_CENSORING TRANSPORT_LOG_UNCENSORED -#endif -#endif - -/* Check censoring at compile time. Evaluates to true when censoring is disabled - * (i.e. when secrets will be logged). For example: - * - * #if TRANSPORT_LOG_SECRETS - * char ssn[16]; - * getSocialSecurityNumber(ssn); - * TRANSPORT_LOGI("Customer ssn: %s", ssn); - * #endif - * - * See TRANSPORT_LOG_SECRET() macro for a more convenient way of guarding single - * log statement. - */ -#define TRANSPORT_LOG_SECRETS \ - (TRANSPORT_LOG_UNCENSORED == _TRANSPORT_LOG_CENSORING) - -/* Static (compile-time) initialization support allows to configure logging - * before entering main() function. This mostly useful in C++ where functions - * and methods could be called during initialization of global objects. Those - * functions and methods could record log messages too and for that reason - * static initialization of logging configuration is customizable. - * - * Macros below allow to specify values to use for initial configuration: - * - TRANSPORT_LOG_EXTERN_TAG_PREFIX - tag prefix (default: none) - * - TRANSPORT_LOG_EXTERN_GLOBAL_FORMAT - global format options (default: see - * TRANSPORT_LOG_MEM_WIDTH in transport_log.c) - * - TRANSPORT_LOG_EXTERN_GLOBAL_OUTPUT - global output facility (default: - * stderr or platform specific, see TRANSPORT_LOG_USE_XXX macros in - * transport_log.c) - * - TRANSPORT_LOG_EXTERN_GLOBAL_OUTPUT_LEVEL - global output log level - * (default: 0 - all levals are "turned on") - * - * For example, in log_config.c: - * - * #include <hicn/transport_log.h> - * TRANSPORT_LOG_DEFINE_TAG_PREFIX = "MyApp"; - * TRANSPORT_LOG_DEFINE_GLOBAL_FORMAT = {CUSTOM_MEM_WIDTH}; - * TRANSPORT_LOG_DEFINE_GLOBAL_OUTPUT = {TRANSPORT_LOG_PUT_STD, - * custom_output_callback, 0}; TRANSPORT_LOG_DEFINE_GLOBAL_OUTPUT_LEVEL = - * TRANSPORT_LOG_INFO; - * - * However, to use any of those macros transport_log library must be compiled - * with following macros defined: - * - to use TRANSPORT_LOG_DEFINE_TAG_PREFIX define - * TRANSPORT_LOG_EXTERN_TAG_PREFIX - * - to use TRANSPORT_LOG_DEFINE_GLOBAL_FORMAT define - * TRANSPORT_LOG_EXTERN_GLOBAL_FORMAT - * - to use TRANSPORT_LOG_DEFINE_GLOBAL_OUTPUT define - * TRANSPORT_LOG_EXTERN_GLOBAL_OUTPUT - * - to use TRANSPORT_LOG_DEFINE_GLOBAL_OUTPUT_LEVEL define - * TRANSPORT_LOG_EXTERN_GLOBAL_OUTPUT_LEVEL - * - * When transport_log library compiled with one of TRANSPORT_LOG_EXTERN_XXX - * macros defined, corresponding TRANSPORT_LOG_DEFINE_XXX macro MUST be used - * exactly once somewhere. Otherwise build will fail with link error (undefined - * symbol). - */ -#define TRANSPORT_LOG_DEFINE_TAG_PREFIX const char *_transport_log_tag_prefix -#define TRANSPORT_LOG_DEFINE_GLOBAL_FORMAT \ - transport_log_format _transport_log_global_format -#define TRANSPORT_LOG_DEFINE_GLOBAL_OUTPUT \ - transport_log_output _transport_log_global_output -#define TRANSPORT_LOG_DEFINE_GLOBAL_OUTPUT_LEVEL \ - int _transport_log_global_output_lvl - -/* Pointer to global format options. Direct modification is not allowed. Use - * transport_log_set_mem_width() instead. Could be used to initialize - * transport_log_spec structure: - * - * const transport_log_output g_output = {TRANSPORT_LOG_PUT_STD, - * output_callback, 0}; const transport_log_spec g_spec = - * {TRANSPORT_LOG_GLOBAL_FORMAT, &g_output}; TRANSPORT_LOGI_AUX(&g_spec, - * "Hello"); - */ -#define TRANSPORT_LOG_GLOBAL_FORMAT \ - ((const transport_log_format *)&_transport_log_global_format) - -/* Pointer to global output variable. Direct modification is not allowed. Use - * transport_log_set_output_v() or transport_log_set_output_p() instead. Could - * be used to initialize transport_log_spec structure: - * - * const transport_log_format g_format = {40}; - * const transport_log_spec g_spec = {g_format, TRANSPORT_LOG_GLOBAL_OUTPUT}; - * TRANSPORT_LOGI_AUX(&g_spec, "Hello"); - */ -#define TRANSPORT_LOG_GLOBAL_OUTPUT \ - ((const transport_log_output *)&_transport_log_global_output) - -/* When defined, all library symbols produced by linker will be prefixed with - * provided value. That allows to use transport_log library privately in another - * libraries without exposing transport_log symbols in their original form (to - * avoid possible conflicts with other libraries / components that also could - * use transport_log for logging). Value must be without quotes, for example: - * - * CC_ARGS := -DTRANSPORT_LOG_LIBRARY_PREFIX=my_lib_ - * - * Note, that in this mode TRANSPORT_LOG_LIBRARY_PREFIX must be defined when - * building transport_log library AND it also must be defined to the same value - * when building a library that uses it. For example, consider fictional - * KittyHttp library that wants to use transport_log for logging. First approach - * that could be taken is to add transport_log.h and transport_log.c to the - * KittyHttp's source code tree directly. In that case it will be enough just to - * define TRANSPORT_LOG_LIBRARY_PREFIX in KittyHttp's build script: - * - * // KittyHttp/CMakeLists.txt - * target_compile_definitions(KittyHttp PRIVATE - * "TRANSPORT_LOG_LIBRARY_PREFIX=KittyHttp_") - * - * If KittyHttp doesn't want to include transport_log source code in its source - * tree and wants to build transport_log as a separate library than - * transport_log library must be built with TRANSPORT_LOG_LIBRARY_PREFIX defined - * to KittyHttp_ AND KittyHttp library itself also needs to define - * TRANSPORT_LOG_LIBRARY_PREFIX to KittyHttp_. It can do so either in its build - * script, as in example above, or by providing a wrapper header that KittyHttp - * library will need to use instead of transport_log.h: - * - * // KittyHttpLogging.h - * #define TRANSPORT_LOG_LIBRARY_PREFIX KittyHttp_ - * #include <hicn/transport_log.h> - * - * Regardless of the method chosen, the end result is that transport_log symbols - * will be prefixed with "KittyHttp_", so if a user of KittyHttp (say - * DogeBrowser) also uses transport_log for logging, they will not interferer - * with each other. Both will have their own log level, output facility, format - * options etc. - */ -#ifdef TRANSPORT_LOG_LIBRARY_PREFIX -#define _TRANSPORT_LOG_DECOR__(prefix, name) prefix##name -#define _TRANSPORT_LOG_DECOR_(prefix, name) _TRANSPORT_LOG_DECOR__(prefix, name) -#define _TRANSPORT_LOG_DECOR(name) \ - _TRANSPORT_LOG_DECOR_(TRANSPORT_LOG_LIBRARY_PREFIX, name) - -#define transport_log_set_tag_prefix \ - _TRANSPORT_LOG_DECOR(transport_log_set_tag_prefix) -#define transport_log_set_mem_width \ - _TRANSPORT_LOG_DECOR(transport_log_set_mem_width) -#define transport_log_set_output_level \ - _TRANSPORT_LOG_DECOR(transport_log_set_output_level) -#define transport_log_set_output_v \ - _TRANSPORT_LOG_DECOR(transport_log_set_output_v) -#define transport_log_set_output_p \ - _TRANSPORT_LOG_DECOR(transport_log_set_output_p) -#define transport_log_out_stderr_callback \ - _TRANSPORT_LOG_DECOR(transport_log_out_stderr_callback) -#define _transport_log_tag_prefix \ - _TRANSPORT_LOG_DECOR(_transport_log_tag_prefix) -#define _transport_log_global_format \ - _TRANSPORT_LOG_DECOR(_transport_log_global_format) -#define _transport_log_global_output \ - _TRANSPORT_LOG_DECOR(_transport_log_global_output) -#define _transport_log_global_output_lvl \ - _TRANSPORT_LOG_DECOR(_transport_log_global_output_lvl) -#define _transport_log_write_d _TRANSPORT_LOG_DECOR(_transport_log_write_d) -#define _transport_log_write_aux_d \ - _TRANSPORT_LOG_DECOR(_transport_log_write_aux_d) -#define _transport_log_write _TRANSPORT_LOG_DECOR(_transport_log_write) -#define _transport_log_write_aux _TRANSPORT_LOG_DECOR(_transport_log_write_aux) -#define _transport_log_write_mem_d \ - _TRANSPORT_LOG_DECOR(_transport_log_write_mem_d) -#define _transport_log_write_mem_aux_d \ - _TRANSPORT_LOG_DECOR(_transport_log_write_mem_aux_d) -#define _transport_log_write_mem _TRANSPORT_LOG_DECOR(_transport_log_write_mem) -#define _transport_log_write_mem_aux \ - _TRANSPORT_LOG_DECOR(_transport_log_write_mem_aux) -#define _transport_log_stderr_spec \ - _TRANSPORT_LOG_DECOR(_transport_log_stderr_spec) -#endif - -#if defined(__printflike) -#define _TRANSPORT_LOG_PRINTFLIKE(str_index, first_to_check) \ - __printflike(str_index, first_to_check) -#elif defined(__GNUC__) -#define _TRANSPORT_LOG_PRINTFLIKE(str_index, first_to_check) \ - __attribute__((format(__printf__, str_index, first_to_check))) -#else -#define _TRANSPORT_LOG_PRINTFLIKE(str_index, first_to_check) -#endif - -#if (defined(_WIN32) || defined(_WIN64)) && !defined(__GNUC__) -#define _TRANSPORT_LOG_FUNCTION __FUNCTION__ -#else -#define _TRANSPORT_LOG_FUNCTION __func__ -#endif - -#if defined(_MSC_VER) && !defined(__INTEL_COMPILER) -#define _TRANSPORT_LOG_INLINE __inline -#define _TRANSPORT_LOG_IF(cond) \ - __pragma(warning(push)) __pragma(warning(disable : 4127)) if (cond) \ - __pragma(warning(pop)) -#define _TRANSPORT_LOG_WHILE(cond) \ - __pragma(warning(push)) __pragma(warning(disable : 4127)) while (cond) \ - __pragma(warning(pop)) -#else -#define _TRANSPORT_LOG_INLINE inline -#define _TRANSPORT_LOG_IF(cond) if (cond) -#define _TRANSPORT_LOG_WHILE(cond) while (cond) -#endif -#define _TRANSPORT_LOG_NEVER _TRANSPORT_LOG_IF(0) -#define _TRANSPORT_LOG_ONCE _TRANSPORT_LOG_WHILE(0) - -#ifdef __cplusplus -extern "C" { -#endif - -/* Set tag prefix. Prefix will be separated from the tag with dot ('.'). - * Use 0 or empty string to disable (default). Common use is to set it to - * the process (or build target) name (e.g. to separate client and server - * processes). Function will NOT copy provided prefix string, but will store the - * pointer. Hence specified prefix string must remain valid. See - * TRANSPORT_LOG_DEFINE_TAG_PREFIX for a way to set it before entering main() - * function. See TRANSPORT_LOG_TAG for more information about tag and tag - * prefix. - */ -void transport_log_set_tag_prefix(const char *const prefix); - -/* Set number of bytes per log line in memory (ASCII-HEX) output. Example: - * - * I hello.MAIN 4c6f72656d20697073756d20646f6c6f Lorem ipsum dolo - * |<- w bytes ->| |<- w chars ->| - * - * See TRANSPORT_LOGF_MEM and TRANSPORT_LOGF_MEM_AUX for more details. - */ -void transport_log_set_mem_width(const unsigned w); - -/* Set "output" log level. See TRANSPORT_LOG_LEVEL and - * TRANSPORT_LOG_OUTPUT_LEVEL for more info about log levels. - */ -void transport_log_set_output_level(const int lvl); - -/* Put mask is a set of flags that define what fields will be added to each - * log message. Default value is TRANSPORT_LOG_PUT_STD and other flags could be - * used to alter its behavior. See transport_log_set_output_v() for more - * details. - * - * Note about TRANSPORT_LOG_PUT_SRC: it will be added only in debug builds - * (NDEBUG is not defined). - */ -enum { - TRANSPORT_LOG_PUT_CTX = 1 << 0, /* context (time, pid, tid, log level) */ - TRANSPORT_LOG_PUT_TAG = 1 << 1, /* tag (including tag prefix) */ - TRANSPORT_LOG_PUT_SRC = 1 << 2, /* source location (file, line, function) */ - TRANSPORT_LOG_PUT_MSG = 1 << 3, /* message text (formatted string) */ - TRANSPORT_LOG_PUT_STD = 0xffff, /* everything (default) */ -}; - -typedef struct transport_log_message { - int lvl; /* Log level of the message */ - const char *tag; /* Associated tag (without tag prefix) */ - char *buf; /* Buffer start */ - char *e; /* Buffer end (last position where EOL with 0 could be written) */ - char *p; /* Buffer content end (append position) */ - char *tag_b; /* Prefixed tag start */ - char *tag_e; /* Prefixed tag end (if != tag_b, points to msg separator) */ - char *msg_b; /* Message start (expanded format string) */ -} transport_log_message; - -/* Type of output callback function. It will be called for each log line allowed - * by both "current" and "output" log levels ("enabled" and "turned on"). - * Callback function is allowed to modify content of the buffers pointed by the - * msg, but it's not allowed to modify any of msg fields. Buffer pointed by msg - * is UTF-8 encoded (no BOM mark). - */ -typedef void (*transport_log_output_cb)(const transport_log_message *msg, - void *arg); - -/* Format options. For more details see transport_log_set_mem_width(). - */ -typedef struct transport_log_format { - unsigned mem_width; /* Bytes per line in memory (ASCII-HEX) dump */ -} transport_log_format; - -/* Output facility. - */ -typedef struct transport_log_output { - unsigned - mask; /* What to put into log line buffer (see TRANSPORT_LOG_PUT_XXX) */ - void *arg; /* User provided output callback argument */ - transport_log_output_cb callback; /* Output callback function */ -} transport_log_output; - -/* Set output callback function. - * - * Mask allows to control what information will be added to the log line buffer - * before callback function is invoked. Default mask value is - * TRANSPORT_LOG_PUT_STD. - */ -void transport_log_set_output_v(const unsigned mask, void *const arg, - const transport_log_output_cb callback); -static _TRANSPORT_LOG_INLINE void transport_log_set_output_p( - const transport_log_output *const output) { - transport_log_set_output_v(output->mask, output->arg, output->callback); -} - -/* Used with _AUX macros and allows to override global format and output - * facility. Use TRANSPORT_LOG_GLOBAL_FORMAT and TRANSPORT_LOG_GLOBAL_OUTPUT for - * values from global configuration. Example: - * - * static const transport_log_output module_output = { - * TRANSPORT_LOG_PUT_STD, 0, custom_output_callback - * }; - * static const transport_log_spec module_spec = { - * TRANSPORT_LOG_GLOBAL_FORMAT, &module_output - * }; - * TRANSPORT_LOGI_AUX(&module_spec, "Position: %ix%i", x, y); - * - * See TRANSPORT_LOGF_AUX and TRANSPORT_LOGF_MEM_AUX for details. - */ -typedef struct transport_log_spec { - const transport_log_format *format; - const transport_log_output *output; -} transport_log_spec; - -#ifdef __cplusplus -} -#endif - -/* Execute log statement if condition is true. Example: - * - * TRANSPORT_LOG_IF(1 < 2, TRANSPORT_LOGI("Log this")); - * TRANSPORT_LOG_IF(1 > 2, TRANSPORT_LOGI("Don't log this")); - * - * Keep in mind though, that if condition can't be evaluated at compile time, - * then it will be evaluated at run time. This will increase exectuable size - * and can have noticeable performance overhead. Try to limit conditions to - * expressions that can be evaluated at compile time. - */ -#define TRANSPORT_LOG_IF(cond, f) \ - do { \ - _TRANSPORT_LOG_IF((cond)) { f; } \ - } \ - _TRANSPORT_LOG_ONCE - -/* Mark log statement as "secret". Log statements that are marked as secrets - * will NOT be executed when censoring is enabled (see TRANSPORT_LOG_CENSORED). - * Example: - * - * TRANSPORT_LOG_SECRET(TRANSPORT_LOGI("Credit card: %s", credit_card)); - * TRANSPORT_LOG_SECRET(TRANSPORT_LOGD_MEM(cipher, cipher_sz, "Cipher - * bytes:")); - */ -#define TRANSPORT_LOG_SECRET(f) TRANSPORT_LOG_IF(TRANSPORT_LOG_SECRETS, f) - -/* Check "current" log level at compile time (ignoring "output" log level). - * Evaluates to true when specified log level is enabled. For example: - * - * #if TRANSPORT_LOG_ENABLED_DEBUG - * const char *const g_enum_strings[] = { - * "enum_value_0", "enum_value_1", "enum_value_2" - * }; - * #endif - * // ... - * #if TRANSPORT_LOG_ENABLED_DEBUG - * TRANSPORT_LOGD("enum value: %s", g_enum_strings[v]); - * #endif - * - * See TRANSPORT_LOG_LEVEL for details. - */ -#define TRANSPORT_LOG_ENABLED(lvl) ((lvl) >= _TRANSPORT_LOG_LEVEL) -#define TRANSPORT_LOG_ENABLED_VERBOSE \ - TRANSPORT_LOG_ENABLED(TRANSPORT_LOG_VERBOSE) -#define TRANSPORT_LOG_ENABLED_DEBUG TRANSPORT_LOG_ENABLED(TRANSPORT_LOG_DEBUG) -#define TRANSPORT_LOG_ENABLED_INFO TRANSPORT_LOG_ENABLED(TRANSPORT_LOG_INFO) -#define TRANSPORT_LOG_ENABLED_WARN TRANSPORT_LOG_ENABLED(TRANSPORT_LOG_WARN) -#define TRANSPORT_LOG_ENABLED_ERROR TRANSPORT_LOG_ENABLED(TRANSPORT_LOG_ERROR) -#define TRANSPORT_LOG_ENABLED_FATAL TRANSPORT_LOG_ENABLED(TRANSPORT_LOG_FATAL) - -/* Check "output" log level at run time (taking into account "current" log - * level as well). Evaluates to true when specified log level is turned on AND - * enabled. For example: - * - * if (TRANSPORT_LOG_ON_DEBUG) - * { - * char hash[65]; - * sha256(data_ptr, data_sz, hash); - * TRANSPORT_LOGD("data: len=%u, sha256=%s", data_sz, hash); - * } - * - * See TRANSPORT_LOG_OUTPUT_LEVEL for details. - */ -#define TRANSPORT_LOG_ON(lvl) \ - (TRANSPORT_LOG_ENABLED((lvl)) && (lvl) >= _TRANSPORT_LOG_OUTPUT_LEVEL) -#define TRANSPORT_LOG_ON_VERBOSE TRANSPORT_LOG_ON(TRANSPORT_LOG_VERBOSE) -#define TRANSPORT_LOG_ON_DEBUG TRANSPORT_LOG_ON(TRANSPORT_LOG_DEBUG) -#define TRANSPORT_LOG_ON_INFO TRANSPORT_LOG_ON(TRANSPORT_LOG_INFO) -#define TRANSPORT_LOG_ON_WARN TRANSPORT_LOG_ON(TRANSPORT_LOG_WARN) -#define TRANSPORT_LOG_ON_ERROR TRANSPORT_LOG_ON(TRANSPORT_LOG_ERROR) -#define TRANSPORT_LOG_ON_FATAL TRANSPORT_LOG_ON(TRANSPORT_LOG_FATAL) - -#ifdef __cplusplus -extern "C" { -#endif - -extern const char *_transport_log_tag_prefix; -extern transport_log_format _transport_log_global_format; -extern transport_log_output _transport_log_global_output; -extern int _transport_log_global_output_lvl; -extern const transport_log_spec _transport_log_stderr_spec; - -void _transport_log_write_d(const char *const func, const char *const file, - const unsigned line, const int lvl, - const char *const tag, const char *const fmt, ...) - _TRANSPORT_LOG_PRINTFLIKE(6, 7); -void _transport_log_write_aux_d(const char *const func, const char *const file, - const unsigned line, - const transport_log_spec *const log, - const int lvl, const char *const tag, - const char *const fmt, ...) - _TRANSPORT_LOG_PRINTFLIKE(7, 8); -void _transport_log_write(const int lvl, const char *const tag, - const char *const fmt, ...) - _TRANSPORT_LOG_PRINTFLIKE(3, 4); -void _transport_log_write_aux(const transport_log_spec *const log, - const int lvl, const char *const tag, - const char *const fmt, ...) - _TRANSPORT_LOG_PRINTFLIKE(4, 5); -void _transport_log_write_mem_d(const char *const func, const char *const file, - const unsigned line, const int lvl, - const char *const tag, const void *const d, - const unsigned d_sz, const char *const fmt, ...) - _TRANSPORT_LOG_PRINTFLIKE(8, 9); -void _transport_log_write_mem_aux_d(const char *const func, - const char *const file, const unsigned line, - const transport_log_spec *const log, - const int lvl, const char *const tag, - const void *const d, const unsigned d_sz, - const char *const fmt, ...) - _TRANSPORT_LOG_PRINTFLIKE(9, 10); -void _transport_log_write_mem(const int lvl, const char *const tag, - const void *const d, const unsigned d_sz, - const char *const fmt, ...) - _TRANSPORT_LOG_PRINTFLIKE(5, 6); -void _transport_log_write_mem_aux(const transport_log_spec *const log, - const int lvl, const char *const tag, - const void *const d, const unsigned d_sz, - const char *const fmt, ...) - _TRANSPORT_LOG_PRINTFLIKE(6, 7); - -#ifdef __cplusplus -} -#endif - -/* Message logging macros: - * - TRANSPORT_LOGV("format string", args, ...) - * - TRANSPORT_LOGD("format string", args, ...) - * - TRANSPORT_LOGI("format string", args, ...) - * - TRANSPORT_LOGW("format string", args, ...) - * - TRANSPORT_LOGE("format string", args, ...) - * - TRANSPORT_LOGF("format string", args, ...) - * - * Memory logging macros: - * - TRANSPORT_LOGV_MEM(data_ptr, data_sz, "format string", args, ...) - * - TRANSPORT_LOGD_MEM(data_ptr, data_sz, "format string", args, ...) - * - TRANSPORT_LOGI_MEM(data_ptr, data_sz, "format string", args, ...) - * - TRANSPORT_LOGW_MEM(data_ptr, data_sz, "format string", args, ...) - * - TRANSPORT_LOGE_MEM(data_ptr, data_sz, "format string", args, ...) - * - TRANSPORT_LOGF_MEM(data_ptr, data_sz, "format string", args, ...) - * - * Auxiliary logging macros: - * - TRANSPORT_LOGV_AUX(&log_instance, "format string", args, ...) - * - TRANSPORT_LOGD_AUX(&log_instance, "format string", args, ...) - * - TRANSPORT_LOGI_AUX(&log_instance, "format string", args, ...) - * - TRANSPORT_LOGW_AUX(&log_instance, "format string", args, ...) - * - TRANSPORT_LOGE_AUX(&log_instance, "format string", args, ...) - * - TRANSPORT_LOGF_AUX(&log_instance, "format string", args, ...) - * - * Auxiliary memory logging macros: - * - TRANSPORT_LOGV_MEM_AUX(&log_instance, data_ptr, data_sz, "format string", - * args, ...) - * - TRANSPORT_LOGD_MEM_AUX(&log_instance, data_ptr, data_sz, "format string", - * args, ...) - * - TRANSPORT_LOGI_MEM_AUX(&log_instance, data_ptr, data_sz, "format string", - * args, ...) - * - TRANSPORT_LOGW_MEM_AUX(&log_instance, data_ptr, data_sz, "format string", - * args, ...) - * - TRANSPORT_LOGE_MEM_AUX(&log_instance, data_ptr, data_sz, "format string", - * args, ...) - * - TRANSPORT_LOGF_MEM_AUX(&log_instance, data_ptr, data_sz, "format string", - * args, ...) - * - * Preformatted string logging macros: - * - TRANSPORT_LOGV_STR("preformatted string"); - * - TRANSPORT_LOGD_STR("preformatted string"); - * - TRANSPORT_LOGI_STR("preformatted string"); - * - TRANSPORT_LOGW_STR("preformatted string"); - * - TRANSPORT_LOGE_STR("preformatted string"); - * - TRANSPORT_LOGF_STR("preformatted string"); - * - * Explicit log level and tag macros: - * - TRANSPORT_LOG_WRITE(level, tag, "format string", args, ...) - * - TRANSPORT_LOG_WRITE_MEM(level, tag, data_ptr, data_sz, "format string", - * args, ...) - * - TRANSPORT_LOG_WRITE_AUX(&log_instance, level, tag, "format string", args, - * ...) - * - TRANSPORT_LOG_WRITE_MEM_AUX(&log_instance, level, tag, data_ptr, data_sz, - * "format string", args, ...) - * - * Format string follows printf() conventions. Both data_ptr and data_sz could - * be 0. Tag can be 0 as well. Most compilers will verify that type of arguments - * match format specifiers in format string. - * - * Library assuming UTF-8 encoding for all strings (char *), including format - * string itself. - */ -#if TRANSPORT_LOG_SRCLOC_NONE == _TRANSPORT_LOG_SRCLOC -#define TRANSPORT_LOG_WRITE(lvl, tag, ...) \ - do { \ - if (TRANSPORT_LOG_ON(lvl)) _transport_log_write(lvl, tag, __VA_ARGS__); \ - } \ - _TRANSPORT_LOG_ONCE -#define TRANSPORT_LOG_WRITE_MEM(lvl, tag, d, d_sz, ...) \ - do { \ - if (TRANSPORT_LOG_ON(lvl)) \ - _transport_log_write_mem(lvl, tag, d, d_sz, __VA_ARGS__); \ - } \ - _TRANSPORT_LOG_ONCE -#define TRANSPORT_LOG_WRITE_AUX(log, lvl, tag, ...) \ - do { \ - if (TRANSPORT_LOG_ON(lvl)) \ - _transport_log_write_aux(log, lvl, tag, __VA_ARGS__); \ - } \ - _TRANSPORT_LOG_ONCE -#define TRANSPORT_LOG_WRITE_MEM_AUX(log, lvl, tag, d, d_sz, ...) \ - do { \ - if (TRANSPORT_LOG_ON(lvl)) \ - _transport_log_write_mem_aux(log, lvl, tag, d, d_sz, __VA_ARGS__); \ - } \ - _TRANSPORT_LOG_ONCE -#else -#define TRANSPORT_LOG_WRITE(lvl, tag, ...) \ - do { \ - if (TRANSPORT_LOG_ON(lvl)) \ - _transport_log_write_d(_TRANSPORT_LOG_SRCLOC_FUNCTION, __FILE__, \ - __LINE__, lvl, tag, __VA_ARGS__); \ - } \ - _TRANSPORT_LOG_ONCE -#define TRANSPORT_LOG_WRITE_MEM(lvl, tag, d, d_sz, ...) \ - do { \ - if (TRANSPORT_LOG_ON(lvl)) \ - _transport_log_write_mem_d(_TRANSPORT_LOG_SRCLOC_FUNCTION, __FILE__, \ - __LINE__, lvl, tag, d, d_sz, __VA_ARGS__); \ - } \ - _TRANSPORT_LOG_ONCE -#define TRANSPORT_LOG_WRITE_AUX(log, lvl, tag, ...) \ - do { \ - if (TRANSPORT_LOG_ON(lvl)) \ - _transport_log_write_aux_d(_TRANSPORT_LOG_SRCLOC_FUNCTION, __FILE__, \ - __LINE__, log, lvl, tag, __VA_ARGS__); \ - } \ - _TRANSPORT_LOG_ONCE -#define TRANSPORT_LOG_WRITE_MEM_AUX(log, lvl, tag, d, d_sz, ...) \ - do { \ - if (TRANSPORT_LOG_ON(lvl)) \ - _transport_log_write_mem_aux_d(_TRANSPORT_LOG_SRCLOC_FUNCTION, __FILE__, \ - __LINE__, log, lvl, tag, d, d_sz, \ - __VA_ARGS__); \ - } \ - _TRANSPORT_LOG_ONCE -#endif - -static _TRANSPORT_LOG_INLINE void _transport_log_unused(const int dummy, ...) { - (void)dummy; -} - -#define _TRANSPORT_LOG_UNUSED(...) \ - do { \ - _TRANSPORT_LOG_NEVER _transport_log_unused(0, __VA_ARGS__); \ - } \ - _TRANSPORT_LOG_ONCE - -#if TRANSPORT_LOG_ENABLED_VERBOSE -#define TRANSPORT_LOGV(...) \ - TRANSPORT_LOG_WRITE(TRANSPORT_LOG_VERBOSE, _TRANSPORT_LOG_TAG, __VA_ARGS__) -#define TRANSPORT_LOGV_AUX(log, ...) \ - TRANSPORT_LOG_WRITE_AUX(log, TRANSPORT_LOG_VERBOSE, _TRANSPORT_LOG_TAG, \ - __VA_ARGS__) -#define TRANSPORT_LOGV_MEM(d, d_sz, ...) \ - TRANSPORT_LOG_WRITE_MEM(TRANSPORT_LOG_VERBOSE, _TRANSPORT_LOG_TAG, d, d_sz, \ - __VA_ARGS__) -#define TRANSPORT_LOGV_MEM_AUX(log, d, d_sz, ...) \ - TRANSPORT_LOG_WRITE_MEM(log, TRANSPORT_LOG_VERBOSE, _TRANSPORT_LOG_TAG, d, \ - d_sz, __VA_ARGS__) -#else -#define TRANSPORT_LOGV(...) _TRANSPORT_LOG_UNUSED(__VA_ARGS__) -#define TRANSPORT_LOGV_AUX(...) _TRANSPORT_LOG_UNUSED(__VA_ARGS__) -#define TRANSPORT_LOGV_MEM(...) _TRANSPORT_LOG_UNUSED(__VA_ARGS__) -#define TRANSPORT_LOGV_MEM_AUX(...) _TRANSPORT_LOG_UNUSED(__VA_ARGS__) -#endif - -#if TRANSPORT_LOG_ENABLED_DEBUG -#define TRANSPORT_LOGD(...) \ - TRANSPORT_LOG_WRITE(TRANSPORT_LOG_DEBUG, _TRANSPORT_LOG_TAG, __VA_ARGS__) -#define TRANSPORT_LOGD_AUX(log, ...) \ - TRANSPORT_LOG_WRITE_AUX(log, TRANSPORT_LOG_DEBUG, _TRANSPORT_LOG_TAG, \ - __VA_ARGS__) -#define TRANSPORT_LOGD_MEM(d, d_sz, ...) \ - TRANSPORT_LOG_WRITE_MEM(TRANSPORT_LOG_DEBUG, _TRANSPORT_LOG_TAG, d, d_sz, \ - __VA_ARGS__) -#define TRANSPORT_LOGD_MEM_AUX(log, d, d_sz, ...) \ - TRANSPORT_LOG_WRITE_MEM_AUX(log, TRANSPORT_LOG_DEBUG, _TRANSPORT_LOG_TAG, d, \ - d_sz, __VA_ARGS__) -#else -#define TRANSPORT_LOGD(...) _TRANSPORT_LOG_UNUSED(__VA_ARGS__) -#define TRANSPORT_LOGD_AUX(...) _TRANSPORT_LOG_UNUSED(__VA_ARGS__) -#define TRANSPORT_LOGD_MEM(...) _TRANSPORT_LOG_UNUSED(__VA_ARGS__) -#define TRANSPORT_LOGD_MEM_AUX(...) _TRANSPORT_LOG_UNUSED(__VA_ARGS__) -#endif - -#if TRANSPORT_LOG_ENABLED_INFO -#define TRANSPORT_LOGI(...) \ - TRANSPORT_LOG_WRITE(TRANSPORT_LOG_INFO, _TRANSPORT_LOG_TAG, __VA_ARGS__) -#define TRANSPORT_LOGI_AUX(log, ...) \ - TRANSPORT_LOG_WRITE_AUX(log, TRANSPORT_LOG_INFO, _TRANSPORT_LOG_TAG, \ - __VA_ARGS__) -#define TRANSPORT_LOGI_MEM(d, d_sz, ...) \ - TRANSPORT_LOG_WRITE_MEM(TRANSPORT_LOG_INFO, _TRANSPORT_LOG_TAG, d, d_sz, \ - __VA_ARGS__) -#define TRANSPORT_LOGI_MEM_AUX(log, d, d_sz, ...) \ - TRANSPORT_LOG_WRITE_MEM_AUX(log, TRANSPORT_LOG_INFO, _TRANSPORT_LOG_TAG, d, \ - d_sz, __VA_ARGS__) -#else -#define TRANSPORT_LOGI(...) _TRANSPORT_LOG_UNUSED(__VA_ARGS__) -#define TRANSPORT_LOGI_AUX(...) _TRANSPORT_LOG_UNUSED(__VA_ARGS__) -#define TRANSPORT_LOGI_MEM(...) _TRANSPORT_LOG_UNUSED(__VA_ARGS__) -#define TRANSPORT_LOGI_MEM_AUX(...) _TRANSPORT_LOG_UNUSED(__VA_ARGS__) -#endif - -#if TRANSPORT_LOG_ENABLED_WARN -#define TRANSPORT_LOGW(...) \ - TRANSPORT_LOG_WRITE(TRANSPORT_LOG_WARN, _TRANSPORT_LOG_TAG, __VA_ARGS__) -#define TRANSPORT_LOGW_AUX(log, ...) \ - TRANSPORT_LOG_WRITE_AUX(log, TRANSPORT_LOG_WARN, _TRANSPORT_LOG_TAG, \ - __VA_ARGS__) -#define TRANSPORT_LOGW_MEM(d, d_sz, ...) \ - TRANSPORT_LOG_WRITE_MEM(TRANSPORT_LOG_WARN, _TRANSPORT_LOG_TAG, d, d_sz, \ - __VA_ARGS__) -#define TRANSPORT_LOGW_MEM_AUX(log, d, d_sz, ...) \ - TRANSPORT_LOG_WRITE_MEM_AUX(log, TRANSPORT_LOG_WARN, _TRANSPORT_LOG_TAG, d, \ - d_sz, __VA_ARGS__) -#else -#define TRANSPORT_LOGW(...) _TRANSPORT_LOG_UNUSED(__VA_ARGS__) -#define TRANSPORT_LOGW_AUX(...) _TRANSPORT_LOG_UNUSED(__VA_ARGS__) -#define TRANSPORT_LOGW_MEM(...) _TRANSPORT_LOG_UNUSED(__VA_ARGS__) -#define TRANSPORT_LOGW_MEM_AUX(...) _TRANSPORT_LOG_UNUSED(__VA_ARGS__) -#endif - -#if TRANSPORT_LOG_ENABLED_ERROR -#define TRANSPORT_LOGE(...) \ - TRANSPORT_LOG_WRITE(TRANSPORT_LOG_ERROR, _TRANSPORT_LOG_TAG, __VA_ARGS__) -#define TRANSPORT_LOGE_AUX(log, ...) \ - TRANSPORT_LOG_WRITE_AUX(log, TRANSPORT_LOG_ERROR, _TRANSPORT_LOG_TAG, \ - __VA_ARGS__) -#define TRANSPORT_LOGE_MEM(d, d_sz, ...) \ - TRANSPORT_LOG_WRITE_MEM(TRANSPORT_LOG_ERROR, _TRANSPORT_LOG_TAG, d, d_sz, \ - __VA_ARGS__) -#define TRANSPORT_LOGE_MEM_AUX(log, d, d_sz, ...) \ - TRANSPORT_LOG_WRITE_MEM_AUX(log, TRANSPORT_LOG_ERROR, _TRANSPORT_LOG_TAG, d, \ - d_sz, __VA_ARGS__) -#else -#define TRANSPORT_LOGE(...) _TRANSPORT_LOG_UNUSED(__VA_ARGS__) -#define TRANSPORT_LOGE_AUX(...) _TRANSPORT_LOG_UNUSED(__VA_ARGS__) -#define TRANSPORT_LOGE_MEM(...) _TRANSPORT_LOG_UNUSED(__VA_ARGS__) -#define TRANSPORT_LOGE_MEM_AUX(...) _TRANSPORT_LOG_UNUSED(__VA_ARGS__) -#endif - -#if TRANSPORT_LOG_ENABLED_FATAL -#define TRANSPORT_LOGF(...) \ - TRANSPORT_LOG_WRITE(TRANSPORT_LOG_FATAL, _TRANSPORT_LOG_TAG, __VA_ARGS__) -#define TRANSPORT_LOGF_AUX(log, ...) \ - TRANSPORT_LOG_WRITE_AUX(log, TRANSPORT_LOG_FATAL, _TRANSPORT_LOG_TAG, \ - __VA_ARGS__) -#define TRANSPORT_LOGF_MEM(d, d_sz, ...) \ - TRANSPORT_LOG_WRITE_MEM(TRANSPORT_LOG_FATAL, _TRANSPORT_LOG_TAG, d, d_sz, \ - __VA_ARGS__) -#define TRANSPORT_LOGF_MEM_AUX(log, d, d_sz, ...) \ - TRANSPORT_LOG_WRITE_MEM_AUX(log, TRANSPORT_LOG_FATAL, _TRANSPORT_LOG_TAG, d, \ - d_sz, __VA_ARGS__) -#else -#define TRANSPORT_LOGF(...) _TRANSPORT_LOG_UNUSED(__VA_ARGS__) -#define TRANSPORT_LOGF_AUX(...) _TRANSPORT_LOG_UNUSED(__VA_ARGS__) -#define TRANSPORT_LOGF_MEM(...) _TRANSPORT_LOG_UNUSED(__VA_ARGS__) -#define TRANSPORT_LOGF_MEM_AUX(...) _TRANSPORT_LOG_UNUSED(__VA_ARGS__) -#endif - -#define TRANSPORT_LOGV_STR(s) TRANSPORT_LOGV("%s", (s)) -#define TRANSPORT_LOGD_STR(s) TRANSPORT_LOGD("%s", (s)) -#define TRANSPORT_LOGI_STR(s) TRANSPORT_LOGI("%s", (s)) -#define TRANSPORT_LOGW_STR(s) TRANSPORT_LOGW("%s", (s)) -#define TRANSPORT_LOGE_STR(s) TRANSPORT_LOGE("%s", (s)) -#define TRANSPORT_LOGF_STR(s) TRANSPORT_LOGF("%s", (s)) - -#ifdef __cplusplus -extern "C" { -#endif - -/* Output to standard error stream. Library uses it by default, though in few - * cases it could be necessary to specify it explicitly. For example, when - * transport_log library is compiled with TRANSPORT_LOG_EXTERN_GLOBAL_OUTPUT, - * application must define and initialize global output variable: - * - * TRANSPORT_LOG_DEFINE_GLOBAL_OUTPUT = {TRANSPORT_LOG_OUT_STDERR}; - * - * Another example is when using custom output, stderr could be used as a - * fallback when custom output facility failed to initialize: - * - * transport_log_set_output_v(TRANSPORT_LOG_OUT_STDERR); - */ -enum { TRANSPORT_LOG_OUT_STDERR_MASK = TRANSPORT_LOG_PUT_STD }; -void transport_log_out_stderr_callback(const transport_log_message *const msg, - void *arg); -#define TRANSPORT_LOG_OUT_STDERR \ - TRANSPORT_LOG_OUT_STDERR_MASK, 0, transport_log_out_stderr_callback - -/* Predefined spec for stderr. Uses global format options - * (TRANSPORT_LOG_GLOBAL_FORMAT) and TRANSPORT_LOG_OUT_STDERR. Could be used to - * force output to stderr for a particular message. Example: - * - * f = fopen("foo.log", "w"); - * if (!f) - * TRANSPORT_LOGE_AUX(TRANSPORT_LOG_STDERR, "Failed to open log file"); - */ -#define TRANSPORT_LOG_STDERR (&_transport_log_stderr_spec) - -#ifdef __cplusplus -} -#endif
\ No newline at end of file diff --git a/libtransport/src/hicn/transport/utils/membuf.h b/libtransport/src/hicn/transport/utils/membuf.h deleted file mode 100644 index 9fc37dd25..000000000 --- a/libtransport/src/hicn/transport/utils/membuf.h +++ /dev/null @@ -1,921 +0,0 @@ -/* - * Copyright 2013-present 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. - */ - -/* - * The code in this file if adapated from the IOBuf of folly: - * https://github.com/facebook/folly/blob/master/folly/io/IOBuf.h - */ - -#pragma once - -#include <hicn/transport/portability/portability.h> -#include <hicn/transport/utils/branch_prediction.h> - -#include <atomic> -#include <cassert> -#include <cinttypes> -#include <cstddef> -#include <cstring> -#include <iterator> -#include <limits> -#include <memory> -#include <type_traits> -#include <vector> - -#include <stdlib.h> - -#ifndef _WIN32 -TRANSPORT_GNU_DISABLE_WARNING("-Wshadow") -#endif - -namespace utils { - -class MemBuf { - public: - enum CreateOp { CREATE }; - enum WrapBufferOp { WRAP_BUFFER }; - enum TakeOwnershipOp { TAKE_OWNERSHIP }; - enum CopyBufferOp { COPY_BUFFER }; - - typedef void (*FreeFunction)(void* buf, void* userData); - - static std::unique_ptr<MemBuf> create(std::size_t capacity); - MemBuf(CreateOp, std::size_t capacity); - - /** - * Create a new MemBuf, using a single memory allocation to allocate space - * for both the MemBuf object and the data storage space. - * - * This saves one memory allocation. However, it can be wasteful if you - * later need to grow the buffer using reserve(). If the buffer needs to be - * reallocated, the space originally allocated will not be freed() until the - * MemBuf object itself is also freed. (It can also be slightly wasteful in - * some cases where you clone this MemBuf and then free the original MemBuf.) - */ - static std::unique_ptr<MemBuf> createCombined(std::size_t capacity); - - /** - * Create a new IOBuf, using separate memory allocations for the IOBuf object - * for the IOBuf and the data storage space. - * - * This requires two memory allocations, but saves space in the long run - * if you know that you will need to reallocate the data buffer later. - */ - static std::unique_ptr<MemBuf> createSeparate(std::size_t capacity); - - /** - * Allocate a new MemBuf chain with the requested total capacity, allocating - * no more than maxBufCapacity to each buffer. - */ - static std::unique_ptr<MemBuf> createChain(size_t totalCapacity, - std::size_t maxBufCapacity); - - static std::unique_ptr<MemBuf> takeOwnership(void* buf, std::size_t capacity, - FreeFunction freeFn = nullptr, - void* userData = nullptr, - bool freeOnError = true) { - return takeOwnership(buf, capacity, capacity, freeFn, userData, - freeOnError); - } - - MemBuf(TakeOwnershipOp op, void* buf, std::size_t capacity, - FreeFunction freeFn = nullptr, void* userData = nullptr, - bool freeOnError = true) - : MemBuf(op, buf, capacity, capacity, freeFn, userData, freeOnError) {} - - static std::unique_ptr<MemBuf> takeOwnership(void* buf, std::size_t capacity, - std::size_t length, - FreeFunction freeFn = nullptr, - void* userData = nullptr, - bool freeOnError = true); - - MemBuf(TakeOwnershipOp, void* buf, std::size_t capacity, std::size_t length, - FreeFunction freeFn = nullptr, void* userData = nullptr, - bool freeOnError = true); - - static std::unique_ptr<MemBuf> wrapBuffer(const void* buf, - std::size_t capacity); - - static MemBuf wrapBufferAsValue(const void* buf, - std::size_t capacity) noexcept; - - MemBuf(WrapBufferOp op, const void* buf, std::size_t capacity) noexcept; - - /** - * Convenience function to create a new MemBuf object that copies data from a - * user-supplied buffer, optionally allocating a given amount of - * headroom and tailroom. - */ - static std::unique_ptr<MemBuf> copyBuffer(const void* buf, std::size_t size, - std::size_t headroom = 0, - std::size_t minTailroom = 0); - - MemBuf(CopyBufferOp op, const void* buf, std::size_t size, - std::size_t headroom = 0, std::size_t minTailroom = 0); - - /** - * Convenience function to free a chain of MemBufs held by a unique_ptr. - */ - static void destroy(std::unique_ptr<MemBuf>&& data) { - auto destroyer = std::move(data); - } - - ~MemBuf(); - - bool empty() const; - - const uint8_t* data() const { return data_; } - - uint8_t* writableData() { return data_; } - - const uint8_t* tail() const { return data_ + length_; } - - uint8_t* writableTail() { return data_ + length_; } - - std::size_t length() const { return length_; } - - std::size_t headroom() const { return std::size_t(data_ - buffer()); } - - std::size_t tailroom() const { return std::size_t(bufferEnd() - tail()); } - - const uint8_t* buffer() const { return buf_; } - - uint8_t* writableBuffer() { return buf_; } - - const uint8_t* bufferEnd() const { return buf_ + capacity_; } - - std::size_t capacity() const { return capacity_; } - - MemBuf* next() { return next_; } - - const MemBuf* next() const { return next_; } - - MemBuf* prev() { return prev_; } - - const MemBuf* prev() const { return prev_; } - - /** - * Shift the data forwards in the buffer. - * - * This shifts the data pointer forwards in the buffer to increase the - * headroom. This is commonly used to increase the headroom in a newly - * allocated buffer. - * - * The caller is responsible for ensuring that there is sufficient - * tailroom in the buffer before calling advance(). - * - * If there is a non-zero data length, advance() will use memmove() to shift - * the data forwards in the buffer. In this case, the caller is responsible - * for making sure the buffer is unshared, so it will not affect other MemBufs - * that may be sharing the same underlying buffer. - */ - void advance(std::size_t amount) { - // In debug builds, assert if there is a problem. - assert(amount <= tailroom()); - - if (length_ > 0) { - memmove(data_ + amount, data_, length_); - } - data_ += amount; - } - - /** - * Shift the data backwards in the buffer. - * - * The caller is responsible for ensuring that there is sufficient headroom - * in the buffer before calling retreat(). - * - * If there is a non-zero data length, retreat() will use memmove() to shift - * the data backwards in the buffer. In this case, the caller is responsible - * for making sure the buffer is unshared, so it will not affect other MemBufs - * that may be sharing the same underlying buffer. - */ - void retreat(std::size_t amount) { - // In debug builds, assert if there is a problem. - assert(amount <= headroom()); - - if (length_ > 0) { - memmove(data_ - amount, data_, length_); - } - data_ -= amount; - } - - void prepend(std::size_t amount) { - data_ -= amount; - length_ += amount; - } - - void append(std::size_t amount) { length_ += amount; } - - void trimStart(std::size_t amount) { - data_ += amount; - length_ -= amount; - } - - void trimEnd(std::size_t amount) { length_ -= amount; } - - // Never call clear on cloned membuf sharing different - // portions of the same underlying buffer. - // Use the trim functions instead. - void clear() { - data_ = writableBuffer(); - length_ = 0; - } - - void reserve(std::size_t minHeadroom, std::size_t minTailroom) { - // Maybe we don't need to do anything. - if (headroom() >= minHeadroom && tailroom() >= minTailroom) { - return; - } - // If the buffer is empty but we have enough total room (head + tail), - // move the data_ pointer around. - if (length() == 0 && headroom() + tailroom() >= minHeadroom + minTailroom) { - data_ = writableBuffer() + minHeadroom; - return; - } - // Bah, we have to do actual work. - reserveSlow(minHeadroom, minTailroom); - } - - bool isChained() const { - assert((next_ == this) == (prev_ == this)); - return next_ != this; - } - - size_t countChainElements() const; - - std::size_t computeChainDataLength() const; - - void prependChain(std::unique_ptr<MemBuf>&& iobuf); - - void appendChain(std::unique_ptr<MemBuf>&& iobuf) { - // Just use prependChain() on the next element in our chain - next_->prependChain(std::move(iobuf)); - } - - std::unique_ptr<MemBuf> unlink() { - next_->prev_ = prev_; - prev_->next_ = next_; - prev_ = this; - next_ = this; - return std::unique_ptr<MemBuf>(this); - } - - /** - * Remove this MemBuf from its current chain and return a unique_ptr to - * the MemBuf that formerly followed it in the chain. - */ - std::unique_ptr<MemBuf> pop() { - MemBuf* next = next_; - next_->prev_ = prev_; - prev_->next_ = next_; - prev_ = this; - next_ = this; - return std::unique_ptr<MemBuf>((next == this) ? nullptr : next); - } - - /** - * Remove a subchain from this chain. - * - * Remove the subchain starting at head and ending at tail from this chain. - * - * Returns a unique_ptr pointing to head. (In other words, ownership of the - * head of the subchain is transferred to the caller.) If the caller ignores - * the return value and lets the unique_ptr be destroyed, the subchain will - * be immediately destroyed. - * - * The subchain referenced by the specified head and tail must be part of the - * same chain as the current MemBuf, but must not contain the current MemBuf. - * However, the specified head and tail may be equal to each other (i.e., - * they may be a subchain of length 1). - */ - std::unique_ptr<MemBuf> separateChain(MemBuf* head, MemBuf* tail) { - assert(head != this); - assert(tail != this); - - head->prev_->next_ = tail->next_; - tail->next_->prev_ = head->prev_; - - head->prev_ = tail; - tail->next_ = head; - - return std::unique_ptr<MemBuf>(head); - } - - /** - * Return true if at least one of the MemBufs in this chain are shared, - * or false if all of the MemBufs point to unique buffers. - * - * Use isSharedOne() to only check this MemBuf rather than the entire chain. - */ - bool isShared() const { - const MemBuf* current = this; - while (true) { - if (current->isSharedOne()) { - return true; - } - current = current->next_; - if (current == this) { - return false; - } - } - } - - /** - * Return true if all MemBufs in this chain are managed by the usual - * refcounting mechanism (and so the lifetime of the underlying memory - * can be extended by clone()). - */ - bool isManaged() const { - const MemBuf* current = this; - while (true) { - if (!current->isManagedOne()) { - return false; - } - current = current->next_; - if (current == this) { - return true; - } - } - } - - /** - * Return true if this MemBuf is managed by the usual refcounting mechanism - * (and so the lifetime of the underlying memory can be extended by - * cloneOne()). - */ - bool isManagedOne() const { return sharedInfo(); } - - /** - * Return true if other MemBufs are also pointing to the buffer used by this - * MemBuf, and false otherwise. - * - * If this MemBuf points at a buffer owned by another (non-MemBuf) part of the - * code (i.e., if the MemBuf was created using wrapBuffer(), or was cloned - * from such an MemBuf), it is always considered shared. - * - * This only checks the current MemBuf, and not other MemBufs in the chain. - */ - bool isSharedOne() const { - // If this is a user-owned buffer, it is always considered shared - if ((TRANSPORT_EXPECT_FALSE(!sharedInfo()))) { - return true; - } - - if ((TRANSPORT_EXPECT_FALSE(sharedInfo()->externallyShared))) { - return true; - } - - if ((TRANSPORT_EXPECT_TRUE(!(flags() & flag_maybe_shared)))) { - return false; - } - - // flag_maybe_shared is set, so we need to check the reference count. - // (Checking the reference count requires an atomic operation, which is why - // we prefer to only check flag_maybe_shared if possible.) - bool shared = sharedInfo()->refcount.load(std::memory_order_acquire) > 1; - if (!shared) { - // we're the last one left - clearFlags(flag_maybe_shared); - } - return shared; - } - - /** - * Ensure that this MemBuf has a unique buffer that is not shared by other - * MemBufs. - * - * unshare() operates on an entire chain of MemBuf objects. If the chain is - * shared, it may also coalesce the chain when making it unique. If the - * chain is coalesced, subsequent MemBuf objects in the current chain will be - * automatically deleted. - * - * Note that buffers owned by other (non-MemBuf) users are automatically - * considered shared. - * - * Throws std::bad_alloc on error. On error the MemBuf chain will be - * unmodified. - * - * Currently unshare may also throw std::overflow_error if it tries to - * coalesce. (TODO: In the future it would be nice if unshare() were smart - * enough not to coalesce the entire buffer if the data is too large. - * However, in practice this seems unlikely to become an issue.) - */ - void unshare() { - if (isChained()) { - unshareChained(); - } else { - unshareOne(); - } - } - - /** - * Ensure that this MemBuf has a unique buffer that is not shared by other - * MemBufs. - * - * unshareOne() operates on a single MemBuf object. This MemBuf will have a - * unique buffer after unshareOne() returns, but other MemBufs in the chain - * may still be shared after unshareOne() returns. - * - * Throws std::bad_alloc on error. On error the MemBuf will be unmodified. - */ - void unshareOne() { - if (isSharedOne()) { - unshareOneSlow(); - } - } - - /** - * Mark the underlying buffers in this chain as shared with external memory - * management mechanism. This will make isShared() always returns true. - * - * This function is not thread-safe, and only safe to call immediately after - * creating an MemBuf, before it has been shared with other threads. - */ - void markExternallyShared(); - - /** - * Mark the underlying buffer that this MemBuf refers to as shared with - * external memory management mechanism. This will make isSharedOne() always - * returns true. - * - * This function is not thread-safe, and only safe to call immediately after - * creating an MemBuf, before it has been shared with other threads. - */ - void markExternallySharedOne() { - SharedInfo* info = sharedInfo(); - if (info) { - info->externallyShared = true; - } - } - - /** - * Ensure that the memory that MemBufs in this chain refer to will continue to - * be allocated for as long as the MemBufs of the chain (or any clone()s - * created from this point onwards) is alive. - * - * This only has an effect for user-owned buffers (created with the - * WRAP_BUFFER constructor or wrapBuffer factory function), in which case - * those buffers are unshared. - */ - void makeManaged() { - if (isChained()) { - makeManagedChained(); - } else { - makeManagedOne(); - } - } - - /** - * Ensure that the memory that this MemBuf refers to will continue to be - * allocated for as long as this MemBuf (or any clone()s created from this - * point onwards) is alive. - * - * This only has an effect for user-owned buffers (created with the - * WRAP_BUFFER constructor or wrapBuffer factory function), in which case - * those buffers are unshared. - */ - void makeManagedOne() { - if (!isManagedOne()) { - // We can call the internal function directly; unmanaged implies shared. - unshareOneSlow(); - } - } - - // /** - // * Coalesce this MemBuf chain into a single buffer. - // * - // * This method moves all of the data in this MemBuf chain into a single - // * contiguous buffer, if it is not already in one buffer. After coalesce() - // * returns, this MemBuf will be a chain of length one. Other MemBufs in - // the - // * chain will be automatically deleted. - // * - // * After coalescing, the MemBuf will have at least as much headroom as the - // * first MemBuf in the chain, and at least as much tailroom as the last - // MemBuf - // * in the chain. - // * - // * Throws std::bad_alloc on error. On error the MemBuf chain will be - // * unmodified. - // * - // * Returns ByteRange that points to the data MemBuf stores. - // */ - // ByteRange coalesce() { - // const std::size_t newHeadroom = headroom(); - // const std::size_t newTailroom = prev()->tailroom(); - // return coalesceWithHeadroomTailroom(newHeadroom, newTailroom); - // } - - // /** - // * This is similar to the coalesce() method, except this allows to set a - // * headroom and tailroom after coalescing. - // * - // * Returns ByteRange that points to the data MemBuf stores. - // */ - // ByteRange coalesceWithHeadroomTailroom(std::size_t newHeadroom, - // std::size_t newTailroom) { - // if (isChained()) { - // coalesceAndReallocate(newHeadroom, computeChainDataLength(), this, - // newTailroom); - // } - // return ByteRange(data_, length_); - // } - - /** - * Ensure that this chain has at least maxLength bytes available as a - * contiguous memory range. - * - * This method coalesces whole buffers in the chain into this buffer as - * necessary until this buffer's length() is at least maxLength. - * - * After coalescing, the MemBuf will have at least as much headroom as the - * first MemBuf in the chain, and at least as much tailroom as the last MemBuf - * that was coalesced. - * - * Throws std::bad_alloc or std::overflow_error on error. On error the MemBuf - * chain will be unmodified. Throws std::overflow_error if maxLength is - * longer than the total chain length. - * - * Upon return, either enough of the chain was coalesced into a contiguous - * region, or the entire chain was coalesced. That is, - * length() >= maxLength || !isChained() is true. - */ - void gather(std::size_t maxLength) { - if (!isChained() || length_ >= maxLength) { - return; - } - coalesceSlow(maxLength); - } - - /** - * Return a new MemBuf chain sharing the same data as this chain. - * - * The new MemBuf chain will normally point to the same underlying data - * buffers as the original chain. (The one exception to this is if some of - * the MemBufs in this chain contain small internal data buffers which cannot - * be shared.) - */ - std::unique_ptr<MemBuf> clone() const; - - /** - * Similar to clone(). But returns MemBuf by value rather than heap-allocating - * it. - */ - MemBuf cloneAsValue() const; - - /** - * Return a new MemBuf with the same data as this MemBuf. - * - * The new MemBuf returned will not be part of a chain (even if this MemBuf is - * part of a larger chain). - */ - std::unique_ptr<MemBuf> cloneOne() const; - - /** - * Similar to cloneOne(). But returns MemBuf by value rather than - * heap-allocating it. - */ - MemBuf cloneOneAsValue() const; - - /** - * Return a new unchained MemBuf that may share the same data as this chain. - * - * If the MemBuf chain is not chained then the new MemBuf will point to the - * same underlying data buffer as the original chain. Otherwise, it will clone - * and coalesce the MemBuf chain. - * - * The new MemBuf will have at least as much headroom as the first MemBuf in - * the chain, and at least as much tailroom as the last MemBuf in the chain. - * - * Throws std::bad_alloc on error. - */ - std::unique_ptr<MemBuf> cloneCoalesced() const; - - /** - * This is similar to the cloneCoalesced() method, except this allows to set a - * headroom and tailroom for the new MemBuf. - */ - std::unique_ptr<MemBuf> cloneCoalescedWithHeadroomTailroom( - std::size_t newHeadroom, std::size_t newTailroom) const; - - /** - * Similar to cloneCoalesced(). But returns MemBuf by value rather than - * heap-allocating it. - */ - MemBuf cloneCoalescedAsValue() const; - - /** - * This is similar to the cloneCoalescedAsValue() method, except this allows - * to set a headroom and tailroom for the new MemBuf. - */ - MemBuf cloneCoalescedAsValueWithHeadroomTailroom( - std::size_t newHeadroom, std::size_t newTailroom) const; - - /** - * Similar to Clone(). But use other as the head node. Other nodes in the - * chain (if any) will be allocted on heap. - */ - void cloneInto(MemBuf& other) const { other = cloneAsValue(); } - - /** - * Similar to CloneOne(). But to fill an existing MemBuf instead of a new - * MemBuf. - */ - void cloneOneInto(MemBuf& other) const { other = cloneOneAsValue(); } - - /** - * Return an iovector suitable for e.g. writev() - * - * auto iov = buf->getIov(); - * auto xfer = writev(fd, iov.data(), iov.size()); - * - * Naturally, the returned iovector is invalid if you modify the buffer - * chain. - */ - std::vector<struct iovec> getIov() const; - - /** - * Update an existing iovec array with the MemBuf data. - * - * New iovecs will be appended to the existing vector; anything already - * present in the vector will be left unchanged. - * - * Naturally, the returned iovec data will be invalid if you modify the - * buffer chain. - */ - void appendToIov(std::vector<struct iovec>* iov) const; - - /** - * Fill an iovec array with the MemBuf data. - * - * Returns the number of iovec filled. If there are more buffer than - * iovec, returns 0. This version is suitable to use with stack iovec - * arrays. - * - * Naturally, the filled iovec data will be invalid if you modify the - * buffer chain. - */ - size_t fillIov(struct iovec* iov, size_t len) const; - - /** - * A helper that wraps a number of iovecs into an MemBuf chain. If count == - * 0, then a zero length buf is returned. This function never returns - * nullptr. - */ - static std::unique_ptr<MemBuf> wrapIov(const iovec* vec, size_t count); - - /** - * A helper that takes ownerships a number of iovecs into an MemBuf chain. If - * count == 0, then a zero length buf is returned. This function never - * returns nullptr. - */ - static std::unique_ptr<MemBuf> takeOwnershipIov(const iovec* vec, - size_t count, - FreeFunction freeFn = nullptr, - void* userData = nullptr, - bool freeOnError = true); - - /* - * Overridden operator new and delete. - * These perform specialized memory management to help support - * createCombined(), which allocates MemBuf objects together with the buffer - * data. - */ - void* operator new(size_t size); - void* operator new(size_t size, void* ptr); - void operator delete(void* ptr); - void operator delete(void* ptr, void* placement); - - // /** - // * Iteration support: a chain of MemBufs may be iterated through using - // * STL-style iterators over const ByteRanges. Iterators are only - // invalidated - // * if the MemBuf that they currently point to is removed. - // */ - // Iterator cbegin() const; - // Iterator cend() const; - // Iterator begin() const; - // Iterator end() const; - - /** - * Allocate a new null buffer. - * - * This can be used to allocate an empty MemBuf on the stack. It will have no - * space allocated for it. This is generally useful only to later use move - * assignment to fill out the MemBuf. - */ - MemBuf() noexcept; - - /** - * Move constructor and assignment operator. - * - * In general, you should only ever move the head of an MemBuf chain. - * Internal nodes in an MemBuf chain are owned by the head of the chain, and - * should not be moved from. (Technically, nothing prevents you from moving - * a non-head node, but the moved-to node will replace the moved-from node in - * the chain. This has implications for ownership, since non-head nodes are - * owned by the chain head. You are then responsible for relinquishing - * ownership of the moved-to node, and manually deleting the moved-from - * node.) - * - * With the move assignment operator, the destination of the move should be - * the head of an MemBuf chain or a solitary MemBuf not part of a chain. If - * the move destination is part of a chain, all other MemBufs in the chain - * will be deleted. - */ - MemBuf(MemBuf&& other) noexcept; - MemBuf& operator=(MemBuf&& other) noexcept; - - MemBuf(const MemBuf& other); - MemBuf& operator=(const MemBuf& other); - - private: - enum FlagsEnum : uintptr_t { - // Adding any more flags would not work on 32-bit architectures, - // as these flags are stashed in the least significant 2 bits of a - // max-align-aligned pointer. - flag_free_shared_info = 0x1, - flag_maybe_shared = 0x2, - flag_mask = flag_free_shared_info | flag_maybe_shared - }; - - struct SharedInfo { - SharedInfo(); - SharedInfo(FreeFunction fn, void* arg); - - // A pointer to a function to call to free the buffer when the refcount - // hits 0. If this is null, free() will be used instead. - FreeFunction freeFn; - void* userData; - std::atomic<uint32_t> refcount; - bool externallyShared{false}; - }; - // Helper structs for use by operator new and delete - struct HeapPrefix; - struct HeapStorage; - struct HeapFullStorage; - - /** - * Create a new MemBuf pointing to an external buffer. - * - * The caller is responsible for holding a reference count for this new - * MemBuf. The MemBuf constructor does not automatically increment the - * reference count. - */ - struct InternalConstructor {}; // avoid conflicts - MemBuf(InternalConstructor, uintptr_t flagsAndSharedInfo, uint8_t* buf, - std::size_t capacity, uint8_t* data, std::size_t length) noexcept; - - void unshareOneSlow(); - void unshareChained(); - void makeManagedChained(); - void coalesceSlow(); - void coalesceSlow(size_t maxLength); - // newLength must be the entire length of the buffers between this and - // end (no truncation) - void coalesceAndReallocate(size_t newHeadroom, size_t newLength, MemBuf* end, - size_t newTailroom); - void coalesceAndReallocate(size_t newLength, MemBuf* end) { - coalesceAndReallocate(headroom(), newLength, end, end->prev_->tailroom()); - } - void decrementRefcount(); - void reserveSlow(std::size_t minHeadroom, std::size_t minTailroom); - void freeExtBuffer(); - - static size_t goodExtBufferSize(std::size_t minCapacity); - static void initExtBuffer(uint8_t* buf, size_t mallocSize, - SharedInfo** infoReturn, - std::size_t* capacityReturn); - static void allocExtBuffer(std::size_t minCapacity, uint8_t** bufReturn, - SharedInfo** infoReturn, - std::size_t* capacityReturn); - static void releaseStorage(HeapStorage* storage, uint16_t freeFlags); - static void freeInternalBuf(void* buf, void* userData); - - /* - * Member variables - */ - - /* - * Links to the next and the previous MemBuf in this chain. - * - * The chain is circularly linked (the last element in the chain points back - * at the head), and next_ and prev_ can never be null. If this MemBuf is the - * only element in the chain, next_ and prev_ will both point to this. - */ - MemBuf* next_{this}; - MemBuf* prev_{this}; - - /* - * A pointer to the start of the data referenced by this MemBuf, and the - * length of the data. - * - * This may refer to any subsection of the actual buffer capacity. - */ - uint8_t* data_{nullptr}; - uint8_t* buf_{nullptr}; - std::size_t length_{0}; - std::size_t capacity_{0}; - - // Pack flags in least significant 2 bits, sharedInfo in the rest - mutable uintptr_t flags_and_shared_info_{0}; - - static inline uintptr_t packFlagsAndSharedInfo(uintptr_t flags, - SharedInfo* info) { - uintptr_t uinfo = reinterpret_cast<uintptr_t>(info); - return flags | uinfo; - } - - inline SharedInfo* sharedInfo() const { - return reinterpret_cast<SharedInfo*>(flags_and_shared_info_ & ~flag_mask); - } - - inline void setSharedInfo(SharedInfo* info) { - uintptr_t uinfo = reinterpret_cast<uintptr_t>(info); - flags_and_shared_info_ = (flags_and_shared_info_ & flag_mask) | uinfo; - } - - inline uintptr_t flags() const { return flags_and_shared_info_ & flag_mask; } - - // flags_ are changed from const methods - inline void setFlags(uintptr_t flags) const { - flags_and_shared_info_ |= flags; - } - - inline void clearFlags(uintptr_t flags) const { - flags_and_shared_info_ &= ~flags; - } - - inline void setFlagsAndSharedInfo(uintptr_t flags, SharedInfo* info) { - flags_and_shared_info_ = packFlagsAndSharedInfo(flags, info); - } - - struct DeleterBase { - virtual ~DeleterBase() {} - virtual void dispose(void* p) = 0; - }; - - template <class UniquePtr> - struct UniquePtrDeleter : public DeleterBase { - typedef typename UniquePtr::pointer Pointer; - typedef typename UniquePtr::deleter_type Deleter; - - explicit UniquePtrDeleter(Deleter deleter) : deleter_(std::move(deleter)) {} - void dispose(void* p) override { - try { - deleter_(static_cast<Pointer>(p)); - delete this; - } catch (...) { - abort(); - } - } - - private: - Deleter deleter_; - }; - - static void freeUniquePtrBuffer(void* ptr, void* userData) { - static_cast<DeleterBase*>(userData)->dispose(ptr); - } -}; - -// template <class UniquePtr> -// typename std::enable_if< -// detail::IsUniquePtrToSL<UniquePtr>::value, -// std::unique_ptr<MemBuf>>::type -// MemBuf::takeOwnership(UniquePtr&& buf, size_t count) { -// size_t size = count * sizeof(typename UniquePtr::element_type); -// auto deleter = new UniquePtrDeleter<UniquePtr>(buf.get_deleter()); -// return takeOwnership( -// buf.release(), size, &MemBuf::freeUniquePtrBuffer, deleter); -// } - -inline std::unique_ptr<MemBuf> MemBuf::copyBuffer(const void* data, - std::size_t size, - std::size_t headroom, - std::size_t minTailroom) { - std::size_t capacity = headroom + size + minTailroom; - std::unique_ptr<MemBuf> buf = MemBuf::create(capacity); - buf->advance(headroom); - if (size != 0) { - memcpy(buf->writableData(), data, size); - } - buf->append(size); - return buf; -} - -} // namespace utils diff --git a/libtransport/src/hicn/transport/utils/object_pool.h b/libtransport/src/hicn/transport/utils/object_pool.h deleted file mode 100644 index e8f837753..000000000 --- a/libtransport/src/hicn/transport/utils/object_pool.h +++ /dev/null @@ -1,89 +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 - -// TODO -#include <hicn/transport/utils/spinlock.h> - -#include <deque> -#include <memory> -#include <mutex> - -namespace utils { - -template <typename T> -class ObjectPool { - class ObjectDeleter { - public: - ObjectDeleter(ObjectPool<T> *pool = nullptr) : pool_(pool) {} - - void operator()(T *t) { - if (pool_) { - pool_->add(t); - } else { - delete t; - } - } - - private: - ObjectPool<T> *pool_; - }; - - public: - using Ptr = std::unique_ptr<T, ObjectDeleter>; - - ObjectPool() : destructor_(false) {} - - ~ObjectPool() { - destructor_ = true; - for (auto &ptr : object_pool_) { - ptr.reset(); - } - } - - std::pair<bool, Ptr> get() { - if (object_pool_.empty()) { - return std::make_pair<bool, Ptr>(false, makePtr(nullptr)); - } - - utils::SpinLock::Acquire locked(object_pool_lock_); - auto ret = std::move(object_pool_.front()); - object_pool_.pop_front(); - return std::make_pair<bool, Ptr>(true, std::move(ret)); - } - - void add(T *object) { - utils::SpinLock::Acquire locked(object_pool_lock_); - - if (TRANSPORT_EXPECT_TRUE(!destructor_)) { - object_pool_.emplace_back(makePtr(object)); - } else { - delete object; - } - } - - Ptr makePtr(T *object) { return Ptr(object, ObjectDeleter(this)); } - - private: - // No copies - ObjectPool(const ObjectPool &other) = delete; - - utils::SpinLock object_pool_lock_; - std::deque<Ptr> object_pool_; - bool destructor_; -}; - -} // namespace utils
\ No newline at end of file diff --git a/libtransport/src/hicn/transport/utils/ring_buffer.h b/libtransport/src/hicn/transport/utils/ring_buffer.h deleted file mode 100644 index 9babe56bd..000000000 --- a/libtransport/src/hicn/transport/utils/ring_buffer.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 <atomic> -#include <cstddef> - -namespace utils { - -/** - * NOTE: Single consumer single producer ring buffer - */ -template <typename Element, std::size_t Size> -class CircularFifo { - public: - enum { Capacity = Size + 1 }; - - CircularFifo() : tail_(0), head_(0), size_(0) {} - virtual ~CircularFifo() {} - - bool push(const Element& item); - bool push(Element&& item); - bool pop(Element& item); - - bool wasEmpty() const; - bool wasFull() const; - bool isLockFree() const; - std::size_t size() const; - - private: - std::size_t increment(std::size_t idx) const; - std::atomic<std::size_t> tail_; // tail(input) index - Element array_[Capacity]; - std::atomic<std::size_t> head_; // head(output) index - std::atomic<std::size_t> size_; -}; - -template <typename Element, std::size_t Size> -bool CircularFifo<Element, Size>::push(const Element& item) { - const auto current_tail = tail_.load(std::memory_order_relaxed); - const auto next_tail = increment(current_tail); - if (next_tail != head_.load(std::memory_order_acquire)) { - array_[current_tail] = item; - tail_.store(next_tail, std::memory_order_release); - size_++; - return true; - } - - // full queue - return false; -} - -/** - * Push by move - */ -template <typename Element, std::size_t Size> -bool CircularFifo<Element, Size>::push(Element&& item) { - const auto current_tail = tail_.load(std::memory_order_relaxed); - const auto next_tail = increment(current_tail); - if (next_tail != head_.load(std::memory_order_acquire)) { - array_[current_tail] = std::move(item); - tail_.store(next_tail, std::memory_order_release); - size_++; - return true; - } - - // full queue - return false; -} - -// Pop by Consumer can only update the head -// (load with relaxed, store with release) -// the tail must be accessed with at least acquire -template <typename Element, std::size_t Size> -bool CircularFifo<Element, Size>::pop(Element& item) { - const size_t current_head = head_.load(std::memory_order_relaxed); - if (current_head == tail_.load(std::memory_order_acquire)) { - return false; // empty queue - } - - item = std::move(array_[current_head]); - head_.store(increment(current_head), std::memory_order_release); - size_--; - return true; -} - -template <typename Element, std::size_t Size> -bool CircularFifo<Element, Size>::wasEmpty() const { - // snapshot with acceptance of that this comparison operation is not atomic - return (head_.load() == tail_.load()); -} - -// snapshot with acceptance that this comparison is not atomic -template <typename Element, std::size_t Size> -bool CircularFifo<Element, Size>::wasFull() const { - const auto next_tail = - increment(tail_.load()); // acquire, we dont know who call - return (next_tail == head_.load()); -} - -template <typename Element, std::size_t Size> -bool CircularFifo<Element, Size>::isLockFree() const { - return (tail_.is_lock_free() && head_.is_lock_free()); -} - -template <typename Element, std::size_t Size> -std::size_t CircularFifo<Element, Size>::increment(std::size_t idx) const { - return (idx + 1) % Capacity; -} - -template <typename Element, std::size_t Size> -std::size_t CircularFifo<Element, Size>::size() const { - return size_.load(std::memory_order_relaxed); -} - -} // namespace utils
\ No newline at end of file diff --git a/libtransport/src/hicn/transport/utils/signer.h b/libtransport/src/hicn/transport/utils/signer.h deleted file mode 100644 index 31b21462b..000000000 --- a/libtransport/src/hicn/transport/utils/signer.h +++ /dev/null @@ -1,90 +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> - -extern "C" { -#include <parc/security/parc_CryptoHashType.h> -#include <parc/security/parc_CryptoSuite.h> -#include <parc/security/parc_KeyStore.h> -#include <parc/security/parc_Signer.h> -#include <parc/security/parc_SymmetricKeySigner.h> -} - -namespace utils { - -using Packet = transport::core::Packet; - -/** - * A signer can use a single key (asymmetric or symmetric) to sign a packet. - */ -class Signer { - friend class Identity; - - public: - /** - * Create a Signer - * - * @param keyStore A keystore containing a private key or simmetric key to - * use to sign packet with this Signer. - * @param suite CryptoSuite to use to verify the signature - */ - Signer(PARCKeyStore *keyStore, CryptoSuite suite); - - /** - * Create a Signer - * - * @param passphrase A string from which the symmetric key will be derived - * @param suite CryptoSuite to use to verify the signature - */ - Signer(const std::string &passphrase, CryptoSuite suite); - - Signer(const PARCSigner *signer, CryptoSuite suite); - - Signer(const PARCSigner *signer); - - ~Signer(); - - /** - * @brief Sign a packet - * - * This method is general and must be used for Public-private key signature, - * HMAC and CRC. - * - * @param packet A pointer to the header of the packet to sign. Mutable - * field in the packet must be set to 0. - * @param key_id Indentifier of the key to use to generate the signature. - */ - void sign(Packet &packet); - - size_t getSignatureLength(); - - PARCKeyStore *getKeyStore(); - - private: - PARCBufferComposer *composer_ = nullptr; - PARCBuffer *key_buffer_ = nullptr; - PARCSymmetricKeyStore *symmetricKeyStore_ = nullptr; - PARCSigner *signer_ = nullptr; - PARCSignature *signature_ = nullptr; - PARCKeyId *key_id_ = nullptr; - CryptoSuite suite_; - size_t signature_length_; - static uint8_t zeros[200]; -}; - -} // namespace utils diff --git a/libtransport/src/hicn/transport/utils/spinlock.h b/libtransport/src/hicn/transport/utils/spinlock.h deleted file mode 100644 index 009a94454..000000000 --- a/libtransport/src/hicn/transport/utils/spinlock.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 <atomic> - -namespace utils { - -class SpinLock : private std::atomic_flag { - public: - class Acquire { - public: - Acquire(SpinLock& spin_lock) : spin_lock_(spin_lock) { spin_lock_.lock(); } - - ~Acquire() { spin_lock_.unlock(); } - - // No copies - Acquire& operator=(const Acquire&) = delete; - Acquire(const Acquire&) = delete; - - private: - SpinLock& spin_lock_; - }; - - SpinLock() { clear(); } - - void lock() { - // busy-wait - while (std::atomic_flag::test_and_set(std::memory_order_acquire)) - ; - } - - void unlock() { clear(std::memory_order_release); } - - bool tryLock() { - return std::atomic_flag::test_and_set(std::memory_order_acquire); - } -}; - -} // namespace utils
\ No newline at end of file diff --git a/libtransport/src/hicn/transport/utils/string_tokenizer.h b/libtransport/src/hicn/transport/utils/string_tokenizer.h deleted file mode 100644 index 36630eb58..000000000 --- a/libtransport/src/hicn/transport/utils/string_tokenizer.h +++ /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. - */ - -#pragma once - -#include <string> - -namespace utils { - -class StringTokenizer { - public: - StringTokenizer(const std::string &str); - StringTokenizer(const std::string &str, const std::string &delim); - - bool hasMoreTokens(); - std::string nextToken(); - - private: - std::string str_; - std::string delimiter_; -}; - -} // namespace utils diff --git a/libtransport/src/hicn/transport/utils/uri.h b/libtransport/src/hicn/transport/utils/uri.h deleted file mode 100644 index 7c28e8552..000000000 --- a/libtransport/src/hicn/transport/utils/uri.h +++ /dev/null @@ -1,47 +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 <algorithm> // find -#include <string> - -namespace utils { - -class Uri { - typedef std::string::const_iterator iterator_t; - - public: - Uri(); - - Uri &parse(const std::string &uri); - - Uri &parseProtocolAndLocator(const std::string &locator); - - std::string getQueryString(); - - std::string getPath(); - - std::string getProtocol(); - - std::string getLocator(); - - std::string getPort(); - - private: - std::string query_string_, path_, protocol_, locator_, port_; -}; // uri - -} // namespace utils diff --git a/libtransport/src/hicn/transport/utils/verifier.h b/libtransport/src/hicn/transport/utils/verifier.h deleted file mode 100644 index 7ec6e7eda..000000000 --- a/libtransport/src/hicn/transport/utils/verifier.h +++ /dev/null @@ -1,103 +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> - -extern "C" { -#include <parc/security/parc_CertificateFactory.h> -#include <parc/security/parc_InMemoryVerifier.h> -#include <parc/security/parc_KeyId.h> -#include <parc/security/parc_Security.h> -#include <parc/security/parc_SymmetricKeySigner.h> -#include <parc/security/parc_Verifier.h> -} - -namespace utils { - -using Packet = transport::core::Packet; - -/** - * A verifier holds a crypto cache that contains all the keys to use for - * verify signatures/hmacs. - */ -class Verifier { - public: - Verifier(); - - ~Verifier(); - - /** - * @brief Check if a key is already in this Verifier. - * - * A PARCVerifier contains a CryptoCache with a set of key to use for - * verification purposes. - * - * @param keyId Identifier of the key to match in the CryptoCache of the - * Verifier. - * @return true if the key is found, false otherwise. - */ - bool hasKey(PARCKeyId *keyId); - - /** - * @brief Add a key to this Verifier - * - * @param key to add - * @return true if the key was added successfully, false otherwise. - */ - bool addKey(PARCKey *key); - - PARCKeyId *addKeyFromPassphrase(const std::string &passphrase, - CryptoSuite suite); - - PARCKeyId *addKeyFromCertificate(const std::string &file_name); - - /** - * @brief Verify a Signature - * - * This method is general and must be used for Public-private key signature, - * HMAC and CRC. - * - * @param signature A pointer to the buffer holding the signature - * @param sign_len Lenght of the signature (must be consistent with the type - * of the key) - * @param bufferSigned A pointer to the packet header signed with - * signature. Mutable fields and the signature field in the packet must be - * set to 0 - * @param buf_len Lenght of bufferSigned - * @param suite CryptoSuite to use to verify the signature - * @param key_id Indentifier of the key to use to verify the signature. The - * key must be already present in the Verifier. - */ - int verify(const Packet &packet); - - CryptoHash getPacketHash(const Packet &packet, - std::shared_ptr<CryptoHasher> hasher); - - private: - PARCVerifier *verifier_ = nullptr; - PARCCertificateFactory *factory_ = nullptr; - PARCCertificate *certificate_ = nullptr; - PARCKeyId *keyId_ = nullptr; - PARCKey *key_ = nullptr; - PARCBuffer *key_buffer_ = nullptr; - PARCSymmetricKeyStore *symmetricKeyStore_ = nullptr; - PARCSigner *signer_ = nullptr; - PARCBufferComposer *composer_ = nullptr; - static uint8_t zeros[200]; -}; - -} // namespace utils diff --git a/libtransport/src/hicn/transport/http/CMakeLists.txt b/libtransport/src/http/CMakeLists.txt index b24c80195..00708822d 100644 --- a/libtransport/src/hicn/transport/http/CMakeLists.txt +++ b/libtransport/src/http/CMakeLists.txt @@ -16,20 +16,6 @@ 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 +set(SOURCE_FILES ${SOURCE_FILES} PARENT_SCOPE)
\ No newline at end of file diff --git a/libtransport/src/http/client_connection.cc b/libtransport/src/http/client_connection.cc new file mode 100644 index 000000000..7a3a636fe --- /dev/null +++ b/libtransport/src/http/client_connection.cc @@ -0,0 +1,317 @@ +/* + * 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/core/content_object.h> +#include <hicn/transport/core/interest.h> +#include <hicn/transport/http/client_connection.h> +#include <hicn/transport/utils/hash.h> +#include <hicn/transport/utils/log.h> + +#include <asio.hpp> +#include <asio/steady_timer.hpp> + +#define DEFAULT_BETA 0.99 +#define DEFAULT_GAMMA 0.07 + +namespace transport { + +namespace http { + +using namespace transport; + +class HTTPClientConnection::Implementation + : public ConsumerSocket::ReadCallback { + static constexpr uint32_t max_buffer_capacity = 64 * 1024; + + public: + Implementation(HTTPClientConnection *http_client) + : http_client_(http_client), + 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( + &Implementation::verifyData, this, std::placeholders::_1, + std::placeholders::_2)); + + consumer_.setSocketOption(ConsumerCallbacksOptions::READ_CALLBACK, this); + + consumer_.connect(); + timer_ = std::make_unique<asio::steady_timer>(consumer_.getIoService()); + } + + 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") { + return sendRequest(url, HTTPMethod::GET, headers, std::move(payload), + response, callback, ipv6_first_word); + } + + 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") { + 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_; + } + + std::shared_ptr<HTTPResponse> response() { + response_->coalescePayloadBuffer(); + return response_; + } + + HTTPClientConnection &stop() { + // This is thread safe and can be called from another thread + consumer_.stop(); + + return *http_client_; + } + + interface::ConsumerSocket &getConsumer() { + return consumer_; + } + + 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 *http_client_; + } + + 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 *http_client_; + } + + private: + void 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( + &Implementation::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(); + } + + bool verifyData(interface::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 processLeavingInterest(interface::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()); + } + } + + // 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 { + if (!read_bytes_callback_) { + response_->appendResponseChunk(std::move(buffer)); + } else { + read_bytes_callback_->onBytesReceived(std::move(buffer)); + } + } + + void readError(const std::error_code ec) noexcept override { + 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 readSuccess(std::size_t total_size) noexcept override { + success_callback_(total_size); + if (read_bytes_callback_) { + read_bytes_callback_->onSuccess(total_size); + } + + return_code_ = HTTPClientConnection::RC::DOWNLOAD_SUCCESS; + } + + HTTPClientConnection *http_client_; + + // 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_; +}; + +HTTPClientConnection::HTTPClientConnection() { + implementation_ = new Implementation(this); +} + +HTTPClientConnection::~HTTPClientConnection() { delete implementation_; } + +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 implementation_->get(url, 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) { + return implementation_->sendRequest(url, method, headers, std::move(payload), + response, callback, ipv6_first_word); +} + +std::shared_ptr<HTTPResponse> HTTPClientConnection::response() { + return implementation_->response(); +} + +ConsumerSocket &HTTPClientConnection::getConsumer() { + return implementation_->getConsumer(); +} + +HTTPClientConnection &HTTPClientConnection::stop() { + return implementation_->stop(); +} + +HTTPClientConnection &HTTPClientConnection::setTimeout( + const std::chrono::seconds &timeout) { + return implementation_->setTimeout(timeout); +} + +HTTPClientConnection &HTTPClientConnection::setCertificate( + const std::string &cert_path) { + return implementation_->setCertificate(cert_path); +} + +} // namespace http + +} // namespace transport diff --git a/libtransport/src/hicn/transport/http/request.cc b/libtransport/src/http/request.cc index 09f709642..09f709642 100644 --- a/libtransport/src/hicn/transport/http/request.cc +++ b/libtransport/src/http/request.cc diff --git a/libtransport/src/hicn/transport/http/response.cc b/libtransport/src/http/response.cc index ba0acd1ac..ba0acd1ac 100644 --- a/libtransport/src/hicn/transport/http/response.cc +++ b/libtransport/src/http/response.cc diff --git a/libtransport/src/hicn/transport/interfaces/CMakeLists.txt b/libtransport/src/implementation/CMakeLists.txt index 88b83e9d4..5423a7697 100644 --- a/libtransport/src/hicn/transport/interfaces/CMakeLists.txt +++ b/libtransport/src/implementation/CMakeLists.txt @@ -13,28 +13,15 @@ cmake_minimum_required(VERSION 3.5 FATAL_ERROR) +list(APPEND SOURCE_FILES + ${CMAKE_CURRENT_SOURCE_DIR}/rtc_socket_producer.cc +) + 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 + ${CMAKE_CURRENT_SOURCE_DIR}/socket_producer.h + ${CMAKE_CURRENT_SOURCE_DIR}/socket_consumer.h ) if (${OPENSSL_VERSION} VERSION_EQUAL "1.1.1a" OR ${OPENSSL_VERSION} VERSION_GREATER "1.1.1a") @@ -55,5 +42,5 @@ if (${OPENSSL_VERSION} VERSION_EQUAL "1.1.1a" OR ${OPENSSL_VERSION} VERSION_GREA ) endif() -set(SOURCE_FILES ${SOURCE_FILES} PARENT_SCOPE) set(HEADER_FILES ${HEADER_FILES} PARENT_SCOPE) +set(SOURCE_FILES ${SOURCE_FILES} PARENT_SCOPE) diff --git a/libtransport/src/hicn/transport/interfaces/p2psecure_socket_consumer.cc b/libtransport/src/implementation/p2psecure_socket_consumer.cc index ec966e509..40ab58161 100644 --- a/libtransport/src/hicn/transport/interfaces/p2psecure_socket_consumer.cc +++ b/libtransport/src/implementation/p2psecure_socket_consumer.cc @@ -1,4 +1,21 @@ -#include <hicn/transport/interfaces/p2psecure_socket_consumer.h> +/* + * 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 <implementation/p2psecure_socket_consumer.h> +#include <interfaces/tls_socket_consumer.h> + #include <openssl/bio.h> #include <openssl/ssl.h> #include <openssl/tls1.h> @@ -6,11 +23,10 @@ #include <random> namespace transport { - -namespace interface { +namespace implementation { void P2PSecureConsumerSocket::setInterestPayload( - ConsumerSocket &c, const core::Interest &interest) { + interface::ConsumerSocket &c, const core::Interest &interest) { Interest &int2 = const_cast<Interest &>(interest); random_suffix_ = int2.getName().getSuffix(); @@ -72,7 +88,7 @@ int read(BIO *b, char *buf, size_t size, size_t *readbytes) { if (size > INT_MAX) size = INT_MAX; - ret = transport::interface::readOld(b, buf, (int)size); + ret = readOld(b, buf, (int)size); if (ret <= 0) { *readbytes = 0; @@ -105,7 +121,7 @@ int write(BIO *b, const char *buf, size_t size, size_t *written) { if (size > INT_MAX) size = INT_MAX; - ret = transport::interface::writeOld(b, buf, (int)size); + ret = writeOld(b, buf, (int)size); if (ret <= 0) { *written = 0; @@ -154,8 +170,10 @@ int P2PSecureConsumerSocket::parseHicnKeyIdCb(SSL *s, unsigned int ext_type, return 1; } -P2PSecureConsumerSocket::P2PSecureConsumerSocket(int handshake_protocol, int transport_protocol) - : ConsumerSocket(handshake_protocol), +P2PSecureConsumerSocket::P2PSecureConsumerSocket( + interface::ConsumerSocket *consumer, int handshake_protocol, + int transport_protocol) + : ConsumerSocket(consumer, transport_protocol), name_(), tls_consumer_(), buf_pool_(), @@ -198,9 +216,9 @@ P2PSecureConsumerSocket::P2PSecureConsumerSocket(int handshake_protocol, int tra 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_meth_set_read(bio_meth_, readOld); + BIO_meth_set_write(bio_meth_, writeOld); + BIO_meth_set_ctrl(bio_meth_, ctrl); BIO *bio = BIO_new(bio_meth_); BIO_set_init(bio, 1); BIO_set_data(bio, this); @@ -246,7 +264,8 @@ int P2PSecureConsumerSocket::consume(const Name &name) { 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_); + TLSConsumerSocket tls_consumer(nullptr, this->protocol_, this->ssl_); + tls_consumer.setInterface(new interface::TLSConsumerSocket(&tls_consumer)); ConsumerTimerCallback *stats_summary_callback = nullptr; this->getSocketOption(ConsumerCallbacksOptions::STATS_SUMMARY, @@ -294,8 +313,11 @@ int P2PSecureConsumerSocket::asyncConsume(const Name &name) { 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_); + std::make_shared<TLSConsumerSocket>(nullptr, this->protocol_, this->ssl_); + tls_consumer_->setInterface( + new interface::TLSConsumerSocket(tls_consumer_.get())); ConsumerTimerCallback *stats_summary_callback = nullptr; this->getSocketOption(ConsumerCallbacksOptions::STATS_SUMMARY, @@ -327,11 +349,10 @@ void P2PSecureConsumerSocket::registerPrefix(const Prefix &producer_namespace) { } int P2PSecureConsumerSocket::setSocketOption( - int socket_option_key, ConsumerSocket::ReadCallback *socket_option_value) { + int socket_option_key, ReadCallback *socket_option_value) { return rescheduleOnIOService( socket_option_key, socket_option_value, - [this](int socket_option_key, - ConsumerSocket::ReadCallback *socket_option_value) -> int { + [this](int socket_option_key, ReadCallback *socket_option_value) -> int { switch (socket_option_key) { case ConsumerCallbacksOptions::READ_CALLBACK: read_callback_decrypted_ = socket_option_value; @@ -377,6 +398,6 @@ void P2PSecureConsumerSocket::readSuccess(std::size_t total_size) noexcept { bool P2PSecureConsumerSocket::isBufferMovable() noexcept { return true; } -} // namespace interface +} // namespace implementation } // namespace transport diff --git a/libtransport/src/hicn/transport/interfaces/p2psecure_socket_consumer.h b/libtransport/src/implementation/p2psecure_socket_consumer.h index ff867f07b..e2ebaf94e 100644 --- a/libtransport/src/hicn/transport/interfaces/p2psecure_socket_consumer.h +++ b/libtransport/src/implementation/p2psecure_socket_consumer.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * 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: @@ -16,16 +16,16 @@ #pragma once #include <hicn/transport/interfaces/socket_consumer.h> -#include <hicn/transport/interfaces/tls_socket_consumer.h> + +#include <implementation/tls_socket_consumer.h> #include <openssl/bio.h> #include <openssl/ssl.h> namespace transport { - -namespace interface { +namespace implementation { class P2PSecureConsumerSocket : public ConsumerSocket, - public ConsumerSocket::ReadCallback { + public interface::ConsumerSocket::ReadCallback { /* Return the number of read bytes in readbytes */ friend int read(BIO *b, char *buf, size_t size, size_t *readbytes); @@ -41,7 +41,9 @@ class P2PSecureConsumerSocket : public ConsumerSocket, friend long ctrl(BIO *b, int cmd, long num, void *ptr); public: - explicit P2PSecureConsumerSocket(int handshake_protocol, int transport_protocol); + explicit P2PSecureConsumerSocket(interface::ConsumerSocket *consumer, + int handshake_protocol, + int transport_protocol); ~P2PSecureConsumerSocket(); @@ -53,7 +55,7 @@ class P2PSecureConsumerSocket : public ConsumerSocket, int setSocketOption( int socket_option_key, - ConsumerSocket::ReadCallback *socket_option_value) override; + interface::ConsumerSocket::ReadCallback *socket_option_value) override; using ConsumerSocket::getSocketOption; using ConsumerSocket::setSocketOption; @@ -98,7 +100,7 @@ class P2PSecureConsumerSocket : public ConsumerSocket, Prefix producer_namespace_; - ConsumerSocket::ReadCallback *read_callback_decrypted_; + interface::ConsumerSocket::ReadCallback *read_callback_decrypted_; std::mutex mtx_; @@ -107,9 +109,8 @@ class P2PSecureConsumerSocket : public ConsumerSocket, int protocol_; - void setInterestPayload(ConsumerSocket &c, const core::Interest &interest); - void processPayload(ConsumerSocket &c, std::size_t bytes_transferred, - const std::error_code &ec); + void setInterestPayload(interface::ConsumerSocket &c, + const core::Interest &interest); static int addHicnKeyIdCb(SSL *s, unsigned int ext_type, unsigned int context, const unsigned char **out, size_t *outlen, X509 *x, @@ -142,6 +143,6 @@ class P2PSecureConsumerSocket : public ConsumerSocket, int download_content(const Name &name); }; -} // namespace interface +} // namespace implementation } // end namespace transport diff --git a/libtransport/src/hicn/transport/interfaces/p2psecure_socket_producer.cc b/libtransport/src/implementation/p2psecure_socket_producer.cc index 8850bde8a..d7161986b 100644 --- a/libtransport/src/hicn/transport/interfaces/p2psecure_socket_producer.cc +++ b/libtransport/src/implementation/p2psecure_socket_producer.cc @@ -1,22 +1,40 @@ +/* + * 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/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 <implementation/p2psecure_socket_producer.h> +#include <implementation/tls_rtc_socket_producer.h> +#include <implementation/tls_socket_producer.h> +#include <interfaces/tls_rtc_socket_producer.h> +#include <interfaces/tls_socket_producer.h> #include <openssl/bio.h> #include <openssl/rand.h> #include <openssl/ssl.h> namespace transport { - -namespace interface { +namespace implementation { /* 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(), +P2PSecureProducerSocket::P2PSecureProducerSocket( + interface::ProducerSocket *producer_socket) + : ProducerSocket(producer_socket), mtx_(), cv_(), map_secure_producers(), @@ -24,8 +42,9 @@ P2PSecureProducerSocket::P2PSecureProducerSocket() list_secure_producers() {} P2PSecureProducerSocket::P2PSecureProducerSocket( - bool rtc, const std::shared_ptr<utils::Identity> &identity) - : ProducerSocket(), + interface::ProducerSocket *producer_socket, bool rtc, + const std::shared_ptr<utils::Identity> &identity) + : ProducerSocket(producer_socket), rtc_(rtc), mtx_(), cv_(), @@ -65,16 +84,19 @@ P2PSecureProducerSocket::~P2PSecureProducerSocket() { if (der_prk_) parcBuffer_Release(&der_prk_); } -void P2PSecureProducerSocket::onInterestCallback(ProducerSocket &p, +void P2PSecureProducerSocket::onInterestCallback(interface::ProducerSocket &p, Interest &interest) { std::unique_lock<std::mutex> lck(mtx_); - TRANSPORT_LOGD("Start handshake at %s", interest.getName().toString().c_str()); + 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()); + new TLSProducerSocket(nullptr, this, interest.getName()); + tls_producer->setInterface(new interface::TLSProducerSocket(tls_producer)); + tls_producer->on_content_produced_application_ = this->on_content_produced_application_; tls_producer->setSocketOption(CONTENT_OBJECT_EXPIRY_TIME, @@ -92,7 +114,9 @@ void P2PSecureProducerSocket::onInterestCallback(ProducerSocket &p, 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()); + new TLSRTCProducerSocket(nullptr, this, interest.getName()); + tls_producer->setInterface( + new interface::TLSRTCProducerSocket(tls_producer)); tls_producer->on_content_produced_application_ = this->on_content_produced_application_; tls_producer->setSocketOption(CONTENT_OBJECT_EXPIRY_TIME, @@ -375,6 +399,6 @@ int P2PSecureProducerSocket::setSocketOption( socket_option_value); } -} // namespace interface +} // namespace implementation } // namespace transport diff --git a/libtransport/src/hicn/transport/interfaces/p2psecure_socket_producer.h b/libtransport/src/implementation/p2psecure_socket_producer.h index ba3fa0189..c2cbf31ac 100644 --- a/libtransport/src/hicn/transport/interfaces/p2psecure_socket_producer.h +++ b/libtransport/src/implementation/p2psecure_socket_producer.h @@ -15,12 +15,13 @@ #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 <hicn/transport/security/identity.h> +#include <hicn/transport/security/signer.h> + +#include <implementation/socket_producer.h> +#include <implementation/tls_rtc_socket_producer.h> +#include <implementation/tls_socket_producer.h> +#include <utils/content_store.h> #include <openssl/ssl.h> #include <condition_variable> @@ -28,17 +29,17 @@ #include <mutex> namespace transport { - -namespace interface { +namespace implementation { class P2PSecureProducerSocket : public ProducerSocket { friend class TLSProducerSocket; friend class TLSRTCProducerSocket; public: - explicit P2PSecureProducerSocket(); + explicit P2PSecureProducerSocket(interface::ProducerSocket *producer_socket); explicit P2PSecureProducerSocket( - bool rtc, const std::shared_ptr<utils::Identity> &identity); + interface::ProducerSocket *producer_socket, bool rtc, + const std::shared_ptr<utils::Identity> &identity); ~P2PSecureProducerSocket(); void produce(const uint8_t *buffer, size_t buffer_size) override; @@ -49,14 +50,14 @@ class P2PSecureProducerSocket : public ProducerSocket { 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; + void asyncProduce(const Name &suffix, const uint8_t *buf, size_t buffer_size, + bool is_last = true, + uint32_t *start_offset = nullptr) override; + int setSocketOption(int socket_option_key, ProducerInterestCallback socket_option_value) override; @@ -121,9 +122,9 @@ class P2PSecureProducerSocket : public ProducerSocket { 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); + void onInterestCallback(interface::ProducerSocket &p, Interest &interest); }; -} // namespace interface +} // namespace implementation } // namespace transport diff --git a/libtransport/src/hicn/transport/interfaces/rtc_socket_producer.cc b/libtransport/src/implementation/rtc_socket_producer.cc index fefa419a9..a5b2b4a0e 100644 --- a/libtransport/src/hicn/transport/interfaces/rtc_socket_producer.cc +++ b/libtransport/src/implementation/rtc_socket_producer.cc @@ -14,7 +14,8 @@ */ #include <hicn/transport/interfaces/callbacks.h> -#include <hicn/transport/interfaces/rtc_socket_producer.h> + +#include <implementation/rtc_socket_producer.h> #include <stdlib.h> #include <time.h> @@ -54,29 +55,10 @@ // +-----------------------------------------+ namespace transport { +namespace implementation { -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(), +RTCProducerSocket::RTCProducerSocket(interface::ProducerSocket *producer_socket) + : ProducerSocket(producer_socket), currentSeg_(1), producedBytes_(0), producedPackets_(0), @@ -168,14 +150,15 @@ void RTCProducerSocket::produce(std::unique_ptr<utils::MemBuf> &&buffer) { content_object->shared_from_this())); if (on_content_object_in_output_buffer_) { - on_content_object_in_output_buffer_(*this, *content_object); + on_content_object_in_output_buffer_(*getInterface(), *content_object); } - TRANSPORT_LOGD("Send content %u (produce)", content_object->getName().getSuffix()); + 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); + on_content_object_output_(*getInterface(), *content_object); } uint32_t old_curr = currentSeg_.load(); @@ -199,7 +182,7 @@ void RTCProducerSocket::onInterest(Interest::Ptr &&interest) { uint32_t lifetime = interest->getLifetime(); if (on_interest_input_) { - on_interest_input_(*this, *interest); + on_interest_input_(*getInterface(), *interest); } uint64_t now = std::chrono::duration_cast<std::chrono::milliseconds>( @@ -216,19 +199,20 @@ void RTCProducerSocket::onInterest(Interest::Ptr &&interest) { if (content_object) { if (on_interest_satisfied_output_buffer_) { - on_interest_satisfied_output_buffer_(*this, *interest); + on_interest_satisfied_output_buffer_(*getInterface(), *interest); } if (on_content_object_output_) { - on_content_object_output_(*this, *content_object); + on_content_object_output_(*getInterface(), *content_object); } - TRANSPORT_LOGD("Send content %u (onInterest)", content_object->getName().getSuffix()); + 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); + on_interest_process_(*getInterface(), *interest); } } @@ -356,13 +340,13 @@ void RTCProducerSocket::sendNack(uint32_t sequence) { nack.setPathLabel(prodLabel_); if (on_content_object_output_) { - on_content_object_output_(*this, nack); + on_content_object_output_(*getInterface(), nack); } TRANSPORT_LOGD("Send nack %u", sequence); portal_->sendContentObject(nack); } -} // namespace interface +} // namespace implementation } // end namespace transport diff --git a/libtransport/src/hicn/transport/interfaces/rtc_socket_producer.h b/libtransport/src/implementation/rtc_socket_producer.h index d7917a8c0..87db2121d 100644 --- a/libtransport/src/hicn/transport/interfaces/rtc_socket_producer.h +++ b/libtransport/src/implementation/rtc_socket_producer.h @@ -15,32 +15,27 @@ #pragma once -#include <hicn/transport/interfaces/socket_producer.h> -#include <hicn/transport/utils/content_store.h> +#include <implementation/socket_producer.h> +#include <utils/content_store.h> #include <atomic> #include <map> #include <mutex> namespace transport { - -namespace interface { +namespace implementation { class RTCProducerSocket : virtual public ProducerSocket { public: - RTCProducerSocket(asio::io_service &io_service); - - RTCProducerSocket(); + RTCProducerSocket(interface::ProducerSocket *producer_socket); ~RTCProducerSocket(); void registerPrefix(const Prefix &producer_namespace) override; - - virtual void produce(std::unique_ptr<utils::MemBuf> &&buffer) override; - - void onInterest(Interest::Ptr &&interest) override; + void produce(std::unique_ptr<utils::MemBuf> &&buffer) override; private: + void onInterest(Interest::Ptr &&interest) override; void sendNack(uint32_t sequence); void updateStats(); void scheduleCacheTimer(uint64_t wait); @@ -66,14 +61,14 @@ class RTCProducerSocket : virtual public ProducerSocket { // 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_; + 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_; + 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 +} // namespace implementation } // end namespace transport diff --git a/libtransport/src/hicn/transport/interfaces/socket.h b/libtransport/src/implementation/socket.h index 4c9bda7df..2e51f3027 100644 --- a/libtransport/src/hicn/transport/interfaces/socket.h +++ b/libtransport/src/implementation/socket.h @@ -16,11 +16,12 @@ #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> +#include <core/facade.h> + #define SOCKET_OPTION_GET 0 #define SOCKET_OPTION_NOT_GET 1 #define SOCKET_OPTION_SET 2 @@ -28,8 +29,7 @@ #define SOCKET_OPTION_DEFAULT 12345 namespace transport { - -namespace interface { +namespace implementation { // Forward Declarations template <typename PortalType> @@ -82,11 +82,8 @@ class Socket { protected: virtual ~Socket(){}; - - protected: - std::string output_interface_; }; -} // namespace interface +} // namespace implementation } // namespace transport diff --git a/libtransport/src/implementation/socket_consumer.h b/libtransport/src/implementation/socket_consumer.h new file mode 100644 index 000000000..2fc8d2b48 --- /dev/null +++ b/libtransport/src/implementation/socket_consumer.h @@ -0,0 +1,950 @@ +/* + * 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/interfaces/socket_consumer.h> +#include <hicn/transport/interfaces/socket_options_default_values.h> +#include <hicn/transport/interfaces/statistics.h> +#include <hicn/transport/security/verifier.h> + +#include <protocols/cbr.h> +#include <protocols/protocol.h> +#include <protocols/raaqm.h> +#include <protocols/rtc.h> +#include <utils/event_thread.h> + +namespace transport { +namespace implementation { + +using namespace core; +using namespace interface; +using ReadCallback = interface::ConsumerSocket::ReadCallback; + +class ConsumerSocket : public Socket<BasePortal> { + public: + ConsumerSocket(interface::ConsumerSocket *consumer, int protocol) + : consumer_interface_(consumer), + 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), + 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<protocol::CbrTransportProtocol>(this); + break; + case TransportProtocolAlgorithms::RTC: + transport_protocol_ = + std::make_unique<protocol::RTCTransportProtocol>(this); + break; + case TransportProtocolAlgorithms::RAAQM: + default: + transport_protocol_ = + std::make_unique<protocol::RaaqmTransportProtocol>(this); + break; + } + } + + ~ConsumerSocket() { + stop(); + async_downloader_.stop(); + } + + interface::ConsumerSocket *getInterface() { + return consumer_interface_; + } + + void setInterface(interface::ConsumerSocket *consumer_socket) { + consumer_interface_ = consumer_socket; + } + + void connect() { portal_->connect(); } + + bool isRunning() { return transport_protocol_->isRunning(); } + + virtual int consume(const Name &name) { + if (transport_protocol_->isRunning()) { + return CONSUMER_BUSY; + } + + network_name_ = name; + network_name_.setSuffix(0); + + transport_protocol_->start(); + + return CONSUMER_FINISHED; + } + + virtual int 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 verifyKeyPackets() { return transport_protocol_->verifyKeyPackets(); } + + void stop() { + if (transport_protocol_->isRunning()) { + transport_protocol_->stop(); + } + } + + void resume() { + if (!transport_protocol_->isRunning()) { + transport_protocol_->resume(); + } + } + + asio::io_service &getIoService() { return portal_->getIoService(); } + + virtual int 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 getSocketOption(int socket_option_key, + interface::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 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; + }); + } + + protected: + 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; + } + + protected: + interface::ConsumerSocket *consumer_interface_; + asio::io_service io_service_; + + std::shared_ptr<Portal> portal_; + utils::EventThread async_downloader_; + + // No need to protect from multiple accesses in the async consumer + // The parameter is accessible only with a getSocketOption and + // set from the consume + 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_; + 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_; + 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<protocol::TransportProtocol> transport_protocol_; + + // Statistic + TransportStatistics stats_; + + utils::SpinLock guard_raaqm_params_; + std::string output_interface_; +}; + +} // namespace implementation +} // namespace transport
\ No newline at end of file diff --git a/libtransport/src/implementation/socket_producer.h b/libtransport/src/implementation/socket_producer.h new file mode 100644 index 000000000..1f03fe53d --- /dev/null +++ b/libtransport/src/implementation/socket_producer.h @@ -0,0 +1,1061 @@ +/* + * 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/security/signer.h> + +#include <implementation/socket.h> + +#include <utils/content_store.h> +#include <utils/event_thread.h> +#include <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 implementation { + +using namespace core; +using namespace interface; + +class ProducerSocket : public Socket<BasePortal>, + public BasePortal::ProducerCallback { + public: + explicit ProducerSocket(interface::ProducerSocket *producer_socket) + : producer_interface_(producer_socket), + 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) {} + + virtual ~ProducerSocket() { + stop(); + if (listening_thread_.joinable()) { + listening_thread_.join(); + } + } + + interface::ProducerSocket *getInterface() { + return producer_interface_; + } + + void setInterface(interface::ProducerSocket *producer_socket) { + producer_interface_ = producer_socket; + } + + void connect() override { + portal_->connect(false); + listening_thread_ = std::thread(std::bind(&ProducerSocket::listen, this)); + } + + 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) { + 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_(*producer_interface_, + std::make_error_code(std::errc(0)), buffer_size); + } + }); + + TRANSPORT_LOGD("--------- END PRODUCE ------------"); + return suffix_strategy->getTotalCount(); + } + + virtual void produce(ContentObject &content_object) { + io_service_.dispatch([this, &content_object]() { + if (on_content_object_in_output_buffer_) { + on_content_object_in_output_buffer_(*producer_interface_, + 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_(*producer_interface_, content_object); + } + }); + + portal_->sendContentObject(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) { + if (!async_thread_.stopped()) { + async_thread_.add([this, suffix, buffer = buf, size = buffer_size, + is_last, start_offset]() { + if (start_offset != nullptr) { + *start_offset = ProducerSocket::produce(suffix, buffer, size, is_last, + *start_offset); + } else { + ProducerSocket::produce(suffix, buffer, size, is_last, 0); + } + }); + } + } + + 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) { + 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); + } + }); + } + } + + virtual void 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); + }); + } + } + + virtual void registerPrefix(const Prefix &producer_namespace) { + served_namespaces_.push_back(producer_namespace); + } + + void serveForever() { + if (listening_thread_.joinable()) { + listening_thread_.join(); + } + } + + void stop() { portal_->stopEventsLoop(); } + + asio::io_service &getIoService() override { return portal_->getIoService(); }; + + virtual void onInterest(Interest &interest) { + if (on_interest_input_) { + on_interest_input_(*producer_interface_, 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_(*producer_interface_, interest); + } + + if (on_content_object_output_) { + on_content_object_output_(*producer_interface_, *content_object); + } + + portal_->sendContentObject(*content_object); + } else { + if (on_interest_process_) { + on_interest_process_(*producer_interface_, interest); + } + } + } + + virtual void onInterest(Interest::Ptr &&interest) override { + onInterest(*interest); + }; + + virtual int 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; + } + + virtual int 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; + }); + } + + virtual int 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; + } + + virtual int setSocketOption(int socket_option_key, + Name *socket_option_value) { + return SOCKET_OPTION_NOT_SET; + } + + virtual int 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; + } + + virtual int setSocketOption( + int socket_option_key, + interface::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; + }); + } + + virtual int setSocketOption( + int socket_option_key, + interface::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; + }); + } + + virtual int setSocketOption( + int socket_option_key, + interface::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; + }); + } + + virtual int 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; + } + + virtual int 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; + } + + virtual int 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; + } + + virtual int 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; + } + + virtual int 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; + } + + virtual int 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; + } + + virtual int getSocketOption( + int socket_option_key, + interface::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; + }); + } + + virtual int getSocketOption( + int socket_option_key, + interface::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; + }); + } + + virtual int getSocketOption( + int socket_option_key, + interface::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; + }); + } + + virtual int 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; + } + + virtual int 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; + } + + virtual int 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; + } + + virtual int 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; + } + + virtual int setSocketOption(int socket_option_key, + const std::string &socket_option_value) { + return SOCKET_OPTION_NOT_SET; + } + + // 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; + } + + // 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 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; + std::unique_lock<std::mutex> lck(mtx); + 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); + + if (!done) { + cv.wait(lck); + } + }); + } else { + result = func(socket_option_key, socket_option_value); + } + + return result; + } + + // Threads + protected: + interface::ProducerSocket *producer_interface_; + std::thread listening_thread_; + 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() { + 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 passContentObjectToCallbacks( + const std::shared_ptr<ContentObject> &content_object) { + if (content_object) { + io_service_.dispatch([this, content_object]() { + if (on_new_segment_) { + on_new_segment_(*producer_interface_, *content_object); + } + + if (on_content_object_to_sign_) { + on_content_object_to_sign_(*producer_interface_, *content_object); + } + + if (on_content_object_in_output_buffer_) { + on_content_object_in_output_buffer_(*producer_interface_, + *content_object); + } + }); + + output_buffer_.insert(content_object); + + io_service_.dispatch([this, content_object]() { + if (on_content_object_output_) { + on_content_object_output_(*producer_interface_, *content_object); + } + }); + + portal_->sendContentObject(*content_object); + } + } +}; // namespace implementation + +} // namespace implementation + +} // namespace transport diff --git a/libtransport/src/hicn/transport/interfaces/tls_rtc_socket_producer.cc b/libtransport/src/implementation/tls_rtc_socket_producer.cc index 27c1e54bd..3b3152993 100644 --- a/libtransport/src/hicn/transport/interfaces/tls_rtc_socket_producer.cc +++ b/libtransport/src/implementation/tls_rtc_socket_producer.cc @@ -1,14 +1,31 @@ +/* + * 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/interfaces/p2psecure_socket_producer.h> -#include <hicn/transport/interfaces/tls_rtc_socket_producer.h> + +#include <implementation/p2psecure_socket_producer.h> +#include <implementation/tls_rtc_socket_producer.h> #include <openssl/bio.h> #include <openssl/rand.h> #include <openssl/ssl.h> namespace transport { +namespace implementation { -namespace interface { int TLSRTCProducerSocket::read(BIO *b, char *buf, size_t size, size_t *readbytes) { int ret; @@ -99,7 +116,9 @@ int TLSRTCProducerSocket::writeOld(BIO *b, const char *buf, int num) { on_content_produced_application); if (socket->to_call_oncontentproduced_ == 0 && on_content_produced_application) { - on_content_produced_application(*socket, std::error_code(), 0); + on_content_produced_application( + (transport::interface::ProducerSocket &)(*socket->getInterface()), + std::error_code(), 0); } }); } @@ -107,9 +126,12 @@ int TLSRTCProducerSocket::writeOld(BIO *b, const char *buf, int num) { return num; } -TLSRTCProducerSocket::TLSRTCProducerSocket(P2PSecureProducerSocket *parent, - const Name &handshake_name) - : RTCProducerSocket(), TLSProducerSocket(parent, handshake_name) { +TLSRTCProducerSocket::TLSRTCProducerSocket( + interface::ProducerSocket *producer_socket, P2PSecureProducerSocket *parent, + const Name &handshake_name) + : ProducerSocket(producer_socket), + RTCProducerSocket(producer_socket), + TLSProducerSocket(producer_socket, 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); @@ -140,7 +162,8 @@ void TLSRTCProducerSocket::accept() { if (on_interest_process_decrypted) { Interest inter(std::move(packet_)); - on_interest_process_decrypted(*this, inter); + on_interest_process_decrypted( + (transport::interface::ProducerSocket &)(*getInterface()), inter); } parent_->cv_.notify_one(); @@ -173,6 +196,6 @@ void TLSRTCProducerSocket::produce(std::unique_ptr<utils::MemBuf> &&buffer) { (void)i; // To shut up gcc 5 } -} // namespace interface +} // namespace implementation } // namespace transport diff --git a/libtransport/src/hicn/transport/interfaces/tls_rtc_socket_producer.h b/libtransport/src/implementation/tls_rtc_socket_producer.h index 16125f889..685c91244 100644 --- a/libtransport/src/hicn/transport/interfaces/tls_rtc_socket_producer.h +++ b/libtransport/src/implementation/tls_rtc_socket_producer.h @@ -15,12 +15,11 @@ #pragma once -#include <hicn/transport/interfaces/rtc_socket_producer.h> -#include <hicn/transport/interfaces/tls_socket_producer.h> +#include <implementation/rtc_socket_producer.h> +#include <implementation/tls_socket_producer.h> namespace transport { - -namespace interface { +namespace implementation { class P2PSecureProducerSocket; @@ -29,7 +28,8 @@ class TLSRTCProducerSocket : public RTCProducerSocket, friend class P2PSecureProducerSocket; public: - explicit TLSRTCProducerSocket(P2PSecureProducerSocket *parent, + explicit TLSRTCProducerSocket(interface::ProducerSocket *producer_socket, + P2PSecureProducerSocket *parent, const Name &handshake_name); ~TLSRTCProducerSocket() = default; @@ -40,8 +40,8 @@ class TLSRTCProducerSocket : public RTCProducerSocket, int async_accept() override; - using TLSProducerSocket::produce; using TLSProducerSocket::onInterest; + using TLSProducerSocket::produce; protected: static int read(BIO *b, char *buf, size_t size, size_t *readbytes); @@ -53,6 +53,6 @@ class TLSRTCProducerSocket : public RTCProducerSocket, static int writeOld(BIO *h, const char *buf, int num); }; -} // namespace interface +} // namespace implementation } // end namespace transport diff --git a/libtransport/src/hicn/transport/interfaces/tls_socket_consumer.cc b/libtransport/src/implementation/tls_socket_consumer.cc index 58b3c1d7d..95b287aa6 100644 --- a/libtransport/src/hicn/transport/interfaces/tls_socket_consumer.cc +++ b/libtransport/src/implementation/tls_socket_consumer.cc @@ -1,4 +1,20 @@ -#include <hicn/transport/interfaces/tls_socket_consumer.h> +/* + * 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 <implementation/tls_socket_consumer.h> + #include <openssl/bio.h> #include <openssl/ssl.h> #include <openssl/tls1.h> @@ -6,10 +22,9 @@ #include <random> namespace transport { +namespace implementation { -namespace interface { - -void TLSConsumerSocket::setInterestPayload(ConsumerSocket &c, +void TLSConsumerSocket::setInterestPayload(interface::ConsumerSocket &c, const core::Interest &interest) { Interest &int2 = const_cast<Interest &>(interest); random_suffix_ = int2.getName().getSuffix(); @@ -68,7 +83,7 @@ int readTLS(BIO *b, char *buf, size_t size, size_t *readbytes) { if (size > INT_MAX) size = INT_MAX; - ret = transport::interface::readOldTLS(b, buf, (int)size); + ret = readOldTLS(b, buf, (int)size); if (ret <= 0) { *readbytes = 0; @@ -101,7 +116,7 @@ int writeTLS(BIO *b, const char *buf, size_t size, size_t *written) { if (size > INT_MAX) size = INT_MAX; - ret = transport::interface::writeOldTLS(b, buf, (int)size); + ret = writeOldTLS(b, buf, (int)size); if (ret <= 0) { *written = 0; @@ -115,8 +130,9 @@ int writeTLS(BIO *b, const char *buf, size_t size, size_t *written) { long ctrlTLS(BIO *b, int cmd, long num, void *ptr) { return 1; } -TLSConsumerSocket::TLSConsumerSocket(int protocol, SSL *ssl) - : ConsumerSocket(protocol), +TLSConsumerSocket::TLSConsumerSocket(interface::ConsumerSocket *consumer_socket, + int protocol, SSL *ssl) + : ConsumerSocket(consumer_socket, protocol), name_(), buf_pool_(), decrypted_content_(), @@ -125,7 +141,6 @@ TLSConsumerSocket::TLSConsumerSocket(int protocol, SSL *ssl) something_to_read_(false), content_downloaded_(false), random_suffix_(), - secure_prefix_(), producer_namespace_(), read_callback_decrypted_(), mtx_(), @@ -153,9 +168,9 @@ TLSConsumerSocket::TLSConsumerSocket(int protocol, 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_meth_set_read(bio_meth, readOldTLS); + BIO_meth_set_write(bio_meth, writeOldTLS); + BIO_meth_set_ctrl(bio_meth, ctrlTLS); BIO *bio = BIO_new(bio_meth); BIO_set_init(bio, 1); BIO_set_data(bio, this); @@ -176,6 +191,12 @@ TLSConsumerSocket::TLSConsumerSocket(int protocol, SSL *ssl) this); }; +/* + * The producer interface is not owned by the application, so is TLSSocket task + * to deallocate the memory + */ +TLSConsumerSocket::~TLSConsumerSocket() { delete consumer_interface_; } + int TLSConsumerSocket::consume(const Name &name, std::unique_ptr<utils::MemBuf> &&buffer) { this->payload_ = std::move(buffer); @@ -308,12 +329,11 @@ void TLSConsumerSocket::registerPrefix(const Prefix &producer_namespace) { producer_namespace_ = producer_namespace; } -int TLSConsumerSocket::setSocketOption( - int socket_option_key, ConsumerSocket::ReadCallback *socket_option_value) { +int TLSConsumerSocket::setSocketOption(int socket_option_key, + ReadCallback *socket_option_value) { return rescheduleOnIOService( socket_option_key, socket_option_value, - [this](int socket_option_key, - ConsumerSocket::ReadCallback *socket_option_value) -> int { + [this](int socket_option_key, ReadCallback *socket_option_value) -> int { switch (socket_option_key) { case ConsumerCallbacksOptions::READ_CALLBACK: read_callback_decrypted_ = socket_option_value; @@ -359,6 +379,6 @@ void TLSConsumerSocket::readSuccess(std::size_t total_size) noexcept { bool TLSConsumerSocket::isBufferMovable() noexcept { return true; } -} // namespace interface +} // namespace implementation } // namespace transport diff --git a/libtransport/src/hicn/transport/interfaces/tls_socket_consumer.h b/libtransport/src/implementation/tls_socket_consumer.h index 05f7fe6a5..2e88dc47e 100644 --- a/libtransport/src/hicn/transport/interfaces/tls_socket_consumer.h +++ b/libtransport/src/implementation/tls_socket_consumer.h @@ -16,14 +16,16 @@ #pragma once #include <hicn/transport/interfaces/socket_consumer.h> + +#include <implementation/socket_consumer.h> + #include <openssl/ssl.h> namespace transport { - -namespace interface { +namespace implementation { class TLSConsumerSocket : public ConsumerSocket, - public ConsumerSocket::ReadCallback { + public interface::ConsumerSocket::ReadCallback { /* Return the number of read bytes in readbytes */ friend int readTLS(BIO *b, char *buf, size_t size, size_t *readbytes); @@ -39,9 +41,10 @@ class TLSConsumerSocket : public ConsumerSocket, friend long ctrlTLS(BIO *b, int cmd, long num, void *ptr); public: - explicit TLSConsumerSocket(int protocol, SSL *ssl_); + explicit TLSConsumerSocket(interface::ConsumerSocket *consumer_socket, + int protocol, SSL *ssl_); - ~TLSConsumerSocket() = default; + ~TLSConsumerSocket(); int consume(const Name &name, std::unique_ptr<utils::MemBuf> &&buffer); int consume(const Name &name) override; @@ -53,7 +56,7 @@ class TLSConsumerSocket : public ConsumerSocket, int setSocketOption( int socket_option_key, - ConsumerSocket::ReadCallback *socket_option_value) override; + interface::ConsumerSocket::ReadCallback *socket_option_value) override; using ConsumerSocket::getSocketOption; using ConsumerSocket::setSocketOption; @@ -76,7 +79,8 @@ class TLSConsumerSocket : public ConsumerSocket, 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 */ + /* 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 */ @@ -92,11 +96,9 @@ class TLSConsumerSocket : public ConsumerSocket, uint32_t random_suffix_; - ip_address_t secure_prefix_; - Prefix producer_namespace_; - ConsumerSocket::ReadCallback *read_callback_decrypted_; + interface::ConsumerSocket::ReadCallback *read_callback_decrypted_; std::mutex mtx_; @@ -105,9 +107,8 @@ class TLSConsumerSocket : public ConsumerSocket, 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); + void setInterestPayload(interface::ConsumerSocket &c, + const core::Interest &interest); virtual void getReadBuffer(uint8_t **application_buffer, size_t *max_length) override; @@ -127,6 +128,6 @@ class TLSConsumerSocket : public ConsumerSocket, int download_content(const Name &name); }; -} // namespace interface +} // namespace implementation } // end namespace transport
\ No newline at end of file diff --git a/libtransport/src/hicn/transport/interfaces/tls_socket_producer.cc b/libtransport/src/implementation/tls_socket_producer.cc index ad85ec6ea..9a5b94a1c 100644 --- a/libtransport/src/hicn/transport/interfaces/tls_socket_producer.cc +++ b/libtransport/src/implementation/tls_socket_producer.cc @@ -1,14 +1,29 @@ -#include <hicn/transport/core/interest.h> -#include <hicn/transport/interfaces/p2psecure_socket_producer.h> -#include <hicn/transport/interfaces/tls_socket_producer.h> +/* + * 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/interfaces/socket_producer.h> + +#include <implementation/p2psecure_socket_producer.h> +#include <implementation/tls_socket_producer.h> #include <openssl/bio.h> #include <openssl/rand.h> #include <openssl/ssl.h> namespace transport { - -namespace interface { +namespace implementation { /* Return the number of read bytes in readbytes */ int TLSProducerSocket::read(BIO *b, char *buf, size_t size, size_t *readbytes) { @@ -113,7 +128,8 @@ int TLSProducerSocket::writeOld(BIO *b, const char *buf, int num) { on_content_produced_application); if (socket->to_call_oncontentproduced_ == 0 && on_content_produced_application) { - on_content_produced_application(*socket, std::error_code(), 0); + on_content_produced_application(*socket->getInterface(), + std::error_code(), 0); } }); } @@ -121,9 +137,10 @@ int TLSProducerSocket::writeOld(BIO *b, const char *buf, int num) { return num; } -TLSProducerSocket::TLSProducerSocket(P2PSecureProducerSocket *parent, +TLSProducerSocket::TLSProducerSocket(interface::ProducerSocket *producer_socket, + P2PSecureProducerSocket *parent, const Name &handshake_name) - : ProducerSocket(), + : ProducerSocket(producer_socket), on_content_produced_application_(), mtx_(), cv_(), @@ -196,6 +213,12 @@ TLSProducerSocket::TLSProducerSocket(P2PSecureProducerSocket *parent, std::placeholders::_2, std::placeholders::_3)); } +/* + * The producer interface is not owned by the application, so is TLSSocket task + * to deallocate the memory + */ +TLSProducerSocket::~TLSProducerSocket() { delete producer_interface_; } + void TLSProducerSocket::accept() { if (SSL_in_before(ssl_) || SSL_in_init(ssl_)) { tls_chunks_ = 1; @@ -214,7 +237,7 @@ void TLSProducerSocket::accept() { if (on_interest_process_decrypted) { Interest inter(std::move(packet_)); - on_interest_process_decrypted(*this, inter); + on_interest_process_decrypted(*getInterface(), inter); } else { throw errors::RuntimeException( "On interest process unset. Unable to perform handshake"); @@ -262,10 +285,11 @@ void TLSProducerSocket::onInterest(ProducerSocket &p, Interest &interest) { getSocketOption(ProducerCallbacksOptions::INTEREST_INPUT, on_interest_input_decrypted); if (on_interest_input_decrypted) - (on_interest_input_decrypted)(*this, interest); + (on_interest_input_decrypted)(*getInterface(), interest); } -void TLSProducerSocket::cacheMiss(ProducerSocket &p, Interest &interest) { +void TLSProducerSocket::cacheMiss(interface::ProducerSocket &p, + Interest &interest) { if (SSL_in_before(ssl_) || SSL_in_init(ssl_)) { std::unique_lock<std::mutex> lck(mtx_); name_ = interest.getName(); @@ -286,11 +310,11 @@ void TLSProducerSocket::cacheMiss(ProducerSocket &p, Interest &interest) { interest.getPayload()->length()); if (on_interest_process_decrypted_ != VOID_HANDLER) - on_interest_process_decrypted_(*this, interest); + on_interest_process_decrypted_(*getInterface(), interest); } } -void TLSProducerSocket::onContentProduced(ProducerSocket &p, +void TLSProducerSocket::onContentProduced(interface::ProducerSocket &p, const std::error_code &err, uint64_t bytes_written) {} @@ -582,6 +606,6 @@ int TLSProducerSocket::getSocketOption( }); } -} // namespace interface +} // namespace implementation } // namespace transport diff --git a/libtransport/src/hicn/transport/interfaces/tls_socket_producer.h b/libtransport/src/implementation/tls_socket_producer.h index 4c09ddaa5..e910c8259 100644 --- a/libtransport/src/hicn/transport/interfaces/tls_socket_producer.h +++ b/libtransport/src/implementation/tls_socket_producer.h @@ -15,16 +15,14 @@ #pragma once -#include <hicn/transport/interfaces/socket_producer.h> -#include <hicn/transport/utils/content_store.h> +#include <implementation/socket_producer.h> #include <openssl/ssl.h> #include <condition_variable> #include <mutex> namespace transport { - -namespace interface { +namespace implementation { class P2PSecureProducerSocket; @@ -32,9 +30,11 @@ class TLSProducerSocket : virtual public ProducerSocket { friend class P2PSecureProducerSocket; public: - explicit TLSProducerSocket(P2PSecureProducerSocket *parent, + explicit TLSProducerSocket(interface::ProducerSocket *producer_socket, + P2PSecureProducerSocket *parent, const Name &handshake_name); - ~TLSProducerSocket() = default; + + ~TLSProducerSocket(); uint32_t produce(Name content_name, const uint8_t *buffer, size_t buffer_size, bool is_last = true, uint32_t start_offset = 0) override { @@ -125,7 +125,7 @@ class TLSProducerSocket : virtual public ProducerSocket { utils::EventThread encryption_thread_; void onInterest(ProducerSocket &p, Interest &interest); - void cacheMiss(ProducerSocket &p, Interest &interest); + void cacheMiss(interface::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); @@ -154,10 +154,10 @@ class TLSProducerSocket : virtual public ProducerSocket { 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); + void onContentProduced(interface::ProducerSocket &p, + const std::error_code &err, uint64_t bytes_written); }; -} // namespace interface +} // namespace implementation } // end namespace transport diff --git a/libtransport/src/interfaces/CMakeLists.txt b/libtransport/src/interfaces/CMakeLists.txt new file mode 100644 index 000000000..daf4b31e5 --- /dev/null +++ b/libtransport/src/interfaces/CMakeLists.txt @@ -0,0 +1,39 @@ +# 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}/rtc_socket_producer.cc + ${CMAKE_CURRENT_SOURCE_DIR}/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}/p2psecure_socket_producer.cc + ${CMAKE_CURRENT_SOURCE_DIR}/p2psecure_socket_consumer.cc + ${CMAKE_CURRENT_SOURCE_DIR}/tls_rtc_socket_producer.cc + ${CMAKE_CURRENT_SOURCE_DIR}/tls_socket_producer.cc + ${CMAKE_CURRENT_SOURCE_DIR}/tls_socket_consumer.cc + ) + + list(APPEND HEADER_FILES + ${CMAKE_CURRENT_SOURCE_DIR}/tls_rtc_socket_producer.h + ${CMAKE_CURRENT_SOURCE_DIR}/tls_socket_producer.h + ${CMAKE_CURRENT_SOURCE_DIR}/tls_socket_consumer.h + ) +endif() + +set(SOURCE_FILES ${SOURCE_FILES} PARENT_SCOPE) diff --git a/libtransport/src/hicn/transport/interfaces/callbacks.cc b/libtransport/src/interfaces/callbacks.cc index 2574e7720..6869ac3f7 100644 --- a/libtransport/src/hicn/transport/interfaces/callbacks.cc +++ b/libtransport/src/interfaces/callbacks.cc @@ -13,7 +13,7 @@ * limitations under the License. */ -#include "callbacks.h" +#include <hicn/transport/interfaces/callbacks.h> namespace transport { diff --git a/libtransport/src/interfaces/p2psecure_socket_consumer.cc b/libtransport/src/interfaces/p2psecure_socket_consumer.cc new file mode 100644 index 000000000..2fa8bb6e3 --- /dev/null +++ b/libtransport/src/interfaces/p2psecure_socket_consumer.cc @@ -0,0 +1,32 @@ +/* + * 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/p2psecure_socket_consumer.h> + +#include <implementation/p2psecure_socket_consumer.h> + +namespace transport { +namespace interface { + +P2PSecureConsumerSocket::P2PSecureConsumerSocket(int handshake_protocol, + int protocol) + : ConsumerSocket() { + socket_ = std::unique_ptr<implementation::ConsumerSocket>( + new implementation::P2PSecureConsumerSocket(this, handshake_protocol, + protocol)); +} + +} // namespace interface +} // namespace transport diff --git a/libtransport/src/hicn/transport/interfaces/publication_options.h b/libtransport/src/interfaces/p2psecure_socket_producer.cc index 6910e5371..37352259c 100644 --- a/libtransport/src/hicn/transport/interfaces/publication_options.h +++ b/libtransport/src/interfaces/p2psecure_socket_producer.cc @@ -13,31 +13,22 @@ * limitations under the License. */ -#pragma once +#include <hicn/transport/interfaces/p2psecure_socket_producer.h> -#include <hicn/transport/core/name.h> +#include <implementation/p2psecure_socket_producer.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) {} +P2PSecureProducerSocket::P2PSecureProducerSocket() { + socket_ = std::make_unique<implementation::P2PSecureProducerSocket>(this); +} - TRANSPORT_ALWAYS_INLINE const core::Name& getName() const { return name_; } - TRANSPORT_ALWAYS_INLINE uint32_t getLifetime() const { - return content_lifetime_milliseconds_; - } +P2PSecureProducerSocket::P2PSecureProducerSocket( + bool rtc, const std::shared_ptr<utils::Identity> &identity) { + socket_ = std::make_unique<implementation::P2PSecureProducerSocket>(this, rtc, + identity); +} - private: - core::Name name_; - uint32_t content_lifetime_milliseconds_; - // TODO Signature -}; } // namespace interface - -} // namespace transport
\ No newline at end of file +} // namespace transport diff --git a/libtransport/src/hicn/transport/http/default_values.h b/libtransport/src/interfaces/rtc_socket_producer.cc index 2d5a6b821..07d72db7e 100644 --- a/libtransport/src/hicn/transport/http/default_values.h +++ b/libtransport/src/interfaces/rtc_socket_producer.cc @@ -13,20 +13,17 @@ * limitations under the License. */ -#pragma once +#include <hicn/transport/interfaces/rtc_socket_producer.h> -#include <cstdint> +#include <implementation/rtc_socket_producer.h> namespace transport { +namespace interface { -namespace http { +RTCProducerSocket::RTCProducerSocket() : ProducerSocket(false) { + socket_ = std::make_unique<implementation::RTCProducerSocket>(this); +} -namespace default_values { +} // namespace interface -const uint16_t ipv6_first_word = 0xb001; // Network byte order - -} // namespace default_values - -} // namespace http - -} // end namespace transport +} // namespace transport diff --git a/libtransport/src/interfaces/socket_consumer.cc b/libtransport/src/interfaces/socket_consumer.cc new file mode 100644 index 000000000..b4be16ade --- /dev/null +++ b/libtransport/src/interfaces/socket_consumer.cc @@ -0,0 +1,196 @@ +/* + * 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 <implementation/socket_consumer.h> + +namespace transport { +namespace interface { + +ConsumerSocket::ConsumerSocket(int protocol) { + socket_ = std::make_unique<implementation::ConsumerSocket>(this, protocol); +} + +ConsumerSocket::ConsumerSocket() {} + +ConsumerSocket::~ConsumerSocket() { socket_->stop(); } + +void ConsumerSocket::connect() { socket_->connect(); } + +bool ConsumerSocket::isRunning() { return socket_->isRunning(); } + +int ConsumerSocket::consume(const Name &name) { return socket_->consume(name); } + +int ConsumerSocket::asyncConsume(const Name &name) { + return socket_->asyncConsume(name); +} + +void ConsumerSocket::stop() { socket_->stop(); } + +void ConsumerSocket::resume() { socket_->resume(); } + +bool ConsumerSocket::verifyKeyPackets() { return socket_->verifyKeyPackets(); } + +asio::io_service &ConsumerSocket::getIoService() { + return socket_->getIoService(); +} + +int ConsumerSocket::setSocketOption(int socket_option_key, + ReadCallback *socket_option_value) { + return socket_->setSocketOption(socket_option_key, socket_option_value); +} + +int ConsumerSocket::getSocketOption(int socket_option_key, + ReadCallback **socket_option_value) { + return socket_->getSocketOption(socket_option_key, socket_option_value); +} + +int ConsumerSocket::setSocketOption(int socket_option_key, + double socket_option_value) { + return socket_->setSocketOption(socket_option_key, socket_option_value); +} + +int ConsumerSocket::setSocketOption(int socket_option_key, + uint32_t socket_option_value) { + return socket_->setSocketOption(socket_option_key, socket_option_value); +} + +int ConsumerSocket::setSocketOption(int socket_option_key, + std::nullptr_t socket_option_value) { + return socket_->setSocketOption(socket_option_key, socket_option_value); +} + +int ConsumerSocket::setSocketOption(int socket_option_key, + bool socket_option_value) { + return socket_->setSocketOption(socket_option_key, socket_option_value); +} + +int ConsumerSocket::setSocketOption( + int socket_option_key, ConsumerContentObjectCallback socket_option_value) { + return socket_->setSocketOption(socket_option_key, socket_option_value); +} + +int ConsumerSocket::setSocketOption( + int socket_option_key, + ConsumerContentObjectVerificationCallback socket_option_value) { + return socket_->setSocketOption(socket_option_key, socket_option_value); +} + +int ConsumerSocket::setSocketOption( + int socket_option_key, ConsumerInterestCallback socket_option_value) { + return socket_->setSocketOption(socket_option_key, socket_option_value); +} + +int ConsumerSocket::setSocketOption( + int socket_option_key, + ConsumerContentObjectVerificationFailedCallback socket_option_value) { + return socket_->setSocketOption(socket_option_key, socket_option_value); +} + +int ConsumerSocket::setSocketOption(int socket_option_key, + IcnObserver *socket_option_value) { + return socket_->setSocketOption(socket_option_key, socket_option_value); +} + +int ConsumerSocket::setSocketOption( + int socket_option_key, + const std::shared_ptr<utils::Verifier> &socket_option_value) { + return socket_->setSocketOption(socket_option_key, socket_option_value); +} + +int ConsumerSocket::setSocketOption(int socket_option_key, + const std::string &socket_option_value) { + return socket_->setSocketOption(socket_option_key, socket_option_value); +} + +int ConsumerSocket::setSocketOption(int socket_option_key, + ConsumerTimerCallback socket_option_value) { + return socket_->setSocketOption(socket_option_key, socket_option_value); +} + +int ConsumerSocket::getSocketOption(int socket_option_key, + double &socket_option_value) { + return socket_->getSocketOption(socket_option_key, socket_option_value); +} + +int ConsumerSocket::getSocketOption(int socket_option_key, + uint32_t &socket_option_value) { + return socket_->getSocketOption(socket_option_key, socket_option_value); +} + +int ConsumerSocket::getSocketOption(int socket_option_key, + bool &socket_option_value) { + return socket_->getSocketOption(socket_option_key, socket_option_value); +} + +int ConsumerSocket::getSocketOption(int socket_option_key, + Name **socket_option_value) { + return socket_->getSocketOption(socket_option_key, socket_option_value); +} + +int ConsumerSocket::getSocketOption( + int socket_option_key, + ConsumerContentObjectCallback **socket_option_value) { + return socket_->setSocketOption(socket_option_key, socket_option_value); +} + +int ConsumerSocket::getSocketOption( + int socket_option_key, + ConsumerContentObjectVerificationCallback **socket_option_value) { + return socket_->setSocketOption(socket_option_key, socket_option_value); +} + +int ConsumerSocket::getSocketOption( + int socket_option_key, ConsumerInterestCallback **socket_option_value) { + return socket_->setSocketOption(socket_option_key, socket_option_value); +} + +int ConsumerSocket::getSocketOption( + int socket_option_key, + ConsumerContentObjectVerificationFailedCallback **socket_option_value) { + return socket_->setSocketOption(socket_option_key, socket_option_value); +} + +int ConsumerSocket::getSocketOption(int socket_option_key, + IcnObserver **socket_option_value) { + return socket_->getSocketOption(socket_option_key, socket_option_value); +} + +int ConsumerSocket::getSocketOption( + int socket_option_key, + std::shared_ptr<utils::Verifier> &socket_option_value) { + return socket_->getSocketOption(socket_option_key, socket_option_value); +} + +int ConsumerSocket::getSocketOption(int socket_option_key, + std::string &socket_option_value) { + return socket_->getSocketOption(socket_option_key, socket_option_value); +} + +int ConsumerSocket::getSocketOption( + int socket_option_key, + interface::TransportStatistics **socket_option_value) { + return socket_->getSocketOption(socket_option_key, socket_option_value); +} + +int ConsumerSocket::getSocketOption( + int socket_option_key, ConsumerTimerCallback **socket_option_value) { + return socket_->getSocketOption(socket_option_key, socket_option_value); +} + +} // namespace interface + +} // namespace transport diff --git a/libtransport/src/interfaces/socket_producer.cc b/libtransport/src/interfaces/socket_producer.cc new file mode 100644 index 000000000..679f7ccf4 --- /dev/null +++ b/libtransport/src/interfaces/socket_producer.cc @@ -0,0 +1,198 @@ +/* + * 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 <implementation/socket_producer.h> + +#include <atomic> +#include <cmath> +#include <condition_variable> +#include <mutex> +#include <queue> +#include <thread> + +namespace transport { + +namespace interface { + +using namespace core; + +ProducerSocket::ProducerSocket(int protocol) { + if (protocol != 0) { + throw std::runtime_error("Production protocol must be 0."); + } + + socket_ = std::make_unique<implementation::ProducerSocket>(this); +} + +ProducerSocket::ProducerSocket(bool) {} + +ProducerSocket::~ProducerSocket() { socket_->stop(); } + +void ProducerSocket::connect() { socket_->connect(); } + +bool ProducerSocket::isRunning() { return socket_->isRunning(); } + +uint32_t ProducerSocket::produce(Name content_name, + std::unique_ptr<utils::MemBuf> &&buffer, + bool is_last, uint32_t start_offset) { + return socket_->produce(content_name, std::move(buffer), is_last, + start_offset); +} + +void ProducerSocket::produce(ContentObject &content_object) { + return socket_->produce(content_object); +} + +void ProducerSocket::produce(std::unique_ptr<utils::MemBuf> &&buffer) { + socket_->produce(std::move(buffer)); +} + +void ProducerSocket::asyncProduce(Name content_name, + std::unique_ptr<utils::MemBuf> &&buffer, + bool is_last, uint32_t offset, + uint32_t **last_segment) { + return socket_->asyncProduce(content_name, std::move(buffer), is_last, offset, + last_segment); +} + +void ProducerSocket::asyncProduce(ContentObject &content_object) { + return socket_->asyncProduce(content_object); +} + +void ProducerSocket::registerPrefix(const Prefix &producer_namespace) { + return socket_->registerPrefix(producer_namespace); +} + +void ProducerSocket::serveForever() { return socket_->serveForever(); } + +void ProducerSocket::stop() { return socket_->stop(); } + +asio::io_service &ProducerSocket::getIoService() { + return socket_->getIoService(); +}; + +int ProducerSocket::setSocketOption(int socket_option_key, + uint32_t socket_option_value) { + return socket_->setSocketOption(socket_option_key, socket_option_value); +} + +int ProducerSocket::setSocketOption(int socket_option_key, + std::nullptr_t socket_option_value) { + return socket_->setSocketOption(socket_option_key, socket_option_value); +} + +int ProducerSocket::setSocketOption(int socket_option_key, + bool socket_option_value) { + return socket_->setSocketOption(socket_option_key, socket_option_value); +} + +int ProducerSocket::setSocketOption(int socket_option_key, + Name *socket_option_value) { + return socket_->setSocketOption(socket_option_key, socket_option_value); +} + +int ProducerSocket::setSocketOption(int socket_option_key, + std::list<Prefix> socket_option_value) { + return socket_->setSocketOption(socket_option_key, socket_option_value); +} + +int ProducerSocket::setSocketOption( + int socket_option_key, ProducerContentObjectCallback socket_option_value) { + return socket_->setSocketOption(socket_option_key, socket_option_value); +} + +int ProducerSocket::setSocketOption( + int socket_option_key, ProducerInterestCallback socket_option_value) { + return socket_->setSocketOption(socket_option_key, socket_option_value); +} + +int ProducerSocket::setSocketOption( + int socket_option_key, ProducerContentCallback socket_option_value) { + return socket_->setSocketOption(socket_option_key, socket_option_value); +} + +int ProducerSocket::setSocketOption(int socket_option_key, + HashAlgorithm socket_option_value) { + return socket_->setSocketOption(socket_option_key, socket_option_value); +} + +int ProducerSocket::setSocketOption(int socket_option_key, + utils::CryptoSuite socket_option_value) { + return socket_->setSocketOption(socket_option_key, socket_option_value); +} + +int ProducerSocket::setSocketOption( + int socket_option_key, + const std::shared_ptr<utils::Signer> &socket_option_value) { + return socket_->setSocketOption(socket_option_key, socket_option_value); +} + +int ProducerSocket::getSocketOption(int socket_option_key, + uint32_t &socket_option_value) { + return socket_->setSocketOption(socket_option_key, socket_option_value); +} + +int ProducerSocket::setSocketOption(int socket_option_key, + const std::string &socket_option_value) { + return socket_->setSocketOption(socket_option_key, socket_option_value); +} + +int ProducerSocket::getSocketOption(int socket_option_key, + bool &socket_option_value) { + return socket_->getSocketOption(socket_option_key, socket_option_value); +} + +int ProducerSocket::getSocketOption(int socket_option_key, + std::list<Prefix> &socket_option_value) { + return socket_->getSocketOption(socket_option_key, socket_option_value); +} + +int ProducerSocket::getSocketOption( + int socket_option_key, + ProducerContentObjectCallback **socket_option_value) { + return socket_->getSocketOption(socket_option_key, socket_option_value); +} + +int ProducerSocket::getSocketOption( + int socket_option_key, ProducerContentCallback **socket_option_value) { + return socket_->getSocketOption(socket_option_key, socket_option_value); +} + +int ProducerSocket::getSocketOption( + int socket_option_key, ProducerInterestCallback **socket_option_value) { + return socket_->getSocketOption(socket_option_key, socket_option_value); +} + +int ProducerSocket::getSocketOption(int socket_option_key, + HashAlgorithm &socket_option_value) { + return socket_->getSocketOption(socket_option_key, socket_option_value); +} + +int ProducerSocket::getSocketOption(int socket_option_key, + utils::CryptoSuite &socket_option_value) { + return socket_->getSocketOption(socket_option_key, socket_option_value); +} + +int ProducerSocket::getSocketOption( + int socket_option_key, + std::shared_ptr<utils::Signer> &socket_option_value) { + return socket_->getSocketOption(socket_option_key, socket_option_value); +} + +} // namespace interface + +} // namespace transport diff --git a/libtransport/src/interfaces/tls_rtc_socket_producer.cc b/libtransport/src/interfaces/tls_rtc_socket_producer.cc new file mode 100644 index 000000000..132f34721 --- /dev/null +++ b/libtransport/src/interfaces/tls_rtc_socket_producer.cc @@ -0,0 +1,32 @@ +/* + * 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 <interfaces/tls_rtc_socket_producer.h> + +#include <implementation/tls_rtc_socket_producer.h> + +namespace transport { +namespace interface { + +TLSRTCProducerSocket::TLSRTCProducerSocket( + implementation::TLSRTCProducerSocket *implementation) { + socket_ = + std::unique_ptr<implementation::TLSRTCProducerSocket>(implementation); +} + +TLSRTCProducerSocket::~TLSRTCProducerSocket() { socket_.release(); } + +} // namespace interface +} // namespace transport diff --git a/libtransport/src/interfaces/tls_rtc_socket_producer.h b/libtransport/src/interfaces/tls_rtc_socket_producer.h new file mode 100644 index 000000000..434edb522 --- /dev/null +++ b/libtransport/src/interfaces/tls_rtc_socket_producer.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2020 Cisco and/or its affiliates. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include <hicn/transport/interfaces/socket_producer.h> + +namespace transport { + +namespace implementation { +class TLSRTCProducerSocket; +} + +namespace interface { + +class TLSRTCProducerSocket : public ProducerSocket { + public: + TLSRTCProducerSocket(implementation::TLSRTCProducerSocket *implementation); + ~TLSRTCProducerSocket(); +}; + +} // namespace interface + +} // end namespace transport
\ No newline at end of file diff --git a/libtransport/src/hicn/transport/core/payload_type.h b/libtransport/src/interfaces/tls_socket_consumer.cc index fa79db35a..d87642f73 100644 --- a/libtransport/src/hicn/transport/core/payload_type.h +++ b/libtransport/src/interfaces/tls_socket_consumer.cc @@ -13,17 +13,19 @@ * limitations under the License. */ -#pragma once +#include <interfaces/tls_socket_consumer.h> -namespace transport { +#include <implementation/tls_socket_consumer.h> -namespace core { +namespace transport { +namespace interface { -enum class PayloadType : uint16_t { - CONTENT_OBJECT = HPT_DATA, - MANIFEST = HPT_MANIFEST, -}; +TLSConsumerSocket::TLSConsumerSocket( + implementation::TLSConsumerSocket *implementation) { + socket_ = std::unique_ptr<implementation::TLSConsumerSocket>(implementation); +} -} // end namespace core +TLSConsumerSocket::~TLSConsumerSocket() { socket_.release(); } -} // end namespace transport
\ No newline at end of file +} // namespace interface +} // namespace transport diff --git a/libtransport/src/hicn/transport/interfaces/verification_policy.h b/libtransport/src/interfaces/tls_socket_consumer.h index cb5140ac1..845a9181f 100644 --- a/libtransport/src/hicn/transport/interfaces/verification_policy.h +++ b/libtransport/src/interfaces/tls_socket_consumer.h @@ -15,19 +15,22 @@ #pragma once -#include <cstdint> +#include <hicn/transport/interfaces/socket_consumer.h> namespace transport { + +namespace implementation { +class TLSConsumerSocket; +} + 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 +class TLSConsumerSocket : public ConsumerSocket { + public: + TLSConsumerSocket(implementation::TLSConsumerSocket *implementation); + ~TLSConsumerSocket(); }; + } // namespace interface -} // namespace transport
\ No newline at end of file + +} // end namespace transport diff --git a/libtransport/src/interfaces/tls_socket_producer.cc b/libtransport/src/interfaces/tls_socket_producer.cc new file mode 100644 index 000000000..44aa0cf8b --- /dev/null +++ b/libtransport/src/interfaces/tls_socket_producer.cc @@ -0,0 +1,31 @@ +/* + * 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 <interfaces/tls_socket_producer.h> + +#include <implementation/tls_socket_producer.h> + +namespace transport { +namespace interface { + +TLSProducerSocket::TLSProducerSocket( + implementation::TLSProducerSocket *implementation) { + socket_ = std::unique_ptr<implementation::TLSProducerSocket>(implementation); +} + +TLSProducerSocket::~TLSProducerSocket() { socket_.release(); } + +} // namespace interface +} // namespace transport diff --git a/libtransport/src/hicn/transport/protocols/download_observer.h b/libtransport/src/interfaces/tls_socket_producer.h index 6d24fe6fd..3c662176a 100644 --- a/libtransport/src/hicn/transport/protocols/download_observer.h +++ b/libtransport/src/interfaces/tls_socket_producer.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * 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: @@ -15,18 +15,22 @@ #pragma once +#include <hicn/transport/interfaces/socket_producer.h> + namespace transport { -namespace protocol { +namespace implementation { +class TLSProducerSocket; +} -class IcnObserver { - public: - virtual ~IcnObserver(){}; +namespace interface { - virtual void notifyStats(double throughput) = 0; - virtual void notifyDownloadTime(double downloadTime) = 0; +class TLSProducerSocket : public ProducerSocket { + public: + TLSProducerSocket(implementation::TLSProducerSocket *implementation); + ~TLSProducerSocket(); }; -} // end namespace protocol +} // namespace interface } // end namespace transport diff --git a/libtransport/src/hicn/transport/protocols/CMakeLists.txt b/libtransport/src/protocols/CMakeLists.txt index 06515e0e2..3156d9ae9 100644 --- a/libtransport/src/hicn/transport/protocols/CMakeLists.txt +++ b/libtransport/src/protocols/CMakeLists.txt @@ -22,9 +22,7 @@ list(APPEND HEADER_FILES ${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 diff --git a/libtransport/src/hicn/transport/protocols/byte_stream_reassembly.cc b/libtransport/src/protocols/byte_stream_reassembly.cc index 2f1e5d8fd..c2996ebc1 100644 --- a/libtransport/src/hicn/transport/protocols/byte_stream_reassembly.cc +++ b/libtransport/src/protocols/byte_stream_reassembly.cc @@ -13,20 +13,25 @@ * 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> +#include <implementation/socket_consumer.h> +#include <protocols/byte_stream_reassembly.h> +#include <protocols/errors.h> +#include <protocols/indexer.h> +#include <protocols/protocol.h> + namespace transport { namespace protocol { +using namespace core; +using ReadCallback = interface::ConsumerSocket::ReadCallback; + ByteStreamReassembly::ByteStreamReassembly( - interface::ConsumerSocket *icn_socket, + implementation::ConsumerSocket *icn_socket, TransportProtocol *transport_protocol) : Reassembly(icn_socket, transport_protocol), index_(IndexManager::invalid_index), @@ -109,7 +114,7 @@ void ByteStreamReassembly::reInitialize() { received_packets_.clear(); // reset read buffer - interface::ConsumerSocket::ReadCallback *read_callback; + ReadCallback *read_callback; reassembly_consumer_socket_->getSocketOption( interface::ConsumerCallbacksOptions::READ_CALLBACK, &read_callback); diff --git a/libtransport/src/hicn/transport/protocols/byte_stream_reassembly.h b/libtransport/src/protocols/byte_stream_reassembly.h index 7c77d486f..5e5c9ec6b 100644 --- a/libtransport/src/hicn/transport/protocols/byte_stream_reassembly.h +++ b/libtransport/src/protocols/byte_stream_reassembly.h @@ -15,7 +15,7 @@ #pragma once -#include <hicn/transport/protocols/reassembly.h> +#include <protocols/reassembly.h> namespace transport { @@ -23,7 +23,7 @@ namespace protocol { class ByteStreamReassembly : public Reassembly { public: - ByteStreamReassembly(interface::ConsumerSocket *icn_socket, + ByteStreamReassembly(implementation::ConsumerSocket *icn_socket, TransportProtocol *transport_protocol); protected: diff --git a/libtransport/src/hicn/transport/protocols/cbr.cc b/libtransport/src/protocols/cbr.cc index 02bc7b5e4..5df55bd5c 100644 --- a/libtransport/src/hicn/transport/protocols/cbr.cc +++ b/libtransport/src/protocols/cbr.cc @@ -13,8 +13,9 @@ * limitations under the License. */ -#include <hicn/transport/interfaces/socket_consumer.h> -#include <hicn/transport/protocols/cbr.h> +#include <implementation/socket_consumer.h> + +#include <protocols/cbr.h> namespace transport { @@ -23,7 +24,7 @@ namespace protocol { using namespace interface; CbrTransportProtocol::CbrTransportProtocol( - interface::ConsumerSocket *icnet_socket) + implementation::ConsumerSocket *icnet_socket) : RaaqmTransportProtocol(icnet_socket) {} int CbrTransportProtocol::start() { return RaaqmTransportProtocol::start(); } diff --git a/libtransport/src/hicn/transport/protocols/cbr.h b/libtransport/src/protocols/cbr.h index e80da14f5..20129f6a3 100644 --- a/libtransport/src/hicn/transport/protocols/cbr.h +++ b/libtransport/src/protocols/cbr.h @@ -15,7 +15,7 @@ #pragma once -#include <hicn/transport/protocols/raaqm.h> +#include <protocols/raaqm.h> namespace transport { @@ -23,7 +23,7 @@ namespace protocol { class CbrTransportProtocol : public RaaqmTransportProtocol { public: - CbrTransportProtocol(interface::ConsumerSocket *icnet_socket); + CbrTransportProtocol(implementation::ConsumerSocket *icnet_socket); int start() override; diff --git a/libtransport/src/hicn/transport/protocols/congestion_window_protocol.h b/libtransport/src/protocols/congestion_window_protocol.h index 36ac6eb17..36ac6eb17 100644 --- a/libtransport/src/hicn/transport/protocols/congestion_window_protocol.h +++ b/libtransport/src/protocols/congestion_window_protocol.h diff --git a/libtransport/src/hicn/transport/protocols/consumer.conf b/libtransport/src/protocols/consumer.conf index 1a366f32f..1a366f32f 100644 --- a/libtransport/src/hicn/transport/protocols/consumer.conf +++ b/libtransport/src/protocols/consumer.conf diff --git a/libtransport/src/hicn/transport/protocols/data_processing_events.h b/libtransport/src/protocols/data_processing_events.h index 8975c2b4a..8975c2b4a 100644 --- a/libtransport/src/hicn/transport/protocols/data_processing_events.h +++ b/libtransport/src/protocols/data_processing_events.h diff --git a/libtransport/src/hicn/transport/protocols/datagram_reassembly.cc b/libtransport/src/protocols/datagram_reassembly.cc index 7b01ad4bc..abd7e984d 100644 --- a/libtransport/src/hicn/transport/protocols/datagram_reassembly.cc +++ b/libtransport/src/protocols/datagram_reassembly.cc @@ -13,14 +13,15 @@ * limitations under the License. */ -#include <hicn/transport/protocols/datagram_reassembly.h> +#include <protocols/datagram_reassembly.h> namespace transport { namespace protocol { -DatagramReassembly::DatagramReassembly(interface::ConsumerSocket* icn_socket, - TransportProtocol* transport_protocol) +DatagramReassembly::DatagramReassembly( + implementation::ConsumerSocket* icn_socket, + TransportProtocol* transport_protocol) : Reassembly(icn_socket, transport_protocol) {} void DatagramReassembly::reassemble(core::ContentObject::Ptr&& content_object) { diff --git a/libtransport/src/hicn/transport/protocols/datagram_reassembly.h b/libtransport/src/protocols/datagram_reassembly.h index 923b6f2c1..2427ae62f 100644 --- a/libtransport/src/hicn/transport/protocols/datagram_reassembly.h +++ b/libtransport/src/protocols/datagram_reassembly.h @@ -15,7 +15,7 @@ #pragma once -#include <hicn/transport/protocols/reassembly.h> +#include <protocols/reassembly.h> namespace transport { @@ -23,7 +23,7 @@ namespace protocol { class DatagramReassembly : public Reassembly { public: - DatagramReassembly(interface::ConsumerSocket *icn_socket, + DatagramReassembly(implementation::ConsumerSocket *icn_socket, TransportProtocol *transport_protocol); virtual void reassemble(core::ContentObject::Ptr &&content_object) override; diff --git a/libtransport/src/hicn/transport/protocols/errors.cc b/libtransport/src/protocols/errors.cc index c2249ed4a..eefb6f957 100644 --- a/libtransport/src/hicn/transport/protocols/errors.cc +++ b/libtransport/src/protocols/errors.cc @@ -13,7 +13,7 @@ * limitations under the License. */ -#include <hicn/transport/protocols/errors.h> +#include <protocols/errors.h> namespace transport { namespace protocol { diff --git a/libtransport/src/hicn/transport/protocols/errors.h b/libtransport/src/protocols/errors.h index cb3d3474e..cb3d3474e 100644 --- a/libtransport/src/hicn/transport/protocols/errors.h +++ b/libtransport/src/protocols/errors.h diff --git a/libtransport/src/hicn/transport/protocols/incremental_indexer.cc b/libtransport/src/protocols/incremental_indexer.cc index 5a8046daa..e590b4fee 100644 --- a/libtransport/src/hicn/transport/protocols/incremental_indexer.cc +++ b/libtransport/src/protocols/incremental_indexer.cc @@ -13,9 +13,10 @@ * limitations under the License. */ -#include <hicn/transport/protocols/incremental_indexer.h> +#include <protocols/incremental_indexer.h> #include <hicn/transport/interfaces/socket_consumer.h> +#include <protocols/protocol.h> namespace transport { namespace protocol { diff --git a/libtransport/src/hicn/transport/protocols/incremental_indexer.h b/libtransport/src/protocols/incremental_indexer.h index b587a8332..20c5e4759 100644 --- a/libtransport/src/hicn/transport/protocols/incremental_indexer.h +++ b/libtransport/src/protocols/incremental_indexer.h @@ -15,14 +15,14 @@ #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 <protocols/indexer.h> +#include <protocols/reassembly.h> +#include <protocols/verification_manager.h> + #include <deque> namespace transport { @@ -38,7 +38,7 @@ class TransportProtocol; class IncrementalIndexer : public Indexer { public: - IncrementalIndexer(interface::ConsumerSocket *icn_socket, + IncrementalIndexer(implementation::ConsumerSocket *icn_socket, TransportProtocol *transport, Reassembly *reassembly) : socket_(icn_socket), reassembly_(reassembly), @@ -128,7 +128,7 @@ class IncrementalIndexer : public Indexer { } protected: - interface::ConsumerSocket *socket_; + implementation::ConsumerSocket *socket_; Reassembly *reassembly_; TransportProtocol *transport_protocol_; uint32_t final_suffix_; diff --git a/libtransport/src/hicn/transport/protocols/indexer.cc b/libtransport/src/protocols/indexer.cc index d95c10ff9..ca12330a6 100644 --- a/libtransport/src/hicn/transport/protocols/indexer.cc +++ b/libtransport/src/protocols/indexer.cc @@ -13,17 +13,17 @@ * 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> +#include <protocols/incremental_indexer.h> +#include <protocols/indexer.h> +#include <protocols/manifest_incremental_indexer.h> +#include <protocols/protocol.h> + namespace transport { namespace protocol { -IndexManager::IndexManager(interface::ConsumerSocket *icn_socket, +IndexManager::IndexManager(implementation::ConsumerSocket *icn_socket, TransportProtocol *transport, Reassembly *reassembly) : indexer_(std::make_unique<IncrementalIndexer>(icn_socket, transport, reassembly)), @@ -43,7 +43,7 @@ void IndexManager::onContentObject(core::Interest::Ptr &&interest, // Check if manifest if (content_object->getPayloadType() == PayloadType::MANIFEST) { IncrementalIndexer *indexer = - static_cast<IncrementalIndexer *>(indexer_.release()); + static_cast<IncrementalIndexer *>(indexer_.release()); indexer_ = std::make_unique<ManifestIncrementalIndexer>(std::move(*indexer)); delete indexer; @@ -52,20 +52,21 @@ void IndexManager::onContentObject(core::Interest::Ptr &&interest, 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))); + 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)); + interest_data_set_.emplace(std::move(interest), + std::move(content_object)); } } } -bool IndexManager::onKeyToVerify() { - return indexer_->onKeyToVerify(); -} +bool IndexManager::onKeyToVerify() { return indexer_->onKeyToVerify(); } void IndexManager::reset(std::uint32_t offset) { indexer_ = std::make_unique<IncrementalIndexer>(icn_socket_, transport_, diff --git a/libtransport/src/hicn/transport/protocols/indexer.h b/libtransport/src/protocols/indexer.h index 87cf9b307..8213a1503 100644 --- a/libtransport/src/hicn/transport/protocols/indexer.h +++ b/libtransport/src/protocols/indexer.h @@ -22,7 +22,7 @@ namespace transport { -namespace interface { +namespace implementation { class ConsumerSocket; } @@ -65,7 +65,7 @@ class IndexManager : Indexer { public: static constexpr uint32_t invalid_index = ~0; - IndexManager(interface::ConsumerSocket *icn_socket, + IndexManager(implementation::ConsumerSocket *icn_socket, TransportProtocol *transport, Reassembly *reassembly); uint32_t getNextSuffix() override { return indexer_->getNextSuffix(); } @@ -96,7 +96,7 @@ class IndexManager : Indexer { bool first_segment_received_; std::set<std::pair<core::Interest::Ptr, core::ContentObject::Ptr>> interest_data_set_; - interface::ConsumerSocket *icn_socket_; + implementation::ConsumerSocket *icn_socket_; TransportProtocol *transport_; Reassembly *reassembly_; }; diff --git a/libtransport/src/hicn/transport/protocols/manifest_incremental_indexer.cc b/libtransport/src/protocols/manifest_incremental_indexer.cc index 592daa4d4..1a2f9dec3 100644 --- a/libtransport/src/hicn/transport/protocols/manifest_incremental_indexer.cc +++ b/libtransport/src/protocols/manifest_incremental_indexer.cc @@ -13,8 +13,10 @@ * limitations under the License. */ -#include <hicn/transport/interfaces/socket_consumer.h> -#include <hicn/transport/protocols/manifest_incremental_indexer.h> +#include <implementation/socket_consumer.h> + +#include <protocols/manifest_incremental_indexer.h> +#include <protocols/protocol.h> #include <cmath> #include <deque> @@ -26,12 +28,12 @@ namespace protocol { using namespace interface; ManifestIncrementalIndexer::ManifestIncrementalIndexer( - interface::ConsumerSocket *icn_socket, TransportProtocol *transport, + implementation::ConsumerSocket *icn_socket, TransportProtocol *transport, Reassembly *reassembly) : IncrementalIndexer(icn_socket, transport, reassembly), suffix_strategy_(utils::SuffixStrategyFactory::getSuffixStrategy( - NextSegmentCalculationStrategy::INCREMENTAL, - next_download_suffix_, 0)) {} + NextSegmentCalculationStrategy::INCREMENTAL, next_download_suffix_, + 0)) {} void ManifestIncrementalIndexer::onContentObject( core::Interest::Ptr &&interest, core::ContentObject::Ptr &&content_object) { @@ -152,7 +154,7 @@ VerificationPolicy ManifestIncrementalIndexer::verifyContentObject( socket_->getSocketOption(ConsumerCallbacksOptions::VERIFICATION_FAILED, &verification_failed_callback); ret = (*verification_failed_callback)( - *socket_, content_object, + *socket_->getInterface(), content_object, make_error_code(protocol_error::integrity_verification_failed)); } diff --git a/libtransport/src/hicn/transport/protocols/manifest_incremental_indexer.h b/libtransport/src/protocols/manifest_incremental_indexer.h index 6e991f86f..88ae1720b 100644 --- a/libtransport/src/hicn/transport/protocols/manifest_incremental_indexer.h +++ b/libtransport/src/protocols/manifest_incremental_indexer.h @@ -15,9 +15,9 @@ #pragma once -#include <hicn/transport/interfaces/socket.h> -#include <hicn/transport/protocols/incremental_indexer.h> -#include <hicn/transport/utils/suffix_strategy.h> +#include <implementation/socket.h> +#include <protocols/incremental_indexer.h> +#include <utils/suffix_strategy.h> #include <list> @@ -32,8 +32,9 @@ class ManifestIncrementalIndexer : public IncrementalIndexer { using SuffixQueue = std::queue<uint32_t>; using HashEntry = std::pair<std::vector<uint8_t>, core::HashAlgorithm>; - ManifestIncrementalIndexer(interface::ConsumerSocket *icn_socket, - TransportProtocol *transport, Reassembly *reassembly); + ManifestIncrementalIndexer(implementation::ConsumerSocket *icn_socket, + TransportProtocol *transport, + Reassembly *reassembly); ManifestIncrementalIndexer(IncrementalIndexer &&indexer) : IncrementalIndexer(std::move(indexer)), diff --git a/libtransport/src/hicn/transport/protocols/packet_manager.h b/libtransport/src/protocols/packet_manager.h index 4d4011ecf..a552607ea 100644 --- a/libtransport/src/hicn/transport/protocols/packet_manager.h +++ b/libtransport/src/protocols/packet_manager.h @@ -23,13 +23,11 @@ namespace protocol { using namespace core; -template <typename PacketType> +template <typename PacketType, std::size_t packet_pool_size = 4096> class PacketManager { static_assert(std::is_base_of<Packet, PacketType>::value, "The packet manager support just Interest and Data."); - static constexpr std::size_t packet_pool_size = 4096; - public: PacketManager(std::size_t size = packet_pool_size) : size_(0) { // Create pool of interests diff --git a/libtransport/src/hicn/transport/protocols/protocol.cc b/libtransport/src/protocols/protocol.cc index db461a66f..aa290bef8 100644 --- a/libtransport/src/hicn/transport/protocols/protocol.cc +++ b/libtransport/src/protocols/protocol.cc @@ -14,7 +14,9 @@ */ #include <hicn/transport/interfaces/socket_consumer.h> -#include <hicn/transport/protocols/protocol.h> + +#include <implementation/socket_consumer.h> +#include <protocols/protocol.h> namespace transport { @@ -22,7 +24,7 @@ namespace protocol { using namespace interface; -TransportProtocol::TransportProtocol(interface::ConsumerSocket *icn_socket, +TransportProtocol::TransportProtocol(implementation::ConsumerSocket *icn_socket, Reassembly *reassembly_protocol) : socket_(icn_socket), reassembly_protocol_(reassembly_protocol), @@ -96,8 +98,6 @@ void TransportProtocol::onContentReassembled(std::error_code ec) { } stop(); - - on_payload->afterRead(); } } // end namespace protocol diff --git a/libtransport/src/hicn/transport/protocols/protocol.h b/libtransport/src/protocols/protocol.h index 4897da902..c094adaae 100644 --- a/libtransport/src/hicn/transport/protocols/protocol.h +++ b/libtransport/src/protocols/protocol.h @@ -17,14 +17,15 @@ #include <atomic> -#include <hicn/transport/interfaces/socket.h> -#include <hicn/transport/protocols/data_processing_events.h> -#include <hicn/transport/protocols/indexer.h> -#include <hicn/transport/protocols/packet_manager.h> -#include <hicn/transport/protocols/reassembly.h> -#include <hicn/transport/protocols/statistics.h> +#include <hicn/transport/interfaces/statistics.h> #include <hicn/transport/utils/object_pool.h> +#include <implementation/socket.h> +#include <protocols/data_processing_events.h> +#include <protocols/indexer.h> +#include <protocols/packet_manager.h> +#include <protocols/reassembly.h> + namespace transport { namespace protocol { @@ -39,7 +40,7 @@ class TransportProtocolCallback { virtual void onTimeout(const core::Interest &interest) = 0; }; -class TransportProtocol : public interface::BasePortal::ConsumerCallback, +class TransportProtocol : public implementation::BasePortal::ConsumerCallback, public PacketManager<Interest>, public ContentObjectProcessingEventCallback { static constexpr std::size_t interest_pool_size = 4096; @@ -47,7 +48,7 @@ class TransportProtocol : public interface::BasePortal::ConsumerCallback, friend class ManifestIndexManager; public: - TransportProtocol(interface::ConsumerSocket *icn_socket, + TransportProtocol(implementation::ConsumerSocket *icn_socket, Reassembly *reassembly_protocol); virtual ~TransportProtocol() = default; @@ -77,14 +78,14 @@ class TransportProtocol : public interface::BasePortal::ConsumerCallback, virtual void onTimeout(Interest::Ptr &&i) = 0; protected: - interface::ConsumerSocket *socket_; + implementation::ConsumerSocket *socket_; std::unique_ptr<Reassembly> reassembly_protocol_; std::unique_ptr<IndexManager> index_manager_; - std::shared_ptr<interface::BasePortal> portal_; + std::shared_ptr<implementation::BasePortal> portal_; std::atomic<bool> is_running_; // True if it si the first time we schedule an interest std::atomic<bool> is_first_; - TransportStatistics *stats_; + interface::TransportStatistics *stats_; }; } // end namespace protocol diff --git a/libtransport/src/hicn/transport/protocols/raaqm.cc b/libtransport/src/protocols/raaqm.cc index 984470edb..8a38f8ccf 100644 --- a/libtransport/src/hicn/transport/protocols/raaqm.cc +++ b/libtransport/src/protocols/raaqm.cc @@ -14,9 +14,11 @@ */ #include <hicn/transport/interfaces/socket_consumer.h> -#include <hicn/transport/protocols/indexer.h> -#include <hicn/transport/protocols/raaqm.h> -#include <hicn/transport/protocols/errors.h> + +#include <implementation/socket_consumer.h> +#include <protocols/errors.h> +#include <protocols/indexer.h> +#include <protocols/raaqm.h> #include <cstdlib> #include <fstream> @@ -27,7 +29,8 @@ namespace protocol { using namespace interface; -RaaqmTransportProtocol::RaaqmTransportProtocol(ConsumerSocket *icn_socket) +RaaqmTransportProtocol::RaaqmTransportProtocol( + implementation::ConsumerSocket *icn_socket) : TransportProtocol(icn_socket, new ByteStreamReassembly(icn_socket, this)), current_window_size_(1), interests_in_flight_(0), @@ -326,14 +329,14 @@ void RaaqmTransportProtocol::onContentObject( socket_->getSocketOption(ConsumerCallbacksOptions::CONTENT_OBJECT_INPUT, &callback_content_object); if (*callback_content_object) { - (*callback_content_object)(*socket_, *content_object); + (*callback_content_object)(*socket_->getInterface(), *content_object); } ConsumerInterestCallback *callback_interest = VOID_HANDLER; socket_->getSocketOption(ConsumerCallbacksOptions::INTEREST_SATISFIED, &callback_interest); if (*callback_interest) { - (*callback_interest)(*socket_, *interest); + (*callback_interest)(*socket_->getInterface(), *interest); } if (content_object->getPayloadType() == PayloadType::CONTENT_OBJECT) { @@ -375,14 +378,14 @@ void RaaqmTransportProtocol::onPacketDropped( socket_->getSocketOption(ConsumerCallbacksOptions::INTEREST_RETRANSMISSION, &callback); if (*callback) { - (*callback)(*socket_, *interest); + (*callback)(*socket_->getInterface(), *interest); } callback = VOID_HANDLER; socket_->getSocketOption(ConsumerCallbacksOptions::INTEREST_OUTPUT, &callback); if (*callback) { - (*callback)(*socket_, *interest); + (*callback)(*socket_->getInterface(), *interest); } if (!is_running_) { @@ -429,7 +432,7 @@ void RaaqmTransportProtocol::onTimeout(Interest::Ptr &&interest) { socket_->getSocketOption(ConsumerCallbacksOptions::INTEREST_EXPIRED, &callback); if (*callback) { - (*callback)(*socket_, *interest); + (*callback)(*socket_->getInterface(), *interest); } afterDataUnsatisfied(segment); @@ -445,14 +448,14 @@ void RaaqmTransportProtocol::onTimeout(Interest::Ptr &&interest) { socket_->getSocketOption(ConsumerCallbacksOptions::INTEREST_RETRANSMISSION, &callback); if (*callback) { - (*callback)(*socket_, *interest); + (*callback)(*socket_->getInterface(), *interest); } callback = VOID_HANDLER; socket_->getSocketOption(ConsumerCallbacksOptions::INTEREST_OUTPUT, &callback); if (*callback) { - (*callback)(*socket_, *interest); + (*callback)(*socket_->getInterface(), *interest); } if (!is_running_) { @@ -495,7 +498,6 @@ void RaaqmTransportProtocol::scheduleNextInterests() { } else { index = index_manager_->getNextSuffix(); if (index == IndexManager::invalid_index) { - TRANSPORT_LOGE("INVALID INDEX %d", index); break; } @@ -521,7 +523,7 @@ void RaaqmTransportProtocol::sendInterest(std::uint64_t next_suffix) { socket_->getSocketOption(ConsumerCallbacksOptions::INTEREST_OUTPUT, &callback); if (*callback) { - callback->operator()(*socket_, *interest); + callback->operator()(*socket_->getInterface(), *interest); } if (TRANSPORT_EXPECT_FALSE(!is_running_ && !is_first_)) { @@ -603,7 +605,7 @@ void RaaqmTransportProtocol::updateStats(uint32_t suffix, uint64_t rtt, socket_->getSocketOption(GeneralTransportOptions::STATS_INTERVAL, timer_interval_milliseconds); if (dt.count() > timer_interval_milliseconds) { - (*stats_callback)(*socket_, *stats_); + (*stats_callback)(*socket_->getInterface(), *stats_); t0_ = utils::SteadyClock::now(); } } diff --git a/libtransport/src/hicn/transport/protocols/raaqm.h b/libtransport/src/protocols/raaqm.h index f2d819ec5..412967770 100644 --- a/libtransport/src/hicn/transport/protocols/raaqm.h +++ b/libtransport/src/protocols/raaqm.h @@ -15,13 +15,14 @@ #pragma once -#include <hicn/transport/protocols/byte_stream_reassembly.h> -#include <hicn/transport/protocols/congestion_window_protocol.h> -#include <hicn/transport/protocols/protocol.h> -#include <hicn/transport/protocols/raaqm_data_path.h> -#include <hicn/transport/protocols/rate_estimation.h> #include <hicn/transport/utils/chrono_typedefs.h> +#include <protocols/byte_stream_reassembly.h> +#include <protocols/congestion_window_protocol.h> +#include <protocols/protocol.h> +#include <protocols/raaqm_data_path.h> +#include <protocols/rate_estimation.h> + #include <queue> #include <vector> @@ -32,7 +33,7 @@ namespace protocol { class RaaqmTransportProtocol : public TransportProtocol, public CWindowProtocol { public: - RaaqmTransportProtocol(interface::ConsumerSocket *icnet_socket); + RaaqmTransportProtocol(implementation::ConsumerSocket *icnet_socket); ~RaaqmTransportProtocol(); diff --git a/libtransport/src/hicn/transport/protocols/raaqm_data_path.cc b/libtransport/src/protocols/raaqm_data_path.cc index e25646205..439549c85 100644 --- a/libtransport/src/hicn/transport/protocols/raaqm_data_path.cc +++ b/libtransport/src/protocols/raaqm_data_path.cc @@ -13,9 +13,10 @@ * limitations under the License. */ -#include <hicn/transport/protocols/raaqm_data_path.h> #include <hicn/transport/utils/chrono_typedefs.h> +#include <protocols/raaqm_data_path.h> + namespace transport { namespace protocol { diff --git a/libtransport/src/hicn/transport/protocols/raaqm_data_path.h b/libtransport/src/protocols/raaqm_data_path.h index 9e4accfa5..6f2afde72 100644 --- a/libtransport/src/hicn/transport/protocols/raaqm_data_path.h +++ b/libtransport/src/protocols/raaqm_data_path.h @@ -16,7 +16,8 @@ #pragma once #include <hicn/transport/utils/chrono_typedefs.h> -#include <hicn/transport/utils/min_filter.h> + +#include <utils/min_filter.h> #include <chrono> #include <climits> diff --git a/libtransport/src/hicn/transport/protocols/rate_estimation.cc b/libtransport/src/protocols/rate_estimation.cc index 50306e6e5..a2cf1aefe 100644 --- a/libtransport/src/hicn/transport/protocols/rate_estimation.cc +++ b/libtransport/src/protocols/rate_estimation.cc @@ -14,9 +14,10 @@ */ #include <hicn/transport/interfaces/socket_options_default_values.h> -#include <hicn/transport/protocols/rate_estimation.h> #include <hicn/transport/utils/log.h> +#include <protocols/rate_estimation.h> + #include <thread> namespace transport { diff --git a/libtransport/src/hicn/transport/protocols/rate_estimation.h b/libtransport/src/protocols/rate_estimation.h index 616501b24..17f39e0b9 100644 --- a/libtransport/src/hicn/transport/protocols/rate_estimation.h +++ b/libtransport/src/protocols/rate_estimation.h @@ -15,8 +15,9 @@ #pragma once -#include <hicn/transport/protocols/download_observer.h> -#include <hicn/transport/protocols/raaqm_data_path.h> +#include <hicn/transport/interfaces/statistics.h> + +#include <protocols/raaqm_data_path.h> #include <chrono> @@ -45,10 +46,10 @@ class IcnRateEstimator { virtual void onDownloadFinished(){}; - virtual void setObserver(IcnObserver *observer) { + virtual void setObserver(interface::IcnObserver *observer) { this->observer_ = observer; }; - IcnObserver *observer_; + interface::IcnObserver *observer_; TimePoint start_time_; TimePoint begin_batch_; double base_alpha_; diff --git a/libtransport/src/hicn/transport/protocols/reassembly.cc b/libtransport/src/protocols/reassembly.cc index 9682d338d..c6602153c 100644 --- a/libtransport/src/hicn/transport/protocols/reassembly.cc +++ b/libtransport/src/protocols/reassembly.cc @@ -14,12 +14,14 @@ */ #include <hicn/transport/interfaces/socket_consumer.h> -#include <hicn/transport/protocols/errors.h> -#include <hicn/transport/protocols/indexer.h> -#include <hicn/transport/protocols/reassembly.h> #include <hicn/transport/utils/array.h> #include <hicn/transport/utils/membuf.h> +#include <implementation/socket_consumer.h> +#include <protocols/errors.h> +#include <protocols/indexer.h> +#include <protocols/reassembly.h> + namespace transport { namespace protocol { diff --git a/libtransport/src/hicn/transport/protocols/reassembly.h b/libtransport/src/protocols/reassembly.h index 34af2a70a..fdc9f2a05 100644 --- a/libtransport/src/hicn/transport/protocols/reassembly.h +++ b/libtransport/src/protocols/reassembly.h @@ -15,14 +15,14 @@ #pragma once -#include <hicn/transport/core/facade.h> +#include <core/facade.h> namespace transport { -namespace interface { +namespace implementation { class ConsumerReadCallback; class ConsumerSocket; -} // namespace interface +} // namespace implementation namespace protocol { @@ -39,7 +39,7 @@ class Reassembly { virtual void onContentReassembled(std::error_code ec) = 0; }; - Reassembly(interface::ConsumerSocket *icn_socket, + Reassembly(implementation::ConsumerSocket *icn_socket, TransportProtocol *transport_protocol) : reassembly_consumer_socket_(icn_socket), transport_protocol_(transport_protocol) {} @@ -56,7 +56,7 @@ class Reassembly { virtual void notifyApplication(); protected: - interface::ConsumerSocket *reassembly_consumer_socket_; + implementation::ConsumerSocket *reassembly_consumer_socket_; TransportProtocol *transport_protocol_; Indexer *index_manager_; std::unique_ptr<utils::MemBuf> read_buffer_; diff --git a/libtransport/src/hicn/transport/protocols/rtc.cc b/libtransport/src/protocols/rtc.cc index fece95d03..0ac3839dd 100644 --- a/libtransport/src/hicn/transport/protocols/rtc.cc +++ b/libtransport/src/protocols/rtc.cc @@ -13,9 +13,10 @@ * limitations under the License. */ -#include <hicn/transport/protocols/rtc.h> +#include <protocols/rtc.h> #include <hicn/transport/interfaces/socket_consumer.h> +#include <implementation/socket_consumer.h> #include <math.h> #include <random> @@ -27,7 +28,7 @@ namespace protocol { using namespace interface; RTCTransportProtocol::RTCTransportProtocol( - interface::ConsumerSocket *icn_socket) + implementation::ConsumerSocket *icn_socket) : TransportProtocol(icn_socket, nullptr), DatagramReassembly(icn_socket, this), inflightInterests_(1 << default_values::log_2_default_buffer_size), @@ -295,7 +296,7 @@ void RTCTransportProtocol::updateStats(uint32_t round_duration) { stats_->updateQueuingDelay(queuingDelay_); stats_->updateLossRatio(lossRate_); stats_->updateAverageRtt(pathTable_[producerPathLabels_[1]]->getMinRtt()); - (*stats_callback)(*socket_, *stats_); + (*stats_callback)(*socket_->getInterface(), *stats_); } // bound also by interest lifitime* production rate if (!gotNack_) { @@ -456,7 +457,7 @@ void RTCTransportProtocol::sendInterest(Name *interest_name, bool rtx) { &on_interest_output); if (*on_interest_output) { - (*on_interest_output)(*socket_, *interest); + (*on_interest_output)(*socket_->getInterface(), *interest); } if (TRANSPORT_EXPECT_FALSE(!is_running_ && !is_first_)) { @@ -893,7 +894,7 @@ void RTCTransportProtocol::onContentObject( socket_->getSocketOption(ConsumerCallbacksOptions::CONTENT_OBJECT_INPUT, &callback_content_object); if (*callback_content_object) { - (*callback_content_object)(*socket_, *content_object); + (*callback_content_object)(*socket_->getInterface(), *content_object); } if (segmentNumber >= HICN_MIN_PROBE_SEQ) { diff --git a/libtransport/src/hicn/transport/protocols/rtc.h b/libtransport/src/protocols/rtc.h index f34afbb5f..f15cdd1eb 100644 --- a/libtransport/src/hicn/transport/protocols/rtc.h +++ b/libtransport/src/protocols/rtc.h @@ -15,14 +15,14 @@ #pragma once +#include <protocols/datagram_reassembly.h> +#include <protocols/protocol.h> +#include <protocols/rtc_data_path.h> + #include <map> #include <queue> #include <unordered_map> -#include <hicn/transport/protocols/datagram_reassembly.h> -#include <hicn/transport/protocols/protocol.h> -#include <hicn/transport/protocols/rtc_data_path.h> - // algorithm state #define HICN_RTC_SYNC_STATE 0 #define HICN_RTC_NORMAL_STATE 1 @@ -81,15 +81,15 @@ typedef enum packetState packetState_t; struct sentInterest { uint64_t transmissionTime; - uint32_t sequence; // sequence number of the interest sent - // to handle seq % buffer_size + uint32_t sequence; // sequence number of the interest sent + // to handle seq % buffer_size packetState_t state; // see packet state }; class RTCTransportProtocol : public TransportProtocol, public DatagramReassembly { public: - RTCTransportProtocol(interface::ConsumerSocket *icnet_socket); + RTCTransportProtocol(implementation::ConsumerSocket *icnet_socket); ~RTCTransportProtocol(); diff --git a/libtransport/src/hicn/transport/protocols/rtc_data_path.cc b/libtransport/src/protocols/rtc_data_path.cc index 0cbff0e3c..30644e939 100644 --- a/libtransport/src/hicn/transport/protocols/rtc_data_path.cc +++ b/libtransport/src/protocols/rtc_data_path.cc @@ -13,11 +13,12 @@ * limitations under the License. */ -#include <hicn/transport/protocols/rtc_data_path.h> -#include <chrono> +#include <protocols/rtc_data_path.h> + #include <cfloat> +#include <chrono> -#define MAX_ROUNDS_WITHOUT_PKTS 10 //2sec +#define MAX_ROUNDS_WITHOUT_PKTS 10 // 2sec namespace transport { @@ -53,62 +54,58 @@ void RTCDataPath::insertOwdSample(int64_t owd) { // for owd we use both min and avg if (owd < min_owd) min_owd = owd; - if(avg_owd != DBL_MAX) + if (avg_owd != DBL_MAX) avg_owd = (avg_owd * (1 - ALPHA_RTC)) + (owd * ALPHA_RTC); else { avg_owd = owd; } - //owd is computed only for valid data packets so we count only - //this for decide if we recevie traffic or not + // owd is computed only for valid data packets so we count only + // this for decide if we recevie traffic or not received_packets_ = true; } -void RTCDataPath::computeInterArrivalGap(uint32_t segmentNumber){ - - //got packet in sequence, compute gap - if(lastRecvSeq_ == (segmentNumber - 1)){ +void RTCDataPath::computeInterArrivalGap(uint32_t segmentNumber) { + // got packet in sequence, compute gap + if (lastRecvSeq_ == (segmentNumber - 1)) { uint64_t now = std::chrono::duration_cast<std::chrono::milliseconds>( - std::chrono::steady_clock::now().time_since_epoch()) - .count(); + std::chrono::steady_clock::now().time_since_epoch()) + .count(); uint64_t delta = now - lastRecvTime_; lastRecvSeq_ = segmentNumber; lastRecvTime_ = now; - if(avg_inter_arrival_ == DBL_MAX) + if (avg_inter_arrival_ == DBL_MAX) avg_inter_arrival_ = delta; else - avg_inter_arrival_ = (avg_inter_arrival_ * (1 -ALPHA_RTC)) - + (delta * ALPHA_RTC); + avg_inter_arrival_ = + (avg_inter_arrival_ * (1 - ALPHA_RTC)) + (delta * ALPHA_RTC); return; } - //ooo packet, update the stasts if needed - if(lastRecvSeq_ <= segmentNumber){ + // ooo packet, update the stasts if needed + if (lastRecvSeq_ <= segmentNumber) { lastRecvSeq_ = segmentNumber; lastRecvTime_ = std::chrono::duration_cast<std::chrono::milliseconds>( - std::chrono::steady_clock::now().time_since_epoch()) - .count(); + std::chrono::steady_clock::now().time_since_epoch()) + .count(); } } -void RTCDataPath::receivedNack(){ - received_nacks_ = true; -} +void RTCDataPath::receivedNack() { received_nacks_ = true; } -double RTCDataPath::getInterArrivalGap(){ - if(avg_inter_arrival_ == DBL_MAX) - return 0; +double RTCDataPath::getInterArrivalGap() { + if (avg_inter_arrival_ == DBL_MAX) return 0; return avg_inter_arrival_; } -bool RTCDataPath::isActive(){ - if(received_nacks_ && rounds_without_packets_ < MAX_ROUNDS_WITHOUT_PKTS) +bool RTCDataPath::isActive() { + if (received_nacks_ && rounds_without_packets_ < MAX_ROUNDS_WITHOUT_PKTS) return true; return false; } void RTCDataPath::roundEnd() { - // reset min_rtt and add it to the history + // reset min_rtt and add it to the history if (min_rtt != UINT_MAX) { prev_min_rtt = min_rtt; } else { @@ -118,8 +115,7 @@ void RTCDataPath::roundEnd() { min_rtt = prev_min_rtt; } - if(min_rtt == 0) - min_rtt = 1; + if (min_rtt == 0) min_rtt = 1; RTThistory_.pushBack(min_rtt); min_rtt = UINT_MAX; @@ -142,7 +138,7 @@ void RTCDataPath::roundEnd() { queuing_delay = 0.0; } - if(!received_packets_) + if (!received_packets_) rounds_without_packets_++; else rounds_without_packets_ = 0; diff --git a/libtransport/src/hicn/transport/protocols/rtc_data_path.h b/libtransport/src/protocols/rtc_data_path.h index 48a67c525..9076b355f 100644 --- a/libtransport/src/hicn/transport/protocols/rtc_data_path.h +++ b/libtransport/src/protocols/rtc_data_path.h @@ -15,12 +15,13 @@ #pragma once -#include <hicn/transport/utils/min_filter.h> #include <stdint.h> #include <climits> +#include <utils/min_filter.h> + #define ALPHA_RTC 0.125 -#define HISTORY_LEN 20 //4 sec +#define HISTORY_LEN 20 // 4 sec namespace transport { @@ -60,15 +61,15 @@ class RTCDataPath { uint64_t lastRecvTime_; double avg_inter_arrival_; - //flags to check if a path is active - //we considere a path active if it reaches a producer + // flags to check if a path is active + // we considere a path active if it reaches a producer //(not a cache) --aka we got at least one nack on this path-- - //and if we receives packets + // and if we receives packets bool received_nacks_; bool received_packets_; - uint8_t rounds_without_packets_; //if we don't get any packet - //for MAX_ROUNDS_WITHOUT_PKTS - //we consider the path inactive + uint8_t rounds_without_packets_; // if we don't get any packet + // for MAX_ROUNDS_WITHOUT_PKTS + // we consider the path inactive utils::MinFilter<uint64_t> RTThistory_; utils::MinFilter<int64_t> OWDhistory_; diff --git a/libtransport/src/hicn/transport/protocols/test/CMakeLists.txt b/libtransport/src/protocols/test/CMakeLists.txt index 6f9fdb9aa..6f9fdb9aa 100644 --- a/libtransport/src/hicn/transport/protocols/test/CMakeLists.txt +++ b/libtransport/src/protocols/test/CMakeLists.txt diff --git a/libtransport/src/hicn/transport/protocols/test/test_transport_producer.cc b/libtransport/src/protocols/test/test_transport_producer.cc index 204f2cbe2..204f2cbe2 100644 --- a/libtransport/src/hicn/transport/protocols/test/test_transport_producer.cc +++ b/libtransport/src/protocols/test/test_transport_producer.cc diff --git a/libtransport/src/hicn/transport/protocols/verification_manager.cc b/libtransport/src/protocols/verification_manager.cc index 74faf0521..8eedd6106 100644 --- a/libtransport/src/hicn/transport/protocols/verification_manager.cc +++ b/libtransport/src/protocols/verification_manager.cc @@ -14,7 +14,10 @@ */ #include <hicn/transport/interfaces/socket_consumer.h> -#include <hicn/transport/protocols/verification_manager.h> +#include <hicn/transport/security/verifier.h> + +#include <implementation/socket_consumer.h> +#include <protocols/verification_manager.h> namespace transport { @@ -59,14 +62,16 @@ interface::VerificationPolicy SignatureVerificationManager::onPacketToVerify( if (TRANSPORT_EXPECT_FALSE(!verifier)) { ret = (*verification_failed_callback)( - *icn_socket_, dynamic_cast<const ContentObject&>(packet), + *icn_socket_->getInterface(), + dynamic_cast<const ContentObject&>(packet), make_error_code(protocol_error::no_verifier_provided)); return ret; } if (!verifier->verify(packet)) { ret = (*verification_failed_callback)( - *icn_socket_, dynamic_cast<const ContentObject&>(packet), + *icn_socket_->getInterface(), + dynamic_cast<const ContentObject&>(packet), make_error_code(protocol_error::signature_verification_failed)); } else { ret = VerificationPolicy::ACCEPT_PACKET; diff --git a/libtransport/src/hicn/transport/protocols/verification_manager.h b/libtransport/src/protocols/verification_manager.h index 293e8103a..7d8a00a65 100644 --- a/libtransport/src/hicn/transport/protocols/verification_manager.h +++ b/libtransport/src/protocols/verification_manager.h @@ -17,7 +17,12 @@ #include <hicn/transport/interfaces/callbacks.h> #include <hicn/transport/interfaces/verification_policy.h> -#include <hicn/transport/protocols/errors.h> + +#include <hicn/transport/core/content_object.h> + +#include <protocols/errors.h> + +#include <queue> namespace transport { @@ -28,7 +33,6 @@ class ConsumerSocket; namespace protocol { using Packet = core::Packet; -using interface::ConsumerSocket; using interface::VerificationPolicy; using ContentObjectPtr = std::shared_ptr<core::ContentObject>; @@ -41,14 +45,14 @@ class VerificationManager { class SignatureVerificationManager : public VerificationManager { public: - SignatureVerificationManager(interface::ConsumerSocket* icn_socket) + SignatureVerificationManager(implementation::ConsumerSocket* icn_socket) : icn_socket_(icn_socket), key_packets_() {} interface::VerificationPolicy onPacketToVerify(const Packet& packet) override; bool onKeyToVerify() override; private: - ConsumerSocket* icn_socket_; + implementation::ConsumerSocket* icn_socket_; std::queue<ContentObjectPtr> key_packets_; ContentObjectPtr copyPacket(const Packet& packet) { diff --git a/libtransport/src/hicn/transport/portability/CMakeLists.txt b/libtransport/src/security/CMakeLists.txt index 5ad3c8207..0e7b5832b 100644 --- a/libtransport/src/hicn/transport/portability/CMakeLists.txt +++ b/libtransport/src/security/CMakeLists.txt @@ -13,20 +13,10 @@ 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 - "" + ${CMAKE_CURRENT_SOURCE_DIR}/signer.cc + ${CMAKE_CURRENT_SOURCE_DIR}/verifier.cc + ${CMAKE_CURRENT_SOURCE_DIR}/identity.cc ) -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/utils/identity.cc b/libtransport/src/security/identity.cc index c5ab03e44..55713245e 100644 --- a/libtransport/src/hicn/transport/utils/identity.cc +++ b/libtransport/src/security/identity.cc @@ -13,7 +13,7 @@ * limitations under the License. */ -#include <hicn/transport/utils/identity.h> +#include <hicn/transport/security/identity.h> extern "C" { #include <parc/security/parc_PublicKeySigner.h> diff --git a/libtransport/src/hicn/transport/utils/signer.cc b/libtransport/src/security/signer.cc index 9ac9a2c45..314c3ea82 100644 --- a/libtransport/src/hicn/transport/utils/signer.cc +++ b/libtransport/src/security/signer.cc @@ -16,9 +16,9 @@ */ #include <hicn/transport/errors/malformed_ahpacket_exception.h> -#include <hicn/transport/utils/key_id.h> +#include <hicn/transport/security/key_id.h> +#include <hicn/transport/security/signer.h> #include <hicn/transport/utils/membuf.h> -#include <hicn/transport/utils/signer.h> extern "C" { #ifndef _WIN32 diff --git a/libtransport/src/hicn/transport/utils/verifier.cc b/libtransport/src/security/verifier.cc index 281ee21dc..19796f718 100644 --- a/libtransport/src/hicn/transport/utils/verifier.cc +++ b/libtransport/src/security/verifier.cc @@ -16,9 +16,9 @@ #include <hicn/transport/core/packet.h> #include <hicn/transport/errors/malformed_ahpacket_exception.h> #include <hicn/transport/portability/portability.h> -#include <hicn/transport/utils/key_id.h> +#include <hicn/transport/security/key_id.h> +#include <hicn/transport/security/verifier.h> #include <hicn/transport/utils/log.h> -#include <hicn/transport/utils/verifier.h> extern "C" { #ifndef _WIN32 @@ -119,6 +119,13 @@ int Verifier::verify(const Packet &packet) { // to initialize packet.payload_head_ const_cast<Packet *>(&packet)->separateHeaderPayload(); bool valid = false; + + // initialize packet.payload_head_ + const_cast<Packet *>(&packet)->separateHeaderPayload(); + // header chain points to the IP + TCP hicn header + // utils::MemBuf *header_chain = packet.header_head_; + // utils::MemBuf *payload_chain = packet.payload_head_; + // uint8_t *hicn_packet = header_chain->writableData(); Packet::Format format = packet.getFormat(); if (!(packet.format_ & HFO_AH)) { diff --git a/libtransport/src/hicn/transport/utils/CMakeLists.txt b/libtransport/src/utils/CMakeLists.txt index 5a7dbe9cc..88d451b6b 100644 --- a/libtransport/src/hicn/transport/utils/CMakeLists.txt +++ b/libtransport/src/utils/CMakeLists.txt @@ -16,9 +16,6 @@ cmake_minimum_required(VERSION 3.5 FATAL_ERROR) list(APPEND SOURCE_FILES ${CMAKE_CURRENT_SOURCE_DIR}/string_tokenizer.cc ${CMAKE_CURRENT_SOURCE_DIR}/uri.cc - ${CMAKE_CURRENT_SOURCE_DIR}/signer.cc - ${CMAKE_CURRENT_SOURCE_DIR}/verifier.cc - ${CMAKE_CURRENT_SOURCE_DIR}/identity.cc ${CMAKE_CURRENT_SOURCE_DIR}/log.cc ${CMAKE_CURRENT_SOURCE_DIR}/membuf.cc ${CMAKE_CURRENT_SOURCE_DIR}/content_store.cc @@ -26,36 +23,13 @@ list(APPEND SOURCE_FILES list(APPEND HEADER_FILES - ${CMAKE_CURRENT_SOURCE_DIR}/array.h - ${CMAKE_CURRENT_SOURCE_DIR}/string_tokenizer.h - ${CMAKE_CURRENT_SOURCE_DIR}/hash.h - ${CMAKE_CURRENT_SOURCE_DIR}/uri.h - ${CMAKE_CURRENT_SOURCE_DIR}/chrono_typedefs.h - ${CMAKE_CURRENT_SOURCE_DIR}/branch_prediction.h - ${CMAKE_CURRENT_SOURCE_DIR}/event_reactor.h - ${CMAKE_CURRENT_SOURCE_DIR}/deadline_timer.h - ${CMAKE_CURRENT_SOURCE_DIR}/ring_buffer.h ${CMAKE_CURRENT_SOURCE_DIR}/event_reactor.h ${CMAKE_CURRENT_SOURCE_DIR}/min_filter.h ${CMAKE_CURRENT_SOURCE_DIR}/stream_buffer.h - ${CMAKE_CURRENT_SOURCE_DIR}/literals.h - ${CMAKE_CURRENT_SOURCE_DIR}/signer.h - ${CMAKE_CURRENT_SOURCE_DIR}/verifier.h - ${CMAKE_CURRENT_SOURCE_DIR}/crypto_hasher.h - ${CMAKE_CURRENT_SOURCE_DIR}/crypto_suite.h - ${CMAKE_CURRENT_SOURCE_DIR}/crypto_hash.h - ${CMAKE_CURRENT_SOURCE_DIR}/crypto_hash_type.h - ${CMAKE_CURRENT_SOURCE_DIR}/identity.h ${CMAKE_CURRENT_SOURCE_DIR}/suffix_strategy.h - ${CMAKE_CURRENT_SOURCE_DIR}/conversions.h - ${CMAKE_CURRENT_SOURCE_DIR}/linux.h - ${CMAKE_CURRENT_SOURCE_DIR}/log.h ${CMAKE_CURRENT_SOURCE_DIR}/event_thread.h - ${CMAKE_CURRENT_SOURCE_DIR}/object_pool.h - ${CMAKE_CURRENT_SOURCE_DIR}/membuf.h - ${CMAKE_CURRENT_SOURCE_DIR}/spinlock.h ${CMAKE_CURRENT_SOURCE_DIR}/content_store.h - ${CMAKE_CURRENT_SOURCE_DIR}/key_id.h + ${CMAKE_CURRENT_SOURCE_DIR}/deadline_timer.h ) if ("${CMAKE_SYSTEM_NAME}" STREQUAL "Linux") @@ -70,9 +44,6 @@ if ("${CMAKE_SYSTEM_NAME}" STREQUAL "Linux") endif() if(NOT WIN32) - list(APPEND HEADER_FILES - ${CMAKE_CURRENT_SOURCE_DIR}/daemonizator.h - ) list(APPEND SOURCE_FILES ${CMAKE_CURRENT_SOURCE_DIR}/daemonizator.cc ) diff --git a/libtransport/src/hicn/transport/utils/content_store.cc b/libtransport/src/utils/content_store.cc index ba13bef41..cb3db6d94 100644 --- a/libtransport/src/hicn/transport/utils/content_store.cc +++ b/libtransport/src/utils/content_store.cc @@ -16,7 +16,9 @@ #include <hicn/transport/core/content_object.h> #include <hicn/transport/core/interest.h> #include <hicn/transport/core/name.h> -#include <hicn/transport/utils/content_store.h> +#include <hicn/transport/utils/log.h> + +#include <utils/content_store.h> namespace utils { @@ -65,7 +67,6 @@ const std::shared_ptr<ContentObject> ContentStore::find( std::shared_ptr<ContentObject> ret = empty_reference_; auto it = content_store_hash_table_.find(interest.getName()); if (it != content_store_hash_table_.end()) { - auto content_lifetime = it->second.first.first->getLifetime(); auto time_passed_since_creation = std::chrono::duration_cast<std::chrono::milliseconds>( @@ -75,8 +76,7 @@ const std::shared_ptr<ContentObject> ContentStore::find( if (time_passed_since_creation > content_lifetime) { fifo_list_.erase(it->second.second); content_store_hash_table_.erase(it); - } - else { + } else { ret = it->second.first.first; } } diff --git a/libtransport/src/hicn/transport/utils/content_store.h b/libtransport/src/utils/content_store.h index 613ffcbc2..03ce76f42 100644 --- a/libtransport/src/hicn/transport/utils/content_store.h +++ b/libtransport/src/utils/content_store.h @@ -15,7 +15,6 @@ #pragma once -#include <hicn/transport/interfaces/socket.h> #include <hicn/transport/utils/spinlock.h> #include <mutex> diff --git a/libtransport/src/hicn/transport/utils/daemonizator.cc b/libtransport/src/utils/daemonizator.cc index c51a68d14..c51a68d14 100644 --- a/libtransport/src/hicn/transport/utils/daemonizator.cc +++ b/libtransport/src/utils/daemonizator.cc diff --git a/libtransport/src/hicn/transport/utils/deadline_timer.h b/libtransport/src/utils/deadline_timer.h index 61f906141..5187754f0 100644 --- a/libtransport/src/hicn/transport/utils/deadline_timer.h +++ b/libtransport/src/utils/deadline_timer.h @@ -15,7 +15,7 @@ #pragma once -#include <hicn/transport/utils/event_reactor.h> +#include <utils/event_reactor.h> #include <chrono> #include <cstddef> diff --git a/libtransport/src/hicn/transport/utils/epoll_event_reactor.cc b/libtransport/src/utils/epoll_event_reactor.cc index a97e89500..0e6590d0e 100644 --- a/libtransport/src/hicn/transport/utils/epoll_event_reactor.cc +++ b/libtransport/src/utils/epoll_event_reactor.cc @@ -14,8 +14,9 @@ */ #include <hicn/transport/utils/branch_prediction.h> -#include <hicn/transport/utils/epoll_event_reactor.h> -#include <hicn/transport/utils/fd_deadline_timer.h> + +#include <utils/epoll_event_reactor.h> +#include <utils/fd_deadline_timer.h> #include <signal.h> #include <unistd.h> diff --git a/libtransport/src/hicn/transport/utils/epoll_event_reactor.h b/libtransport/src/utils/epoll_event_reactor.h index 04c10fc7e..4cb87ebd4 100644 --- a/libtransport/src/hicn/transport/utils/epoll_event_reactor.h +++ b/libtransport/src/utils/epoll_event_reactor.h @@ -15,8 +15,8 @@ #pragma once -#include <hicn/transport/utils/event_reactor.h> #include <hicn/transport/utils/spinlock.h> +#include <utils/event_reactor.h> #include <sys/epoll.h> #include <atomic> diff --git a/libtransport/src/hicn/transport/utils/event_reactor.h b/libtransport/src/utils/event_reactor.h index 4f8b58296..4f8b58296 100644 --- a/libtransport/src/hicn/transport/utils/event_reactor.h +++ b/libtransport/src/utils/event_reactor.h diff --git a/libtransport/src/hicn/transport/utils/event_thread.h b/libtransport/src/utils/event_thread.h index e50ae9648..e50ae9648 100644 --- a/libtransport/src/hicn/transport/utils/event_thread.h +++ b/libtransport/src/utils/event_thread.h diff --git a/libtransport/src/hicn/transport/utils/fd_deadline_timer.h b/libtransport/src/utils/fd_deadline_timer.h index 1c14513c9..8bc3bbca3 100644 --- a/libtransport/src/hicn/transport/utils/fd_deadline_timer.h +++ b/libtransport/src/utils/fd_deadline_timer.h @@ -16,10 +16,11 @@ #pragma once #include <hicn/transport/errors/runtime_exception.h> -#include <hicn/transport/utils/deadline_timer.h> -#include <hicn/transport/utils/epoll_event_reactor.h> #include <hicn/transport/utils/log.h> +#include <utils/deadline_timer.h> +#include <utils/epoll_event_reactor.h> + #include <chrono> #include <cstddef> diff --git a/libtransport/src/hicn/transport/utils/log.cc b/libtransport/src/utils/log.cc index 27dd3f541..27dd3f541 100644 --- a/libtransport/src/hicn/transport/utils/log.cc +++ b/libtransport/src/utils/log.cc diff --git a/libtransport/src/hicn/transport/utils/membuf.cc b/libtransport/src/utils/membuf.cc index e75e85b35..e75e85b35 100644 --- a/libtransport/src/hicn/transport/utils/membuf.cc +++ b/libtransport/src/utils/membuf.cc diff --git a/libtransport/src/utils/memory_pool_allocator.h b/libtransport/src/utils/memory_pool_allocator.h new file mode 100644 index 000000000..adc1443ad --- /dev/null +++ b/libtransport/src/utils/memory_pool_allocator.h @@ -0,0 +1,152 @@ +/* + * 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.sudo make instamake install + */ + +#pragma once + +#include <memory> + +namespace utils { + +template <class T, std::size_t growSize = 1024> +class MemoryPool { + struct Block { + Block *next; + }; + + class Buffer { + static const std::size_t blockSize = sizeof(T) > sizeof(Block) + ? sizeof(T) + : sizeof(Block); + uint8_t data[blockSize * growSize]; + + public: + Buffer *const next; + + Buffer(Buffer *next) : next(next) {} + + T *getBlock(std::size_t index) { + return reinterpret_cast<T *>(&data[blockSize * index]); + } + }; + + Block *firstFreeBlock = nullptr; + Buffer *firstBuffer = nullptr; + std::size_t bufferedBlocks = growSize; + + public: + MemoryPool() = default; + MemoryPool(MemoryPool &&memoryPool) = delete; + MemoryPool(const MemoryPool &memoryPool) = delete; + MemoryPool operator=(MemoryPool &&memoryPool) = delete; + MemoryPool operator=(const MemoryPool &memoryPool) = delete; + + ~MemoryPool() { + while (firstBuffer) { + Buffer *buffer = firstBuffer; + firstBuffer = buffer->next; + delete buffer; + } + } + + T *allocate() { + if (firstFreeBlock) { + Block *block = firstFreeBlock; + firstFreeBlock = block->next; + return reinterpret_cast<T *>(block); + } + + if (bufferedBlocks >= growSize) { + firstBuffer = new Buffer(firstBuffer); + bufferedBlocks = 0; + } + + return firstBuffer->getBlock(bufferedBlocks++); + } + + void deallocate(T *pointer) { + Block *block = reinterpret_cast<Block *>(pointer); + block->next = firstFreeBlock; + firstFreeBlock = block; + } +}; + +template <class T, std::size_t growSize = 1024> +class Allocator : private MemoryPool<T, growSize> { +#ifdef _WIN32 + Allocator *copyAllocator; + std::allocator<T> *rebindAllocator = nullptr; +#endif + + public: + typedef std::size_t size_type; + typedef std::ptrdiff_t difference_type; + typedef T *pointer; + typedef const T *const_pointer; + typedef T &reference; + typedef const T &const_reference; + typedef T value_type; + + template <class U> + struct rebind { + typedef Allocator<U, growSize> other; + }; + +#ifdef _WIN32 + Allocator() = default; + + Allocator(Allocator &allocator) : copyAllocator(&allocator) {} + + template <class U> + Allocator(const Allocator<U, growSize> &other) { + if (!std::is_same<T, U>::value) rebindAllocator = new std::allocator<T>(); + } + + ~Allocator() { delete rebindAllocator; } +#endif + + pointer allocate(size_type n, const void *hint = 0) { +#ifdef _WIN32 + if (copyAllocator) return copyAllocator->allocate(n, hint); + + if (rebindAllocator) return rebindAllocator->allocate(n, hint); +#endif + + if (n != 1 || hint) throw std::bad_alloc(); + + return MemoryPool<T, growSize>::allocate(); + } + + void deallocate(pointer p, size_type n) { +#ifdef _WIN32 + if (copyAllocator) { + copyAllocator->deallocate(p, n); + return; + } + + if (rebindAllocator) { + rebindAllocator->deallocate(p, n); + return; + } +#endif + + MemoryPool<T, growSize>::deallocate(p); + } + + void construct(pointer p, const_reference val) { new (p) T(val); } + + void destroy(pointer p) { p->~T(); } +}; + +}
\ No newline at end of file diff --git a/libtransport/src/hicn/transport/utils/min_filter.h b/libtransport/src/utils/min_filter.h index dcfd5652d..dcfd5652d 100644 --- a/libtransport/src/hicn/transport/utils/min_filter.h +++ b/libtransport/src/utils/min_filter.h diff --git a/libtransport/src/hicn/transport/utils/stream_buffer.h b/libtransport/src/utils/stream_buffer.h index adfb696f2..adfb696f2 100644 --- a/libtransport/src/hicn/transport/utils/stream_buffer.h +++ b/libtransport/src/utils/stream_buffer.h diff --git a/libtransport/src/hicn/transport/utils/string_tokenizer.cc b/libtransport/src/utils/string_tokenizer.cc index a280a3c43..a280a3c43 100644 --- a/libtransport/src/hicn/transport/utils/string_tokenizer.cc +++ b/libtransport/src/utils/string_tokenizer.cc diff --git a/libtransport/src/hicn/transport/utils/suffix_strategy.h b/libtransport/src/utils/suffix_strategy.h index ab9b1eff6..6c4dd2785 100644 --- a/libtransport/src/hicn/transport/utils/suffix_strategy.h +++ b/libtransport/src/utils/suffix_strategy.h @@ -15,8 +15,7 @@ #pragma once -#include <hicn/transport/core/manifest_format.h> -#include <limits> +#include <core/manifest_format.h> namespace utils { diff --git a/libtransport/src/hicn/transport/utils/test.h b/libtransport/src/utils/test.h index e3dd619ac..e3dd619ac 100644 --- a/libtransport/src/hicn/transport/utils/test.h +++ b/libtransport/src/utils/test.h diff --git a/libtransport/src/hicn/transport/utils/uri.cc b/libtransport/src/utils/uri.cc index 33eb8b45b..33eb8b45b 100644 --- a/libtransport/src/hicn/transport/utils/uri.cc +++ b/libtransport/src/utils/uri.cc |